Merge branch 'dev' into departmental-structure
This commit is contained in:
commit
ec47e012a7
310 files changed
+31263
-6681
No files matched your search
@@ -49,6 +49,7 @@ def register_blueprints(app: Flask) -> None:
|
||||
)
|
||||
from app.api.files import files_bp
|
||||
from app.api.contract_payment import contract_payment_bp
|
||||
from app.api.equipment_acceptance import equipment_acceptance_bp
|
||||
from app.api.order_delivery_reply import order_delivery_reply_bp
|
||||
from app.api.in_transit_transfer import in_transit_transfer_bp
|
||||
from app.api.integration_connector import integration_connector_bp
|
||||
@@ -81,6 +82,7 @@ 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(equipment_acceptance_bp, url_prefix='/api/equipment-acceptance')
|
||||
app.register_blueprint(order_delivery_reply_bp, url_prefix='/api/order-delivery-reply')
|
||||
app.register_blueprint(in_transit_transfer_bp, url_prefix='/api/in-transit-transfer')
|
||||
app.register_blueprint(integration_connector_bp, url_prefix='/api/integration-connector')
|
||||
@@ -0,0 +1,205 @@
|
||||
"""
|
||||
backend/app/api/equipment_acceptance/__init__.py
|
||||
|
||||
用途:设备验收预警的 Chat 作业面接口。
|
||||
依赖:JWT 当前用户、Agent 授权、sync_service、统一成功响应。
|
||||
逻辑:持有 equipment_acceptance Agent 的用户可看停留列表、发送记录、已归档 Excel 和配置;同步、扫描、发送和保存配置仅平台管理员。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
from flask import Blueprint, g, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, UnauthorizedError
|
||||
from app.core.response import ok
|
||||
from app.models import Agent
|
||||
from app.services.equipment_acceptance.config_service import (
|
||||
get_acceptance_config,
|
||||
save_acceptance_config,
|
||||
)
|
||||
from app.services.equipment_acceptance.alert_service import generate_alerts, send_pending_alerts
|
||||
from app.services.equipment_acceptance.send_record_service import get_send_file, list_send_files, list_send_records
|
||||
from app.services.equipment_acceptance.sync_service import (
|
||||
get_acceptance_order,
|
||||
list_acceptance_orders,
|
||||
sync_acceptance_snapshots,
|
||||
)
|
||||
|
||||
equipment_acceptance_bp = Blueprint("equipment_acceptance", __name__)
|
||||
EQUIPMENT_ACCEPTANCE_AGENT_CODE = "equipment_acceptance"
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""
|
||||
读取当前登录用户。
|
||||
|
||||
Returns:
|
||||
已认证用户。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 没有有效登录身份。
|
||||
"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _user_has_equipment_acceptance_agent(user) -> bool:
|
||||
"""
|
||||
判断用户是否持有启用中的设备验收预警 Agent。
|
||||
|
||||
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions。
|
||||
"""
|
||||
agent = Agent.query.filter_by(agent_code=EQUIPMENT_ACCEPTANCE_AGENT_CODE, is_active=True).first()
|
||||
return bool(agent is not None and agent in user.agents)
|
||||
|
||||
|
||||
def _require_equipment_acceptance_access():
|
||||
"""
|
||||
确保当前用户可以打开设备验收预警作业面。
|
||||
|
||||
核心逻辑:平台管理员放行;普通用户必须被授予启用中的 equipment_acceptance Agent。
|
||||
|
||||
Returns:
|
||||
已认证且有权查看的用户。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 没有有效登录身份。
|
||||
ForbiddenError: 已登录但没有该 Agent。
|
||||
"""
|
||||
user = _require_user()
|
||||
if user.is_platform_admin() or _user_has_equipment_acceptance_agent(user):
|
||||
return user
|
||||
raise ForbiddenError(
|
||||
"Equipment acceptance agent permission required",
|
||||
code="EQUIPMENT_ACCEPTANCE.FORBIDDEN",
|
||||
)
|
||||
|
||||
|
||||
def _require_equipment_acceptance_admin():
|
||||
"""
|
||||
确保当前用户可以触发 E10 同步。
|
||||
|
||||
核心逻辑:先确认能看作业面,再要求平台管理员。同步会读取外部库并改写本地快照。
|
||||
|
||||
Returns:
|
||||
已认证的管理员。
|
||||
|
||||
Raises:
|
||||
ForbiddenError: 不是平台管理员。
|
||||
"""
|
||||
user = _require_equipment_acceptance_access()
|
||||
if not user.is_platform_admin():
|
||||
raise ForbiddenError(
|
||||
"Admin privilege required for equipment acceptance sync",
|
||||
code="EQUIPMENT_ACCEPTANCE.ADMIN_REQUIRED",
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/sync", methods=["POST"])
|
||||
def sync_equipment_acceptance():
|
||||
"""从 E10 拉取验收单并写入本地快照。仅平台管理员。"""
|
||||
_require_equipment_acceptance_admin()
|
||||
return ok(sync_acceptance_snapshots(), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/orders", methods=["GET"])
|
||||
def list_equipment_acceptance_orders():
|
||||
"""分页查看已同步的验收单。focus 按原型分组过滤,summary 始终统计全部单据。"""
|
||||
_require_equipment_acceptance_access()
|
||||
page = _int_arg("page", 1)
|
||||
page_size = _int_arg("page_size", 20)
|
||||
payload = list_acceptance_orders(
|
||||
monitor_status=request.args.get("monitor_status"),
|
||||
focus=request.args.get("focus"),
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/config", methods=["GET"])
|
||||
def get_equipment_acceptance_config():
|
||||
"""读取四档天数和三个固定岗位。候选人名单只给平台管理员。"""
|
||||
user = _require_equipment_acceptance_access()
|
||||
payload = get_acceptance_config(include_candidates=user.is_platform_admin())
|
||||
return ok(payload, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/config", methods=["PUT"])
|
||||
def save_equipment_acceptance_config():
|
||||
"""保存四档天数和三个固定岗位。仅平台管理员。发送时刻不在本接口。"""
|
||||
user = _require_equipment_acceptance_access()
|
||||
if not user.is_platform_admin():
|
||||
raise ForbiddenError(
|
||||
"Admin privilege required for equipment acceptance settings",
|
||||
code="EQUIPMENT_ACCEPTANCE.SETTINGS_ADMIN_REQUIRED",
|
||||
)
|
||||
payload = request.get_json(silent=True) or {}
|
||||
saved = save_acceptance_config(payload, updated_by=user.id)
|
||||
return ok(saved, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/alerts/scan", methods=["POST"])
|
||||
def scan_equipment_acceptance_alerts():
|
||||
"""管理员立即同步 E10 并生成待发送记录。不发企业微信。"""
|
||||
_require_equipment_acceptance_admin()
|
||||
return ok(generate_alerts(), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/alerts/send", methods=["POST"])
|
||||
def send_equipment_acceptance_alerts():
|
||||
"""管理员立即把待发送记录按收件人发到企业微信。"""
|
||||
_require_equipment_acceptance_admin()
|
||||
return ok(send_pending_alerts(), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/send-files", methods=["GET"])
|
||||
def list_equipment_acceptance_send_files():
|
||||
"""列出最近按收件人归档的 Excel。不含文件字节。"""
|
||||
_require_equipment_acceptance_access()
|
||||
return ok({"items": list_send_files()}, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/send-files/<int:file_id>/excel", methods=["GET"])
|
||||
def download_equipment_acceptance_send_file(file_id: int):
|
||||
"""下载一份当时发给收件人的设备验收预警 Excel。"""
|
||||
_require_equipment_acceptance_access()
|
||||
row = get_send_file(file_id)
|
||||
return send_file(
|
||||
BytesIO(row.excel_file_data),
|
||||
as_attachment=True,
|
||||
download_name=row.excel_file_name or f"equipment-acceptance-alert-{file_id}.xlsx",
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/sends", methods=["GET"])
|
||||
def list_equipment_acceptance_sends():
|
||||
"""分页查看发送记录。扫描写入后这里才有行。"""
|
||||
_require_equipment_acceptance_access()
|
||||
payload = list_send_records(page=_int_arg("page", 1), page_size=_int_arg("page_size", 20))
|
||||
return ok(payload, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/orders/<int:order_id>", methods=["GET"])
|
||||
def get_equipment_acceptance_order(order_id: int):
|
||||
"""查看一张验收单的节点和操作人原值。"""
|
||||
_require_equipment_acceptance_access()
|
||||
return ok(get_acceptance_order(order_id), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
def _int_arg(name: str, default: int) -> int:
|
||||
"""读取正整数查询参数,非法时用默认值。"""
|
||||
raw = request.args.get(name)
|
||||
if raw is None or str(raw).strip() == "":
|
||||
return default
|
||||
try:
|
||||
return int(raw)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
@@ -793,6 +793,32 @@ def retry_source_rpa_api(source_code: str):
|
||||
}, status=202)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/sources/retry-rpa-batch", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def retry_sources_rpa_batch_api():
|
||||
"""批量重试多来源收料 RPA:全部有效来源合并写**一个** batch trigger(一文件 N units)。
|
||||
|
||||
【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个来源编码时调用;
|
||||
逐来源调用单来源端点会产生 N 个 trigger 文件,Worker 每文件开/关一次浏览器;
|
||||
合并单文件后 Worker 单次登录串行导出全部来源(与收料排程路径同效率)。
|
||||
|
||||
请求体:{"source_codes": ["DSV360_AWSBI", ...]}。逐来源解析失败分层与
|
||||
fail-closed 语义同单来源端点;单源配置缺失跳过并记录,不阻断其余来源。
|
||||
"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
source_codes = [str(code).strip() for code in (payload.get("source_codes") or []) if str(code).strip()]
|
||||
if not source_codes:
|
||||
raise ValidationError("source_codes is required")
|
||||
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa_batch
|
||||
|
||||
outcome = trigger_receipt_rpa_batch(
|
||||
source_codes=source_codes,
|
||||
business_date=str(business_date_now()),
|
||||
reason="transfer_retry_receipt",
|
||||
)
|
||||
return _ok(outcome)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/backlog", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def backlog_api():
|
||||
|
||||
@@ -16,7 +16,11 @@ backend/app/api/order_delivery_reply.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, g, request
|
||||
from datetime import datetime
|
||||
from io import BytesIO
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
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
|
||||
@@ -28,6 +32,8 @@ from app.services.order_delivery_reply.sync_service import OrderDeliverySyncServ
|
||||
|
||||
order_delivery_reply_bp = Blueprint("order_delivery_reply", __name__)
|
||||
|
||||
XLSX_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
|
||||
|
||||
def _utc_to_shanghai(value) -> str | None:
|
||||
"""
|
||||
@@ -121,6 +127,28 @@ def list_lines():
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@order_delivery_reply_bp.get("/lines/export")
|
||||
def export_lines():
|
||||
"""
|
||||
导出当前筛选下的全部订单行 Excel(不分页)。
|
||||
|
||||
用途与触发时机:工作台工具栏「导出 Excel」按钮;查询参数与列表一致
|
||||
(keyword/order_date/status),导出全部命中行(服务层 EXPORT_MAX_ROWS 兜底)。
|
||||
|
||||
参数与输出约束:要求 order_delivery_reply.access 及以上;返回 xlsx 文件流(attachment,
|
||||
文件名带北京时间日期)。
|
||||
"""
|
||||
_require_access()
|
||||
content = query_service.export_lines(request.args.to_dict(flat=True))
|
||||
filename = f"订单交期回复_{datetime.now(ZoneInfo('Asia/Shanghai')):%Y%m%d}.xlsx"
|
||||
return send_file(
|
||||
BytesIO(content),
|
||||
as_attachment=True,
|
||||
download_name=filename,
|
||||
mimetype=XLSX_MIME_TYPE,
|
||||
)
|
||||
|
||||
|
||||
@order_delivery_reply_bp.get("/lines/<order_no>/<int:line_no>")
|
||||
def get_line(order_no: str, line_no: int):
|
||||
"""
|
||||
|
||||
@@ -334,6 +334,26 @@ def rpa_receipt_batch_ready():
|
||||
return jsonify({'success': True, 'data': ingest_receipt_callback(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/receipt-unit-progress', methods=['POST'])
|
||||
def rpa_receipt_unit_progress():
|
||||
"""收料单元领取/导出中:awaiting_rpa → processing,供管理端实时看到进行中。
|
||||
|
||||
本路由同时是收料超时对账的活动锚数据源(mark 落单元 started_at);
|
||||
曾因重构分叉合并丢失(2026-10-08),Worker 上报全程 404,勿再从旧路径文件删除。
|
||||
"""
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import mark_receipt_unit_processing
|
||||
|
||||
return jsonify({'success': True, 'data': mark_receipt_unit_processing(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/receipt-batch-progress', methods=['POST'])
|
||||
def rpa_receipt_batch_progress():
|
||||
"""收料 RPA 每完成一笔导出的累计进度回写(非终态,对齐库存 inventory-batch-progress)。"""
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import report_receipt_batch_progress
|
||||
|
||||
return jsonify({'success': True, 'data': report_receipt_batch_progress(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-batch-claimed', methods=['POST'])
|
||||
def rpa_inventory_batch_claimed():
|
||||
"""v2 Worker 领取回调:仅记录 Attempt 执行阶段。"""
|
||||
|
||||
@@ -20,7 +20,7 @@ from flask import Blueprint, Response, current_app, g, request, send_file
|
||||
|
||||
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.errors import AppError, ConflictError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNotice, ShippingOrderTask
|
||||
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
|
||||
@@ -186,6 +186,7 @@ def workspace_shipping_tasks():
|
||||
lifecycle_status=lifecycle_status,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
is_admin=bool(user.is_platform_admin()),
|
||||
))
|
||||
|
||||
|
||||
@@ -394,14 +395,38 @@ def workspace_batch_restore_shipping_tasks():
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-exports/archive', methods=['POST'])
|
||||
def workspace_shipping_export_archive():
|
||||
"""按显式任务号下载当前用户可访问的 ready 发货 Excel ZIP。"""
|
||||
"""按显式任务号下载当前用户可下载(创建者或管理员)的 ready 发货 Excel ZIP。"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
task_nos = data.get('task_nos')
|
||||
if task_nos is not None and not isinstance(task_nos, list):
|
||||
raise ValidationError('task_nos must be a list', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID')
|
||||
from app.services.shipping_notice.export_archive import build_export_archive
|
||||
stream, filename, _manifest = build_export_archive(user_id=user.id, task_nos=task_nos or [])
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
|
||||
stream, filename, manifest = build_export_archive(
|
||||
user_id=user.id,
|
||||
task_nos=task_nos or [],
|
||||
is_admin=bool(user.is_platform_admin()),
|
||||
)
|
||||
# 与 business_no 批量导出同一审计口径:按票落 record_access_audit(自行提交)。
|
||||
for entry in manifest.get('entries') or []:
|
||||
aggregate_no = str(entry.get('business_no') or '').strip()
|
||||
task_no = str(entry.get('task_no') or '').strip()
|
||||
if not aggregate_no and not task_no:
|
||||
continue
|
||||
record_access_audit(
|
||||
action='download_task_excel',
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=task_no or aggregate_no,
|
||||
actor_id=user.id,
|
||||
task_no=task_no or None,
|
||||
reason_code='excel_downloaded',
|
||||
metadata={
|
||||
'export': 'batch_zip',
|
||||
'batch_status': str(entry.get('status') or ''),
|
||||
},
|
||||
)
|
||||
response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip')
|
||||
response.call_on_close(stream.close)
|
||||
return response
|
||||
@@ -455,7 +480,11 @@ def workspace_confirm_shipping_customer(task_no: str):
|
||||
details={'field': 'customer_id'},
|
||||
) from exc
|
||||
updated = confirm_task_customer(task, customer_id=customer_id, actor_id=user.id)
|
||||
return _ok(serialize_task_detail(updated))
|
||||
return _ok(serialize_task_detail(
|
||||
updated,
|
||||
viewer_user_id=user.id,
|
||||
is_admin=bool(user.is_platform_admin()),
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
|
||||
@@ -499,7 +528,7 @@ def workspace_create_shipping_task_from_notice():
|
||||
db.session.commit()
|
||||
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
|
||||
orchestrator_started = start_task_orchestrator(task_id)
|
||||
return _ok({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
|
||||
return _ok({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task, viewer_user_id=user.id) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/replace-notice', methods=['POST'])
|
||||
def workspace_replace_shipping_task_notice(task_no: str):
|
||||
@@ -657,7 +686,12 @@ def workspace_shipping_task_ui_state(task_no: str):
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok(build_task_ui_state(task, include_stage_context=True))
|
||||
return _ok(build_task_ui_state(
|
||||
task,
|
||||
include_stage_context=True,
|
||||
viewer_user_id=user.id,
|
||||
viewer_is_admin=bool(user.is_platform_admin()),
|
||||
))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET'])
|
||||
def workspace_shipping_task_chat_actions(task_no: str):
|
||||
@@ -1032,6 +1066,38 @@ def _load_business_notice_for_user(*, business_no: str, user_id: int) -> Shippin
|
||||
return task
|
||||
|
||||
|
||||
def _load_business_notice_readable_for_user(
|
||||
*,
|
||||
business_no: str,
|
||||
user_id: int,
|
||||
is_admin: bool,
|
||||
) -> ShippingNotice:
|
||||
"""
|
||||
按精确发货通知单号加载当前用户可下载的 Notice(创建者或管理员)。
|
||||
|
||||
核心逻辑:下载是只读动作,授权走 can_download_task_export 统一谓词口径
|
||||
(可下载=可见),不经过写路径的履约归属断言;管理员可下载其可见的正式
|
||||
Notice,且每次下载均由端点写入 record_access_audit。
|
||||
|
||||
Args:
|
||||
business_no: 对外发货通知单号。
|
||||
user_id: 当前服务端会话用户主键。
|
||||
is_admin: 是否平台管理员。
|
||||
|
||||
Returns:
|
||||
可下载的 ShippingNotice。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 编号不存在、非正式 Notice 或用户不可见。
|
||||
"""
|
||||
normalized = str(business_no or '').strip().upper()
|
||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||||
task = get_task_visible_to_user(normalized, user_id, is_admin=is_admin)
|
||||
if not isinstance(task, ShippingNotice) or str(task.business_no or '').strip().upper() != normalized:
|
||||
raise NotFoundError('Shipping notice not found')
|
||||
return task
|
||||
|
||||
|
||||
def _start_notice_rpa_upload(*, business_no: str, user_id: int, artifact_id: int | None = None) -> dict[str, Any]:
|
||||
"""按 business_no 发起单张通知的货代 RPA 上传或重试。"""
|
||||
task = _load_business_notice_for_user(business_no=business_no, user_id=user_id)
|
||||
@@ -1138,9 +1204,13 @@ def workspace_batch_start_shipping_notice_rpa_upload():
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/export', methods=['GET'])
|
||||
def workspace_shipping_notice_export(business_no: str):
|
||||
"""按发货通知单号下载该通知唯一的正式 Excel,并保留下载审计。"""
|
||||
"""按发货通知单号下载该通知唯一的正式 Excel(创建者或管理员),并保留下载审计。"""
|
||||
user = _require_user()
|
||||
task = _load_business_notice_for_user(business_no=business_no, user_id=int(user.id))
|
||||
task = _load_business_notice_readable_for_user(
|
||||
business_no=business_no,
|
||||
user_id=int(user.id),
|
||||
is_admin=bool(user.is_platform_admin()),
|
||||
)
|
||||
err_msg = task_export_error_message(task)
|
||||
if err_msg:
|
||||
raise NotFoundError(err_msg)
|
||||
@@ -1162,7 +1232,7 @@ def workspace_shipping_notice_export(business_no: str):
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notices/batch/export', methods=['POST'])
|
||||
def workspace_shipping_notice_export_archive():
|
||||
"""按多个 business_no 下载各自唯一 Excel 的 ZIP;任一越权或缺文件均整体拒绝。"""
|
||||
"""按多个 business_no 下载各自唯一 Excel 的 ZIP(创建者或管理员);任一越权或缺文件均整体拒绝。"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
raw_values = data.get('business_nos')
|
||||
@@ -1174,8 +1244,32 @@ def workspace_shipping_notice_export_archive():
|
||||
if not business_nos or len(business_nos) > 100:
|
||||
raise ValidationError('business_nos must contain 1 to 100 business numbers')
|
||||
from app.services.shipping_notice.export_archive import build_export_archive
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
|
||||
stream, filename, _manifest = build_export_archive(user_id=int(user.id), business_nos=business_nos)
|
||||
stream, filename, manifest = build_export_archive(
|
||||
user_id=int(user.id),
|
||||
business_nos=business_nos,
|
||||
is_admin=bool(user.is_platform_admin()),
|
||||
)
|
||||
# 批量导出与单票下载同一审计口径:按票落 record_access_audit(自行提交),
|
||||
# manifest.business_no 是 aggregate 事实源;missing/checksum 票据也留痕。
|
||||
for entry in manifest.get('entries') or []:
|
||||
aggregate_no = str(entry.get('business_no') or '').strip()
|
||||
task_no = str(entry.get('task_no') or '').strip()
|
||||
if not aggregate_no and not task_no:
|
||||
continue
|
||||
record_access_audit(
|
||||
action='download_notice_excel',
|
||||
aggregate_type='shipping_notice',
|
||||
aggregate_id=aggregate_no or task_no,
|
||||
actor_id=user.id,
|
||||
task_no=task_no or None,
|
||||
reason_code='excel_downloaded',
|
||||
metadata={
|
||||
'export': 'batch_zip',
|
||||
'batch_status': str(entry.get('status') or ''),
|
||||
},
|
||||
)
|
||||
response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip')
|
||||
response.call_on_close(stream.close)
|
||||
return response
|
||||
@@ -1183,9 +1277,10 @@ def workspace_shipping_notice_export_archive():
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET'])
|
||||
def workspace_shipping_task_export(task_no: str):
|
||||
"""下载当前用户可访问任务的出货 Excel;写入统一访问审计。"""
|
||||
"""下载当前用户可下载任务的出货 Excel(创建者或管理员);写入统一访问审计。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
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=bool(user.is_platform_admin()))
|
||||
task = _require_formal_notice(task)
|
||||
err_msg = task_export_error_message(task)
|
||||
if err_msg:
|
||||
@@ -2103,6 +2198,88 @@ def workspace_confirm_shipping_order_review_customer(case_no: str):
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/customer/rebind',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_rebind_shipping_order_review_customer(case_no: str):
|
||||
"""
|
||||
确认客户改绑:直接修改已确认的客户识别结果并刷新订单快照客户。
|
||||
|
||||
Body: customer_id, expected_order_data_version, reason?
|
||||
仅当订单编辑窗 header 可编辑(任一通知无 Export Artifact 且无活动 Gate Attempt,
|
||||
即发货通知/Excel 未产生)时允许;版本乐观锁与状态守卫在服务层 fail-closed。
|
||||
"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
customer_id = int(data.get('customer_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'Customer id is required',
|
||||
code='SHIPPING.CUSTOMER_REBIND_CUSTOMER_REQUIRED',
|
||||
details={'field': 'customer_id'},
|
||||
) from exc
|
||||
try:
|
||||
expected_order_data_version = int(data.get('expected_order_data_version'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'Expected order data version is required',
|
||||
code='SHIPPING.CUSTOMER_REBIND_VERSION_REQUIRED',
|
||||
details={'field': 'expected_order_data_version'},
|
||||
) from exc
|
||||
|
||||
from app.services.shipping_notice.customer_resolution_service import rebind_confirmed_customer
|
||||
from app.services.shipping_notice.order_review_customer_service import (
|
||||
project_review_case_customer_resolution,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_draft_service import soft_load_review_case_for_audit
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_case
|
||||
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
|
||||
|
||||
case = soft_load_review_case_for_audit(user_id=int(user.id), case_no=str(case_no or ''))
|
||||
if case is None:
|
||||
raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
|
||||
formal = resolve_formal_ot(case)
|
||||
if not formal.get('has_formal_ot') or formal.get('task') is None:
|
||||
raise ConflictError(
|
||||
'A formal order task is required before rebinding customer',
|
||||
code='SHIPPING.FORMAL_OT_REQUIRED',
|
||||
details={'task_missing': bool(formal.get('task_missing'))},
|
||||
)
|
||||
|
||||
result = rebind_confirmed_customer(
|
||||
task=formal['task'],
|
||||
new_customer_id=customer_id,
|
||||
actor_id=int(user.id),
|
||||
expected_order_data_version=expected_order_data_version,
|
||||
reason=str(data.get('reason') or '').strip() or None,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
resolution = result['resolution']
|
||||
rebind_record = next(
|
||||
(
|
||||
item.get('rebind') for item in (resolution.evidence_json or [])
|
||||
if isinstance(item, dict) and item.get('rebind')
|
||||
),
|
||||
None,
|
||||
) or {}
|
||||
refreshed_case = soft_load_review_case_for_audit(user_id=int(user.id), case_no=str(case_no or ''))
|
||||
return _ok({
|
||||
'case': serialize_review_case(refreshed_case) if refreshed_case is not None else None,
|
||||
'customer_resolution': (
|
||||
project_review_case_customer_resolution(refreshed_case)
|
||||
if refreshed_case is not None else None
|
||||
),
|
||||
'rebind': {
|
||||
'previous_customer_id': rebind_record.get('previous_customer_id'),
|
||||
'customer_id': int(resolution.confirmed_customer_id),
|
||||
'snapshot_id': int(result['snapshot'].id),
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/reservation/revalidate',
|
||||
methods=['POST'],
|
||||
|
||||
Reference in new issue
Block a user