Merge branch 'dev' into snow
# Conflicts: # backend/app/api/chat.py # backend/app/services/admin/permission_service.py # frontend/src/features/user/views/UserProfilePage.vue
This commit is contained in:
commit
5faf86b184
691 files changed
+55948
-17728
No files matched your search
@@ -428,6 +428,21 @@ def get_shipping_inventory_configuration_catalog():
|
||||
})
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/movement-fields', methods=['GET'])
|
||||
@require_admin
|
||||
def list_movement_fields():
|
||||
"""标准异动字段目录(只读领域契约,供收料异动解析规则映射表单;禁止增删)。"""
|
||||
from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
|
||||
|
||||
return _ok([
|
||||
{
|
||||
'code': field.code, 'value_type': str(field.value_type),
|
||||
'required': bool(field.required), 'is_identity': bool(field.is_identity),
|
||||
}
|
||||
for field in MOVEMENT_FIELDS
|
||||
])
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/parsing-profiles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_parsing_profiles():
|
||||
|
||||
@@ -15,7 +15,7 @@ from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError
|
||||
from app.models import Agent, User, AgentGuide
|
||||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||
from app.services.minio_service import minio_service
|
||||
from app.services.integrations.minio import minio_service
|
||||
|
||||
# 定义 Blueprint,将在应用工厂中注册为 /api/agents
|
||||
agents_bp = Blueprint('agents', __name__)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -36,7 +36,7 @@ def get_chat_query_preview(chat_log_id: int):
|
||||
if not sql:
|
||||
raise ValidationError('query preview sql is missing')
|
||||
|
||||
from app.services.text2sql import Text2SQLService
|
||||
from app.services.integrations.text2sql import Text2SQLService
|
||||
total_count = payload.get('total_count')
|
||||
try:
|
||||
total_count = int(total_count) if total_count is not None else None
|
||||
|
||||
@@ -87,7 +87,7 @@ def chat_completions():
|
||||
role=getattr(user, 'role', None),
|
||||
)
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
external_conversation_id = None
|
||||
if conversation_id:
|
||||
|
||||
@@ -35,7 +35,7 @@ def _should_reset_provider_conversation_for_asset_query(query: str, agent_proxy)
|
||||
- 仅当用户本轮问题可脱离上一轮上下文独立完成时触发;
|
||||
- 这样可以保留本地同一历史会话,又避免把上一轮超大结果继续带给上游模型,导致 context length 爆掉。
|
||||
"""
|
||||
from app.services.text2sql import Text2SQLService
|
||||
from app.services.integrations.text2sql import Text2SQLService
|
||||
|
||||
return Text2SQLService._should_reset_provider_conversation(query, agent_proxy)
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ def get_oa_employees():
|
||||
page = 1
|
||||
page_size = 20
|
||||
try:
|
||||
from app.services.oa_sqlserver import OASQLServerService
|
||||
from app.services.integrations.oa.sqlserver import OASQLServerService
|
||||
result = OASQLServerService.search_employees(keyword, page, page_size)
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
@@ -39,7 +39,7 @@ def resolve_oa_names():
|
||||
sub_ids = request.args.get('subcompany_ids', '').strip()
|
||||
result = {}
|
||||
try:
|
||||
from app.services.oa_sqlserver import OASQLServerService
|
||||
from app.services.integrations.oa.sqlserver import OASQLServerService
|
||||
if dept_ids:
|
||||
for did in dept_ids.split(','):
|
||||
did = did.strip()
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
api/chat/sessions.py
|
||||
|
||||
用途:处理聊天会话、历史消息与本地结构化消息路由。
|
||||
依赖:chat.shared、chat.core、ChatSession、ChatLog。
|
||||
逻辑:校验当前用户和 Agent 后读写会话及日志,保持历史数据兼容查询。
|
||||
依赖:chat.shared、chat.core、ChatSession、ChatLog、_normalize_user_attachments。
|
||||
逻辑:校验当前用户和 Agent 后读写会话及日志;用户附件快照写库前规范化,超限显式失败不落半截。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -246,7 +246,8 @@ def save_local_message():
|
||||
保存前端本地生成的聊天记录(如表单、确认弹窗、合同审查结果卡等)。
|
||||
|
||||
核心逻辑:user 角色用 content/query 落库;纯文本 assistant 忽略 query 防重复气泡;
|
||||
结构化 typed 消息(leave-form / procurement-contract-review 等)保留 query,供历史回放与会话标题。
|
||||
结构化 typed 消息(leave-form / procurement-contract-review 等)保留 query,供历史回放与会话标题;
|
||||
user 角色 payload 含 user_attachments 时写库前调用 _normalize_user_attachments,超限抛 ValidationError。
|
||||
"""
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
@@ -286,6 +287,13 @@ def save_local_message():
|
||||
if user_query and _looks_like_review_auto_title(session.title or ''):
|
||||
session.title = _session_title_from_text(user_query)
|
||||
|
||||
# [STEP] 用户附件快照写前规范化;超限由 _normalize_user_attachments 显式失败,禁止落半截
|
||||
if role == 'user' and isinstance(payload, dict) and 'user_attachments' in payload:
|
||||
payload = {
|
||||
**payload,
|
||||
'user_attachments': _normalize_user_attachments(payload.get('user_attachments')),
|
||||
}
|
||||
|
||||
# 如果 payload 里面包含 formId,且该 formId 已经被保存过,可以直接更新该记录
|
||||
# 这样能保证前端表单状态(例如已确认)被持久化
|
||||
local_id = payload.get('formId') if payload and isinstance(payload, dict) else None
|
||||
|
||||
@@ -24,9 +24,9 @@ from flask import Blueprint, request, Response, stream_with_context, jsonify, g,
|
||||
from sqlalchemy import func, desc, or_, exists, and_
|
||||
from openpyxl import load_workbook
|
||||
from app.services.agent_runtime_context.dify_inputs import build_chat_dify_inputs
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
from app.core.config.settings import Config
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
from app.services.integrations.integration_api import IntegrationApiService
|
||||
from app.core.decorators import require_agent_permission
|
||||
from app.models import Agent, ChatLog, ChatSession, Feedback
|
||||
from app import db
|
||||
@@ -43,7 +43,7 @@ from app.core.errors import (
|
||||
SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice'
|
||||
|
||||
# 用户消息附件白名单(迁移自 legacy app/api/chat.py;供 ChatLog payload 与历史接口复用)。
|
||||
CHAT_USER_ATTACHMENT_LIMIT = 20
|
||||
CHAT_USER_ATTACHMENT_LIMIT = 200
|
||||
CHAT_USER_ATTACHMENT_MAX_SIZE = 10 * 1024 * 1024 * 1024
|
||||
CHAT_USER_ATTACHMENT_TYPES = {'image', 'document', 'audio', 'video', 'custom'}
|
||||
CHAT_USER_ATTACHMENT_SOURCES = {'local', 'remote', 'shipping_notice'}
|
||||
@@ -53,18 +53,31 @@ def _normalize_user_attachments(value) -> list[dict]:
|
||||
"""
|
||||
校验并清洗用户消息附件快照,供 ChatLog payload 与历史接口复用。
|
||||
|
||||
核心逻辑:仅接受展示白名单字段;剥离路径、控制字符与未知枚举,不接收 URL、上传 ID 或资产编号。
|
||||
核心逻辑:仅接受展示白名单字段;剥离路径、控制字符与未知枚举;
|
||||
列表长度超过 CHAT_USER_ATTACHMENT_LIMIT 时显式失败,禁止静默截断。
|
||||
|
||||
Args:
|
||||
value: 前端 user_attachments 原始值;必须为列表,最多处理 20 项。
|
||||
value: 前端 user_attachments 原始值;必须为列表。
|
||||
|
||||
Returns:
|
||||
可安全写入 JSON 的附件快照列表;非法项目被忽略。
|
||||
|
||||
Raises:
|
||||
ValidationError: 列表长度超过上限(code=CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED)。
|
||||
"""
|
||||
if not isinstance(value, list):
|
||||
return []
|
||||
if len(value) > CHAT_USER_ATTACHMENT_LIMIT:
|
||||
raise ValidationError(
|
||||
f'User attachments exceed limit ({CHAT_USER_ATTACHMENT_LIMIT})',
|
||||
code='CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED',
|
||||
details={
|
||||
'limit': CHAT_USER_ATTACHMENT_LIMIT,
|
||||
'count': len(value),
|
||||
},
|
||||
)
|
||||
normalized: list[dict] = []
|
||||
for item in value[:CHAT_USER_ATTACHMENT_LIMIT]:
|
||||
for item in value:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
raw_name = str(item.get('name') or '')
|
||||
|
||||
@@ -27,7 +27,7 @@ def upload_chat_file():
|
||||
if not upload:
|
||||
raise ValidationError('file is required')
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
from app.core.config.settings import Config
|
||||
|
||||
params = DifyService.get_app_parameters(agent, force_refresh=True)
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
backend/app/api/contract_payment.py
|
||||
|
||||
用途:采购合同付款预警 Agent 的合同台账、付款计划、待发送摘要、台账汇总卡和同步 API。
|
||||
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、contract_payment 服务和通用 Job 队列。
|
||||
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、Agent 授权、contract_payment 服务和通用 Job 队列。
|
||||
逻辑:页面查询合同、节点、本周待发送摘要与四张汇总卡;同步和预警操作入队,避免请求线程执行外部系统和企微调用。
|
||||
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍。
|
||||
鉴权:查询接口要求 `contract_payment.access`(admin 默认开,可显式授予普通用户);
|
||||
鉴权:查询接口要求平台 admin 或持有 `agent_code=contract_payment` 的 Agent 授权;
|
||||
同步/扫描/周汇总发送仅 `role=admin`。
|
||||
"""
|
||||
|
||||
@@ -21,6 +21,7 @@ from app.core.response import ok
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
from app.models import (
|
||||
Agent,
|
||||
ContractPaymentAlert,
|
||||
ContractPaymentAlertBatch,
|
||||
ContractPaymentAttachment,
|
||||
@@ -41,6 +42,8 @@ from app.services.file_assets.service import read_asset_bytes
|
||||
|
||||
contract_payment_bp = Blueprint("contract_payment", __name__)
|
||||
|
||||
CONTRACT_PAYMENT_AGENT_CODE = "contract_payment"
|
||||
|
||||
|
||||
def _attachment_parse_priority(attachment: ContractPaymentAttachment) -> tuple[int, int]:
|
||||
"""
|
||||
@@ -74,35 +77,45 @@ def _require_user():
|
||||
return user
|
||||
|
||||
|
||||
def _user_has_contract_payment_agent(user) -> bool:
|
||||
"""
|
||||
判断用户是否持有启用中的合同付款预警 Agent。
|
||||
|
||||
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions;admin 不走此判断。
|
||||
"""
|
||||
agent = Agent.query.filter_by(agent_code=CONTRACT_PAYMENT_AGENT_CODE, is_active=True).first()
|
||||
return bool(agent is not None and agent in user.agents)
|
||||
|
||||
|
||||
def _require_contract_payment_access():
|
||||
"""
|
||||
确保当前用户已登录且具备合同付款预警访问权限。
|
||||
|
||||
核心逻辑:登录校验之后读取 `contract_payment.access`;admin 角色默认具备,
|
||||
其他角色需在用户管理中显式授予。无权限时返回业务 403,而不是静默空数据。
|
||||
核心逻辑:平台 admin 放行;普通用户必须被授予启用中的 `agent_code=contract_payment` Agent。
|
||||
无权限时返回业务 403,而不是静默空数据。
|
||||
|
||||
Args:
|
||||
无。当前请求身份由 JWT 上下文提供。
|
||||
Returns:
|
||||
已认证且具备合同付款预警访问权限的用户。
|
||||
已认证且具备合同付款预警 Agent 授权(或 admin)的用户。
|
||||
Raises:
|
||||
UnauthorizedError: 请求没有有效登录身份。
|
||||
ForbiddenError: 已登录但没有 `contract_payment.access`。
|
||||
ForbiddenError: 已登录但没有合同付款预警 Agent 授权。
|
||||
"""
|
||||
user = _require_user()
|
||||
if not user.can_access_contract_payment():
|
||||
raise ForbiddenError(
|
||||
'Contract payment access required',
|
||||
code='CONTRACT_PAYMENT.FORBIDDEN',
|
||||
)
|
||||
return user
|
||||
if getattr(user, "role", None) == "admin" or _user_has_contract_payment_agent(user):
|
||||
return user
|
||||
raise ForbiddenError(
|
||||
'Contract payment agent permission required',
|
||||
code='CONTRACT_PAYMENT.FORBIDDEN',
|
||||
)
|
||||
|
||||
|
||||
def _require_contract_payment_admin():
|
||||
"""
|
||||
确保当前用户既有合同付款预警访问权,又是平台管理员。
|
||||
|
||||
核心逻辑:普通授权用户可查台账;同步 OA、强制覆盖、批量重解析、扫描预警和发送周汇总
|
||||
核心逻辑:持有 Agent 的普通用户可查台账;同步 OA、强制覆盖、批量重解析、扫描预警和发送周汇总
|
||||
会改写外部系统或触发企微,因此仅 `role=admin` 可调用。
|
||||
|
||||
Args:
|
||||
@@ -195,19 +208,48 @@ def _serialize_contract(row: ContractPaymentContract) -> dict:
|
||||
}
|
||||
|
||||
|
||||
@contract_payment_bp.route("/contracts", methods=["GET"])
|
||||
def list_contracts():
|
||||
def _review_only_requested() -> bool:
|
||||
"""
|
||||
查询合同台账。
|
||||
判断当前请求是否只要待确认合同。
|
||||
|
||||
核心逻辑:支持合同编号、流程编号、采购单号、供应商名称、解析状态和汇总卡口径(focus)筛选,并按 offset 分页返回台账。
|
||||
Args:
|
||||
无。筛选条件从 query string 读取。
|
||||
无。读取 query string 的 review_only。
|
||||
Returns:
|
||||
标准成功 envelope,data 包含 total、page、page_size、pages 和 items。
|
||||
值为 1 / true / yes 时为 True。
|
||||
"""
|
||||
return str(request.args.get("review_only") or "").strip().lower() in {"1", "true", "yes"}
|
||||
|
||||
|
||||
def _scoped_contract_query(*, review_only: bool, parse_status: str = ""):
|
||||
"""
|
||||
按台账 / 待确认口径收窄合同查询。
|
||||
|
||||
核心逻辑:review_only 优先于 parse_status;二者都空时默认只看已解析台账。
|
||||
Args:
|
||||
review_only: 为 True 时只返回 needs_review。
|
||||
parse_status: 精确解析状态;review_only 为 False 且为空时默认 parsed。
|
||||
Returns:
|
||||
已套上解析状态条件的合同查询。
|
||||
"""
|
||||
_require_contract_payment_access()
|
||||
query = db.session.query(ContractPaymentContract)
|
||||
if review_only:
|
||||
return query.filter_by(parse_status="needs_review")
|
||||
if parse_status:
|
||||
return query.filter_by(parse_status=parse_status)
|
||||
# 自动付款预警台账仅展示关键解析事实完整的合同;待确认合同由独立导航集中处理。
|
||||
return query.filter_by(parse_status="parsed")
|
||||
|
||||
|
||||
def _apply_contract_text_filters(query):
|
||||
"""
|
||||
叠关键词过滤。
|
||||
|
||||
核心逻辑:keyword 对合同号、流程号、采购单号、供应商、申请人做模糊 OR。
|
||||
Args:
|
||||
query: 已按解析状态收窄的合同查询。
|
||||
Returns:
|
||||
叠加文本过滤后的查询。
|
||||
"""
|
||||
keyword = str(request.args.get("keyword") or "").strip()
|
||||
if keyword:
|
||||
like = f"%{keyword}%"
|
||||
@@ -216,16 +258,28 @@ def list_contracts():
|
||||
| ContractPaymentContract.workflow_no.ilike(like)
|
||||
| ContractPaymentContract.purchase_order_no.ilike(like)
|
||||
| ContractPaymentContract.supplier_name.ilike(like)
|
||||
| ContractPaymentContract.applicant_name.ilike(like)
|
||||
)
|
||||
return query
|
||||
|
||||
|
||||
@contract_payment_bp.route("/contracts", methods=["GET"])
|
||||
def list_contracts():
|
||||
"""
|
||||
查询合同台账。
|
||||
|
||||
核心逻辑:支持合同编号、流程编号、采购单号、供应商、申请人、解析状态和汇总卡口径(focus)筛选,并按 offset 分页返回台账。
|
||||
Args:
|
||||
无。筛选条件从 query string 读取。
|
||||
Returns:
|
||||
标准成功 envelope,data 包含 total、page、page_size、pages 和 items。
|
||||
"""
|
||||
_require_contract_payment_access()
|
||||
review_only = _review_only_requested()
|
||||
parse_status = str(request.args.get("parse_status") or "").strip()
|
||||
review_only = str(request.args.get("review_only") or "").strip().lower() in {"1", "true", "yes"}
|
||||
if review_only:
|
||||
query = query.filter_by(parse_status="needs_review")
|
||||
elif parse_status:
|
||||
query = query.filter_by(parse_status=parse_status)
|
||||
else:
|
||||
# 自动付款预警台账仅展示关键解析事实完整的合同;待确认合同由独立导航集中处理。
|
||||
query = query.filter_by(parse_status="parsed")
|
||||
query = _apply_contract_text_filters(
|
||||
_scoped_contract_query(review_only=review_only, parse_status=parse_status)
|
||||
)
|
||||
focus = str(request.args.get("focus") or "").strip()
|
||||
if focus:
|
||||
if review_only:
|
||||
@@ -262,7 +316,7 @@ def get_ledger_summary():
|
||||
Args:
|
||||
无。
|
||||
Returns:
|
||||
标准成功 envelope,含 due、overdue、needs_completion、due_this_month。
|
||||
标准成功 envelope,含 due、overdue、active、due_this_month。
|
||||
"""
|
||||
_require_contract_payment_access()
|
||||
return ok(ledger_focus_counts(session=db.session), request_id=getattr(g, "request_id", None))
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/api/file_check_tools.py
|
||||
|
||||
用途:文件检核 / 立账凭证检核 Chatflow 显式 HTTP Tool API(启动检核复用本蓝图)。
|
||||
依赖:workspace_file_check、file_check_tools、schedule.scheduler_service。
|
||||
逻辑:发起检核时可透传顶层 mode/invoice_no(或嵌套 run_options)写入 ScheduleRun.api_request_json。
|
||||
逻辑:发起检核时可透传顶层 mode/invoice_no(或嵌套 run_options)写入 ScheduleRun.api_request_json;实际执行入队 FILE_CHECK_RUN,由 schedule worker 执行。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -17,6 +17,7 @@ from sqlalchemy import text
|
||||
|
||||
from app import db
|
||||
from app.api.workspace_file_check import serialize_file_judgement
|
||||
from app.jobs import JobType, enqueue
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
@@ -31,7 +32,7 @@ from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE, resolve_hx
|
||||
from app.services.schedule import _build_srm_conn_str
|
||||
from app.services.schedule.query_service import get_run, serialize_run
|
||||
from app.services.schedule.srm_service import _fetch_records
|
||||
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
|
||||
from app.services.schedule.scheduler_service import _generate_run_no
|
||||
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
|
||||
|
||||
try:
|
||||
@@ -543,28 +544,16 @@ def run_file_check():
|
||||
db.session.commit()
|
||||
_record_run_bind(run, data)
|
||||
db.session.commit()
|
||||
app = current_app._get_current_object()
|
||||
run_id = run.id
|
||||
task_id = task.id
|
||||
|
||||
def _background():
|
||||
with app.app_context():
|
||||
t = db.session.get(ScheduleTask, task_id)
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if not t or not r:
|
||||
return
|
||||
try:
|
||||
run_task_now(t, trigger_type="dify_chatflow", triggered_by_user_id=None, run=r)
|
||||
except Exception as exc:
|
||||
current_app.logger.error("[file-check-tool] run_id=%s failed: %s", run_id, exc, exc_info=True)
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if r and r.status == "running":
|
||||
r.status = "failed"
|
||||
r.error_message = str(exc)
|
||||
r.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
threading.Thread(target=_background, daemon=True, name=f"file-check-run-{run_id}").start()
|
||||
enqueue(
|
||||
JobType.FILE_CHECK_RUN,
|
||||
{"task_id": task_id, "schedule_run_id": run_id},
|
||||
domain="file_check",
|
||||
business_ref=str(run_id),
|
||||
message="等待执行文件检核",
|
||||
)
|
||||
db.session.refresh(run)
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
|
||||
@@ -28,7 +28,7 @@ from app.services.in_transit_transfer.execution_service import (
|
||||
)
|
||||
from app.services.in_transit_transfer.manual_close_service import manual_close_item
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck
|
||||
from app.services.in_transit_transfer.retry_service import retry_item
|
||||
from app.services.in_transit_transfer.retry_service import requery_items as retry_service_requery_items, retry_item
|
||||
from app.services.in_transit_transfer.serializers import (
|
||||
serialize_item,
|
||||
serialize_source,
|
||||
@@ -72,9 +72,11 @@ def _ok(payload: Any, *, status: int = 200):
|
||||
@in_transit_transfer_bp.route("/prechecks", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def create_precheck_api():
|
||||
"""创建或复用一次调拨预检(只读,不写 ERP)。
|
||||
"""创建或复用一次调拨预检(只读,不写 外部系统)。
|
||||
|
||||
请求体:{"source_codes": [...], "business_date": "YYYY-MM-DD"(可选)}。
|
||||
请求体:{"source_codes": [...], "business_date": "YYYY-MM-DD"(可选),
|
||||
"receipt_date_from"/"receipt_date_to"(可选),
|
||||
"transfer_type": "in_transit_to_hub"(可选,缺省在途仓至HUB仓)}。
|
||||
响应:201 envelope,data 为预检摘要(precheck_id/hash/计数/来源进度)。
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
@@ -89,6 +91,9 @@ def create_precheck_api():
|
||||
source_codes=[str(item).strip() for item in source_codes],
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
receipt_date_from=str(body.get("receipt_date_from")) if body.get("receipt_date_from") else None,
|
||||
receipt_date_to=str(body.get("receipt_date_to")) if body.get("receipt_date_to") else None,
|
||||
transfer_type=str(body.get("transfer_type")) if body.get("transfer_type") else None,
|
||||
)
|
||||
return _ok(serialize_summary(summary), status=201)
|
||||
|
||||
@@ -111,7 +116,7 @@ def execute_precheck_api(precheck_id: str):
|
||||
"""确认预检选择范围并直接生成执行 Run(决策 4/5:无独立确认页)。
|
||||
|
||||
请求体:{"invoice_nos": [...]}(可选;缺省执行全部可执行项)。
|
||||
响应:201 envelope,data 为 run_no / run 状态 / ERP 单号聚合结果。
|
||||
响应:201 envelope,data 为 run_no / run 状态 / 外部系统 单号聚合结果。
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
invoice_nos = body.get("invoice_nos") if isinstance(body, dict) else None
|
||||
@@ -130,6 +135,88 @@ def execute_precheck_api(precheck_id: str):
|
||||
}, status=201)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/prechecks/<precheck_no>/items/requery", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def requery_items_api(precheck_no: str):
|
||||
"""批量重查 外部系统 库存(可恢复阻断行);body 可选 invoice_nos 限定范围。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
invoice_nos = body.get("invoice_nos") if isinstance(body.get("invoice_nos"), list) else None
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
return _ok(retry_service_requery_items(
|
||||
precheck_no=precheck_no, deps=deps, invoice_nos=invoice_nos,
|
||||
actor_id=str(user.id) if user.id else None,
|
||||
))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/sources/receipt-files", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def download_source_receipt_files_api():
|
||||
"""按选中来源打包下载各自最新归档收料文件(zip);记录访问审计。"""
|
||||
import io
|
||||
import zipfile
|
||||
from pathlib import Path as _Path
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
source_codes = body.get("source_codes")
|
||||
if not isinstance(source_codes, list) or not [c for c in source_codes if str(c or "").strip()]:
|
||||
raise ValidationError("source_codes is required")
|
||||
|
||||
buffer = io.BytesIO()
|
||||
included: list[str] = []
|
||||
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
|
||||
for code in source_codes:
|
||||
code = str(code or "").strip()
|
||||
if not code:
|
||||
continue
|
||||
report = (
|
||||
ShippingReceiptReportFile.query
|
||||
.join(ShippingReceiptReportFile.unit_run)
|
||||
.filter(
|
||||
ShippingReceiptReportFile.unit_run.has(source_code=code),
|
||||
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)与徽标/预检取文件同口径,
|
||||
# 单一事实来源见 receipt_file_gate。
|
||||
usable_receipt_file_condition(),
|
||||
)
|
||||
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
|
||||
.first()
|
||||
)
|
||||
if report is None:
|
||||
continue
|
||||
data = file_asset_storage.get_bytes(report.storage_key)
|
||||
safe_name = _Path(report.original_filename or f"{report.id}.xlsx").name
|
||||
archive.writestr(f"{code}-{safe_name}", data)
|
||||
included.append(code)
|
||||
if not included:
|
||||
raise NotFoundError("no archived receipt files", code="SHIPPING.RECEIPT_FILE_NOT_FOUND")
|
||||
|
||||
user = _require_user()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_RECEIPT_FILES_DOWNLOADED",
|
||||
aggregate_type="in_transit_source",
|
||||
aggregate_id=",".join(included),
|
||||
actor_type="user",
|
||||
actor_id=str(user.id) if user.id else None,
|
||||
actor_display=str(getattr(user, "name", "") or ""),
|
||||
request_id=getattr(g, "request_id", None),
|
||||
result="success",
|
||||
))
|
||||
db.session.commit()
|
||||
buffer.seek(0)
|
||||
return send_file(
|
||||
buffer,
|
||||
mimetype="application/zip",
|
||||
as_attachment=True,
|
||||
download_name=f"receipt-files-{len(included)}-source{'s' if len(included) > 1 else ''}.zip",
|
||||
)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def get_run_api(run_no: str):
|
||||
@@ -149,14 +236,14 @@ def cancel_run_api(run_no: str):
|
||||
@in_transit_transfer_bp.route("/items/<int:item_id>/retry", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def retry_item_api(item_id: int):
|
||||
"""人工重试异常项(基于冻结文件仅重新查询 ERP,创建新 Attempt)。
|
||||
"""人工重试异常项(基于冻结文件仅重新查询 外部系统,创建新 Attempt)。
|
||||
|
||||
请求体:{"kind": "erp_recheck"}(可选,默认 erp_recheck)。
|
||||
请求体:{"kind": "external_recheck"}(可选,默认 external_recheck)。
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
kind = body.get("kind") if isinstance(body, dict) else None
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
return _ok(retry_item(item_id=item_id, deps=deps, kind=kind or "erp_recheck"))
|
||||
return _ok(retry_item(item_id=item_id, deps=deps, kind=kind or "external_recheck"))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/items/<int:item_id>/manual-close", methods=["POST"])
|
||||
@@ -257,10 +344,10 @@ def receipt_files_api(run_no: str):
|
||||
)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>/erp-inventory", methods=["GET"])
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>/external-inventory", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def erp_inventory_api(run_no: str):
|
||||
"""下载本次预检冻结的 ERP 库存表(csv);记录访问审计。"""
|
||||
"""下载本次预检冻结的 外部系统 库存表(csv);记录访问审计。"""
|
||||
import io
|
||||
|
||||
from app import db
|
||||
@@ -270,19 +357,19 @@ def erp_inventory_api(run_no: str):
|
||||
run = TransferRun.query.filter_by(run_no=str(run_no).strip()).first()
|
||||
if run is None:
|
||||
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
|
||||
lines = ["invoice_no,source_code,material_no,from_warehouse,to_warehouse,receipt_quantity,erp_quantity,result,erp_document_no"]
|
||||
lines = ["invoice_no,source_code,material_no,from_warehouse,to_warehouse,receipt_quantity,external_quantity,result,external_document_no"]
|
||||
for item in TransferInvoiceItem.query.filter_by(run_id=run.id).order_by(TransferInvoiceItem.invoice_no).all():
|
||||
lines.append(",".join([
|
||||
str(item.invoice_no), str(item.source_code), str(item.material_no),
|
||||
str(item.from_warehouse), str(item.to_warehouse),
|
||||
str(item.receipt_quantity), str(item.erp_quantity or ""),
|
||||
str(item.result_code or item.status), str(item.erp_document_no or ""),
|
||||
str(item.receipt_quantity), str(item.external_quantity or ""),
|
||||
str(item.result_code or item.status), str(item.external_document_no or ""),
|
||||
]))
|
||||
data = ("\n".join(lines) + "\n").encode("utf-8")
|
||||
|
||||
user = _require_user()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_ERP_INVENTORY_DOWNLOADED",
|
||||
event_type="TRANSFER_EXTERNAL_INVENTORY_DOWNLOADED",
|
||||
aggregate_type="transfer_run",
|
||||
aggregate_id=run_no,
|
||||
run_no=run_no,
|
||||
@@ -297,7 +384,7 @@ def erp_inventory_api(run_no: str):
|
||||
io.BytesIO(data),
|
||||
mimetype="text/csv",
|
||||
as_attachment=True,
|
||||
download_name=f"erp-inventory-{run_no}.csv",
|
||||
download_name=f"external-inventory-{run_no}.csv",
|
||||
)
|
||||
|
||||
|
||||
@@ -315,8 +402,9 @@ def transfer_metrics_api():
|
||||
def transfer_sources_api():
|
||||
"""来源实例列表(决策 3:平台 DBS/Crane 仅分组,实例为执行边界)。
|
||||
|
||||
每来源附收料文件状态(ready/fetching/failed/none + has_ready_file),
|
||||
供前端门禁(无 ready 文件时禁止确认预检)与状态标识。只读复用已启用库存来源。
|
||||
每来源附收料文件状态(ready/fetching/failed/expired/none + has_ready_file),
|
||||
供前端门禁(无 ready 文件时禁止确认预检)与状态标识;保留期已到或非当天
|
||||
(业务日)抓取且未清理均投影 expired。只读复用已启用库存来源。
|
||||
"""
|
||||
from app.models import ShippingInventorySource
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||
|
||||
@@ -22,7 +22,7 @@ from app.core.errors import (
|
||||
ValidationError,
|
||||
raise_for_status,
|
||||
)
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
from app.services.integrations.integration_api import IntegrationApiService
|
||||
integration_bp = Blueprint('integration', __name__)
|
||||
|
||||
|
||||
|
||||
@@ -1,21 +1,30 @@
|
||||
"""api/integration_connector.py
|
||||
|
||||
用途:Integration Connector Admin API——配置实体 CRUD、能力清单、能力调用端点与连接测试。
|
||||
依赖:Flask Blueprint、app.core.response、app.core.decorators.require_admin、gateway。
|
||||
依赖:Flask Blueprint、app.core.response、app.core.decorators.require_admin、gateway、credential_crypto。
|
||||
逻辑:全部 require_admin;能力调用只接受 {params, context, operation_id, idempotency_key},
|
||||
拒绝 interface_id(禁止覆盖 Binding);配置写操作做字段白名单校验,非法即 400。
|
||||
接口定义的连接器类型由所属客户端实例服务端推导(单一事实源);接口定义与绑定的
|
||||
状态只经 /publish /unpublish /retire /reopen 动作端点按 CONFIG_STATUS_TRANSITIONS
|
||||
转移(绑定发布附加就绪门禁:接口须已发布且客户端启用);绑定创建/更新做客户端
|
||||
与接口成对校验(接口定义必须属于所选客户端实例,错配即 400)。
|
||||
凭据引用状态为两态开关:PUT 仅允许 active/retired(rotating 不可进入,存量可置回
|
||||
active 恢复);接口定义 enabled 冻结忽略传值(可用性只由 status 表达)。
|
||||
凭据引用 db 模式在服务端加密用户名/密码落库,接口响应永不回显明文/密文。
|
||||
注意:url_prefix 在 api/__init__.py 注册为 /api/integration-connector(区别于既有
|
||||
/api/integration Dify 文件代理)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import uuid
|
||||
|
||||
from flask import Blueprint, request
|
||||
|
||||
from app.core.credential_crypto import CredentialCryptoErrorCodes, decrypt_secret, encrypt_secret
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.core.errors import AppError, NotFoundError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.models import (
|
||||
IntegrationBinding,
|
||||
@@ -23,14 +32,36 @@ from app.models import (
|
||||
IntegrationCredentialReference,
|
||||
IntegrationInterfaceDefinition,
|
||||
)
|
||||
from app.services.integration_connector.capability import ensure_capabilities_loaded, list_capabilities
|
||||
from app.services.integration_connector.capability import list_capabilities
|
||||
from app.services.integration_connector.credential_types import (
|
||||
build_secret_dict,
|
||||
get_credential_type,
|
||||
list_credential_types,
|
||||
visible_fields,
|
||||
)
|
||||
from app.services.integration_connector.gateway import get_capability_gateway
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult
|
||||
from app.services.integration_connector.security import CREDENTIAL_KEY_CONFIG_NAME, _DB_SECRET_CODES
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult, merge_client_config
|
||||
|
||||
integration_connector_bp = Blueprint('integration_connector', __name__)
|
||||
|
||||
VALID_CONNECTOR_TYPES = ('rest', 'soap')
|
||||
VALID_STATUSES = ('draft', 'published', 'retired')
|
||||
VALID_SECRET_PROVIDERS = ('db', 'env')
|
||||
# 凭据两态化(UI 可达状态):resolve_credential 只解析 active(fail-closed),「轮换中」
|
||||
# 现语义等于断供且真实版本化轮换未实现(属 P2),故 PUT 只允许在 active/retired 间切换,
|
||||
# rotating 不再可进入;存量 rotating 数据保留只读展示,经 PUT 置 active 即恢复。
|
||||
VALID_CREDENTIAL_UI_STATUSES = ('active', 'retired')
|
||||
|
||||
# 配置实体生命周期转移表(接口定义与绑定共用):动作 → (源状态, 目标状态)。状态不再
|
||||
# 由 PUT 直接改写,只能经动作端点按此表转移(draft→published 发布;published→draft 撤回;
|
||||
# published→retired 退役;retired→draft 恢复为草稿,作为无版本化阶段的保险阀)。
|
||||
CONFIG_STATUS_TRANSITIONS = {
|
||||
'publish': ('draft', 'published'),
|
||||
'unpublish': ('published', 'draft'),
|
||||
'retire': ('published', 'retired'),
|
||||
'reopen': ('retired', 'draft'),
|
||||
}
|
||||
|
||||
|
||||
def _require(value, field: str) -> None:
|
||||
@@ -39,6 +70,70 @@ def _require(value, field: str) -> None:
|
||||
raise ValidationError(f'{field} is required', details={'field': field})
|
||||
|
||||
|
||||
def _require_client(code: str) -> IntegrationClientInstance:
|
||||
"""按编码取客户端实例;不存在即 400(接口定义的连接器类型以其为单一事实源)。"""
|
||||
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
||||
if client is None:
|
||||
raise ValidationError(
|
||||
'client instance not found', code='INTEGRATION.CLIENT_INSTANCE_NOT_FOUND',
|
||||
details={'client_instance_code': code},
|
||||
)
|
||||
return client
|
||||
|
||||
|
||||
def _apply_status_transition(entity, action: str, *, kind: str) -> None:
|
||||
"""按转移表校验并落库状态;非法动作或源状态不符即 400。"""
|
||||
transition = CONFIG_STATUS_TRANSITIONS.get(action)
|
||||
if transition is None:
|
||||
raise ValidationError(
|
||||
'unknown lifecycle action', details={'allowed': sorted(CONFIG_STATUS_TRANSITIONS)})
|
||||
src, dst = transition
|
||||
if entity.status != src:
|
||||
raise ValidationError(
|
||||
f'{kind} status is {entity.status}, cannot {action}',
|
||||
code='INTEGRATION.ILLEGAL_STATUS_TRANSITION',
|
||||
details={'action': action, 'from': entity.status, 'to': dst},
|
||||
)
|
||||
entity.status = dst
|
||||
|
||||
|
||||
def _require_interface(code: str) -> IntegrationInterfaceDefinition:
|
||||
"""按编码取接口定义;不存在即 400(绑定成对校验以其所属客户端为准,而非依赖外键报 500)。"""
|
||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first()
|
||||
if iface is None:
|
||||
raise ValidationError(
|
||||
'interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND',
|
||||
details={'interface_definition_code': code},
|
||||
)
|
||||
return iface
|
||||
|
||||
|
||||
def _validate_binding_pair(client_code, interface_code) -> tuple[IntegrationClientInstance, IntegrationInterfaceDefinition]:
|
||||
"""绑定成对校验:接口定义必须属于所选客户端实例(接口归属即客户端归属)。
|
||||
|
||||
错配组合会产生「拿 A 客户端的地址/凭据发 B 接口报文」的调用,创建/更新时直接
|
||||
400(fail-fast),不留给调用期 fail-closed。
|
||||
"""
|
||||
client = _require_client(str(client_code).strip())
|
||||
iface = _require_interface(str(interface_code).strip())
|
||||
if iface.client_instance_code != client.code:
|
||||
raise ValidationError(
|
||||
'interface definition does not belong to the selected client instance',
|
||||
code='INTEGRATION.BINDING_PAIR_MISMATCH',
|
||||
details={
|
||||
'client_instance_code': client.code,
|
||||
'interface_definition_code': iface.code,
|
||||
'interface_client_instance_code': iface.client_instance_code,
|
||||
},
|
||||
)
|
||||
return client, iface
|
||||
|
||||
|
||||
def _interface_transition(iface, action: str) -> None:
|
||||
"""按转移表校验并落库接口定义状态;非法动作或源状态不符即 400。"""
|
||||
_apply_status_transition(iface, action, kind='interface')
|
||||
|
||||
|
||||
def _serialize_client(client) -> dict:
|
||||
return {
|
||||
'id': client.id, 'code': client.code, 'name': client.name,
|
||||
@@ -64,7 +159,7 @@ def _serialize_binding(binding) -> dict:
|
||||
return {
|
||||
'id': binding.id, 'capability': binding.capability,
|
||||
'context_selector_json': binding.context_selector_json or {},
|
||||
'context_source_code': binding.context_source_code,
|
||||
'param_mapping_json': binding.param_mapping_json or {},
|
||||
'client_instance_code': binding.client_instance_code,
|
||||
'interface_definition_code': binding.interface_definition_code,
|
||||
'mapping_version': binding.mapping_version, 'priority': binding.priority,
|
||||
@@ -73,15 +168,59 @@ def _serialize_binding(binding) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _decrypted_secret(cred) -> dict:
|
||||
"""db 模式下解密凭据字典;密文缺失或主密钥异常时返回空 dict(fail-closed 不炸列表)。"""
|
||||
if cred.secret_provider != 'db' or not cred.secret_ciphertext:
|
||||
return {}
|
||||
try:
|
||||
raw = decrypt_secret(
|
||||
cred.secret_ciphertext,
|
||||
key_config_name=CREDENTIAL_KEY_CONFIG_NAME,
|
||||
codes=_DB_SECRET_CODES,
|
||||
)
|
||||
parsed = json.loads(raw)
|
||||
return parsed if isinstance(parsed, dict) else {}
|
||||
except AppError:
|
||||
return {}
|
||||
|
||||
|
||||
def _serialize_credential(cred) -> dict:
|
||||
secret_dict = _decrypted_secret(cred)
|
||||
return {
|
||||
'id': cred.id, 'code': cred.code, 'secret_ref': cred.secret_ref,
|
||||
'secret_provider': cred.secret_provider, 'credential_type': cred.credential_type,
|
||||
# 非密字段按类型定义回显(如 username);密文字段与密文本身永不回显。
|
||||
'secret_fields': visible_fields(cred.credential_type, secret_dict),
|
||||
'has_secret': bool(cred.secret_ciphertext),
|
||||
'version': cred.version, 'status': cred.status,
|
||||
'updated_at': cred.updated_at.isoformat() if cred.updated_at else None,
|
||||
'last_verified_at': cred.last_verified_at.isoformat() if cred.last_verified_at else None,
|
||||
}
|
||||
|
||||
|
||||
def _apply_db_secret(cred, body) -> None:
|
||||
"""db 模式:按凭据类型定义组装字段并加密落库;只改部分字段可沿用解密出的旧值。
|
||||
|
||||
类型必须在凭据类型注册表内(fail-closed);合并旧值后必填字段仍缺失即拒绝。
|
||||
"""
|
||||
ctype = str(body.get('credential_type') or cred.credential_type or 'password').strip()
|
||||
if get_credential_type(ctype) is None:
|
||||
raise ValidationError('unknown credential_type', details={'credential_type': ctype})
|
||||
cred.credential_type = ctype
|
||||
current = _decrypted_secret(cred) if cred.secret_ciphertext else {}
|
||||
values: dict = dict(current)
|
||||
for key in (field['key'] for field in get_credential_type(ctype)['fields']):
|
||||
incoming = body.get(key)
|
||||
if incoming is not None and str(incoming) != '':
|
||||
values[key] = str(incoming)
|
||||
merged = build_secret_dict(ctype, values)
|
||||
cred.secret_ciphertext = encrypt_secret(
|
||||
json.dumps(merged, ensure_ascii=False),
|
||||
key_config_name=CREDENTIAL_KEY_CONFIG_NAME,
|
||||
codes=_DB_SECRET_CODES,
|
||||
)
|
||||
|
||||
|
||||
def _result_to_dict(result: IntegrationCallResult) -> dict:
|
||||
return {
|
||||
'status': result.status,
|
||||
@@ -98,7 +237,6 @@ def _result_to_dict(result: IntegrationCallResult) -> dict:
|
||||
@integration_connector_bp.route('/capabilities', methods=['GET'])
|
||||
@require_admin
|
||||
def list_capabilities_endpoint():
|
||||
ensure_capabilities_loaded()
|
||||
data = [{
|
||||
'name': spec.name, 'write': spec.write, 'idempotency': spec.idempotency,
|
||||
'input_schema': spec.input_schema, 'output_schema': spec.output_schema,
|
||||
@@ -231,15 +369,15 @@ def create_interface_definition():
|
||||
code = str(body.get('code') or '').strip()
|
||||
_require(code, 'code')
|
||||
_require(body.get('client_instance_code'), 'client_instance_code')
|
||||
connector_type = str(body.get('connector_type') or '')
|
||||
if connector_type not in VALID_CONNECTOR_TYPES:
|
||||
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
|
||||
# 连接器类型以所选客户端实例为单一事实源(服务端推导落库,忽略请求体传值,
|
||||
# 杜绝接口与客户端类型不一致);客户端不存在即 400,而非依赖外键报 500。
|
||||
client = _require_client(str(body['client_instance_code']).strip())
|
||||
status = str(body.get('status') or 'draft')
|
||||
if status not in VALID_STATUSES:
|
||||
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
|
||||
iface = IntegrationInterfaceDefinition(
|
||||
code=code, name=str(body.get('name') or code).strip(),
|
||||
client_instance_code=body['client_instance_code'], connector_type=connector_type,
|
||||
client_instance_code=client.code, connector_type=client.connector_type,
|
||||
http_method=(str(body.get('http_method') or '').strip().upper() or None),
|
||||
request_path=(str(body.get('request_path') or '').strip() or None),
|
||||
request_spec_json=body.get('request_spec_json') or {},
|
||||
@@ -247,7 +385,9 @@ def create_interface_definition():
|
||||
response_mapping_json=body.get('response_mapping_json') or {},
|
||||
output_schema_json=body.get('output_schema_json') or {},
|
||||
version=int(body.get('version') or 1), status=status,
|
||||
enabled=bool(body.get('enabled', True)),
|
||||
# enabled 冻结:与 status 重复表达可用性且运行时不消费(假开关),请求体传值忽略;
|
||||
# 可用性只由 status 生命周期表达,列待 P2 版本化迁移时清理。
|
||||
enabled=True,
|
||||
)
|
||||
from app import db
|
||||
db.session.add(iface)
|
||||
@@ -258,7 +398,11 @@ def create_interface_definition():
|
||||
@integration_connector_bp.route('/interface-definitions/<code>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_interface_definition(code):
|
||||
"""更新接口定义(code 不变;可改模板/入参/回传/出参 Schema、状态、启停)。"""
|
||||
"""更新接口定义(code 不变;可改模板/入参/回传/出参 Schema 与所属客户端)。
|
||||
|
||||
状态不在此改写(须经 /publish /unpublish /retire /reopen 动作端点按转移表流转);
|
||||
连接器类型由所属客户端实例服务端推导,请求体传值被忽略。
|
||||
"""
|
||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first()
|
||||
if iface is None:
|
||||
raise NotFoundError('interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND')
|
||||
@@ -268,12 +412,9 @@ def update_interface_definition(code):
|
||||
iface.name = str(body['name']).strip()
|
||||
if body.get('client_instance_code') is not None:
|
||||
_require(body.get('client_instance_code'), 'client_instance_code')
|
||||
iface.client_instance_code = body['client_instance_code']
|
||||
if body.get('connector_type') is not None:
|
||||
connector_type = str(body['connector_type'])
|
||||
if connector_type not in VALID_CONNECTOR_TYPES:
|
||||
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
|
||||
iface.connector_type = connector_type
|
||||
client = _require_client(str(body['client_instance_code']).strip())
|
||||
iface.client_instance_code = client.code
|
||||
iface.connector_type = client.connector_type
|
||||
if 'http_method' in body:
|
||||
iface.http_method = str(body.get('http_method') or '').strip().upper() or None
|
||||
if 'request_path' in body:
|
||||
@@ -283,18 +424,52 @@ def update_interface_definition(code):
|
||||
setattr(iface, json_field, body.get(json_field) or {})
|
||||
if body.get('version') is not None:
|
||||
iface.version = int(body.get('version') or 1)
|
||||
if body.get('status') is not None:
|
||||
status = str(body['status'])
|
||||
if status not in VALID_STATUSES:
|
||||
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
|
||||
iface.status = status
|
||||
if 'enabled' in body:
|
||||
iface.enabled = bool(body.get('enabled', True))
|
||||
from app import db
|
||||
db.session.commit()
|
||||
return ok(_serialize_interface(iface))
|
||||
|
||||
|
||||
# ---- 接口定义生命周期(状态只经动作端点按转移表流转) ----
|
||||
|
||||
def _do_interface_lifecycle(code: str, action: str):
|
||||
"""动作端点共用体:取接口 → 按转移表转移 → 落库并回显。"""
|
||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first()
|
||||
if iface is None:
|
||||
raise NotFoundError('interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND')
|
||||
_interface_transition(iface, action)
|
||||
from app import db
|
||||
db.session.commit()
|
||||
return ok(_serialize_interface(iface))
|
||||
|
||||
|
||||
@integration_connector_bp.route('/interface-definitions/<code>/publish', methods=['POST'])
|
||||
@require_admin
|
||||
def publish_interface_definition(code):
|
||||
"""发布接口定义(draft → published):发布后才会被绑定解析选中。"""
|
||||
return _do_interface_lifecycle(code, 'publish')
|
||||
|
||||
|
||||
@integration_connector_bp.route('/interface-definitions/<code>/unpublish', methods=['POST'])
|
||||
@require_admin
|
||||
def unpublish_interface_definition(code):
|
||||
"""撤回发布(published → draft):临时下线,修正后可重新发布。"""
|
||||
return _do_interface_lifecycle(code, 'unpublish')
|
||||
|
||||
|
||||
@integration_connector_bp.route('/interface-definitions/<code>/retire', methods=['POST'])
|
||||
@require_admin
|
||||
def retire_interface_definition(code):
|
||||
"""退役(published → retired):该接口引用的所有绑定同时失效。"""
|
||||
return _do_interface_lifecycle(code, 'retire')
|
||||
|
||||
|
||||
@integration_connector_bp.route('/interface-definitions/<code>/reopen', methods=['POST'])
|
||||
@require_admin
|
||||
def reopen_interface_definition(code):
|
||||
"""恢复为草稿(retired → draft):版本化发布上线前的保险阀,重新走发布流程。"""
|
||||
return _do_interface_lifecycle(code, 'reopen')
|
||||
|
||||
|
||||
# ---- Binding ----
|
||||
|
||||
@integration_connector_bp.route('/bindings', methods=['GET'])
|
||||
@@ -307,23 +482,22 @@ def list_bindings():
|
||||
@integration_connector_bp.route('/bindings', methods=['POST'])
|
||||
@require_admin
|
||||
def create_binding():
|
||||
"""创建绑定:成对校验客户端与接口后落库;新建固定落 draft,发布走 /publish 动作端点。"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
_require(body.get('capability'), 'capability')
|
||||
_require(body.get('client_instance_code'), 'client_instance_code')
|
||||
_require(body.get('interface_definition_code'), 'interface_definition_code')
|
||||
status = str(body.get('status') or 'draft')
|
||||
if status not in VALID_STATUSES:
|
||||
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
|
||||
client, iface = _validate_binding_pair(body['client_instance_code'], body['interface_definition_code'])
|
||||
binding = IntegrationBinding(
|
||||
capability=body['capability'],
|
||||
context_selector_json=body.get('context_selector_json') or {},
|
||||
context_source_code=(str(body.get('context_source_code') or '').strip() or None),
|
||||
client_instance_code=body['client_instance_code'],
|
||||
interface_definition_code=body['interface_definition_code'],
|
||||
param_mapping_json=body.get('param_mapping_json') or {},
|
||||
client_instance_code=client.code,
|
||||
interface_definition_code=iface.code,
|
||||
mapping_version=int(body.get('mapping_version') or 1),
|
||||
priority=int(body.get('priority') or 0),
|
||||
environment=str(body.get('environment') or 'prod').strip(),
|
||||
status=status,
|
||||
status='draft',
|
||||
)
|
||||
from app import db
|
||||
db.session.add(binding)
|
||||
@@ -334,7 +508,11 @@ def create_binding():
|
||||
@integration_connector_bp.route('/bindings/<int:binding_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_binding(binding_id):
|
||||
"""更新绑定(capability 不变;可改 context 选择器、客户端/接口、映射版本、优先级、环境、生效区间、状态)。"""
|
||||
"""更新绑定(capability 不变;可改 context 选择器、客户端/接口、映射版本、优先级、环境、生效区间)。
|
||||
|
||||
状态不在此改写(须经 /publish /unpublish /retire /reopen 动作端点按转移表流转);
|
||||
客户端与接口成对校验:以变更后的最终组合为准,接口定义不属于该客户端即 400。
|
||||
"""
|
||||
from app import db
|
||||
binding = db.session.get(IntegrationBinding, binding_id)
|
||||
if binding is None:
|
||||
@@ -345,14 +523,23 @@ def update_binding(binding_id):
|
||||
binding.capability = body['capability']
|
||||
if 'context_selector_json' in body:
|
||||
binding.context_selector_json = body.get('context_selector_json') or {}
|
||||
if 'context_source_code' in body:
|
||||
binding.context_source_code = str(body.get('context_source_code') or '').strip() or None
|
||||
if body.get('client_instance_code') is not None:
|
||||
_require(body.get('client_instance_code'), 'client_instance_code')
|
||||
binding.client_instance_code = body['client_instance_code']
|
||||
if body.get('interface_definition_code') is not None:
|
||||
_require(body.get('interface_definition_code'), 'interface_definition_code')
|
||||
binding.interface_definition_code = body['interface_definition_code']
|
||||
if 'param_mapping_json' in body:
|
||||
binding.param_mapping_json = body.get('param_mapping_json') or {}
|
||||
new_client_code = body.get('client_instance_code')
|
||||
new_iface_code = body.get('interface_definition_code')
|
||||
if new_client_code is not None:
|
||||
_require(new_client_code, 'client_instance_code')
|
||||
if new_iface_code is not None:
|
||||
_require(new_iface_code, 'interface_definition_code')
|
||||
if new_client_code is not None or new_iface_code is not None:
|
||||
_validate_binding_pair(
|
||||
new_client_code if new_client_code is not None else binding.client_instance_code,
|
||||
new_iface_code if new_iface_code is not None else binding.interface_definition_code,
|
||||
)
|
||||
if new_client_code is not None:
|
||||
binding.client_instance_code = str(new_client_code).strip()
|
||||
if new_iface_code is not None:
|
||||
binding.interface_definition_code = str(new_iface_code).strip()
|
||||
if body.get('mapping_version') is not None:
|
||||
binding.mapping_version = int(body.get('mapping_version') or 1)
|
||||
if body.get('priority') is not None:
|
||||
@@ -363,16 +550,69 @@ def update_binding(binding_id):
|
||||
binding.effective_from = body['effective_from'] or None
|
||||
if body.get('effective_to') is not None:
|
||||
binding.effective_to = body['effective_to'] or None
|
||||
if body.get('status') is not None:
|
||||
status = str(body['status'])
|
||||
if status not in VALID_STATUSES:
|
||||
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
|
||||
binding.status = status
|
||||
from app import db
|
||||
db.session.commit()
|
||||
return ok(_serialize_binding(binding))
|
||||
|
||||
|
||||
# ---- 绑定生命周期(状态只经动作端点按转移表流转) ----
|
||||
|
||||
def _do_binding_lifecycle(binding_id: int, action: str):
|
||||
"""动作端点共用体:取绑定 → 按转移表转移 → 落库并回显。
|
||||
|
||||
发布(publish)附加就绪门禁:引用的接口定义须已发布、客户端实例须启用,
|
||||
否则 400——避免出现列表「已发布」但调用期永远 fail-closed 的死绑定
|
||||
(与 binding.resolve_binding 的调用期门禁同一语义)。
|
||||
"""
|
||||
from app import db
|
||||
binding = db.session.get(IntegrationBinding, binding_id)
|
||||
if binding is None:
|
||||
raise NotFoundError('binding not found', code='INTEGRATION.BINDING_NOT_FOUND')
|
||||
if action == 'publish':
|
||||
client = IntegrationClientInstance.query.filter_by(code=binding.client_instance_code).first()
|
||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=binding.interface_definition_code).first()
|
||||
if client is None or iface is None or iface.status != 'published' or not client.enabled:
|
||||
raise ValidationError(
|
||||
'binding target not ready: interface must be published and client instance enabled',
|
||||
code='INTEGRATION.BINDING_TARGET_NOT_READY',
|
||||
details={
|
||||
'client_instance_code': binding.client_instance_code,
|
||||
'interface_definition_code': binding.interface_definition_code,
|
||||
},
|
||||
)
|
||||
_apply_status_transition(binding, action, kind='binding')
|
||||
db.session.commit()
|
||||
return ok(_serialize_binding(binding))
|
||||
|
||||
|
||||
@integration_connector_bp.route('/bindings/<int:binding_id>/publish', methods=['POST'])
|
||||
@require_admin
|
||||
def publish_binding(binding_id):
|
||||
"""发布绑定(draft → published):发布后才会被绑定解析选中。"""
|
||||
return _do_binding_lifecycle(binding_id, 'publish')
|
||||
|
||||
|
||||
@integration_connector_bp.route('/bindings/<int:binding_id>/unpublish', methods=['POST'])
|
||||
@require_admin
|
||||
def unpublish_binding(binding_id):
|
||||
"""撤回发布(published → draft):临时下线,修正后可重新发布。"""
|
||||
return _do_binding_lifecycle(binding_id, 'unpublish')
|
||||
|
||||
|
||||
@integration_connector_bp.route('/bindings/<int:binding_id>/retire', methods=['POST'])
|
||||
@require_admin
|
||||
def retire_binding(binding_id):
|
||||
"""退役(published → retired):绑定退出自动调用。"""
|
||||
return _do_binding_lifecycle(binding_id, 'retire')
|
||||
|
||||
|
||||
@integration_connector_bp.route('/bindings/<int:binding_id>/reopen', methods=['POST'])
|
||||
@require_admin
|
||||
def reopen_binding(binding_id):
|
||||
"""恢复为草稿(retired → draft):重新走发布流程。"""
|
||||
return _do_binding_lifecycle(binding_id, 'reopen')
|
||||
|
||||
|
||||
# ---- 凭据引用 ----
|
||||
|
||||
@integration_connector_bp.route('/credential-references', methods=['GET'])
|
||||
@@ -385,41 +625,87 @@ def list_credential_references():
|
||||
@integration_connector_bp.route('/credential-references', methods=['POST'])
|
||||
@require_admin
|
||||
def create_credential_reference():
|
||||
"""创建凭据引用:db 模式(默认)按凭据类型加密字段落库;env 模式只存配置键名。"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
_require(body.get('code'), 'code')
|
||||
_require(body.get('secret_ref'), 'secret_ref')
|
||||
from app import db
|
||||
# 缺省保持 env(兼容既有直连 API 调用);管理端 db 模式显式传 secret_provider='db'。
|
||||
provider = str(body.get('secret_provider') or 'env').strip()
|
||||
if provider not in VALID_SECRET_PROVIDERS:
|
||||
raise ValidationError('invalid secret_provider', details={'allowed': list(VALID_SECRET_PROVIDERS)})
|
||||
code = str(body['code']).strip()
|
||||
if IntegrationCredentialReference.query.filter_by(code=code).first():
|
||||
raise ValidationError('credential reference code already exists', code='RESOURCE.CONFLICT')
|
||||
status = str(body.get('status') or 'active')
|
||||
if status not in ('active', 'rotating', 'retired'):
|
||||
raise ValidationError('invalid credential status', details={'allowed': ['active', 'rotating', 'retired']})
|
||||
cred = IntegrationCredentialReference(
|
||||
code=str(body['code']).strip(),
|
||||
secret_ref=str(body['secret_ref']).strip(),
|
||||
secret_provider=str(body.get('secret_provider') or 'env').strip(),
|
||||
code=code,
|
||||
secret_ref=str(body.get('secret_ref') or '').strip(),
|
||||
secret_provider=provider,
|
||||
credential_type=str(body.get('credential_type') or 'password').strip(),
|
||||
version=int(body.get('version') or 1),
|
||||
status=str(body.get('status') or 'active'),
|
||||
status=status,
|
||||
)
|
||||
if provider == 'db':
|
||||
_apply_db_secret(cred, body)
|
||||
cred.secret_ref = f'db:{code}'
|
||||
else:
|
||||
_require(cred.secret_ref, 'secret_ref')
|
||||
from app import db
|
||||
db.session.add(cred)
|
||||
db.session.commit()
|
||||
# 永不回显真实凭据值;只回元数据。
|
||||
# 永不回显真实凭据值;只回元数据与非密字段。
|
||||
return ok(_serialize_credential(cred), status=201)
|
||||
|
||||
|
||||
@integration_connector_bp.route('/credential-references/types', methods=['GET'])
|
||||
@require_admin
|
||||
def list_credential_type_specs():
|
||||
"""凭据类型注册表清单(类型 + 字段定义),供管理端动态渲染表单与占位符提示。"""
|
||||
return ok(list_credential_types())
|
||||
|
||||
|
||||
@integration_connector_bp.route('/credential-references/<code>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_credential_reference(code):
|
||||
"""更新凭据引用(code 不变;可改 secret_ref/provider/type/status)。只存引用,永不回显明文。"""
|
||||
"""更新凭据引用(code 不变);db 模式可只改部分字段(其余沿用旧值),永不回显明文。"""
|
||||
cred = IntegrationCredentialReference.query.filter_by(code=code).first()
|
||||
if cred is None:
|
||||
raise NotFoundError('credential reference not found', code='INTEGRATION.CREDENTIAL_NOT_FOUND')
|
||||
body = request.get_json(silent=True) or {}
|
||||
if body.get('secret_ref') is not None:
|
||||
_require(body.get('secret_ref'), 'secret_ref')
|
||||
cred.secret_ref = str(body['secret_ref']).strip()
|
||||
if body.get('secret_provider') is not None:
|
||||
cred.secret_provider = str(body['secret_provider']).strip()
|
||||
if body.get('credential_type') is not None:
|
||||
cred.credential_type = str(body['credential_type']).strip()
|
||||
provider = str(body['secret_provider']).strip()
|
||||
if provider not in VALID_SECRET_PROVIDERS:
|
||||
raise ValidationError('invalid secret_provider', details={'allowed': list(VALID_SECRET_PROVIDERS)})
|
||||
cred.secret_provider = provider
|
||||
if provider == 'env':
|
||||
# 切回 env 模式时清掉遗留密文,避免失效凭据残留库中。
|
||||
cred.secret_ciphertext = None
|
||||
field_keys = tuple(
|
||||
field['key'] for field in (get_credential_type(
|
||||
str(body.get('credential_type') or cred.credential_type or 'password')) or {'fields': []}
|
||||
)['fields']
|
||||
)
|
||||
has_secret_input = any(body.get(key) is not None for key in field_keys)
|
||||
if cred.secret_provider == 'db':
|
||||
if has_secret_input or body.get('credential_type') is not None or not cred.secret_ciphertext:
|
||||
_apply_db_secret(cred, body)
|
||||
cred.secret_ref = f'db:{cred.code}'
|
||||
else:
|
||||
if body.get('secret_ref') is not None:
|
||||
_require(body.get('secret_ref'), 'secret_ref')
|
||||
cred.secret_ref = str(body['secret_ref']).strip()
|
||||
if has_secret_input:
|
||||
raise ValidationError('credential fields only apply to db credentials')
|
||||
if body.get('status') is not None:
|
||||
cred.status = str(body['status']).strip()
|
||||
# 状态改写冻结为两态开关:仅允许 active/retired(管理端行内开关即走此通道);
|
||||
# rotating 不可进入——其现语义等于断供(resolve_credential 只解析 active),
|
||||
# 真实版本化轮换属 P2;存量 rotating 数据经置 active 即恢复。
|
||||
status = str(body['status']).strip()
|
||||
if status not in VALID_CREDENTIAL_UI_STATUSES:
|
||||
raise ValidationError(
|
||||
'invalid credential status', details={'allowed': list(VALID_CREDENTIAL_UI_STATUSES)})
|
||||
cred.status = status
|
||||
from app import db
|
||||
db.session.commit()
|
||||
return ok(_serialize_credential(cred))
|
||||
@@ -430,6 +716,11 @@ def update_credential_reference(code):
|
||||
@integration_connector_bp.route('/client-instances/<code>/test', methods=['POST'])
|
||||
@require_admin
|
||||
def test_connection(code):
|
||||
"""连接测试探针:只证明网络/服务可达(设计文档:连接测试不做业务调用)。
|
||||
|
||||
配置兼容层与 binding.resolve_binding 同源:endpoint/timeout_seconds 独立列
|
||||
拼回 config_json 后再交给 transport,否则存独立列的地址会被误判为未冻结。
|
||||
"""
|
||||
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
||||
if client is None:
|
||||
raise NotFoundError('client instance not found')
|
||||
@@ -439,9 +730,20 @@ def test_connection(code):
|
||||
raise ValidationError(
|
||||
'no transport available for client', code='INTEGRATION.TRANSPORT_NOT_FROZEN',
|
||||
)
|
||||
raw = transport.call(
|
||||
client={'config_json': client.config_json or {}, 'credential': {}},
|
||||
interface={'request_spec_json': {}},
|
||||
request={},
|
||||
)
|
||||
return ok({'ok': True, 'status': raw.get('status') or 'success', 'result': raw})
|
||||
client_payload = {
|
||||
'config_json': merge_client_config({
|
||||
'config_json': client.config_json or {},
|
||||
'endpoint': client.endpoint,
|
||||
'timeout_seconds': client.timeout_seconds,
|
||||
}),
|
||||
'credential': {},
|
||||
}
|
||||
probe = getattr(transport, 'probe', None)
|
||||
if probe is not None:
|
||||
raw = probe(client=client_payload)
|
||||
ok_flag = bool(raw.get('ok'))
|
||||
else:
|
||||
# 测试替身等未实现 probe 的传输:回退 call(空 interface 规格)。
|
||||
raw = transport.call(client=client_payload, interface={'request_spec_json': {}}, request={})
|
||||
ok_flag = raw.get('status') not in ('business_failed', 'technical_failed', 'timeout', 'result_unknown')
|
||||
return ok({'ok': ok_flag, 'status': 'success' if ok_flag else 'failed', 'result': raw})
|
||||
@@ -1,10 +0,0 @@
|
||||
"""
|
||||
backend/app/api/knowledge_base.py
|
||||
|
||||
用途:知识库 API 兼容 shim(Wave 3 迁包过渡期)。
|
||||
依赖:app.api.kb。
|
||||
逻辑:旧 import 路径仍可用;新代码请用 app.api.kb。
|
||||
"""
|
||||
from app.api.kb import knowledge_base_bp
|
||||
|
||||
__all__ = ['knowledge_base_bp']
|
||||
@@ -1,10 +0,0 @@
|
||||
"""
|
||||
backend/app/api/schedule_admin.py
|
||||
|
||||
用途:排程 API 兼容 shim(Wave 3 迁包过渡期)。
|
||||
依赖:app.api.schedule。
|
||||
逻辑:旧 import 路径仍可用;新代码请用 app.api.schedule。
|
||||
"""
|
||||
from app.api.schedule import schedule_admin_bp
|
||||
|
||||
__all__ = ['schedule_admin_bp']
|
||||
@@ -27,6 +27,7 @@ from app.services.training_config_service import get_published_config, list_trai
|
||||
from app.services.lean_training_service import (
|
||||
LEAN_TRAINING_TYPE,
|
||||
create_or_update_weekly_task,
|
||||
export_dashboard_excel,
|
||||
get_current_weekly_task,
|
||||
get_weekly_task_for_admin,
|
||||
list_dashboard,
|
||||
@@ -275,3 +276,16 @@ def get_admin_lean_training_dashboard():
|
||||
_require_lean_training_manager()
|
||||
raw_task_id = request.args.get("task_id", type=int)
|
||||
return ok(list_dashboard(raw_task_id))
|
||||
|
||||
|
||||
@training_admin_bp.route("/lean-training/dashboard/export", methods=["GET"])
|
||||
def export_admin_lean_training_dashboard():
|
||||
_require_lean_training_manager()
|
||||
raw_task_id = request.args.get("task_id", type=int)
|
||||
file_data, file_name = export_dashboard_excel(raw_task_id)
|
||||
return send_file(
|
||||
BytesIO(file_data),
|
||||
as_attachment=True,
|
||||
download_name=file_name,
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
@@ -14,7 +14,7 @@ from flask import current_app, jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ValidationError
|
||||
from app.services.wecom_notify import send_wecom_event_message
|
||||
from app.services.integrations.wecom.notify import send_wecom_event_message
|
||||
|
||||
from . import auth as _compat
|
||||
from .auth import auth_bp
|
||||
|
||||
@@ -14,8 +14,8 @@ from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaul
|
||||
from app.services.feedback_notify import send_feedback_group_notification
|
||||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||
from app.services.agent_registry.serialization import serialize_registry_fields
|
||||
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
|
||||
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
|
||||
from app.services.integrations.wecom.notify import mark_wecom_message_opened, send_wecom_event_message
|
||||
from app.services.integrations.wecom.crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
|
||||
from app.core.auth.jwt import get_current_user as _auth_current_user, issue_local_access_token
|
||||
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
|
||||
from sqlalchemy import and_, or_, inspect, insert
|
||||
|
||||
@@ -14,7 +14,7 @@ from flask import current_app, jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ConflictError, ForbiddenError, UnauthorizedError, ValidationError
|
||||
from app.services.wecom_crypto import decrypt_wecom_aes, extract_encrypt_field
|
||||
from app.services.integrations.wecom.crypto import decrypt_wecom_aes, extract_encrypt_field
|
||||
|
||||
from . import auth as _compat
|
||||
from .auth import auth_bp
|
||||
|
||||
@@ -13,7 +13,7 @@ from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaul
|
||||
from app.services.feedback_notify import send_feedback_group_notification
|
||||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||
from app.services.agent_registry.serialization import serialize_registry_fields
|
||||
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
|
||||
from app.services.integrations.wecom.notify import mark_wecom_message_opened, send_wecom_event_message
|
||||
import re
|
||||
import ast
|
||||
from app.core.errors import (
|
||||
@@ -108,7 +108,7 @@ def submit_leave_workflow():
|
||||
if not form_data.get(key):
|
||||
raise ValidationError(f'{label}不能为空。')
|
||||
try:
|
||||
from app.services.oa_leave_workflow import OALeaveWorkflowService, OALeaveWorkflowError
|
||||
from app.services.integrations.oa.leave_workflow import OALeaveWorkflowService, OALeaveWorkflowError
|
||||
result = OALeaveWorkflowService.submit_leave_request(form_data, user)
|
||||
except OALeaveWorkflowError as exc:
|
||||
current_app.logger.warning('[oa-leave] submit failed user_id=%s employee_id=%s err=%s', getattr(user, 'id', None), form_data.get('employeeId'), exc)
|
||||
@@ -358,7 +358,7 @@ def get_agent_details(id):
|
||||
|
||||
dify_parameters = None
|
||||
if resolve_runtime_provider(agent) in {'dify', 'hybrid'} and getattr(agent, 'dify_api_key', None):
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
try:
|
||||
params = DifyService.get_app_parameters(agent)
|
||||
|
||||
@@ -154,6 +154,21 @@ def _require_formal_notice(task: Any) -> ShippingNotice:
|
||||
return task
|
||||
|
||||
|
||||
def _require_editable_task(task: Any) -> Any:
|
||||
"""订单编辑写接口的实体守卫:正式 Notice 或建单前 OT 均可。
|
||||
|
||||
核心逻辑:订单字段/行的编辑权限由服务层状态制闸门裁决
|
||||
(Excel ready 硬冻结 + 活动 Attempt 忙碌锁 + Schema 反向锁),
|
||||
与实体类型无关——通知准备阶段(Notice 未建)编辑履约字段是受支持场景。
|
||||
"""
|
||||
if not isinstance(task, (ShippingNotice, ShippingOrderTask)):
|
||||
raise ValidationError(
|
||||
'Formal shipping notice is required for this operation',
|
||||
code='SHIPPING.FORMAL_NOTICE_REQUIRED',
|
||||
)
|
||||
return task
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
|
||||
def workspace_shipping_tasks():
|
||||
"""分页列出当前用户可见的发货任务,可按处理状态过滤。"""
|
||||
@@ -199,6 +214,7 @@ def workspace_shipping_my_todos():
|
||||
todo_category=str(request.args.get('todo_category') or '').strip() or None,
|
||||
customer=str(request.args.get('customer') or '').strip() or None,
|
||||
task_no=str(request.args.get('task_no') or '').strip() or None,
|
||||
terminal_kind=str(request.args.get('terminal_kind') or '').strip() or None,
|
||||
))
|
||||
|
||||
|
||||
@@ -212,6 +228,67 @@ def workspace_shipping_my_todos_count():
|
||||
return _ok(count_my_todos(user.id, is_admin=is_admin))
|
||||
|
||||
|
||||
def _done_lines_report_params() -> dict[str, Any]:
|
||||
"""解析明细报表共用筛选参数(客户/料号/发货通知日期范围),供查询与导出复用。"""
|
||||
return {
|
||||
'customer': str(request.args.get('customer') or '').strip() or None,
|
||||
'part_number': str(request.args.get('part_number') or '').strip() or None,
|
||||
'notice_date_from': str(request.args.get('notice_date_from') or '').strip() or None,
|
||||
'notice_date_to': str(request.args.get('notice_date_to') or '').strip() or None,
|
||||
}
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/my-todos/done-lines', methods=['GET'])
|
||||
def workspace_shipping_done_lines():
|
||||
"""
|
||||
分页列出已完成(已核验上传成功)通知的平铺明细行,供「通知完成」子视图报表。
|
||||
|
||||
核心逻辑:明细行跨 Notice 混排、不按 OT 聚合;支持 客户 / 料号 /
|
||||
发货通知日期范围 筛选;行结构为标准 12 字段 + 溯源编号(task_no/business_no)。
|
||||
"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.done_line_report import list_done_notice_lines
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
try:
|
||||
page = int(request.args.get('page') or 1)
|
||||
page_size = int(request.args.get('page_size') or 20)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('page and page_size must be integers') from exc
|
||||
return _ok(list_done_notice_lines(
|
||||
user.id,
|
||||
is_admin=is_admin,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
**_done_lines_report_params(),
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/my-todos/done-lines/export', methods=['GET'])
|
||||
def workspace_shipping_done_lines_export():
|
||||
"""
|
||||
导出当前筛选下的已完成通知明细 Excel。
|
||||
|
||||
核心逻辑:固定 12 列标准格式(客户/客户编号/订单日期/订单项次/料号/数量/
|
||||
约定出货日期/客户PO/已用数量/open qty/订单单号/单价),OT 编号不落列;
|
||||
已用数量 / open qty 无数据源留空。
|
||||
"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.done_line_report import build_done_lines_xlsx
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
stream, filename = build_done_lines_xlsx(
|
||||
user.id,
|
||||
is_admin=is_admin,
|
||||
**_done_lines_report_params(),
|
||||
)
|
||||
response = send_file(
|
||||
stream, as_attachment=True, download_name=filename, mimetype=EXPORT_MIME_TYPE,
|
||||
)
|
||||
response.call_on_close(stream.close)
|
||||
return response
|
||||
|
||||
|
||||
def _batch_task_nos(data: dict) -> list[str]:
|
||||
"""校验批量任务号,统一限制 100 条并去重,避免前端循环绕过服务端门禁。"""
|
||||
raw_task_nos = data.get('task_nos')
|
||||
@@ -481,6 +558,45 @@ def workspace_shipping_task_detail(task_no: str):
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/odm-options', methods=['GET'])
|
||||
def workspace_shipping_task_odm_options(task_no: str):
|
||||
"""返回整单 ODM ID 候选与当前选择(工作台整单裁决路径,只读)。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
from app.services.shipping_notice.notice_odm_choice_service import notice_odm_options
|
||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||||
|
||||
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok(notice_odm_options(task))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/odm-choice', methods=['POST'])
|
||||
def workspace_set_shipping_task_odm_choice(task_no: str):
|
||||
"""保存整单 ODM ID 用户选择;重复提交覆盖旧选择,成功后前端可重试生成 Excel。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
from app.services.shipping_notice.notice_odm_choice_service import set_notice_odm_choice
|
||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||||
|
||||
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
snapshot_line_id = int(data.get('snapshot_line_id') or 0)
|
||||
except (TypeError, ValueError):
|
||||
snapshot_line_id = 0
|
||||
result = set_notice_odm_choice(
|
||||
task,
|
||||
snapshot_line_id=snapshot_line_id,
|
||||
odm_id=str(data.get('odm_id') or ''),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/audit-timeline', methods=['GET'])
|
||||
def workspace_list_shipping_task_audit_timeline(task_no: str):
|
||||
"""业务用户 Task 审计时间线(统一 ShippingAuditEvent,无敏感快照)。"""
|
||||
@@ -559,7 +675,7 @@ def workspace_update_shipping_notice_fields(task_no: str):
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
task = _require_formal_notice(task)
|
||||
task = _require_editable_task(task)
|
||||
data = request.get_json(silent=True) or {}
|
||||
fields = data.get('fields')
|
||||
if not isinstance(fields, dict) or not fields:
|
||||
@@ -606,7 +722,7 @@ def workspace_update_shipping_notice_line(task_no: str):
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
task = _require_formal_notice(task)
|
||||
task = _require_editable_task(task)
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
line_index = int(data.get('line_index'))
|
||||
@@ -695,7 +811,7 @@ def workspace_add_shipping_notice_line(task_no: str):
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
task = _require_formal_notice(task)
|
||||
task = _require_editable_task(task)
|
||||
data = request.get_json(silent=True) or {}
|
||||
line = data.get('line')
|
||||
if not isinstance(line, dict) or not line:
|
||||
@@ -721,7 +837,7 @@ def workspace_remove_shipping_notice_line(task_no: str):
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
task = _require_formal_notice(task)
|
||||
task = _require_editable_task(task)
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
line_index = int(data.get('line_index'))
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
backend/app/api/workspace/voucher_check.py
|
||||
|
||||
用途:工作台立账凭证检核查询与强制重检 API(任务列表 / 批次明细 / 企微发送记录)。
|
||||
依赖:auth.jwt、response_utils envelope、voucher_check.query_service。
|
||||
逻辑:对话与检核任务页共用;GET notifications 为企微发送记录;POST runs 仅 admin,以 force_all 入队周批排程。
|
||||
用途:立账凭证检核查询、强制重检与通知配置 API(任务列表 / 最近一次检核 / 批次明细 / 企微发送记录 / 按类型接收人)。
|
||||
依赖:auth.jwt、response_utils envelope、Agent 授权、voucher_check.query_service、notify_config_service。
|
||||
逻辑:Chat Agent 与旧工作台查询共用;GET runs/latest 不跟筛选;GET notifications 为企微发送记录;
|
||||
查询要求平台 admin 或持有 `agent_code=voucher_check` 的 Agent 授权;POST runs 与通知配置仅 admin。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -13,23 +14,88 @@ from flask import Blueprint, request
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.services.voucher_check import query_service
|
||||
from app.models import Agent
|
||||
from app.services.voucher_check import notify_config_service, query_service
|
||||
|
||||
workspace_voucher_check_bp = Blueprint("workspace_voucher_check", __name__)
|
||||
|
||||
VOUCHER_CHECK_AGENT_CODE = "voucher_check"
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""
|
||||
返回当前登录用户。
|
||||
|
||||
Returns:
|
||||
已认证用户。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 请求没有有效登录身份。
|
||||
"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _require_admin():
|
||||
"""工作台强制重检仅管理员可触发,鉴权方式与本蓝图 GET 一致。"""
|
||||
def _user_has_voucher_check_agent(user) -> bool:
|
||||
"""
|
||||
判断用户是否持有启用中的立账凭证检核 Agent。
|
||||
|
||||
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions;admin 不走此判断。
|
||||
|
||||
Args:
|
||||
user: 已认证用户。
|
||||
|
||||
Returns:
|
||||
已绑定启用中的 voucher_check Agent 时为 True。
|
||||
"""
|
||||
agent = Agent.query.filter_by(agent_code=VOUCHER_CHECK_AGENT_CODE, is_active=True).first()
|
||||
return bool(agent is not None and agent in user.agents)
|
||||
|
||||
|
||||
def _require_voucher_check_access():
|
||||
"""
|
||||
确保当前用户已登录且具备立账凭证检核访问权限。
|
||||
|
||||
核心逻辑:平台 admin 放行;普通用户必须被授予启用中的 `agent_code=voucher_check` Agent。
|
||||
无权限时返回业务 403,而不是静默空数据。
|
||||
|
||||
Returns:
|
||||
已认证且具备立账凭证 Agent 授权(或 admin)的用户。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 请求没有有效登录身份。
|
||||
ForbiddenError: 已登录但没有立账凭证 Agent 授权。
|
||||
"""
|
||||
user = _require_user()
|
||||
if getattr(user, "role", None) == "admin" or _user_has_voucher_check_agent(user):
|
||||
return user
|
||||
raise ForbiddenError(
|
||||
"Voucher check agent permission required",
|
||||
code="VOUCHER_CHECK.FORBIDDEN",
|
||||
)
|
||||
|
||||
|
||||
def _require_admin():
|
||||
"""
|
||||
确保当前用户既有立账凭证访问权,又是平台管理员。
|
||||
|
||||
核心逻辑:持有 Agent 的普通用户可查检核任务与发送记录;强制重检与通知配置仅 `role=admin`。
|
||||
|
||||
Returns:
|
||||
已认证的管理员用户。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 请求没有有效登录身份。
|
||||
ForbiddenError: 无立账凭证访问权,或已授权但不是管理员。
|
||||
"""
|
||||
user = _require_voucher_check_access()
|
||||
if getattr(user, "role", None) != "admin":
|
||||
raise ForbiddenError("Admin privilege required")
|
||||
raise ForbiddenError(
|
||||
"Admin privilege required for voucher check jobs",
|
||||
code="VOUCHER_CHECK.ADMIN_REQUIRED",
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
@@ -37,9 +103,9 @@ def _require_admin():
|
||||
def workspace_voucher_runs():
|
||||
"""
|
||||
分页查看检核任务列表。
|
||||
核心逻辑:委托 query_service.list_runs,按资料所属期间/业务方/状态筛选。
|
||||
核心逻辑:委托 query_service.list_runs;period 为 YYYY 或 YYYY-MM,可再按业务方/状态筛选。
|
||||
"""
|
||||
_require_user()
|
||||
_require_voucher_check_access()
|
||||
data = query_service.list_runs(
|
||||
period=request.args.get("period"),
|
||||
profile_code=request.args.get("profile_code"),
|
||||
@@ -69,13 +135,23 @@ def workspace_voucher_force_run():
|
||||
return ok(data)
|
||||
|
||||
|
||||
@workspace_voucher_check_bp.route("/accounting-voucher-check/runs/latest", methods=["GET"])
|
||||
def workspace_voucher_latest_run():
|
||||
"""
|
||||
读取最近一次立账凭证检核批次(含排队/执行中)。
|
||||
核心逻辑:委托 query_service.get_latest_run;不跟列表 period/status;无批次时 data 为 null。
|
||||
"""
|
||||
_require_voucher_check_access()
|
||||
return ok(query_service.get_latest_run())
|
||||
|
||||
|
||||
@workspace_voucher_check_bp.route("/accounting-voucher-check/runs/<int:run_id>/items", methods=["GET"])
|
||||
def workspace_voucher_run_items(run_id: int):
|
||||
"""
|
||||
分页查看批次明细。
|
||||
核心逻辑:委托 query_service.list_run_items,可按 result 过滤,并返回 by_file_type。
|
||||
"""
|
||||
_require_user()
|
||||
_require_voucher_check_access()
|
||||
data = query_service.list_run_items(
|
||||
run_id=run_id,
|
||||
result=request.args.get("result"),
|
||||
@@ -88,10 +164,10 @@ def workspace_voucher_run_items(run_id: int):
|
||||
@workspace_voucher_check_bp.route("/accounting-voucher-check/notifications", methods=["GET"])
|
||||
def workspace_voucher_notifications():
|
||||
"""
|
||||
分页查看企微缺件汇总发送记录。
|
||||
核心逻辑:委托 query_service.list_notifications,可按期间和发送状态筛选。
|
||||
分页查看企微缺件通知发送记录。
|
||||
核心逻辑:委托 query_service.list_notifications;period 为 YYYY 或 YYYY-MM,可再按发送状态筛选。
|
||||
"""
|
||||
_require_user()
|
||||
_require_voucher_check_access()
|
||||
data = query_service.list_notifications(
|
||||
period=request.args.get("period"),
|
||||
send_status=request.args.get("send_status"),
|
||||
@@ -99,3 +175,29 @@ def workspace_voucher_notifications():
|
||||
page_size=request.args.get("page_size", default=50, type=int) or 50,
|
||||
)
|
||||
return ok(data)
|
||||
|
||||
|
||||
@workspace_voucher_check_bp.route("/accounting-voucher-check/notify-config", methods=["GET"])
|
||||
def workspace_voucher_notify_config_get():
|
||||
"""
|
||||
读取按文件类型的企微接收人配置。
|
||||
核心逻辑:仅 admin;规则来自销售 Profile,接收人来自独立配置表。
|
||||
"""
|
||||
_require_admin()
|
||||
return ok(notify_config_service.get_notify_config(profile_code=request.args.get("profile_code")))
|
||||
|
||||
|
||||
@workspace_voucher_check_bp.route("/accounting-voucher-check/notify-config", methods=["PUT"])
|
||||
def workspace_voucher_notify_config_put():
|
||||
"""
|
||||
保存按文件类型的企微接收人。
|
||||
核心逻辑:仅 admin;未知规则码丢弃;未绑企微的人可保存但发送时跳过。
|
||||
"""
|
||||
user = _require_admin()
|
||||
payload = request.get_json(silent=True) or {}
|
||||
data = notify_config_service.save_notify_config(
|
||||
profile_code=payload.get("profile_code") or request.args.get("profile_code"),
|
||||
recipients=payload.get("recipients"),
|
||||
updated_by=getattr(user, "id", None),
|
||||
)
|
||||
return ok(data)
|
||||
@@ -1,10 +0,0 @@
|
||||
"""
|
||||
backend/app/api/workspace_schedule.py
|
||||
|
||||
用途:工作台排程 API 兼容 shim(Wave 1 迁包)。
|
||||
依赖:app.api.workspace.schedule。
|
||||
逻辑:旧 import 路径仍可用;新代码请用 app.api.workspace。
|
||||
"""
|
||||
from app.api.workspace.schedule import workspace_schedule_bp
|
||||
|
||||
__all__ = ['workspace_schedule_bp']
|
||||
@@ -1,10 +0,0 @@
|
||||
"""
|
||||
backend/app/api/workspace_shipping_notice.py
|
||||
|
||||
用途:工作台发货通知 API 兼容 shim(Wave 1 迁包)。
|
||||
依赖:app.api.workspace.shipping_notice。
|
||||
逻辑:旧 import 路径继续 re-export `workspace_shipping_notice_bp`;真实实现统一维护在 workspace 子包中,避免双份路由漂移。
|
||||
"""
|
||||
from app.api.workspace.shipping_notice import workspace_shipping_notice_bp
|
||||
|
||||
__all__ = ['workspace_shipping_notice_bp']
|
||||
Reference in new issue
Block a user