Merge branch 'hugo-shipping-notice' into dev
# Conflicts: # backend/app/api/__init__.py # backend/app/jobs/types.py # backend/app/models/__init__.py # backend/app/services/schedule/job_registry.py # docs/features/README.md # docs/funclist.md # docs/tec.md # frontend/src/locales/zh-CN/admin.json
This commit is contained in:
commit
dac31e48bd
691 files changed
+53341
-14863
No files matched your search
@@ -45,6 +45,8 @@ def register_blueprints(app: Flask) -> None:
|
||||
from app.api.files import files_bp
|
||||
from app.api.procurement_contract_tools import procurement_contract_bp
|
||||
from app.api.contract_payment import contract_payment_bp
|
||||
from app.api.in_transit_transfer import in_transit_transfer_bp
|
||||
from app.api.integration_connector import integration_connector_bp
|
||||
|
||||
app.register_blueprint(chat_bp, url_prefix='/api/chat')
|
||||
app.register_blueprint(admin_bp, url_prefix='/api/admin')
|
||||
@@ -75,3 +77,5 @@ def register_blueprints(app: Flask) -> None:
|
||||
app.register_blueprint(files_bp, url_prefix='/api/files')
|
||||
app.register_blueprint(procurement_contract_bp, url_prefix='/api/procurement-contract')
|
||||
app.register_blueprint(contract_payment_bp, url_prefix='/api/contract-payment')
|
||||
app.register_blueprint(in_transit_transfer_bp, url_prefix='/api/in-transit-transfer')
|
||||
app.register_blueprint(integration_connector_bp, url_prefix='/api/integration-connector')
|
||||
@@ -26,10 +26,8 @@ from app.services.shipping_notice.customer_shadow_resolution import (
|
||||
label_shadow_resolution,
|
||||
)
|
||||
from app.services.shipping_notice.customer_auto_resolution import (
|
||||
correct_numbered_task_customer,
|
||||
get_auto_resolution_metrics,
|
||||
)
|
||||
from app.services.shipping_notice.query_service import get_task_by_ref
|
||||
|
||||
XLSX_MIME_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
|
||||
|
||||
@@ -287,32 +285,6 @@ def get_shipping_customer_shadow_report():
|
||||
return jsonify(report)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers/numbered-task-correction', methods=['POST'])
|
||||
@require_admin
|
||||
def correct_shipping_numbered_task_customer():
|
||||
"""管理员更正已编号任务客户;保留原号作废并生成有替代关系的新号。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
task_ref = str(data.get('task_ref') or data.get('task_no') or '').strip().upper()
|
||||
if not task_ref:
|
||||
raise ValidationError(
|
||||
'Task reference is required',
|
||||
code='SHIPPING.CUSTOMER_CORRECTION_TASK_REQUIRED',
|
||||
)
|
||||
try:
|
||||
customer_id = int(data.get('customer_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Customer id is required', code='SHIPPING.CUSTOMER_CONFIRMATION_CUSTOMER_REQUIRED') from exc
|
||||
task = get_task_by_ref(task_ref)
|
||||
if task is None:
|
||||
raise ValidationError('Shipping task not found', code='SHIPPING.CUSTOMER_CORRECTION_TASK_MISSING')
|
||||
return jsonify(correct_numbered_task_customer(
|
||||
task,
|
||||
customer_id=customer_id,
|
||||
reason=str(data.get('reason') or ''),
|
||||
actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customer-shadow-resolutions/<int:resolution_id>/label', methods=['PUT'])
|
||||
@require_admin
|
||||
def label_shipping_customer_shadow_resolution(resolution_id: int):
|
||||
|
||||
@@ -234,25 +234,22 @@ def simulate_shipping_order_schema_derivation(version_id: int):
|
||||
"""
|
||||
对 Schema 版本派生规则做样本模拟(不创建或修改订单)。
|
||||
|
||||
请求体:lines[] 或 sample_ref=`extraction:<id>`;可选 derivation_rules。
|
||||
事务:服务层只写入审计实体,本路由统一 commit。
|
||||
硬切换后该能力已停用;line_no 由系统按单据内顺序生成。
|
||||
"""
|
||||
payload = service.simulate_derivation(
|
||||
version_id,
|
||||
request.get_json(silent=True) or {},
|
||||
actor_id=_actor_id(),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
raise ValidationError(
|
||||
'Schema derivation is disabled; line_no is system-generated',
|
||||
code='SHIPPING.ORDER_SCHEMA_DERIVATION_DISABLED',
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/derivation-simulate-samples', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_order_schema_derivation_simulate_samples():
|
||||
"""列出可供派生规则模拟的历史 Extraction 样本摘要。"""
|
||||
limit = request.args.get('limit', 20, type=int)
|
||||
return _ok(service.list_derivation_simulate_samples(limit=limit or 20))
|
||||
raise ValidationError(
|
||||
'Schema derivation is disabled; line_no is system-generated',
|
||||
code='SHIPPING.ORDER_SCHEMA_DERIVATION_DISABLED',
|
||||
)
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/published-contract', methods=['GET'])
|
||||
@require_admin
|
||||
|
||||
@@ -13,8 +13,24 @@ chat_bp = Blueprint('chat', __name__)
|
||||
|
||||
# 子模块导入时在同一 Blueprint 上注册原有 URL。
|
||||
from . import assets, completions, directory, feedback, previews, sessions, uploads # noqa: E402, F401
|
||||
from .shared import ( # noqa: E402, F401
|
||||
CHAT_USER_ATTACHMENT_LIMIT,
|
||||
CHAT_USER_ATTACHMENT_MAX_SIZE,
|
||||
CHAT_USER_ATTACHMENT_SOURCES,
|
||||
CHAT_USER_ATTACHMENT_TYPES,
|
||||
_merge_user_attachments_from_terminal_event,
|
||||
_normalize_user_attachments,
|
||||
)
|
||||
from app.api.chat_turns import register_chat_turn_routes # noqa: E402
|
||||
|
||||
register_chat_turn_routes(chat_bp)
|
||||
|
||||
__all__ = ['chat_bp']
|
||||
__all__ = [
|
||||
'chat_bp',
|
||||
'CHAT_USER_ATTACHMENT_LIMIT',
|
||||
'CHAT_USER_ATTACHMENT_MAX_SIZE',
|
||||
'CHAT_USER_ATTACHMENT_SOURCES',
|
||||
'CHAT_USER_ATTACHMENT_TYPES',
|
||||
'_merge_user_attachments_from_terminal_event',
|
||||
'_normalize_user_attachments',
|
||||
]
|
||||
@@ -8,6 +8,7 @@ api/chat/sessions.py
|
||||
from __future__ import annotations
|
||||
|
||||
from .shared import * # noqa: F403
|
||||
from .shared import _normalize_user_attachments
|
||||
from . import chat_bp
|
||||
from .core import (
|
||||
_chat_logs_for_session,
|
||||
@@ -194,19 +195,32 @@ def get_chat_messages():
|
||||
messages = []
|
||||
agent_code = str(getattr(g.current_agent, 'agent_code', '') or '').strip() or 'generic'
|
||||
for log in logs:
|
||||
if log.query:
|
||||
messages.append({'role': 'user', 'content': _user_facing_chat_query(log.query, agent_code=agent_code)})
|
||||
raw_payload = log.payload if isinstance(log.payload, dict) else {}
|
||||
user_attachments = _normalize_user_attachments(raw_payload.get('user_attachments'))
|
||||
assistant_payload = {
|
||||
key: value
|
||||
for key, value in raw_payload.items()
|
||||
if key != 'user_attachments'
|
||||
}
|
||||
if log.query or user_attachments:
|
||||
user_msg = {
|
||||
'role': 'user',
|
||||
'content': _user_facing_chat_query(log.query or '', agent_code=agent_code),
|
||||
}
|
||||
if user_attachments:
|
||||
user_msg['attachments'] = user_attachments
|
||||
messages.append(user_msg)
|
||||
if (
|
||||
not log.answer
|
||||
and not log.message_type
|
||||
and not log.payload
|
||||
and not assistant_payload
|
||||
):
|
||||
continue
|
||||
if (
|
||||
log.query
|
||||
and log.answer == log.query
|
||||
and (not log.message_type or log.message_type == 'text')
|
||||
and not log.payload
|
||||
and not assistant_payload
|
||||
):
|
||||
continue
|
||||
assistant_msg = {
|
||||
@@ -220,8 +234,8 @@ def get_chat_messages():
|
||||
assistant_msg['run_id'] = log.run_id
|
||||
if log.message_type:
|
||||
assistant_msg['type'] = log.message_type
|
||||
if log.payload:
|
||||
assistant_msg['payload'] = log.payload
|
||||
if assistant_payload:
|
||||
assistant_msg['payload'] = assistant_payload
|
||||
messages.append(assistant_msg)
|
||||
return jsonify(messages)
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import ntpath
|
||||
import posixpath
|
||||
import tempfile
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import uuid
|
||||
import json
|
||||
@@ -41,6 +42,95 @@ 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_MAX_SIZE = 10 * 1024 * 1024 * 1024
|
||||
CHAT_USER_ATTACHMENT_TYPES = {'image', 'document', 'audio', 'video', 'custom'}
|
||||
CHAT_USER_ATTACHMENT_SOURCES = {'local', 'remote', 'shipping_notice'}
|
||||
|
||||
|
||||
def _normalize_user_attachments(value) -> list[dict]:
|
||||
"""
|
||||
校验并清洗用户消息附件快照,供 ChatLog payload 与历史接口复用。
|
||||
|
||||
核心逻辑:仅接受展示白名单字段;剥离路径、控制字符与未知枚举,不接收 URL、上传 ID 或资产编号。
|
||||
|
||||
Args:
|
||||
value: 前端 user_attachments 原始值;必须为列表,最多处理 20 项。
|
||||
|
||||
Returns:
|
||||
可安全写入 JSON 的附件快照列表;非法项目被忽略。
|
||||
"""
|
||||
if not isinstance(value, list):
|
||||
return []
|
||||
normalized: list[dict] = []
|
||||
for item in value[:CHAT_USER_ATTACHMENT_LIMIT]:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
raw_name = str(item.get('name') or '')
|
||||
basename = re.split(r'[\\/]+', raw_name)[-1]
|
||||
name = re.sub(r'[\x00-\x1f\x7f]', '', basename).strip()[:255]
|
||||
attachment_type = str(item.get('type') or '').strip().lower()
|
||||
source = str(item.get('source') or '').strip().lower()
|
||||
if not name or attachment_type not in CHAT_USER_ATTACHMENT_TYPES or source not in CHAT_USER_ATTACHMENT_SOURCES:
|
||||
continue
|
||||
snapshot = {
|
||||
'name': name,
|
||||
'type': attachment_type,
|
||||
'source': source,
|
||||
}
|
||||
extension = str(item.get('extension') or '').strip().lower()
|
||||
if re.fullmatch(r'[a-z0-9]{1,16}', extension):
|
||||
snapshot['extension'] = extension
|
||||
try:
|
||||
size = int(item.get('size')) if item.get('size') is not None else None
|
||||
except (TypeError, ValueError):
|
||||
size = None
|
||||
if size is not None and 0 <= size <= CHAT_USER_ATTACHMENT_MAX_SIZE:
|
||||
snapshot['size'] = size
|
||||
normalized.append(snapshot)
|
||||
return normalized
|
||||
|
||||
|
||||
def _merge_user_attachments_from_terminal_event(
|
||||
event_data: dict,
|
||||
*,
|
||||
user_id: int,
|
||||
agent_id: int,
|
||||
session_id: str,
|
||||
user_attachments: list[dict],
|
||||
) -> bool:
|
||||
"""
|
||||
在终态 SSE 已给出 ChatLog ID 后,按归属校验合并用户附件快照。
|
||||
|
||||
Args:
|
||||
event_data: 上游终态 SSE 数据,必须包含正整数 chat_log_id。
|
||||
user_id: 当前用户 ID。
|
||||
agent_id: 当前 Agent ID。
|
||||
session_id: 当前 HXOPS 本地会话 ID。
|
||||
user_attachments: 已完成白名单校验的附件快照。
|
||||
|
||||
Returns:
|
||||
找到归属一致的 ChatLog 并成功合并时返回 True,否则返回 False。
|
||||
"""
|
||||
if not user_attachments:
|
||||
return False
|
||||
try:
|
||||
chat_log_id = int(event_data.get('chat_log_id') or 0)
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
if chat_log_id <= 0:
|
||||
return False
|
||||
from app.services.chat.log_service import merge_chat_log_payload
|
||||
return merge_chat_log_payload(
|
||||
chat_log_id=chat_log_id,
|
||||
user_id=int(user_id or 0),
|
||||
agent_id=int(agent_id or 0),
|
||||
session_id=session_id,
|
||||
payload_patch={'user_attachments': user_attachments},
|
||||
)
|
||||
|
||||
|
||||
|
||||
PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip()
|
||||
|
||||
|
||||
@@ -0,0 +1,428 @@
|
||||
"""backend/app/api/in_transit_transfer.py
|
||||
|
||||
用途:在途仓自动调拨用户态 API(仓库管理人员)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、app.core.response、precheck_service、deps。
|
||||
逻辑:薄路由层鉴权与参数校验;成功响应统一 envelope(ok + request_id);
|
||||
Phase 1 提供预检创建(POST /prechecks)与进度恢复(GET /prechecks/{id})。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import wraps
|
||||
from typing import Any
|
||||
|
||||
from flask import Blueprint, g, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.models import Agent
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
from app.services.in_transit_transfer.cancellation import cancel_run
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now
|
||||
from app.services.in_transit_transfer.excel_export import _MIME, build_exceptions_workbook
|
||||
from app.services.in_transit_transfer.execution_service import (
|
||||
execute_precheck,
|
||||
get_run,
|
||||
serialize_run_result,
|
||||
)
|
||||
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.serializers import (
|
||||
serialize_item,
|
||||
serialize_source,
|
||||
serialize_summary,
|
||||
)
|
||||
|
||||
in_transit_transfer_bp = Blueprint("in_transit_transfer", __name__)
|
||||
|
||||
TRANSFER_AGENT_CODE = "in_transit_transfer"
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""校验当前登录用户;未认证抛 UnauthorizedError。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError("Unauthorized")
|
||||
return user
|
||||
|
||||
|
||||
def require_transfer_permission(f):
|
||||
"""装饰器:admin 放行,或持有 in_transit_transfer Agent 权限的用户放行。"""
|
||||
|
||||
@wraps(f)
|
||||
def decorated(*args, **kwargs):
|
||||
user = _require_user()
|
||||
if user.role == "admin":
|
||||
return f(*args, **kwargs)
|
||||
agent = Agent.query.filter_by(agent_code=TRANSFER_AGENT_CODE, is_active=True).first()
|
||||
if agent is None or agent not in user.agents:
|
||||
raise ForbiddenError("Transfer agent permission required")
|
||||
return f(*args, **kwargs)
|
||||
|
||||
return decorated
|
||||
|
||||
|
||||
def _ok(payload: Any, *, status: int = 200):
|
||||
"""统一成功 envelope(带 request_id)。"""
|
||||
return ok(payload, request_id=getattr(g, "request_id", None), status=status)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/prechecks", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def create_precheck_api():
|
||||
"""创建或复用一次调拨预检(只读,不写 ERP)。
|
||||
|
||||
请求体:{"source_codes": [...], "business_date": "YYYY-MM-DD"(可选)}。
|
||||
响应:201 envelope,data 为预检摘要(precheck_id/hash/计数/来源进度)。
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
if not isinstance(body, dict):
|
||||
raise ValidationError("request body must be a JSON object")
|
||||
source_codes = body.get("source_codes")
|
||||
if not isinstance(source_codes, list) or not source_codes:
|
||||
raise ValidationError("source_codes is required")
|
||||
business_date = str(body.get("business_date") or business_date_now())
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
summary = create_precheck(
|
||||
source_codes=[str(item).strip() for item in source_codes],
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
)
|
||||
return _ok(serialize_summary(summary), status=201)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/prechecks/<precheck_id>", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def get_precheck_api(precheck_id: str):
|
||||
"""恢复预检进度与明细(页面刷新/会话恢复)。"""
|
||||
restored = restore_precheck(precheck_id)
|
||||
return _ok({
|
||||
"summary": serialize_summary(restored["summary"]),
|
||||
"items": [serialize_item(item) for item in restored["items"]],
|
||||
"sources": [serialize_source(source) for source in restored["sources"]],
|
||||
})
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/prechecks/<precheck_id>/execute", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def execute_precheck_api(precheck_id: str):
|
||||
"""确认预检选择范围并直接生成执行 Run(决策 4/5:无独立确认页)。
|
||||
|
||||
请求体:{"invoice_nos": [...]}(可选;缺省执行全部可执行项)。
|
||||
响应:201 envelope,data 为 run_no / run 状态 / ERP 单号聚合结果。
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
invoice_nos = body.get("invoice_nos") if isinstance(body, dict) else None
|
||||
if invoice_nos is not None and not isinstance(invoice_nos, list):
|
||||
raise ValidationError("invoice_nos must be a list")
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
outcome = execute_precheck(
|
||||
precheck_id=precheck_id,
|
||||
deps=deps,
|
||||
selected_invoice_nos=invoice_nos,
|
||||
)
|
||||
return _ok({
|
||||
"run_no": outcome.run_no,
|
||||
"status": outcome.status,
|
||||
"result": serialize_run_result(outcome.result),
|
||||
}, status=201)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def get_run_api(run_no: str):
|
||||
"""恢复 Run 最终结果(页面刷新/会话恢复)。"""
|
||||
return _ok(get_run(run_no))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>/cancel", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def cancel_run_api(run_no: str):
|
||||
"""请求停止剩余任务(原因必填,已成功单据保留)。"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
reason = body.get("reason") if isinstance(body, dict) else None
|
||||
return _ok(cancel_run(run_no=run_no, reason=reason))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/items/<int:item_id>/retry", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def retry_item_api(item_id: int):
|
||||
"""人工重试异常项(基于冻结文件仅重新查询 ERP,创建新 Attempt)。
|
||||
|
||||
请求体:{"kind": "erp_recheck"}(可选,默认 erp_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"))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/items/<int:item_id>/manual-close", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def manual_close_item_api(item_id: int):
|
||||
"""人工关闭异常项(原因必填,永久排除)。"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
reason = body.get("reason") if isinstance(body, dict) else None
|
||||
return _ok(manual_close_item(item_id=item_id, reason=reason))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>/exceptions.xlsx", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def exceptions_excel_api(run_no: str):
|
||||
"""下载本次 Run 的七 Sheet 异常 Excel(下载行为记录访问审计)。"""
|
||||
import io
|
||||
|
||||
from app import db
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
|
||||
data = build_exceptions_workbook(run_no)
|
||||
user = _require_user()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_EXCEL_DOWNLOADED",
|
||||
aggregate_type="transfer_run",
|
||||
aggregate_id=run_no,
|
||||
run_no=run_no,
|
||||
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()
|
||||
return send_file(
|
||||
io.BytesIO(data),
|
||||
mimetype=_MIME,
|
||||
as_attachment=True,
|
||||
download_name=f"transfer-exceptions-{run_no}.xlsx",
|
||||
)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>/receipt-files", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def receipt_files_api(run_no: str):
|
||||
"""下载本次收料来源文件(清单 + 原始行追溯,zip);记录访问审计。"""
|
||||
import io
|
||||
import json
|
||||
import zipfile
|
||||
|
||||
from app import db
|
||||
from app.models import TransferInvoiceItem, TransferRun
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
|
||||
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")
|
||||
precheck = run.prechecks[0] if run.prechecks else None
|
||||
file_snapshot = precheck.file_snapshot_json if precheck and isinstance(precheck.file_snapshot_json, dict) else {}
|
||||
|
||||
buffer = io.BytesIO()
|
||||
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
|
||||
for source_code in run.source_codes_json:
|
||||
manifest = {
|
||||
"source_code": source_code,
|
||||
"business_date": run.business_date,
|
||||
**dict(file_snapshot.get(source_code) or {}),
|
||||
}
|
||||
archive.writestr(f"{source_code}-receipt-info.json", json.dumps(manifest, ensure_ascii=False, indent=2))
|
||||
rows = []
|
||||
for item in TransferInvoiceItem.query.filter_by(run_id=run.id).all():
|
||||
for line in (item.raw_lines_json or []):
|
||||
rows.append({
|
||||
"invoice_no": item.invoice_no, "source_code": item.source_code,
|
||||
"sheet": line.get("sheet", ""), "row_no": line.get("row_no", ""),
|
||||
"file_version": line.get("file_version", ""),
|
||||
})
|
||||
archive.writestr("raw-line-trace.json", json.dumps(rows, ensure_ascii=False, indent=2))
|
||||
|
||||
user = _require_user()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_RECEIPT_FILES_DOWNLOADED",
|
||||
aggregate_type="transfer_run",
|
||||
aggregate_id=run_no,
|
||||
run_no=run_no,
|
||||
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()
|
||||
return send_file(
|
||||
io.BytesIO(buffer.getvalue()),
|
||||
mimetype="application/zip",
|
||||
as_attachment=True,
|
||||
download_name=f"receipt-files-{run_no}.zip",
|
||||
)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>/erp-inventory", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def erp_inventory_api(run_no: str):
|
||||
"""下载本次预检冻结的 ERP 库存表(csv);记录访问审计。"""
|
||||
import io
|
||||
|
||||
from app import db
|
||||
from app.models import TransferInvoiceItem, TransferRun
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
|
||||
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"]
|
||||
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 ""),
|
||||
]))
|
||||
data = ("\n".join(lines) + "\n").encode("utf-8")
|
||||
|
||||
user = _require_user()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_ERP_INVENTORY_DOWNLOADED",
|
||||
aggregate_type="transfer_run",
|
||||
aggregate_id=run_no,
|
||||
run_no=run_no,
|
||||
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()
|
||||
return send_file(
|
||||
io.BytesIO(data),
|
||||
mimetype="text/csv",
|
||||
as_attachment=True,
|
||||
download_name=f"erp-inventory-{run_no}.csv",
|
||||
)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/metrics", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def transfer_metrics_api():
|
||||
"""调拨运营指标(成功率/失败类型/待处理老化/通知失败),供运营看板。"""
|
||||
from app.services.in_transit_transfer.metrics import collect_metrics
|
||||
|
||||
return _ok(collect_metrics())
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/sources", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def transfer_sources_api():
|
||||
"""来源实例列表(决策 3:平台 DBS/Crane 仅分组,实例为执行边界)。
|
||||
|
||||
每来源附收料文件状态(ready/fetching/failed/none + has_ready_file),
|
||||
供前端门禁(无 ready 文件时禁止确认预检)与状态标识。只读复用已启用库存来源。
|
||||
"""
|
||||
from app.models import ShippingInventorySource
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||
|
||||
rows = ShippingInventorySource.query.filter_by(enabled=True).order_by(
|
||||
ShippingInventorySource.connector_type, ShippingInventorySource.source_code,
|
||||
).all()
|
||||
return _ok([
|
||||
{
|
||||
"source_code": source.source_code,
|
||||
"display_name": source.display_name,
|
||||
"platform": source.connector_type,
|
||||
"enabled": bool(source.enabled),
|
||||
**resolve_source_file_status(source_code=source.source_code),
|
||||
}
|
||||
for source in rows
|
||||
])
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/sources/<source_code>/retry-rpa", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def retry_source_rpa_api(source_code: str):
|
||||
"""对指定来源重新触发一次收料 RPA 抓取(复用货代收料 trigger 链路)。
|
||||
|
||||
响应:{"source_code", "file_status", "ok"};配置缺失时 fail-closed(ok=False)。
|
||||
"""
|
||||
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now
|
||||
|
||||
source_code = str(source_code).strip()
|
||||
outcome = trigger_receipt_rpa(
|
||||
source_code=source_code,
|
||||
business_date=str(business_date_now()),
|
||||
reason="transfer_retry_receipt",
|
||||
)
|
||||
status = resolve_source_file_status(source_code=source_code)
|
||||
if not outcome.get("ok"):
|
||||
return _ok({
|
||||
"source_code": source_code,
|
||||
"ok": False,
|
||||
"file_status": status["file_status"],
|
||||
"error_code": outcome.get("error_code"),
|
||||
})
|
||||
return _ok({
|
||||
"source_code": source_code,
|
||||
"ok": True,
|
||||
"file_status": "fetching",
|
||||
"callback_id": outcome.get("callback_id"),
|
||||
}, status=202)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/backlog", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def backlog_api():
|
||||
"""待处理异常列表(可恢复/已关闭/结果未知 + 老化等级);查看记录访问审计。"""
|
||||
from app import db
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.backlog_service import list_backlog
|
||||
|
||||
items = list_backlog()
|
||||
user = _require_user()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type='TRANSFER_BACKLOG_VIEWED',
|
||||
aggregate_type='transfer_backlog',
|
||||
aggregate_id='backlog',
|
||||
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',
|
||||
after={'item_count': len(items)},
|
||||
))
|
||||
db.session.commit()
|
||||
return _ok([_serialize_backlog_item(item) for item in items])
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/backlog/summary", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def backlog_summary_api():
|
||||
"""待处理异常汇总(含 3/5/7 天老化分级)。"""
|
||||
from app.services.in_transit_transfer.backlog_service import backlog_summary
|
||||
|
||||
summary = backlog_summary()
|
||||
return _ok({
|
||||
'recoverable': summary.recoverable_count,
|
||||
'closed': summary.closed_count,
|
||||
'unknown': summary.unknown_count,
|
||||
'aging': {
|
||||
'warn_3d': summary.warn_3d,
|
||||
'escalate_5d': summary.escalate_5d,
|
||||
'critical_7d': summary.critical_7d,
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
def _serialize_backlog_item(item) -> dict[str, Any]:
|
||||
"""待处理池项序列化。"""
|
||||
return {
|
||||
'item_id': item.item_id,
|
||||
'source_code': item.source_code,
|
||||
'invoice_no': item.invoice_no,
|
||||
'material_no': item.material_no,
|
||||
'status': item.status,
|
||||
'reason': item.reason,
|
||||
'age_days': item.age_days,
|
||||
'aging_level': item.aging_level,
|
||||
'last_attempt_at': item.last_attempt_at,
|
||||
}
|
||||
@@ -0,0 +1,447 @@
|
||||
"""api/integration_connector.py
|
||||
|
||||
用途:Integration Connector Admin API——配置实体 CRUD、能力清单、能力调用端点与连接测试。
|
||||
依赖:Flask Blueprint、app.core.response、app.core.decorators.require_admin、gateway。
|
||||
逻辑:全部 require_admin;能力调用只接受 {params, context, operation_id, idempotency_key},
|
||||
拒绝 interface_id(禁止覆盖 Binding);配置写操作做字段白名单校验,非法即 400。
|
||||
注意:url_prefix 在 api/__init__.py 注册为 /api/integration-connector(区别于既有
|
||||
/api/integration Dify 文件代理)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from flask import Blueprint, request
|
||||
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.models import (
|
||||
IntegrationBinding,
|
||||
IntegrationClientInstance,
|
||||
IntegrationCredentialReference,
|
||||
IntegrationInterfaceDefinition,
|
||||
)
|
||||
from app.services.integration_connector.capability import ensure_capabilities_loaded, list_capabilities
|
||||
from app.services.integration_connector.gateway import get_capability_gateway
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult
|
||||
|
||||
integration_connector_bp = Blueprint('integration_connector', __name__)
|
||||
|
||||
VALID_CONNECTOR_TYPES = ('rest', 'soap')
|
||||
VALID_STATUSES = ('draft', 'published', 'retired')
|
||||
|
||||
|
||||
def _require(value, field: str) -> None:
|
||||
"""字段必填校验。"""
|
||||
if value is None or (isinstance(value, str) and not value.strip()):
|
||||
raise ValidationError(f'{field} is required', details={'field': field})
|
||||
|
||||
|
||||
def _serialize_client(client) -> dict:
|
||||
return {
|
||||
'id': client.id, 'code': client.code, 'name': client.name,
|
||||
'connector_type': client.connector_type, 'environment': client.environment,
|
||||
'endpoint': client.endpoint, 'timeout_seconds': client.timeout_seconds,
|
||||
'config_json': client.config_json or {}, 'credential_ref_code': client.credential_ref_code,
|
||||
'enabled': client.enabled,
|
||||
}
|
||||
|
||||
|
||||
def _serialize_interface(iface) -> dict:
|
||||
return {
|
||||
'id': iface.id, 'code': iface.code, 'name': iface.name,
|
||||
'client_instance_code': iface.client_instance_code, 'connector_type': iface.connector_type,
|
||||
'http_method': iface.http_method, 'request_path': iface.request_path,
|
||||
'request_spec_json': iface.request_spec_json or {}, 'input_schema_json': iface.input_schema_json or {},
|
||||
'response_mapping_json': iface.response_mapping_json or {}, 'output_schema_json': iface.output_schema_json or {},
|
||||
'version': iface.version, 'status': iface.status, 'enabled': iface.enabled,
|
||||
}
|
||||
|
||||
|
||||
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,
|
||||
'client_instance_code': binding.client_instance_code,
|
||||
'interface_definition_code': binding.interface_definition_code,
|
||||
'mapping_version': binding.mapping_version, 'priority': binding.priority,
|
||||
'environment': binding.environment, 'effective_from': binding.effective_from,
|
||||
'effective_to': binding.effective_to, 'status': binding.status,
|
||||
}
|
||||
|
||||
|
||||
def _serialize_credential(cred) -> dict:
|
||||
return {
|
||||
'id': cred.id, 'code': cred.code, 'secret_ref': cred.secret_ref,
|
||||
'secret_provider': cred.secret_provider, 'credential_type': cred.credential_type,
|
||||
'version': cred.version, 'status': cred.status,
|
||||
'last_verified_at': cred.last_verified_at.isoformat() if cred.last_verified_at else None,
|
||||
}
|
||||
|
||||
|
||||
def _result_to_dict(result: IntegrationCallResult) -> dict:
|
||||
return {
|
||||
'status': result.status,
|
||||
'data': result.data,
|
||||
'error_code': result.error_code,
|
||||
'error_message': result.error_message,
|
||||
'document_no': result.document_no,
|
||||
'trace_id': result.trace_id,
|
||||
}
|
||||
|
||||
|
||||
# ---- 能力清单与调用 ----
|
||||
|
||||
@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,
|
||||
} for spec in list_capabilities()]
|
||||
return ok(data)
|
||||
|
||||
|
||||
@integration_connector_bp.route('/capabilities/<capability>', methods=['POST'])
|
||||
@require_admin
|
||||
def call_capability(capability):
|
||||
body = request.get_json(silent=True) or {}
|
||||
if body.get('interface_id') is not None:
|
||||
raise ValidationError(
|
||||
'interface_id is not allowed for capability calls',
|
||||
code='INTEGRATION.INTERFACE_ID_NOT_ALLOWED',
|
||||
)
|
||||
params = body.get('params') or {}
|
||||
context = body.get('context') or {}
|
||||
operation_id = str(body.get('operation_id') or f'api-{uuid.uuid4().hex}')
|
||||
idempotency_key = body.get('idempotency_key')
|
||||
result = get_capability_gateway().call(
|
||||
capability=capability, context=context, params=params,
|
||||
operation_id=operation_id, idempotency_key=idempotency_key,
|
||||
)
|
||||
return ok(_result_to_dict(result))
|
||||
|
||||
|
||||
# ---- 客户端实例 ----
|
||||
|
||||
@integration_connector_bp.route('/client-instances', methods=['GET'])
|
||||
@require_admin
|
||||
def list_client_instances():
|
||||
rows = IntegrationClientInstance.query.order_by(IntegrationClientInstance.code).all()
|
||||
return ok([_serialize_client(row) for row in rows])
|
||||
|
||||
|
||||
@integration_connector_bp.route('/client-instances', methods=['POST'])
|
||||
@require_admin
|
||||
def create_client_instance():
|
||||
body = request.get_json(silent=True) or {}
|
||||
connector_type = str(body.get('connector_type') or '').strip()
|
||||
_require(body.get('code'), 'code')
|
||||
_require(body.get('name'), 'name')
|
||||
if connector_type not in VALID_CONNECTOR_TYPES:
|
||||
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
|
||||
if IntegrationClientInstance.query.filter_by(code=body['code']).first():
|
||||
raise ValidationError('client instance code already exists', code='RESOURCE.CONFLICT')
|
||||
client = IntegrationClientInstance(
|
||||
code=str(body['code']).strip(), name=str(body['name']).strip(),
|
||||
connector_type=connector_type, environment=str(body.get('environment') or 'prod').strip(),
|
||||
endpoint=(str(body.get('endpoint') or '').strip() or None),
|
||||
timeout_seconds=(int(body['timeout_seconds']) if body.get('timeout_seconds') is not None else None),
|
||||
config_json=body.get('config_json') or {},
|
||||
credential_ref_code=body.get('credential_ref_code'),
|
||||
enabled=bool(body.get('enabled', True)),
|
||||
)
|
||||
from app import db
|
||||
db.session.add(client)
|
||||
db.session.commit()
|
||||
return ok(_serialize_client(client), status=201)
|
||||
|
||||
|
||||
@integration_connector_bp.route('/client-instances/<code>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_client_instance(code):
|
||||
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
||||
if client is None:
|
||||
raise NotFoundError('client instance not found', code='INTEGRATION.CLIENT_INSTANCE_NOT_FOUND')
|
||||
return ok(_serialize_client(client))
|
||||
|
||||
|
||||
@integration_connector_bp.route('/client-instances/<code>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_client_instance(code):
|
||||
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
||||
if client is None:
|
||||
raise NotFoundError('client instance not found')
|
||||
from app import db
|
||||
db.session.delete(client)
|
||||
db.session.commit()
|
||||
return ok({'deleted': True})
|
||||
|
||||
|
||||
@integration_connector_bp.route('/client-instances/<code>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_client_instance(code):
|
||||
"""更新客户端实例(code 不变;可改名称/连接配置/凭据引用/启停)。"""
|
||||
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
||||
if client is None:
|
||||
raise NotFoundError('client instance not found', code='INTEGRATION.CLIENT_INSTANCE_NOT_FOUND')
|
||||
body = request.get_json(silent=True) or {}
|
||||
connector_type = str(body.get('connector_type') or client.connector_type)
|
||||
if connector_type not in VALID_CONNECTOR_TYPES:
|
||||
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
|
||||
if body.get('name') is not None:
|
||||
_require(body.get('name'), 'name')
|
||||
client.name = str(body['name']).strip()
|
||||
if body.get('connector_type') is not None:
|
||||
client.connector_type = connector_type
|
||||
if body.get('environment') is not None:
|
||||
client.environment = str(body['environment']).strip()
|
||||
if 'endpoint' in body:
|
||||
client.endpoint = str(body.get('endpoint') or '').strip() or None
|
||||
if 'timeout_seconds' in body:
|
||||
client.timeout_seconds = int(body['timeout_seconds']) if body.get('timeout_seconds') is not None else None
|
||||
if 'config_json' in body:
|
||||
client.config_json = body.get('config_json') or {}
|
||||
if 'credential_ref_code' in body:
|
||||
client.credential_ref_code = body.get('credential_ref_code')
|
||||
if 'enabled' in body:
|
||||
client.enabled = bool(body.get('enabled', True))
|
||||
from app import db
|
||||
db.session.commit()
|
||||
return ok(_serialize_client(client))
|
||||
|
||||
|
||||
# ---- 接口定义 ----
|
||||
|
||||
@integration_connector_bp.route('/interface-definitions', methods=['GET'])
|
||||
@require_admin
|
||||
def list_interface_definitions():
|
||||
rows = IntegrationInterfaceDefinition.query.order_by(IntegrationInterfaceDefinition.code).all()
|
||||
return ok([_serialize_interface(row) for row in rows])
|
||||
|
||||
|
||||
@integration_connector_bp.route('/interface-definitions', methods=['POST'])
|
||||
@require_admin
|
||||
def create_interface_definition():
|
||||
body = request.get_json(silent=True) or {}
|
||||
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)})
|
||||
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,
|
||||
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 {},
|
||||
input_schema_json=body.get('input_schema_json') or {},
|
||||
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)),
|
||||
)
|
||||
from app import db
|
||||
db.session.add(iface)
|
||||
db.session.commit()
|
||||
return ok(_serialize_interface(iface), status=201)
|
||||
|
||||
|
||||
@integration_connector_bp.route('/interface-definitions/<code>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_interface_definition(code):
|
||||
"""更新接口定义(code 不变;可改模板/入参/回传/出参 Schema、状态、启停)。"""
|
||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first()
|
||||
if iface is None:
|
||||
raise NotFoundError('interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND')
|
||||
body = request.get_json(silent=True) or {}
|
||||
if body.get('name') is not None:
|
||||
_require(body.get('name'), 'name')
|
||||
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
|
||||
if 'http_method' in body:
|
||||
iface.http_method = str(body.get('http_method') or '').strip().upper() or None
|
||||
if 'request_path' in body:
|
||||
iface.request_path = str(body.get('request_path') or '').strip() or None
|
||||
for json_field in ('request_spec_json', 'input_schema_json', 'response_mapping_json', 'output_schema_json'):
|
||||
if json_field in body:
|
||||
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))
|
||||
|
||||
|
||||
# ---- Binding ----
|
||||
|
||||
@integration_connector_bp.route('/bindings', methods=['GET'])
|
||||
@require_admin
|
||||
def list_bindings():
|
||||
rows = IntegrationBinding.query.order_by(IntegrationBinding.capability, IntegrationBinding.priority.desc()).all()
|
||||
return ok([_serialize_binding(row) for row in rows])
|
||||
|
||||
|
||||
@integration_connector_bp.route('/bindings', methods=['POST'])
|
||||
@require_admin
|
||||
def create_binding():
|
||||
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)})
|
||||
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'],
|
||||
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,
|
||||
)
|
||||
from app import db
|
||||
db.session.add(binding)
|
||||
db.session.commit()
|
||||
return ok(_serialize_binding(binding), status=201)
|
||||
|
||||
|
||||
@integration_connector_bp.route('/bindings/<int:binding_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_binding(binding_id):
|
||||
"""更新绑定(capability 不变;可改 context 选择器、客户端/接口、映射版本、优先级、环境、生效区间、状态)。"""
|
||||
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')
|
||||
body = request.get_json(silent=True) or {}
|
||||
if body.get('capability') is not None:
|
||||
_require(body.get('capability'), 'capability')
|
||||
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 body.get('mapping_version') is not None:
|
||||
binding.mapping_version = int(body.get('mapping_version') or 1)
|
||||
if body.get('priority') is not None:
|
||||
binding.priority = int(body.get('priority') or 0)
|
||||
if body.get('environment') is not None:
|
||||
binding.environment = str(body['environment']).strip()
|
||||
if body.get('effective_from') is not None:
|
||||
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))
|
||||
|
||||
|
||||
# ---- 凭据引用 ----
|
||||
|
||||
@integration_connector_bp.route('/credential-references', methods=['GET'])
|
||||
@require_admin
|
||||
def list_credential_references():
|
||||
rows = IntegrationCredentialReference.query.order_by(IntegrationCredentialReference.code).all()
|
||||
return ok([_serialize_credential(row) for row in rows])
|
||||
|
||||
|
||||
@integration_connector_bp.route('/credential-references', methods=['POST'])
|
||||
@require_admin
|
||||
def create_credential_reference():
|
||||
body = request.get_json(silent=True) or {}
|
||||
_require(body.get('code'), 'code')
|
||||
_require(body.get('secret_ref'), 'secret_ref')
|
||||
from app import db
|
||||
cred = IntegrationCredentialReference(
|
||||
code=str(body['code']).strip(),
|
||||
secret_ref=str(body['secret_ref']).strip(),
|
||||
secret_provider=str(body.get('secret_provider') or 'env').strip(),
|
||||
credential_type=str(body.get('credential_type') or 'password').strip(),
|
||||
version=int(body.get('version') or 1),
|
||||
status=str(body.get('status') or 'active'),
|
||||
)
|
||||
db.session.add(cred)
|
||||
db.session.commit()
|
||||
# 永不回显真实凭据值;只回元数据。
|
||||
return ok(_serialize_credential(cred), status=201)
|
||||
|
||||
|
||||
@integration_connector_bp.route('/credential-references/<code>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_credential_reference(code):
|
||||
"""更新凭据引用(code 不变;可改 secret_ref/provider/type/status)。只存引用,永不回显明文。"""
|
||||
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()
|
||||
if body.get('status') is not None:
|
||||
cred.status = str(body['status']).strip()
|
||||
from app import db
|
||||
db.session.commit()
|
||||
return ok(_serialize_credential(cred))
|
||||
|
||||
|
||||
# ---- 连接测试 ----
|
||||
|
||||
@integration_connector_bp.route('/client-instances/<code>/test', methods=['POST'])
|
||||
@require_admin
|
||||
def test_connection(code):
|
||||
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
||||
if client is None:
|
||||
raise NotFoundError('client instance not found')
|
||||
gateway = get_capability_gateway()
|
||||
transport = gateway.transports.get(client.connector_type)
|
||||
if transport is None:
|
||||
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})
|
||||
@@ -256,15 +256,6 @@ def tool_match_inventory():
|
||||
resume_gate_code='inventory_matching',
|
||||
))
|
||||
|
||||
@shipping_notice_bp.route('/tools/submit_decision', methods=['POST'])
|
||||
def tool_submit_decision():
|
||||
"""
|
||||
提交人工决策。
|
||||
【AI 触发时机】:当用户明确表达确认、驳回、重解析、重匹配、确认映射或关闭任务时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.submit_decision(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/confirm_customer', methods=['POST'])
|
||||
def tool_confirm_customer():
|
||||
"""
|
||||
|
||||
@@ -16,7 +16,7 @@ from app.services.agent_category import serialize_agent_list_item, sort_agent_ro
|
||||
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.core.auth.jwt import get_current_user as _auth_current_user
|
||||
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
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
@@ -22,12 +22,12 @@ from app import db
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNotice
|
||||
from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNotice, ShippingOrderTask
|
||||
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
|
||||
from app.services.shipping_notice.constants import (
|
||||
AUTO_CHAIN_FALLBACK,
|
||||
CP_EXPORT_GENERATED,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
POSITION_EXPORT_GENERATED,
|
||||
POSITION_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
)
|
||||
from app.services.shipping_notice.processing_ownership import assert_notice_task_ownership
|
||||
from app.services.shipping_notice.query_service import (
|
||||
@@ -53,7 +53,6 @@ from app.services.shipping_notice.customer_identity_gate import (
|
||||
confirm_task_customer,
|
||||
list_customer_options,
|
||||
)
|
||||
from app.services.shipping_notice.order_customer_matching import confirm_order_customer_match
|
||||
|
||||
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
|
||||
|
||||
@@ -145,6 +144,16 @@ def _assert_fulfillment_task_ownership(task: ShippingNotice, user_id: int) -> No
|
||||
)
|
||||
|
||||
|
||||
def _require_formal_notice(task: Any) -> ShippingNotice:
|
||||
"""正式 Notice 专属接口的实体守卫;OT 在库存门禁前不得进入通知/上传写路径。"""
|
||||
if not isinstance(task, ShippingNotice):
|
||||
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():
|
||||
"""分页列出当前用户可见的发货任务,可按处理状态过滤。"""
|
||||
@@ -214,7 +223,7 @@ def _batch_task_nos(data: dict) -> list[str]:
|
||||
return normalized
|
||||
|
||||
|
||||
def _can_dispose_task(user, task: ShippingNotice) -> bool:
|
||||
def _can_dispose_task(user, task) -> bool:
|
||||
"""管理员可跨用户处置;普通用户仅可处置自己名下或未归属任务。"""
|
||||
return str(getattr(user, 'role', '')).lower() == 'admin' or task.user_id in {None, user.id}
|
||||
|
||||
@@ -372,96 +381,6 @@ def workspace_confirm_shipping_customer(task_no: str):
|
||||
return _ok(serialize_task_detail(updated))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-order-extractions/<int:extraction_id>/customer-matches/<role>/confirm',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_confirm_order_customer_match(extraction_id: int, role: str):
|
||||
"""确认当前用户订单解析中的 Bill-to 客户或 Ship-to 送货站点。"""
|
||||
user = _require_user()
|
||||
extraction = (
|
||||
db.session.query(ShippingOrderExtraction)
|
||||
.join(ShippingOrderIntake, ShippingOrderIntake.id == ShippingOrderExtraction.intake_id)
|
||||
.filter(
|
||||
ShippingOrderExtraction.id == extraction_id,
|
||||
ShippingOrderIntake.user_id == user.id,
|
||||
)
|
||||
.one_or_none()
|
||||
)
|
||||
if extraction is None:
|
||||
raise NotFoundError(
|
||||
'Order extraction not found',
|
||||
code='SHIPPING.ORDER_EXTRACTION_NOT_FOUND',
|
||||
)
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
customer_id = int(data.get('customer_id'))
|
||||
site_id = int(data['site_id']) if data.get('site_id') is not None else None
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'Customer id is required',
|
||||
code='SHIPPING.ORDER_CUSTOMER_REQUIRED',
|
||||
details={'field': 'customer_id'},
|
||||
) from exc
|
||||
result = confirm_order_customer_match(
|
||||
extraction.id,
|
||||
role=role,
|
||||
customer_id=customer_id,
|
||||
site_id=site_id,
|
||||
actor_id=user.id,
|
||||
reason=str(data.get('reason') or ''),
|
||||
commit=False,
|
||||
)
|
||||
# [STEP P1-7] 抽取侧客户确认后,同事务内触发 Case 级协调器(level-triggered reconcile 补偿)。
|
||||
# 通过 Extraction → Candidate → Review Case 反查未终态 Case;若抽取阶段太早尚无 Case,不报错跳过。
|
||||
if role == 'bill_to':
|
||||
from app.models import (
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewStream,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_auto_progress_coordinator import (
|
||||
reconcile_single_case_for_auto_progress,
|
||||
)
|
||||
_TERMINAL = frozenset({
|
||||
'confirmed', 'confirming', 'non_order', 'superseded', 'quality_issue', 'reparse_pending',
|
||||
})
|
||||
candidates = list(
|
||||
ShippingOrderCandidate.query
|
||||
.filter_by(order_extraction_id=int(extraction.id))
|
||||
.all()
|
||||
)
|
||||
candidate_ids = {int(c.id) for c in candidates}
|
||||
case = None
|
||||
if candidate_ids:
|
||||
case = (
|
||||
ShippingOrderReviewCase.query
|
||||
.join(
|
||||
ShippingOrderReviewStream,
|
||||
ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id,
|
||||
)
|
||||
.filter(ShippingOrderReviewCase.candidate_id.in_(candidate_ids))
|
||||
.first()
|
||||
)
|
||||
if case is None and extraction.run_id:
|
||||
case = (
|
||||
ShippingOrderReviewCase.query
|
||||
.join(
|
||||
ShippingOrderReviewStream,
|
||||
ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id,
|
||||
)
|
||||
.filter(ShippingOrderReviewCase.run_id == int(extraction.run_id))
|
||||
.first()
|
||||
)
|
||||
if case is not None and str(case.status or '') not in _TERMINAL and not case.confirmed_task_id:
|
||||
reconcile_single_case_for_auto_progress(
|
||||
case=case,
|
||||
trigger='extraction_customer_confirmed',
|
||||
refresh_validation=True,
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
|
||||
def workspace_create_shipping_task_from_notice():
|
||||
"""接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。"""
|
||||
@@ -491,12 +410,15 @@ def workspace_create_shipping_task_from_notice():
|
||||
task_no=task_id,
|
||||
)
|
||||
if not intake.accepted:
|
||||
return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED})
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'position': POSITION_NOTICE_TEXT_EXTRACTION_FAILED})
|
||||
from app.models import ShippingOrderTask
|
||||
from app.models import ShippingOrderIntake
|
||||
task = ShippingOrderTask.query.filter_by(task_no=task_id).first()
|
||||
if task:
|
||||
task.raw_content = intake.text
|
||||
task.source_file_name = intake.filename or task.source_file_name
|
||||
task.source_file_type = intake.source_file_type or task.source_file_type
|
||||
intake_row = db.session.get(ShippingOrderIntake, task.intake_id) if task.intake_id else None
|
||||
if intake_row is not None:
|
||||
intake_row.extracted_text = intake.text
|
||||
intake_row.parse_warnings_json = list(intake.warnings or [])
|
||||
db.session.commit()
|
||||
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
|
||||
orchestrator_started = start_task_orchestrator(task_id)
|
||||
@@ -540,7 +462,7 @@ def workspace_shipping_task_detail(task_no: str):
|
||||
返回指定任务的详情快照与内嵌 UI State。
|
||||
|
||||
核心逻辑:详情接口直接内嵌 `ui_state`,让页面首屏读取任务详情时即可拿到
|
||||
checkpoint / actions / steps,减少前端二次推导与竞态刷新。
|
||||
position / user_mode / actions / steps,减少前端二次推导与竞态刷新。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
@@ -548,8 +470,8 @@ def workspace_shipping_task_detail(task_no: str):
|
||||
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
# [PERF] view=workbench 供订单生命周期工作台首屏裁剪:剔除复核编辑器重字段,
|
||||
# 响应体与序列化耗时显著下降;缺省/非法值一律回退 full,保持兼容。
|
||||
# [PERF] view=workbench:跳过 DETAIL 重投影,仅身份壳 + ui_state enrich;
|
||||
# 缺省/非法值一律回退 full,保持兼容。
|
||||
view = str(request.args.get('view', 'full') or 'full').strip().lower()
|
||||
if view not in ('full', 'workbench'):
|
||||
view = 'full'
|
||||
@@ -637,6 +559,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)
|
||||
data = request.get_json(silent=True) or {}
|
||||
fields = data.get('fields')
|
||||
if not isinstance(fields, dict) or not fields:
|
||||
@@ -683,6 +606,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)
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
line_index = int(data.get('line_index'))
|
||||
@@ -771,6 +695,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)
|
||||
data = request.get_json(silent=True) or {}
|
||||
line = data.get('line')
|
||||
if not isinstance(line, dict) or not line:
|
||||
@@ -796,6 +721,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)
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
line_index = int(data.get('line_index'))
|
||||
@@ -834,11 +760,15 @@ def workspace_auto_progress_shipping_task(task_no: str):
|
||||
str(task.task_no), trigger='workspace_auto_progress', operator_id=int(user.id),
|
||||
)
|
||||
|
||||
# 兼容旧前端:若仍有 export 路径则附带 download_url。
|
||||
# 导出下载路径只从当前有效 Artifact 读取,Notice 不再保存文件投影。
|
||||
if isinstance(result, dict) and result.get('status') in {'completed', 'running', 'ok'}:
|
||||
# 重新加载任务以读取 export_file_path(若决策器已推进到导出)。
|
||||
refreshed = get_task_for_user(task_no, user.id)
|
||||
export_path = getattr(refreshed, 'export_file_path', None) if refreshed is not None else None
|
||||
artifact = None
|
||||
if refreshed is not None:
|
||||
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
|
||||
|
||||
artifact = latest_export_artifact(refreshed)
|
||||
export_path = getattr(artifact, 'file_path', None)
|
||||
if export_path:
|
||||
result = {
|
||||
**result,
|
||||
@@ -862,6 +792,7 @@ def workspace_mark_manual_uploaded(task_no: str):
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
task = _require_formal_notice(task)
|
||||
_assert_fulfillment_task_ownership(task, user.id)
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
data = request.get_json(silent=True) or {}
|
||||
@@ -1139,6 +1070,7 @@ def workspace_shipping_task_export(task_no: str):
|
||||
"""下载当前用户可访问任务的出货 Excel;写入统一访问审计。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
task = _require_formal_notice(task)
|
||||
err_msg = task_export_error_message(task)
|
||||
if err_msg:
|
||||
raise NotFoundError(err_msg)
|
||||
@@ -1900,19 +1832,17 @@ def workspace_patch_shipping_order_review_header_field(case_no: str, field_id: s
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines/<line_key>/fields/<field_id>', methods=['PATCH'])
|
||||
def workspace_patch_shipping_order_review_line_field(case_no: str, line_key: str, field_id: str):
|
||||
"""修改或恢复一个复核订单行字段;行只接受服务端返回的稳定 line_key。"""
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines/<draft_line_id>/fields/<field_id>', methods=['PATCH'])
|
||||
def workspace_patch_shipping_order_review_line_field(case_no: str, draft_line_id: str, field_id: str):
|
||||
"""修改或恢复一个复核订单行字段;行只接受服务端返回的 draft_line_id。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import patch_line_field
|
||||
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_field_changed')
|
||||
result = patch_line_field(
|
||||
user_id=user.id, case_no=case_no, line_key=line_key, field_id=field_id, value=payload.get('value'),
|
||||
user_id=user.id, case_no=case_no, draft_line_id=draft_line_id, field_id=field_id, value=payload.get('value'),
|
||||
expected_draft_version=payload.get('expected_draft_version'),
|
||||
restore_machine=bool(payload.get('restore_machine')),
|
||||
override_reason_code=payload.get('override_reason_code'),
|
||||
override_reason_text=payload.get('override_reason_text'),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
@@ -1930,30 +1860,30 @@ def workspace_add_shipping_order_review_line(case_no: str):
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines/<line_key>/copy', methods=['POST'])
|
||||
def workspace_copy_shipping_order_review_line(case_no: str, line_key: str):
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines/<draft_line_id>/copy', methods=['POST'])
|
||||
def workspace_copy_shipping_order_review_line(case_no: str, draft_line_id: str):
|
||||
"""复制一条复核行;后端校验会阻断由复制造成的重复 Reservation。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import copy_line
|
||||
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_copied')
|
||||
result = copy_line(
|
||||
user_id=user.id, case_no=case_no, line_key=line_key,
|
||||
user_id=user.id, case_no=case_no, draft_line_id=draft_line_id,
|
||||
expected_draft_version=payload.get('expected_draft_version'),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines/<line_key>', methods=['DELETE'])
|
||||
def workspace_delete_shipping_order_review_line(case_no: str, line_key: str):
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines/<draft_line_id>', methods=['DELETE'])
|
||||
def workspace_delete_shipping_order_review_line(case_no: str, draft_line_id: str):
|
||||
"""删除一条复核行;即使删除最后一行,也只更新草稿和阻断校验。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import delete_line
|
||||
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_deleted')
|
||||
result = delete_line(
|
||||
user_id=user.id, case_no=case_no, line_key=line_key,
|
||||
user_id=user.id, case_no=case_no, draft_line_id=draft_line_id,
|
||||
expected_draft_version=payload.get('expected_draft_version'),
|
||||
)
|
||||
db.session.commit()
|
||||
@@ -1992,7 +1922,7 @@ def workspace_reroute_shipping_order_review_inventory_routing(case_no: str):
|
||||
"""
|
||||
按最新已发布规则重算库存源路由;不重新识别 PDF,并清除历史人工库存源决定。
|
||||
|
||||
核心逻辑:可选 line_key;携带 expected_draft_version 与幂等键。
|
||||
核心逻辑:可选 draft_line_id;携带 expected_draft_version 与幂等键。
|
||||
"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import reroute_inventory_routing
|
||||
@@ -2005,7 +1935,7 @@ def workspace_reroute_shipping_order_review_inventory_routing(case_no: str):
|
||||
case_no=case_no,
|
||||
expected_draft_version=payload.get('expected_draft_version'),
|
||||
idempotency_key=payload.get('idempotency_key'),
|
||||
line_key=payload.get('line_key'),
|
||||
draft_line_id=payload.get('draft_line_id'),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
@@ -2122,7 +2052,7 @@ def workspace_decide_shipping_order_review_line_fulfillment(case_no: str):
|
||||
"""
|
||||
写入行级履约决定。
|
||||
|
||||
Body: line_key, decision_code, reason?, release_field_values?, expected_draft_version?
|
||||
Body: draft_line_id, decision_code, reason?, release_field_values?, expected_draft_version?
|
||||
"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
@@ -2134,7 +2064,7 @@ def workspace_decide_shipping_order_review_line_fulfillment(case_no: str):
|
||||
result = decide_review_line_fulfillment(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
line_key=str(data.get('line_key') or ''),
|
||||
draft_line_id=str(data.get('draft_line_id') or ''),
|
||||
decision_code=str(data.get('decision_code') or ''),
|
||||
reason=str(data.get('reason') or '').strip() or None,
|
||||
release_field_values=(
|
||||
@@ -2156,7 +2086,7 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str):
|
||||
"""
|
||||
为选中完整明细行创建履约波次。
|
||||
|
||||
Body: line_keys[], expected_draft_version, idempotency_key, reason?
|
||||
Body: snapshot_line_ids[], expected_draft_version, idempotency_key, reason?
|
||||
只允许正式 OT 走 create_post_ot_fulfillment_wave +
|
||||
schedule_post_ot_wave_progress。无正式 OT 的历史波次路径已下线,调用方必须
|
||||
先完成正式建单,避免同一业务动作存在两套推进事实。
|
||||
@@ -2171,14 +2101,14 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str):
|
||||
|
||||
case = soft_load_review_case_for_audit(user_id=int(user.id), case_no=str(case_no or ''))
|
||||
formal = resolve_formal_ot(case) if case is not None else {'has_formal_ot': False}
|
||||
line_keys = list(data.get('line_keys') or [])
|
||||
snapshot_line_ids = list(data.get('snapshot_line_ids') or [])
|
||||
idem = data.get('idempotency_key') or request.headers.get('Idempotency-Key')
|
||||
reason = str(data.get('reason') or '').strip() or None
|
||||
|
||||
if formal.get('has_formal_ot'):
|
||||
result = create_post_ot_fulfillment_wave(
|
||||
case_no=str(case_no),
|
||||
line_keys=line_keys,
|
||||
snapshot_line_ids=snapshot_line_ids,
|
||||
decision_source='user',
|
||||
actor_user_id=int(user.id),
|
||||
reason=reason,
|
||||
@@ -2190,7 +2120,7 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str):
|
||||
progress = schedule_post_ot_wave_progress(
|
||||
task_no=str(result.get('task_no') or ''),
|
||||
wave_no=result.get('wave_no'),
|
||||
line_keys=list(result.get('accepted_line_keys') or line_keys),
|
||||
snapshot_line_ids=list(result.get('accepted_snapshot_line_ids') or snapshot_line_ids),
|
||||
review_case_id=int(result.get('review_case_id') or (case.id if case is not None else 0) or 0) or None,
|
||||
idempotency_row_id=result.get('idempotency_row_id'),
|
||||
request_idempotency_key=str(result.get('idempotency_key') or idem or '') or None,
|
||||
@@ -2223,7 +2153,7 @@ def workspace_close_shipping_order_review_fulfillment(case_no: str):
|
||||
"""
|
||||
关闭行级或 Case 剩余开放行。
|
||||
|
||||
Body: reason, line_keys?, expected_draft_version?
|
||||
Body: reason, draft_line_ids?, expected_draft_version?
|
||||
"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
@@ -2236,7 +2166,7 @@ def workspace_close_shipping_order_review_fulfillment(case_no: str):
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
reason=str(data.get('reason') or ''),
|
||||
line_keys=list(data.get('line_keys') or []) or None,
|
||||
draft_line_ids=list(data.get('draft_line_ids') or []) or None,
|
||||
expected_draft_version=data.get('expected_draft_version'),
|
||||
actor_is_admin=is_admin,
|
||||
)
|
||||
@@ -2349,9 +2279,7 @@ def workspace_confirm_shipping_order_review_case(case_no: str):
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_confirmation_service import (
|
||||
confirm_review_case,
|
||||
finalize_sync_auto_progress_after_commit,
|
||||
resolve_confirm_outcome,
|
||||
schedule_auto_progress_after_review_confirm,
|
||||
)
|
||||
|
||||
payload = _review_draft_payload(
|
||||
@@ -2366,14 +2294,22 @@ def workspace_confirm_shipping_order_review_case(case_no: str):
|
||||
warning_acknowledgements=payload.get('warning_acknowledgements'),
|
||||
)
|
||||
# [STEP] 与建单同事务写入 shipping_notice_run,避免「已建单、推进失败不可恢复」。
|
||||
# 复核确认只产生 OT;正式 ShippingNotice 尚未生成,不能把 OT 编号投递到
|
||||
# 旧的 notice-run Job。库存源候选的裁决/冻结确认后由正式 inventory_source_routing
|
||||
# Gate 负责;通过 schedule_auto_progress_after_review_confirm 入队自动推进,
|
||||
# 使 OT 在不冻结候选的情况下仍能走到库存链路。
|
||||
from app.services.shipping_notice.order_review_confirmation_service import (
|
||||
finalize_sync_auto_progress_after_commit,
|
||||
schedule_auto_progress_after_review_confirm,
|
||||
)
|
||||
progress = schedule_auto_progress_after_review_confirm(
|
||||
task_no=result.get('task_no'),
|
||||
task_no=str(result.get('task_no')),
|
||||
idempotent_replay=bool(result.get('idempotent_replay')),
|
||||
created_by_id=int(user.id),
|
||||
commit=False,
|
||||
)
|
||||
# [STEP] BE-4:正式 OT 创建后补触发自动履约(flag 关时 enqueue 内部 no-op)
|
||||
if result.get('task_no') and not result.get('idempotent_replay'):
|
||||
if result.get('shipping_notice_no') and not result.get('idempotent_replay'):
|
||||
from app.services.shipping_notice.line_auto_fulfill_coordinator import (
|
||||
enqueue_post_ot_auto_fulfill_job,
|
||||
)
|
||||
@@ -2383,8 +2319,8 @@ def workspace_confirm_shipping_order_review_case(case_no: str):
|
||||
commit=False,
|
||||
)
|
||||
db.session.commit()
|
||||
# [STEP] sync 执行失败不得变成 HTTP 500,须返回「确认成功 + 推进态」字段。
|
||||
progress = finalize_sync_auto_progress_after_commit(progress)
|
||||
# [STEP] sync 执行失败不得变成 HTTP 500,须返回「确认成功 + 推进态」字段。
|
||||
result = dict(result)
|
||||
result.pop('trigger_auto_progress', None)
|
||||
result['confirm_ok'] = True
|
||||
@@ -2395,12 +2331,36 @@ def workspace_confirm_shipping_order_review_case(case_no: str):
|
||||
'message': '无需调度自动推进,或任务已离开待推进态',
|
||||
}
|
||||
else:
|
||||
# [STEP] 仅下发 position / user_mode;禁止 checkpoint 别名。
|
||||
position = progress.get('position')
|
||||
user_mode = progress.get('user_mode')
|
||||
if not position or not user_mode:
|
||||
try:
|
||||
from app.models import ShippingOrderTask
|
||||
from app.services.shipping_notice.progress_workflow import (
|
||||
_entry_position,
|
||||
_entry_user_mode,
|
||||
)
|
||||
|
||||
ot = (
|
||||
db.session.query(ShippingOrderTask)
|
||||
.filter(
|
||||
ShippingOrderTask.task_no == str(result.get('task_no') or '').strip().upper()
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if ot is not None:
|
||||
position = position or _entry_position(ot)
|
||||
user_mode = user_mode or _entry_user_mode(ot)
|
||||
except Exception:
|
||||
pass
|
||||
result['auto_progress_started'] = bool(progress.get('auto_progress_started'))
|
||||
result['auto_progress'] = {
|
||||
'status': progress.get('status'),
|
||||
'message': progress.get('message'),
|
||||
'enqueue_result': progress.get('enqueue_result'),
|
||||
'checkpoint': progress.get('checkpoint'),
|
||||
'position': position,
|
||||
'user_mode': user_mode,
|
||||
}
|
||||
result['confirm_outcome'] = resolve_confirm_outcome(
|
||||
{
|
||||
@@ -2632,7 +2592,7 @@ def workspace_request_shipping_order_review_llm_suggestion(case_no: str):
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
field_id=str(payload.get('field_id') or ''),
|
||||
line_key=payload.get('line_key'),
|
||||
draft_line_id=payload.get('draft_line_id'),
|
||||
evidence_level=payload.get('evidence_level'),
|
||||
issue_code=payload.get('issue_code'),
|
||||
allow_full_pdf=bool(payload.get('allow_full_pdf')),
|
||||
|
||||
Reference in new issue
Block a user