Compare commits
34
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8c48329d4e | ||
|
|
a10ecc8073 | ||
|
|
79050d02ba | ||
|
|
f5611d6783 | ||
|
|
70c7f03a5a | ||
|
|
440afe097f | ||
|
|
dfd48e08e7 | ||
|
|
00c52fdaae | ||
|
|
0331029ead | ||
|
|
b032bb6729 | ||
|
|
5d0a79f5fb | ||
|
|
3bb9938c05 | ||
|
|
fa5d316b25 | ||
|
|
95e7db0831 | ||
|
|
724cd74043 | ||
|
|
31434f8424 | ||
|
|
627da80e65 | ||
|
|
11cfedcc62 | ||
|
|
a5d7085c08 | ||
|
|
47ff0107bd | ||
|
|
050987692a | ||
|
|
19d6b234ea | ||
|
|
68c944607c | ||
|
|
d75f2e7d86 | ||
|
|
b8fe089b3d | ||
|
|
3e8b12b954 | ||
|
|
6502f73cb5 | ||
|
|
1a2753d3b5 | ||
|
|
2250ac98e6 | ||
|
|
5f9df244c0 | ||
|
|
3b53a2219c | ||
|
|
5187b6105b | ||
|
|
570d1c605c | ||
|
|
8cd8012632 |
No files matched your search
@@ -43,7 +43,7 @@ def _ok(data, *, status: int = 200):
|
||||
@admin_bp.route('/freight-rpa/rpa-profiles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_rpa_profiles():
|
||||
"""列出脱敏后的 RPA Profile 配置。"""
|
||||
"""列出 RPA Profile;响应含用户名明文,不含密码与密文。"""
|
||||
return _ok(freight_rpa_source_admin_service.list_profiles())
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ def create_shipping_rpa_profile():
|
||||
@admin_bp.route('/freight-rpa/rpa-profiles/<int:profile_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_rpa_profile(profile_id: int):
|
||||
"""更新 RPA Profile;未提交密码字段时保留既有密文。"""
|
||||
"""更新 RPA Profile;用户名与已存明文相同、或密码留空时不重写对应密文。"""
|
||||
return _ok(freight_rpa_source_admin_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id))
|
||||
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ backend/app/api/freight_rpa.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
from flask import Blueprint, current_app, jsonify, request
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.core.tool_auth import require_tool_auth
|
||||
@@ -65,6 +65,12 @@ def heartbeat():
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc))
|
||||
# 心跳存储不可用(ServiceUnavailableError)原样上抛,由全局 AppError handler 出标准错误 envelope。
|
||||
# 到期的 Crane 定时回查跟着心跳落成 trigger;写失败不让心跳本身失败。
|
||||
try:
|
||||
from app.services.freight_rpa.upload.crane_recheck import materialize_due_crane_rechecks
|
||||
materialize_due_crane_rechecks()
|
||||
except Exception:
|
||||
current_app.logger.exception('crane recheck materialize failed')
|
||||
return jsonify({'status': 'ok', 'message': 'heartbeat recorded', 'data': worker})
|
||||
|
||||
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
unconfigured 后再各写最多一个 batch;
|
||||
证据下载(POST /sources/inbound-files)按同一函数打包各来源最新可用
|
||||
入站/出站文件;当天清单(GET /sources/<code>/evidence-files)复用可用
|
||||
条件返回当天全部文件,并分别签发预览地址与带保存名的下载地址;
|
||||
条件返回当天全部文件;单文件下载(GET .../evidence-files/<file_id>)
|
||||
由当前站点回传字节,不把 HTTP MinIO 地址交给 HTTPS 页面;
|
||||
匹配创建(POST /matchings)与进度恢复(GET /matchings/{id});执行为 D8
|
||||
异步契约(POST /items/execute → 202 queued + run_no,单在提交时组建);
|
||||
result_unknown 单人工重新触发(POST /runs/{run_no}/documents/{doc_no}/
|
||||
@@ -369,9 +370,9 @@ def list_source_evidence_files_api(source_code: str):
|
||||
查询参数 record_kind 缺省 inbound,只接受 inbound 或 outbound。
|
||||
可用条件与证据压缩包相同,但返回当天全部可用文件,不只最新一份。
|
||||
每项含 file_id、original_filename、created_at、sha256、file_size、
|
||||
presigned_url、download_url。不解析 Excel,不含行数。预览与下载各签一次
|
||||
presigned_get_url(storage_key, expires_seconds=300);下载地址额外带
|
||||
download_name(库存源_东八区年月日_时分.扩展名),避免浏览器用对象键哈希当保存名。
|
||||
presigned_url、download_url。不解析 Excel,不含行数。预览仍打开
|
||||
presigned_url。单文件下载不使用 download_url,改走
|
||||
GET evidence-files/<file_id>,由当前站点回传。
|
||||
签发时写 TRANSFER_INBOUND_FILES_DOWNLOADED,aggregate_id 为 source_code。
|
||||
"""
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
@@ -401,6 +402,47 @@ def list_source_evidence_files_api(source_code: str):
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/sources/<source_code>/evidence-files/<int:file_id>", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def download_source_evidence_file_api(source_code: str, file_id: int):
|
||||
"""把一份仍可用的证据文件经当前站点返回给浏览器。
|
||||
|
||||
查询参数 record_kind 缺省 inbound,只接受 inbound 或 outbound。
|
||||
只接受该来源、该记录类型下仍在可用窗口内的归档。保存名用
|
||||
evidence_download_filename。页面是 HTTPS,MinIO 公网地址是 HTTP,
|
||||
直接打开预签名链接会被浏览器当成不安全下载拦掉。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
file_id: 归档文件主键。
|
||||
|
||||
Returns:
|
||||
附件响应。找不到或已不可用时 404,错误码 SHIPPING.INBOUND_FILE_NOT_FOUND。
|
||||
"""
|
||||
import io
|
||||
import mimetypes
|
||||
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
kind = str(request.args.get("record_kind") or "inbound").strip()
|
||||
if kind not in {"inbound", "outbound"}:
|
||||
raise ValidationError("record_kind must be inbound or outbound")
|
||||
code = str(source_code or "").strip()
|
||||
report = next((item for item in _usable_archive_files(code, kind) if item.id == file_id), None)
|
||||
if report is None:
|
||||
raise NotFoundError("evidence file is not available", code="SHIPPING.INBOUND_FILE_NOT_FOUND")
|
||||
data = file_asset_storage.get_bytes(report.storage_key)
|
||||
download_name = evidence_download_filename(code, report.created_at, report.original_filename)
|
||||
_record_evidence_download_audit(aggregate_id=code)
|
||||
mime = mimetypes.guess_type(download_name)[0] or "application/octet-stream"
|
||||
return send_file(
|
||||
io.BytesIO(data),
|
||||
mimetype=mime,
|
||||
as_attachment=True,
|
||||
download_name=download_name,
|
||||
)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def get_run_api(run_no: str):
|
||||
@@ -1436,6 +1478,7 @@ def _serialize_backlog_item(item) -> dict[str, Any]:
|
||||
'item_id': item.item_id,
|
||||
'source_code': item.source_code,
|
||||
'invoice_no': item.invoice_no,
|
||||
'external_doc_no': item.external_doc_no,
|
||||
'material_no': item.material_no,
|
||||
'status': item.status,
|
||||
'reason': item.reason,
|
||||
|
||||
@@ -1102,6 +1102,47 @@ def workspace_confirm_shipping_notice_uploaded(business_no: str):
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/refresh-crane-upload', methods=['POST'])
|
||||
def workspace_refresh_crane_upload_status(business_no: str):
|
||||
"""手动刷新一张仍在分配中的 Crane 发货单。
|
||||
|
||||
核心逻辑:校验当前用户可见的通知单,读取最近一次上传尝试,写入一条只查状态的 trigger。
|
||||
不改 10 分钟定时回查的到期时间,也不重新上传 Excel。
|
||||
|
||||
Args:
|
||||
business_no: 对外发货通知单号,同时是 Crane 的 Pull Request #。
|
||||
|
||||
Returns:
|
||||
JSON: business_no 与 trigger_queued。
|
||||
|
||||
Raises:
|
||||
ValidationError: 没有可刷新的上传尝试或来源连接。
|
||||
ConflictError: 当前不是分配中,或上一次手动刷新还在排队。
|
||||
"""
|
||||
user = _require_user()
|
||||
task = _load_business_notice_for_user(business_no=business_no, user_id=int(user.id))
|
||||
from app.services.freight_rpa.upload.crane_recheck import request_manual_crane_refresh
|
||||
from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source
|
||||
from app.services.shipping_notice.onhand_source_repository import get_rpa_trigger_inventory_source
|
||||
from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt
|
||||
|
||||
attempt = latest_upload_attempt(task)
|
||||
from app.models import ShippingExportArtifact
|
||||
artifact = db.session.get(ShippingExportArtifact, attempt.artifact_id) if attempt is not None else None
|
||||
snapshot = task_rpa_inventory_source(task) or {}
|
||||
upload_source = get_rpa_trigger_inventory_source(str(snapshot.get('source_code') or '')) if snapshot.get('source_code') else None
|
||||
if attempt is None or artifact is None or not isinstance(upload_source, dict):
|
||||
raise ValidationError('Crane upload status cannot be refreshed', code='SHIPPING.UPLOAD_CRANE_ALLOCATING')
|
||||
trigger_path = request_manual_crane_refresh(
|
||||
attempt,
|
||||
upload_source,
|
||||
task_no=str(task.task_no),
|
||||
export_file_path=str(artifact.file_path or ''),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok({'business_no': str(task.business_no), 'trigger_queued': bool(trigger_path)})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/rpa-upload', methods=['POST'])
|
||||
def workspace_start_shipping_notice_rpa_upload(business_no: str):
|
||||
"""按发货通知单号发起 RPA 上传;RPA 成功事实仍由受信回调裁决。"""
|
||||
|
||||
@@ -69,11 +69,9 @@ class FreightRpaProfile(Base):
|
||||
login_config_json: Mapped[dict[str, Any]] = mapped_column(
|
||||
JSON, default=lambda: {'auth_mode': 'password'}, nullable=False,
|
||||
)
|
||||
# 连接级“发货 Excel 自动上传”配置。先使用 login_url 登录,再访问 upload_config_json.entry_url 进入上传页;
|
||||
# 上传配置由管理端表单编辑,后端白名单校验后保存为受限 JSON。白名单字段仅
|
||||
# enabled / entry_url / file_input_selector / submit_mode / submit_selector /
|
||||
# result_mode / result_selector / success_texts / timeout_seconds。
|
||||
# 一条连接只保存一份上传配置;该配置变更不递增 config_version(见 admin 服务)。
|
||||
# 连接级“发货 Excel 自动上传”开关。只保存 {enabled}。
|
||||
# 上传页、文件控件、提交和成功判断在连接器代码里,由 login_url 的主机拼出入口。
|
||||
# 该配置变更不递增 config_version(见 admin 服务)。
|
||||
upload_config_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
|
||||
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||
|
||||
@@ -7,6 +7,7 @@ services/admin/freight_rpa_source_admin_service.py
|
||||
freight_rpa_form_utils、credential_crypto、parsing_profile、upload_config_validation、
|
||||
onhand_source_repository.validate_source_profile、audit_service。
|
||||
逻辑:admin_freight_rpa 蓝图的 rpa-profiles / sources / bind-parsing / activate 委托本服务;
|
||||
Profile 列表与保存回执返回用户名明文,密码与密文不返回;
|
||||
在手快照/路由规则/外部映射仍见 shipping_onhand_admin_service。
|
||||
"""
|
||||
|
||||
@@ -15,7 +16,7 @@ from __future__ import annotations
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.core.errors import ConflictError, NotFoundError, ServiceUnavailableError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
FreightRpaOnhandExternalMapping,
|
||||
@@ -38,7 +39,7 @@ from app.services.admin.freight_rpa_form_utils import (
|
||||
validate_report_path as _validate_report_path,
|
||||
)
|
||||
from app.services.freight_rpa import parsing_profile as onhand_parsing_profile
|
||||
from app.services.freight_rpa.common.credential_crypto import encrypt_credential
|
||||
from app.services.freight_rpa.common.credential_crypto import decrypt_credential, encrypt_credential
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.onhand_source_repository import validate_source_profile
|
||||
from app.services.shipping_notice.upload_config_validation import validate_upload_config
|
||||
@@ -77,27 +78,50 @@ def _validate_profile_login_config(data: dict[str, Any]) -> dict[str, str]:
|
||||
|
||||
|
||||
|
||||
def _stored_username(profile: FreightRpaProfile) -> str | None:
|
||||
"""解密已保存的用户名,供管理端辨认账号。
|
||||
|
||||
核心逻辑:用户名是账号标识,库内仍只存密文;解密失败时返回 None,避免坏密文拖垮连接列表。
|
||||
密码不走本函数。
|
||||
|
||||
Args:
|
||||
profile: 已持久化的货代登录连接。
|
||||
|
||||
Returns:
|
||||
str | None: 用户名明文;未配置或无法解密时为 None。
|
||||
"""
|
||||
if not profile.username_ciphertext:
|
||||
return None
|
||||
try:
|
||||
return decrypt_credential(profile.username_ciphertext)
|
||||
except (ServiceUnavailableError, ValidationError):
|
||||
return None
|
||||
|
||||
|
||||
def _profile_payload(profile: FreightRpaProfile) -> dict[str, Any]:
|
||||
"""序列化系统连接。用户名明文回传,密码与密文不出现在响应中。"""
|
||||
return {
|
||||
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
|
||||
'connector_type': profile.connector_type, 'login_url': profile.login_url,
|
||||
'login_config_json': profile.login_config_json or {'auth_mode': 'password'}, 'enabled': bool(profile.enabled),
|
||||
'upload_config_json': profile.upload_config_json,
|
||||
'config_version': profile.config_version, 'username_masked': _mask(profile.username_ciphertext),
|
||||
'config_version': profile.config_version,
|
||||
'username': _stored_username(profile),
|
||||
'username_masked': _mask(profile.username_ciphertext),
|
||||
'password_configured': bool(profile.password_ciphertext), 'credential_updated_at': _iso(profile.credential_updated_at),
|
||||
'created_at': _iso(profile.created_at), 'updated_at': _iso(profile.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _mask(ciphertext: str | None) -> str | None:
|
||||
"""凭据密文不支持反向展示;仅以配置状态提示管理员。"""
|
||||
"""密码等不可回显凭据只报告是否已配置。"""
|
||||
return 'configured' if ciphertext else None
|
||||
|
||||
|
||||
|
||||
|
||||
def list_profiles() -> list[dict[str, Any]]:
|
||||
"""列出 Profile 元数据,不返回可恢复的凭据。"""
|
||||
"""列出 Profile。响应含用户名明文,不含密码与密文。"""
|
||||
return [_profile_payload(item) for item in FreightRpaProfile.query.order_by(FreightRpaProfile.profile_code).all()]
|
||||
|
||||
|
||||
@@ -113,7 +137,11 @@ def delete_profile(profile_id: int) -> None:
|
||||
|
||||
|
||||
def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
|
||||
"""创建或更新货代登录连接;密码留空表示保留既有密文。"""
|
||||
"""创建或更新货代登录连接。
|
||||
|
||||
核心逻辑:用户名留空,或与已存明文相同,不重写用户名密文;密码留空则保留既有密码密文。
|
||||
只有用户名实际变更或提交了新密码时才刷新 credential_updated_at。
|
||||
"""
|
||||
profile = db.session.get(FreightRpaProfile, profile_id) if profile_id else None
|
||||
if profile_id and profile is None:
|
||||
raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
|
||||
@@ -138,11 +166,14 @@ def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int
|
||||
)
|
||||
username = _text(data, 'username')
|
||||
password = _text(data, 'password')
|
||||
if username is not None:
|
||||
# [STEP] 管理端回显的用户名会随保存再次提交;与库内明文相同则不轮换 Fernet 密文。
|
||||
username_changed = False
|
||||
if username is not None and _stored_username(profile) != username:
|
||||
profile.username_ciphertext = encrypt_credential(username)
|
||||
username_changed = True
|
||||
if password is not None:
|
||||
profile.password_ciphertext = encrypt_credential(password)
|
||||
if username is not None or password is not None:
|
||||
if username_changed or password is not None:
|
||||
profile.credential_updated_at = datetime.utcnow()
|
||||
# 连接级受控上传配置(受限 JSON);与库存 RPA 运行期配置隔离,不参与 config_version。
|
||||
if 'upload_config_json' in data:
|
||||
|
||||
@@ -4,6 +4,8 @@ backend/app/services/file_assets/storage.py
|
||||
用途:私有 MinIO 业务文件存储适配层(与 agent-guides 公开 bucket 隔离)。
|
||||
依赖:minio、app.core.config.settings、app.core.errors.ServiceUnavailableError。
|
||||
逻辑:由 file_assets.service 与调拨证据清单调用;禁止 public-read policy 与本地静默回退;
|
||||
读写删走 MINIO_ENDPOINT(容器内网)。浏览器预签走 MINIO_PUBLIC_BASE_URL,
|
||||
因为签名包含 Host,不能把 host.docker.internal 交给浏览器后再替换。
|
||||
读写删失败统一抛 503。预签下载可附带 response-content-disposition,避免保存名落成对象键。
|
||||
"""
|
||||
|
||||
@@ -13,6 +15,7 @@ import io
|
||||
import logging
|
||||
from datetime import timedelta
|
||||
from typing import BinaryIO
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from minio import Minio
|
||||
from minio.error import S3Error
|
||||
@@ -24,16 +27,75 @@ _LOGGER = logging.getLogger(__name__)
|
||||
_cfg = config[ACTIVE_ENV_NAME]
|
||||
|
||||
|
||||
def resolve_presign_endpoint(
|
||||
public_base: str,
|
||||
fallback_endpoint: str,
|
||||
fallback_secure: bool,
|
||||
) -> tuple[str, bool]:
|
||||
"""把浏览器可访问的 MinIO 基址收成预签名客户端的 endpoint 与 secure。
|
||||
|
||||
核心逻辑:SigV4 把 Host 写进签名。正式环境容器用 host.docker.internal:9000
|
||||
读写,浏览器必须打开 MINIO_PUBLIC_BASE_URL(如 http://ai.well-trust.com:9000)。
|
||||
基址为空或解析不出主机时退回内网端点。80/443 省略端口,交给 Minio 客户端按协议补。
|
||||
|
||||
Args:
|
||||
public_base: MINIO_PUBLIC_BASE_URL,可带或不带协议。
|
||||
fallback_endpoint: 容器内访问用的 host:port。
|
||||
fallback_secure: 内网端点是否走 HTTPS。
|
||||
|
||||
Returns:
|
||||
(endpoint, secure)。endpoint 形如 ai.well-trust.com:9000。
|
||||
"""
|
||||
raw = (public_base or "").strip()
|
||||
if not raw:
|
||||
return fallback_endpoint, fallback_secure
|
||||
parsed = urlparse(raw if "://" in raw else f"http://{raw}")
|
||||
host = parsed.hostname
|
||||
if not host:
|
||||
return fallback_endpoint, fallback_secure
|
||||
if ":" in host:
|
||||
host = f"[{host}]"
|
||||
secure = parsed.scheme.lower() == "https"
|
||||
port = parsed.port
|
||||
if port and not ((secure and port == 443) or (not secure and port == 80)):
|
||||
return f"{host}:{port}", secure
|
||||
return host, secure
|
||||
|
||||
|
||||
class FileAssetStorage:
|
||||
"""私有业务文件 MinIO 存储客户端。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""分别建立内网读写客户端与浏览器预签名客户端。
|
||||
|
||||
核心逻辑:两端点主机与协议相同时共用一个客户端。预签名客户端只在
|
||||
生成 URL 时做本地签名,不靠它访问内网 MinIO。
|
||||
"""
|
||||
endpoint = str(_cfg.MINIO_ENDPOINT or "").strip()
|
||||
access_key = _cfg.MINIO_ACCESS_KEY
|
||||
secret_key = _cfg.MINIO_SECRET_KEY
|
||||
secure = bool(_cfg.MINIO_SECURE)
|
||||
self.client = Minio(
|
||||
_cfg.MINIO_ENDPOINT,
|
||||
access_key=_cfg.MINIO_ACCESS_KEY,
|
||||
secret_key=_cfg.MINIO_SECRET_KEY,
|
||||
secure=_cfg.MINIO_SECURE,
|
||||
endpoint,
|
||||
access_key=access_key,
|
||||
secret_key=secret_key,
|
||||
secure=secure,
|
||||
)
|
||||
# [STEP 1] 预签名单独用浏览器主机。只改 URL 字符串会使签名失效。
|
||||
presign_endpoint, presign_secure = resolve_presign_endpoint(
|
||||
str(_cfg.MINIO_PUBLIC_BASE_URL or ""),
|
||||
endpoint,
|
||||
secure,
|
||||
)
|
||||
if presign_endpoint == endpoint and presign_secure == secure:
|
||||
self.presign_client = self.client
|
||||
else:
|
||||
self.presign_client = Minio(
|
||||
presign_endpoint,
|
||||
access_key=access_key,
|
||||
secret_key=secret_key,
|
||||
secure=presign_secure,
|
||||
)
|
||||
self.bucket_name = str(_cfg.MINIO_FILE_ASSETS_BUCKET or 'hxops-file-assets').strip()
|
||||
|
||||
def _ensure_bucket_exists(self) -> None:
|
||||
@@ -120,6 +182,19 @@ class FileAssetStorage:
|
||||
except S3Error:
|
||||
return False
|
||||
|
||||
def _bind_presign_region(self) -> None:
|
||||
"""把内网客户端已探到的 region 抄给预签名客户端。
|
||||
|
||||
核心逻辑:minio-py 在签名前会请求 GetBucketLocation。若用公网客户端发这次请求,
|
||||
容器里可能访问不到浏览器入口,或每次下载多一次公网探测。
|
||||
bucket 检查已经通过内网客户端写入 _region_map;这里只复用该结果。
|
||||
尚未探测到时用 MinIO 默认 us-east-1。
|
||||
"""
|
||||
if self.presign_client is self.client:
|
||||
return
|
||||
region = self.client._region_map.get(self.bucket_name) or "us-east-1"
|
||||
self.presign_client._region_map[self.bucket_name] = region
|
||||
|
||||
def presigned_get_url(
|
||||
self,
|
||||
storage_key: str,
|
||||
@@ -129,7 +204,9 @@ class FileAssetStorage:
|
||||
) -> str:
|
||||
"""生成短期受控下载 URL。
|
||||
|
||||
核心逻辑:对象键常为内容哈希,浏览器会把它当成保存名。
|
||||
核心逻辑:先把内网探到的 region 绑到 presign_client,再用它签名。
|
||||
主机来自 MINIO_PUBLIC_BASE_URL。签名在本地完成,不再向公网探测 bucket 区域。
|
||||
对象键常为内容哈希,浏览器会把它当成保存名。
|
||||
download_name 非空时把 response-content-disposition 签进 URL,
|
||||
让保存对话框使用业务文件名。预览地址不要传这个参数。
|
||||
|
||||
@@ -139,16 +216,17 @@ class FileAssetStorage:
|
||||
download_name: 附件保存名;只接受调用方已洗净的文件名。
|
||||
|
||||
Returns:
|
||||
带过期签名的 GET URL。
|
||||
带过期签名的 GET URL,主机是浏览器可访问的 MinIO 地址。
|
||||
"""
|
||||
self._ensure_bucket_exists()
|
||||
self._bind_presign_region()
|
||||
response_headers = None
|
||||
if download_name:
|
||||
safe = download_name.replace('"', '').replace('\\', '').replace('\r', '').replace('\n', '')
|
||||
response_headers = {
|
||||
'response-content-disposition': f'attachment; filename="{safe}"',
|
||||
}
|
||||
return self.client.presigned_get_object(
|
||||
return self.presign_client.presigned_get_object(
|
||||
self.bucket_name,
|
||||
storage_key,
|
||||
expires=timedelta(seconds=max(int(expires_seconds or 60), 60)),
|
||||
|
||||
@@ -3,8 +3,9 @@ services/freight_rpa/common/credential_crypto.py
|
||||
|
||||
用途:加密和解密库存 RPA Profile 的登录凭据(委托通用 core 模块,仅固定本域密钥键与错误码)。
|
||||
依赖:app.core.credential_crypto(Fernet 加解密);调用方仅保存密文,不将凭据写入日志或 API 响应。
|
||||
逻辑:管理服务写入 Profile 前调用 encrypt_credential;RPA 配置读取服务在受控内存中调用
|
||||
decrypt_credential。主密钥键 FREIGHT_RPA_CREDENTIAL_KEY(2026-09-18 RPA 命名空间)。
|
||||
逻辑:管理服务写入 Profile 前调用 encrypt_credential;管理端读取 Profile 时只解密用户名用于展示;
|
||||
密码仅在 RPA 执行内存中调用 decrypt_credential。密码与密文不得进入 API 响应或日志。
|
||||
主密钥键 FREIGHT_RPA_CREDENTIAL_KEY(2026-09-18 RPA 命名空间)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -48,7 +49,7 @@ def decrypt_credential(ciphertext: str) -> str:
|
||||
ciphertext: 数据库中保存的 Fernet 密文。
|
||||
|
||||
Returns:
|
||||
str: 仅供 RPA 执行内存使用的明文。
|
||||
str: 明文。密码只留在 RPA 执行内存;用户名可由管理端 Profile 接口返回。禁止写入日志。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: 未配置或配置了无效的主密钥。
|
||||
|
||||
@@ -44,6 +44,7 @@ from app.core.errors import NotFoundError
|
||||
from app.models import (
|
||||
FreightRpaInboundReportConfig,
|
||||
FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun,
|
||||
FreightRpaOnhandReportConfig,
|
||||
FreightRpaOutboundReportConfig,
|
||||
FreightRpaOutboundReportFile,
|
||||
@@ -659,6 +660,72 @@ def latest_usable_inbound_file(
|
||||
return _inbound_file_view(report)
|
||||
|
||||
|
||||
def latest_usable_inbound_files_by_source(
|
||||
source_ids: list[int],
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> dict[str, InboundFileView]:
|
||||
"""一次取出这批来源各自最新的可用入站归档(来源状态批量投影用)。
|
||||
|
||||
用途:调拨 GET /sources 批量渲染来源卡时按批取文件身份,查询次数不随
|
||||
来源个数增长;口径与 latest_usable_inbound_file 完全一致(同一
|
||||
usable_inbound_file_condition 权威),只是按来源主键集合一次取回。
|
||||
|
||||
Args:
|
||||
source_ids: 来源主键集合(FreightRpaInboundUnitRun.source_id)。
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
source_code → InboundFileView;没有可用文件的来源不出现,每个来源
|
||||
只留 created_at/id 最新一条。
|
||||
"""
|
||||
rows = (
|
||||
FreightRpaInboundReportFile.query
|
||||
.join(FreightRpaInboundReportFile.unit_run)
|
||||
.filter(
|
||||
FreightRpaInboundUnitRun.source_id.in_([int(i) for i in source_ids]),
|
||||
usable_inbound_file_condition(now=now),
|
||||
)
|
||||
.order_by(FreightRpaInboundReportFile.created_at.desc(), FreightRpaInboundReportFile.id.desc())
|
||||
.all()
|
||||
)
|
||||
picked: dict[str, InboundFileView] = {}
|
||||
for report in rows:
|
||||
view = _inbound_file_view(report)
|
||||
if view.source_code not in picked:
|
||||
picked[view.source_code] = view
|
||||
return picked
|
||||
|
||||
|
||||
def expired_inbound_source_codes(
|
||||
source_ids: list[int],
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> set[str]:
|
||||
"""一次找出仍有失效未清理入站归档的来源编码(expired 投影依据,存在性判断)。
|
||||
|
||||
用途:调拨来源状态批量投影判断哪些来源因隔日旧文件/保留期已到提示重抓;
|
||||
口径与 has_expired_inbound_file 同核(expired_inbound_file_condition)。
|
||||
|
||||
Args:
|
||||
source_ids: 来源主键集合。
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
至少有一份失效未清理入站归档的 source_code 集合。
|
||||
"""
|
||||
rows = (
|
||||
FreightRpaInboundReportFile.query
|
||||
.join(FreightRpaInboundReportFile.unit_run)
|
||||
.filter(
|
||||
FreightRpaInboundUnitRun.source_id.in_([int(i) for i in source_ids]),
|
||||
expired_inbound_file_condition(now=now),
|
||||
)
|
||||
.with_entities(FreightRpaInboundUnitRun.source_code)
|
||||
.distinct()
|
||||
.all()
|
||||
)
|
||||
return {str(row[0]) for row in rows}
|
||||
|
||||
|
||||
def read_inbound_file_bytes(file_id: int) -> bytes:
|
||||
"""按 file_id 读取入站归档文件的对象字节。
|
||||
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
"""
|
||||
services/freight_rpa/upload/crane_recheck.py
|
||||
|
||||
用途:Crane 发货单进入分配中之后的状态回查。
|
||||
依赖:ShippingUploadAttempt、freight_rpa.upload.trigger_io、page_contract。
|
||||
逻辑:自动上传只排一次 10 分钟后的回查;手动刷新另写一条 status_check trigger,
|
||||
不顺延、不取消那一次定时。两条回查都只让 Worker 重新登录并按 Pull Request # 看行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import ShippingExportArtifact, ShippingNotice, ShippingUploadAttempt
|
||||
from app.services.freight_rpa.upload.page_contract import crane_recheck_due_at
|
||||
from app.services.freight_rpa.upload.trigger_io import write_upload_trigger
|
||||
|
||||
CRANE_ALLOCATING_CODE = 'CRANE_ALLOCATING'
|
||||
|
||||
|
||||
def is_crane_allocating(attempt: ShippingUploadAttempt | None) -> bool:
|
||||
"""当前尝试是否停在 Crane 已接收、尚未分配完成。"""
|
||||
return (
|
||||
attempt is not None
|
||||
and attempt.status == 'running'
|
||||
and attempt.error_code == CRANE_ALLOCATING_CODE
|
||||
)
|
||||
|
||||
|
||||
def _evidence(attempt: ShippingUploadAttempt) -> dict[str, Any]:
|
||||
raw = attempt.success_evidence_json
|
||||
return dict(raw) if isinstance(raw, dict) else {}
|
||||
|
||||
|
||||
def _recheck(evidence: dict[str, Any]) -> dict[str, Any]:
|
||||
raw = evidence.get('crane_recheck')
|
||||
return dict(raw) if isinstance(raw, dict) else {}
|
||||
|
||||
|
||||
def remember_crane_allocating(
|
||||
attempt: ShippingUploadAttempt,
|
||||
artifact: ShippingExportArtifact,
|
||||
callback_id: str,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> ShippingUploadAttempt:
|
||||
"""把尝试标成分配中,并在首次进入时记下唯一一次定时回查。
|
||||
|
||||
核心逻辑:due_at 只在还没有时写入。后续回查回调仍是分配中时,不改到期时间,
|
||||
也不把定时标记成已触发。
|
||||
|
||||
Args:
|
||||
attempt: 本次上传尝试。
|
||||
artifact: 已提交的发货 Excel。
|
||||
callback_id: 本次回调幂等键。重复的同一个键直接返回。
|
||||
now: 测试注入的当前时间。
|
||||
|
||||
Returns:
|
||||
ShippingUploadAttempt: 仍为 running、错误码为 CRANE_ALLOCATING 的尝试。
|
||||
"""
|
||||
evidence = _evidence(attempt)
|
||||
if evidence.get('last_callback_id') == callback_id or attempt.callback_id == callback_id:
|
||||
return attempt
|
||||
recheck = _recheck(evidence)
|
||||
if not recheck.get('due_at'):
|
||||
pull_request_no = str(artifact.file_name or '').rsplit('.', 1)[0] or str(artifact.file_name or '')
|
||||
recheck = {
|
||||
'due_at': crane_recheck_due_at(now).isoformat(timespec='seconds'),
|
||||
'fired': False,
|
||||
'pull_request_no': pull_request_no,
|
||||
}
|
||||
evidence['crane_recheck'] = recheck
|
||||
evidence['last_callback_id'] = callback_id
|
||||
evidence['manual_refresh_inflight'] = False
|
||||
attempt.success_evidence_json = evidence
|
||||
attempt.status = 'running'
|
||||
attempt.error_code = CRANE_ALLOCATING_CODE
|
||||
attempt.error_message = None
|
||||
attempt.finished_at = None
|
||||
if not attempt.callback_id:
|
||||
attempt.callback_id = callback_id
|
||||
artifact.status = 'uploading'
|
||||
db.session.flush()
|
||||
return attempt
|
||||
|
||||
|
||||
def _write_status_check(
|
||||
attempt: ShippingUploadAttempt,
|
||||
upload_source: dict[str, Any],
|
||||
*,
|
||||
task_no: str,
|
||||
export_file_path: str,
|
||||
pull_request_no: str,
|
||||
kind: str,
|
||||
) -> str | None:
|
||||
"""写入一条只查状态的上传 trigger。文件复制失败时返回 None。"""
|
||||
# 定时回查的回调键固定,重复心跳不会写成两次有效回调。
|
||||
# 手动刷新每次使用新键,避免上一次「仍在分配」把这一次回调当成重复而跳过。
|
||||
callback_id = f'crane-recheck:{attempt.id}:scheduled'
|
||||
trigger_filename = f'upload_recheck_{task_no}_scheduled.json'
|
||||
if kind == 'manual':
|
||||
callback_id = f'crane-recheck:{attempt.id}:manual:{datetime.utcnow().strftime("%Y%m%d%H%M%S%f")}'
|
||||
trigger_filename = f'upload_recheck_{task_no}_manual.json'
|
||||
_queue, trigger_path, _callback = write_upload_trigger(
|
||||
task_no,
|
||||
export_file_path,
|
||||
{'mode': 'status_check', 'recheck_kind': kind, 'pull_request_no': pull_request_no},
|
||||
attempt_id=int(attempt.id),
|
||||
artifact_id=int(attempt.artifact_id),
|
||||
connector_type='crane',
|
||||
upload_config={'enabled': True},
|
||||
login_url=str(upload_source.get('login_url') or '').strip() or None,
|
||||
credential_envelope=upload_source.get('credential_envelope') if isinstance(upload_source.get('credential_envelope'), dict) else None,
|
||||
callback_id=callback_id,
|
||||
business_no=pull_request_no,
|
||||
trigger_filename=trigger_filename,
|
||||
)
|
||||
return trigger_path
|
||||
|
||||
|
||||
def fire_scheduled_crane_recheck(
|
||||
attempt: ShippingUploadAttempt,
|
||||
upload_source: dict[str, Any],
|
||||
*,
|
||||
task_no: str,
|
||||
export_file_path: str,
|
||||
now: datetime | None = None,
|
||||
) -> bool:
|
||||
"""到期后写入唯一一次定时回查。未到期、已触发或不是分配中时不写文件。
|
||||
|
||||
Returns:
|
||||
bool: 本次是否新写了 trigger。
|
||||
"""
|
||||
if not is_crane_allocating(attempt):
|
||||
return False
|
||||
evidence = _evidence(attempt)
|
||||
recheck = _recheck(evidence)
|
||||
if recheck.get('fired') or not recheck.get('due_at'):
|
||||
return False
|
||||
due_at = datetime.fromisoformat(str(recheck['due_at']))
|
||||
if due_at > (now or datetime.utcnow()):
|
||||
return False
|
||||
pull_request_no = str(recheck.get('pull_request_no') or '').strip()
|
||||
trigger_path = _write_status_check(
|
||||
attempt, upload_source, task_no=task_no, export_file_path=export_file_path,
|
||||
pull_request_no=pull_request_no, kind='scheduled',
|
||||
)
|
||||
if not trigger_path:
|
||||
return False
|
||||
recheck['fired'] = True
|
||||
evidence['crane_recheck'] = recheck
|
||||
attempt.success_evidence_json = evidence
|
||||
db.session.flush()
|
||||
return True
|
||||
|
||||
|
||||
def request_manual_crane_refresh(
|
||||
attempt: ShippingUploadAttempt,
|
||||
upload_source: dict[str, Any],
|
||||
*,
|
||||
task_no: str,
|
||||
export_file_path: str,
|
||||
) -> str:
|
||||
"""手动刷新:立刻写一条状态回查,不改定时回查的到期时间和已触发标记。
|
||||
|
||||
Raises:
|
||||
ConflictError: 当前不是分配中,或上一次手动刷新还没回调。
|
||||
ValidationError: 共享目录写不出 trigger。
|
||||
"""
|
||||
if not is_crane_allocating(attempt):
|
||||
raise ConflictError(
|
||||
'Crane upload is not waiting for allocation',
|
||||
code='SHIPPING.UPLOAD_CRANE_ALLOCATING',
|
||||
)
|
||||
evidence = _evidence(attempt)
|
||||
if evidence.get('manual_refresh_inflight'):
|
||||
raise ConflictError(
|
||||
'A Crane status refresh is already queued',
|
||||
code='SHIPPING.UPLOAD_CRANE_REFRESH_INFLIGHT',
|
||||
)
|
||||
recheck = _recheck(evidence)
|
||||
pull_request_no = str(recheck.get('pull_request_no') or '').strip()
|
||||
due_at = recheck.get('due_at')
|
||||
fired = bool(recheck.get('fired'))
|
||||
trigger_path = _write_status_check(
|
||||
attempt, upload_source, task_no=task_no, export_file_path=export_file_path,
|
||||
pull_request_no=pull_request_no, kind='manual',
|
||||
)
|
||||
if not trigger_path:
|
||||
raise ValidationError(
|
||||
'Crane status refresh trigger directory is unavailable',
|
||||
code='SHIPPING.UPLOAD_TRIGGER_UNAVAILABLE',
|
||||
)
|
||||
evidence['manual_refresh_inflight'] = True
|
||||
evidence['crane_recheck'] = {**recheck, 'due_at': due_at, 'fired': fired, 'pull_request_no': pull_request_no}
|
||||
attempt.success_evidence_json = evidence
|
||||
db.session.flush()
|
||||
return trigger_path
|
||||
|
||||
|
||||
def materialize_due_crane_rechecks(now: datetime | None = None) -> int:
|
||||
"""心跳时把已到期且尚未触发的 Crane 定时回查写成 trigger。
|
||||
|
||||
Returns:
|
||||
int: 新写入的 trigger 数量。
|
||||
"""
|
||||
from app.services.shipping_notice.onhand_source_repository import get_rpa_trigger_inventory_source
|
||||
|
||||
moment = now or datetime.utcnow()
|
||||
written = 0
|
||||
attempts = ShippingUploadAttempt.query.filter_by(status='running', error_code=CRANE_ALLOCATING_CODE).all()
|
||||
for attempt in attempts:
|
||||
artifact = db.session.get(ShippingExportArtifact, attempt.artifact_id)
|
||||
notice = db.session.get(ShippingNotice, artifact.task_id) if artifact is not None else None
|
||||
if artifact is None or notice is None or not artifact.file_path:
|
||||
continue
|
||||
from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source
|
||||
|
||||
snapshot = task_rpa_inventory_source(notice) or {}
|
||||
source_code = str(snapshot.get('source_code') or '').strip()
|
||||
upload_source = get_rpa_trigger_inventory_source(source_code) if source_code else None
|
||||
if not isinstance(upload_source, dict) or str(upload_source.get('connector_type') or '').lower() != 'crane':
|
||||
continue
|
||||
if fire_scheduled_crane_recheck(
|
||||
attempt, upload_source, task_no=str(notice.task_no),
|
||||
export_file_path=str(artifact.file_path), now=moment,
|
||||
):
|
||||
written += 1
|
||||
if written:
|
||||
db.session.commit()
|
||||
return written
|
||||
@@ -0,0 +1,68 @@
|
||||
"""
|
||||
services/freight_rpa/upload/page_contract.py
|
||||
|
||||
用途:货代发货 Excel 上传的平台页面契约。入口路径、文件控件和成功条件由代码固定。
|
||||
依赖:标准库 urllib。
|
||||
逻辑:系统连接只保存是否启用自动上传;Worker 用登录地址的主机拼出上传页。
|
||||
DBS 上传后当页即可判定;Crane 先进入分配中,10 分钟后再查一次。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
CRANE_RECHECK_DELAY = timedelta(minutes=10)
|
||||
DBS_UPLOAD_PATH = '/main/portal/frame/WMSUpload2'
|
||||
CRANE_UPLOAD_HASH = '/#/shipping-order-upload'
|
||||
|
||||
|
||||
def build_upload_entry_url(connector_type: str, login_url: str) -> str:
|
||||
"""按平台把登录地址的主机拼成上传页。
|
||||
|
||||
核心逻辑:页面路径属于连接器代码。管理端不再保存上传入口 URL。
|
||||
|
||||
Args:
|
||||
connector_type: dbs 或 crane。
|
||||
login_url: 系统连接上的 HTTPS 登录地址。
|
||||
|
||||
Returns:
|
||||
str: 该平台固定上传页。
|
||||
|
||||
Raises:
|
||||
ValueError: 连接类型或登录地址无法构成上传页。
|
||||
"""
|
||||
kind = str(connector_type or '').strip().lower()
|
||||
parsed = urlsplit(str(login_url or '').strip())
|
||||
host = parsed.netloc.strip()
|
||||
if parsed.scheme.lower() != 'https' or not host or not parsed.hostname:
|
||||
raise ValueError('login_url must be HTTPS with a host')
|
||||
if kind == 'dbs':
|
||||
return f'https://{host}{DBS_UPLOAD_PATH}'
|
||||
if kind == 'crane':
|
||||
return f'https://{host}{CRANE_UPLOAD_HASH}'
|
||||
raise ValueError(f'unsupported connector_type: {connector_type or "<empty>"}')
|
||||
|
||||
|
||||
def classify_crane_order_row(order_status: str, order_status_description: str) -> str:
|
||||
"""判断 Crane 发货单行处于分配中、已分配,还是都不是。
|
||||
|
||||
Args:
|
||||
order_status: Order Status 列文本。
|
||||
order_status_description: Order Status Description 列文本。
|
||||
|
||||
Returns:
|
||||
str: allocated、allocating 或 other。
|
||||
"""
|
||||
status = ' '.join(str(order_status or '').split()).lower()
|
||||
description = ' '.join(str(order_status_description or '').split()).lower()
|
||||
if status == 'processing' and description == 'shipping order allocated':
|
||||
return 'allocated'
|
||||
if status == 'processing' and description == 'allocating the shipping order':
|
||||
return 'allocating'
|
||||
return 'other'
|
||||
|
||||
|
||||
def crane_recheck_due_at(now: datetime | None = None) -> datetime:
|
||||
"""自动上传进入分配中之后,唯一一次定时回查的到期时间。"""
|
||||
return (now or datetime.utcnow()) + CRANE_RECHECK_DELAY
|
||||
@@ -76,6 +76,7 @@ def write_upload_trigger(
|
||||
credential_envelope: dict[str, Any] | None = None,
|
||||
callback_id: str | None = None,
|
||||
business_no: str | None = None,
|
||||
trigger_filename: str | None = None,
|
||||
) -> tuple[str | None, str | None, str | None]:
|
||||
"""
|
||||
复制发货 Excel 至共享上传队列,并以原子发布方式写入 RPA 上传触发 JSON。
|
||||
@@ -84,7 +85,7 @@ def write_upload_trigger(
|
||||
触发文件固化本次上传契约快照,Worker 据此进入 DSV/Crane 受控流程:
|
||||
schema_version / task_no / attempt_id / artifact_id / callback_id(非空)/
|
||||
connector_type / upload_config(本次快照 + upload_config_hash)/ login_url / credential_envelope / file_path。
|
||||
平台差异(文件选择器、提交与结果判定)由 Worker 的受控 Adapter 按 upload_config 执行。
|
||||
平台页面动作由 Worker 连接器代码固定;upload_config 只携带是否启用自动上传。
|
||||
写入复用“临时文件 + fsync + os.replace”原子方式,避免 Worker 读取半写 JSON。
|
||||
|
||||
Args:
|
||||
@@ -100,6 +101,7 @@ def write_upload_trigger(
|
||||
credential_envelope: 连接凭据密文信封(Worker 据此登录)。
|
||||
callback_id: 回调幂等 ID;为空时自动生成,保证非空。
|
||||
business_no: 发货通知对外业务编号(业务单号),用于精简上传文件名;为空时回退 task_no。
|
||||
trigger_filename: 触发文件名。状态回查使用独立文件名,避免覆盖正在上传的 trigger。
|
||||
|
||||
Returns:
|
||||
tuple[str | None, str | None, str | None]: (queue 文件路径, trigger 文件路径, callback_id);
|
||||
@@ -113,14 +115,21 @@ def write_upload_trigger(
|
||||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
src = Path(export_file_path)
|
||||
if not src.is_file():
|
||||
status_check = str((payload or {}).get('mode') or '') == 'status_check'
|
||||
if not src.is_file() and not status_check:
|
||||
return None, None, None
|
||||
# [STEP] 精简上传文件名:仅用业务编号(业务单号),避免 task_no 与导出文件名重复拼接过长;
|
||||
# 业务编号为空时回退到内部任务号,扩展名沿用源文件(无扩展名时按 xlsx 兜底)。
|
||||
emit_no = str(business_no or '').strip() or task_no
|
||||
suffix = str(src.suffix or '.xlsx').lower()
|
||||
dest = queue / f"{emit_no}{suffix}"
|
||||
shutil.copy2(src, dest)
|
||||
if src.is_file():
|
||||
shutil.copy2(src, dest)
|
||||
queued_file = str(dest)
|
||||
elif status_check:
|
||||
queued_file = ''
|
||||
else:
|
||||
return None, None, None
|
||||
|
||||
resolved_callback_id = str(callback_id or '').strip() or f'upload:{task_no}:{uuid.uuid4().hex[:12]}'
|
||||
body = {
|
||||
@@ -135,10 +144,10 @@ def write_upload_trigger(
|
||||
"upload_config_hash": upload_config_hash,
|
||||
"login_url": login_url,
|
||||
"credential_envelope": credential_envelope,
|
||||
"file_path": str(dest),
|
||||
"file_path": queued_file,
|
||||
"requested_at": datetime.utcnow().isoformat(),
|
||||
**(payload or {}),
|
||||
}
|
||||
trigger_path = trigger_dir / f"upload_{task_no}.json"
|
||||
trigger_path = trigger_dir / (trigger_filename or f"upload_{task_no}.json")
|
||||
_write_trigger_json_atomic(trigger_path, body)
|
||||
return str(dest), str(trigger_path), resolved_callback_id
|
||||
@@ -36,6 +36,7 @@ from app.models import TransferAttempt, TransferInvoiceItem, TransferMovementLed
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
circle_ledger_record_ids_scope_union,
|
||||
pending_ledger_query,
|
||||
ledger_external_doc_no,
|
||||
transfer_type_code_of,
|
||||
)
|
||||
from app.services.in_transit_transfer.status import TransferStatus
|
||||
@@ -100,6 +101,8 @@ class BacklogItemDTO:
|
||||
result_code: Optional[str] = None
|
||||
# 出生匹配快照上的调拨类型 code。空串表示行没有匹配或快照未写类型。
|
||||
transfer_type: str = ""
|
||||
# 档上的外部单号。空串表示这行没有外部单号。
|
||||
external_doc_no: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -207,7 +210,7 @@ def _latest_attempt_times(item_ids: list[int]) -> dict[int, datetime]:
|
||||
def _backlog_base_query(statuses, *, source_code: str | None = None, keyword: str | None = None):
|
||||
"""待处理池基础查询(状态集合 + 可选来源/关键字过滤)。
|
||||
|
||||
keyword 与前端池内筛选同字段集(Invoice/料号/品名/来源,2026-10-16 随
|
||||
keyword 与前端池内筛选同字段集(单号/外部单号/料号/品名/来源,2026-10-16 随
|
||||
服务端分页下推),大小写不敏感子串匹配(ilike)。
|
||||
|
||||
Args:
|
||||
@@ -222,12 +225,19 @@ def _backlog_base_query(statuses, *, source_code: str | None = None, keyword: st
|
||||
query = query.filter_by(source_code=source_code)
|
||||
if keyword:
|
||||
like = f"%{keyword}%"
|
||||
query = query.filter(or_(
|
||||
TransferInvoiceItem.invoice_no.ilike(like),
|
||||
TransferInvoiceItem.material_no.ilike(like),
|
||||
TransferInvoiceItem.material_name.ilike(like),
|
||||
TransferInvoiceItem.source_code.ilike(like),
|
||||
))
|
||||
query = (
|
||||
query.outerjoin(
|
||||
TransferMovementLedger,
|
||||
TransferInvoiceItem.ledger_record_id == TransferMovementLedger.id,
|
||||
)
|
||||
.filter(or_(
|
||||
TransferInvoiceItem.invoice_no.ilike(like),
|
||||
TransferMovementLedger.external_doc_no.ilike(like),
|
||||
TransferInvoiceItem.material_no.ilike(like),
|
||||
TransferInvoiceItem.material_name.ilike(like),
|
||||
TransferInvoiceItem.source_code.ilike(like),
|
||||
))
|
||||
)
|
||||
return query
|
||||
|
||||
|
||||
@@ -266,6 +276,7 @@ def _backlog_dtos(rows: list[TransferInvoiceItem], current: datetime) -> list[Ba
|
||||
item_id=item.id,
|
||||
source_code=item.source_code,
|
||||
invoice_no=item.invoice_no,
|
||||
external_doc_no=ledger_external_doc_no(item),
|
||||
material_no=item.material_no,
|
||||
status=item.status,
|
||||
reason=item.result_message or item.result_code or "",
|
||||
@@ -303,7 +314,10 @@ def list_backlog(*, now: datetime | None = None, source_code: str | None = None)
|
||||
current = now or datetime.utcnow()
|
||||
rows = (
|
||||
_backlog_base_query(_ALL_BACKLOG_STATUSES, source_code=source_code)
|
||||
.options(joinedload(TransferInvoiceItem.matching))
|
||||
.options(
|
||||
joinedload(TransferInvoiceItem.matching),
|
||||
joinedload(TransferInvoiceItem.ledger_record),
|
||||
)
|
||||
.order_by(*_BACKLOG_ORDER_BY)
|
||||
.all()
|
||||
)
|
||||
@@ -330,7 +344,7 @@ def list_backlog_page(
|
||||
Args:
|
||||
now: 判定时刻(默认当前时间)。
|
||||
source_code: 可选来源过滤。
|
||||
keyword: 可选关键字(Invoice/料号/品名/来源,子串大小写不敏感)。
|
||||
keyword: 可选关键字(单号/外部单号/料号/品名/来源,子串大小写不敏感)。
|
||||
result_filter: 结果切片(all/recoverable/closed/unknown)。
|
||||
page: 页码(1 起)。
|
||||
page_size: 每页行数(1..100)。
|
||||
@@ -345,7 +359,10 @@ def list_backlog_page(
|
||||
base = _backlog_base_query(statuses, source_code=source_code, keyword=keyword or None)
|
||||
total = base.count()
|
||||
rows = (
|
||||
base.options(joinedload(TransferInvoiceItem.matching))
|
||||
base.options(
|
||||
joinedload(TransferInvoiceItem.matching),
|
||||
joinedload(TransferInvoiceItem.ledger_record),
|
||||
)
|
||||
.order_by(*_BACKLOG_ORDER_BY)
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
|
||||
@@ -124,6 +124,8 @@ class MatchingItemDTO:
|
||||
# 出生匹配快照上的调拨类型 code。可调拨明细跨类型混排时用来展示类别;
|
||||
# 无匹配或快照未写类型时为空串。
|
||||
transfer_type: str = ""
|
||||
# 档上的外部单号(WMS Order #)。空串表示这行没有外部单号。
|
||||
external_doc_no: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
||||
@@ -63,6 +63,7 @@ from app.services.in_transit_transfer.matching_service import (
|
||||
RouteMapping,
|
||||
TransferDeps,
|
||||
item_external_lot_no,
|
||||
ledger_external_doc_no,
|
||||
)
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
from app.services.in_transit_transfer.orchestrator import (
|
||||
@@ -805,12 +806,12 @@ def _build_order_lines(items: list[TransferInvoiceItem]) -> list[dict]:
|
||||
ERP 行粒度 = 物料+批号:同单同料号同批号跨 Invoice 聚合为一行,数量按
|
||||
Decimal 精确相加后取 6 位小数;客户端行数量为数值型(能力 Schema number,
|
||||
且须可 JSON 序列化进引擎审计),快照文本(6 位小数字符串)随 D14 留档。
|
||||
行内附带 invoice_no 溯源(逗号连接,供测试替身/排障;ERP 契约无此字段,
|
||||
真实绑定未映射即透传为惰性键)。
|
||||
行内附带 invoice_no 与 external_doc_no 溯源(各自逗号连接,供清单展示与排障;
|
||||
ERP 契约无这两字段,真实绑定未映射即透传为惰性键)。
|
||||
|
||||
Returns:
|
||||
行 dict 列表:line_no/material_no/from_warehouse/to_warehouse/lot_no/
|
||||
quantity/unit/invoice_no/quantity_text(quantity_text 仅供快照,调用方裁剪)。
|
||||
quantity/unit/invoice_no/external_doc_no/quantity_text(quantity_text 仅供快照,调用方裁剪)。
|
||||
"""
|
||||
grouped: dict[tuple[str, str, str, str], list[TransferInvoiceItem]] = {}
|
||||
for item in items:
|
||||
@@ -831,6 +832,9 @@ def _build_order_lines(items: list[TransferInvoiceItem]) -> list[dict]:
|
||||
quantity = total.quantize(_QUANTITY_QUANT)
|
||||
unit = next((str(item.unit or "").strip() for item in group if str(item.unit or "").strip()), "")
|
||||
invoices = ",".join(sorted({item.invoice_no for item in group}))
|
||||
external_docs = ",".join(sorted({
|
||||
doc for item in group if (doc := ledger_external_doc_no(item))
|
||||
}))
|
||||
lines.append({
|
||||
"line_no": index,
|
||||
"material_no": key[0],
|
||||
@@ -840,6 +844,7 @@ def _build_order_lines(items: list[TransferInvoiceItem]) -> list[dict]:
|
||||
"quantity": float(quantity),
|
||||
"unit": unit,
|
||||
"invoice_no": invoices,
|
||||
"external_doc_no": external_docs,
|
||||
"quantity_text": f"{quantity:.6f}",
|
||||
})
|
||||
return lines
|
||||
@@ -1273,6 +1278,7 @@ def _build_run_result(run: TransferRun) -> RunResultDTO:
|
||||
material_name=item.material_name,
|
||||
specification=item.specification,
|
||||
invoice_no=item.invoice_no,
|
||||
external_doc_no=ledger_external_doc_no(item),
|
||||
movement_date=item.movement_date,
|
||||
from_warehouse=item.from_warehouse,
|
||||
from_quantity=Decimal(item.external_quantity) if item.external_quantity else None,
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
movement_date 非空)+ 类型快照范围规则(apply_scope_filters 单一编译器)+
|
||||
未被有效 items 占用(D17:ledger_record_id 引用或同匹配 grain
|
||||
(source, invoice/doc_no, material, movement_date) 已被有效 item 占用;
|
||||
取消匹配即释放)。tt14 档自然键扩维后同 grain 可对应多条档(如 carton
|
||||
取消匹配即释放;ADR 0007 匹配顶替在圈档前取消被新范围盖住、尚未写 ERP 的旧匹配)。tt14 档自然键扩维后同 grain 可对应多条档(如 carton
|
||||
空→有值的重解析双行);出生前按 grain 择一建 item(不累加数量,防翻倍),
|
||||
占用亦按 grain 互斥。业务字段=档原值;仓库经 resolve_warehouse;库存评估
|
||||
链以 items 为工作单元。create_matching 先落 Run + Matching 再驱动管道。
|
||||
@@ -295,11 +295,12 @@ def _dedupe_ledger_records_for_item_birth(
|
||||
def _effective_occupancy_filter(*, exclude_matching_id: int | None = None):
|
||||
"""构造「未被有效 items 占用」(D17)的 NOT EXISTS 过滤(圈档互斥单一口径)。
|
||||
|
||||
占用定义(规格 §9 + grain 互斥):存在有效 item(所属匹配未取消、行非
|
||||
blocked_file_removed)且满足其一——(a) ledger_record_id 直指本档;
|
||||
(b) 与本档同匹配 grain(source/invoice=doc_no/material/movement_date)。
|
||||
(b) 覆盖 tt14 自然键扩维后同业务 grain 的镜像分叉档,避免待匹配桶与二次
|
||||
匹配仍圈到兄弟档。取消匹配即释放;人工关闭/成功终态不释放。
|
||||
占用定义(规格 §9 + grain 互斥 + ADR 0007):存在已挂上匹配的有效 item
|
||||
(所属匹配未取消,或该行是人工关闭;行非 blocked_file_removed)且满足其一
|
||||
——(a) ledger_record_id 直指本档;(b) 与本档同匹配 grain
|
||||
(source/invoice=doc_no/material/movement_date)。没有挂上匹配的明细不占用。
|
||||
(b) 覆盖 tt14 自然键扩维后同业务 grain 的镜像分叉档。取消匹配即释放,
|
||||
人工关闭除外;成功终态不释放。
|
||||
|
||||
Args:
|
||||
exclude_matching_id: 重查对账场景传入本匹配 id——本匹配自有 items 不构成
|
||||
@@ -308,9 +309,8 @@ def _effective_occupancy_filter(*, exclude_matching_id: int | None = None):
|
||||
SQLAlchemy NOT EXISTS 子句(作用于 TransferMovementLedger 查询)。
|
||||
"""
|
||||
# material_code 可空:COALESCE 与出生侧 ``material_code or ""`` 对齐。
|
||||
# grain 互斥只认「已绑定未取消匹配」的行——出生翻转前 matching_id=NULL 的
|
||||
# 历史孤儿行不得按 grain 封死整票待匹配(本地曾因此从 ~2k 掉到 5)。
|
||||
# ledger_record_id 直指占用仍含 NULL 归属行(保持 D17 原口径)。
|
||||
# 【ADR 0007】没有挂上匹配的明细不占货(直指与 grain 都不算)。
|
||||
# 人工关闭在所属匹配被顶替之后仍然占用。
|
||||
grain_match = and_(
|
||||
TransferInvoiceItem.matching_id.isnot(None),
|
||||
TransferInvoiceItem.source_code == TransferMovementLedger.source_code,
|
||||
@@ -328,17 +328,21 @@ def _effective_occupancy_filter(*, exclude_matching_id: int | None = None):
|
||||
TransferInvoiceItem.result_code != RESULT_FILE_REMOVED),
|
||||
]
|
||||
if exclude_matching_id is None:
|
||||
# 匹配创建:任何未取消匹配(含无归属的历史行)的有效引用都算占用。
|
||||
# 匹配创建:必须已挂上匹配。未取消的匹配占用;人工关闭在匹配被顶替后仍占用。
|
||||
item_conditions.append(TransferInvoiceItem.matching_id.isnot(None))
|
||||
item_conditions.append(or_(
|
||||
TransferInvoiceItem.matching_id.is_(None),
|
||||
TransferMatching.status != _MATCHING_STATUS_CANCELLED,
|
||||
TransferInvoiceItem.status == status_machine.TransferStatus.MANUALLY_CLOSED.value,
|
||||
))
|
||||
else:
|
||||
# 重查对账:仅「其他匹配」的有效引用算占用(本匹配自有 items 允许刷新)。
|
||||
item_conditions.append(and_(
|
||||
TransferInvoiceItem.matching_id.isnot(None),
|
||||
TransferInvoiceItem.matching_id != exclude_matching_id,
|
||||
TransferMatching.status != _MATCHING_STATUS_CANCELLED,
|
||||
or_(
|
||||
TransferMatching.status != _MATCHING_STATUS_CANCELLED,
|
||||
TransferInvoiceItem.status == status_machine.TransferStatus.MANUALLY_CLOSED.value,
|
||||
),
|
||||
))
|
||||
occupancy = (
|
||||
db.session.query(TransferInvoiceItem.id)
|
||||
@@ -611,6 +615,23 @@ def matching_transform_rules(matching: TransferMatching) -> tuple[TransformRule,
|
||||
return parse_transform_rules(scope.get("transform_rules"))
|
||||
|
||||
|
||||
def ledger_external_doc_no(item: TransferInvoiceItem) -> str:
|
||||
"""读取明细行对应异动档上的外部单号。
|
||||
|
||||
核心逻辑:外部单号只在档上(WMS Order #),明细行经 ledger_record_id 指向档。
|
||||
没有档、或档上为空时返回空串,列表显示占位。
|
||||
|
||||
Args:
|
||||
item: 明细行。ledger_record 可已预加载;未预加载时按外键懒加载。
|
||||
Returns:
|
||||
外部单号;没有则空串。
|
||||
"""
|
||||
record = item.ledger_record
|
||||
if record is None:
|
||||
return ""
|
||||
return str(record.external_doc_no or "").strip()
|
||||
|
||||
|
||||
def item_external_lot_no(item: TransferInvoiceItem) -> str:
|
||||
"""行批号的外部形态派生(按行所属匹配快照的转换规则;无规则=恒等)。
|
||||
|
||||
@@ -1242,6 +1263,116 @@ def _item_evaluated_sha(item: TransferInvoiceItem) -> str | None:
|
||||
return lines[0].get("file_sha256")
|
||||
|
||||
|
||||
def _source_set(codes: list[str] | None) -> tuple[str, ...]:
|
||||
"""把来源编码收成可比较的集合。
|
||||
|
||||
核心逻辑:去掉空白后排序,使 [B, A] 与 [A, B] 视为同一组来源。
|
||||
Args:
|
||||
codes: 来源编码列表;None 当空。
|
||||
Returns:
|
||||
排序后的来源编码元组。
|
||||
"""
|
||||
return tuple(sorted(str(code).strip() for code in (codes or []) if str(code).strip()))
|
||||
|
||||
|
||||
def _date_range_covers(new_from: str | None, new_to: str | None, old_from: str | None, old_to: str | None) -> bool:
|
||||
"""新异动日期范围是否把旧范围整个盖住。
|
||||
|
||||
核心逻辑:任一侧缺少起或止,都视为没盖住(无日期范围的旧匹配不被顶替)。
|
||||
日期是 YYYY-MM-DD,字符串序与日历序一致。
|
||||
Args:
|
||||
new_from / new_to: 本次匹配的异动日期起止。
|
||||
old_from / old_to: 旧匹配快照上的异动日期起止。
|
||||
Returns:
|
||||
新范围包含旧范围时为 True。
|
||||
"""
|
||||
if not new_from or not new_to or not old_from or not old_to:
|
||||
return False
|
||||
return str(new_from) <= str(old_from) and str(new_to) >= str(old_to)
|
||||
|
||||
|
||||
def _matching_has_erp_activity(items: list[TransferInvoiceItem]) -> bool:
|
||||
"""匹配是否已经写出单据,或有行正在写、结果未知。
|
||||
|
||||
核心逻辑:有外部单号,或行状态为执行中、结果未知、成功,就不顶替,
|
||||
避免把在途 ERP 写入拆成两张单。
|
||||
Args:
|
||||
items: 该匹配名下的明细。
|
||||
Returns:
|
||||
存在上述活动时为 True。
|
||||
"""
|
||||
active = {
|
||||
status_machine.TransferStatus.EXECUTING.value,
|
||||
status_machine.TransferStatus.RESULT_UNKNOWN.value,
|
||||
status_machine.TransferStatus.SUCCESS.value,
|
||||
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
|
||||
}
|
||||
return any(
|
||||
(item.external_document_no or "").strip() or item.status in active
|
||||
for item in items
|
||||
)
|
||||
|
||||
|
||||
def _supersede_covered_matchings(
|
||||
*,
|
||||
transfer_type: str,
|
||||
source_codes: list[str],
|
||||
movement_date_from: str | None,
|
||||
movement_date_to: str | None,
|
||||
exclude_matching_id: int,
|
||||
) -> None:
|
||||
"""圈档前顶替被新范围盖住、尚未写 ERP 的旧匹配(ADR 0007)。
|
||||
|
||||
核心逻辑:同一调拨类型、同一组来源、旧日期范围被新范围整个盖住,且名下没有
|
||||
ERP 单据、没有正在写或结果未知的行,则匹配改为 cancelled,名下明细一并取消。
|
||||
盖不住或已在写 ERP 的旧匹配保持原样,清单不列举它们的编号。
|
||||
|
||||
Args:
|
||||
transfer_type: 本次匹配的调拨类型编码。
|
||||
source_codes: 本次来源集合。
|
||||
movement_date_from / movement_date_to: 本次异动日期范围;缺一则不顶替任何人。
|
||||
exclude_matching_id: 刚落库、尚未圈档的本次匹配,不能把自己顶掉。
|
||||
"""
|
||||
new_sources = _source_set(source_codes)
|
||||
if not new_sources:
|
||||
return
|
||||
candidates = (
|
||||
TransferMatching.query
|
||||
.filter(TransferMatching.id != exclude_matching_id)
|
||||
.filter(TransferMatching.status != _MATCHING_STATUS_CANCELLED)
|
||||
.all()
|
||||
)
|
||||
for matching in candidates:
|
||||
scope = matching.scope_json if isinstance(matching.scope_json, dict) else {}
|
||||
if str(scope.get("transfer_type") or "") != transfer_type:
|
||||
continue
|
||||
if _source_set(scope.get("source_codes")) != new_sources:
|
||||
continue
|
||||
items = TransferInvoiceItem.query.filter_by(matching_id=matching.id).all()
|
||||
covered = _date_range_covers(
|
||||
movement_date_from,
|
||||
movement_date_to,
|
||||
scope.get("movement_date_from"),
|
||||
scope.get("movement_date_to"),
|
||||
)
|
||||
# 匹配状态 success 只表示没有可执行行(全阻断也会落成 success),
|
||||
# 不能当成已经写出 ERP。是否写过只看行上的单据号和执行状态。
|
||||
if (
|
||||
not covered
|
||||
or matching.status == status_machine.TransferStatus.EXECUTING.value
|
||||
or _matching_has_erp_activity(items)
|
||||
):
|
||||
continue
|
||||
matching.status = _MATCHING_STATUS_CANCELLED
|
||||
for item in items:
|
||||
# 人工关闭是仓库人员的裁定,顶替不把它改回可圈状态。
|
||||
if item.status == status_machine.TransferStatus.MANUALLY_CLOSED.value:
|
||||
continue
|
||||
item.status = status_machine.TransferStatus.CANCELLED.value
|
||||
item.result_code = "cancelled"
|
||||
item.result_message = "superseded by a new matching"
|
||||
|
||||
|
||||
def create_matching(
|
||||
*,
|
||||
source_codes: list[str],
|
||||
@@ -1259,6 +1390,7 @@ def create_matching(
|
||||
管道回写 status/counts/estimated/hash 后随主事务统一提交。类型必填且配置
|
||||
驱动(REQUIRED/NOT_CONFIGURED/DISABLED fail-closed,D8)。圈档记录类型由
|
||||
run_matching 对已加载的 scope_rules 调用 record_kinds_of,不再写死入站。
|
||||
【ADR 0007】圈档前顶替被本次日期范围盖住、尚未写 ERP 的同类型同来源旧匹配。
|
||||
|
||||
Args:
|
||||
source_codes / business_date / deps: 同 run_matching。
|
||||
@@ -1299,6 +1431,14 @@ def create_matching(
|
||||
)
|
||||
db.session.add(matching)
|
||||
db.session.flush()
|
||||
# [ADR 0007] 先释放被盖住的旧匹配,本次圈档才能看到那批货。
|
||||
_supersede_covered_matchings(
|
||||
transfer_type=config.code,
|
||||
source_codes=list(source_codes),
|
||||
movement_date_from=movement_date_from,
|
||||
movement_date_to=movement_date_to,
|
||||
exclude_matching_id=matching.id,
|
||||
)
|
||||
|
||||
result = run_matching(
|
||||
source_codes=source_codes,
|
||||
@@ -1404,6 +1544,7 @@ def restore_matching(
|
||||
# 同口径(2026-09-29 统一),同一批行在匹配卡/可调拨明细/待处理池顺序一致。
|
||||
rows_all = (
|
||||
TransferInvoiceItem.query
|
||||
.options(joinedload(TransferInvoiceItem.ledger_record))
|
||||
.filter(TransferInvoiceItem.matching_id == matching.id)
|
||||
.order_by(
|
||||
TransferInvoiceItem.movement_date.asc().nulls_last(),
|
||||
@@ -1531,6 +1672,7 @@ def _item_dto(
|
||||
material_name=item.material_name,
|
||||
specification=item.specification,
|
||||
invoice_no=item.invoice_no,
|
||||
external_doc_no=ledger_external_doc_no(item),
|
||||
movement_date=item.movement_date,
|
||||
lot_no=item.lot_no or "",
|
||||
movement_warehouse_code=item.movement_warehouse_code or "",
|
||||
@@ -1600,7 +1742,10 @@ def list_executable_items(*, deps: TransferDeps | None = None, now: datetime | N
|
||||
# 2026-09-29 与待处理池/匹配卡视图统一为同一口径(用户按同序处理两个池子)。
|
||||
rows = (
|
||||
TransferInvoiceItem.query
|
||||
.options(joinedload(TransferInvoiceItem.matching))
|
||||
.options(
|
||||
joinedload(TransferInvoiceItem.matching),
|
||||
joinedload(TransferInvoiceItem.ledger_record),
|
||||
)
|
||||
# [防御性双保险] 所属匹配已取消的行不入队:取消路径已把匹配名下 ready
|
||||
# 行退役为 cancelled(cancellation.py),此处按匹配状态再拒一次——
|
||||
# 防绕过取消路径的状态组合(如手工改库/历史数据)产生可执行行。
|
||||
|
||||
@@ -12,7 +12,10 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.in_transit_transfer.matching_service import item_external_lot_no
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
item_external_lot_no,
|
||||
ledger_external_doc_no,
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 单状态 → 展示分组映射(Task 17:首页「已执行」区块统计口径)
|
||||
@@ -71,6 +74,7 @@ def serialize_item(item) -> dict[str, Any]:
|
||||
"material_name": item.material_name,
|
||||
"specification": item.specification,
|
||||
"invoice_no": item.invoice_no,
|
||||
"external_doc_no": getattr(item, "external_doc_no", "") or "",
|
||||
"lot_no": item.lot_no,
|
||||
"movement_date": item.movement_date,
|
||||
"from_warehouse": item.from_warehouse,
|
||||
@@ -177,6 +181,7 @@ def serialize_order(doc, items: list) -> dict[str, Any]:
|
||||
# 行级溯源来源单号(2026-09-29 契约扩充,随 ERP 写入行同款口径
|
||||
# 透传):业务上一行恒对应一张 invoice,前端明细表首列展示。
|
||||
"invoice_no": line["invoice_no"],
|
||||
"external_doc_no": line.get("external_doc_no") or "",
|
||||
"material_no": line["material_no"],
|
||||
"material_name": name_by_key.get(
|
||||
(line["material_no"], line["lot_no"],
|
||||
@@ -222,6 +227,7 @@ def serialize_executed_order(doc, items: list) -> dict[str, Any]:
|
||||
"items": [
|
||||
{
|
||||
"invoice_no": item.invoice_no,
|
||||
"external_doc_no": ledger_external_doc_no(item),
|
||||
"material_no": item.material_no,
|
||||
"material_name": item.material_name,
|
||||
# 批号保持文件证据原形态(raw 原则);展示侧拨出批号由前端
|
||||
|
||||
@@ -4,10 +4,11 @@
|
||||
按来源实例与记录类型投影"是否有 ready 文件 / 是否抓取中 / 是否失败 /
|
||||
是否解析失败 / 无文件待触发 / 出站未配置",供 /sources 接口与前端门禁使用。
|
||||
调拨不维护独立抓取状态表(低耦合)。
|
||||
依赖:freight_rpa.reports.queries(入站最新可用归档 / 失效存在性 /
|
||||
get_outbound_config,以及解析失败标记的只读写入口);入站与出站执行单元行、
|
||||
出站归档文件模型;date_policy.business_date_utc_window(出站文件新鲜度与
|
||||
入站可用条件同口径)。
|
||||
依赖:freight_rpa.reports.queries(入站可用归档批量/单来源读取、失效来源存在性、
|
||||
get_outbound_config、解析失败标记只读写入口;入站归档文件模型不直连——
|
||||
阶段 B Task 4 边界);入站/出站执行单元行与出站归档文件、出站报表配置模型
|
||||
(出站证据轴 2026-10-22 起直连读取,不在边界禁列);
|
||||
date_policy.business_date_utc_window(出站文件新鲜度与入站可用条件同口径)。
|
||||
逻辑:resolve_source_file_status 按 record_kind 分流,缺省 inbound,既有调用方
|
||||
不传记录类型时返回值不变。入站顺序:可用文件 → ready,但 parse_failed_at
|
||||
非空 → parse_failed;进行中单元 → fetching;最新单元空数据 → no_data;
|
||||
@@ -28,10 +29,9 @@ from typing import Any, Callable
|
||||
from sqlalchemy import and_, not_, or_
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.models.freight_rpa_inbound_report import (
|
||||
FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun,
|
||||
)
|
||||
# 入站归档文件模型归 freight_rpa 域读写(阶段 B Task 4 边界),批量/单来源读取
|
||||
# 一律经 queries 只读函数;入站执行单元模型不在禁列(状态投影按 status 消费)。
|
||||
from app.models.freight_rpa_inbound_report import FreightRpaInboundUnitRun
|
||||
from app.models.freight_rpa_outbound_report import (
|
||||
FreightRpaOutboundReportConfig,
|
||||
FreightRpaOutboundReportFile,
|
||||
@@ -39,12 +39,12 @@ from app.models.freight_rpa_outbound_report import (
|
||||
)
|
||||
from app.services.freight_rpa.reports.queries import (
|
||||
clear_inbound_parse_failure as _clear_parse_failure_by_id,
|
||||
expired_inbound_file_condition,
|
||||
expired_inbound_source_codes,
|
||||
get_outbound_config,
|
||||
has_expired_inbound_file,
|
||||
latest_usable_inbound_file,
|
||||
latest_usable_inbound_files_by_source,
|
||||
mark_inbound_parse_failure as _mark_parse_failure_by_id,
|
||||
usable_inbound_file_condition,
|
||||
)
|
||||
from app.services.in_transit_transfer.date_policy import business_date_utc_window
|
||||
|
||||
@@ -288,13 +288,13 @@ def _project_file_status(
|
||||
|
||||
|
||||
def _latest_files_by_source(file_model: type, unit_model: type, source_ids: list[int], *filters: Any) -> dict[str, _FileFact]:
|
||||
"""一次取出这批来源各自最新的可用归档。
|
||||
"""一次取出这批来源各自最新的可用出站归档(入站批查已下沉 queries 层)。
|
||||
|
||||
核心逻辑:按来源主键过滤后按创建时间、文件主键倒序,每个来源只留第一条。
|
||||
只取状态判断用到的列,不加载执行单元上的 JSON 快照。
|
||||
|
||||
Args:
|
||||
file_model: 入站或出站归档文件模型。
|
||||
file_model: 出站归档文件模型。
|
||||
unit_model: 对应的执行单元模型,用来按 source_id 过滤。
|
||||
source_ids: 要投影的来源主键。
|
||||
filters: 可用文件条件(未删除、当天业务日、未过保留期)。
|
||||
@@ -359,13 +359,13 @@ def _units_by_source(unit_model: type, source_ids: list[int]) -> tuple[dict[str,
|
||||
|
||||
|
||||
def _expired_source_codes(file_model: type, unit_model: type, source_ids: list[int], *filters: Any) -> set[str]:
|
||||
"""一次找出仍有失效未清理归档的来源编码。
|
||||
"""一次找出仍有失效未清理出站归档的来源编码(入站批查已下沉 queries 层)。
|
||||
|
||||
核心逻辑:只判断存在性,不取文件内容。失效条件由调用方传入,与单来源
|
||||
has_expired_* 使用同一套未删除且不满足新鲜度/保留期的口径。
|
||||
|
||||
Args:
|
||||
file_model: 入站或出站归档文件模型。
|
||||
file_model: 出站归档文件模型。
|
||||
unit_model: 对应的执行单元模型。
|
||||
source_ids: 要投影的来源主键。
|
||||
filters: 失效文件条件。
|
||||
@@ -412,19 +412,17 @@ def resolve_source_file_statuses(sources: list[Any]) -> dict[str, dict[str, dict
|
||||
.all()
|
||||
)
|
||||
}
|
||||
inbound_files = _latest_files_by_source(
|
||||
FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun,
|
||||
source_ids,
|
||||
usable_inbound_file_condition(now=now),
|
||||
)
|
||||
inbound_files = {
|
||||
code: _FileFact(
|
||||
file_id=view.file_id,
|
||||
original_filename=view.original_filename,
|
||||
sha256=view.sha256,
|
||||
parse_failed_at=view.parse_failed_at,
|
||||
)
|
||||
for code, view in latest_usable_inbound_files_by_source(source_ids, now=now).items()
|
||||
}
|
||||
inbound_latest, inbound_active = _units_by_source(FreightRpaInboundUnitRun, source_ids)
|
||||
inbound_expired = _expired_source_codes(
|
||||
FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun,
|
||||
source_ids,
|
||||
expired_inbound_file_condition(now=now),
|
||||
)
|
||||
inbound_expired = expired_inbound_source_codes(source_ids, now=now)
|
||||
outbound_files = _latest_files_by_source(
|
||||
FreightRpaOutboundReportFile,
|
||||
FreightRpaOutboundUnitRun,
|
||||
|
||||
@@ -2,18 +2,24 @@
|
||||
|
||||
用途:自动处理可调拨异动与历史可恢复异常;执行结果通知统一走
|
||||
排程「启用通知」通用企微通知,本任务不自建领域通知。
|
||||
依赖:auto_transfer、transfer deps、job_registry.ScheduleExecuteResult、
|
||||
依赖:auto_transfer、recovery_service、transfer deps、job_registry.ScheduleExecuteResult、
|
||||
inbound_trigger_service.list_inbound_capable_source_codes(缺省来源口径)、
|
||||
transfer_type_config_service.get_enabled(缺省类型口径)、
|
||||
date_policy(业务日与日期解析)。
|
||||
逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发入站 RPA),
|
||||
不依赖其他排程成功;来源留空兜底为全部启用入站来源;可选异动日期范围
|
||||
不依赖其他排程成功;来源留空兜底为全部启用入站来源;【调拨类型 2026-10-23】
|
||||
job_params.transfer_types 为 multi_select,留空=全部启用中的类型配置,
|
||||
按类型逐轮 run_auto_transfer(恢复复核与类型无关,循环外只跑一次);
|
||||
类型配置为空/读取失败 fail-closed 硬失败,不静默跳过;可选异动日期范围
|
||||
以「T−N 偏移天数」配置,执行时按当日业务日换算为具体日期透传匹配层——
|
||||
该偏移参数是自动处理面的唯一日期边界;【T−2 成熟封顶 2026-10-21】引擎
|
||||
只圈 movement_date ≤ T−2 的成熟记录(T−2 之前数据全部成熟),未配置
|
||||
偏移即处理全部成熟积压;偏移终点落在 T−1/当天(0/1)会被匹配层
|
||||
MOVEMENT_DATE_RANGE_INVALID 拒绝(快速失败交框架通知);空数据日(无
|
||||
run_no 且无 errors)置 domain_notification_managed 保持静默(C5),有
|
||||
Run 或硬失败交由框架完成卡按排程「启用通知」发送。
|
||||
MOVEMENT_DATE_RANGE_INVALID 拒绝(快速失败交框架通知);空数据日(全部
|
||||
类型均无 run_no 且无 errors)置 domain_notification_managed 保持静默
|
||||
(C5),有 Run 或硬失败交由框架完成卡按排程「启用通知」发送。
|
||||
返回:七元组位序=(total, success, failed, skipped, details, errors, step_logs),
|
||||
warnings 无对应槽位——恢复/来源汇总写 step_logs(dict),不得挤占 errors 位。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -21,11 +27,13 @@ from __future__ import annotations
|
||||
from datetime import timedelta
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome, run_auto_transfer
|
||||
from app.services.in_transit_transfer.auto_transfer import run_auto_transfer
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now, parse_date
|
||||
from app.services.in_transit_transfer.inbound_trigger_service import list_inbound_capable_source_codes
|
||||
from app.services.in_transit_transfer.recovery_service import RecoveryOutcome, run_daily_recovery
|
||||
from app.services.schedule.job_registry import ScheduleExecuteResult
|
||||
|
||||
|
||||
@@ -52,6 +60,33 @@ def _wanted_source_codes(task: ScheduleTask) -> list[str]:
|
||||
return codes
|
||||
|
||||
|
||||
def _wanted_transfer_types(params: dict[str, Any], errors: list[str]) -> list[str]:
|
||||
"""提取结构化 transfer_types;留空回落为全部启用中的类型配置(fail-closed)。
|
||||
|
||||
Args:
|
||||
params: 排程结构化参数(job_params.transfer_types 可为列表/字符串/缺省)。
|
||||
errors: 错误累积列表(类型配置读取失败/为空时写入,由调用方硬失败)。
|
||||
Returns:
|
||||
去空白后的类型编码列表;配置为空或脏配置读取失败时为空列表(已落错误)。
|
||||
"""
|
||||
values = params.get("transfer_types") or []
|
||||
if isinstance(values, str):
|
||||
values = [values]
|
||||
codes = [str(item).strip() for item in values if str(item).strip()]
|
||||
if codes:
|
||||
return codes
|
||||
from app.services.in_transit_transfer.transfer_type_config_service import get_enabled
|
||||
|
||||
try:
|
||||
codes = [dto.code for dto in get_enabled()]
|
||||
except AppError as exc:
|
||||
errors.append(f"调拨类型配置读取失败: {exc}")
|
||||
return []
|
||||
if not codes:
|
||||
errors.append("无启用中的调拨类型配置(须先在管理端调拨类型页创建并启用)")
|
||||
return codes
|
||||
|
||||
|
||||
def _offset_to_date(business_date: str, offset_days: Any, label: str, errors: list[str]) -> str | None:
|
||||
"""把「T−N 偏移天数」参数换算为执行日口径的具体异动日期(T−N)。
|
||||
|
||||
@@ -77,12 +112,14 @@ def _offset_to_date(business_date: str, offset_days: Any, label: str, errors: li
|
||||
|
||||
|
||||
def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""自动调拨:恢复 + 匹配(严格相等)+ 执行;通知统一走排程「启用通知」。
|
||||
"""自动调拨:恢复(一次)→ 按类型逐轮「匹配(严格相等)+ 执行」;通知走排程「启用通知」。
|
||||
|
||||
核心逻辑:不自建领域汇总通知(任务级通知人参数已移除,收件人取排程表单
|
||||
底部「启用通知」配置);仅在空数据日(无 run_no 且无 errors)置
|
||||
domain_notification_managed 抑制框架完成卡(C5 空数据日静默);
|
||||
有 run_no(成功/部分失败)或硬失败时框架卡照常发送/兜底。
|
||||
核心逻辑:不自建领域汇总通知(收件人取排程表单底部「启用通知」配置);
|
||||
仅在空数据日(全部类型均无 run_no 且无 errors)置 domain_notification_managed
|
||||
抑制框架完成卡(C5 空数据日静默);有 run_no 或硬失败时框架卡照常发送/兜底。
|
||||
调拨类型留空=全部启用类型逐轮执行(D8:类型=平台配置,排程不隐式假设单一
|
||||
类型;配置为空/读取失败 fail-closed 硬失败);历史恢复与类型无关,循环外
|
||||
只跑一次(重复恢复会对同一批行重复建 Attempt 并重复外部查询)。
|
||||
可选异动日期范围以「T−N 偏移天数」配置(receipt_from/to_offset_days),
|
||||
执行时按当日业务日换算为具体日期透传匹配层,供测试/排障缩小本轮处理面;
|
||||
【T−2 成熟封顶 2026-10-21】引擎只圈 ≤T−2 成熟记录,未配置偏移即处理全部
|
||||
@@ -90,7 +127,7 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
|
||||
硬失败路径;偏移非法(负数/小数/非数字)同样快速失败不执行。
|
||||
|
||||
Args:
|
||||
task: 排程任务(job_params: source_codes/recover_history/
|
||||
task: 排程任务(job_params: transfer_types/source_codes/recover_history/
|
||||
receipt_from_offset_days/receipt_to_offset_days)。
|
||||
run: 排程执行批次(空数据日写入 response_summary_json 标记)。
|
||||
Returns:
|
||||
@@ -101,60 +138,99 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
|
||||
recover_history = bool(params.get("recover_history", True))
|
||||
business_date = str(business_date_now())
|
||||
|
||||
# [STEP] T−N 偏移换算:非法配置快速失败(不执行、交框架失败通知),
|
||||
# 防止坏参数被静默忽略后退化成全量积压处理。
|
||||
param_errors: list[str] = []
|
||||
# [STEP 1] 配置解析与 T−N 偏移换算:非法配置快速失败(不执行、交框架失败通知),
|
||||
# 防止坏参数被静默忽略后退化成全量积压处理。硬失败以 failed_count=1 落终态
|
||||
# failed(total=0 且 errors 非空会被框架判 success「无待处理数据」,不可用)。
|
||||
errors: list[str] = []
|
||||
transfer_types = _wanted_transfer_types(params, errors)
|
||||
movement_date_from = _offset_to_date(
|
||||
business_date, params.get("receipt_from_offset_days"), "异动日期起点", param_errors)
|
||||
business_date, params.get("receipt_from_offset_days"), "异动日期起点", errors)
|
||||
movement_date_to = _offset_to_date(
|
||||
business_date, params.get("receipt_to_offset_days"), "异动日期终点", param_errors)
|
||||
if param_errors:
|
||||
return (0, 0, 0, 0, [], [f"sources={len(source_codes)}"], param_errors)
|
||||
business_date, params.get("receipt_to_offset_days"), "异动日期终点", errors)
|
||||
if errors:
|
||||
return (1, 0, 1, 0, [], errors, [
|
||||
{"step": "config", "status": "failed", "detail": f"sources={len(source_codes)}"},
|
||||
])
|
||||
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
# [出生翻转 2026-10-14] 调拨类型配置化(D8 匹配创建必填):排程参数
|
||||
# job_params.transfer_type 承载类型编码,原样透传匹配层;缺省 None 时
|
||||
# 匹配层 fail-closed(TRANSFER_TYPE_REQUIRED 随 errors 硬失败透出),
|
||||
# 不回落固定类型(类型=平台配置,排程不隐式假设)。
|
||||
transfer_type = str(params.get("transfer_type") or "").strip() or None
|
||||
outcome = run_auto_transfer(
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
source_codes=source_codes,
|
||||
recover_history=recover_history,
|
||||
movement_date_from=movement_date_from,
|
||||
movement_date_to=movement_date_to,
|
||||
transfer_type=transfer_type,
|
||||
)
|
||||
|
||||
# [STEP] 空数据日静默门禁:无 run 且无错误(匹配后无可执行行,C5)时置
|
||||
# 标记抑制框架完成卡;有 run 或硬失败时框架卡照常通知/兜底。
|
||||
if not outcome.run_no and not outcome.errors:
|
||||
# [STEP 2] 恢复复核只跑一次:扫全部 blocked_recoverable 行(与类型无关),
|
||||
# result_unknown / manually_closed 在服务内只读隔离/永久排除。恢复失败计一个
|
||||
# failed 单元——否则「恢复失败+各类型均空数据日」total=0 会被框架判 success。
|
||||
recovery = RecoveryOutcome()
|
||||
recovery_failed = False
|
||||
if recover_history:
|
||||
try:
|
||||
recovery = run_daily_recovery(business_date=business_date, deps=deps)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
recovery_failed = True
|
||||
errors.append(f"recovery_failed: {exc}")
|
||||
step_logs: list[dict[str, Any]] = [{
|
||||
"step": "recovery",
|
||||
"status": "failed" if recovery_failed else ("success" if recover_history else "skipped"),
|
||||
"detail": {
|
||||
"recovered": recovery.recovered_count,
|
||||
"still_blocked": recovery.still_blocked_count,
|
||||
"skipped_result_unknown": recovery.skipped_result_unknown,
|
||||
"skipped_manually_closed": recovery.skipped_manually_closed,
|
||||
},
|
||||
}]
|
||||
failed_units = 1 if recovery_failed else 0
|
||||
|
||||
# [STEP 3] 按类型逐轮自动调拨:单类型失败不阻断其余类型(run_auto_transfer
|
||||
# 内部捕获进 outcome.errors)。
|
||||
results: list[dict[str, Any]] = []
|
||||
success_runs = 0
|
||||
failed_runs = 0
|
||||
for code in transfer_types:
|
||||
outcome = run_auto_transfer(
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
source_codes=source_codes,
|
||||
recover_history=False,
|
||||
movement_date_from=movement_date_from,
|
||||
movement_date_to=movement_date_to,
|
||||
transfer_type=code,
|
||||
)
|
||||
errors.extend(outcome.errors)
|
||||
if outcome.run_no:
|
||||
results.append({
|
||||
"transfer_type": code,
|
||||
"run_no": outcome.run_no,
|
||||
"status": outcome.run_status,
|
||||
})
|
||||
if outcome.run_status in {"success", "partial_failed"}:
|
||||
success_runs += 1
|
||||
else:
|
||||
failed_runs += 1
|
||||
elif outcome.errors:
|
||||
failed_runs += 1
|
||||
|
||||
# [STEP 4] 空数据日静默门禁:全部类型均无 run 且无错误(C5)时置标记抑制
|
||||
# 框架完成卡;有 run 或硬失败时框架卡照常通知/兜底。
|
||||
if not results and not errors:
|
||||
run.response_summary_json = {
|
||||
**(run.response_summary_json or {}),
|
||||
"domain_notification_managed": True,
|
||||
}
|
||||
results: list[dict[str, Any]] = []
|
||||
errors: list[str] = list(outcome.errors)
|
||||
recovery = outcome.recovery
|
||||
warnings: list[str] = [
|
||||
f"sources={len(source_codes)} recovered={recovery.recovered_count} still_blocked={recovery.still_blocked_count}",
|
||||
]
|
||||
if outcome.run_no:
|
||||
results.append({
|
||||
"run_no": outcome.run_no,
|
||||
"status": outcome.run_status,
|
||||
step_logs.append({
|
||||
"step": "auto_transfer", "status": "skipped",
|
||||
"detail": "no executable items; execution and notification skipped",
|
||||
})
|
||||
elif not outcome.errors:
|
||||
# 空数据日:匹配后无可执行行,执行与通知按 C5 跳过,不记失败。
|
||||
warnings.append("no executable items; execution and notification skipped")
|
||||
success = 1 if outcome.run_status in {"success", "partial_failed"} else 0
|
||||
|
||||
summary_text = (
|
||||
f"sources={len(source_codes)} types={len(transfer_types)} "
|
||||
f"runs={len(results)} recovered={recovery.recovered_count} "
|
||||
f"still_blocked={recovery.still_blocked_count}"
|
||||
)
|
||||
return (
|
||||
success + recovery.recovered_count,
|
||||
success,
|
||||
recovery.still_blocked_count,
|
||||
success_runs + failed_runs + recovery.recovered_count + failed_units,
|
||||
success_runs,
|
||||
failed_runs + failed_units + recovery.still_blocked_count,
|
||||
0,
|
||||
results,
|
||||
warnings,
|
||||
errors,
|
||||
step_logs + [
|
||||
{"step": "summary", "status": "failed" if errors else "success", "detail": summary_text},
|
||||
],
|
||||
)
|
||||
@@ -5,7 +5,8 @@ backend/app/services/schedule/job_options.py
|
||||
依赖:models.Agent、shipping_notice.onhand_source_repository。
|
||||
逻辑:api/schedule/platform_tasks.py options 接口与 job_params 选项范围校验调用;
|
||||
前端只认识 options_source 字符串,不感知数据来自哪张表/哪个配置文件。
|
||||
货代 RPA 注册键为 freight_rpa_sources、freight_rpa_inbound_sources 与 freight_rpa_outbound_sources。
|
||||
货代 RPA 注册键为 freight_rpa_sources、freight_rpa_inbound_sources 与 freight_rpa_outbound_sources;
|
||||
在途调拨注册键为 transfer_types(启用中的调拨类型配置)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -78,6 +79,20 @@ def _freight_rpa_outbound_sources_options() -> list[dict[str, Any]]:
|
||||
} for source, _config in rows]
|
||||
|
||||
|
||||
def _transfer_types_options() -> list[dict[str, Any]]:
|
||||
"""启用中的调拨类型(value=类型编码;供在途自动调拨排程选类型,留空=全部)。"""
|
||||
from app.services.in_transit_transfer.transfer_type_config_service import get_enabled
|
||||
|
||||
return [
|
||||
{
|
||||
"label": (dto.names or {}).get("zh-CN") or dto.code,
|
||||
"value": dto.code,
|
||||
"description": dto.description or None,
|
||||
}
|
||||
for dto in get_enabled()
|
||||
]
|
||||
|
||||
|
||||
def _hxops_users_options() -> list[dict[str, Any]]:
|
||||
"""全部启用用户(value=users.id);订单交期回复未回复提醒收件人等场景用。"""
|
||||
from app.models import User
|
||||
@@ -118,6 +133,7 @@ _OPTIONS_PROVIDERS: dict[str, Callable[[], list[dict[str, Any]]]] = {
|
||||
"freight_rpa_sources": _freight_rpa_sources_options,
|
||||
"freight_rpa_inbound_sources": _freight_rpa_inbound_sources_options,
|
||||
"freight_rpa_outbound_sources": _freight_rpa_outbound_sources_options,
|
||||
"transfer_types": _transfer_types_options,
|
||||
"hxops_users": _hxops_users_options,
|
||||
"users": _users_options,
|
||||
}
|
||||
|
||||
@@ -606,10 +606,21 @@ def _register_builtin_platform_jobs() -> None:
|
||||
handler=run_in_transit_transfer_schedule,
|
||||
description=(
|
||||
"自动匹配可调拨项并生成 ERP 调拨单,含历史可恢复异常复核;"
|
||||
"缺收料文件时自动触发收料 RPA。执行时间建议配置在期望调拨时点之前。"
|
||||
"缺收料文件时自动触发收料 RPA。调拨类型留空=全部启用类型逐轮执行。"
|
||||
"执行时间建议配置在期望调拨时点之前。"
|
||||
),
|
||||
category="platform",
|
||||
params_schema=(
|
||||
{
|
||||
"key": "transfer_types",
|
||||
"type": "multi_select",
|
||||
"label": "调拨类型",
|
||||
"label_key": "admin.schedule.form.transferTypeCodes",
|
||||
"required": False,
|
||||
"default": [],
|
||||
"options_source": "transfer_types",
|
||||
"help": "留空=全部启用中的调拨类型;按类型逐轮匹配并执行,恢复复核只跑一次。",
|
||||
},
|
||||
{
|
||||
"key": "source_codes",
|
||||
"type": "multi_select",
|
||||
|
||||
@@ -46,26 +46,56 @@ from app.path_utils import resolve_backend_relative_path
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
|
||||
def _released_line_indexes_for_task(order_task_id: int) -> set[int]:
|
||||
"""按正式 OT 身份读取已审计短缺放行的行号集合(复核 Case 的 confirmed_task_id 恒为 OT id)。"""
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
|
||||
|
||||
rows = (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.join(
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id,
|
||||
)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(order_task_id),
|
||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||
ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage',
|
||||
ShippingOrderReviewLineDecision.line_index.isnot(None),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
return {int(row.line_index) for row in rows}
|
||||
|
||||
|
||||
def _notice_source_code(task: ShippingNotice) -> str | None:
|
||||
"""返回正式 Notice 行级匹配中唯一使用的库存源;多源导出必须显式拒绝。
|
||||
|
||||
匹配事实的 task_id 挂在正式 OT 上:传 Notice 时取 order_task_id,
|
||||
传 OT 本身时取 id(整单 ODM 候选投影会在物化前以 OT 调用)。
|
||||
已审计短缺放行行(release_onhand_shortage)的 match_result 恒为 not_found
|
||||
(如预约键 0 命中的料号兜底行),其事实源码与 matched 行同票参与唯一性
|
||||
裁决;只按 matched 过滤会让「整单放行」的单永远解析不到库存源
|
||||
(回归 OT-20261027-4BD4CEFF)。
|
||||
"""
|
||||
task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
|
||||
if task_id is None:
|
||||
return None
|
||||
task_id = int(task_id)
|
||||
released_line_indexes = _released_line_indexes_for_task(task_id)
|
||||
codes = [
|
||||
str(row[0]).strip().upper()
|
||||
for row in db.session.query(ShippingNoticeLineOnhandMatch.source_code).filter(
|
||||
for row in db.session.query(
|
||||
ShippingNoticeLineOnhandMatch.source_code,
|
||||
ShippingNoticeLineOnhandMatch.match_result,
|
||||
ShippingNoticeLineOnhandMatch.line_index,
|
||||
).filter(
|
||||
ShippingNoticeLineOnhandMatch.task_id == task_id,
|
||||
ShippingNoticeLineOnhandMatch.is_current.is_(True),
|
||||
ShippingNoticeLineOnhandMatch.match_result == 'matched',
|
||||
ShippingNoticeLineOnhandMatch.source_code.isnot(None),
|
||||
).distinct().all()
|
||||
if row[0]
|
||||
).all()
|
||||
if row[0] and (row[1] == 'matched' or (row[2] is not None and int(row[2]) in released_line_indexes))
|
||||
]
|
||||
codes = list(dict.fromkeys(codes))
|
||||
return codes[0] if len(codes) == 1 else None
|
||||
|
||||
|
||||
@@ -87,19 +117,31 @@ def _notice_chosen_odm(task: ShippingNotice) -> str | None:
|
||||
|
||||
|
||||
def _notice_inventory_file_id(task: ShippingNotice) -> int | None:
|
||||
"""从 Notice 行级匹配读取本次导出的唯一库存文件。"""
|
||||
"""从 Notice 行级匹配读取本次导出的唯一库存文件。
|
||||
|
||||
已审计短缺放行行(not_found 事实)的证据快照与 matched 行同票:整单放行时
|
||||
库存证据文件仍必须落 Artifact 审计,否则证据流断链(回归 OT-20261027-4BD4CEFF)。
|
||||
"""
|
||||
task_id = getattr(task, 'order_task_id', None)
|
||||
if task_id is None:
|
||||
return None
|
||||
task_id = int(task_id)
|
||||
released_line_indexes = _released_line_indexes_for_task(task_id)
|
||||
ids = [
|
||||
int(row[0]) for row in db.session.query(ShippingNoticeLineOnhandMatch.onhand_snapshot_id).filter(
|
||||
int(row[0]) for row in db.session.query(
|
||||
ShippingNoticeLineOnhandMatch.onhand_snapshot_id,
|
||||
ShippingNoticeLineOnhandMatch.match_result,
|
||||
ShippingNoticeLineOnhandMatch.line_index,
|
||||
).filter(
|
||||
ShippingNoticeLineOnhandMatch.task_id == task_id,
|
||||
ShippingNoticeLineOnhandMatch.is_current.is_(True),
|
||||
ShippingNoticeLineOnhandMatch.match_result == 'matched',
|
||||
ShippingNoticeLineOnhandMatch.onhand_snapshot_id.isnot(None),
|
||||
).distinct().all()
|
||||
).all()
|
||||
if row[0] is not None and (
|
||||
row[1] == 'matched' or (row[2] is not None and int(row[2]) in released_line_indexes)
|
||||
)
|
||||
]
|
||||
ids = list(dict.fromkeys(ids))
|
||||
return ids[0] if len(ids) == 1 else None
|
||||
|
||||
|
||||
@@ -799,8 +841,14 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
|
||||
header_inventory_fields = _inventory_fields_by_mode(mappings, 'header')
|
||||
# [STEP 1] 短缺放行的人工字段仅从该行的活动决定审计快照读取,
|
||||
# 只能补模板行级库存字段,不能污染快照或任务级库存输入。
|
||||
# [身份口径] 复核 Case.confirmed_task_id 恒为正式 OT id;本函数入参可能是
|
||||
# 换绑后的 Notice,必须经 order_task_id 回链 OT,否则放行/结案决定恒查空,
|
||||
# 放行行进不了导出资格、结案行漏剔除(与 _facts_order_task 同款键位纪律)。
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
|
||||
|
||||
order_task_id_for_decisions = int(
|
||||
getattr(source_notice, 'order_task_id', None) or source_notice.id
|
||||
)
|
||||
release_overrides_by_source_line: dict[int, dict[str, Any]] = {}
|
||||
released_source_line_indexes: set[int] = set()
|
||||
if source_notice.id is not None:
|
||||
@@ -808,7 +856,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
|
||||
ShippingOrderReviewCase.confirmed_task_id == order_task_id_for_decisions,
|
||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||
ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage',
|
||||
)
|
||||
@@ -835,7 +883,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
|
||||
ShippingOrderReviewCase.confirmed_task_id == order_task_id_for_decisions,
|
||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||
ShippingOrderReviewLineDecision.decision_code == 'close_unfulfillable',
|
||||
)
|
||||
|
||||
@@ -2520,7 +2520,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
|
||||
# 三态结果:success / failed / unknown。result 显式给定则优先,否则由 success 布尔推导。
|
||||
raw_result = str(payload.get('result') or '').strip().lower()
|
||||
if raw_result in {'success', 'failed', 'unknown'}:
|
||||
if raw_result in {'success', 'failed', 'unknown', 'allocating'}:
|
||||
result_status = raw_result
|
||||
else:
|
||||
result_status = 'success' if success else 'failed'
|
||||
@@ -2614,6 +2614,25 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
position=POSITION_UPLOADED if has_verified_upload_success(task) else None,
|
||||
)
|
||||
|
||||
if completed.status == 'running' and completed.error_code == 'CRANE_ALLOCATING':
|
||||
set_task_step_progress(
|
||||
task,
|
||||
stage="freight_uploading",
|
||||
step_title="上传货代",
|
||||
status="running",
|
||||
message='货代已接收文件,正在分配,稍后自动回查一次',
|
||||
progress_percent=90,
|
||||
detail='Processing + Allocating the Shipping Order',
|
||||
)
|
||||
log_task_event(task, 'upload_rpa_allocating', {'artifact_id': completed.artifact_id, 'attempt_id': completed.id})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status='running',
|
||||
task=task,
|
||||
message='货代已接收文件,正在分配',
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
if completed.status == 'unknown':
|
||||
# unknown 已可能提交但无法确认外部系统结果:保持待人工,禁止自动重试,避免重复上传。
|
||||
set_task_step_progress(
|
||||
|
||||
@@ -414,7 +414,11 @@ def _shortage_release_required_fields(
|
||||
source_code=resolved_source_code, enabled=True,
|
||||
).first()
|
||||
template = getattr(source, 'excel_template', None) if source is not None else None
|
||||
profile = getattr(source, 'parsing_profile', None) if source is not None else None
|
||||
# [s18 改名] 解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系
|
||||
# (与 freight_rpa.parsing_profile.require_source_profile 同口径);
|
||||
# 站点行 getattr 读法会静默得 None,曾致短缺放行(自动+人工)全部失败。
|
||||
release_config = getattr(source, 'onhand_report_config', None) if source is not None else None
|
||||
profile = release_config.parsing_profile if release_config is not None else None
|
||||
if template is None or profile is None:
|
||||
raise ConflictError(
|
||||
'Inventory source export template is unavailable',
|
||||
|
||||
@@ -1951,16 +1951,19 @@ def list_freight_notice_groups_for_task(
|
||||
.first()
|
||||
)
|
||||
from app.services.shipping_notice.upload_attempt_service import project_notice_upload_status
|
||||
projected_upload_status = project_notice_upload_status(notice)
|
||||
hide_allocating_error = projected_upload_status == 'allocating'
|
||||
items.append({
|
||||
'business_no': business_no,
|
||||
'po_number': po_number,
|
||||
# Notice 面契约:成功统一为 uploaded,禁止下发 Attempt 原词 succeeded。
|
||||
'upload_status': project_notice_upload_status(notice),
|
||||
'upload_status': projected_upload_status,
|
||||
'upload_mode': upload_mode,
|
||||
'upload_attempt': upload_attempt,
|
||||
'upload_error_code': getattr(latest_attempt, 'error_code', None),
|
||||
'upload_error_code': None if hide_allocating_error else getattr(latest_attempt, 'error_code', None),
|
||||
# 逐单失败原因:优先取最近一次上传的错误正文,回退到任务级 error_message。
|
||||
'upload_error_message': (getattr(latest_attempt, 'error_message', None) or '')[:500] or None,
|
||||
# 分配中的内部错误码不是失败原因,不能把这一行显示成需人工。
|
||||
'upload_error_message': None if hide_allocating_error else ((getattr(latest_attempt, 'error_message', None) or '')[:500] or None),
|
||||
'export_file_name': getattr(artifact, 'file_name', None),
|
||||
'available_actions': available_actions,
|
||||
'lines': _notice_line_summary_for_task(notice),
|
||||
|
||||
@@ -75,6 +75,14 @@ def start_rpa_attempt(task: ShippingNotice, *, artifact_id: int | None = None, i
|
||||
return existing
|
||||
if ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id, status='succeeded').first():
|
||||
raise ConflictError('Artifact has already been uploaded', code='SHIPPING.UPLOAD_ARTIFACT_COMPLETED')
|
||||
allocating = ShippingUploadAttempt.query.filter_by(
|
||||
artifact_id=artifact.id, status='running', error_code='CRANE_ALLOCATING',
|
||||
).first()
|
||||
if allocating is not None:
|
||||
raise ConflictError(
|
||||
'Crane has accepted the file and is still allocating; refresh status instead of uploading again',
|
||||
code='SHIPPING.UPLOAD_CRANE_ALLOCATING',
|
||||
)
|
||||
# 业务决定:结果未知(timed_out/unknown)不再阻断重新下发 RPA。该状态表示“无法判断上传是否成功/失败”,
|
||||
# 为避免用户卡死、无法继续尝试,允许再次触发;若上次实际上传成功,重复触发可能产生重复单,
|
||||
# 需由用户在 CRANE 侧核查(错误文案已提示)。幂等 key 去重仍保留。
|
||||
@@ -123,7 +131,7 @@ def project_notice_upload_status(task: ShippingNotice | Any) -> str | None:
|
||||
task: 正式 Notice,或可解析到 Notice 的 OT。
|
||||
|
||||
Returns:
|
||||
uploaded | uploading | pending | failed | unknown | 其它透传小写 | None。
|
||||
uploaded | allocating | uploading | pending | failed | unknown | 其它透传小写 | None。
|
||||
"""
|
||||
attempt = latest_upload_attempt(task)
|
||||
if attempt is not None:
|
||||
@@ -131,6 +139,8 @@ def project_notice_upload_status(task: ShippingNotice | Any) -> str | None:
|
||||
# Attempt 层当前写入成功态只有 succeeded(callback result=success 已在 complete_attempt 内翻译)。
|
||||
if status == 'succeeded':
|
||||
return 'uploaded'
|
||||
if status == 'running' and str(getattr(attempt, 'error_code', None) or '') == 'CRANE_ALLOCATING':
|
||||
return 'allocating'
|
||||
if status in _UPLOAD_IN_FLIGHT_TOKENS:
|
||||
return 'uploading'
|
||||
if status == 'pending':
|
||||
@@ -221,9 +231,9 @@ def _normalize_callback_result(result: str | None, success: bool) -> str:
|
||||
"""
|
||||
if result is not None:
|
||||
normalized = str(result or '').strip().lower()
|
||||
if normalized not in {'success', 'failed', 'unknown'}:
|
||||
if normalized not in {'success', 'failed', 'unknown', 'allocating'}:
|
||||
raise ValidationError(
|
||||
'result must be success, failed or unknown',
|
||||
'result must be success, failed, unknown or allocating',
|
||||
code='SHIPPING.UPLOAD_RESULT_INVALID',
|
||||
)
|
||||
return normalized
|
||||
@@ -243,7 +253,7 @@ def complete_attempt(
|
||||
callback_id: 回调幂等键(唯一)。
|
||||
freight_ref_no: 成功时货代回执号。
|
||||
error_message: 失败/未知时的脱敏错误信息。
|
||||
result: 三态结果 success / failed / unknown;三态与布尔推导见 _normalize_callback_result。
|
||||
result: success / failed / unknown / allocating。allocating 表示 Crane 已接收且仍在分配。
|
||||
|
||||
Returns:
|
||||
ShippingUploadAttempt: 已更新状态的 Attob。
|
||||
@@ -266,10 +276,16 @@ def complete_attempt(
|
||||
if artifact.status in {'superseded', 'invalidated'}:
|
||||
raise ConflictError('Superseded artifact cannot accept callback', code='SHIPPING.ARTIFACT_ALREADY_SUPERSEDED')
|
||||
if attempt.status == 'succeeded' or artifact.status == 'uploaded':
|
||||
if str(result or '').strip().lower() == 'allocating':
|
||||
return attempt
|
||||
raise ConflictError('Late callback cannot overwrite uploaded artifact', code='SHIPPING.UPLOAD_CALLBACK_STALE')
|
||||
if attempt.status not in {'pending', 'running', 'timed_out', 'unknown'}:
|
||||
raise ConflictError('Callback is not valid for this attempt', code='SHIPPING.UPLOAD_CALLBACK_STALE')
|
||||
result_status = _normalize_callback_result(result, success)
|
||||
if result_status == 'allocating':
|
||||
from app.services.freight_rpa.upload.crane_recheck import remember_crane_allocating
|
||||
|
||||
return remember_crane_allocating(attempt, artifact, callback)
|
||||
attempt.callback_id = callback
|
||||
attempt.finished_at = datetime.utcnow()
|
||||
task = db.session.get(ShippingNotice, artifact.task_id)
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
"""
|
||||
services/shipping_notice/upload_config_validation.py
|
||||
|
||||
用途:对连接级“发货 Excel 自动上传”配置做后端严格白名单校验,产出受限 JSON。
|
||||
依赖:app.core.errors.ValidationError;仅标准库,不引入第三方。
|
||||
逻辑:配置由管理端表单编辑,但后端只接受本模块允许的字段、枚举与安全边界;
|
||||
禁止自由 JavaScript、脚本、URL 模板、Cookie 或任意浏览器动作落库。
|
||||
upload_config 是“这次上传到底用了什么”的快照来源,不做版本管理(见技术文档)。
|
||||
用途:系统连接只保存「是否启用发货 Excel 自动上传」。
|
||||
依赖:app.core.errors.ValidationError;标准库 hashlib/json。
|
||||
逻辑:页面路径、选择器和成功文案由连接器代码固定,管理端提交的这些字段一律丢弃。
|
||||
upload_config 快照只保留 enabled,供本次上传审计。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,192 +15,34 @@ from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
# 连接类型与各平台已审核域名(主机名白名单,后缀匹配以覆盖同域子站)。
|
||||
ALLOWED_CONNECTOR_TYPES = frozenset({'dbs', 'crane'})
|
||||
ALLOWED_PLATFORM_DOMAINS: dict[str, tuple[str, ...]] = {
|
||||
'dbs': ('dbschenker.com',),
|
||||
'crane': ('craneww.com',),
|
||||
}
|
||||
ALLOWED_SUBMIT_MODES = frozenset({'auto_after_file', 'click_submit'})
|
||||
ALLOWED_RESULT_MODES = frozenset({'page_notice', 'history_record'})
|
||||
|
||||
# 字段白名单:禁止把额外键(模板、Cookie、脚本)混入配置。
|
||||
ALLOWED_KEYS = frozenset({
|
||||
'enabled', 'entry_url', 'file_input_selector',
|
||||
'submit_mode', 'submit_selector',
|
||||
'result_mode', 'result_selector', 'success_texts', 'timeout_seconds',
|
||||
})
|
||||
|
||||
MAX_ENTRY_URL_LENGTH = 500
|
||||
MAX_SELECTOR_LENGTH = 200
|
||||
MAX_SUCCESS_TEXTS = 10
|
||||
MAX_SUCCESS_TEXT_LENGTH = 200
|
||||
MIN_TIMEOUT_SECONDS = 1
|
||||
MAX_TIMEOUT_SECONDS = 600
|
||||
DEFAULT_TIMEOUT_SECONDS = 120
|
||||
|
||||
# 复用的字符黑名单:任何脚本/表达式/注入语义都拒绝。
|
||||
_BLOCKED_SELECTOR_MARKERS = (
|
||||
'javascript:', '<script', 'expression(', 'onclick=', 'onload=', 'onerror=',
|
||||
'onmouseover=', 'onmouseout=', 'onfocus=', 'onblur=', 'onchange=', 'oninput=',
|
||||
)
|
||||
_BLOCKED_SELECTOR_CHARS = ('(', ')', '{', '}', ';', '<', '>', '`', '\\', '\n', '\r')
|
||||
|
||||
|
||||
def _reject(message: str, *, field: str) -> None:
|
||||
raise ValidationError(message, code='SHIPPING.UPLOAD_CONFIG_INVALID', details={'field': field})
|
||||
|
||||
|
||||
def _normalize_text(value: Any) -> str:
|
||||
return str(value or '').strip()
|
||||
|
||||
|
||||
def _validate_entry_url(connector_type: str, value: Any, *, required: bool = True) -> str | None:
|
||||
"""校验上传入口为 HTTPS 且主机名属于已审核平台域名。"""
|
||||
url = _normalize_text(value)
|
||||
if not url:
|
||||
if required:
|
||||
_reject('entry_url is required', field='entry_url')
|
||||
return None
|
||||
if len(url) > MAX_ENTRY_URL_LENGTH:
|
||||
_reject('entry_url is too long', field='entry_url')
|
||||
if not url.lower().startswith('https://'):
|
||||
_reject('entry_url must be HTTPS', field='entry_url')
|
||||
# 简单主机名解析:仅定位 host:port 部分,禁止 userinfo/query 进入主机判断。
|
||||
scheme_rest = url[8:]
|
||||
authority = scheme_rest.split('/', 1)[0].split('?', 1)[0].split('#', 1)[0]
|
||||
host = authority.split('@')[-1].split(':')[0].strip().lower()
|
||||
if not host:
|
||||
_reject('entry_url host is invalid', field='entry_url')
|
||||
allowed = ALLOWED_PLATFORM_DOMAINS.get(connector_type, ())
|
||||
if not any(host == domain or host.endswith('.' + domain) for domain in allowed):
|
||||
_reject(
|
||||
f'entry_url host not allowed for {connector_type}',
|
||||
field='entry_url',
|
||||
)
|
||||
return url
|
||||
|
||||
|
||||
def _validate_css_selector(value: Any, *, field: str, required: bool) -> str | None:
|
||||
"""校验普通 CSS selector:限制长度、拒绝脚本及表达式语义。"""
|
||||
selector = _normalize_text(value)
|
||||
if not selector:
|
||||
if required:
|
||||
_reject(f'{field} is required', field=field)
|
||||
return None
|
||||
if len(selector) > MAX_SELECTOR_LENGTH:
|
||||
_reject(f'{field} is too long', field=field)
|
||||
lowered = selector.lower()
|
||||
for marker in _BLOCKED_SELECTOR_MARKERS:
|
||||
if marker in lowered:
|
||||
_reject(f'{field} contains script semantics', field=field)
|
||||
for char in _BLOCKED_SELECTOR_CHARS:
|
||||
if char in selector:
|
||||
_reject(f'{field} contains an invalid character', field=field)
|
||||
return selector
|
||||
|
||||
|
||||
def _validate_success_texts(value: Any) -> list[str]:
|
||||
if value in (None, ''):
|
||||
return []
|
||||
if not isinstance(value, list):
|
||||
_reject('success_texts must be a list', field='success_texts')
|
||||
if len(value) > MAX_SUCCESS_TEXTS:
|
||||
_reject('success_texts is too long', field='success_texts')
|
||||
result: list[str] = []
|
||||
for item in value:
|
||||
text = _normalize_text(item)
|
||||
if not text or len(text) > MAX_SUCCESS_TEXT_LENGTH:
|
||||
_reject('success_texts contains an invalid item', field='success_texts')
|
||||
if text not in result:
|
||||
result.append(text)
|
||||
return result
|
||||
|
||||
|
||||
def validate_upload_config(connector_type: str, raw: Any) -> dict[str, Any] | None:
|
||||
"""白名单校验连接级上传配置,返回规范化 JSON;raw 为空/None 表示未配置(返回 None)。
|
||||
"""只保留 enabled。页面参数即使随旧表单提交也不落库。
|
||||
|
||||
Args:
|
||||
connector_type: 连接类型,仅允许 dbs / crane。
|
||||
raw: 管理端提交的原始上传配置对象。
|
||||
raw: 管理端提交的上传配置。None 或空串表示未配置。
|
||||
|
||||
Returns:
|
||||
dict | None: 规范化受限 JSON;未配置时返回 None。
|
||||
dict | None: ``{"enabled": bool}``;未配置时返回 None。
|
||||
|
||||
Raises:
|
||||
ValidationError: 含未知字段/非法枚举/不安全 selector/非 HTTPS 或非法域名/
|
||||
enabled=true 但缺少上传或结果判定所需字段。
|
||||
ValidationError: 连接类型非法或上传配置不是对象。
|
||||
"""
|
||||
normalized_connector = _normalize_text(connector_type).lower()
|
||||
normalized_connector = str(connector_type or '').strip().lower()
|
||||
if normalized_connector not in ALLOWED_CONNECTOR_TYPES:
|
||||
_reject('connector_type must be dbs or crane', field='connector_type')
|
||||
if raw in (None, ''):
|
||||
return None
|
||||
if not isinstance(raw, dict):
|
||||
_reject('upload_config must be an object', field='upload_config_json')
|
||||
unknown = set(raw) - ALLOWED_KEYS
|
||||
if unknown:
|
||||
_reject(f'upload_config contains unsupported fields: {sorted(unknown)}', field='upload_config_json')
|
||||
|
||||
enabled = raw.get('enabled') is True
|
||||
|
||||
config: dict[str, Any] = {
|
||||
'enabled': enabled,
|
||||
'entry_url': _validate_entry_url(normalized_connector, raw.get('entry_url'), required=enabled),
|
||||
'file_input_selector': _validate_css_selector(
|
||||
raw.get('file_input_selector'), field='file_input_selector', required=enabled,
|
||||
),
|
||||
'submit_mode': _normalize_text(raw.get('submit_mode')),
|
||||
'submit_selector': _validate_css_selector(
|
||||
raw.get('submit_selector'), field='submit_selector', required=False,
|
||||
),
|
||||
'result_mode': _normalize_text(raw.get('result_mode')),
|
||||
'result_selector': _validate_css_selector(
|
||||
raw.get('result_selector'), field='result_selector', required=False,
|
||||
),
|
||||
'success_texts': _validate_success_texts(raw.get('success_texts')),
|
||||
'timeout_seconds': raw.get('timeout_seconds', DEFAULT_TIMEOUT_SECONDS),
|
||||
}
|
||||
|
||||
if config['submit_mode'] not in ALLOWED_SUBMIT_MODES:
|
||||
_reject('submit_mode must be auto_after_file or click_submit', field='submit_mode')
|
||||
if config['result_mode'] not in ALLOWED_RESULT_MODES:
|
||||
_reject('result_mode must be page_notice or history_record', field='result_mode')
|
||||
if config['submit_mode'] == 'auto_after_file':
|
||||
# auto_after_file 由页面在选文件后自动提交,不应同时配置提交按钮选择器。
|
||||
config['submit_selector'] = None
|
||||
|
||||
try:
|
||||
timeout = int(config['timeout_seconds'])
|
||||
except (TypeError, ValueError):
|
||||
_reject('timeout_seconds must be an integer', field='timeout_seconds')
|
||||
if timeout < MIN_TIMEOUT_SECONDS or timeout > MAX_TIMEOUT_SECONDS:
|
||||
_reject(
|
||||
f'timeout_seconds must be within [{MIN_TIMEOUT_SECONDS}, {MAX_TIMEOUT_SECONDS}]',
|
||||
field='timeout_seconds',
|
||||
)
|
||||
config['timeout_seconds'] = timeout
|
||||
|
||||
if enabled:
|
||||
# 完成一次上传所需的公共字段由上述必填校验覆盖;此处补齐连接差异。
|
||||
if not config['file_input_selector']:
|
||||
_reject('enabled upload requires file_input_selector', field='file_input_selector')
|
||||
if config['submit_mode'] == 'click_submit' and not config['submit_selector']:
|
||||
_reject('enabled click_submit upload requires submit_selector', field='submit_selector')
|
||||
# 结果判定:dbs(DSV) 使用代码内置的受控成功流(History 绿状态/页面证据),
|
||||
# 不强制 admin 填写结果字段;crane 必须由 admin 补全提交/结果判定字段后才可启用。
|
||||
if normalized_connector == 'crane':
|
||||
if config['result_mode'] == 'page_notice':
|
||||
if not config['result_selector'] or not config['success_texts']:
|
||||
_reject(
|
||||
'enabled crane page_notice upload requires result_selector and success_texts',
|
||||
field='result_selector',
|
||||
)
|
||||
elif config['result_mode'] == 'history_record' and not config['result_selector']:
|
||||
_reject('enabled crane history_record upload requires result_selector', field='result_selector')
|
||||
|
||||
# 未启用时仍保存规范化的受限 JSON,方便 admin 预填后续补全。
|
||||
return config
|
||||
return {'enabled': raw.get('enabled') is True}
|
||||
|
||||
|
||||
def compute_upload_config_hash(config: dict[str, Any] | None) -> str | None:
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
"""合并常用问题模糊匹配与库存异动自然键两条 Alembic 头。
|
||||
|
||||
backend/migrations/versions/mh23e4f5a6b7_merge_faq_fuzzy_and_ledger_heads.py
|
||||
用途:把 FAQ 模糊匹配列与库存异动外部单号自然键收成单一升级路径。
|
||||
依赖:b51c9e4a7d30、tt21c8d9e0f1a2。
|
||||
逻辑:不改业务表,只声明两条已完成迁移线在此收敛,避免 flask db upgrade 与 pre-commit 因多 head 失败。
|
||||
|
||||
Revision ID: mh23e4f5a6b7
|
||||
Revises: b51c9e4a7d30, tt21c8d9e0f1a2
|
||||
Create Date: 2026-10-23 15:05:00.000000
|
||||
"""
|
||||
|
||||
from alembic import op # noqa: F401 - Alembic migration module contract
|
||||
|
||||
|
||||
revision = "mh23e4f5a6b7"
|
||||
down_revision = ("b51c9e4a7d30", "tt21c8d9e0f1a2")
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""合并 FAQ 模糊匹配 head 与库存异动自然键 head,不执行数据库结构变更。"""
|
||||
pass
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""撤销合并节点;不会回滚两个父分支的业务变更。"""
|
||||
pass
|
||||
@@ -0,0 +1,75 @@
|
||||
"""
|
||||
migrations/versions/s20a1b2c3d4e_review_line_decision_code_rename.py
|
||||
|
||||
用途:批次 S 漏网补丁——复核行决定表的决策码迁移。
|
||||
s17b(表改名)/s17c(枚举数据替换)/s18 均未覆盖
|
||||
shipping_order_review_line_decisions.decision_code:旧码数据不搬、
|
||||
ck_shipping_review_line_decisions_code 不重建,导致新代码写入
|
||||
release_onhand_shortage / wait_onhand 时撞 prod 旧 CHECK
|
||||
(IntegrityError,自动放行被吞、人工放行报错)。
|
||||
依赖:alembic.op、SQLAlchemy;down_revision 为 mh23e4f5a6b7(现仓库唯一 head)。
|
||||
逻辑:先 drop 旧 CHECK(否则新码 UPDATE 直接违约),再做两次精确值替换
|
||||
(release_inventory_shortage→release_onhand_shortage、
|
||||
wait_inventory→wait_onhand,其余码不变),最后按
|
||||
models/shipping_order_review_line_decision.py 的现行码集重建同名 CHECK。
|
||||
line_status 的 CHECK 已是新集(released_shortage 早已在列),本迁移不动。
|
||||
snapshot_json 内的历史码是审计快照,按不可变原则不改写。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = "s20a1b2c3d4e"
|
||||
down_revision = "mh23e4f5a6b7"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_TABLE = "shipping_order_review_line_decisions"
|
||||
_CHECK = "ck_shipping_review_line_decisions_code"
|
||||
|
||||
# 与模型 CheckConstraint 逐字一致的新码集(升级方向)
|
||||
_NEW_CODES = (
|
||||
"'wait_onhand', 'use_new_inventory_file', 'change_inventory_source', "
|
||||
"'fulfill_complete_line_now', 'close_unfulfillable', 'reopen', 'release_onhand_shortage'"
|
||||
)
|
||||
# hg1i2j3k4l5m 时的旧码集(降级方向)
|
||||
_OLD_CODES = (
|
||||
"'wait_inventory', 'use_new_inventory_file', 'change_inventory_source', "
|
||||
"'fulfill_complete_line_now', 'close_unfulfillable', 'reopen', 'release_inventory_shortage'"
|
||||
)
|
||||
|
||||
# 旧码 → 新码(词根 inventory→onhand 的两个改名对;升级方向)
|
||||
_UPDATES_UP: tuple[tuple[str, str], ...] = (
|
||||
("release_inventory_shortage", "release_onhand_shortage"),
|
||||
("wait_inventory", "wait_onhand"),
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# [STEP 1] 先摘旧 CHECK:旧码集不含新码,先改值必违约。
|
||||
op.drop_constraint(_CHECK, _TABLE, type_="check")
|
||||
# [STEP 2] 精确值替换(只碰两个改名对,其余决策码保持原值)。
|
||||
for old, new in _UPDATES_UP:
|
||||
op.execute(
|
||||
sa.text(
|
||||
f"UPDATE {_TABLE} SET decision_code = :new WHERE decision_code = :old"
|
||||
).bindparams(old=old, new=new)
|
||||
)
|
||||
# [STEP 3] 按模型现行码集重建同名 CHECK。
|
||||
op.create_check_constraint(_CHECK, _TABLE, f"decision_code IN ({_NEW_CODES})")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# [STEP 1] 先摘新 CHECK,再把新码精确换回旧码。
|
||||
op.drop_constraint(_CHECK, _TABLE, type_="check")
|
||||
for old, new in _UPDATES_UP:
|
||||
op.execute(
|
||||
sa.text(
|
||||
f"UPDATE {_TABLE} SET decision_code = :old WHERE decision_code = :new"
|
||||
).bindparams(old=old, new=new)
|
||||
)
|
||||
# [STEP 2] 恢复旧码集 CHECK。
|
||||
op.create_check_constraint(_CHECK, _TABLE, f"decision_code IN ({_OLD_CODES})")
|
||||
@@ -2255,3 +2255,51 @@ def test_evidence_files_list_returns_today_size_and_presigned_url(
|
||||
event_type="TRANSFER_INBOUND_FILES_DOWNLOADED",
|
||||
).one()
|
||||
assert audit.aggregate_id == EVIDENCE_SOURCE
|
||||
|
||||
|
||||
def test_evidence_file_download_streams_through_the_site(
|
||||
app, client, admin_headers, monkeypatch,
|
||||
):
|
||||
"""单文件下载由当前站点回传,保存名不用对象键。"""
|
||||
now = datetime.utcnow().replace(microsecond=0)
|
||||
source = _ensure_evidence_source()
|
||||
report = _seed_evidence_file(
|
||||
source, kind="inbound", filename="Inbound.xlsx",
|
||||
storage_key="evidence/one", sha="61" * 32, file_size=12,
|
||||
created_at=now,
|
||||
)
|
||||
_patch_archive_bytes(monkeypatch, {"evidence/one": b"PK-xlsx"})
|
||||
|
||||
response = client.get(
|
||||
f"{API_PREFIX}/sources/{EVIDENCE_SOURCE}/evidence-files/{report.id}?record_kind=inbound",
|
||||
headers=admin_headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
# [断言意图] 响应体是对象内容,不是跳到 MinIO 的地址。
|
||||
assert response.data == b"PK-xlsx"
|
||||
from app.api.in_transit_transfer import evidence_download_filename
|
||||
|
||||
download_name = evidence_download_filename(EVIDENCE_SOURCE, now, "Inbound.xlsx")
|
||||
# [断言意图] 保存名沿用库存源加东八区时间,浏览器不会落到哈希对象键。
|
||||
assert download_name in response.headers.get("Content-Disposition", "")
|
||||
|
||||
|
||||
def test_evidence_file_download_rejects_unavailable_file(app, client, admin_headers):
|
||||
"""已清理或不在可用窗口的归档不能经站点下载。"""
|
||||
now = datetime.utcnow().replace(microsecond=0)
|
||||
source = _ensure_evidence_source()
|
||||
report = _seed_evidence_file(
|
||||
source, kind="inbound", filename="Deleted.xlsx",
|
||||
storage_key="evidence/gone", sha="62" * 32, file_size=12,
|
||||
created_at=now, deleted=True,
|
||||
)
|
||||
|
||||
response = client.get(
|
||||
f"{API_PREFIX}/sources/{EVIDENCE_SOURCE}/evidence-files/{report.id}?record_kind=inbound",
|
||||
headers=admin_headers,
|
||||
)
|
||||
|
||||
# [断言意图] 清单里不会出现的文件,单文件下载同样拒绝。
|
||||
assert response.status_code == 404
|
||||
assert response.get_json()["error"]["code"] == "SHIPPING.INBOUND_FILE_NOT_FOUND"
|
||||
@@ -3,7 +3,7 @@ tests/services/admin/test_shipping_inventory_service.py
|
||||
|
||||
用途:验证库存主数据管理服务的安全性和关键业务约束。
|
||||
依赖:Flask app/db、freight_rpa_source_admin_service、shipping_onhand_admin_service、库存配置模型。
|
||||
逻辑:管理后台写配置前锁定凭据脱敏、Driver 一致、规则发布不可变和 ERP 默认映射唯一性。
|
||||
逻辑:管理后台写配置前锁定用户名可回显、密码与密文不回传、Driver 一致、规则发布不可变和 ERP 默认映射唯一性。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,6 +22,7 @@ from app.models import (
|
||||
FreightRpaSource,
|
||||
FreightRpaSourceParsingBindingAudit,
|
||||
FreightRpaOnhandStructureAnalysis,
|
||||
FreightRpaProfile,
|
||||
)
|
||||
|
||||
|
||||
@@ -160,15 +161,50 @@ def _published_route_field_id() -> str:
|
||||
)
|
||||
|
||||
|
||||
def test_profile_credentials_are_not_returned(app):
|
||||
"""Profile 保存后只返回配置标记,响应中不能含凭据明文或密文。"""
|
||||
def test_profile_returns_username_and_keeps_password_secret(app):
|
||||
"""Profile 回执返回用户名明文,密码与密文不得出现。相同用户名再次保存不轮换密文。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
payload = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
|
||||
# 用户名是账号标识,管理端需要明文辨认;密码只报告已配置。
|
||||
assert payload['username'] == 'test-user'
|
||||
assert payload['password_configured'] is True
|
||||
assert payload['username_masked'] == 'configured'
|
||||
assert 'password' not in payload
|
||||
assert 'ciphertext' not in payload
|
||||
stored = db.session.get(FreightRpaProfile, payload['id'])
|
||||
original_username = stored.username_ciphertext
|
||||
original_password = stored.password_ciphertext
|
||||
original_updated_at = stored.credential_updated_at
|
||||
unchanged = _profile_data()
|
||||
unchanged.pop('password')
|
||||
unchanged['display_name'] = 'DBS EU renamed'
|
||||
again = freight_rpa_source_admin_service.save_profile(unchanged, actor_id=None, profile_id=payload['id'])
|
||||
# 回显后的原用户名随表单提交时,不得重加密或刷新凭据时间。
|
||||
assert again['username'] == 'test-user'
|
||||
db.session.refresh(stored)
|
||||
assert stored.username_ciphertext == original_username
|
||||
assert stored.password_ciphertext == original_password
|
||||
assert stored.credential_updated_at == original_updated_at
|
||||
assert stored.display_name == 'DBS EU renamed'
|
||||
|
||||
|
||||
def test_profile_username_change_reencrypts_without_touching_password(app):
|
||||
"""只改用户名时重写用户名密文,密码密文保持不变。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
payload = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
|
||||
stored = db.session.get(FreightRpaProfile, payload['id'])
|
||||
original_username = stored.username_ciphertext
|
||||
original_password = stored.password_ciphertext
|
||||
changed = _profile_data()
|
||||
changed.pop('password')
|
||||
changed['username'] = 'other-user'
|
||||
updated = freight_rpa_source_admin_service.save_profile(changed, actor_id=None, profile_id=payload['id'])
|
||||
assert updated['username'] == 'other-user'
|
||||
db.session.refresh(stored)
|
||||
assert stored.username_ciphertext != original_username
|
||||
assert stored.password_ciphertext == original_password
|
||||
|
||||
|
||||
def test_profile_rejects_page_operation_configuration(app):
|
||||
@@ -620,29 +656,23 @@ def test_upload_config_change_does_not_bump_rpa_profile_version(app):
|
||||
profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
|
||||
base_version = profile['config_version']
|
||||
upload_cfg = {
|
||||
'enabled': True, 'entry_url': 'https://s360.dbschenker.com/main/portal/frame/WMSUpload2',
|
||||
'file_input_selector': 'input#file2', 'submit_mode': 'auto_after_file', 'submit_selector': None,
|
||||
'result_mode': 'page_notice', 'result_selector': None, 'success_texts': [], 'timeout_seconds': 120,
|
||||
'enabled': True, 'entry_url': 'https://evil.example/steal',
|
||||
'file_input_selector': 'input#file2', 'submit_mode': 'auto_after_file',
|
||||
}
|
||||
updated = freight_rpa_source_admin_service.save_profile(
|
||||
{**_profile_data(), 'upload_config_json': upload_cfg}, actor_id=None, profile_id=profile['id'],
|
||||
)
|
||||
assert updated['config_version'] == base_version
|
||||
assert updated['upload_config_json']['enabled'] is True
|
||||
assert updated['upload_config_json'] == {'enabled': True}
|
||||
# 仅修改运行期连接配置(login_url)仍应递增 config_version。
|
||||
bumped = freight_rpa_source_admin_service.save_profile(
|
||||
{**_profile_data(), 'login_url': 'https://example.invalid/login-v2'},
|
||||
actor_id=None, profile_id=profile['id'],
|
||||
)
|
||||
assert bumped['config_version'] == base_version + 1
|
||||
# 非法上传配置(HTTP / 非法主机 / 脚本 selector)应拒绝。
|
||||
# 上传配置必须是对象;页面字段不再作为校验对象。
|
||||
with pytest.raises(ValidationError):
|
||||
freight_rpa_source_admin_service.save_profile(
|
||||
{**_profile_data(), 'upload_config_json': {'enabled': True, 'entry_url': 'http://evil.example/x', 'file_input_selector': '#f', 'submit_mode': 'auto_after_file', 'result_mode': 'page_notice', 'timeout_seconds': 120}},
|
||||
actor_id=None, profile_id=profile['id'],
|
||||
)
|
||||
with pytest.raises(ValidationError):
|
||||
freight_rpa_source_admin_service.save_profile(
|
||||
{**_profile_data(), 'upload_config_json': {'enabled': True, 'entry_url': 'https://evil.example/x', 'file_input_selector': '#f', 'submit_mode': 'auto_after_file', 'result_mode': 'page_notice', 'timeout_seconds': 120}},
|
||||
{**_profile_data(), 'upload_config_json': 'not-an-object'},
|
||||
actor_id=None, profile_id=profile['id'],
|
||||
)
|
||||
@@ -0,0 +1,79 @@
|
||||
"""
|
||||
backend/tests/services/file_assets/test_storage_presign.py
|
||||
|
||||
用途:验证业务文件预签名下载地址使用浏览器可访问的 MinIO 主机。
|
||||
依赖:file_assets.storage、minio。
|
||||
逻辑:正式环境内网端点与公网基址不同;断言签名 URL 的主机是公网基址,读写客户端仍是内网端点。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.file_assets import storage as storage_mod
|
||||
from app.services.file_assets.storage import resolve_presign_endpoint
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def _patch_minio_config(monkeypatch, *, public_base: str, secure: bool = False) -> None:
|
||||
"""把存储配置钉成正式环境形态:容器内网端点 + 浏览器公网基址。"""
|
||||
monkeypatch.setattr(storage_mod._cfg, "MINIO_ENDPOINT", "host.docker.internal:9000")
|
||||
monkeypatch.setattr(storage_mod._cfg, "MINIO_ACCESS_KEY", "test-access")
|
||||
monkeypatch.setattr(storage_mod._cfg, "MINIO_SECRET_KEY", "test-secret")
|
||||
monkeypatch.setattr(storage_mod._cfg, "MINIO_SECURE", secure)
|
||||
monkeypatch.setattr(storage_mod._cfg, "MINIO_PUBLIC_BASE_URL", public_base)
|
||||
monkeypatch.setattr(storage_mod._cfg, "MINIO_FILE_ASSETS_BUCKET", "hxops-file-assets")
|
||||
|
||||
|
||||
def test_resolve_presign_endpoint_keeps_explicit_port():
|
||||
"""公网基址的非默认端口必须留在预签名端点里。"""
|
||||
endpoint, secure = resolve_presign_endpoint(
|
||||
"http://ai.well-trust.com:9000",
|
||||
"host.docker.internal:9000",
|
||||
False,
|
||||
)
|
||||
# [断言意图] 正式环境浏览器入口是 9000,不能收成 80。
|
||||
assert endpoint == "ai.well-trust.com:9000"
|
||||
assert secure is False
|
||||
|
||||
|
||||
def test_resolve_presign_endpoint_falls_back_when_public_base_empty():
|
||||
"""公网基址为空时继续用内网端点,避免签出空主机。"""
|
||||
endpoint, secure = resolve_presign_endpoint("", "192.168.100.192:9000", False)
|
||||
# [断言意图] 未配置公网基址时行为与改前一致。
|
||||
assert endpoint == "192.168.100.192:9000"
|
||||
assert secure is False
|
||||
|
||||
|
||||
def test_presigned_get_url_uses_public_host(monkeypatch):
|
||||
"""正式环境下载链接的主机必须是 MINIO_PUBLIC_BASE_URL。"""
|
||||
_patch_minio_config(monkeypatch, public_base="http://ai.well-trust.com:9000")
|
||||
store = storage_mod.FileAssetStorage()
|
||||
monkeypatch.setattr(store, "_ensure_bucket_exists", lambda: None)
|
||||
|
||||
url = store.presigned_get_url(
|
||||
"shipping/outbound-reports/2026/10/1/abc.xlsx",
|
||||
expires_seconds=300,
|
||||
download_name="CRANE_20261020_1815.xlsx",
|
||||
)
|
||||
|
||||
# [断言意图] 浏览器打开的是公网 MinIO,签名里不能再出现容器内网主机。
|
||||
assert url.startswith(
|
||||
"http://ai.well-trust.com:9000/hxops-file-assets/shipping/outbound-reports/2026/10/1/abc.xlsx?"
|
||||
)
|
||||
assert "host.docker.internal" not in url
|
||||
assert "X-Amz-Signature=" in url
|
||||
assert "response-content-disposition=" in url
|
||||
# [断言意图] 读写仍走容器内网端点,避免把公网主机写进上传客户端。
|
||||
assert store.client is not store.presign_client
|
||||
assert store.client._base_url.host == "host.docker.internal:9000"
|
||||
assert store.presign_client._base_url.host == "ai.well-trust.com:9000"
|
||||
|
||||
|
||||
def test_presigned_get_url_reuses_client_when_hosts_match(monkeypatch):
|
||||
"""内网端点与公网基址相同时不另建客户端。"""
|
||||
_patch_minio_config(monkeypatch, public_base="http://host.docker.internal:9000")
|
||||
store = storage_mod.FileAssetStorage()
|
||||
# [断言意图] 开发环境两端点一致,预签名与读写共用同一客户端。
|
||||
assert store.presign_client is store.client
|
||||
@@ -0,0 +1,100 @@
|
||||
"""
|
||||
backend/tests/services/freight_rpa/test_crane_upload_recheck.py
|
||||
|
||||
用途:验证上传配置只保留开关,以及 Crane 分配中只排一次定时回查。
|
||||
依赖:page_contract、upload_attempt_service、crane_recheck、Flask 测试库。
|
||||
逻辑:先断言入口 URL 和行分类,再走 complete_attempt、定时回查和手动刷新。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.services.freight_rpa.upload.crane_recheck import (
|
||||
fire_scheduled_crane_recheck,
|
||||
request_manual_crane_refresh,
|
||||
)
|
||||
from app.services.freight_rpa.upload.page_contract import (
|
||||
build_upload_entry_url,
|
||||
classify_crane_order_row,
|
||||
)
|
||||
from app.services.shipping_notice.upload_attempt_service import (
|
||||
complete_attempt,
|
||||
project_notice_upload_status,
|
||||
start_rpa_attempt,
|
||||
)
|
||||
from tests.test_shipping_upload_attempt import _ready_artifact
|
||||
|
||||
|
||||
def test_upload_entry_url_comes_from_login_host_and_crane_row_is_classified():
|
||||
"""DBS/Crane 上传页由登录主机拼接;只有两句固定文案分别表示已分配和分配中。"""
|
||||
assert build_upload_entry_url('dbs', 'https://s360.dbschenker.com/login') == (
|
||||
'https://s360.dbschenker.com/main/portal/frame/WMSUpload2'
|
||||
)
|
||||
assert build_upload_entry_url('crane', 'https://wms-portal.craneww.com/') == (
|
||||
'https://wms-portal.craneww.com/#/shipping-order-upload'
|
||||
)
|
||||
assert classify_crane_order_row('Processing', 'Shipping Order Allocated') == 'allocated'
|
||||
assert classify_crane_order_row('Processing', 'Allocating the Shipping Order') == 'allocating'
|
||||
assert classify_crane_order_row('Completed', 'Shipping Order Allocated') == 'other'
|
||||
|
||||
|
||||
def test_allocating_schedules_one_recheck_and_blocks_another_upload(app):
|
||||
"""首次分配中写下 10 分钟回查;第二次回调不改到期时间,也不能重新上传。"""
|
||||
with app.app_context():
|
||||
notice, artifact, _reservation = _ready_artifact()
|
||||
artifact.file_name = 'MXI26082801.xlsx'
|
||||
attempt = start_rpa_attempt(notice, artifact_id=artifact.id, idempotency_key='crane-key')
|
||||
started = datetime(2026, 10, 23, 3, 0, 0)
|
||||
complete_attempt(attempt, success=False, callback_id='upload-1', result='allocating')
|
||||
# remember 使用 utcnow;这里只断言间隔为 10 分钟,不绑定测试开始时刻。
|
||||
due_at = datetime.fromisoformat(attempt.success_evidence_json['crane_recheck']['due_at'])
|
||||
assert timedelta(minutes=9) < due_at - datetime.utcnow() <= timedelta(minutes=10)
|
||||
assert attempt.success_evidence_json['crane_recheck']['fired'] is False
|
||||
assert project_notice_upload_status(notice) == 'allocating'
|
||||
|
||||
complete_attempt(attempt, success=False, callback_id='recheck-1', result='allocating')
|
||||
assert attempt.success_evidence_json['crane_recheck']['due_at'] == due_at.isoformat(timespec='seconds')
|
||||
|
||||
with pytest.raises(ConflictError) as blocked:
|
||||
start_rpa_attempt(notice, artifact_id=artifact.id, idempotency_key='crane-key-2')
|
||||
assert blocked.value.code == 'SHIPPING.UPLOAD_CRANE_ALLOCATING'
|
||||
assert started < due_at
|
||||
|
||||
|
||||
def test_manual_refresh_does_not_move_the_one_scheduled_recheck(app):
|
||||
"""手动刷新另写一条状态回查,不改定时到期时间,也不把定时标记成已触发。"""
|
||||
with app.app_context():
|
||||
notice, artifact, _reservation = _ready_artifact()
|
||||
attempt = start_rpa_attempt(notice, artifact_id=artifact.id, idempotency_key='crane-manual')
|
||||
complete_attempt(attempt, success=False, callback_id='upload-manual', result='allocating')
|
||||
due_at = attempt.success_evidence_json['crane_recheck']['due_at']
|
||||
source = {'login_url': 'https://wms-portal.craneww.com/', 'connector_type': 'crane'}
|
||||
|
||||
first = request_manual_crane_refresh(
|
||||
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path,
|
||||
)
|
||||
assert first.endswith(f'upload_recheck_{notice.task_no}_manual.json')
|
||||
assert attempt.success_evidence_json['crane_recheck']['due_at'] == due_at
|
||||
assert attempt.success_evidence_json['crane_recheck']['fired'] is False
|
||||
|
||||
with pytest.raises(ConflictError) as inflight:
|
||||
request_manual_crane_refresh(
|
||||
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path,
|
||||
)
|
||||
assert inflight.value.code == 'SHIPPING.UPLOAD_CRANE_REFRESH_INFLIGHT'
|
||||
|
||||
future = datetime.fromisoformat(due_at) + timedelta(seconds=1)
|
||||
assert fire_scheduled_crane_recheck(
|
||||
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path, now=future,
|
||||
) is True
|
||||
assert fire_scheduled_crane_recheck(
|
||||
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path, now=future,
|
||||
) is False
|
||||
db.session.refresh(attempt)
|
||||
assert attempt.success_evidence_json['crane_recheck']['due_at'] == due_at
|
||||
assert attempt.success_evidence_json['crane_recheck']['fired'] is True
|
||||
@@ -1,16 +1,18 @@
|
||||
"""在途调拨单据级执行测试(execute_items 同步组合路径:门禁 + 组建单 + 逐单执行)。
|
||||
|
||||
用途:验证同步执行组合入口的两道门禁(①存在且可执行 ②文件版本对账,失败路径
|
||||
均携带 details 列表且外部系统 写入为 0;原「行级新鲜度 TTL」门禁已于
|
||||
2026-09-25 退役——items_stale 拒绝用例随之删除,TTL 降级为前端展示徽标)、
|
||||
D1 五元组建单与单据级写语义(一单一次 create_transfer、单内行共享单结果)、
|
||||
写前路由复查(漂移阻断)、result_unknown 不自动重试、单间失败隔离
|
||||
(不同组互不影响)、匹配 scope 执行入口(execute_matching_items)与按
|
||||
外部系统 单号投影。
|
||||
用途:验证同步执行组合入口的执行存在性门禁(①存在且可执行,失败携带 details
|
||||
列表且外部系统 写入为 0;原「文件版本对账」门禁已于 2026-10-22 退役——
|
||||
文件更新/缺失不再拦执行,行装饰 file_current 徽标仅提示,防错下沉 worker
|
||||
写前库存复查;原「行级新鲜度 TTL」门禁已于 2026-09-25 退役——items_stale
|
||||
拒绝用例随之删除,TTL 降级为前端展示徽标)、D1 五元组建单与单据级写语义
|
||||
(一单一次 create_transfer、单内行共享单结果)、写前路由复查(漂移阻断)、
|
||||
result_unknown 不自动重试、单间失败隔离(不同组互不影响)、匹配 scope
|
||||
执行入口(execute_matching_items)与按外部系统单号投影。
|
||||
依赖:transfer_db、fakes、repo_fakes、matching_service、execution_service。
|
||||
逻辑:T10 单据级重构后执行单元 = ERP 调拨单(TransferDocument);本文件为存量按行
|
||||
执行测试的按单改写版(场景不弱化:门禁/幂等/隔离/投影逐一保留);
|
||||
文件对账门禁经 patch_source_file_status 夹具注入来源文件状态投影替身。
|
||||
来源文件状态投影经 patch_source_file_status 夹具注入替身(装饰断言另打
|
||||
matching_service 命名空间)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -29,6 +31,7 @@ from app.services.in_transit_transfer.matching_service import (
|
||||
RouteMapping,
|
||||
TransferDeps,
|
||||
create_matching,
|
||||
list_executable_items,
|
||||
)
|
||||
from tests.services.in_transit_transfer.fakes import FakeCapabilityClient
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps, seed_rows_from_file
|
||||
@@ -252,35 +255,57 @@ def test_execute_items_rejects_unknown_or_not_ready_ids(transfer_db, dbs_ready_f
|
||||
assert _execution_runs() == []
|
||||
|
||||
|
||||
def test_execute_items_rejects_when_file_updated(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""门禁②:来源最新可用文件版本 ≠ 行评估版本戳(文件已更新未重新匹配)→ FILE_CHANGED。"""
|
||||
# monkeypatch resolve_source_file_status 返回新 checksum:模拟"文件更新但未重新匹配",
|
||||
# (重跑匹配会把行原地刷成新版本,无法构造本场景)。
|
||||
def test_execute_items_proceeds_when_file_updated_and_decorates_not_current(
|
||||
transfer_db, dbs_ready_file, patch_source_file_status, monkeypatch,
|
||||
):
|
||||
"""[2026-10-22 文件版本对账门禁退役] 文件已更新不再是执行门禁。
|
||||
|
||||
入站抓取是部分导出——新文件不含某行 ≠ 该行失效/已处理,按最新文件 sha
|
||||
对账曾把大量未处理行错误卡死(业务实测 557 行积压)。执行照常写 ERP;
|
||||
行装饰 file_current=False 仅提示不拦截,防错下沉 worker 写前库存复查。
|
||||
"""
|
||||
patch_source_file_status({"DBS-AWSBI": "e" * 64})
|
||||
# 装饰读取走 matching_service 命名空间的同名投影(退役后该函数仅剩展示
|
||||
# 消费方),此处同步打桩保持与执行侧替身同源。
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.matching_service.resolve_source_file_status",
|
||||
lambda *, source_code, record_kind="inbound": {
|
||||
"file_status": "ready", "has_ready_file": True,
|
||||
"file_no": "REC-TEST", "file_sha256": "e" * 64,
|
||||
},
|
||||
)
|
||||
deps, erp, items = _ready_items(
|
||||
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
||||
)
|
||||
# 断言:行当前性徽标如实提示「行评估版本戳 ≠ 最新可用文件」。
|
||||
listing = list_executable_items(deps=deps)
|
||||
decorated = {row.item_id: row for row in listing["items"]}
|
||||
assert all(decorated[item.id].file_current is False for item in items)
|
||||
|
||||
with pytest.raises(ValidationError) as excinfo:
|
||||
execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
assert excinfo.value.code == "TRANSFER.FILE_CHANGED"
|
||||
assert sorted(excinfo.value.details["changed_item_ids"]) == sorted(item.id for item in items)
|
||||
assert erp.write_calls() == []
|
||||
assert _execution_runs() == []
|
||||
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
# 断言:徽标不拦截执行——同组两 Invoice 合并一单、一次写调用、行全 success。
|
||||
assert outcome.status == "success"
|
||||
assert len(erp.write_calls()) == 1
|
||||
linked = _load_items(outcome.run_no)
|
||||
assert all(item.status == "success" for item in linked.values())
|
||||
|
||||
|
||||
def test_execute_items_rejects_when_source_file_missing(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""门禁②:来源无可用文件(latest 无 file_sha256)也属 FILE_CHANGED(fail-closed)。"""
|
||||
def test_execute_items_proceeds_when_source_file_missing(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""[2026-10-22 门禁退役] 来源无可用文件同样不拦执行。
|
||||
|
||||
档是镜像事实,不随当日文件可用性消失(evidence_sync 已落档的行照常可执行)。
|
||||
"""
|
||||
patch_source_file_status({"DBS-AWSBI": None})
|
||||
deps, erp, items = _ready_items(
|
||||
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError) as excinfo:
|
||||
execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
assert excinfo.value.code == "TRANSFER.FILE_CHANGED"
|
||||
assert sorted(excinfo.value.details["changed_item_ids"]) == sorted(item.id for item in items)
|
||||
assert erp.write_calls() == []
|
||||
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
# 断言:无可用文件不拒绝执行——照常组建单并写入外部系统。
|
||||
assert outcome.status == "success"
|
||||
assert len(erp.write_calls()) == 1
|
||||
linked = _load_items(outcome.run_no)
|
||||
assert all(item.status == "success" for item in linked.values())
|
||||
|
||||
|
||||
def test_execute_matching_items_executes_selected_invoices(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""在途调拨匹配服务测试(L1,SQLite 内存库)。
|
||||
|
||||
用途:验证日期范围校验(截止≤业务日期)、严格数量匹配、来源隔离、
|
||||
匹配快照 Hash 稳定、缺文件等待与进度恢复;专项用例锁生产默认 lag=2。
|
||||
匹配快照 Hash 稳定、缺文件等待与进度恢复、匹配顶替;专项用例锁生产默认 lag=2。
|
||||
依赖:app fixture、transfer_db、fakes、repo_fakes、matching_service。
|
||||
逻辑:全部经真实 ORM 落库(create_matching/restore_matching),
|
||||
外部依赖注入 Fake 替身。圈档记录类型用例直接插出站档行,
|
||||
@@ -1152,3 +1152,182 @@ def test_cancel_matching_releases_ledger_occupancy(transfer_db, dbs_ready_file):
|
||||
born = TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
|
||||
assert len(born) == 2
|
||||
assert all(row.status == "ready_to_execute" for row in born)
|
||||
|
||||
|
||||
def test_create_matching_supersedes_covered_unwritten_matching(transfer_db, dbs_ready_file):
|
||||
"""新匹配盖住同一类型、同一来源、尚未写 ERP 的旧匹配时,旧匹配取消,货出现在新匹配上。
|
||||
|
||||
夹具两行异动日都是 2026-08-04。第一次与第二次都用 08-01~08-04,新范围盖住旧范围。
|
||||
"""
|
||||
from app.models import TransferInvoiceItem, TransferMatching
|
||||
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
covered = dict(
|
||||
source_codes=["DBS-AWSBI"],
|
||||
business_date="2026-08-06",
|
||||
transfer_type="in_transit_to_hub",
|
||||
movement_date_from="2026-08-01",
|
||||
movement_date_to="2026-08-04",
|
||||
)
|
||||
|
||||
first = create_matching(deps=deps, **covered)
|
||||
# [断言意图] 顶替前旧匹配自己先圈到夹具的两张单,证明后面的 2 不是「本来就没占上」。
|
||||
assert first.counts.executable_count == 2
|
||||
|
||||
second = create_matching(deps=deps, **covered)
|
||||
|
||||
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
|
||||
# [断言意图] 被盖住且未写 ERP 的旧匹配不再有效,其可执行行不能留在队列里二次写 ERP。
|
||||
assert first_matching.status == "cancelled"
|
||||
retired = TransferInvoiceItem.query.filter_by(matching_id=first_matching.id).all()
|
||||
assert retired
|
||||
assert all(row.status == "cancelled" for row in retired)
|
||||
# [断言意图] 同一批货(HOM-001、HOX-002)出现在新匹配上,且仍可执行。
|
||||
assert second.counts.executable_count == 2
|
||||
second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one()
|
||||
reborn = {
|
||||
row.invoice_no
|
||||
for row in TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
|
||||
}
|
||||
assert reborn == {"HOM-001", "HOX-002"}
|
||||
|
||||
|
||||
def test_create_matching_supersedes_covered_matching_with_only_blocked_rows(transfer_db, dbs_ready_file):
|
||||
"""全阻断的旧匹配状态虽是 success,只要还没写 ERP,新范围盖住时仍要顶替。"""
|
||||
from app.models import TransferInvoiceItem, TransferMatching
|
||||
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1")
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
covered = dict(
|
||||
source_codes=["DBS-AWSBI"],
|
||||
business_date="2026-08-06",
|
||||
transfer_type="in_transit_to_hub",
|
||||
movement_date_from="2026-08-01",
|
||||
movement_date_to="2026-08-04",
|
||||
)
|
||||
first = create_matching(deps=deps, **covered)
|
||||
# [断言意图] 数量对不上时匹配状态是 success,不能因此被当成「已经写出单据」。
|
||||
assert first.status == "success"
|
||||
assert first.counts.executable_count == 0
|
||||
|
||||
second = create_matching(deps=deps, **covered)
|
||||
|
||||
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
|
||||
assert first_matching.status == "cancelled"
|
||||
second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one()
|
||||
reborn = {
|
||||
row.invoice_no
|
||||
for row in TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
|
||||
}
|
||||
assert reborn == {"HOM-001", "HOX-002"}
|
||||
|
||||
|
||||
def test_create_matching_keeps_previous_when_new_range_does_not_cover(transfer_db, dbs_ready_file):
|
||||
"""新范围盖不住旧范围时,旧匹配保持有效,货仍留在旧匹配上。"""
|
||||
from app.models import TransferMatching
|
||||
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
first = create_matching(
|
||||
source_codes=["DBS-AWSBI"],
|
||||
business_date="2026-08-06",
|
||||
deps=deps,
|
||||
transfer_type="in_transit_to_hub",
|
||||
movement_date_from="2026-08-01",
|
||||
movement_date_to="2026-08-04",
|
||||
)
|
||||
second = create_matching(
|
||||
source_codes=["DBS-AWSBI"],
|
||||
business_date="2026-08-06",
|
||||
deps=deps,
|
||||
transfer_type="in_transit_to_hub",
|
||||
movement_date_from="2026-08-04",
|
||||
movement_date_to="2026-08-04",
|
||||
)
|
||||
|
||||
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
|
||||
# [断言意图] 08-04~08-04 盖不住 08-01~08-04,旧匹配不能被取消。
|
||||
assert first_matching.status == "ready_to_execute"
|
||||
# [断言意图] 货仍被旧匹配占用,新匹配圈不到,清单不另列历史匹配编号。
|
||||
assert second.counts.executable_count == 0
|
||||
|
||||
|
||||
def test_supersede_keeps_manually_closed_goods_out_of_the_new_matching(transfer_db, dbs_ready_file):
|
||||
"""顶替后,人工关闭的单号不回到新匹配。"""
|
||||
from app.models import TransferInvoiceItem, TransferMatching
|
||||
from app.services.in_transit_transfer.manual_close_service import manual_close_item
|
||||
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
covered = dict(
|
||||
source_codes=["DBS-AWSBI"],
|
||||
business_date="2026-08-06",
|
||||
transfer_type="in_transit_to_hub",
|
||||
movement_date_from="2026-08-01",
|
||||
movement_date_to="2026-08-04",
|
||||
)
|
||||
first = create_matching(deps=deps, **covered)
|
||||
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
|
||||
closed = TransferInvoiceItem.query.filter_by(matching_id=first_matching.id, invoice_no="HOX-002").one()
|
||||
manual_close_item(item_id=closed.id, reason="这批不再调拨")
|
||||
|
||||
second = create_matching(deps=deps, **covered)
|
||||
|
||||
# [断言意图] 人工关闭跨过顶替仍然有效,新匹配不能把 HOX-002 再圈成可执行。
|
||||
assert db.session.get(TransferInvoiceItem, closed.id).status == "manually_closed"
|
||||
second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one()
|
||||
reborn = {
|
||||
row.invoice_no
|
||||
for row in TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
|
||||
}
|
||||
assert reborn == {"HOM-001"}
|
||||
|
||||
|
||||
def test_unattached_item_does_not_block_a_new_matching(transfer_db, dbs_ready_file):
|
||||
"""没有挂上任何匹配的明细不占货,新匹配仍能圈到那张单。"""
|
||||
from app.models import TransferInvoiceItem, TransferMatching, TransferMovementLedger
|
||||
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
ledger = TransferMovementLedger.query.filter_by(source_code="DBS-AWSBI", doc_no="HOM-001").first()
|
||||
db.session.add(TransferInvoiceItem(
|
||||
matching_id=None,
|
||||
ledger_record_id=ledger.id,
|
||||
source_code="DBS-AWSBI",
|
||||
invoice_no="HOM-001",
|
||||
material_no="MAT-001",
|
||||
movement_date="2026-08-04",
|
||||
from_warehouse="DBS-TRANSIT",
|
||||
to_warehouse="HUB-CN01",
|
||||
movement_quantity="1200",
|
||||
status="matching",
|
||||
result_code="pending_stock_check",
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
summary = create_matching(
|
||||
source_codes=["DBS-AWSBI"],
|
||||
business_date="2026-08-06",
|
||||
deps=deps,
|
||||
transfer_type="in_transit_to_hub",
|
||||
movement_date_from="2026-08-01",
|
||||
movement_date_to="2026-08-04",
|
||||
)
|
||||
matching = TransferMatching.query.filter_by(matching_no=summary.matching_id).one()
|
||||
# [断言意图] 悬挂行没有匹配编号,不能挡住 HOM-001;两张夹具单都进新匹配。
|
||||
invoices = {
|
||||
row.invoice_no
|
||||
for row in TransferInvoiceItem.query.filter_by(matching_id=matching.id).all()
|
||||
}
|
||||
assert invoices == {"HOM-001", "HOX-002"}
|
||||
@@ -3,14 +3,20 @@
|
||||
用途:验证在途自动调拨 platform job 注册契约与 handler 调用形态;
|
||||
in-transit-receipt-file 已于 2026-09-28 下线(文件就绪保障内建于自动调拨,
|
||||
见 job_registry 在途自动调拨描述),此处锁定其"不再注册"防回归。
|
||||
依赖:schedule.job_registry、inbound_trigger_service、in_transit_transfer_job。
|
||||
逻辑:只验证注册契约与调用形态,真实排程触发由 scheduler 驱动。
|
||||
依赖:schedule.job_registry、job_options、inbound_trigger_service、
|
||||
transfer_type_config_service、in_transit_transfer_job。
|
||||
逻辑:只验证注册契约与调用形态(run_auto_transfer/run_daily_recovery 打桩),
|
||||
真实排程触发由 scheduler 驱动;七元组位序=(total, success, failed,
|
||||
skipped, results, errors, step_logs),errors 位只放真实错误。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome
|
||||
from app.services.in_transit_transfer.recovery_service import RecoveryOutcome
|
||||
from app.services.schedule.job_options import is_known_options_source
|
||||
from app.services.schedule.job_registry import get_platform_job, list_platform_jobs
|
||||
|
||||
|
||||
@@ -22,14 +28,23 @@ def test_receipt_file_job_deregistered():
|
||||
|
||||
|
||||
def test_transfer_job_registered_with_schedule_defaults():
|
||||
"""自动调拨 job 注册且含来源/恢复参数契约;描述不得硬编码时刻。"""
|
||||
"""自动调拨 job 注册且含类型/来源/恢复参数契约;描述不得硬编码时刻。"""
|
||||
import re
|
||||
|
||||
job = get_platform_job("in-transit-transfer")
|
||||
assert job is not None
|
||||
assert job.enabled
|
||||
keys = {field.get("key") for field in job.params_schema}
|
||||
assert {"source_codes", "recover_history", "receipt_from_offset_days", "receipt_to_offset_days"} <= keys
|
||||
assert {
|
||||
"transfer_types", "source_codes", "recover_history",
|
||||
"receipt_from_offset_days", "receipt_to_offset_days",
|
||||
} <= keys
|
||||
# 断言:调拨类型=multi_select 动态选项源(启用中的类型配置),留空=全部。
|
||||
types_field = next(f for f in job.params_schema if f.get("key") == "transfer_types")
|
||||
assert types_field.get("type") == "multi_select"
|
||||
assert types_field.get("options_source") == "transfer_types"
|
||||
assert types_field.get("default") == []
|
||||
assert is_known_options_source("transfer_types")
|
||||
# 断言:任务级通知人已移除——通知统一走排程「启用通知」,防止参数回归。
|
||||
assert "notify_user_ids" not in keys
|
||||
assert not re.search(r"\d{2}:\d{2}", job.description), "描述禁止硬编码执行时刻"
|
||||
@@ -133,55 +148,108 @@ def test_wanted_source_codes_falls_back_when_empty(monkeypatch):
|
||||
assert _wanted_source_codes(string_param) == ["DBS_HUB"]
|
||||
|
||||
|
||||
def test_handler_empty_data_day_stays_silent(monkeypatch):
|
||||
"""空数据日(无 run_no 且无 errors):不传领域通知参数,置静默标记抑制框架完成卡(C5)。"""
|
||||
def test_wanted_transfer_types_falls_back_to_all_enabled(monkeypatch):
|
||||
"""调拨类型留空=全部启用类型;显式选择优先;空配置/脏配置 fail-closed 落错误。"""
|
||||
import app.services.in_transit_transfer.transfer_type_config_service as type_mod
|
||||
from app.services.schedule.in_transit_transfer_job import _wanted_transfer_types
|
||||
|
||||
errors: list[str] = []
|
||||
monkeypatch.setattr(type_mod, "get_enabled", lambda: [
|
||||
SimpleNamespace(code="in_transit_to_hub"), SimpleNamespace(code="hub_repair_out"),
|
||||
])
|
||||
assert _wanted_transfer_types({}, errors) == ["in_transit_to_hub", "hub_repair_out"]
|
||||
assert errors == []
|
||||
assert _wanted_transfer_types({"transfer_types": ["in_transit_to_hub"]}, errors) == ["in_transit_to_hub"]
|
||||
assert _wanted_transfer_types({"transfer_types": "hub_to_hub"}, errors) == ["hub_to_hub"]
|
||||
|
||||
monkeypatch.setattr(type_mod, "get_enabled", lambda: [])
|
||||
assert _wanted_transfer_types({}, errors) == []
|
||||
# 断言:空类型配置不静默——落错误由调用方硬失败(D8 fail-closed)。
|
||||
assert errors and "调拨类型" in errors[-1]
|
||||
|
||||
|
||||
def test_transfer_types_options_provider_lists_enabled(app, transfer_db):
|
||||
"""transfer_types 选项源:仅启用类型,label 取 names zh-CN,value=类型编码。"""
|
||||
from tests.services.in_transit_transfer.factories import seed_transfer_type_config
|
||||
from app.services.schedule.job_options import list_job_options
|
||||
|
||||
seed_transfer_type_config("in_transit_to_hub", enabled=True)
|
||||
seed_transfer_type_config("hub_repair_out", enabled=False)
|
||||
transfer_db.session.commit()
|
||||
|
||||
options = list_job_options("transfer_types")
|
||||
codes = {option["value"] for option in options}
|
||||
# 断言:停用类型不进选项(与排程留空=全部启用类型的口径一致)。
|
||||
assert "in_transit_to_hub" in codes
|
||||
assert "hub_repair_out" not in codes
|
||||
label = next(o["label"] for o in options if o["value"] == "in_transit_to_hub")
|
||||
assert label == "类型 in_transit_to_hub"
|
||||
|
||||
|
||||
def _patch_schedule_env(monkeypatch, *, types=None, sources=("CRANE_SGP",)):
|
||||
"""handler 单测公共打桩:来源/类型缺省口径 + 依赖与恢复隔离(不触库)。"""
|
||||
import app.services.in_transit_transfer.transfer_type_config_service as type_mod
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: list(sources))
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
monkeypatch.setattr(
|
||||
type_mod, "get_enabled",
|
||||
lambda: [SimpleNamespace(code=code) for code in (types if types is not None else ["in_transit_to_hub"])],
|
||||
)
|
||||
return job_mod
|
||||
|
||||
|
||||
def test_handler_empty_data_day_stays_silent(monkeypatch):
|
||||
"""空数据日(全部类型均无 run 且无 errors):置静默标记抑制框架完成卡(C5)。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||
captured = {}
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return job_mod.AutoTransferOutcome()
|
||||
return AutoTransferOutcome()
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
task = ScheduleTask(job_params={"source_codes": [], "recover_history": True})
|
||||
run = ScheduleRun(run_no="RUNR-1", status="running")
|
||||
total, success, failed, skipped, results, warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
total, success, failed, skipped, results, errors, step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
|
||||
# 断言:领域通知接线已移除(不再透传 sender/recipients);空数据日置 C5 静默标记。
|
||||
assert "sender" not in captured
|
||||
assert "recipients" not in captured
|
||||
# 断言:恢复在循环外只跑一次;run_auto_transfer 恒收 recover_history=False。
|
||||
assert captured["recover_history"] is False
|
||||
assert captured["movement_date_from"] is None
|
||||
assert captured["movement_date_to"] is None
|
||||
assert captured["source_codes"] == ["CRANE_SGP"]
|
||||
assert captured["recover_history"] is True
|
||||
assert captured["transfer_type"] == "in_transit_to_hub"
|
||||
assert run.response_summary_json["domain_notification_managed"] is True
|
||||
assert (total, success, failed, skipped) == (0, 0, 0, 0)
|
||||
assert results == []
|
||||
assert any("no executable items" in w for w in warnings)
|
||||
assert results == [] and errors == []
|
||||
# 断言:恢复汇总与空数据说明落 step_logs(dict),errors 位不受污染。
|
||||
assert step_logs[0]["step"] == "recovery"
|
||||
assert any(item.get("step") == "auto_transfer" for item in step_logs)
|
||||
|
||||
|
||||
def test_handler_converts_t_minus_offsets(monkeypatch):
|
||||
"""T−N 偏移天数按执行日业务日换算为具体收料日期透传;留空为 None。"""
|
||||
from datetime import date
|
||||
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||
monkeypatch.setattr(job_mod, "business_date_now", lambda: date(2026, 10, 12))
|
||||
captured = {}
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return job_mod.AutoTransferOutcome()
|
||||
return AutoTransferOutcome()
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
task = ScheduleTask(job_params={"receipt_from_offset_days": 4, "receipt_to_offset_days": 2})
|
||||
run = ScheduleRun(run_no="RUNR-4", status="running")
|
||||
@@ -195,79 +263,227 @@ def test_handler_converts_t_minus_offsets(monkeypatch):
|
||||
|
||||
def test_handler_rejects_invalid_offset_without_execution(monkeypatch):
|
||||
"""偏移非法(负数/非整数):快速失败不执行,错误走框架失败通知。"""
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
|
||||
def _must_not_run(**kwargs):
|
||||
raise AssertionError("run_auto_transfer must not run with invalid offsets")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _must_not_run)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
run = ScheduleRun(run_no="RUNR-5", status="running")
|
||||
task = ScheduleTask(job_params={"receipt_from_offset_days": -1})
|
||||
_total, _success, _failed, _skipped, results, _warnings, errors = (
|
||||
total, _success, failed, _skipped, results, errors, _step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
# 断言:负数偏移不执行、不置静默标记(框架卡照常告警),错误信息含参数名。
|
||||
# 断言:负数偏移不执行、不置静默标记(框架卡照常告警),错误信息含参数名;
|
||||
# failed_count=1 使终态为 failed(total=0+errors 会被框架误判 success,禁用)。
|
||||
assert (total, failed) == (1, 1)
|
||||
assert results == []
|
||||
assert any("异动日期起点" in e for e in errors)
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
|
||||
task = ScheduleTask(job_params={"receipt_to_offset_days": 2.5})
|
||||
_total, _success, _failed, _skipped, _results, _warnings, errors = (
|
||||
_total, _success, _failed, _skipped, _results, errors, _step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
# 断言:小数偏移同样快速失败。
|
||||
assert any("异动日期终点" in e for e in errors)
|
||||
|
||||
|
||||
def test_handler_run_day_uses_framework_notification(monkeypatch):
|
||||
"""有 Run(成功):不置静默标记,框架完成卡按排程「启用通知」照常发送。"""
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
def test_handler_runs_each_type_once_and_recovery_once(monkeypatch):
|
||||
"""多类型逐轮执行:每类型一次 run_auto_transfer(recover_history=False),恢复只跑一次。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
job_mod = _patch_schedule_env(monkeypatch, types=["in_transit_to_hub", "hub_repair_out"])
|
||||
recovery_calls: list[dict] = []
|
||||
|
||||
def _fake_recovery(**kwargs):
|
||||
recovery_calls.append(kwargs)
|
||||
return RecoveryOutcome(recovered_count=2)
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", _fake_recovery)
|
||||
calls: list[dict] = []
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
return job_mod.AutoTransferOutcome(run_no="TR-1", run_status="success")
|
||||
calls.append(kwargs)
|
||||
return AutoTransferOutcome(run_no=f"TR-{len(calls)}", run_status="success")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
|
||||
task = ScheduleTask(job_params={"transfer_types": ["in_transit_to_hub", "hub_repair_out"]})
|
||||
run = ScheduleRun(run_no="RUNR-6", status="running")
|
||||
total, success, failed, skipped, results, errors, step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
|
||||
# 断言:逐类型各跑一轮且带类型编码;恢复与类型无关只跑一次。
|
||||
assert [c["transfer_type"] for c in calls] == ["in_transit_to_hub", "hub_repair_out"]
|
||||
assert all(c["recover_history"] is False for c in calls)
|
||||
assert len(recovery_calls) == 1
|
||||
# 断言:total=success+failed+recovered(2 成功 Run + 2 恢复行)。
|
||||
assert (total, success, failed, skipped) == (4, 2, 0, 0)
|
||||
assert [r["run_no"] for r in results] == ["TR-1", "TR-2"]
|
||||
assert errors == []
|
||||
# 断言:恢复汇总落 step_logs(recovered=2),errors 位只放真实错误。
|
||||
assert step_logs[0]["step"] == "recovery"
|
||||
assert step_logs[0]["detail"]["recovered"] == 2
|
||||
|
||||
|
||||
def test_handler_empty_type_config_fails_hard(monkeypatch):
|
||||
"""类型配置为空:fail-closed 硬失败(failed=1 → 框架 failed 终态),不执行。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
job_mod = _patch_schedule_env(monkeypatch, types=[])
|
||||
|
||||
def _must_not_run(**kwargs):
|
||||
raise AssertionError("run_auto_transfer must not run without transfer types")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _must_not_run)
|
||||
|
||||
task = ScheduleTask(job_params={})
|
||||
run = ScheduleRun(run_no="RUNR-7", status="running")
|
||||
total, _success, failed, _skipped, results, errors, _step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
# 断言:空配置硬失败不执行、不静默,错误信息指向类型配置缺失。
|
||||
assert (total, failed) == (1, 1)
|
||||
assert results == []
|
||||
assert any("调拨类型" in e for e in errors)
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
|
||||
|
||||
def test_handler_run_day_uses_framework_notification(monkeypatch):
|
||||
"""有 Run(成功):不置静默标记,框架完成卡按排程「启用通知」照常发送。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
return AutoTransferOutcome(run_no="TR-1", run_status="success")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
task = ScheduleTask(job_params={})
|
||||
run = ScheduleRun(run_no="RUNR-2", status="running")
|
||||
total, success, failed, skipped, results, _warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
total, success, failed, skipped, results, errors, _step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
|
||||
# 断言:有 run 不抑制框架通知;run_no 落入 results 供完成卡/留痕展示。
|
||||
# 断言:有 run 不抑制框架通知;run_no+类型落入 results 供完成卡/留痕展示。
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
assert results and results[0]["run_no"] == "TR-1"
|
||||
assert results[0]["transfer_type"] == "in_transit_to_hub"
|
||||
assert (total, success, failed, skipped) == (1, 1, 0, 0)
|
||||
assert errors == []
|
||||
|
||||
|
||||
def test_handler_hard_failure_keeps_framework_notification(monkeypatch):
|
||||
"""硬失败(无 run_no、有 errors):不置静默标记,框架完成卡兜底告警。"""
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
def test_handler_recovery_failure_counts_as_failed(monkeypatch):
|
||||
"""恢复复核抛异常:计一个 failed 单元——防止「恢复失败+空数据日」被框架判 success。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
|
||||
def _boom(**_kwargs):
|
||||
raise RuntimeError("stock source offline")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", _boom)
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
return job_mod.AutoTransferOutcome(errors=["match pipeline boom"])
|
||||
return AutoTransferOutcome() # 各类型均空数据(无 Run 无错误)
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
|
||||
task = ScheduleTask(job_params={})
|
||||
run = ScheduleRun(run_no="RUNR-9", status="running")
|
||||
total, success, failed, _skipped, results, errors, step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
# 断言:恢复失败落 errors 且计 failed(终态 failed 交框架失败通知),
|
||||
# 恢复 step_log 标 failed;不置静默标记。
|
||||
assert (total, success, failed) == (1, 0, 1)
|
||||
assert results == []
|
||||
assert errors == ["recovery_failed: stock source offline"]
|
||||
assert step_logs[0]["step"] == "recovery" and step_logs[0]["status"] == "failed"
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
|
||||
|
||||
def test_handler_recovery_skipped_marks_step_log(monkeypatch):
|
||||
"""recover_history=false:恢复不执行,step_log 标 skipped 且不计 failed。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
|
||||
def _must_not_recover(**_kwargs):
|
||||
raise AssertionError("run_daily_recovery must not run when recover_history is false")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", _must_not_recover)
|
||||
monkeypatch.setattr(
|
||||
job_mod, "run_auto_transfer",
|
||||
lambda **_kwargs: AutoTransferOutcome(run_no="TR-10", run_status="success"),
|
||||
)
|
||||
|
||||
task = ScheduleTask(job_params={"recover_history": False})
|
||||
run = ScheduleRun(run_no="RUNR-10", status="running")
|
||||
total, success, failed, _skipped, results, errors, step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
# 断言:恢复被跳过(step_log=skipped、无恢复错误),Run 照常产出。
|
||||
assert (total, success, failed) == (1, 1, 0)
|
||||
assert results and results[0]["run_no"] == "TR-10"
|
||||
assert errors == []
|
||||
assert step_logs[0]["step"] == "recovery" and step_logs[0]["status"] == "skipped"
|
||||
|
||||
|
||||
def test_handler_hard_failure_keeps_framework_notification(monkeypatch):
|
||||
"""硬失败(无 run_no、有 errors):不置静默标记,框架完成卡兜底告警。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
return AutoTransferOutcome(errors=["match pipeline boom"])
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
task = ScheduleTask(job_params={})
|
||||
run = ScheduleRun(run_no="RUNR-3", status="running")
|
||||
_total, _success, _failed, _skipped, results, _warnings, errors = (
|
||||
_total, _success, failed, _skipped, results, errors, _step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
|
||||
# 断言:硬失败不抑制框架完成卡(兜底告警),errors 原样上抛、无 results。
|
||||
# 断言:硬失败不抑制框架完成卡(兜底告警),errors 原样上抛、无 results,
|
||||
# 该类型计入 failed_count(终态 failed 交框架失败通知)。
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
assert results == []
|
||||
assert errors == ["match pipeline boom"]
|
||||
assert failed == 1
|
||||
|
||||
|
||||
def test_handler_type_failure_isolated_per_type(monkeypatch):
|
||||
"""单类型硬失败不阻断其余类型;失败类型计入 failed,成功类型照常出 Run。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
job_mod = _patch_schedule_env(monkeypatch, types=["bad_type", "in_transit_to_hub"])
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
if kwargs["transfer_type"] == "bad_type":
|
||||
return AutoTransferOutcome(errors=["type config disabled"])
|
||||
return AutoTransferOutcome(run_no="TR-9", run_status="success")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
|
||||
task = ScheduleTask(job_params={})
|
||||
run = ScheduleRun(run_no="RUNR-8", status="running")
|
||||
total, success, failed, _skipped, results, errors, _step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
|
||||
# 断言:好类型照常执行出 Run;坏类型落 errors 并计入 failed(部分失败终态)。
|
||||
assert (total, success, failed) == (2, 1, 1)
|
||||
assert len(results) == 1 and results[0]["transfer_type"] == "in_transit_to_hub"
|
||||
assert errors == ["type config disabled"]
|
||||
@@ -1410,7 +1410,7 @@ def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path):
|
||||
|
||||
assert events[0] == ("session", "https://s360.dbschenker.com/")
|
||||
assert events[1] == ("goto", "https://s360.dbschenker.com/main/portal/frame/WMSUpload2")
|
||||
assert ("file", "#file2") in events
|
||||
assert ("file", "input#file2") in events
|
||||
assert ("click", 'button.btn.btn-primary.upload-button:has-text("Process File")') in events
|
||||
|
||||
|
||||
|
||||
@@ -142,7 +142,7 @@ def _freeze_export_snapshot(
|
||||
|
||||
def _materialize_export_notice(
|
||||
*, ot: ShippingOrderTask, snapshot: ShippingOrderSnapshot, inventory_file: FreightRpaOnhandReportFile,
|
||||
source_code: str, notice_no: str,
|
||||
source_code: str, notice_no: str, match_result: str = 'matched',
|
||||
) -> ShippingNotice:
|
||||
"""从 OT 的冻结快照构造正式 Notice、NoticeLine、匹配事实与活动库存链接。
|
||||
|
||||
@@ -168,7 +168,8 @@ def _materialize_export_notice(
|
||||
for line in snapshot.lines:
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
task_id=ot.id, snapshot_line_id=line.id, line_no=line.line_no,
|
||||
match_result='matched', onhand_status='ready',
|
||||
line_index=int(line.line_no) - 1,
|
||||
match_result=match_result, onhand_status='ready',
|
||||
onhand_snapshot_id=inventory_file.id, source_code=source_code,
|
||||
is_current=True, detail_json={},
|
||||
))
|
||||
@@ -922,6 +923,8 @@ def test_export_commit_failure_removes_generated_file(app, tmp_path, monkeypatch
|
||||
|
||||
def _build_multi_odm_notice(
|
||||
*, tmp_path, odm_values=None, customer_odm_ids=None, choice_odm=None, line_specs=None,
|
||||
released_shortage: bool = False, unreleased_shortage: bool = False,
|
||||
order_part: str = 'PN-A', inventory_part: str | None = None,
|
||||
):
|
||||
"""
|
||||
构造「订单行命中多个 ODM ID」的整单导出场景;须在 app_context 内调用。
|
||||
@@ -931,6 +934,11 @@ def _build_multi_odm_notice(
|
||||
line_specs: 多订单行场景 [{'part': 料号, 'odm_values': [...]}];提供时忽略 odm_values。
|
||||
customer_odm_ids: 客户数据的 ODM ID 范围(None = 不限定)。
|
||||
choice_odm: 整单用户选择(写入 OT.chosen_odm_id)
|
||||
released_shortage: True 时唯一行构造为短缺放行场景——订单料号不在库存行
|
||||
(匹配键 0 命中)、事实落 not_found、并落已确认复核 Case 的系统放行决定
|
||||
(release_field_values 携带 ODM 证据值),整单无任何 matched 事实。
|
||||
unreleased_shortage: True 时事实落 not_found 但不落放行决定(未放行短缺)。
|
||||
order_part / inventory_part: 订单行与库存行的料号(放行场景两者必须不同)。
|
||||
Returns:
|
||||
(notice, customer)。
|
||||
"""
|
||||
@@ -979,7 +987,7 @@ def _build_multi_odm_notice(
|
||||
task_id=ot.id, schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction); db.session.flush()
|
||||
specs = line_specs or [{'part': 'PN-A', 'odm_values': odm_values}]
|
||||
specs = line_specs or [{'part': order_part, 'odm_values': odm_values}]
|
||||
snapshot_lines = []
|
||||
for index, spec in enumerate(specs, start=1):
|
||||
order_line = ShippingOrderLine(extraction_id=extraction.id, position=index, line_no=index)
|
||||
@@ -998,7 +1006,7 @@ def _build_multi_odm_notice(
|
||||
inventory_rows = []
|
||||
for spec in specs:
|
||||
for odm in spec['odm_values']:
|
||||
inventory_rows.append({_inventory_field_id('part_number'): spec['part'], _inventory_field_id('odm_id'): odm})
|
||||
inventory_rows.append({_inventory_field_id('part_number'): inventory_part or spec['part'], _inventory_field_id('odm_id'): odm})
|
||||
inventory_file = FreightRpaOnhandReportFile(
|
||||
onhand_file_no='SIF-ODMSCOPE', user_id=None, source_file_name='odm-scope.xlsx',
|
||||
storage_path=str(tmp_path / 'odm-scope.xlsx'),
|
||||
@@ -1014,7 +1022,25 @@ def _build_multi_odm_notice(
|
||||
)
|
||||
notice = _materialize_export_notice(
|
||||
ot=ot, snapshot=snapshot, inventory_file=inventory_file, source_code='ODMSCOPE', notice_no='TASK-ODMSCOPE',
|
||||
match_result='not_found' if (released_shortage or unreleased_shortage) else 'matched',
|
||||
)
|
||||
if released_shortage:
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
|
||||
case = ShippingOrderReviewCase(
|
||||
case_no='CASE-ODMSCOPE-RELEASE', run_id=931, unit_id=932, document_id=933,
|
||||
owner_user_id=1, status='confirmed', confirmed_task_id=int(ot.id),
|
||||
)
|
||||
db.session.add(case); db.session.flush()
|
||||
db.session.add(ShippingOrderReviewLineDecision(
|
||||
review_case_id=case.id, draft_line_id='line-1', line_index=0,
|
||||
decision_code='release_onhand_shortage', decision_source='system',
|
||||
line_status='released_shortage', is_active=True,
|
||||
snapshot_json={
|
||||
'release_field_values': {str(_inventory_field_id('odm_id')): 'ODM-1'},
|
||||
'release_evidence_scope': 'part_fallback',
|
||||
},
|
||||
))
|
||||
db.session.flush()
|
||||
if choice_odm is not None:
|
||||
for match in ShippingNoticeLineOnhandMatch.query.filter_by(task_id=int(ot.id), is_current=True).all():
|
||||
match.chosen_odm_id = choice_odm
|
||||
@@ -1113,6 +1139,60 @@ def test_export_keeps_conflict_when_odm_scope_cannot_decide(app, tmp_path):
|
||||
generate_shipment_excel(task)
|
||||
|
||||
|
||||
def test_export_released_shortage_only_notice_resolves_source_and_rows(app, tmp_path):
|
||||
"""整单短缺放行(0 条 matched 事实)也能解析库存源并按放行证据导出。
|
||||
|
||||
回归 OT-20261027-4BD4CEFF:预约键 0 命中→料号兜底自动放行后,行事实恒为
|
||||
not_found;_notice_source_code 只认 matched 会让整单放行的单报
|
||||
「库存源不存在或已停用」;prepare_export_match_inputs 的放行决定 join 须按
|
||||
confirmed_task_id(OT) 回链,Notice 身份调用不得丢放行行。
|
||||
"""
|
||||
from app.services.shipping_notice.export import _notice_source_code, prepare_export_match_inputs
|
||||
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
notice, _customer = _build_multi_odm_notice(
|
||||
tmp_path=tmp_path, released_shortage=True,
|
||||
order_part='PN-GONE', inventory_part='PN-OTHER', odm_values=['ODM-1'],
|
||||
)
|
||||
|
||||
# 断言意图 1:源解析把放行行事实与 matched 行同票,整单放行也能拿到唯一源。
|
||||
assert _notice_source_code(notice) == 'ODMSCOPE'
|
||||
|
||||
# 断言意图 2:以 Notice 身份准备导出输入,放行决定经 OT 回链可查到,
|
||||
# 放行行进入导出行集并携带审计补录值(无 matched 事实也不报「没有匹配」)。
|
||||
inputs = prepare_export_match_inputs(notice)
|
||||
assert inputs['released_snapshot_line_ids']
|
||||
assert inputs['released_export_line_indexes'] == {0}
|
||||
assert list(inputs['release_overrides_by_line'][0].values()) == ['ODM-1']
|
||||
assert [row['__order_line_index'] for row in inputs['line_values']] == [0]
|
||||
|
||||
# 断言意图 3:整单放行时证据快照仍落 Artifact 审计(matched-only 不再断证据链)。
|
||||
assert inputs['verification'] is not None
|
||||
|
||||
path, _filename_value, _artifact = generate_shipment_excel(notice)
|
||||
workbook = load_workbook(path, data_only=True)
|
||||
try:
|
||||
assert workbook['Detail'].cell(2, 1).value == 'ODM-1'
|
||||
finally:
|
||||
workbook.close()
|
||||
|
||||
|
||||
def test_unreleased_shortage_notice_still_lacks_source(app, tmp_path):
|
||||
"""未放行的短缺行不得参与源解析:matched-only 语义对未放行场景保持不变。"""
|
||||
from app.services.shipping_notice.export import _notice_source_code
|
||||
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
notice, _customer = _build_multi_odm_notice(
|
||||
tmp_path=tmp_path, unreleased_shortage=True,
|
||||
order_part='PN-GONE', inventory_part='PN-OTHER', odm_values=['ODM-1'],
|
||||
)
|
||||
|
||||
# 断言意图:not_found 且无放行决定的事实不充当导出源依据(fail-closed 不变)。
|
||||
assert _notice_source_code(notice) is None
|
||||
|
||||
|
||||
def test_notice_odm_options_and_choice_roundtrip(app, tmp_path):
|
||||
"""整单候选按客户范围逐行投影;合法选择落库并回显,非法选择有明确错误。"""
|
||||
from app.core.errors import AppError
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# 调拨对话只解释规则并带路
|
||||
|
||||
状态:被 [ADR 0006](0006-defer-transfer-conversation.md) 取代(2026-10-26)。下文保留当时的取舍,不再作为实施依据。
|
||||
|
||||
手工调拨已由卡片按钮测通,自动调拨另案验收。2026-10-26 决定:在途调拨的第一刀对话只做简体中文的规则说明,并按固定带路表打开已有视图、指出按钮。生成调拨单、勾选、关闭、重查、重新触发仍由那些按钮提交。首页已经显示的数量不在对话里重报。Dify 1.16.1 Chatflow 只交回一句中文和一个可选视图代码;未知代码或只问数量时留在首页。提示词以仓库文本为唯一口径,从仓库发布到 Dify。
|
||||
|
||||
这样做是因为写接口一旦成为模型工具,就会绕开卡片上已经测过的门禁(看见的行、关闭必填原因、结果未知只能重新触发)。气泡图平台把写操作做成确认后的工具,是因为那里没有这套卡片。首页数字在能打字时已经可见,再查一套没有意义。
|
||||
|
||||
## Considered Options
|
||||
|
||||
- **Dify 直接调用写接口,或用 Human Input 再确认一次**:被否——同一件提交会有两扇门,Human Input 与匹配卡、执行看板重复。
|
||||
- **每轮把首页计数塞进提示词,由模型报数**:被否——能对话时人就在首页,卡片已经是这套数字的呈现。
|
||||
- **自研多轮工具循环**:被否——HXOPS 的 hybrid 运行时已经只接 Dify Chatflow。
|
||||
|
||||
## Consequences
|
||||
|
||||
- 带路表:规则或数量留在首页;库存匹配打开来源选择(确认范围并匹配);待匹配只读;生成、勾选、可调拨明细打开可调拨明细(生成调拨单);重查、恢复处理、关闭异常行打开待恢复异常(重查库存,或关闭且须填原因);已人工关闭只查看原因;结果未知打开执行看板对应分组(重新触发);关闭调拨单或看失败单打开执行看板的失败分组(关闭调拨单)。没分清是待恢复异常还是失败调拨单时先问,不猜。
|
||||
- 提示词只陈述八条:执行边界是出入站来源实例;数量必须与 ERP 严格相等;恢复处理就是重查库存;人工关闭只保留原因;结果未知只能在执行看板重新触发;写操作在卡片按钮上完成;数量以首页卡片为准;不讲述某一次自动调拨,也不解释某一张发票为什么被挡住。点名发票、追问某次自动运行或要求直接生成时,只说明并打开对应类别的视图。
|
||||
- 界面四语言卡片不变。自动调拨的测试、排程和 ERP 写路径不在本决策内。按发票解释阻断原因、讲述最近一次自动运行、在对话里填好来源和日期并创建匹配,留到下一刀。
|
||||
- 术语见 `docs/features/in-transit-transfer/GLOSSARY.md` 的调拨对话、恢复处理、人工关闭、结果未知。
|
||||
@@ -0,0 +1,18 @@
|
||||
# 调拨对话先不做
|
||||
|
||||
状态:accepted,取代 [ADR 0005](0005-transfer-conversation-explains-and-routes.md)。
|
||||
|
||||
2026-10-26 决定先不做在途调拨对话。匹配、勾选、生成调拨单、重查库存、人工关闭和重新触发都是确定动作,现有卡片已经是最短路径。再加一轮 Chatflow,只是在同一次点击之前多一次等待。规则说明也不在这轮写成卡片旁的固定文字。
|
||||
|
||||
按某张发票解释阻断原因,留到卡片上的现有文字确实答不清时再单独立项。在那之前不接 Chatflow,不发布提示词,不增加视图代码。
|
||||
|
||||
## Considered Options
|
||||
|
||||
- **按 ADR 0005 做解释加带路**:被否——带路的终点仍是现有按钮,对话比直接点卡片更慢。
|
||||
- **现在就把规则写进卡片文案**:被否——这轮连说明文案也不加,避免借停对话之机扩大改动。
|
||||
|
||||
## Consequences
|
||||
|
||||
- 不写规格,不改聊天回合,不改首页视图切换。
|
||||
- 自动调拨的测试、排程和 ERP 写路径仍按原案,与本决定无关。
|
||||
- 术语表不保留「调拨对话」。恢复处理、人工关闭、结果未知仍是现行卡片上的概念。
|
||||
@@ -0,0 +1,18 @@
|
||||
# 新匹配顶替尚未写 ERP 的旧匹配
|
||||
|
||||
状态:accepted。
|
||||
|
||||
2026-10-27 决定:提交一次新匹配时,取消所有被它盖住、且还没有任何 ERP 单据的旧匹配,再按新的日期范围重新圈档。同一批货不能同时留在两张未取消的匹配上,否则可执行行会各写一次 ERP。画面上不再为这件事单加取消按钮。
|
||||
|
||||
顶替只发生在同一调拨类型、同一组来源,且新的日期范围把旧范围整个盖住的时候。旧匹配没有日期范围、正在写 ERP、结果未知,或已经写出单据,都保持有效,货留在原匹配里。清单不列举这些匹配的编号。人工关闭的货不回到新匹配。没有挂上任何匹配的明细不占货。
|
||||
|
||||
## Considered Options
|
||||
|
||||
- **只加取消按钮**:被否——仓库人员的下一步就是再匹配一次,按钮多一次确认,不解决「提交新匹配时期望直接看到货」。
|
||||
- **允许重复匹配**:被否——两张未取消的匹配会把同一批可执行货各写一次 ERP。
|
||||
|
||||
## Consequences
|
||||
|
||||
- 圈档仍互斥。顶替是取消的自动出口,不是第二套占用规则。
|
||||
- 日期没盖住或已经在写 ERP 时,这些货留在原匹配里。新清单只显示这次圈出来的行。
|
||||
- 人工关闭跨过顶替继续有效。未归属匹配的明细不再挡住圈档。
|
||||
@@ -56,7 +56,7 @@ _Avoid_: 仓库映射(专指映射档本身)
|
||||
### 在途调拨 · 平台侧概念
|
||||
|
||||
**匹配明细 (Matching Item)**:
|
||||
一次匹配从异动档圈定并永久绑定的执行明细行,承载库存核对结果、执行状态与 ERP 单据关联;自创建起归属唯一匹配。
|
||||
一次匹配从异动档圈定并永久绑定的执行明细行,承载库存核对结果、执行状态与 ERP 单据关联;自创建起归属唯一匹配。尚未归属任何匹配的行不占货。
|
||||
_Avoid_: 待办行、入站明细
|
||||
|
||||
**记录类型 (Record Kind)**:
|
||||
@@ -75,6 +75,26 @@ _Avoid_: 数据源、站点、Inbound Source Instance
|
||||
一个出入站来源实例上、按记录类型分开的一条抓取与文件状态。同一来源实例可同时有入站证据流和出站证据流。
|
||||
_Avoid_: 来源状态、部分就绪
|
||||
|
||||
**恢复处理 (Recovery Requery)**:
|
||||
对待恢复异常重新核对 ERP 库存的那一次查询。与「重查库存」是同一件事。
|
||||
_Avoid_: 把已人工关闭的记录重新打开
|
||||
|
||||
**人工关闭 (Manual Close)**:
|
||||
仓库人员判定某条明细不再继续调拨,并留下原因之后的状态。该状态只保留原因供查看。匹配顶替不把这些货放回新匹配。
|
||||
_Avoid_: 删除、恢复处理、匹配顶替
|
||||
|
||||
**占用 (Occupancy)**:
|
||||
一批货已被某次仍有效的匹配圈住,因而不能再进一次新匹配。人工关闭的货也算占用。没有挂上任何匹配的明细不构成占用。
|
||||
_Avoid_: 锁定、文件占用
|
||||
|
||||
**匹配顶替 (Matching Supersede)**:
|
||||
新匹配成立时对既有匹配的取代:同一调拨类型、同一组来源、日期范围被新范围完全盖住、且还没有任何 ERP 单据的旧匹配全部不再有效,其中的货按新匹配重新圈定。盖不住、正在写 ERP、或结果未知的旧匹配保持有效。
|
||||
_Avoid_: 重复匹配、再匹配一次
|
||||
|
||||
**结果未知 (Result Unknown)**:
|
||||
一次调拨写入之后,ERP 是否已经生成单据仍不能确定的状态。
|
||||
_Avoid_: 失败、待恢复异常
|
||||
|
||||
**收料 RPA (Receipt RPA · 旧名保留)**:
|
||||
入站证据抓取链路的**实现载体**:在途调拨的入站抓取复用货代 shipping_notice 域的 ShippingReceiptReport RPA,故该域内的数据表名(`shipping_receipt_report_*`)、RPA 契约(`shipping_receipt_rpa.v1` / `receipt_export_batch`)、目录(`freight_rpa/receipt/`)与环境变量(`FREIGHT_RPA_RECEIPT_*`)保留「收料/receipt」旧名,默认不改(与运行期收敛口径一致;如后续确需更名须单独立项评估)。它与在途调拨域所说的「入站(链路/文件/抓取)」是**同一条物理链路**——域内业务说辞(代码、API、前端文案)一律用「入站」,读代码遇到 receipt 旧名时按本条映射理解。
|
||||
_Avoid_: 把「收料」当作独立业务概念(在途调拨域已统一为入站);未经立项更名 shipping_notice 域保留的 receipt 旧名;新增代码用「收料」指代在途调拨业务
|
||||
@@ -12,7 +12,7 @@
|
||||
- **路由归属(拨出库位)**:拨出库位取仓库映射行的「在途仓编码」(`shipping_inventory_external_mappings.in_transit_warehouse_code`,保存端必填)。映射行按库存源 `warehouse_resolution_mode` 选择(`DefaultRouteResolver`):`inventory_match`(按库存行匹配)源优先按「库存源 + 入站文件仓库列(`warehouse_code`)== 货代仓库」精确匹配,匹配不到回退「库存源 + 货代仓库为空」的默认映射行(空库位兜底);`fixed`(指定仓库)源仅一条启用映射直接取用。入站文件仓库列原值随明细落库于 `transfer_invoice_items.movement_warehouse_code`,执行/重试期以它重解析路由,路由变化 fail-closed 阻断(`TRANSFER.ROUTE_NOT_RESOLVED` / `matching_expired`)。运维注意:来源的 movement 解析方案须把入站文件「仓库」表头映射到领域字段 `warehouse_code`,未映射时该值为空、inventory_match 源将直接走空库位兜底。
|
||||
- **调拨业务类型(2026-10-14 配置化,取代 2026-09-22 代码枚举)**:调拨类型来自平台配置(表 `transfer_type_configs`,管理端「在途调拨类型」页维护),代码不再枚举类型——类型决定匹配数据范围(范围规则引擎)、仓库取值(仓库定义)与字段转换(如批号前缀替换)。`transfer_runs.transfer_type` CHECK 约束已放开,类型合法性由配置表校验;`transfer_type` 在匹配创建**必填**(缺省/未配置/停用 fail-closed)。配置为空时前端空态 + 匹配 fail-closed(「暂无可用调拨类型」是设计行为,见 §11)。类型、范围规则与转换规则随匹配快照进 `scope_json` 参与匹配 Hash。历史:原三类型枚举(`in_transit_to_hub` 唯一开放 / `hub_repair_out`、`hub_to_hub` 占位「即将上线」)已整体退役,无兼容层。完整模型与上线 SOP 见 §11。
|
||||
- **异步**:`transfer` 队列(`worker_in_transit_transfer.py`)消费匹配/执行 Run/执行 Item 三类 Job。
|
||||
- **排程**:`in-transit-transfer`(建议 09:00 前)platform job(`schedule/job_registry.py`);当日入站文件缺失时该 job 自动触发收料 RPA 抓取(历史独立 `in-transit-receipt-file` job 已并入,注册表中不再单列)。
|
||||
- **排程**:`in-transit-transfer`(建议 09:00 前)platform job(`schedule/job_registry.py`);当日入站文件缺失时该 job 自动触发收料 RPA 抓取(历史独立 `in-transit-receipt-file` job 已并入,注册表中不再单列)。job_params:`transfer_types`(multi_select,选项源 `transfer_types`=启用中的类型配置,**留空=全部启用类型逐轮执行**,恢复复核与类型无关循环外只跑一次,类型配置为空/读取失败 fail-closed 硬失败)、`source_codes`(留空=全部启用入站来源)、`recover_history`(默认开)、`receipt_from/to_offset_days`(T−N 偏移,留空=全部成熟积压,T−2 成熟封顶由匹配层把关)。执行结果通知统一走排程「启用通知」框架完成卡,空数据日(全部类型均无 Run 且无错误)置 `domain_notification_managed` 静默(C5);历史任务级通知人参数 `notify_user_ids` 已移除。
|
||||
|
||||
## 2. 数据库
|
||||
|
||||
@@ -32,7 +32,8 @@
|
||||
| `IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS` | 5 | 老化升级阈值 |
|
||||
| `IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS` | 7 | 老化严重阈值 |
|
||||
| `IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET` | hxops-transfer | 归档 bucket |
|
||||
| `MINIO_ENDPOINT` / `MINIO_ACCESS_KEY` / `MINIO_SECRET_KEY` / `MINIO_SECURE` | 既有 | MinIO 连接(复用既有变量) |
|
||||
| `MINIO_ENDPOINT` / `MINIO_ACCESS_KEY` / `MINIO_SECRET_KEY` / `MINIO_SECURE` | 既有 | 容器内读写 MinIO(正式环境为 `host.docker.internal:9000`,勿改成公网主机) |
|
||||
| `MINIO_PUBLIC_BASE_URL` | 既有 | 预览预签名的浏览器主机。正式环境为 `http://ai.well-trust.com:9000`。单文件「下载」不把该地址交给浏览器,改由站点 HTTPS 接口回传,避免 HTTPS 页面打开 HTTP MinIO 被拦截 |
|
||||
| `FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR` | 既有 | 收料 RPA trigger 目录(复用收料链路) |
|
||||
|
||||
> 外部系统(ERP)端点与凭据由集成连接器的客户端实例/凭据引用管理,不使用独立环境变量;
|
||||
@@ -385,7 +386,7 @@ cd backend && flask db upgrade
|
||||
### 11.6 items 出生翻转与 D17 圈档互斥(迁移 `tt12c3d4e5f6a7`)
|
||||
|
||||
- **出生翻转(ADR 0001)**:`transfer_invoice_items` 退化为纯匹配执行记录——匹配创建时从档按类型范围规则圈定生成(`matching_id`/`ledger_record_id` 出生即绑定,业务字段取档原值、路由解析落 from/to);证据落地只写档不写行;重查 `requery_items` 弃 items SQL 圈行(`scope_item_query` 退役),改**对档对账**(同一编译器、同一快照规则):档有行无→补建、档证据变→刷新证据并重置待查、档记录被新版本替换→items 失效隔离(`blocked_file_removed` 语义)。
|
||||
- **D17 圈档互斥**:一条档记录一生只生成一次 items 绑定——匹配创建圈档排除「已被有效 items 占用」的档记录(存在所属匹配未取消、行未被失效隔离的 item 引用即占用)。取消匹配(items→cancelled)释放占用,记录可被后续匹配重圈;人工关闭/成功终态不释放(前者=业务裁定不拨,后者=档级封存)。重查只对账本匹配自有 items,不受此规则影响。取消按 `matching_id` 圈定名下 ready 未建单行退役(出生行 `run_id=None`,按 run_id 圈行恒不命中)。
|
||||
- **D17 圈档互斥**:一条档记录一生只生成一次 items 绑定——匹配创建圈档排除「已被有效 items 占用」的档记录(存在所属匹配未取消、行未被失效隔离的 item 引用即占用)。取消匹配(items→cancelled)释放占用,记录可被后续匹配重圈;人工关闭/成功终态不释放(前者=业务裁定不拨,后者=档级封存)。【ADR 0007】提交新匹配时,同一调拨类型、同一组来源、日期范围被新范围整个盖住、且还没有任何 ERP 单据的旧匹配自动取消后再圈档;盖不住或已在写 ERP 的旧匹配保持有效,货留在原匹配里,清单不列举编号。没有挂上匹配的明细不占用。重查只对账本匹配自有 items,不受此规则影响。取消按 `matching_id` 圈定名下 ready 未建单行退役(出生行 `run_id=None`,按 run_id 圈行恒不命中)。
|
||||
|
||||
### 11.7 首页待办看板「待匹配」桶(D16)
|
||||
|
||||
|
||||
@@ -1858,21 +1858,16 @@ GET /api/admin/shipping-order-schema/published-contract
|
||||
|
||||
### 连接级受控上传参数(upload_config_json,连接例外)
|
||||
|
||||
发货 Excel 自动上传的页面参数作为 `ShippingRpaProfile.upload_config_json` 直接挂在既有“系统连接”上,一条连接只保存一份上传配置。**这是连接级受控上传参数的例外**:它只作用于货代上传,不向库存 RPA 或收料 RPA 扩散,也不新建 Upload Profile、关联表、版本表或发布流。
|
||||
发货 Excel 自动上传只在系统连接上保存是否启用。页面路径、按钮和成功判断写在对应货代的连接器里。**这是连接级开关,不是页面参数**:它只作用于货代上传,不向库存 RPA 或收料 RPA 扩散,也不新建 Upload Profile、关联表、版本表或发布流。
|
||||
|
||||
- **配置由管理端表单编辑,后端保存为受限 JSON**。白名单字段仅 `enabled / entry_url / file_input_selector / submit_mode / submit_selector / result_mode / result_selector / success_texts / timeout_seconds`;保存时后端严格校验:
|
||||
- `connector_type` 仍只能是 `dbs / crane`。
|
||||
- `entry_url` 必须 HTTPS,且主机名只允许该连接已审核的平台域名(`dbschenker.com` / `craneww.com` 后缀匹配)。
|
||||
- 三个 selector 只允许普通 CSS selector,限制长度(≤200)并拒绝 `javascript:`、`<script`、`expression(`、`on*=` 及 `() {} ; < >` 等脚本/表达式语义。
|
||||
- `submit_mode` 只允许 `auto_after_file / click_submit`;`result_mode` 只允许 `page_notice / history_record`。
|
||||
- `enabled=true` 时须具备完成一次上传与判定结果所需的全部字段:公共必填 `entry_url / file_input_selector / submit_mode / timeout_seconds`;`click_submit` 须有 `submit_selector`;crane 启用时还须补全 `result_selector` 与成功文本/记录判定字段(DSV 由代码内置的受控成功流判定,不强制管理员填写)。
|
||||
- 禁止自由 JavaScript、脚本、URL 模板、Cookie 或任意浏览器动作落库。
|
||||
- **DSV 初始值**:`enabled=true`,`entry_url=https://s360.dbschenker.com/main/portal/frame/WMSUpload2`,`file_input_selector=input#file2`,`submit_mode=auto_after_file`,`submit_selector=null`,`result_mode=page_notice`,`success_texts=[]`,`timeout_seconds=120`。
|
||||
- **Crane 初始值**:`enabled=false`(提交按钮、成功提示或上传历史记录的稳定选择器尚未确认,仅有文件选择器不代表可安全自动提交),`entry_url=https://wms-portal.craneww.com/#/shipping-order-upload`,`file_input_selector=input[name="OrderFileUpload"]`,`submit_mode=click_submit`,`submit_selector=null`,`result_mode=page_notice`,`success_texts=[]`,`timeout_seconds=120`。管理员完成页面验证并补全提交/成功判定字段后才可 `enabled=true`。
|
||||
- **不改版本号**:`upload_config_json` 变更不递增 `config_version`,避免库存 RPA 配置测试被误判过期;不维护 `upload_config_version`(无发布流、无并发编辑审批、无历史回放需求)。每个 trigger 固化本次 upload_config 快照即可保证“这次上传用了什么”;需要审计关联时对快照计算 `config_hash`(sha256)。
|
||||
- **Worker 保留两个受控 Adapter**:`DsvUploadAdapter`(DSV 入口、文件选择与结果判定)与 `CraneUploadAdapter`(Crane 入口、文件选择、提交与结果判定),**不再根据环境变量拼接 DSV/Crane 页面动作**。用连接 `login_url` 登录后访问 `upload_config.entry_url` 进入上传页;`upload_config` 决定“该连接使用哪个已支持的受控流程及其页面参数”,浏览器动作与安全边界由代码负责;Worker 上传与最终提交的全局开关(`FREIGHT_RPA_WORKER_UPLOAD_ENABLED` / `..._CONFIRM_SUBMIT`)仍作为部署级二次确认保留,但不再承载页面参数。
|
||||
- **执行链路**:用户触发批量 RPA 上传 → 后端创建 Upload Attempt → 读取任务已确定的系统连接及 `upload_config_json` → 复制发货 Excel 到共享上传队列 → 生成非空 `callback_id` → 原子写入 trigger(复用“临时文件 + fsync + os.replace”,携带 `schema_version / task_no / attempt_id / artifact_id / callback_id / connector_type / upload_config 快照 / upload_config_hash / login_url / credential_envelope`)→ Windows Worker 取 trigger → 按 `connector_type` 进入 DSV/Crane Adapter → 登录、打开 entry_url、选择 Excel、提交 → 以受控页面选择器判定 → 回调。
|
||||
- **结果三态**:`success`(取得可核验成功证据)、`failed`(明确页面失败、浏览器错误、超时或回调失败)、`unknown`(已可能提交但无法确认外部系统结果)。`unknown` 必须转人工处理,禁止自动重试以避免重复上传;成功/失败/未知、页面证据摘要与脱敏错误写入现有 Upload Attempt 与货代审计事件。
|
||||
- **配置只保存是否启用**。`upload_config_json` 落库只保留 `{enabled}`。旧客户端带来的入口 URL、文件选择器、提交方式、结果选择器和成功文本在保存时丢弃,不作为运行参数。`connector_type` 仍只能是 `dbs / crane`。
|
||||
- **页面动作在连接器代码里**。Worker 用连接 `login_url` 的主机拼出上传页:DBS 为 `/main/portal/frame/WMSUpload2`,Crane 为 `/#/shipping-order-upload`。DBS 固定点击 `Process File`,并同时核对成功提示与两个错误面板。Crane 固定使用 `input[name="OrderFileUpload"]`。
|
||||
- **DBS 同步完成**。同一页面即可判定成功或失败,没有状态回查。
|
||||
- **Crane 先进入分配中**。提交后若该行是 `Processing + Allocating the Shipping Order`,尝试保持 `running` 且 `error_code=CRANE_ALLOCATING`,业务状态为 `allocating`(已接收,分配中)。只有 `Processing + Shipping Order Allocated` 才算上传成功。自动上传后只排一次 10 分钟后的 Worker 重新登录回查;手动刷新是另一次立即回查,不改那一次定时的到期时间。两条回查都只按 Pull Request #(Excel 文件名去扩展名)看行,不重新上传。仍在分配中时禁止再次上传同一文件。
|
||||
- **不改版本号**:`upload_config_json` 变更不递增 `config_version`,避免库存 RPA 配置测试被误判过期。
|
||||
- **Worker 保留两个受控 Adapter**:`DsvUploadAdapter` 与 `CraneUploadAdapter`。Worker 上传与最终提交的全局开关(`FREIGHT_RPA_WORKER_UPLOAD_ENABLED` / `..._CONFIRM_SUBMIT`)仍作为部署级二次确认保留。
|
||||
- **执行链路**:用户触发批量 RPA 上传 → 后端创建 Upload Attempt → 读取任务已确定的系统连接及是否启用自动上传 → 复制发货 Excel 到共享上传队列 → 生成非空 `callback_id` → 原子写入 trigger → Windows Worker 按 `connector_type` 登录并打开代码固定的上传页。Crane 分配中的到期回查由 Worker 心跳写成 `mode=status_check` 的 trigger。
|
||||
- **结果**:`success`(取得可核验成功证据)、`failed`(明确页面失败)、`unknown`(无法确认,转人工且禁止自动重试)、`allocating`(Crane 已接收,仍在分配)。分配中的状态回查若暂时看不到行,保持分配中,不改成 unknown。
|
||||
|
||||
发布门禁:全局只有一个 published 版本;已发布版本不可编辑;字段首次发布后 `scope/value_type` 不可修改;**同一 field_id 的 `field_code` 一经发布不可变更**(改名 = 退役旧字段 + 新建字段,允许同一 `field_code` 漂移到新 `field_id`),历史发布快照保留旧名称;证据来源、比较器、规范化器和校验器只能引用后端白名单。
|
||||
|
||||
@@ -2425,7 +2420,7 @@ cd C:\HxopsRpaTest
|
||||
|
||||
默认 Secret 路径为 `C:\HxopsRpaSecrets\test.xml` 与 `prod.xml`。文件不得进入仓库、SMB 共享、日志或其他 Windows 用户目录。
|
||||
|
||||
DSV/Crane 登录地址、账号和密码必须先在 HXOPS 管理端的 RPA Profile 中配置。后端将加密凭据作为 trigger 的 `credential_envelope` 发送给 Worker,Worker 只用 `FREIGHT_RPA_CREDENTIAL_KEY` 解密,不从 Windows Secret 文件重新录入。
|
||||
DSV/Crane 登录地址、账号和密码必须先在 HXOPS 管理端的 RPA Profile 中配置。管理端 Profile 接口回传用户名明文,便于辨认账号;密码与密文不返回,留空保存表示不修改。库内仍只存 Fernet 密文。后端将加密凭据作为 trigger 的 `credential_envelope` 发送给 Worker,Worker 只用 `FREIGHT_RPA_CREDENTIAL_KEY` 解密,不从 Windows Secret 文件重新录入。
|
||||
|
||||
手工启动 test:
|
||||
|
||||
|
||||
+2
-2
@@ -201,7 +201,7 @@
|
||||
| 人工复核与字段证据闭环(阶段 5) | 已实现 | 单头、订单行、冲突解决均要求乐观锁、原因和结构化 `document_cell`/`manual_input` 证据;跨订单或伪造证据在写值前拒绝,复核审计保存结构化证据且详情页展示页码、表格、单元格与原文 |
|
||||
| 原 PDF 双层重解析 | 已实现 | “重新识别此 PDF”仅为当前原始文件创建后继 Run;“重新解析本批次”逐 PDF 创建独立子 Run、局部成功替换,按完整 Run 谱系选择每个原文件的当前 Case;已确认/履约文件排除;不支持上传替代 PDF。 |
|
||||
| 多订单 Candidate 判重与自动建批 | 已实现 | Candidate 身份/内容双指纹;高置信 SKU+Qty 订单自动建 Task,低置信/冲突/修订保留待处理;部分消费 Intake 不丢剩余订单;缺 Reservation/Source Type/Hub Code 的 Task 停在自然对话补字段门禁 |
|
||||
| 库存 RPA 源配置 | 已实现 | 源、报表路径与查询参数维护在数据库 `freight_rpa_sources`(管理端货代 RPA 页);期初 YAML 已于 2026-10-20 删除,运行时只读数据库 |
|
||||
| 库存 RPA 源配置 | 已实现 | 源、报表路径与查询参数维护在数据库 `freight_rpa_sources`(管理端货代 RPA 页);期初 YAML 已于 2026-10-20 删除,运行时只读数据库。来源站点可复制为未保存草稿(连接、模板、仓库解析、库存/入站/出站报表),保存后保持停用;不复制快照、仓库映射、路由规则与测试结果。 |
|
||||
| 订单解析阶段库存源判定 | 已实现 | `parse_notice` 内 adjudicate 写线索;低置信度先 `parse_review`,解析通过后再 `inventory_source_review`;稳定态 `resolved`/`user_confirmed` |
|
||||
| 文件解析阶段问题清单 | 已实现 | 步骤 2 工作台/`ui_state.summary.issues` 一次列出解析复核、RSV、库存源门禁与 parse warnings |
|
||||
| 发货通知关键字段真值校验 | 已实现 | LLM 出候选、后端裁决;支持多模板 Reservation 别名,拒绝 32 位 hex/UUID;仅按 TSV 列关系与唯一 SKU/APN/MPN 证据纠错;`parse_validation` 留痕,blocking issue 在解析确认和库存匹配前双重阻断 |
|
||||
@@ -819,7 +819,7 @@
|
||||
| 可调拨清单勾选与 ERP 原子调拨 | 后端已实现 | 可调拨明细队列勾选按行提交执行 Run/写前复查/Invoice 幂等/duplicate_success/result_unknown 隔离/单项失败不阻断/按票聚合结果(写路径已接线,见下行「ERP 建单写路径」) |
|
||||
| 排程/恢复/异常/通知 | 后端已实现 | 08:00 入站文件与 09:00 自动调拨(现注册表单列 `in-transit-transfer` platform job,缺当日入站文件自动触发收料 RPA);任务参数=来源实例/历史可恢复异常复核/可选异动日期起止(T-N 偏移天数,执行日换算,测试/排障缩小匹配面;留空=全部成熟积压;非法偏移快速失败,偏移终点落在 T−1/当天或更晚由匹配层卡控截止≤T−2);待处理池 3/5/7 天老化;人工重试/关闭;七 Sheet 异常 Excel;执行结果通知统一走排程「启用通知」通用执行结果通知(空数据日静默,失败不改 ERP 结果;2026-10-12 移除任务级通知人参数) |
|
||||
| 调拨类型配置化(2026-10-14) | 已实现 | 类型来自平台配置表 `transfer_type_configs`(ADR 0002,代码枚举/CHECK 约束/前端 union/「即将上线」占位全退役):管理端「在途调拨类型」页四块配置(基本信息/范围规则/仓库定义/字段转换),admin CRUD API + chat enabled 最小暴露 API;`transfer_type` 匹配创建必填(未配置/停用 fail-closed),配置为空前端空态;范围规则引擎(18 字段白名单、规则间 AND 值间 OR、内存谓词+SQL 编译双形态)、仓库定义(mapped/fixed+法人覆盖)、字段转换(批号前缀替换,六个系统边界生效,行/档保原值);规则随匹配快照进 scope_json;管理页见 `features/admin/modules/transfer-types/`,运维手册 technical.md §11 |
|
||||
| 库存异动档与出生翻转(2026-10-14) | 已实现 | 新建 `transfer_movement_ledger`(ADR 0001,外部入站/出站记录唯一镜像):自然键幂等五语义(插入/sha 幂等跳过/证据变原行更新/缺席不删/已执行封存)、record_kind 声明+in_out_flag 交叉校验(矛盾打审计标记照常落档)、D13 业务字段+出站预留列、档级封存回写(执行成功 transfer_executed=true 防二次调拨);items 出生翻转=匹配创建时从档圈定建行(matching_id/ledger_record_id 出生即绑定),落地停写 items、重查对档对账、scope_item_query 退役;D17 圈档互斥(一条档记录一生一次绑定,取消释放/终态不释放);2026-10-21 外部单据身份扩维:自然键 8→10 成分(+外部单号/外部项次=WMS Order #/行号,迁移 tt21c8d9e0f1a2)作档幂等主键管控,movement 契约字段目录扩至 20 字段(解析 Profile 可映射),解析层料号空行静默跳过(不管控、不进异动表) |
|
||||
| 库存异动档与出生翻转(2026-10-14) | 已实现 | 新建 `transfer_movement_ledger`(ADR 0001,外部入站/出站记录唯一镜像):自然键幂等五语义(插入/sha 幂等跳过/证据变原行更新/缺席不删/已执行封存)、record_kind 声明+in_out_flag 交叉校验(矛盾打审计标记照常落档)、D13 业务字段+出站预留列、档级封存回写(执行成功 transfer_executed=true 防二次调拨);items 出生翻转=匹配创建时从档圈定建行(matching_id/ledger_record_id 出生即绑定),落地停写 items、重查对档对账、scope_item_query 退役;D17 圈档互斥(一条档记录一生一次绑定,取消释放/终态不释放;ADR 0007:新匹配自动顶替同一类型、同一来源、日期被盖住且尚未写 ERP 的旧匹配,人工关闭仍排除,未挂匹配的明细不占用,清单不列举历史匹配编号);2026-10-21 外部单据身份扩维:自然键 8→10 成分(+外部单号/外部项次=WMS Order #/行号,迁移 tt21c8d9e0f1a2)作档幂等主键管控,movement 契约字段目录扩至 20 字段(解析 Profile 可映射),解析层料号空行静默跳过(不管控、不进异动表) |
|
||||
| 入站/出站统一改版与幂等修复(2026-10-15) | 已实现 | record_kind 枚举值改版 inbound/outbound(迁移 tt14 值迁移);明细/单据列异动口径 `movement_*`(异动日期/数量/仓库列与匹配创建参数 `movement_date_from/to`、序列化键、Excel 表头随行更名,无兼容层);异动档自然键扩为 8 成分(+箱号/批号,三份真实 WMS 文件实测塌缩归零)+「异动日期非空才落档」过滤(`date_skipped`,未完成/已取消行不入档);解析规则 purpose 三枚举 onhand/inbound/outbound(迁移 tt15 值迁移);入站配置绑定校验 inbound 专用(`SHIPPING.INBOUND_PROFILE_INVALID`),出站绑定 `SHIPPING.OUTBOUND_PROFILE_INVALID`(2026-10-19 出站全栈);解析规则退役守卫补查入站/出站配置绑定;API 路由 `/sources/inbound-files`、`/runs/{run_no}/inbound-files` 与错误码/审计事件 inbound 化;出站 RPA 与调拨 sink 见 [superpowers/specs/2026-10-19-freight-rpa-outbound-and-rename-design.md](superpowers/specs/2026-10-19-freight-rpa-outbound-and-rename-design.md);2026-10-15 设计见 [superpowers/specs/2026-10-15-inbound-outbound-idempotency-rename-design.md](superpowers/specs/2026-10-15-inbound-outbound-idempotency-rename-design.md),运维手册 technical.md §12 |
|
||||
| 待匹配桶清空并重新解析(2026-10-15) | 已下线(2026-10-22) | 原入口会重放该来源保留期内全部归档,一次执行可把历史行整批灌进待匹配。界面与 `GET/POST /backlog/pending-match/reparse*` 已移除。重解析只保留来源卡「重新解析」(当天最新一份,不删行)。 |
|
||||
| 首页待匹配桶与 file_current 改锚(2026-10-14) | 已实现 | 待办看板新增「待匹配」桶(已落档但从未匹配的外部记录只读可见+去匹配引导,不可勾选执行),四队列卡数据源改档+最近执行状态联查;file_current 门禁改锚档记录 file_version(==来源最新可用文件 sha 即当前) |
|
||||
|
||||
@@ -1,27 +1,32 @@
|
||||
/**
|
||||
* features/admin/modules/approvals/ApprovalsPage.vue
|
||||
* 用户注册审批独立页面。路由:/admin/approvals
|
||||
* 用途:用户注册审批列表。一张卡片里放标题和待审表格。
|
||||
* 依赖:AdminListPage、useApprovalsAdmin、useElementProvider、element-plus、roleLabel。
|
||||
* 逻辑:路由未挂进当前菜单。通过和拒绝由 composable 弹出 Element 确认框后调接口。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ShieldCheck, Trash2 } from 'lucide-vue-next';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import { CircleCheck, Delete } from '@element-plus/icons-vue';
|
||||
import { ElButton, ElConfigProvider, ElTable, ElTableColumn, ElTag } from 'element-plus';
|
||||
import 'element-plus/dist/index.css';
|
||||
import 'element-plus/theme-chalk/dark/css-vars.css';
|
||||
import '@/features/admin/styles/element-trial.css';
|
||||
import AdminListPage from '@/features/admin/components/AdminListPage.vue';
|
||||
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
|
||||
import { adminRoleLabel } from '@/features/admin/utils/roleLabel';
|
||||
import type { AdminUserRow } from '@/features/admin/types/admin.types';
|
||||
import { useApprovalsAdmin } from './composables/useApprovalsAdmin';
|
||||
|
||||
const { t } = useI18n();
|
||||
const { elementLocale } = useElementProvider();
|
||||
|
||||
const {
|
||||
pendingUsers,
|
||||
isLoading,
|
||||
showConfirmDialog,
|
||||
confirmMessage,
|
||||
loadAll,
|
||||
approveUser,
|
||||
rejectUser,
|
||||
closeConfirm,
|
||||
confirmActionHandler,
|
||||
} = useApprovalsAdmin();
|
||||
|
||||
onMounted(() => {
|
||||
@@ -30,80 +35,60 @@ onMounted(() => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="admin-table-section">
|
||||
<div v-if="isLoading" class="flex items-center justify-center py-20">
|
||||
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
|
||||
</div>
|
||||
<ElConfigProvider :locale="elementLocale">
|
||||
<AdminListPage :loading="isLoading">
|
||||
<template #title>
|
||||
<h2 class="section-title">{{ t('admin.approval.title') }}</h2>
|
||||
<p class="section-desc">{{ t('admin.approval.subtitle') }}</p>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<div class="admin-table-header">
|
||||
<div>
|
||||
<h2 class="section-title">{{ t('admin.approval.title') }}</h2>
|
||||
<p class="section-desc mt-1">{{ t('admin.approval.subtitle') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="admin-table-wrap">
|
||||
<table class="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="px-8 py-4 text-left text-xs">{{ t('admin.approval.headers.username') }}</th>
|
||||
<th class="px-8 py-4 text-left text-xs">{{ t('admin.approval.headers.nameId') }}</th>
|
||||
<th class="px-8 py-4 text-left text-xs">{{ t('admin.approval.headers.contact') }}</th>
|
||||
<th class="px-8 py-4 text-left text-xs">{{ t('admin.approval.headers.role') }}</th>
|
||||
<th class="px-8 py-4 text-right text-xs">{{ t('admin.approval.headers.actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="pendingUsers.length === 0">
|
||||
<td colspan="5" class="px-8 admin-table-empty">{{ t('admin.approval.noPending') }}</td>
|
||||
</tr>
|
||||
<tr v-for="user in pendingUsers" :key="user.id">
|
||||
<td class="px-8 py-5 text-sm font-medium text-primary">
|
||||
<div>{{ user.username }}</div>
|
||||
<div class="text-xs text-muted font-normal">{{ user.email }}</div>
|
||||
</td>
|
||||
<td class="px-8 py-5 text-sm text-muted">
|
||||
<div>{{ user.real_name || '-' }}</div>
|
||||
<div class="text-xs text-muted font-mono">{{ user.employee_id || '-' }}</div>
|
||||
</td>
|
||||
<td class="px-8 py-5 text-sm text-muted">{{ user.phone_number || '-' }}</td>
|
||||
<td class="px-8 py-5">
|
||||
<span
|
||||
class="px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800 border border-yellow-200"
|
||||
>
|
||||
{{ adminRoleLabel(t, user.role, user.role_name) }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-8 py-5 text-right flex items-center justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="p-2 text-green-600 bg-green-50 rounded-lg hover:bg-green-100 transition-colors"
|
||||
:title="t('admin.approval.confirmApprove')"
|
||||
@click="approveUser(user.id)"
|
||||
>
|
||||
<ShieldCheck class="w-4 h-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="p-2 text-red-600 bg-red-50 rounded-lg hover:bg-red-100 transition-colors"
|
||||
:title="t('admin.approval.confirmReject')"
|
||||
@click="rejectUser(user.id)"
|
||||
>
|
||||
<Trash2 class="w-4 h-4" />
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<DeleteConfirmDialog
|
||||
v-model="showConfirmDialog"
|
||||
:message="confirmMessage"
|
||||
@cancel="closeConfirm"
|
||||
@confirm="confirmActionHandler"
|
||||
/>
|
||||
</section>
|
||||
<ElTable
|
||||
class="hx-admin-table"
|
||||
:data="pendingUsers"
|
||||
row-key="id"
|
||||
:empty-text="t('admin.approval.noPending')"
|
||||
>
|
||||
<ElTableColumn :label="t('admin.approval.headers.username')" min-width="200">
|
||||
<template #default="{ row }">
|
||||
<div>{{ (row as AdminUserRow).username }}</div>
|
||||
<p class="hx-element-hint">{{ (row as AdminUserRow).email }}</p>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('admin.approval.headers.nameId')" min-width="160">
|
||||
<template #default="{ row }">
|
||||
<div>{{ (row as AdminUserRow).real_name || '-' }}</div>
|
||||
<p class="hx-element-hint">{{ (row as AdminUserRow).employee_id || '-' }}</p>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('admin.approval.headers.contact')" min-width="140">
|
||||
<template #default="{ row }">{{ (row as AdminUserRow).phone_number || '-' }}</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('admin.approval.headers.role')" min-width="120">
|
||||
<template #default="{ row }">
|
||||
<ElTag effect="light" type="warning">
|
||||
{{ adminRoleLabel(t, (row as AdminUserRow).role, (row as AdminUserRow).role_name) }}
|
||||
</ElTag>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('admin.approval.headers.actions')" width="120" align="right">
|
||||
<template #default="{ row }">
|
||||
<ElButton
|
||||
link
|
||||
type="primary"
|
||||
:icon="CircleCheck"
|
||||
:title="t('admin.approval.confirmApprove')"
|
||||
@click="approveUser((row as AdminUserRow).id)"
|
||||
/>
|
||||
<ElButton
|
||||
link
|
||||
type="danger"
|
||||
:icon="Delete"
|
||||
:title="t('admin.approval.confirmReject')"
|
||||
@click="rejectUser((row as AdminUserRow).id)"
|
||||
/>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
</ElTable>
|
||||
</AdminListPage>
|
||||
</ElConfigProvider>
|
||||
</template>
|
||||
@@ -1,9 +1,12 @@
|
||||
/**
|
||||
* features/admin/modules/approvals/composables/useApprovalsAdmin.ts
|
||||
* 用户注册审批:待审列表、通过、拒绝。
|
||||
* 用途:用户注册审批的待审列表、通过和拒绝。
|
||||
* 依赖:admin.api、useMessage、useAdminNavBadges、element-plus 的确认框。
|
||||
* 逻辑:ApprovalsPage 调用本模块;通过和拒绝都先弹出 Element 确认框,成功后刷新列表和导航角标。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ElMessageBox } from 'element-plus';
|
||||
import { approveAdminUser, listAdminUsers, rejectAdminUser } from '@/features/admin/api/admin.api';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { useAdminNavBadges } from '@/features/admin/composables/useAdminNavBadges';
|
||||
@@ -17,10 +20,6 @@ export function useApprovalsAdmin() {
|
||||
const users = ref<AdminUserRow[]>([]);
|
||||
const isLoading = ref(true);
|
||||
|
||||
const showConfirmDialog = ref(false);
|
||||
const confirmMessage = ref('');
|
||||
let confirmAction: (() => Promise<void> | void) | null = null;
|
||||
|
||||
const pendingUsers = computed(() => users.value.filter((u) => u.status === 'pending'));
|
||||
|
||||
const loadUsers = async (): Promise<void> => {
|
||||
@@ -38,61 +37,61 @@ export function useApprovalsAdmin() {
|
||||
isLoading.value = false;
|
||||
};
|
||||
|
||||
const openConfirm = (message: string, action: () => Promise<void> | void): void => {
|
||||
confirmMessage.value = message;
|
||||
confirmAction = action;
|
||||
showConfirmDialog.value = true;
|
||||
};
|
||||
|
||||
const closeConfirm = (): void => {
|
||||
showConfirmDialog.value = false;
|
||||
confirmAction = null;
|
||||
};
|
||||
|
||||
const confirmActionHandler = async (): Promise<void> => {
|
||||
if (!confirmAction) return;
|
||||
/**
|
||||
* 弹出确认框。点取消时 Element 会拒绝 Promise,这里吞掉,不当成失败。
|
||||
* @param message - 确认正文
|
||||
* @returns 用户是否点了确定
|
||||
*/
|
||||
async function confirmAction(message: string): Promise<boolean> {
|
||||
try {
|
||||
await confirmAction();
|
||||
} finally {
|
||||
closeConfirm();
|
||||
await ElMessageBox.confirm(message, t('common.deleteDialog.defaultTitle'), {
|
||||
confirmButtonText: t('common.deleteDialog.confirm'),
|
||||
cancelButtonText: t('common.deleteDialog.cancel'),
|
||||
type: 'warning',
|
||||
});
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const approveUser = (userId: number): void => {
|
||||
openConfirm(t('admin.approval.confirmApprove'), async () => {
|
||||
try {
|
||||
await approveAdminUser(userId);
|
||||
await loadUsers();
|
||||
await refreshBadges();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
msg.error((e as Error).message || t('admin.msg.failed'));
|
||||
}
|
||||
});
|
||||
};
|
||||
/**
|
||||
* 通过一条待审注册。先确认,再调审批接口并刷新角标。
|
||||
* @param userId - 待审用户主键
|
||||
*/
|
||||
async function approveUser(userId: number): Promise<void> {
|
||||
if (!(await confirmAction(t('admin.approval.confirmApprove')))) return;
|
||||
try {
|
||||
await approveAdminUser(userId);
|
||||
await loadUsers();
|
||||
await refreshBadges();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
msg.error((e as Error).message || t('admin.msg.failed'));
|
||||
}
|
||||
}
|
||||
|
||||
const rejectUser = (userId: number): void => {
|
||||
openConfirm(t('admin.approval.confirmReject'), async () => {
|
||||
try {
|
||||
await rejectAdminUser(userId);
|
||||
await loadUsers();
|
||||
await refreshBadges();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
msg.error((e as Error).message || t('admin.msg.requestFailed'));
|
||||
}
|
||||
});
|
||||
};
|
||||
/**
|
||||
* 拒绝一条待审注册。先确认,再调拒绝接口并刷新角标。
|
||||
* @param userId - 待审用户主键
|
||||
*/
|
||||
async function rejectUser(userId: number): Promise<void> {
|
||||
if (!(await confirmAction(t('admin.approval.confirmReject')))) return;
|
||||
try {
|
||||
await rejectAdminUser(userId);
|
||||
await loadUsers();
|
||||
await refreshBadges();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
msg.error((e as Error).message || t('admin.msg.requestFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
pendingUsers,
|
||||
isLoading,
|
||||
showConfirmDialog,
|
||||
confirmMessage,
|
||||
loadAll,
|
||||
approveUser,
|
||||
rejectUser,
|
||||
closeConfirm,
|
||||
confirmActionHandler,
|
||||
};
|
||||
}
|
||||
@@ -1,16 +1,15 @@
|
||||
/**
|
||||
* features/admin/modules/departments/DepartmentsPage.vue
|
||||
* 用途:部门管理列表。一张卡片里放标题、添加按钮、搜索、表格。
|
||||
* 依赖:AdminListPage、useDepartmentsAdmin、useElementProvider、element-plus、lucide-vue-next、部门表单和员工名单弹窗。
|
||||
* 依赖:AdminListPage、useDepartmentsAdmin、useElementProvider、element-plus、部门表单和员工名单弹窗。
|
||||
* 逻辑:路由 /admin/departments。骨架用 AdminListPage。筛选、列和两个弹窗留在本页。
|
||||
* 名称、编码、公司用表头排序,排的是当前过滤结果。删除用 Element 确认框。
|
||||
* 表格用 Element stripe 斑马纹。员工、编辑、删除保持图标按钮,悬停文案走 i18n title。
|
||||
* 表格用 Element stripe 斑马纹。员工数、编辑、删除用 Element 链接按钮,悬停文案走 i18n title。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Plus } from '@element-plus/icons-vue';
|
||||
import { Edit, Trash2, Users } from 'lucide-vue-next';
|
||||
import { Delete, Edit, Plus, User } from '@element-plus/icons-vue';
|
||||
import {
|
||||
ElButton,
|
||||
ElConfigProvider,
|
||||
@@ -157,36 +156,34 @@ onMounted(() => {
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('admin.dept.headers.members')" width="120" align="center">
|
||||
<template #default="{ row }">
|
||||
<button
|
||||
type="button"
|
||||
class="dept-member-btn"
|
||||
<ElButton
|
||||
link
|
||||
type="primary"
|
||||
:icon="User"
|
||||
:title="t('admin.dept.actions.viewMembers')"
|
||||
@click="openDepartmentMembers((row as AdminDepartmentRow).id)"
|
||||
>
|
||||
<Users class="dept-member-icon" />
|
||||
<span>{{ row.member_count || 0 }}</span>
|
||||
</button>
|
||||
{{ row.member_count || 0 }}
|
||||
</ElButton>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('admin.dept.headers.actions')" width="120" align="right">
|
||||
<template #default="{ row }">
|
||||
<div class="dept-row-actions">
|
||||
<button
|
||||
type="button"
|
||||
class="dept-icon-btn dept-icon-btn--edit"
|
||||
<ElButton
|
||||
link
|
||||
type="primary"
|
||||
:icon="Edit"
|
||||
:title="t('admin.dept.actions.edit')"
|
||||
@click="editDepartment(row as AdminDepartmentRow)"
|
||||
>
|
||||
<Edit class="dept-action-icon" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="dept-icon-btn dept-icon-btn--delete"
|
||||
/>
|
||||
<ElButton
|
||||
link
|
||||
type="danger"
|
||||
:icon="Delete"
|
||||
:title="t('admin.dept.actions.delete')"
|
||||
@click="deleteDepartment((row as AdminDepartmentRow).id)"
|
||||
>
|
||||
<Trash2 class="dept-action-icon" />
|
||||
</button>
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
@@ -219,69 +216,9 @@ onMounted(() => {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.dept-member-btn,
|
||||
.dept-icon-btn {
|
||||
border: 0;
|
||||
cursor: pointer;
|
||||
line-height: 0;
|
||||
}
|
||||
|
||||
.dept-member-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 8px;
|
||||
border-radius: 8px;
|
||||
background: #eff6ff;
|
||||
color: #2563eb;
|
||||
}
|
||||
|
||||
.dept-member-btn:hover {
|
||||
background: #dbeafe;
|
||||
}
|
||||
|
||||
.dept-member-icon {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
}
|
||||
|
||||
.dept-member-btn span {
|
||||
margin-left: 4px;
|
||||
font-size: 12px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.dept-row-actions {
|
||||
display: inline-flex;
|
||||
justify-content: flex-end;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.dept-icon-btn {
|
||||
padding: 6px;
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
transition: background-color 0.15s ease;
|
||||
}
|
||||
|
||||
.dept-action-icon {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
}
|
||||
|
||||
.dept-icon-btn--edit {
|
||||
color: #4f46e5;
|
||||
}
|
||||
|
||||
.dept-icon-btn--edit:hover {
|
||||
background: #eef2ff;
|
||||
}
|
||||
|
||||
.dept-icon-btn--delete {
|
||||
color: #dc2626;
|
||||
}
|
||||
|
||||
.dept-icon-btn--delete:hover {
|
||||
background: #fef2f2;
|
||||
}
|
||||
</style>
|
||||
@@ -1,12 +1,14 @@
|
||||
<!--
|
||||
features/admin/modules/freight-rpa/FreightRpaPage.vue
|
||||
用途:货代来源站点管理工作台,维护解析方案、连接、站点、入站/出站报表配置、模板与运行审计。
|
||||
依赖:element-plus(抽屉/弹窗/表单控件/标签/空态,沿用管理端 element-trial 主题)、
|
||||
依赖:element-plus(抽屉/弹窗/表单控件/标签/提示/空态,沿用管理端 element-trial 主题)、
|
||||
admin.api、inboundReportConfigForm、outboundReportConfigForm、parsingProfileListGroups、
|
||||
Vue Router、Vue Composition API、Vue I18n。
|
||||
逻辑:由 AdminLayout 统一业务目录选择工作区;section 深链与当前工作区双向同步。
|
||||
来源站点详情三块折叠——库存报表|入站报表|出站报表;入站/出站走独立 get/save API。
|
||||
复制新增只预填未保存草稿(sourceCloneDraft),保存后新站点保持停用。卡片入口是右上角复制图标,抽屉底栏保留文字按钮。
|
||||
报表规则列表按用途分段(库存→入站→出站),组内按 profile_code / version 排序。
|
||||
系统连接回显用户名明文,密码留空表示不修改。自动上传只保存开关,页面动作在连接器代码里。
|
||||
视觉层已迁移 Element Plus(element-trial 主题),间距由 AdminLayout 壳层持有。
|
||||
-->
|
||||
<template>
|
||||
@@ -96,18 +98,28 @@
|
||||
</section>
|
||||
</div>
|
||||
<div v-else class="object-list">
|
||||
<button
|
||||
<article
|
||||
v-for="item in currentItems"
|
||||
:key="String(item.id)"
|
||||
type="button"
|
||||
class="object-row"
|
||||
class="object-row object-row-split"
|
||||
:class="{ selected: selectedId === Number(item.id) }"
|
||||
@click="selectItem(item)"
|
||||
>
|
||||
<span class="row-primary">{{ rowTitle(item) }}</span>
|
||||
<span class="row-secondary">{{ rowMeta(item) }}</span>
|
||||
<span class="status-dot" :class="item.enabled === false || item.status === 'retired' ? 'off' : 'on'"></span>
|
||||
</button>
|
||||
<button type="button" class="object-row-main" @click="selectItem(item)">
|
||||
<span class="row-primary">{{ rowTitle(item) }}</span>
|
||||
<span class="row-secondary">{{ rowMeta(item) }}</span>
|
||||
<span class="status-dot" :class="item.enabled === false || item.status === 'retired' ? 'off' : 'on'"></span>
|
||||
</button>
|
||||
<el-tooltip v-if="activeTab === 'sources'" :content="t('admin.freightRpa.cloneSource')" placement="top">
|
||||
<el-button
|
||||
class="object-row-copy"
|
||||
text
|
||||
:icon="CopyDocument"
|
||||
:aria-label="t('admin.freightRpa.cloneSourceAria', { name: rowTitle(item) })"
|
||||
:data-testid="`clone-source-${item.id}`"
|
||||
@click="duplicateSource(item)"
|
||||
/>
|
||||
</el-tooltip>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<el-drawer
|
||||
@@ -132,32 +144,22 @@
|
||||
<label><span>{{ t('admin.freightRpa.connectionName') }}</span><el-input v-model="profile.display_name" required /></label>
|
||||
<label><span>{{ t('admin.freightRpa.connectorType') }}</span><el-select v-model="profile.connector_type"><el-option value="dbs" :label="t('admin.freightRpa.platform.dbs')" /><el-option value="crane" :label="t('admin.freightRpa.platform.crane')" /></el-select></label>
|
||||
<label><span>{{ t('admin.freightRpa.loginUrl') }}</span><el-input v-model="profile.login_url" type="url" required /></label>
|
||||
<label><span>{{ t('admin.freightRpa.username') }}</span><el-input v-model="profile.username" name="shipping-rpa-credential-user" autocomplete="one-time-code" readonly :placeholder="t('admin.freightRpa.writeOnlyHint')" @focus="unlockCredentialField" /></label>
|
||||
<label><span>{{ t('admin.freightRpa.username') }}</span><el-input v-model="profile.username" name="shipping-rpa-username" autocomplete="off" /></label>
|
||||
<label><span>{{ t('admin.freightRpa.password') }}</span><el-input v-model="profile.password" name="shipping-rpa-credential-password" type="password" autocomplete="new-password" readonly :placeholder="t('admin.freightRpa.writeOnlyHint')" @focus="unlockCredentialField" /></label>
|
||||
<div class="switch-field"><span>{{ t('admin.freightRpa.enabled') }}</span><div class="switch-control"><el-switch v-model="profile.enabled" /><b>{{ profile.enabled ? t('admin.freightRpa.enabledState') : t('admin.freightRpa.disabledState') }}</b></div></div>
|
||||
|
||||
<section class="upload-config-section full">
|
||||
<header class="upload-config-heading">
|
||||
<b>{{ t('admin.freightRpa.uploadConfigTitle') }}</b>
|
||||
<small>{{ t('admin.freightRpa.uploadConfigHint') }}</small>
|
||||
</header>
|
||||
<div class="switch-field"><span>{{ t('admin.freightRpa.uploadAutoEnabled') }}</span><div class="switch-control"><el-switch v-model="profile.upload_config_json.enabled" /><b>{{ profile.upload_config_json.enabled ? t('admin.freightRpa.enabledState') : t('admin.freightRpa.disabledState') }}</b></div></div>
|
||||
<label><span>{{ t('admin.freightRpa.uploadEntryUrl') }}</span><el-input v-model="profile.upload_config_json.entry_url" type="url" /></label>
|
||||
<label><span>{{ t('admin.freightRpa.uploadFileSelector') }}</span><el-input v-model="profile.upload_config_json.file_input_selector" /></label>
|
||||
<label><span>{{ t('admin.freightRpa.uploadSubmitMode') }}</span><el-select v-model="profile.upload_config_json.submit_mode"><el-option value="auto_after_file" :label="t('admin.freightRpa.uploadSubmitAuto')" /><el-option value="click_submit" :label="t('admin.freightRpa.uploadSubmitClick')" /></el-select></label>
|
||||
<label v-if="profile.upload_config_json.submit_mode === 'click_submit'"><span>{{ t('admin.freightRpa.uploadSubmitSelector') }}</span><el-input v-model="profile.upload_config_json.submit_selector" /></label>
|
||||
<label><span>{{ t('admin.freightRpa.uploadResultMode') }}</span><el-select v-model="profile.upload_config_json.result_mode"><el-option value="page_notice" :label="t('admin.freightRpa.uploadResultPageNotice')" /><el-option value="history_record" :label="t('admin.freightRpa.uploadResultHistory')" /></el-select></label>
|
||||
<label><span>{{ t('admin.freightRpa.uploadResultSelector') }}</span><el-input v-model="profile.upload_config_json.result_selector" /></label>
|
||||
<label><span>{{ t('admin.freightRpa.uploadSuccessTexts') }}</span><el-input v-model="successTextsInput" type="textarea" :rows="2" :placeholder="t('admin.freightRpa.uploadSuccessTextsHint')" /></label>
|
||||
<label><span>{{ t('admin.freightRpa.uploadTimeout') }}</span><el-input-number v-model="profile.upload_config_json.timeout_seconds" :min="1" /></label>
|
||||
<div class="form-tip full">{{ t('admin.freightRpa.uploadConfigBoundary') }}</div>
|
||||
</section>
|
||||
|
||||
<div class="form-tip full">{{ t('admin.freightRpa.connectionBoundary') }}</div>
|
||||
<div class="switch-field"><span>{{ t('admin.freightRpa.uploadAutoEnabled') }}</span><div class="switch-control"><el-switch v-model="profile.upload_config_json.enabled" /><b>{{ profile.upload_config_json.enabled ? t('admin.freightRpa.enabledState') : t('admin.freightRpa.disabledState') }}</b></div></div>
|
||||
</template>
|
||||
|
||||
<template v-else-if="activeTab === 'sources'">
|
||||
<label><span>{{ t('admin.freightRpa.sourceCode') }}</span><el-input v-model="source.source_code" required /></label>
|
||||
<el-alert
|
||||
v-if="sourceCloneFrom && !selectedId"
|
||||
class="full"
|
||||
type="info"
|
||||
:closable="false"
|
||||
:title="t('admin.freightRpa.cloneSourceBanner', { code: sourceCloneFrom.source_code, name: sourceCloneFrom.display_name })"
|
||||
data-testid="clone-source-banner"
|
||||
/>
|
||||
<label><span>{{ t('admin.freightRpa.sourceCode') }}</span><el-input ref="sourceCodeInputRef" v-model="source.source_code" required data-testid="source-code-input" /></label>
|
||||
<label><span>{{ t('admin.freightRpa.inventorySiteName') }}</span><el-input v-model="source.display_name" required /></label>
|
||||
<label><span>{{ t('admin.freightRpa.connectorType') }}</span><el-select v-model="source.connector_type"><el-option value="dbs" :label="t('admin.freightRpa.platform.dbs')" /><el-option value="crane" :label="t('admin.freightRpa.platform.crane')" /></el-select></label>
|
||||
<label><span>{{ t('admin.freightRpa.connection') }}</span><el-select v-model="source.rpa_profile_id"><el-option :value="0" :label="t('admin.freightRpa.chooseConnection')" /><el-option v-for="item in compatibleProfiles" :key="String(item.id)" :value="Number(item.id)" :label="item.display_name || item.profile_code" /></el-select></label>
|
||||
@@ -193,7 +195,7 @@
|
||||
<label class="full"><span>{{ t('admin.freightRpa.parsingProfiles') }}</span><el-select v-model="source.onhand_report_config.parsing_profile_id"><el-option :value="0" :label="t('admin.freightRpa.notConfigured')" /><el-option v-for="item in parsingProfiles.filter((row) => row.status === 'published' && row.purpose === 'onhand')" :key="String(item.id)" :value="Number(item.id)" :label="`${item.display_name || item.profile_code} V${item.version}`" /></el-select></label>
|
||||
</div>
|
||||
</section>
|
||||
<section v-if="selectedId" class="path-card inbound full" :class="{ configured: inboundConfigExists }">
|
||||
<section v-if="selectedId || inboundConfigExists" class="path-card inbound full" :class="{ configured: inboundConfigExists }">
|
||||
<button type="button" class="path-card-header" :aria-expanded="inboundSectionOpen" @click="toggleInboundSection">
|
||||
<span class="path-card-title"><b>{{ t('admin.freightRpa.inboundReportConfig') }}</b></span>
|
||||
<el-tag class="path-badge" :type="inboundConfigExists ? 'success' : 'info'" size="small">{{ inboundConfigExists ? t('admin.freightRpa.pathSectionConfigured') : t('admin.freightRpa.pathSectionNotConfigured') }}</el-tag>
|
||||
@@ -219,7 +221,7 @@
|
||||
<label class="full"><span>{{ t('admin.freightRpa.movementBindingLabel') }}</span><el-select v-model="inboundConfig.parsing_profile_id"><el-option :value="null as unknown as string" :label="t('admin.freightRpa.movementBindingNone')" /><el-option v-for="item in parsingProfiles.filter((row) => row.status === 'published' && row.purpose === 'inbound')" :key="`movement-bind-${item.id}`" :value="Number(item.id)" :label="`${item.display_name || item.profile_code} V${item.version}`" /></el-select></label>
|
||||
</div>
|
||||
</section>
|
||||
<section v-if="selectedId" class="path-card outbound full" :class="{ configured: outboundConfigExists }">
|
||||
<section v-if="selectedId || outboundConfigExists" class="path-card outbound full" :class="{ configured: outboundConfigExists }">
|
||||
<button type="button" class="path-card-header" :aria-expanded="outboundSectionOpen" @click="toggleOutboundSection">
|
||||
<span class="path-card-title"><b>{{ t('admin.freightRpa.outboundReportConfig') }}</b></span>
|
||||
<el-tag class="path-badge" :type="outboundConfigExists ? 'success' : 'info'" size="small">{{ outboundConfigExists ? t('admin.freightRpa.pathSectionConfigured') : t('admin.freightRpa.pathSectionNotConfigured') }}</el-tag>
|
||||
@@ -455,6 +457,7 @@
|
||||
<el-button v-if="activeTab === 'rules' && selectedId && selectedRuleStatus === 'published'" size="small" @click="retireCurrentRule">{{ t('admin.freightRpa.retire') }}</el-button>
|
||||
<el-button v-if="activeTab === 'templates' && selectedId && selectedTemplateStatus === 'draft'" size="small" @click="publishCurrentTemplate">{{ t('admin.freightRpa.publishTemplate') }}</el-button>
|
||||
<el-button v-if="activeTab === 'templates' && selectedId && selectedTemplateStatus !== 'draft'" size="small" @click="createTemplateVersion">{{ t('admin.freightRpa.createTemplateVersion') }}</el-button>
|
||||
<el-button v-if="activeTab === 'sources' && selectedId" size="small" data-testid="clone-source-drawer" @click="duplicateSourceFromDrawer">{{ t('admin.freightRpa.cloneSource') }}</el-button>
|
||||
<el-button v-if="activeTab === 'templates' && selectedId" size="small" @click="openTemplateCloneDialog">{{ t('admin.freightRpa.cloneTemplate') }}</el-button>
|
||||
<el-button v-if="activeTab === 'templates' && selectedId && selectedTemplateStatus === 'published'" type="danger" plain size="small" class="retire-template-action" @click="retireCurrentTemplate">{{ t('admin.freightRpa.retireTemplate') }}</el-button>
|
||||
<el-button v-if="activeTab === 'parsing' && selectedId && selectedParsingStatus === 'draft'" size="small" @click="publishCurrentParsingProfile">{{ t('admin.freightRpa.publishProfile') }}</el-button>
|
||||
@@ -581,8 +584,9 @@ import {
|
||||
ElSelect,
|
||||
ElSwitch,
|
||||
ElTag,
|
||||
ElTooltip,
|
||||
} from 'element-plus';
|
||||
import { Plus, Search } from '@element-plus/icons-vue';
|
||||
import { CopyDocument, Plus, Search } from '@element-plus/icons-vue';
|
||||
import 'element-plus/dist/index.css';
|
||||
import 'element-plus/theme-chalk/dark/css-vars.css';
|
||||
import '@/features/admin/styles/element-trial.css';
|
||||
@@ -642,6 +646,7 @@ import {
|
||||
} from '@/features/admin/api/admin.api';
|
||||
import type { ShippingOnhandReadinessCheck, ShippingOnhandValidationBatch } from '@/features/admin/api/admin.api';
|
||||
import { normaliseInventoryReportPath } from './shippingOnhandSourceForm';
|
||||
import { buildSourceCloneDraft, type SourceCloneDraft, type SourceCloneReportConfig } from './sourceCloneDraft';
|
||||
import { buildInboundReportConfigPayload } from './inboundReportConfigForm';
|
||||
import { buildOutboundReportConfigPayload } from './outboundReportConfigForm';
|
||||
import { buildMovementFieldMapping } from './movementParsingProfileForm';
|
||||
@@ -663,6 +668,8 @@ const router = useRouter();
|
||||
const message = useMessage();
|
||||
const activeTab = ref<TabKey>('parsing');
|
||||
const selectedId = ref<number | null>(null);
|
||||
const sourceCloneFrom = ref<{ source_code: string; display_name: string } | null>(null);
|
||||
const sourceCodeInputRef = ref<InstanceType<typeof ElInput> | null>(null);
|
||||
const drawerOpen = ref(false);
|
||||
const orderSchemaPublished = ref(false);
|
||||
const saving = ref(false);
|
||||
@@ -722,33 +729,12 @@ const filenameVariableCandidates = computed(() => {
|
||||
return filenameVariables.filter((item) => item.key.toLowerCase().includes(query) || t(item.labelKey).toLowerCase().includes(query));
|
||||
});
|
||||
|
||||
/** 连接级“发货 Excel 自动上传”配置的受控 JSON 形状(字段与后端白名单一致)。 */
|
||||
interface ProfileUploadConfig {
|
||||
enabled: boolean;
|
||||
entry_url: string;
|
||||
file_input_selector: string;
|
||||
submit_mode: 'auto_after_file' | 'click_submit';
|
||||
submit_selector: string | null;
|
||||
result_mode: 'page_notice' | 'history_record';
|
||||
result_selector: string | null;
|
||||
success_texts: string[];
|
||||
timeout_seconds: number;
|
||||
}
|
||||
|
||||
/** 连接级“发货 Excel 自动上传”默认配置:DSV 为已确认 URL+input#file2;Crane 保持未启用待管理员补全。 */
|
||||
function defaultUploadConfig(connectorType: string): ProfileUploadConfig {
|
||||
if (connectorType === 'crane') {
|
||||
return { enabled: false, entry_url: 'https://wms-portal.craneww.com/#/shipping-order-upload', file_input_selector: 'input[name="OrderFileUpload"]', submit_mode: 'click_submit', submit_selector: null, result_mode: 'page_notice', result_selector: null, success_texts: [], timeout_seconds: 120 };
|
||||
}
|
||||
return { enabled: true, entry_url: 'https://s360.dbschenker.com/main/portal/frame/WMSUpload2', file_input_selector: 'input#file2', submit_mode: 'auto_after_file', submit_selector: null, result_mode: 'page_notice', result_selector: null, success_texts: [], timeout_seconds: 120 };
|
||||
/** 系统连接只保存是否启用自动上传;页面路径和成功判断在连接器代码里。 */
|
||||
function defaultUploadConfig(connectorType: string): { enabled: boolean } {
|
||||
return { enabled: connectorType !== 'crane' };
|
||||
}
|
||||
|
||||
const profile = reactive({ profile_code: '', display_name: '', connector_type: 'dbs', login_url: '', username: '', password: '', login_config_json: { auth_mode: 'password' }, enabled: true, upload_config_json: defaultUploadConfig('dbs') });
|
||||
/** 成功文本以换行分隔的输入视图,写回 success_texts 数组。 */
|
||||
const successTextsInput = computed<string>({
|
||||
get: () => (profile.upload_config_json.success_texts || []).join('\n'),
|
||||
set: (value) => { profile.upload_config_json.success_texts = String(value || '').split(/\r?\n/).map((item) => item.trim()).filter(Boolean); },
|
||||
});
|
||||
const parsing = reactive({
|
||||
profile_code: '', display_name: '', file_format: 'xlsx', sheet_name: '', header_row_index: 1,
|
||||
purpose: 'onhand' as 'onhand' | 'inbound' | 'outbound',
|
||||
@@ -1106,7 +1092,7 @@ watch(
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
/** 新建连接时按货代类型切换上传配置默认值;编辑既有连接不覆盖已保存配置。 */
|
||||
/** 新建连接时按货代类型决定自动上传默认开关;编辑既有连接不覆盖已保存配置。 */
|
||||
watch(
|
||||
() => profile.connector_type,
|
||||
(nextType) => {
|
||||
@@ -1123,6 +1109,7 @@ function selectInventoryMappingTab(tab: 'parsing' | 'inventoryFields'): void {
|
||||
/** 重置当前工作区的编辑表单,作为创建新对象的入口。 */
|
||||
function createNew(): void {
|
||||
selectedId.value = null;
|
||||
sourceCloneFrom.value = null;
|
||||
if (activeTab.value === 'profiles') Object.assign(profile, { profile_code: '', display_name: '', connector_type: 'dbs', login_url: '', username: '', password: '', login_config_json: { auth_mode: 'password' }, enabled: true, upload_config_json: defaultUploadConfig('dbs') });
|
||||
if (activeTab.value === 'parsing') { Object.assign(parsing, { profile_code: '', display_name: '', file_format: 'xlsx', sheet_name: '', header_row_index: 1, purpose: 'onhand', field_mappings: [], match_keys: [], movement_mappings: [] }); structureAnalysis.value = null; pendingSampleReplacement.value = null; sampleReplacementConfirmed.value = false; selectedTemporaryInventorySession.value = ''; }
|
||||
if (activeTab.value === 'inventoryFields') Object.assign(inventoryField, { display_name: '', description: '', value_type: 'text', usage_type: 'general', sort_order: 100, status: 'active' });
|
||||
@@ -1151,10 +1138,11 @@ function createNew(): void {
|
||||
drawerOpen.value = true;
|
||||
}
|
||||
|
||||
/** 将列表对象复制到当前编辑表单,凭据字段永远不从列表回填。 */
|
||||
/** 将列表对象复制到当前编辑表单。用户名回填明文,密码不回填。 */
|
||||
function selectItem(item: Item): void {
|
||||
selectedId.value = Number(item.id);
|
||||
if (activeTab.value === 'profiles') Object.assign(profile, { ...item, username: '', password: '', login_config_json: item.login_config_json || { auth_mode: 'password' }, upload_config_json: item.upload_config_json || defaultUploadConfig(item.connector_type) });
|
||||
sourceCloneFrom.value = null;
|
||||
if (activeTab.value === 'profiles') Object.assign(profile, { ...item, username: String(item.username || ''), password: '', login_config_json: item.login_config_json || { auth_mode: 'password' }, upload_config_json: { enabled: Boolean(item.upload_config_json?.enabled) } });
|
||||
if (activeTab.value === 'parsing') Object.assign(parsing, {
|
||||
profile_code: item.profile_code, display_name: item.display_name, file_format: item.file_format,
|
||||
sheet_name: item.definition?.sheet_name || '', header_row_index: item.definition?.header_row_index ?? 0,
|
||||
@@ -1321,15 +1309,164 @@ function closeDrawer(): void {
|
||||
resetReceiptConfig(source.connector_type);
|
||||
resetOutboundConfig(source.connector_type);
|
||||
sourceBaseline.value = '';
|
||||
sourceCloneFrom.value = null;
|
||||
drawerOpen.value = false;
|
||||
selectedId.value = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把接口里的入站或出站配置整理成复制草稿能接受的形状。
|
||||
* 核心逻辑:Crane 固定报表名,与抽屉读取逻辑一致;没有配置时返回 null。
|
||||
* @param config - 入站或出站 GET 返回;不存在时为 null。
|
||||
* @param connectorType - 货代类型,决定路径默认值。
|
||||
* @param kind - inbound 或 outbound。
|
||||
* @returns 深拷贝前的报表配置,或 null。
|
||||
*/
|
||||
function movementConfigFromApi(config: Record<string, unknown> | null, connectorType: string, kind: 'inbound' | 'outbound'): SourceCloneReportConfig | null {
|
||||
if (!config) return null;
|
||||
const isCrane = connectorType.toLowerCase() === 'crane';
|
||||
const defaults: Record<string, string> = kind === 'inbound'
|
||||
? (isCrane ? { report_name: 'Inbound Details' } : { program_group: '', program_label: '', report_group: 'Inbound', report_name: '' })
|
||||
: (isCrane ? { report_name: 'Outbound Details' } : { program_group: '', program_label: '', report_group: 'Outbound', report_name: '' });
|
||||
const storedPath = (config.report_path_json || {}) as Record<string, string>;
|
||||
const parameters = Array.isArray(config.query_parameters_json) ? config.query_parameters_json as Parameter[] : [];
|
||||
return {
|
||||
report_path_json: isCrane ? defaults : { ...defaults, ...storedPath },
|
||||
query_parameters_json: parameters.map((parameter) => ({ ...parameter, values: [...(parameter.values || [])] })),
|
||||
parsing_profile_id: config.parsing_profile_id ? Number(config.parsing_profile_id) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 把复制草稿写入新建表单,并在有入站或出站时展开对应卡片。
|
||||
* 核心逻辑:selectedId 保持为空,保存前不落库;已有报表配置标记为待写入,避免空配置被创建。
|
||||
* @param draft - buildSourceCloneDraft 的返回值。
|
||||
*/
|
||||
function applySourceCloneDraft(draft: SourceCloneDraft): void {
|
||||
// [STEP 1] 站点头部与库存报表进入新建表单,启用检查不继承来源站点。
|
||||
selectedId.value = null;
|
||||
Object.assign(source, {
|
||||
source_code: draft.source_code,
|
||||
display_name: draft.display_name,
|
||||
connector_type: draft.connector_type,
|
||||
rpa_profile_id: draft.rpa_profile_id,
|
||||
excel_template_id: draft.excel_template_id,
|
||||
warehouse_resolution_mode: draft.warehouse_resolution_mode,
|
||||
fixed_warehouse_id: draft.fixed_warehouse_id,
|
||||
snapshot_ttl_seconds: draft.snapshot_ttl_seconds,
|
||||
onhand_report_config: draft.onhand_report_config,
|
||||
enabled: false,
|
||||
activation: { ready: false, checks: [], missing_requirements: ['parsing_profile', 'excel_template'] },
|
||||
});
|
||||
// [STEP 2] 仅当来源站点已有入站或出站时预填,并标记为保存时必须写入。
|
||||
if (draft.inbound_report_config) {
|
||||
Object.assign(inboundConfig, draft.inbound_report_config);
|
||||
inboundConfigExists.value = true;
|
||||
inboundSectionTouched.value = true;
|
||||
inboundSectionOpen.value = true;
|
||||
inboundBaseline.value = serialiseInboundInput();
|
||||
} else {
|
||||
resetReceiptConfig(draft.connector_type);
|
||||
inboundConfigExists.value = false;
|
||||
inboundSectionTouched.value = false;
|
||||
inboundSectionOpen.value = false;
|
||||
inboundBaseline.value = '';
|
||||
}
|
||||
if (draft.outbound_report_config) {
|
||||
Object.assign(outboundConfig, draft.outbound_report_config);
|
||||
outboundConfigExists.value = true;
|
||||
outboundSectionTouched.value = true;
|
||||
outboundSectionOpen.value = true;
|
||||
outboundBaseline.value = serialiseOutboundInput();
|
||||
} else {
|
||||
resetOutboundConfig(draft.connector_type);
|
||||
outboundConfigExists.value = false;
|
||||
outboundSectionTouched.value = false;
|
||||
outboundSectionOpen.value = false;
|
||||
outboundBaseline.value = '';
|
||||
}
|
||||
sourceCloneFrom.value = draft.clone_from;
|
||||
inventoryPathOpen.value = true;
|
||||
sourceBaseline.value = '';
|
||||
drawerOpen.value = true;
|
||||
void nextTick(() => sourceCodeInputRef.value?.focus());
|
||||
}
|
||||
|
||||
/**
|
||||
* 从卡片复制来源站点。先读取独立的入站和出站配置,再打开未保存草稿。
|
||||
* @param item - 列表中的来源站点。
|
||||
*/
|
||||
async function duplicateSource(item: Item): Promise<void> {
|
||||
const sourceId = Number(item.id);
|
||||
const connectorType = String(item.connector_type || '');
|
||||
try {
|
||||
const [inbound, outbound] = await Promise.all([
|
||||
getInboundReportConfig(sourceId),
|
||||
getOutboundReportConfig(sourceId),
|
||||
]);
|
||||
const itemConfig = (item.onhand_report_config || {}) as { report_path_json?: Record<string, string>; query_parameters_json?: Parameter[]; parsing_profile_id?: number | string };
|
||||
const reportPath = connectorType === 'dbs'
|
||||
? { program_group: '', program_label: '', report_group: 'Inventory', report_name: '', ...(itemConfig.report_path_json || {}) }
|
||||
: (itemConfig.report_path_json || {});
|
||||
applySourceCloneDraft(buildSourceCloneDraft({
|
||||
source_code: String(item.source_code || ''),
|
||||
display_name: String(item.display_name || ''),
|
||||
connector_type: connectorType,
|
||||
rpa_profile_id: Number(item.rpa_profile_id) || 0,
|
||||
excel_template_id: Number(item.excel_template_id) || 0,
|
||||
warehouse_resolution_mode: String(item.warehouse_resolution_mode || 'fixed'),
|
||||
fixed_warehouse_id: String(item.fixed_warehouse_id || ''),
|
||||
snapshot_ttl_seconds: Number(item.snapshot_ttl_seconds) || 86400,
|
||||
onhand_report_config: {
|
||||
report_path_json: normaliseInventoryReportPath(connectorType, reportPath) as Record<string, string>,
|
||||
query_parameters_json: (itemConfig.query_parameters_json || []).map((parameter) => ({ ...parameter, values: [...(parameter.values || [])] })),
|
||||
parsing_profile_id: itemConfig.parsing_profile_id ? Number(itemConfig.parsing_profile_id) : 0,
|
||||
},
|
||||
inbound_report_config: movementConfigFromApi(inbound, connectorType, 'inbound'),
|
||||
outbound_report_config: movementConfigFromApi(outbound, connectorType, 'outbound'),
|
||||
}, t('admin.freightRpa.copySuffix')));
|
||||
} catch (cause) {
|
||||
showError(cause, 'loadFailed');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从已打开的站点抽屉复制当前表单,包含尚未保存的入站和出站修改。
|
||||
*/
|
||||
function duplicateSourceFromDrawer(): void {
|
||||
if (activeTab.value !== 'sources' || !selectedId.value) return;
|
||||
applySourceCloneDraft(buildSourceCloneDraft({
|
||||
source_code: source.source_code,
|
||||
display_name: source.display_name,
|
||||
connector_type: source.connector_type,
|
||||
rpa_profile_id: Number(source.rpa_profile_id) || 0,
|
||||
excel_template_id: Number(source.excel_template_id) || 0,
|
||||
warehouse_resolution_mode: source.warehouse_resolution_mode,
|
||||
fixed_warehouse_id: source.fixed_warehouse_id || '',
|
||||
snapshot_ttl_seconds: Number(source.snapshot_ttl_seconds) || 86400,
|
||||
onhand_report_config: {
|
||||
report_path_json: { ...source.onhand_report_config.report_path_json },
|
||||
query_parameters_json: source.onhand_report_config.query_parameters_json.map((parameter) => ({ ...parameter, values: [...parameter.values] })),
|
||||
parsing_profile_id: Number(source.onhand_report_config.parsing_profile_id) || 0,
|
||||
},
|
||||
inbound_report_config: inboundConfigExists.value ? {
|
||||
report_path_json: { ...inboundConfig.report_path_json },
|
||||
query_parameters_json: inboundConfig.query_parameters_json.map((parameter) => ({ ...parameter, values: [...parameter.values] })),
|
||||
parsing_profile_id: inboundConfig.parsing_profile_id ? Number(inboundConfig.parsing_profile_id) : null,
|
||||
} : null,
|
||||
outbound_report_config: outboundConfigExists.value ? {
|
||||
report_path_json: { ...outboundConfig.report_path_json },
|
||||
query_parameters_json: outboundConfig.query_parameters_json.map((parameter) => ({ ...parameter, values: [...parameter.values] })),
|
||||
parsing_profile_id: outboundConfig.parsing_profile_id ? Number(outboundConfig.parsing_profile_id) : null,
|
||||
} : null,
|
||||
}, t('admin.freightRpa.copySuffix')));
|
||||
}
|
||||
|
||||
/** 按当前对象类型调用对应 API,成功后重新加载服务端真相。 */
|
||||
async function saveCurrent(): Promise<void> {
|
||||
saving.value = true;
|
||||
try {
|
||||
if (activeTab.value === 'profiles') await saveShippingRpaProfile({ ...profile, display_name: profile.display_name || profile.profile_code, upload_config_json: profile.upload_config_json }, selectedId.value || undefined);
|
||||
if (activeTab.value === 'profiles') await saveShippingRpaProfile({ ...profile, display_name: profile.display_name || profile.profile_code, upload_config_json: { enabled: Boolean(profile.upload_config_json?.enabled) } }, selectedId.value || undefined);
|
||||
if (activeTab.value === 'parsing') {
|
||||
const payload = parsingUsesMovementContract.value ? {
|
||||
profile_code: parsing.profile_code, display_name: parsing.display_name || parsing.profile_code, file_format: parsing.file_format,
|
||||
@@ -1383,11 +1520,18 @@ async function saveCurrent(): Promise<void> {
|
||||
}
|
||||
if (activeTab.value === 'sources') {
|
||||
// s18 起在手报表配置随站点载荷内嵌 onhand_report_config 提交(服务端写配置行),站点头部只存基础字段。
|
||||
await saveShippingOnhandSource({ ...source, enabled: false, fixed_warehouse_id: source.warehouse_resolution_mode === 'fixed' ? source.fixed_warehouse_id : null, onhand_report_config: {
|
||||
const savedSource = await saveShippingOnhandSource({ ...source, enabled: false, fixed_warehouse_id: source.warehouse_resolution_mode === 'fixed' ? source.fixed_warehouse_id : null, onhand_report_config: {
|
||||
report_path_json: normaliseInventoryReportPath(source.connector_type, source.onhand_report_config.report_path_json),
|
||||
query_parameters_json: source.onhand_report_config.query_parameters_json,
|
||||
parsing_profile_id: source.onhand_report_config.parsing_profile_id,
|
||||
} }, selectedId.value || undefined);
|
||||
} }, selectedId.value || undefined) as Item;
|
||||
// 复制草稿首次保存后立刻记下新主键,入站或出站失败时重试走更新,避免再插入一条站点。
|
||||
if (!selectedId.value) {
|
||||
const createdId = Number(savedSource?.id);
|
||||
if (!createdId) throw new Error(t('admin.freightRpa.saveFailed'));
|
||||
selectedId.value = createdId;
|
||||
sourceCloneFrom.value = null;
|
||||
}
|
||||
// 入站与站点同批保存:仅当已有配置或管理员展开过入站卡时才提交,避免未配置站点被误建空入站配置。
|
||||
if (selectedId.value && (inboundSectionTouched.value || (inboundConfigExists.value && inboundBaseline.value !== serialiseInboundInput()))) {
|
||||
try {
|
||||
@@ -1774,11 +1918,16 @@ function rowTitle(item: Item): string {
|
||||
|
||||
/**
|
||||
* 列表卡副标题。
|
||||
* 核心逻辑:mappings 展示「在途仓编码 → 目标仓编码」;缺在途仓时退化为仅目标编码。
|
||||
* 核心逻辑:mappings 展示「在途仓编码 → 目标仓编码」;系统连接展示平台与用户名。
|
||||
* @param item - 当前列表行对象
|
||||
* @returns 副标题文案
|
||||
*/
|
||||
function rowMeta(item: Item): string {
|
||||
if (activeTab.value === 'profiles') {
|
||||
const platform = item.connector_type ? t(`admin.freightRpa.platform.${item.connector_type}`) : String(item.profile_code || '');
|
||||
const username = String(item.username || '').trim();
|
||||
return username ? `${platform} · ${username}` : platform;
|
||||
}
|
||||
if (activeTab.value === 'mappings') {
|
||||
const targetCode = String(item.external_warehouse_code || '-');
|
||||
const inTransit = String(item.in_transit_warehouse_code || '').trim();
|
||||
@@ -1916,6 +2065,14 @@ onMounted(load);
|
||||
.object-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 10px; }
|
||||
.object-empty { grid-column: 1 / -1; }
|
||||
.object-row { position: relative; display: flex; width: 100%; min-height: 72px; flex-direction: column; justify-content: center; gap: 4px; border: 1px solid var(--el-border-color-light); border-radius: 8px; background: var(--el-bg-color); padding: 12px 30px 12px 13px; text-align: left; cursor: pointer; }
|
||||
.object-row-split { height: 100%; justify-content: flex-start; padding: 0; cursor: default; }
|
||||
.object-row-main { display: flex; width: 100%; flex: 1 1 auto; min-height: 72px; flex-direction: column; justify-content: center; gap: 4px; border: 0; background: transparent; padding: 12px 30px 12px 13px; text-align: left; cursor: pointer; color: inherit; font: inherit; }
|
||||
.object-row-split:has(.object-row-copy) .object-row-main { padding-right: 62px; }
|
||||
.object-row-main:focus-visible { outline: 2px solid var(--el-color-primary); outline-offset: -2px; }
|
||||
/* 复制图标贴在状态点左侧。平时保持可见但较淡,悬停或键盘聚焦时再加深,避免底栏把卡片垫高。 */
|
||||
.object-row-copy { position: absolute; top: 6px; right: 28px; width: 28px; min-width: 28px; height: 28px; margin: 0; padding: 0; opacity: 0.45; --el-button-text-color: var(--el-text-color-secondary); }
|
||||
.object-row:hover .object-row-copy,
|
||||
.object-row-copy:focus-visible { opacity: 1; --el-button-text-color: var(--el-color-primary); }
|
||||
.object-row:hover { border-color: var(--el-color-primary-light-5); background: var(--el-color-primary-light-9); }
|
||||
.object-row.selected { border-color: var(--el-color-primary-light-7); background: var(--el-color-primary-light-9); }
|
||||
.row-primary { color: var(--el-text-color-regular); font-size: 13px; font-weight: 600; }
|
||||
@@ -2001,11 +2158,6 @@ onMounted(load);
|
||||
.filename-variable-menu code { color: var(--el-color-primary-dark-2); font-size: 12px; }
|
||||
.filename-variable-menu p { margin: 0; padding: 8px; color: var(--el-text-color-placeholder); font-size: 12px; }
|
||||
.form-tip { border-radius: 8px; background: var(--el-fill-color-light); padding: 11px; color: var(--el-text-color-secondary); font-size: 12px; line-height: 1.55; }
|
||||
.upload-config-section { grid-column: 1 / -1; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; border: 1px solid var(--el-border-color-lighter); border-radius: 9px; background: var(--el-bg-color); padding: 0 12px 12px; }
|
||||
.upload-config-heading { display: grid; gap: 2px; grid-column: 1 / -1; padding: 11px 0 8px; }
|
||||
.upload-config-heading b { color: var(--el-text-color-regular); font-size: 12px; }
|
||||
.upload-config-heading small { color: var(--el-text-color-placeholder); font-size: 12px; }
|
||||
.upload-config-section .full { grid-column: 1 / -1; }
|
||||
.sample-evidence-card { display: grid; gap: 12px; border: 1px solid var(--el-border-color-lighter); border-radius: 8px; background: var(--el-fill-color-lighter); padding: 14px; }
|
||||
.sample-evidence-card > div { display: grid; gap: 3px; }
|
||||
.sample-evidence-card strong { color: var(--el-text-color-regular); font-size: 13px; }
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* features/admin/modules/freight-rpa/sourceCloneDraft.spec.ts
|
||||
* 用途:锁定来源站点复制草稿的字段边界。
|
||||
* 依赖:sourceCloneDraft、vitest。
|
||||
* 逻辑:复制必须清空唯一编号、强制停用,并深拷贝查询条件;没有的入站或出站不得变成空配置。
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { buildSourceCloneDraft, type SourceCloneInput } from './sourceCloneDraft';
|
||||
|
||||
function sourceInput(overrides: Partial<SourceCloneInput> = {}): SourceCloneInput {
|
||||
return {
|
||||
source_code: 'BYAWSATL01',
|
||||
display_name: 'DSV 360 / Bison / AWSBI',
|
||||
connector_type: 'dbs',
|
||||
rpa_profile_id: 7,
|
||||
excel_template_id: 3,
|
||||
warehouse_resolution_mode: 'fixed',
|
||||
fixed_warehouse_id: 'WH-ATL',
|
||||
snapshot_ttl_seconds: 86400,
|
||||
onhand_report_config: {
|
||||
report_path_json: { program_group: 'Bison', program_label: 'AWSBI', report_group: 'Inventory', report_name: 'On Hand' },
|
||||
query_parameters_json: [{ name: 'Site', mode: 'single', values: ['ATL'], required: true, select_all: false }],
|
||||
parsing_profile_id: 11,
|
||||
},
|
||||
inbound_report_config: {
|
||||
report_path_json: { program_group: 'Bison', program_label: 'AWSBI', report_group: 'Inbound', report_name: 'Receipt' },
|
||||
query_parameters_json: [{ name: 'Warehouse', mode: 'multi_text', values: ['ATL'], required: false, select_all: false }],
|
||||
parsing_profile_id: 21,
|
||||
},
|
||||
outbound_report_config: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('buildSourceCloneDraft', () => {
|
||||
it('clears the unique code, suffixes the name, and forces the draft to stay disabled', () => {
|
||||
// 关键断言:编号必须由管理员重填,名称带副本后缀,且不能继承已启用状态。
|
||||
const draft = buildSourceCloneDraft(sourceInput(), '副本');
|
||||
|
||||
expect(draft.source_code).toBe('');
|
||||
expect(draft.display_name).toBe('DSV 360 / Bison / AWSBI 副本');
|
||||
expect(draft.enabled).toBe(false);
|
||||
expect(draft.clone_from).toEqual({ source_code: 'BYAWSATL01', display_name: 'DSV 360 / Bison / AWSBI' });
|
||||
expect(draft.rpa_profile_id).toBe(7);
|
||||
expect(draft.excel_template_id).toBe(3);
|
||||
expect(draft.fixed_warehouse_id).toBe('WH-ATL');
|
||||
expect(draft.onhand_report_config.parsing_profile_id).toBe(11);
|
||||
expect(draft.onhand_report_config.report_path_json.report_name).toBe('On Hand');
|
||||
});
|
||||
|
||||
it('deep-copies query values so editing the draft does not change the source', () => {
|
||||
const input = sourceInput();
|
||||
const draft = buildSourceCloneDraft(input, '副本');
|
||||
|
||||
draft.onhand_report_config.query_parameters_json[0].values.push('FRA');
|
||||
draft.inbound_report_config?.query_parameters_json[0].values.push('FRA');
|
||||
|
||||
// 关键断言:来源卡片上的条件数组保持原值,草稿修改不得回写。
|
||||
expect(input.onhand_report_config.query_parameters_json[0].values).toEqual(['ATL']);
|
||||
expect(input.inbound_report_config?.query_parameters_json[0].values).toEqual(['ATL']);
|
||||
});
|
||||
|
||||
it('omits inbound and outbound configs that the source does not have', () => {
|
||||
const draft = buildSourceCloneDraft(sourceInput({ inbound_report_config: null, outbound_report_config: null }), 'Copy');
|
||||
|
||||
// 关键断言:缺失的报表配置保持 null,保存时才不会建出空的入站或出站行。
|
||||
expect(draft.inbound_report_config).toBeNull();
|
||||
expect(draft.outbound_report_config).toBeNull();
|
||||
expect(draft.display_name).toBe('DSV 360 / Bison / AWSBI Copy');
|
||||
});
|
||||
|
||||
it('does not carry identity, activation, or unrelated records', () => {
|
||||
const draft = buildSourceCloneDraft({
|
||||
...sourceInput(),
|
||||
id: 99,
|
||||
enabled: true,
|
||||
activation: { ready: true, checks: [{ code: 'configuration_test' }] },
|
||||
external_mappings: [{ external_warehouse_code: 'SHOULD-NOT-COPY' }],
|
||||
} as SourceCloneInput & Record<string, unknown>, '副本');
|
||||
|
||||
// 关键断言:主键、启用检查、仓库映射不属于可复制配置。
|
||||
expect(draft).not.toHaveProperty('id');
|
||||
expect(draft).not.toHaveProperty('activation');
|
||||
expect(draft).not.toHaveProperty('external_mappings');
|
||||
expect(draft.enabled).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* features/admin/modules/freight-rpa/sourceCloneDraft.ts
|
||||
* 用途:把已有来源站点配置变成一份尚未落库的新建草稿。
|
||||
* 依赖:无。
|
||||
* 逻辑:FreightRpaPage 在卡片或抽屉点击「复制新增」时调用;保存仍走既有新建接口。
|
||||
*/
|
||||
|
||||
export type SourceCloneParameter = {
|
||||
name: string;
|
||||
mode: string;
|
||||
values: string[];
|
||||
required: boolean;
|
||||
select_all: boolean;
|
||||
joiner?: string;
|
||||
};
|
||||
|
||||
export type SourceCloneReportConfig = {
|
||||
report_path_json: Record<string, string>;
|
||||
query_parameters_json: SourceCloneParameter[];
|
||||
parsing_profile_id: number | null;
|
||||
};
|
||||
|
||||
export type SourceCloneInput = {
|
||||
source_code: string;
|
||||
display_name: string;
|
||||
connector_type: string;
|
||||
rpa_profile_id: number;
|
||||
excel_template_id: number;
|
||||
warehouse_resolution_mode: string;
|
||||
fixed_warehouse_id: string;
|
||||
snapshot_ttl_seconds: number;
|
||||
onhand_report_config: {
|
||||
report_path_json: Record<string, string>;
|
||||
query_parameters_json: SourceCloneParameter[];
|
||||
parsing_profile_id: number;
|
||||
};
|
||||
inbound_report_config: SourceCloneReportConfig | null;
|
||||
outbound_report_config: SourceCloneReportConfig | null;
|
||||
};
|
||||
|
||||
export type SourceCloneDraft = {
|
||||
source_code: '';
|
||||
display_name: string;
|
||||
connector_type: string;
|
||||
rpa_profile_id: number;
|
||||
excel_template_id: number;
|
||||
warehouse_resolution_mode: string;
|
||||
fixed_warehouse_id: string;
|
||||
snapshot_ttl_seconds: number;
|
||||
enabled: false;
|
||||
onhand_report_config: {
|
||||
report_path_json: Record<string, string>;
|
||||
query_parameters_json: SourceCloneParameter[];
|
||||
parsing_profile_id: number;
|
||||
};
|
||||
inbound_report_config: SourceCloneReportConfig | null;
|
||||
outbound_report_config: SourceCloneReportConfig | null;
|
||||
clone_from: { source_code: string; display_name: string };
|
||||
};
|
||||
|
||||
/**
|
||||
* 深拷贝查询条件,避免草稿里改值时回写到来源对象。
|
||||
* @param parameters - 来源站点上的查询条件。
|
||||
* @returns 条件与取值都是新数组的副本。
|
||||
*/
|
||||
function cloneParameters(parameters: SourceCloneParameter[] | undefined): SourceCloneParameter[] {
|
||||
return (parameters || []).map((parameter) => ({
|
||||
...parameter,
|
||||
values: [...(parameter.values || [])],
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 复制一份报表配置;没有配置时返回 null,避免保存时建出空的入站或出站行。
|
||||
* @param config - 已有报表配置;空表示该站点没有这块配置。
|
||||
* @returns 深拷贝后的配置,或 null。
|
||||
*/
|
||||
function cloneReport(config: SourceCloneReportConfig | null | undefined): SourceCloneReportConfig | null {
|
||||
if (!config) return null;
|
||||
return {
|
||||
report_path_json: { ...(config.report_path_json || {}) },
|
||||
query_parameters_json: cloneParameters(config.query_parameters_json),
|
||||
parsing_profile_id: config.parsing_profile_id ? Number(config.parsing_profile_id) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从来源站点生成未保存草稿。
|
||||
* 核心逻辑:配置字段逐项深拷贝;库存源编号清空;名称追加副本后缀;启用状态固定为停用。
|
||||
* 不复制主键、启用检查、快照、仓库映射和路由规则。
|
||||
* @param input - 来源站点当前可见配置,入站或出站没有配置时传 null。
|
||||
* @param copySuffix - 追加在名称后的本地化后缀,例如「副本」。
|
||||
* @returns 可直接填入新建表单的草稿,source_code 恒为空字符串。
|
||||
*/
|
||||
export function buildSourceCloneDraft(input: SourceCloneInput, copySuffix: string): SourceCloneDraft {
|
||||
const displayName = String(input.display_name || input.source_code || '').trim();
|
||||
const suffix = String(copySuffix || '').trim();
|
||||
return {
|
||||
source_code: '',
|
||||
display_name: suffix ? `${displayName} ${suffix}` : displayName,
|
||||
connector_type: input.connector_type,
|
||||
rpa_profile_id: Number(input.rpa_profile_id) || 0,
|
||||
excel_template_id: Number(input.excel_template_id) || 0,
|
||||
warehouse_resolution_mode: input.warehouse_resolution_mode,
|
||||
fixed_warehouse_id: input.fixed_warehouse_id || '',
|
||||
snapshot_ttl_seconds: Number(input.snapshot_ttl_seconds) || 86400,
|
||||
enabled: false,
|
||||
onhand_report_config: {
|
||||
report_path_json: { ...(input.onhand_report_config?.report_path_json || {}) },
|
||||
query_parameters_json: cloneParameters(input.onhand_report_config?.query_parameters_json),
|
||||
parsing_profile_id: Number(input.onhand_report_config?.parsing_profile_id) || 0,
|
||||
},
|
||||
inbound_report_config: cloneReport(input.inbound_report_config),
|
||||
outbound_report_config: cloneReport(input.outbound_report_config),
|
||||
clone_from: {
|
||||
source_code: String(input.source_code || ''),
|
||||
display_name: displayName,
|
||||
},
|
||||
};
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* features/admin/modules/reports/composables/useReportsAdmin.ts
|
||||
* 用途:管理后台报表(多表浏览、筛选、排序、chat_logs 批量删除、使用分析与应用运营看板)。
|
||||
* 依赖:admin.api、useReportLayoutStorage、useOffsetPagination、useMessage、dateTime、vue-router。
|
||||
* 逻辑:ReportsPage 调用本 composable;使用分析按用户服务端分页、按应用前端分页,均复用 PaginationBar;
|
||||
* 依赖:admin.api、useReportLayoutStorage、useOffsetPagination、useMessage、dateTime、vue-router、element-plus(ElMessageBox)。
|
||||
* 逻辑:ReportsPage 调用本 composable;使用分析按用户服务端分页、按应用前端分页,页码状态交给页面的 ElPagination;
|
||||
* 低使用应用优先消费后端 low_agents(含零使用启用应用),与应用运营口径对齐;
|
||||
* 统计范围统一为开始/结束日期(默认近 30 天),经 start_date/end_date 传给后端,聊天日志走 created_from/created_to;
|
||||
* 趋势 by_day 前端按日期升序兜底;问题分析优先问题表前端分页;非表页切换时清空通用表状态防幽灵分页。
|
||||
@@ -10,6 +10,7 @@
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { ElMessageBox } from 'element-plus';
|
||||
import * as XLSX from 'xlsx';
|
||||
import {
|
||||
batchDeleteAdminChatLogs,
|
||||
@@ -655,30 +656,6 @@ export function useReportsAdmin() {
|
||||
};
|
||||
const isLoading = ref(true);
|
||||
|
||||
const showDeleteConfirmDialog = ref(false);
|
||||
const deleteConfirmMessage = ref('');
|
||||
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
|
||||
|
||||
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
|
||||
deleteConfirmMessage.value = message;
|
||||
deleteConfirmAction = action;
|
||||
showDeleteConfirmDialog.value = true;
|
||||
};
|
||||
|
||||
const closeDeleteConfirm = (): void => {
|
||||
showDeleteConfirmDialog.value = false;
|
||||
deleteConfirmAction = null;
|
||||
};
|
||||
|
||||
const confirmDelete = async (): Promise<void> => {
|
||||
if (!deleteConfirmAction) return;
|
||||
try {
|
||||
await deleteConfirmAction();
|
||||
} finally {
|
||||
closeDeleteConfirm();
|
||||
}
|
||||
};
|
||||
|
||||
const resolveTableFromRoute = (): AdminReportTableId => {
|
||||
const table = route.params.table;
|
||||
if (typeof table === 'string' && (ADMIN_REPORT_TABLES as readonly string[]).includes(table)) {
|
||||
@@ -1575,25 +1552,41 @@ const toggleAllReportRows = () => {
|
||||
selectedReportRowIds.value = Array.from(merged);
|
||||
};
|
||||
|
||||
const batchDeleteChatLogs = async () => {
|
||||
/**
|
||||
* 批量删除已勾选的聊天日志。
|
||||
* 核心逻辑:先弹出 Element 确认框;取消则直接返回。确认后按当前选中 id 调用原批量删除接口并刷新列表与总数。
|
||||
* @returns 无。取消确认时不请求接口。
|
||||
*/
|
||||
const batchDeleteChatLogs = async (): Promise<void> => {
|
||||
if (!isChatLogsTable.value) return;
|
||||
if (selectedReportRowIds.value.length === 0) return;
|
||||
const targetRowIds = [...selectedReportRowIds.value];
|
||||
openDeleteConfirm(`Delete ${targetRowIds.length} selected chat logs?`, async () => {
|
||||
isDeletingChatLogs.value = true;
|
||||
try {
|
||||
const data = await batchDeleteAdminChatLogs(targetRowIds);
|
||||
msg.success(`Deleted ${data.deleted_count ?? 0} chat logs.`);
|
||||
selectedReportRowIds.value = [];
|
||||
await loadTableData();
|
||||
chatLogsTotal.value = await loadTableCount('chat_logs');
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
msg.error((e as Error).message || t('admin.msg.failed'));
|
||||
} finally {
|
||||
isDeletingChatLogs.value = false;
|
||||
}
|
||||
});
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
t('admin.report.deleteSelected', { count: targetRowIds.length }),
|
||||
t('common.deleteDialog.defaultTitle'),
|
||||
{
|
||||
type: 'warning',
|
||||
confirmButtonText: t('common.deleteDialog.confirm'),
|
||||
cancelButtonText: t('common.deleteDialog.cancel'),
|
||||
},
|
||||
);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
isDeletingChatLogs.value = true;
|
||||
try {
|
||||
const data = await batchDeleteAdminChatLogs(targetRowIds);
|
||||
msg.success(`Deleted ${data.deleted_count ?? 0} chat logs.`);
|
||||
selectedReportRowIds.value = [];
|
||||
await loadTableData();
|
||||
chatLogsTotal.value = await loadTableCount('chat_logs');
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
msg.error((e as Error).message || t('admin.msg.failed'));
|
||||
} finally {
|
||||
isDeletingChatLogs.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
watch(currentTable, async () => {
|
||||
@@ -1913,8 +1906,6 @@ watch([reportPageSize, issueQuestionTotal], () => {
|
||||
reportRangeStart,
|
||||
reportRangeEnd,
|
||||
reportPageButtons,
|
||||
showDeleteConfirmDialog,
|
||||
deleteConfirmMessage,
|
||||
loadAll,
|
||||
handleFilterChange,
|
||||
resetChatLogsColumns,
|
||||
@@ -1941,6 +1932,5 @@ watch([reportPageSize, issueQuestionTotal], () => {
|
||||
goToReportPage,
|
||||
prevReportPage,
|
||||
nextReportPage,
|
||||
confirmDelete,
|
||||
};
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+123
-71
@@ -1,14 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/admin/modules/training-config/components/LeanTargetModal.vue
|
||||
* 用途:精益周任务"受训对象"选择弹窗,支持按角色、按员工两个维度多选(两个范围取并集生效)。
|
||||
* 依赖:vue-i18n、lucide 图标与父级培训配置页面传入的目标状态(角色/用户 ID/用户列表)。
|
||||
* 逻辑:弹窗打开时从 props 快照到本地草稿(取消不污染外部状态);员工支持关键字搜索;
|
||||
* 确认后 emit save({ roles, userIds }),由父级写回表单并随"保存任务"统一落库。
|
||||
* 用途:精益周任务受训对象选择对话框,按角色和员工两个维度多选。
|
||||
* 依赖:element-plus 对话框、复选框和搜索框、vue-i18n、父级传入的用户列表。
|
||||
* 逻辑:打开时把父级选择快照到本地草稿,取消不回写。确认后 emit save,由父级随保存任务提交。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Search } from 'lucide-vue-next';
|
||||
import { ElButton, ElCheckbox, ElDialog, ElForm, ElFormItem, ElInput, ElText } from 'element-plus';
|
||||
import type { AdminUserRow } from '../../../types/admin.types';
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -48,91 +47,144 @@ const summaryLabel = computed(() => t('admin.trainingConfig.lean.targetSelectedC
|
||||
users: draftUserIds.value.length,
|
||||
}));
|
||||
|
||||
/**
|
||||
* 切换一个角色是否进入本次草稿。
|
||||
* @param role - 角色名
|
||||
*/
|
||||
const toggleRole = (role: string) => {
|
||||
draftRoles.value = draftRoles.value.includes(role)
|
||||
? draftRoles.value.filter((item) => item !== role)
|
||||
: [...draftRoles.value, role];
|
||||
};
|
||||
|
||||
/**
|
||||
* 切换一名员工是否进入本次草稿。
|
||||
* @param userId - 用户主键
|
||||
*/
|
||||
const toggleUser = (userId: number) => {
|
||||
draftUserIds.value = draftUserIds.value.includes(userId)
|
||||
? draftUserIds.value.filter((item) => item !== userId)
|
||||
: [...draftUserIds.value, userId];
|
||||
};
|
||||
|
||||
/**
|
||||
* 把草稿交回父级。落库仍等父级保存周任务。
|
||||
*/
|
||||
const handleSave = () => {
|
||||
emit('save', { roles: [...draftRoles.value], userIds: [...draftUserIds.value] });
|
||||
};
|
||||
|
||||
/**
|
||||
* 对话框关闭时通知页面收起。
|
||||
* @param open - Element 对话框的打开状态
|
||||
*/
|
||||
function onVisibleChange(open: boolean): void {
|
||||
if (!open) emit('close');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="props.visible" class="admin-modal-overlay animate-fade-in items-center" @click.self="emit('close')">
|
||||
<div class="admin-modal-panel max-w-2xl max-h-[92vh] scale-100">
|
||||
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
|
||||
<h3 class="section-title">{{ t('admin.trainingConfig.lean.targetModalTitle') }}</h3>
|
||||
<p class="mt-1 text-xs text-muted">{{ t('admin.trainingConfig.lean.targetsHint') }}</p>
|
||||
<ElDialog
|
||||
:model-value="props.visible"
|
||||
:title="t('admin.trainingConfig.lean.targetModalTitle')"
|
||||
width="680px"
|
||||
align-center
|
||||
append-to-body
|
||||
:close-on-click-modal="false"
|
||||
@update:model-value="onVisibleChange"
|
||||
>
|
||||
<ElText type="info">{{ t('admin.trainingConfig.lean.targetsHint') }}</ElText>
|
||||
<ElForm label-position="top" class="lean-target-form">
|
||||
<div class="lean-target-grid">
|
||||
<ElFormItem :label="t('admin.trainingConfig.lean.targetRoles')">
|
||||
<div class="lean-target-list">
|
||||
<ElCheckbox
|
||||
v-for="role in props.roleOptions"
|
||||
:key="role"
|
||||
:model-value="draftRoles.includes(role)"
|
||||
@change="toggleRole(role)"
|
||||
>
|
||||
{{ role }}
|
||||
</ElCheckbox>
|
||||
<ElText v-if="!props.roleOptions.length" type="info">{{ t('admin.trainingConfig.lean.targetRolesEmpty') }}</ElText>
|
||||
</div>
|
||||
</ElFormItem>
|
||||
<ElFormItem :label="t('admin.trainingConfig.lean.targetUsers')">
|
||||
<ElInput
|
||||
v-model="keyword"
|
||||
class="lean-target-search"
|
||||
clearable
|
||||
:placeholder="t('admin.trainingConfig.lean.targetSearchPlaceholder')"
|
||||
/>
|
||||
<div class="lean-target-list lean-target-list--scroll">
|
||||
<ElCheckbox
|
||||
v-for="user in filteredUsers"
|
||||
:key="user.id"
|
||||
:model-value="draftUserIds.includes(user.id)"
|
||||
@change="toggleUser(user.id)"
|
||||
>
|
||||
{{ user.real_name || user.username }}
|
||||
<ElText type="info">{{ user.username }}</ElText>
|
||||
</ElCheckbox>
|
||||
<ElText v-if="!filteredUsers.length" type="info">{{ t('admin.trainingConfig.lean.targetUsersEmpty') }}</ElText>
|
||||
</div>
|
||||
</ElFormItem>
|
||||
</div>
|
||||
<div class="px-5 sm:px-8 py-5 overflow-y-auto">
|
||||
<div class="grid gap-5 md:grid-cols-2">
|
||||
<!-- 按角色选择 -->
|
||||
<div class="space-y-2">
|
||||
<label class="label-field">{{ t('admin.trainingConfig.lean.targetRoles') }}</label>
|
||||
<div class="space-y-2 rounded-xl border border-default bg-surface p-3">
|
||||
<label
|
||||
v-for="role in props.roleOptions"
|
||||
:key="role"
|
||||
class="flex cursor-pointer items-center gap-3 rounded-lg px-2 py-2 text-sm transition hover:bg-surface-soft"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
class="h-4 w-4 rounded border-default text-emerald-600 focus:ring-emerald-500"
|
||||
:checked="draftRoles.includes(role)"
|
||||
@change="toggleRole(role)"
|
||||
/>
|
||||
<span class="text-primary">{{ role }}</span>
|
||||
</label>
|
||||
<p v-if="!props.roleOptions.length" class="px-2 py-3 text-xs text-muted">{{ t('admin.trainingConfig.lean.targetRolesEmpty') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 按员工选择 -->
|
||||
<div class="space-y-2">
|
||||
<label class="label-field">{{ t('admin.trainingConfig.lean.targetUsers') }}</label>
|
||||
<div class="relative">
|
||||
<Search class="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted" />
|
||||
<input
|
||||
v-model="keyword"
|
||||
type="text"
|
||||
class="input-field pl-9 text-sm"
|
||||
:placeholder="t('admin.trainingConfig.lean.targetSearchPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="max-h-64 space-y-1 overflow-y-auto rounded-xl border border-default bg-surface p-2">
|
||||
<label
|
||||
v-for="user in filteredUsers"
|
||||
:key="user.id"
|
||||
class="flex cursor-pointer items-center gap-3 rounded-lg px-2 py-2 text-sm transition hover:bg-surface-soft"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
class="h-4 w-4 rounded border-default text-emerald-600 focus:ring-emerald-500"
|
||||
:checked="draftUserIds.includes(user.id)"
|
||||
@change="toggleUser(user.id)"
|
||||
/>
|
||||
<span class="min-w-0 flex-1 truncate text-primary">{{ user.real_name || user.username }}</span>
|
||||
<span class="shrink-0 text-xs text-muted">{{ user.username }}</span>
|
||||
</label>
|
||||
<p v-if="!filteredUsers.length" class="px-2 py-3 text-xs text-muted">{{ t('admin.trainingConfig.lean.targetUsersEmpty') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</ElForm>
|
||||
<template #footer>
|
||||
<div class="lean-target-footer">
|
||||
<ElText type="info">{{ summaryLabel }}</ElText>
|
||||
<div>
|
||||
<ElButton @click="emit('close')">{{ t('admin.cancel') }}</ElButton>
|
||||
<ElButton type="primary" @click="handleSave">{{ t('admin.trainingConfig.lean.targetConfirm') }}</ElButton>
|
||||
</div>
|
||||
</div>
|
||||
<div class="admin-modal-footer">
|
||||
<p class="mr-auto text-xs text-muted">{{ summaryLabel }}</p>
|
||||
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
|
||||
<button type="button" class="btn-primary" @click="handleSave">
|
||||
{{ t('admin.trainingConfig.lean.targetConfirm') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</ElDialog>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.lean-target-form {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.lean-target-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.lean-target-list {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding: 8px;
|
||||
border: 1px solid var(--el-border-color);
|
||||
border-radius: var(--el-border-radius-base);
|
||||
}
|
||||
|
||||
.lean-target-list--scroll {
|
||||
max-height: 16rem;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
:deep(.lean-target-search) {
|
||||
width: 16rem;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.lean-target-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
.lean-target-grid {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
+42
-33
@@ -1,11 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/admin/modules/training-config/components/TrainingTypeFormModal.vue
|
||||
* 用途:提供培训类型 code 与名称的新增、编辑弹窗。
|
||||
* 依赖:vue-i18n 与父级培训配置页面的表单状态。
|
||||
* 逻辑:允许管理员输入符合编码规范的自定义类型 code,并将保存动作交由父级处理。
|
||||
* 用途:培训类型编码和名称的新增、编辑对话框。
|
||||
* 依赖:element-plus 对话框和表单、vue-i18n、父级传入的类型表单。
|
||||
* 逻辑:TrainingConfigPage 打开本组件。字段仍写回父级 form 对象,保存由父级校验并调接口。样式跟页面已引入的 Element 皮肤走。
|
||||
*/
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ElButton, ElDialog, ElForm, ElFormItem, ElInput } from 'element-plus';
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean;
|
||||
@@ -16,37 +17,45 @@ const props = defineProps<{
|
||||
|
||||
const emit = defineEmits<{ close: []; save: [] }>();
|
||||
const { t } = useI18n();
|
||||
|
||||
/**
|
||||
* 对话框关闭时通知页面收起。提交中不响应关闭。
|
||||
* @param open - Element 对话框的打开状态
|
||||
*/
|
||||
function onVisibleChange(open: boolean): void {
|
||||
if (!open && !props.isSaving) emit('close');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="props.visible" class="admin-modal-overlay animate-fade-in items-center" @click.self="emit('close')">
|
||||
<div class="admin-modal-panel max-w-lg max-h-[92vh] scale-100">
|
||||
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
|
||||
<h3 class="section-title">{{ props.editing ? t('admin.trainingConfig.editType') : t('admin.trainingConfig.addType') }}</h3>
|
||||
</div>
|
||||
<div class="px-5 sm:px-8 py-5 space-y-4 overflow-y-auto">
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.trainingConfig.fields.type') }}</label>
|
||||
<input
|
||||
v-model="props.form.training_type"
|
||||
type="text"
|
||||
class="input-field text-sm"
|
||||
maxlength="50"
|
||||
pattern="[a-z][a-z0-9_-]*"
|
||||
:placeholder="t('admin.trainingConfig.placeholders.typeCode')"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.trainingConfig.fields.name') }}</label>
|
||||
<input v-model="props.form.name" type="text" class="input-field text-sm" :placeholder="t('admin.trainingConfig.fields.name')" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="admin-modal-footer">
|
||||
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
|
||||
<button type="button" class="btn-primary disabled:opacity-70" :disabled="props.isSaving" @click="emit('save')">
|
||||
{{ props.isSaving ? `${t('admin.save')}...` : props.editing ? t('admin.update') : t('admin.add') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<ElDialog
|
||||
:model-value="visible"
|
||||
:title="editing ? t('admin.trainingConfig.editType') : t('admin.trainingConfig.addType')"
|
||||
width="480px"
|
||||
align-center
|
||||
append-to-body
|
||||
:close-on-click-modal="false"
|
||||
:close-on-press-escape="!isSaving"
|
||||
:show-close="!isSaving"
|
||||
@update:model-value="onVisibleChange"
|
||||
>
|
||||
<ElForm label-position="top" :model="form" @submit.prevent="emit('save')">
|
||||
<ElFormItem :label="t('admin.trainingConfig.fields.type')">
|
||||
<ElInput
|
||||
v-model="form.training_type"
|
||||
maxlength="50"
|
||||
:placeholder="t('admin.trainingConfig.placeholders.typeCode')"
|
||||
/>
|
||||
</ElFormItem>
|
||||
<ElFormItem :label="t('admin.trainingConfig.fields.name')">
|
||||
<ElInput v-model="form.name" :placeholder="t('admin.trainingConfig.fields.name')" />
|
||||
</ElFormItem>
|
||||
</ElForm>
|
||||
<template #footer>
|
||||
<ElButton :disabled="isSaving" @click="emit('close')">{{ t('admin.cancel') }}</ElButton>
|
||||
<ElButton type="primary" :loading="isSaving" @click="emit('save')">
|
||||
{{ editing ? t('admin.update') : t('admin.add') }}
|
||||
</ElButton>
|
||||
</template>
|
||||
</ElDialog>
|
||||
</template>
|
||||
@@ -1,26 +1,24 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/admin/modules/wecom/WecomLayout.vue
|
||||
* 企微管理壳层:二级 Tab、共享 composable、子路由出口。
|
||||
* 用途:企微管理壳层。注入共享数据,并提供 Element 语言与样式。
|
||||
* 依赖:useWecomAdmin、useElementProvider、element-plus、WECOM_ADMIN_KEY。
|
||||
* 逻辑:路由 /admin/wecom 的父级。首屏等 loadAll 结束后再渲染子页。子页自己放页签和列表,解绑确认在 composable 里完成。
|
||||
*/
|
||||
import { onMounted, provide } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { RefreshCw } from 'lucide-vue-next';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import WecomSubNav from './components/WecomSubNav.vue';
|
||||
import { ElConfigProvider, ElLoading } from 'element-plus';
|
||||
import 'element-plus/dist/index.css';
|
||||
import 'element-plus/theme-chalk/dark/css-vars.css';
|
||||
import '@/features/admin/styles/element-trial.css';
|
||||
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
|
||||
import { useWecomAdmin } from './composables/useWecomAdmin';
|
||||
import { WECOM_ADMIN_KEY } from './wecom.context';
|
||||
|
||||
const { t } = useI18n();
|
||||
const vLoading = ElLoading.directive;
|
||||
const { elementLocale } = useElementProvider();
|
||||
const wecomAdmin = useWecomAdmin();
|
||||
const { isLoading } = wecomAdmin;
|
||||
provide(WECOM_ADMIN_KEY, wecomAdmin);
|
||||
const {
|
||||
isLoading,
|
||||
showDeleteConfirmDialog,
|
||||
deleteConfirmMessage,
|
||||
confirmDelete,
|
||||
refreshWecomData,
|
||||
} = wecomAdmin;
|
||||
|
||||
onMounted(() => {
|
||||
void wecomAdmin.loadAll();
|
||||
@@ -28,33 +26,15 @@ onMounted(() => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="isLoading" class="flex items-center justify-center py-20">
|
||||
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
|
||||
</div>
|
||||
|
||||
<section v-else class="section-gap animate-fade-in-up space-y-6">
|
||||
<div class="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
|
||||
<div>
|
||||
<h2 class="section-title">{{ t('admin.wecom.title') }}</h2>
|
||||
<p class="section-desc mt-1">{{ t('admin.wecom.subtitle') }}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-secondary inline-flex items-center gap-2 px-4 py-2 text-secondary rounded-xl hover-surface-soft transition-all shadow-sm"
|
||||
@click="refreshWecomData()"
|
||||
>
|
||||
<RefreshCw class="w-4 h-4" />
|
||||
{{ t('admin.wecom.refresh') }}
|
||||
</button>
|
||||
<ElConfigProvider :locale="elementLocale">
|
||||
<div v-loading="isLoading" class="wecom-layout">
|
||||
<router-view v-if="!isLoading" />
|
||||
</div>
|
||||
|
||||
<WecomSubNav />
|
||||
<router-view />
|
||||
|
||||
<DeleteConfirmDialog
|
||||
v-model="showDeleteConfirmDialog"
|
||||
:message="deleteConfirmMessage"
|
||||
@confirm="confirmDelete"
|
||||
/>
|
||||
</section>
|
||||
</ElConfigProvider>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.wecom-layout {
|
||||
min-height: 16rem;
|
||||
}
|
||||
</style>
|
||||
@@ -1,10 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/admin/modules/wecom/components/WecomOverviewCards.vue
|
||||
* 企微 userid 绑定概览统计卡片。
|
||||
* 用途:企微 userid 绑定概览。四张统计卡,不是列表。
|
||||
* 依赖:getAdminWecomBindingStats、element-plus 的卡片和统计。
|
||||
* 逻辑:绑定管理页放在列表卡片正文里。数字用 ElStatistic;说明句用文字块。refreshKey 变化时重拉。
|
||||
*/
|
||||
import { onMounted, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ElCard, ElStatistic, ElText } from 'element-plus';
|
||||
import { getAdminWecomBindingStats } from '@/features/admin/api/admin.api';
|
||||
import type { WecomBindingStats } from '@/features/admin/types/wecom.types';
|
||||
|
||||
@@ -16,7 +19,8 @@ const { t } = useI18n();
|
||||
const stats = ref<WecomBindingStats | null>(null);
|
||||
|
||||
/**
|
||||
* 拉取绑定统计,供设置页概览卡片展示。
|
||||
* 拉取绑定统计,供概览卡片展示。
|
||||
* 核心逻辑:请求失败时清空卡片,避免留下过期数字。
|
||||
*/
|
||||
const loadStats = async (): Promise<void> => {
|
||||
try {
|
||||
@@ -42,22 +46,43 @@ defineExpose({ reload: loadStats });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="stats" class="grid grid-cols-2 xl:grid-cols-4 gap-3">
|
||||
<div class="rounded-xl bg-surface-soft px-4 py-3">
|
||||
<div class="text-xs text-muted">{{ t('admin.wecom.overview.bound') }}</div>
|
||||
<div class="mt-1 text-xl font-semibold text-primary">{{ stats.bound }} / {{ stats.total_active }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-surface-soft px-4 py-3">
|
||||
<div class="text-xs text-muted">{{ t('admin.wecom.overview.unbound') }}</div>
|
||||
<div class="mt-1 text-xl font-semibold text-amber-700">{{ stats.unbound }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-surface-soft px-4 py-3">
|
||||
<div class="text-xs text-muted">{{ t('admin.wecom.overview.boundRate') }}</div>
|
||||
<div class="mt-1 text-xl font-semibold text-emerald-700">{{ stats.bound_rate }}%</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-surface-soft px-4 py-3">
|
||||
<div class="text-xs text-muted">{{ t('admin.wecom.overview.hint') }}</div>
|
||||
<div class="mt-1 text-sm text-secondary leading-5">{{ t('admin.wecom.overview.hintDesc') }}</div>
|
||||
</div>
|
||||
<div v-if="stats" class="wecom-overview">
|
||||
<ElCard shadow="never">
|
||||
<ElStatistic
|
||||
:title="t('admin.wecom.overview.bound')"
|
||||
:value="stats.bound"
|
||||
:suffix="` / ${stats.total_active}`"
|
||||
/>
|
||||
</ElCard>
|
||||
<ElCard shadow="never">
|
||||
<ElStatistic :title="t('admin.wecom.overview.unbound')" :value="stats.unbound" />
|
||||
</ElCard>
|
||||
<ElCard shadow="never">
|
||||
<ElStatistic :title="t('admin.wecom.overview.boundRate')" :value="stats.bound_rate" suffix="%" />
|
||||
</ElCard>
|
||||
<ElCard shadow="never">
|
||||
<div class="wecom-overview__hint-title">{{ t('admin.wecom.overview.hint') }}</div>
|
||||
<ElText type="info">{{ t('admin.wecom.overview.hintDesc') }}</ElText>
|
||||
</ElCard>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.wecom-overview {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.wecom-overview__hint-title {
|
||||
margin-bottom: 8px;
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: var(--el-font-size-small);
|
||||
}
|
||||
|
||||
@media (min-width: 1280px) {
|
||||
.wecom-overview {
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,33 +1,43 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/admin/modules/wecom/components/WecomSubNav.vue
|
||||
* 企微管理二级 Tab 导航。
|
||||
* 用途:企微管理的设置、绑定、审计页签。
|
||||
* 依赖:AdminListTabs、vue-router、vue-i18n。
|
||||
* 逻辑:放进各子页 AdminListPage 的 tabs 插槽。页签名就是现有路由名,点击只做 router.push。
|
||||
*/
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRoute } from 'vue-router';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import AdminListTabs from '@/features/admin/components/AdminListTabs.vue';
|
||||
|
||||
const { t } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
|
||||
const tabs = [
|
||||
{ name: 'AdminWecomSettings', labelKey: 'admin.wecom.nav.settings' },
|
||||
{ name: 'AdminWecomBindings', labelKey: 'admin.wecom.nav.bindings' },
|
||||
{ name: 'AdminWecomAudits', labelKey: 'admin.wecom.nav.audits' },
|
||||
] as const;
|
||||
|
||||
const tabItems = computed(() => tabs.map((tab) => ({
|
||||
name: tab.name,
|
||||
label: t(tab.labelKey),
|
||||
})));
|
||||
|
||||
const activeTab = computed(() => String(route.name || 'AdminWecomSettings'));
|
||||
|
||||
/**
|
||||
* 切换企微子页。
|
||||
* 核心逻辑:页签名与路由名相同,只跳转,不改路由表。
|
||||
* @param name - AdminListTabs 当前 name
|
||||
*/
|
||||
function onTabChange(name: string): void {
|
||||
if (name === activeTab.value) return;
|
||||
void router.push({ name });
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-wrap gap-2 border-b border-subtle pb-3">
|
||||
<router-link
|
||||
v-for="tab in tabs"
|
||||
:key="tab.name"
|
||||
:to="{ name: tab.name }"
|
||||
class="rounded-xl px-4 py-2 text-sm font-medium transition-colors"
|
||||
:class="route.name === tab.name
|
||||
? 'bg-brand-50 text-brand-700 ring-1 ring-brand-200'
|
||||
: 'text-secondary hover:bg-surface-soft hover:text-primary'"
|
||||
>
|
||||
{{ t(tab.labelKey) }}
|
||||
</router-link>
|
||||
</div>
|
||||
<AdminListTabs :model-value="activeTab" :items="tabItems" @update:model-value="onTabChange" />
|
||||
</template>
|
||||
@@ -1,14 +1,23 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/admin/modules/wecom/components/WecomSyncPanel.vue
|
||||
* OA userInfo_view 工号→wecom_userid 同步面板(预览 + 确认写入)。
|
||||
* 依赖:useWecomSync、WECOM_ADMIN_KEY.refreshWecomData。
|
||||
* 逻辑:绑定管理页调用;先扫本地工号,再按 IN 查 OA userInfo_view 匹配写入。
|
||||
* 用途:OA userInfo_view 工号到 wecom_userid 的预览和确认写入面板。
|
||||
* 依赖:useWecomSync、WECOM_ADMIN_KEY.refreshWecomData、element-plus。
|
||||
* 逻辑:绑定管理页调用。先扫本地工号,再按 IN 查 OA 匹配。确认写入在 composable 里弹 Element 确认框。
|
||||
*/
|
||||
import { inject } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { RefreshCw } from 'lucide-vue-next';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import { Refresh } from '@element-plus/icons-vue';
|
||||
import {
|
||||
ElAlert,
|
||||
ElButton,
|
||||
ElLoading,
|
||||
ElStatistic,
|
||||
ElTable,
|
||||
ElTableColumn,
|
||||
ElText,
|
||||
} from 'element-plus';
|
||||
import type { WecomSyncPendingUpdate } from '@/features/admin/types/wecom.types';
|
||||
import { WECOM_ADMIN_KEY } from '../wecom.context';
|
||||
import { useWecomSync } from '../composables/useWecomSync';
|
||||
|
||||
@@ -16,146 +25,190 @@ const emit = defineEmits<{
|
||||
applied: [];
|
||||
}>();
|
||||
|
||||
const vLoading = ElLoading.directive;
|
||||
const { t } = useI18n();
|
||||
const { refreshWecomData } = inject(WECOM_ADMIN_KEY)!;
|
||||
|
||||
const {
|
||||
isSyncing,
|
||||
previewSummary,
|
||||
showApplyConfirm,
|
||||
canApplySync,
|
||||
applyBlockHint,
|
||||
previewSync,
|
||||
requestApplySync,
|
||||
confirmApplySync,
|
||||
} = useWecomSync({
|
||||
onApplied: async () => {
|
||||
await refreshWecomData();
|
||||
emit('applied');
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* 预览表的行键。同一工号待写入的 userid 唯一。
|
||||
* @param row - 待更新行
|
||||
* @returns 工号与 userid 拼成的键
|
||||
*/
|
||||
function pendingRowKey(row: WecomSyncPendingUpdate): string {
|
||||
return `${row.employee_id}-${row.wecom_userid}`;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="card shadow-sm p-5 space-y-4">
|
||||
<div>
|
||||
<h3 class="font-semibold text-primary">{{ t('admin.wecom.sync.title') }}</h3>
|
||||
<p class="mt-1 text-sm text-muted">{{ t('admin.wecom.sync.desc') }}</p>
|
||||
<p class="mt-2 text-xs text-sky-900 bg-sky-50 border border-sky-100 rounded-lg px-3 py-2">
|
||||
{{ t('admin.wecom.sync.oaSourceNote') }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="wecom-sync">
|
||||
<h3 class="wecom-sync__title">{{ t('admin.wecom.sync.title') }}</h3>
|
||||
<ElText type="info">{{ t('admin.wecom.sync.desc') }}</ElText>
|
||||
<ElAlert
|
||||
class="wecom-sync__note"
|
||||
type="info"
|
||||
:closable="false"
|
||||
:title="t('admin.wecom.sync.oaSourceNote')"
|
||||
/>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
|
||||
<div class="wecom-sync__fields">
|
||||
<div>
|
||||
<div class="text-xs text-muted">{{ t('admin.wecom.sync.oaWorkcodeField') }}</div>
|
||||
<div class="mt-1 font-mono text-primary">userInfo_view.workcode</div>
|
||||
<div class="wecom-sync__label">{{ t('admin.wecom.sync.oaWorkcodeField') }}</div>
|
||||
<div class="wecom-sync__mono">userInfo_view.workcode</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-xs text-muted">{{ t('admin.wecom.sync.oaWecomIdField') }}</div>
|
||||
<div class="mt-1 font-mono text-primary">userInfo_view.id</div>
|
||||
<div class="wecom-sync__label">{{ t('admin.wecom.sync.oaWecomIdField') }}</div>
|
||||
<div class="wecom-sync__mono">userInfo_view.id</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-2"
|
||||
:class="isSyncing ? 'btn-secondary opacity-60' : 'btn-primary'"
|
||||
:disabled="isSyncing"
|
||||
@click="previewSync"
|
||||
>
|
||||
<RefreshCw class="w-4 h-4" :class="{ 'animate-spin': isSyncing }" />
|
||||
{{ t('admin.wecom.sync.preview') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
:class="canApplySync && !isSyncing ? 'btn-primary' : 'btn-secondary opacity-60'"
|
||||
:disabled="isSyncing"
|
||||
:title="applyBlockHint || undefined"
|
||||
@click="requestApplySync"
|
||||
>
|
||||
{{ t('admin.wecom.sync.apply') }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="applyBlockHint && !isSyncing" class="text-xs text-muted">
|
||||
{{ applyBlockHint }}
|
||||
</p>
|
||||
<div class="wecom-sync__actions">
|
||||
<ElButton type="primary" :icon="Refresh" :loading="isSyncing" @click="previewSync">
|
||||
{{ t('admin.wecom.sync.preview') }}
|
||||
</ElButton>
|
||||
<ElButton
|
||||
:type="canApplySync ? 'primary' : 'default'"
|
||||
:disabled="isSyncing"
|
||||
:title="applyBlockHint || undefined"
|
||||
@click="requestApplySync"
|
||||
>
|
||||
{{ t('admin.wecom.sync.apply') }}
|
||||
</ElButton>
|
||||
</div>
|
||||
<ElText v-if="applyBlockHint && !isSyncing" type="info">{{ applyBlockHint }}</ElText>
|
||||
|
||||
<div v-if="previewSummary" class="rounded-xl border border-subtle bg-surface-soft p-4 space-y-3 text-sm">
|
||||
<div class="grid grid-cols-2 md:grid-cols-4 gap-3">
|
||||
<div>
|
||||
<div class="text-xs text-muted">{{ t('admin.wecom.sync.stats.localCandidates') }}</div>
|
||||
<div class="font-semibold text-primary">{{ previewSummary.local_candidates }}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-xs text-muted">{{ t('admin.wecom.sync.stats.oaMatched') }}</div>
|
||||
<div class="font-semibold text-primary">{{ previewSummary.local_matched }}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-xs text-muted">{{ t('admin.wecom.sync.stats.wouldUpdate') }}</div>
|
||||
<div class="font-semibold text-brand-700">{{ previewSummary.would_update }}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-xs text-muted">{{ t('admin.wecom.sync.stats.conflicts') }}</div>
|
||||
<div class="font-semibold" :class="previewSummary.conflicts?.length ? 'text-red-600' : 'text-emerald-700'">
|
||||
{{ previewSummary.conflicts?.length || 0 }}
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="previewSummary" v-loading="isSyncing" class="wecom-sync__result">
|
||||
<div class="wecom-sync__stats">
|
||||
<ElStatistic :title="t('admin.wecom.sync.stats.localCandidates')" :value="previewSummary.local_candidates" />
|
||||
<ElStatistic :title="t('admin.wecom.sync.stats.oaMatched')" :value="previewSummary.local_matched" />
|
||||
<ElStatistic :title="t('admin.wecom.sync.stats.wouldUpdate')" :value="previewSummary.would_update" />
|
||||
<ElStatistic :title="t('admin.wecom.sync.stats.conflicts')" :value="previewSummary.conflicts?.length || 0" />
|
||||
</div>
|
||||
|
||||
<div v-if="previewSummary.local_missing > 0" class="text-xs text-muted">
|
||||
<ElText v-if="previewSummary.local_missing > 0" type="info">
|
||||
{{ t('admin.wecom.sync.localMissingHint', { count: previewSummary.local_missing }) }}
|
||||
</div>
|
||||
</ElText>
|
||||
|
||||
<div v-if="previewSummary.pending_updates?.length" class="overflow-x-auto">
|
||||
<table class="admin-table min-w-full">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="px-3 py-2 text-xs">{{ t('admin.wecom.headers.employeeId') }}</th>
|
||||
<th class="px-3 py-2 text-xs">{{ t('admin.wecom.headers.user') }}</th>
|
||||
<th class="px-3 py-2 text-xs">{{ t('admin.wecom.headers.wecomUserId') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="row in previewSummary.pending_updates" :key="`${row.employee_id}-${row.wecom_userid}`">
|
||||
<td class="px-3 py-2 text-xs">{{ row.employee_id }}</td>
|
||||
<td class="px-3 py-2 text-xs">
|
||||
{{ row.username }}
|
||||
<span v-if="row.name" class="text-muted"> · {{ row.name }}</span>
|
||||
</td>
|
||||
<td class="px-3 py-2 text-xs font-mono">{{ row.wecom_userid }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p v-if="previewSummary.would_update > previewSummary.pending_updates.length" class="mt-2 text-xs text-muted">
|
||||
{{ t('admin.wecom.sync.previewTruncated', { total: previewSummary.would_update }) }}
|
||||
</p>
|
||||
</div>
|
||||
<ElTable
|
||||
v-if="previewSummary.pending_updates?.length"
|
||||
class="hx-admin-table"
|
||||
:data="previewSummary.pending_updates"
|
||||
:row-key="pendingRowKey"
|
||||
:empty-text="t('admin.wecom.noData')"
|
||||
>
|
||||
<ElTableColumn :label="t('admin.wecom.headers.employeeId')" min-width="140">
|
||||
<template #default="{ row }">{{ (row as WecomSyncPendingUpdate).employee_id }}</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('admin.wecom.headers.user')" min-width="180">
|
||||
<template #default="{ row }">
|
||||
{{ (row as WecomSyncPendingUpdate).username }}
|
||||
<ElText v-if="(row as WecomSyncPendingUpdate).name" type="info">
|
||||
· {{ (row as WecomSyncPendingUpdate).name }}
|
||||
</ElText>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('admin.wecom.headers.wecomUserId')" min-width="180">
|
||||
<template #default="{ row }">
|
||||
<span class="wecom-sync__mono">{{ (row as WecomSyncPendingUpdate).wecom_userid }}</span>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
</ElTable>
|
||||
<ElText
|
||||
v-if="previewSummary.pending_updates?.length && previewSummary.would_update > previewSummary.pending_updates.length"
|
||||
type="info"
|
||||
>
|
||||
{{ t('admin.wecom.sync.previewTruncated', { total: previewSummary.would_update }) }}
|
||||
</ElText>
|
||||
|
||||
<div v-if="previewSummary.conflicts?.length" class="space-y-2">
|
||||
<div class="text-xs font-medium text-red-700">{{ t('admin.wecom.sync.conflictsTitle') }}</div>
|
||||
<div
|
||||
<div v-if="previewSummary.conflicts?.length" class="wecom-sync__conflicts">
|
||||
<ElText type="danger">{{ t('admin.wecom.sync.conflictsTitle') }}</ElText>
|
||||
<ElAlert
|
||||
v-for="(conflict, idx) in previewSummary.conflicts"
|
||||
:key="idx"
|
||||
class="rounded-lg border border-red-100 bg-red-50 px-3 py-2 text-xs text-red-800"
|
||||
type="error"
|
||||
:closable="false"
|
||||
:title="conflict.employee_id + ' / ' + conflict.username"
|
||||
>
|
||||
{{ conflict.employee_id }} / {{ conflict.username }}
|
||||
<span v-if="conflict.old_wecom_userid"> · {{ conflict.old_wecom_userid }} → {{ conflict.new_wecom_userid }}</span>
|
||||
<span v-else-if="conflict.occupied_by_username"> · {{ t('admin.wecom.sync.occupiedBy', { user: conflict.occupied_by_username }) }}</span>
|
||||
</div>
|
||||
<span v-if="conflict.old_wecom_userid">{{ conflict.old_wecom_userid }} → {{ conflict.new_wecom_userid }}</span>
|
||||
<span v-else-if="conflict.occupied_by_username">
|
||||
{{ t('admin.wecom.sync.occupiedBy', { user: conflict.occupied_by_username }) }}
|
||||
</span>
|
||||
</ElAlert>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DeleteConfirmDialog
|
||||
v-model="showApplyConfirm"
|
||||
:title="t('admin.wecom.sync.applyConfirmTitle')"
|
||||
:message="t('admin.wecom.sync.applyConfirm', { count: previewSummary?.would_update || 0 })"
|
||||
:confirm-text="t('admin.wecom.sync.applyConfirmButton')"
|
||||
confirm-tone="primary"
|
||||
@confirm="confirmApplySync"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.wecom-sync {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 16px 32px 24px;
|
||||
border-top: 1px solid var(--el-border-color-lighter);
|
||||
}
|
||||
|
||||
.wecom-sync__title {
|
||||
margin: 0;
|
||||
color: var(--el-text-color-primary);
|
||||
font-size: var(--el-font-size-large);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.wecom-sync__note {
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.wecom-sync__fields,
|
||||
.wecom-sync__stats {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.wecom-sync__label {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: var(--el-font-size-small);
|
||||
}
|
||||
|
||||
.wecom-sync__mono {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||
}
|
||||
|
||||
.wecom-sync__actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.wecom-sync__result {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.wecom-sync__conflicts {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
.wecom-sync__stats {
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,11 +1,12 @@
|
||||
/**
|
||||
* features/admin/modules/wecom/composables/useWecomAdmin.ts
|
||||
* 企业微信:绑定、系统配置、通知、登录审计。
|
||||
* 依赖:admin.api、useMessage、wecom 展示工具、PaginationBar 所需的审计分页状态。
|
||||
* 逻辑:绑定走服务端分页;登录审计仍一次拉取最近 200 条,由前端切片分页。
|
||||
* 依赖:admin.api、useMessage、wecom 展示工具、element-plus 确认框。
|
||||
* 逻辑:绑定走服务端分页;登录审计仍一次拉取最近 200 条,由前端切片分页。解绑用 ElMessageBox。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ElMessageBox } from 'element-plus';
|
||||
import * as XLSX from 'xlsx';
|
||||
import {
|
||||
bindAdminWecomUser,
|
||||
@@ -90,10 +91,6 @@ export function useWecomAdmin() {
|
||||
const wecomSystemSettings = ref<WecomSystemSettings>(createDefaultWecomSystemSettings());
|
||||
const wecomIntegrationManifest = ref<WecomIntegrationManifest | null>(null);
|
||||
|
||||
const showDeleteConfirmDialog = ref(false);
|
||||
const deleteConfirmMessage = ref('');
|
||||
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
|
||||
|
||||
const wecomBindUserOptions = computed(() => {
|
||||
const keyword = wecomBindUserQuery.value.trim().toLowerCase();
|
||||
return users.value
|
||||
@@ -110,26 +107,6 @@ export function useWecomAdmin() {
|
||||
}));
|
||||
});
|
||||
|
||||
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
|
||||
deleteConfirmMessage.value = message;
|
||||
deleteConfirmAction = action;
|
||||
showDeleteConfirmDialog.value = true;
|
||||
};
|
||||
|
||||
const closeDeleteConfirm = (): void => {
|
||||
showDeleteConfirmDialog.value = false;
|
||||
deleteConfirmAction = null;
|
||||
};
|
||||
|
||||
const confirmDelete = async (): Promise<void> => {
|
||||
if (!deleteConfirmAction) return;
|
||||
try {
|
||||
await deleteConfirmAction();
|
||||
} finally {
|
||||
closeDeleteConfirm();
|
||||
}
|
||||
};
|
||||
|
||||
const loadUsers = async (): Promise<void> => {
|
||||
try {
|
||||
users.value = await listAdminUsers();
|
||||
@@ -428,19 +405,31 @@ export function useWecomAdmin() {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 管理员解绑企微 userid。取消确认则不请求。
|
||||
* 核心逻辑:Element 确认框使用通用删除标题和按钮;确定后仍调用既有解绑接口并刷新列表。
|
||||
* @param userId - 本地用户主键
|
||||
*/
|
||||
const unbindWecomUserByAdmin = async (userId: number): Promise<void> => {
|
||||
openDeleteConfirm(t('admin.wecom.confirmUnbind'), async () => {
|
||||
isSaving.value = true;
|
||||
try {
|
||||
await unbindAdminWecomUser(userId);
|
||||
await refreshWecomData();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
msg.error((e as Error).message || t('admin.wecom.msg.unbindFailed'));
|
||||
} finally {
|
||||
isSaving.value = false;
|
||||
}
|
||||
});
|
||||
try {
|
||||
await ElMessageBox.confirm(t('admin.wecom.confirmUnbind'), t('common.deleteDialog.defaultTitle'), {
|
||||
type: 'warning',
|
||||
confirmButtonText: t('common.deleteDialog.confirm'),
|
||||
cancelButtonText: t('common.deleteDialog.cancel'),
|
||||
});
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
isSaving.value = true;
|
||||
try {
|
||||
await unbindAdminWecomUser(userId);
|
||||
await refreshWecomData();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
msg.error((e as Error).message || t('admin.wecom.msg.unbindFailed'));
|
||||
} finally {
|
||||
isSaving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const exportWecomAudits = (): void => {
|
||||
@@ -522,8 +511,6 @@ export function useWecomAdmin() {
|
||||
wecomNotifyMetrics,
|
||||
wecomSystemSettings,
|
||||
wecomIntegrationManifest,
|
||||
showDeleteConfirmDialog,
|
||||
deleteConfirmMessage,
|
||||
loadAll,
|
||||
refreshWecomData,
|
||||
selectWecomBindUser,
|
||||
@@ -539,6 +526,5 @@ export function useWecomAdmin() {
|
||||
bindWecomUser,
|
||||
unbindWecomUserByAdmin,
|
||||
exportWecomAudits,
|
||||
confirmDelete,
|
||||
};
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
/**
|
||||
* features/admin/modules/wecom/composables/useWecomSync.ts
|
||||
* OA userInfo_view → 本地 wecom_userid 同步:预览 dry-run 与确认写入。
|
||||
* 用途:OA userInfo_view 工号到本地 wecom_userid 的预览与确认写入。
|
||||
* 依赖:admin.api 的 syncAdminWecomUserids、useMessage、element-plus 确认框。
|
||||
* 逻辑:WecomSyncPanel 调用。先 dry-run,确认后再 apply。确认框取消则不写库。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ElMessageBox } from 'element-plus';
|
||||
import { syncAdminWecomUserids } from '@/features/admin/api/admin.api';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import type { WecomSyncSummary } from '@/features/admin/types/wecom.types';
|
||||
@@ -17,7 +20,6 @@ export function useWecomSync(options?: { onApplied?: () => void | Promise<void>
|
||||
|
||||
const isSyncing = ref(false);
|
||||
const previewSummary = ref<WecomSyncSummary | null>(null);
|
||||
const showApplyConfirm = ref(false);
|
||||
const previewAttempted = ref(false);
|
||||
const previewFailed = ref(false);
|
||||
|
||||
@@ -79,9 +81,29 @@ export function useWecomSync(options?: { onApplied?: () => void | Promise<void>
|
||||
};
|
||||
|
||||
/**
|
||||
* 打开确认写入对话框;不可写入时弹出对应提示。
|
||||
* 确认后把预览结果写入数据库。
|
||||
* 核心逻辑:调用 syncAdminWecomUserids({ apply: true }),成功后刷新预览摘要并通知页面。
|
||||
*/
|
||||
const requestApplySync = (): void => {
|
||||
const confirmApplySync = async (): Promise<void> => {
|
||||
isSyncing.value = true;
|
||||
try {
|
||||
const summary = await syncAdminWecomUserids({ apply: true });
|
||||
previewSummary.value = summary;
|
||||
msg.success(t('admin.wecom.sync.applyDone', { count: summary.updated || 0 }));
|
||||
await options?.onApplied?.();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
msg.error((e as Error).message || t('admin.wecom.sync.applyFailed'));
|
||||
} finally {
|
||||
isSyncing.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 请求确认写入。不可写入时只提示原因;可以写入时先弹确认框,取消则不写库。
|
||||
* 核心逻辑:拦截条件与原来一致。确认文案仍用同步模块自己的标题和按钮,取消按钮用通用文案。
|
||||
*/
|
||||
const requestApplySync = async (): Promise<void> => {
|
||||
if (isSyncing.value) return;
|
||||
if (previewFailed.value || (previewAttempted.value && !previewSummary.value)) {
|
||||
msg.warning(t('admin.wecom.sync.previewFirstAfterFail'));
|
||||
@@ -99,36 +121,28 @@ export function useWecomSync(options?: { onApplied?: () => void | Promise<void>
|
||||
msg.info(t('admin.wecom.sync.nothingToUpdate'));
|
||||
return;
|
||||
}
|
||||
showApplyConfirm.value = true;
|
||||
};
|
||||
|
||||
/**
|
||||
* 确认后将预览结果写入数据库。
|
||||
*/
|
||||
const confirmApplySync = async (): Promise<void> => {
|
||||
isSyncing.value = true;
|
||||
try {
|
||||
const summary = await syncAdminWecomUserids({ apply: true });
|
||||
previewSummary.value = summary;
|
||||
showApplyConfirm.value = false;
|
||||
msg.success(t('admin.wecom.sync.applyDone', { count: summary.updated || 0 }));
|
||||
await options?.onApplied?.();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
msg.error((e as Error).message || t('admin.wecom.sync.applyFailed'));
|
||||
} finally {
|
||||
isSyncing.value = false;
|
||||
await ElMessageBox.confirm(
|
||||
t('admin.wecom.sync.applyConfirm', { count: previewSummary.value.would_update || 0 }),
|
||||
t('admin.wecom.sync.applyConfirmTitle'),
|
||||
{
|
||||
type: 'warning',
|
||||
confirmButtonText: t('admin.wecom.sync.applyConfirmButton'),
|
||||
cancelButtonText: t('common.deleteDialog.cancel'),
|
||||
},
|
||||
);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
await confirmApplySync();
|
||||
};
|
||||
|
||||
return {
|
||||
isSyncing,
|
||||
previewSummary,
|
||||
showApplyConfirm,
|
||||
canApplySync,
|
||||
applyBlockHint,
|
||||
previewSync,
|
||||
requestApplySync,
|
||||
confirmApplySync,
|
||||
};
|
||||
}
|
||||
@@ -1,18 +1,37 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/admin/modules/wecom/pages/WecomAuditsPage.vue
|
||||
* 企微与密码登录审计列表。
|
||||
* 依赖:WECOM_ADMIN_KEY、PaginationBar、formatLocalDateTime。
|
||||
* 逻辑:表格渲染当前页切片;分页条对已拉取的最近 200 条做前端翻页。
|
||||
* 用途:企微与密码登录审计列表。
|
||||
* 依赖:AdminListPage、AdminListTabs、WECOM_ADMIN_KEY、element-plus、formatLocalDateTime。
|
||||
* 逻辑:路由 AdminWecomAudits。页签仍跳原来的三个子路由。表格渲染当前页切片;分页对已拉取的最近 200 条做前端翻页。
|
||||
*/
|
||||
import { inject } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Download } from 'lucide-vue-next';
|
||||
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
||||
import { Download, Refresh } from '@element-plus/icons-vue';
|
||||
import {
|
||||
ElButton,
|
||||
ElConfigProvider,
|
||||
ElOption,
|
||||
ElPagination,
|
||||
ElSelect,
|
||||
ElSpace,
|
||||
ElTable,
|
||||
ElTableColumn,
|
||||
ElTag,
|
||||
ElText,
|
||||
} from 'element-plus';
|
||||
import 'element-plus/dist/index.css';
|
||||
import 'element-plus/theme-chalk/dark/css-vars.css';
|
||||
import '@/features/admin/styles/element-trial.css';
|
||||
import AdminListPage from '@/features/admin/components/AdminListPage.vue';
|
||||
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
|
||||
import { formatLocalDateTime } from '@/shared/utils/dateTime';
|
||||
import type { WecomLoginAuditRow } from '@/features/admin/types/wecom.types';
|
||||
import WecomSubNav from '../components/WecomSubNav.vue';
|
||||
import { WECOM_ADMIN_KEY } from '../wecom.context';
|
||||
|
||||
const { t } = useI18n();
|
||||
const { elementLocale } = useElementProvider();
|
||||
const {
|
||||
wecomAuditSourceFilter,
|
||||
wecomAuditStatusFilter,
|
||||
@@ -20,83 +39,134 @@ const {
|
||||
wecomAuditsPageSize,
|
||||
wecomAuditsPageSizeOptions,
|
||||
wecomAuditsTotal,
|
||||
filteredWecomLoginAudits,
|
||||
pagedWecomLoginAudits,
|
||||
exportWecomAudits,
|
||||
refreshWecomData,
|
||||
getWecomAuditReasonText,
|
||||
getWecomAuditMetaText,
|
||||
} = inject(WECOM_ADMIN_KEY)!;
|
||||
|
||||
/**
|
||||
* 登录来源筛选。空值表示全部,写回 composable 的 all。
|
||||
* 核心逻辑:ElSelect 不用空字符串当选项值,业务判断仍看 all。
|
||||
* @param value - 选中的来源;清空为 undefined 或空串
|
||||
*/
|
||||
function onAuditSourceChange(value: 'wecom' | 'password' | '' | undefined): void {
|
||||
wecomAuditSourceFilter.value = value ? value : 'all';
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录结果筛选。空值表示全部,写回 composable 的 all。
|
||||
* @param value - 选中的状态;清空为 undefined 或空串
|
||||
*/
|
||||
function onAuditStatusChange(value: 'success' | 'failed' | '' | undefined): void {
|
||||
wecomAuditStatusFilter.value = value ? value : 'all';
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="admin-table-section">
|
||||
<div class="admin-table-header admin-table-header--stacked px-5 py-4">
|
||||
<h3 class="font-semibold text-primary">{{ t('admin.wecom.auditTitle') }}</h3>
|
||||
<div class="flex w-full md:w-auto flex-wrap md:flex-nowrap items-center justify-start md:justify-end gap-2">
|
||||
<select v-model="wecomAuditSourceFilter" class="admin-table-filter-input h-11 min-w-[112px] shrink-0">
|
||||
<option value="all">{{ t('admin.wecom.filters.allSources') }}</option>
|
||||
<option value="wecom">{{ t('admin.wecom.sources.wecom') }}</option>
|
||||
<option value="password">{{ t('admin.wecom.sources.password') }}</option>
|
||||
</select>
|
||||
<select v-model="wecomAuditStatusFilter" class="admin-table-filter-input h-11 min-w-[112px] shrink-0">
|
||||
<option value="all">{{ t('admin.wecom.filters.allStatus') }}</option>
|
||||
<option value="success">{{ t('admin.wecom.auditStatus.success') }}</option>
|
||||
<option value="failed">{{ t('admin.wecom.auditStatus.failed') }}</option>
|
||||
</select>
|
||||
<button type="button" class="btn-secondary h-11 shrink-0 text-sm" @click="exportWecomAudits()">
|
||||
<Download class="w-4 h-4" />
|
||||
{{ t('admin.wecom.exportAudit') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="admin-table-wrap">
|
||||
<table class="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.auditHeaders.time') }}</th>
|
||||
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.auditHeaders.source') }}</th>
|
||||
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.auditHeaders.user') }}</th>
|
||||
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.auditHeaders.status') }}</th>
|
||||
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.auditHeaders.reason') }}</th>
|
||||
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.auditHeaders.ip') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="filteredWecomLoginAudits.length === 0">
|
||||
<td colspan="6" class="px-4 admin-table-empty">{{ t('admin.wecom.noAuditData') }}</td>
|
||||
</tr>
|
||||
<tr v-for="row in pagedWecomLoginAudits" :key="row.id">
|
||||
<td class="px-4 py-3 text-xs text-muted whitespace-nowrap" :title="row.created_at || '-'">{{ formatLocalDateTime(row.created_at) }}</td>
|
||||
<td class="px-4 py-3 text-xs text-secondary">{{ t('admin.wecom.sources.' + row.source) }}</td>
|
||||
<td class="px-4 py-3 text-xs text-secondary">{{ row.username || '-' }}</td>
|
||||
<td class="px-4 py-3">
|
||||
<span
|
||||
class="inline-flex px-2 py-0.5 rounded-full text-[11px] font-medium"
|
||||
:class="row.status === 'success' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'"
|
||||
>
|
||||
{{ t('admin.wecom.auditStatus.' + row.status) }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-4 py-3 text-xs text-muted max-w-[360px] align-top">
|
||||
<div class="max-w-[360px] whitespace-normal break-words">
|
||||
<div class="text-xs text-secondary leading-5">{{ getWecomAuditReasonText(row) }}</div>
|
||||
<div v-if="getWecomAuditMetaText(row)" class="mt-1 text-[11px] text-muted leading-5" :title="getWecomAuditMetaText(row)">
|
||||
{{ getWecomAuditMetaText(row) }}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-4 py-3 text-xs text-muted font-mono">{{ row.ip || '-' }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="px-4 pb-4 pt-2">
|
||||
<PaginationBar
|
||||
v-model:page="wecomAuditsPage"
|
||||
v-model:page-size="wecomAuditsPageSize"
|
||||
:total="wecomAuditsTotal"
|
||||
:page-size-options="[...wecomAuditsPageSizeOptions]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<ElConfigProvider :locale="elementLocale">
|
||||
<AdminListPage>
|
||||
<template #title>
|
||||
<h2 class="section-title">{{ t('admin.wecom.title') }}</h2>
|
||||
<p class="section-desc mt-1">{{ t('admin.wecom.subtitle') }}</p>
|
||||
</template>
|
||||
<template #actions>
|
||||
<ElSpace>
|
||||
<ElButton :icon="Refresh" @click="refreshWecomData()">{{ t('admin.wecom.refresh') }}</ElButton>
|
||||
<ElButton :icon="Download" @click="exportWecomAudits()">{{ t('admin.wecom.exportAudit') }}</ElButton>
|
||||
</ElSpace>
|
||||
</template>
|
||||
<template #tabs>
|
||||
<WecomSubNav />
|
||||
</template>
|
||||
<template #filters>
|
||||
<ElSelect
|
||||
class="wecom-filter-select"
|
||||
:model-value="wecomAuditSourceFilter === 'all' ? undefined : wecomAuditSourceFilter"
|
||||
clearable
|
||||
:placeholder="t('admin.wecom.filters.allSources')"
|
||||
@update:model-value="onAuditSourceChange"
|
||||
>
|
||||
<ElOption :label="t('admin.wecom.sources.wecom')" value="wecom" />
|
||||
<ElOption :label="t('admin.wecom.sources.password')" value="password" />
|
||||
</ElSelect>
|
||||
<ElSelect
|
||||
class="wecom-filter-select"
|
||||
:model-value="wecomAuditStatusFilter === 'all' ? undefined : wecomAuditStatusFilter"
|
||||
clearable
|
||||
:placeholder="t('admin.wecom.filters.allStatus')"
|
||||
@update:model-value="onAuditStatusChange"
|
||||
>
|
||||
<ElOption :label="t('admin.wecom.auditStatus.success')" value="success" />
|
||||
<ElOption :label="t('admin.wecom.auditStatus.failed')" value="failed" />
|
||||
</ElSelect>
|
||||
</template>
|
||||
|
||||
<ElTable
|
||||
class="hx-admin-table"
|
||||
:data="pagedWecomLoginAudits"
|
||||
row-key="id"
|
||||
:empty-text="t('admin.wecom.noAuditData')"
|
||||
>
|
||||
<ElTableColumn :label="t('admin.wecom.auditHeaders.time')" min-width="180">
|
||||
<template #default="{ row }">
|
||||
{{ formatLocalDateTime((row as WecomLoginAuditRow).created_at) }}
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('admin.wecom.auditHeaders.source')" min-width="120">
|
||||
<template #default="{ row }">
|
||||
{{ t('admin.wecom.sources.' + (row as WecomLoginAuditRow).source) }}
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('admin.wecom.auditHeaders.user')" min-width="140">
|
||||
<template #default="{ row }">{{ (row as WecomLoginAuditRow).username || '-' }}</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('admin.wecom.auditHeaders.status')" min-width="110">
|
||||
<template #default="{ row }">
|
||||
<ElTag
|
||||
effect="light"
|
||||
:type="(row as WecomLoginAuditRow).status === 'success' ? 'success' : 'danger'"
|
||||
>
|
||||
{{ t('admin.wecom.auditStatus.' + (row as WecomLoginAuditRow).status) }}
|
||||
</ElTag>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('admin.wecom.auditHeaders.reason')" min-width="240">
|
||||
<template #default="{ row }">
|
||||
<div>{{ getWecomAuditReasonText(row as WecomLoginAuditRow) }}</div>
|
||||
<ElText v-if="getWecomAuditMetaText(row as WecomLoginAuditRow)" type="info">
|
||||
{{ getWecomAuditMetaText(row as WecomLoginAuditRow) }}
|
||||
</ElText>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('admin.wecom.auditHeaders.ip')" min-width="140">
|
||||
<template #default="{ row }">
|
||||
<span class="wecom-audit-mono">{{ (row as WecomLoginAuditRow).ip || '-' }}</span>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
</ElTable>
|
||||
|
||||
<template #pagination>
|
||||
<ElPagination
|
||||
v-model:current-page="wecomAuditsPage"
|
||||
v-model:page-size="wecomAuditsPageSize"
|
||||
:total="wecomAuditsTotal"
|
||||
:page-sizes="[...wecomAuditsPageSizeOptions]"
|
||||
layout="total, sizes, prev, pager, next"
|
||||
background
|
||||
/>
|
||||
</template>
|
||||
</AdminListPage>
|
||||
</ElConfigProvider>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
:deep(.wecom-filter-select) {
|
||||
width: 11rem;
|
||||
}
|
||||
|
||||
.wecom-audit-mono {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||
}
|
||||
</style>
|
||||
@@ -1,291 +1,273 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/admin/modules/wecom/pages/WecomBindingsPage.vue
|
||||
* 企微 OA 同步、快速绑定与绑定列表(搜索 + 服务端分页)。
|
||||
* 依赖:WECOM_ADMIN_KEY、WecomSyncPanel、PaginationBar。
|
||||
* 用途:企微绑定概览、OA 同步、快速绑定和绑定列表。
|
||||
* 依赖:AdminListPage、AdminListTabs、WecomOverviewCards、WecomSyncPanel、WECOM_ADMIN_KEY、element-plus。
|
||||
* 逻辑:路由 AdminWecomBindings。概览和同步在页签卡片里;绑定列表单独一张 AdminListPage,搜索和分页只服务这张表。
|
||||
*/
|
||||
import { inject } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Link2, Search, Unlink2 } from 'lucide-vue-next';
|
||||
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
||||
import { Link, Refresh } from '@element-plus/icons-vue';
|
||||
import {
|
||||
ElButton,
|
||||
ElCheckbox,
|
||||
ElConfigProvider,
|
||||
ElForm,
|
||||
ElFormItem,
|
||||
ElInput,
|
||||
ElOption,
|
||||
ElPagination,
|
||||
ElSelect,
|
||||
ElTable,
|
||||
ElTableColumn,
|
||||
ElTag,
|
||||
ElText,
|
||||
} from 'element-plus';
|
||||
import 'element-plus/dist/index.css';
|
||||
import 'element-plus/theme-chalk/dark/css-vars.css';
|
||||
import '@/features/admin/styles/element-trial.css';
|
||||
import AdminListPage from '@/features/admin/components/AdminListPage.vue';
|
||||
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
|
||||
import type { WecomBindingRow } from '@/features/admin/types/wecom.types';
|
||||
import WecomOverviewCards from '../components/WecomOverviewCards.vue';
|
||||
import WecomSyncPanel from '../components/WecomSyncPanel.vue';
|
||||
import WecomSubNav from '../components/WecomSubNav.vue';
|
||||
import { WECOM_ADMIN_KEY } from '../wecom.context';
|
||||
|
||||
const { t } = useI18n();
|
||||
const { elementLocale } = useElementProvider();
|
||||
const {
|
||||
|
||||
wecomBindUserQuery,
|
||||
|
||||
wecomBindUserDropdownOpen,
|
||||
|
||||
wecomBindUserOptions,
|
||||
|
||||
wecomBindUserQuery,
|
||||
wecomBindForm,
|
||||
|
||||
isSaving,
|
||||
|
||||
wecomBoundOnly,
|
||||
|
||||
wecomBindings,
|
||||
|
||||
wecomBindingsKeyword,
|
||||
|
||||
wecomBindingsPage,
|
||||
|
||||
wecomBindingsPageSize,
|
||||
|
||||
wecomBindingsTotal,
|
||||
|
||||
wecomBindingsPages,
|
||||
|
||||
wecomBindingsPageSizeOptions,
|
||||
|
||||
selectWecomBindUser,
|
||||
|
||||
scheduleCloseWecomBindUserDropdown,
|
||||
|
||||
bindWecomUser,
|
||||
|
||||
unbindWecomUserByAdmin,
|
||||
|
||||
refreshWecomData,
|
||||
|
||||
} = inject(WECOM_ADMIN_KEY)!;
|
||||
|
||||
/**
|
||||
* 同步写入成功后刷新绑定列表和配置。
|
||||
* 核心逻辑:面板内部已经刷新过一次,这里再拉一次,保持原来的 applied 回调。
|
||||
*/
|
||||
const onSyncApplied = async (): Promise<void> => {
|
||||
await refreshWecomData();
|
||||
};
|
||||
|
||||
/**
|
||||
* 选择要绑定的本地用户。清空时把 user_id 写回空串。
|
||||
* 核心逻辑:下拉自己按姓名过滤,不再占用原来的搜索词,避免选项被收成一条。
|
||||
* @param value - 用户 id;清空为 undefined 或空串
|
||||
*/
|
||||
function onBindUserChange(value: number | string | undefined): void {
|
||||
if (value == null || value === '') {
|
||||
wecomBindForm.value.user_id = '';
|
||||
wecomBindUserQuery.value = '';
|
||||
return;
|
||||
}
|
||||
wecomBindForm.value.user_id = Number(value);
|
||||
wecomBindUserQuery.value = '';
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="space-y-6">
|
||||
<WecomOverviewCards />
|
||||
<WecomSyncPanel @applied="onSyncApplied" />
|
||||
|
||||
<p class="text-sm text-muted">{{ t('admin.wecom.bindingsHint') }}</p>
|
||||
|
||||
|
||||
|
||||
<div class="card shadow-sm p-5 space-y-4">
|
||||
|
||||
<h3 class="font-semibold text-primary">{{ t('admin.wecom.quickBind') }}</h3>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-4 gap-3">
|
||||
|
||||
<div class="relative md:col-span-1">
|
||||
|
||||
<input
|
||||
|
||||
v-model="wecomBindUserQuery"
|
||||
|
||||
type="text"
|
||||
|
||||
class="input-field"
|
||||
|
||||
:placeholder="t('admin.wecom.fields.userSelect')"
|
||||
|
||||
@focus="wecomBindUserDropdownOpen = true"
|
||||
|
||||
@input="wecomBindUserDropdownOpen = true"
|
||||
|
||||
@blur="scheduleCloseWecomBindUserDropdown()"
|
||||
|
||||
/>
|
||||
|
||||
<div v-if="wecomBindUserDropdownOpen" class="admin-dropdown w-72">
|
||||
|
||||
<button
|
||||
|
||||
v-for="u in wecomBindUserOptions"
|
||||
|
||||
:key="u.id"
|
||||
|
||||
type="button"
|
||||
|
||||
class="flex w-full items-center justify-between gap-3 px-3 py-2 text-left hover:bg-blue-50"
|
||||
|
||||
@mousedown.prevent="selectWecomBindUser(u.id, u.label)"
|
||||
|
||||
>
|
||||
|
||||
<span class="text-sm text-primary">{{ u.label }}</span>
|
||||
|
||||
<span class="text-xs text-muted">{{ u.employeeId || '' }}</span>
|
||||
|
||||
</button>
|
||||
|
||||
<div v-if="wecomBindUserOptions.length === 0" class="px-3 py-2 text-sm text-muted">
|
||||
|
||||
{{ t('admin.wecom.noData') }}
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<ElConfigProvider :locale="elementLocale">
|
||||
<div class="wecom-bindings">
|
||||
<AdminListPage>
|
||||
<template #title>
|
||||
<h2 class="section-title">{{ t('admin.wecom.title') }}</h2>
|
||||
<p class="section-desc mt-1">{{ t('admin.wecom.subtitle') }}</p>
|
||||
</template>
|
||||
<template #actions>
|
||||
<ElButton :icon="Refresh" @click="refreshWecomData()">{{ t('admin.wecom.refresh') }}</ElButton>
|
||||
</template>
|
||||
<template #tabs>
|
||||
<WecomSubNav />
|
||||
</template>
|
||||
|
||||
<div class="wecom-bindings__block">
|
||||
<WecomOverviewCards />
|
||||
</div>
|
||||
|
||||
<input v-model="wecomBindForm.wecom_userid" :placeholder="t('admin.wecom.fields.wecomUserId')" class="input-field md:col-span-2" />
|
||||
|
||||
<input v-model="wecomBindForm.wecom_unionid" :placeholder="t('admin.wecom.fields.wecomUnionId')" class="input-field" />
|
||||
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end">
|
||||
|
||||
<button type="button" :disabled="isSaving" class="btn-primary px-5 py-2 disabled:opacity-60" @click="bindWecomUser()">
|
||||
|
||||
<Link2 class="w-4 h-4" /> {{ t('admin.wecom.bind') }}
|
||||
|
||||
</button>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<div class="admin-table-section space-y-0">
|
||||
|
||||
<div class="admin-table-header px-5 py-4 flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
|
||||
|
||||
<h3 class="font-semibold text-primary">{{ t('admin.wecom.bindingList') }}</h3>
|
||||
|
||||
<div class="flex flex-col gap-3 sm:flex-row sm:items-center">
|
||||
|
||||
<div class="relative min-w-[240px]">
|
||||
|
||||
<Search class="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted" />
|
||||
|
||||
<input
|
||||
|
||||
v-model="wecomBindingsKeyword"
|
||||
|
||||
type="search"
|
||||
|
||||
class="input-field pl-9"
|
||||
|
||||
:placeholder="t('admin.wecom.searchBindings')"
|
||||
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
<label class="inline-flex items-center gap-2 text-sm text-secondary whitespace-nowrap">
|
||||
|
||||
<input v-model="wecomBoundOnly" type="checkbox" class="w-4 h-4 rounded text-brand-600 border-default" />
|
||||
|
||||
{{ t('admin.wecom.boundOnly') }}
|
||||
|
||||
</label>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="admin-table-wrap">
|
||||
|
||||
<table class="admin-table">
|
||||
|
||||
<thead>
|
||||
|
||||
<tr>
|
||||
|
||||
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.headers.user') }}</th>
|
||||
|
||||
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.headers.employeeId') }}</th>
|
||||
|
||||
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.headers.roleStatus') }}</th>
|
||||
|
||||
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.headers.wecomUserId') }}</th>
|
||||
|
||||
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.headers.unionId') }}</th>
|
||||
|
||||
<th class="px-4 py-3 text-xs text-right">{{ t('admin.wecom.headers.actions') }}</th>
|
||||
|
||||
</tr>
|
||||
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
|
||||
<tr v-if="wecomBindings.length === 0">
|
||||
|
||||
<td colspan="6" class="px-4 admin-table-empty">{{ t('admin.wecom.noData') }}</td>
|
||||
|
||||
</tr>
|
||||
|
||||
<tr v-for="u in wecomBindings" :key="u.id">
|
||||
|
||||
<td class="px-4 py-3">
|
||||
|
||||
<div class="text-sm font-medium text-primary">{{ u.username }} <span class="text-muted">(#{{ u.id }})</span></div>
|
||||
|
||||
<div class="text-xs text-muted">{{ u.real_name || '-' }} · {{ u.email }}</div>
|
||||
|
||||
</td>
|
||||
|
||||
<td class="px-4 py-3 text-sm text-secondary font-mono">{{ u.employee_id || '-' }}</td>
|
||||
|
||||
<td class="px-4 py-3 text-sm text-secondary">{{ t('admin.role.' + u.role) }} / {{ t('admin.status.' + u.status) }}</td>
|
||||
|
||||
<td class="px-4 py-3 text-sm text-secondary font-mono">{{ u.wecom_userid || '-' }}</td>
|
||||
|
||||
<td class="px-4 py-3 text-sm text-secondary font-mono">{{ u.wecom_unionid || '-' }}</td>
|
||||
|
||||
<td class="px-4 py-3 text-right">
|
||||
|
||||
<button
|
||||
|
||||
v-if="u.wecom_userid"
|
||||
|
||||
type="button"
|
||||
|
||||
class="inline-flex items-center gap-1 px-3 py-1.5 text-xs text-red-600 bg-red-50 rounded-lg hover:bg-red-100"
|
||||
|
||||
@click="unbindWecomUserByAdmin(u.id)"
|
||||
|
||||
<WecomSyncPanel @applied="onSyncApplied" />
|
||||
<div class="wecom-bindings__block">
|
||||
<ElText type="info">{{ t('admin.wecom.bindingsHint') }}</ElText>
|
||||
<h3 class="wecom-bindings__heading">{{ t('admin.wecom.quickBind') }}</h3>
|
||||
<ElForm label-position="top" :model="wecomBindForm" @submit.prevent="bindWecomUser()">
|
||||
<div class="wecom-bindings__form">
|
||||
<ElFormItem :label="t('admin.wecom.fields.userSelect')">
|
||||
<ElSelect
|
||||
:model-value="wecomBindForm.user_id === '' ? undefined : wecomBindForm.user_id"
|
||||
filterable
|
||||
clearable
|
||||
:placeholder="t('admin.wecom.fields.userSelect')"
|
||||
@update:model-value="onBindUserChange"
|
||||
>
|
||||
<ElOption
|
||||
v-for="user in wecomBindUserOptions"
|
||||
:key="user.id"
|
||||
:label="user.label"
|
||||
:value="user.id"
|
||||
/>
|
||||
</ElSelect>
|
||||
</ElFormItem>
|
||||
<ElFormItem class="wecom-bindings__wide" :label="t('admin.wecom.fields.wecomUserId')">
|
||||
<ElInput v-model="wecomBindForm.wecom_userid" :placeholder="t('admin.wecom.fields.wecomUserId')" />
|
||||
</ElFormItem>
|
||||
<ElFormItem :label="t('admin.wecom.fields.wecomUnionId')">
|
||||
<ElInput v-model="wecomBindForm.wecom_unionid" :placeholder="t('admin.wecom.fields.wecomUnionId')" />
|
||||
</ElFormItem>
|
||||
</div>
|
||||
<div class="wecom-bindings__submit">
|
||||
<ElButton type="primary" :icon="Link" :loading="isSaving" @click="bindWecomUser()">
|
||||
{{ t('admin.wecom.bind') }}
|
||||
</ElButton>
|
||||
</div>
|
||||
</ElForm>
|
||||
</div>
|
||||
</AdminListPage>
|
||||
|
||||
<Unlink2 class="w-3.5 h-3.5" />
|
||||
<AdminListPage>
|
||||
<template #title>
|
||||
<h2 class="section-title">{{ t('admin.wecom.bindingList') }}</h2>
|
||||
</template>
|
||||
<template #filters>
|
||||
<ElInput
|
||||
v-model="wecomBindingsKeyword"
|
||||
class="wecom-filter-search"
|
||||
clearable
|
||||
:placeholder="t('admin.wecom.searchBindings')"
|
||||
/>
|
||||
<ElCheckbox v-model="wecomBoundOnly">{{ t('admin.wecom.boundOnly') }}</ElCheckbox>
|
||||
</template>
|
||||
|
||||
{{ t('admin.wecom.unbind') }}
|
||||
|
||||
</button>
|
||||
|
||||
</td>
|
||||
|
||||
</tr>
|
||||
|
||||
</tbody>
|
||||
|
||||
</table>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="px-4 pb-4 pt-2">
|
||||
|
||||
<PaginationBar
|
||||
|
||||
v-model:page="wecomBindingsPage"
|
||||
|
||||
v-model:page-size="wecomBindingsPageSize"
|
||||
|
||||
:total="wecomBindingsTotal"
|
||||
|
||||
:pages="wecomBindingsPages"
|
||||
|
||||
:page-size-options="[...wecomBindingsPageSizeOptions]"
|
||||
|
||||
:visible="wecomBindingsTotal > 0 || !!wecomBindingsKeyword.trim()"
|
||||
|
||||
/>
|
||||
|
||||
</div>
|
||||
<ElTable
|
||||
class="hx-admin-table"
|
||||
:data="wecomBindings"
|
||||
row-key="id"
|
||||
:empty-text="t('admin.wecom.noData')"
|
||||
>
|
||||
<ElTableColumn :label="t('admin.wecom.headers.user')" min-width="220">
|
||||
<template #default="{ row }">
|
||||
<div>
|
||||
{{ (row as WecomBindingRow).username }}
|
||||
<ElText type="info">(#{{ (row as WecomBindingRow).id }})</ElText>
|
||||
</div>
|
||||
<ElText type="info">
|
||||
{{ (row as WecomBindingRow).real_name || '-' }} · {{ (row as WecomBindingRow).email }}
|
||||
</ElText>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('admin.wecom.headers.employeeId')" min-width="140">
|
||||
<template #default="{ row }">
|
||||
<span class="wecom-bindings__mono">{{ (row as WecomBindingRow).employee_id || '-' }}</span>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('admin.wecom.headers.roleStatus')" min-width="180">
|
||||
<template #default="{ row }">
|
||||
<span>{{ t('admin.role.' + (row as WecomBindingRow).role) }}</span>
|
||||
<ElTag
|
||||
class="wecom-bindings__status"
|
||||
effect="light"
|
||||
:type="(row as WecomBindingRow).status === 'active' ? 'success' : 'info'"
|
||||
>
|
||||
{{ t('admin.status.' + (row as WecomBindingRow).status) }}
|
||||
</ElTag>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('admin.wecom.headers.wecomUserId')" min-width="160">
|
||||
<template #default="{ row }">
|
||||
<span class="wecom-bindings__mono">{{ (row as WecomBindingRow).wecom_userid || '-' }}</span>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('admin.wecom.headers.unionId')" min-width="160">
|
||||
<template #default="{ row }">
|
||||
<span class="wecom-bindings__mono">{{ (row as WecomBindingRow).wecom_unionid || '-' }}</span>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('admin.wecom.headers.actions')" width="120" align="right">
|
||||
<template #default="{ row }">
|
||||
<ElButton
|
||||
v-if="(row as WecomBindingRow).wecom_userid"
|
||||
link
|
||||
type="danger"
|
||||
@click="unbindWecomUserByAdmin((row as WecomBindingRow).id)"
|
||||
>
|
||||
{{ t('admin.wecom.unbind') }}
|
||||
</ElButton>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
</ElTable>
|
||||
|
||||
<template #pagination v-if="wecomBindingsTotal > 0 || !!wecomBindingsKeyword.trim()">
|
||||
<ElPagination
|
||||
v-model:current-page="wecomBindingsPage"
|
||||
v-model:page-size="wecomBindingsPageSize"
|
||||
:total="wecomBindingsTotal"
|
||||
:page-sizes="[...wecomBindingsPageSizeOptions]"
|
||||
layout="total, sizes, prev, pager, next"
|
||||
background
|
||||
/>
|
||||
</template>
|
||||
</AdminListPage>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</ElConfigProvider>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.wecom-bindings {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.wecom-bindings__block {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 16px 32px 24px;
|
||||
border-top: 1px solid var(--el-border-color-lighter);
|
||||
}
|
||||
|
||||
.wecom-bindings__heading {
|
||||
margin: 0;
|
||||
color: var(--el-text-color-primary);
|
||||
font-size: var(--el-font-size-large);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.wecom-bindings__form {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
column-gap: 16px;
|
||||
}
|
||||
|
||||
.wecom-bindings__submit {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.wecom-bindings__mono {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||
}
|
||||
|
||||
.wecom-bindings__status {
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
:deep(.wecom-filter-search) {
|
||||
width: 16rem;
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
.wecom-bindings__form {
|
||||
grid-template-columns: 1fr 2fr 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,16 +1,42 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/admin/modules/wecom/pages/WecomSettingsPage.vue
|
||||
* 企微系统配置、通知与集成复制。
|
||||
* 依赖:WECOM_ADMIN_KEY、lucide CircleHelp。
|
||||
* 逻辑:绑定概览卡片只在绑定管理页展示,本页仅编辑系统/通知配置。
|
||||
* 用途:企微系统配置、通知指标和集成复制。
|
||||
* 依赖:AdminListPage、AdminListTabs、WECOM_ADMIN_KEY、element-plus。
|
||||
* 逻辑:路由 AdminWecomSettings。绑定概览不在本页。表单仍写回同一个 settings 对象,保存函数不变。
|
||||
*/
|
||||
import { inject } from 'vue';
|
||||
import { computed, inject } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { CircleHelp } from 'lucide-vue-next';
|
||||
import { QuestionFilled, Refresh } from '@element-plus/icons-vue';
|
||||
import {
|
||||
ElAlert,
|
||||
ElButton,
|
||||
ElCard,
|
||||
ElCollapse,
|
||||
ElCollapseItem,
|
||||
ElConfigProvider,
|
||||
ElForm,
|
||||
ElFormItem,
|
||||
ElIcon,
|
||||
ElInput,
|
||||
ElOption,
|
||||
ElSelect,
|
||||
ElStatistic,
|
||||
ElSwitch,
|
||||
ElText,
|
||||
ElTooltip,
|
||||
} from 'element-plus';
|
||||
import 'element-plus/dist/index.css';
|
||||
import 'element-plus/theme-chalk/dark/css-vars.css';
|
||||
import '@/features/admin/styles/element-trial.css';
|
||||
import AdminListPage from '@/features/admin/components/AdminListPage.vue';
|
||||
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
|
||||
import type { WecomIntegrationManifest } from '@/features/admin/types/wecom.types';
|
||||
import WecomSubNav from '../components/WecomSubNav.vue';
|
||||
import { WECOM_ADMIN_KEY } from '../wecom.context';
|
||||
|
||||
const { t } = useI18n();
|
||||
const { elementLocale } = useElementProvider();
|
||||
const {
|
||||
wecomSystemSettings,
|
||||
isSaving,
|
||||
@@ -23,238 +49,426 @@ const {
|
||||
generateWecomEncodingAesKey,
|
||||
saveWecomSystemSettings,
|
||||
saveWecomNotifySettings,
|
||||
refreshWecomData,
|
||||
copyText,
|
||||
} = inject(WECOM_ADMIN_KEY)!;
|
||||
|
||||
const copyFieldDefs: Array<{ key: keyof WecomIntegrationManifest; labelKey: string }> = [
|
||||
{ key: 'public_base_url', labelKey: 'admin.wecom.copyFields.publicBaseUrl' },
|
||||
{ key: 'callback_url', labelKey: 'admin.wecom.copyFields.callbackUrl' },
|
||||
{ key: 'callback_token', labelKey: 'admin.wecom.copyFields.callbackToken' },
|
||||
{ key: 'encoding_aes_key', labelKey: 'admin.wecom.copyFields.encodingAesKey' },
|
||||
{ key: 'oauth_redirect_uri', labelKey: 'admin.wecom.copyFields.oauthRedirectUri' },
|
||||
{ key: 'homepage_url', labelKey: 'admin.wecom.copyFields.homepageUrl' },
|
||||
{ key: 'trusted_domain', labelKey: 'admin.wecom.copyFields.trustedDomain' },
|
||||
{ key: 'authorize_api', labelKey: 'admin.wecom.copyFields.authorizeApi' },
|
||||
{ key: 'login_api', labelKey: 'admin.wecom.copyFields.loginApi' },
|
||||
];
|
||||
|
||||
const copyItems = computed(() => {
|
||||
const manifest = wecomIntegrationManifest.value;
|
||||
if (!manifest) return [];
|
||||
return copyFieldDefs.map((item) => ({
|
||||
key: item.key,
|
||||
label: t(item.labelKey),
|
||||
value: manifest[item.key] || '',
|
||||
}));
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="space-y-6">
|
||||
<div class="card shadow-sm p-5 space-y-4">
|
||||
<h3 class="font-semibold text-primary">{{ t('admin.wecom.systemSettings') }}</h3>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
<label class="inline-flex items-center gap-2 text-sm text-secondary">
|
||||
<input v-model="wecomSystemSettings.enabled" type="checkbox" class="admin-checkbox" />
|
||||
{{ t('admin.wecom.fields.enabled') }}
|
||||
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.enabled')" />
|
||||
</label>
|
||||
<label class="inline-flex items-center gap-2 text-sm text-secondary">
|
||||
<input v-model="wecomSystemSettings.auto_create_user" type="checkbox" class="admin-checkbox" />
|
||||
{{ t('admin.wecom.fields.autoCreateUser') }}
|
||||
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.autoCreateUser')" />
|
||||
</label>
|
||||
</div>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
|
||||
{{ t('admin.wecom.fields.corpId') }}
|
||||
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.corpId')" />
|
||||
</label>
|
||||
<input v-model="wecomSystemSettings.corp_id" class="input-field" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
|
||||
{{ t('admin.wecom.fields.agentId') }}
|
||||
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.agentId')" />
|
||||
</label>
|
||||
<input v-model="wecomSystemSettings.agent_id" class="input-field" />
|
||||
</div>
|
||||
<div class="md:col-span-2">
|
||||
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
|
||||
{{ t('admin.wecom.fields.secret') }}
|
||||
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.secret')" />
|
||||
</label>
|
||||
<input v-model="wecomSystemSettings.secret" type="password" class="input-field" />
|
||||
</div>
|
||||
<div class="md:col-span-2">
|
||||
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
|
||||
{{ t('admin.wecom.fields.redirectUri') }}
|
||||
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.redirectUri')" />
|
||||
</label>
|
||||
<input v-model="wecomSystemSettings.redirect_uri" class="input-field" />
|
||||
</div>
|
||||
<div class="md:col-span-2">
|
||||
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
|
||||
{{ t('admin.wecom.fields.publicBaseUrl') }}
|
||||
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.publicBaseUrl')" />
|
||||
</label>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<input
|
||||
v-model="wecomSystemSettings.public_base_url"
|
||||
:placeholder="t('admin.wecom.publicBasePlaceholder')"
|
||||
class="input-field flex-1 min-w-[200px]"
|
||||
/>
|
||||
<button type="button" class="btn-secondary px-4 shrink-0" @click="generateWecomAddressesFromPublicBase()">
|
||||
{{ t('admin.wecom.generateAddresses') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
|
||||
{{ t('admin.wecom.fields.callbackToken') }}
|
||||
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.callbackToken')" />
|
||||
</label>
|
||||
<div class="flex gap-2">
|
||||
<input v-model="wecomSystemSettings.callback_token" class="input-field flex-1 min-w-0" />
|
||||
<button type="button" class="btn-secondary px-3 shrink-0 text-xs" @click="generateWecomCallbackToken()">
|
||||
{{ t('admin.wecom.generateToken') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
|
||||
{{ t('admin.wecom.fields.encodingAesKey') }}
|
||||
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.encodingAesKey')" />
|
||||
</label>
|
||||
<div class="flex gap-2">
|
||||
<input v-model="wecomSystemSettings.encoding_aes_key" class="input-field flex-1 min-w-0 font-mono text-xs" />
|
||||
<button type="button" class="btn-secondary px-3 shrink-0 text-xs" @click="generateWecomEncodingAesKey()">
|
||||
{{ t('admin.wecom.generateEncodingKey') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
|
||||
{{ t('admin.wecom.fields.callbackUrl') }}
|
||||
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.callbackUrl')" />
|
||||
</label>
|
||||
<input v-model="wecomSystemSettings.callback_url" class="input-field" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
|
||||
{{ t('admin.wecom.fields.homepageUrl') }}
|
||||
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.homepageUrl')" />
|
||||
</label>
|
||||
<input v-model="wecomSystemSettings.homepage_url" class="input-field" />
|
||||
</div>
|
||||
<div class="md:col-span-2">
|
||||
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
|
||||
{{ t('admin.wecom.fields.trustedDomain') }}
|
||||
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.trustedDomain')" />
|
||||
</label>
|
||||
<input v-model="wecomSystemSettings.trusted_domain" class="input-field" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
|
||||
{{ t('admin.wecom.fields.matchRules') }}
|
||||
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.matchRules')" />
|
||||
</label>
|
||||
<input v-model="wecomSystemSettings.match_rules" class="input-field" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
|
||||
{{ t('admin.wecom.fields.matchOperator') }}
|
||||
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.matchOperator')" />
|
||||
</label>
|
||||
<select v-model="wecomSystemSettings.match_operator" class="input-field">
|
||||
<option value="AND">AND</option>
|
||||
<option value="OR">OR</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
|
||||
{{ t('admin.wecom.fields.firstLoginBindMode') }}
|
||||
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.firstLoginBindMode')" />
|
||||
</label>
|
||||
<select v-model="wecomSystemSettings.first_login_bind_mode" class="input-field">
|
||||
<option value="match_rules">{{ t('admin.wecom.bindModes.match_rules') }}</option>
|
||||
<option value="input_verify">{{ t('admin.wecom.bindModes.input_verify') }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
|
||||
{{ t('admin.wecom.fields.firstLoginInputFields') }}
|
||||
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.firstLoginInputFields')" />
|
||||
</label>
|
||||
<input v-model="wecomSystemSettings.first_login_input_fields" class="input-field" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
|
||||
{{ t('admin.wecom.fields.employeeIdSource') }}
|
||||
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.employeeIdSource')" />
|
||||
</label>
|
||||
<input v-model="wecomSystemSettings.employee_id_source" class="input-field" />
|
||||
</div>
|
||||
<label class="inline-flex items-center gap-2 text-sm text-secondary pt-7">
|
||||
<input v-model="wecomSystemSettings.mobile_normalize" type="checkbox" class="admin-checkbox" />
|
||||
{{ t('admin.wecom.fields.mobileNormalize') }}
|
||||
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.mobileNormalize')" />
|
||||
</label>
|
||||
</div>
|
||||
<div class="flex justify-end">
|
||||
<button type="button" :disabled="isSaving" class="btn-primary px-5 py-2 disabled:opacity-60" @click="saveWecomSystemSettings()">
|
||||
{{ t('admin.save') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<ElConfigProvider :locale="elementLocale">
|
||||
<AdminListPage>
|
||||
<template #title>
|
||||
<h2 class="section-title">{{ t('admin.wecom.title') }}</h2>
|
||||
<p class="section-desc mt-1">{{ t('admin.wecom.subtitle') }}</p>
|
||||
</template>
|
||||
<template #actions>
|
||||
<ElButton :icon="Refresh" @click="refreshWecomData()">{{ t('admin.wecom.refresh') }}</ElButton>
|
||||
</template>
|
||||
<template #tabs>
|
||||
<WecomSubNav />
|
||||
</template>
|
||||
|
||||
<div class="grid grid-cols-1 xl:grid-cols-2 gap-6">
|
||||
<div class="card shadow-sm p-5 space-y-4">
|
||||
<h3 class="font-semibold text-primary">{{ t('admin.wecom.notifySettings') }}</h3>
|
||||
<label class="inline-flex items-center gap-2 text-sm text-secondary">
|
||||
<input v-model="wecomNotifySettings.enabled" type="checkbox" class="admin-checkbox" />
|
||||
{{ t('admin.wecom.notifyEnabled') }}
|
||||
</label>
|
||||
<input v-model="wecomNotifySettings.base_url" :placeholder="t('admin.wecom.notifyBaseUrl')" class="input-field" />
|
||||
<input v-model="wecomNotifyEventsText" :placeholder="t('admin.wecom.notifyEvents')" class="input-field" />
|
||||
<div class="flex justify-end">
|
||||
<button type="button" :disabled="isSaving" class="btn-primary px-5 py-2 disabled:opacity-60" @click="saveWecomNotifySettings()">
|
||||
{{ t('admin.save') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card shadow-sm p-5 space-y-4">
|
||||
<h3 class="font-semibold text-primary">{{ t('admin.wecom.notifyMetrics') }}</h3>
|
||||
<div v-if="wecomNotifyMetrics" class="grid grid-cols-2 gap-3 text-sm">
|
||||
<div class="rounded-lg bg-surface-soft px-3 py-2">
|
||||
<div class="text-muted">{{ t('admin.wecom.metricTotal') }}</div>
|
||||
<div class="text-lg font-semibold text-primary">{{ wecomNotifyMetrics.total }}</div>
|
||||
</div>
|
||||
<div class="rounded-lg bg-surface-soft px-3 py-2">
|
||||
<div class="text-muted">{{ t('admin.wecom.metricSuccessRate') }}</div>
|
||||
<div class="text-lg font-semibold text-emerald-700">{{ wecomNotifyMetrics.send_success_rate }}%</div>
|
||||
</div>
|
||||
<div class="rounded-lg bg-surface-soft px-3 py-2">
|
||||
<div class="text-muted">{{ t('admin.wecom.metricOpenedRate') }}</div>
|
||||
<div class="text-lg font-semibold text-blue-700">{{ wecomNotifyMetrics.opened_24h_rate }}%</div>
|
||||
</div>
|
||||
<div class="rounded-lg bg-surface-soft px-3 py-2">
|
||||
<div class="text-muted">{{ t('admin.wecom.metricWindowDays') }}</div>
|
||||
<div class="text-lg font-semibold text-primary">{{ wecomNotifyMetrics.window_days }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<details class="card shadow-sm p-5">
|
||||
<summary class="cursor-pointer font-semibold text-primary">{{ t('admin.wecom.integrationCopyTitle') }}</summary>
|
||||
<div class="mt-4 space-y-4">
|
||||
<p class="text-xs text-muted">{{ t('admin.wecom.integrationCopyDesc') }}</p>
|
||||
<p class="text-xs text-amber-800 bg-amber-50 border border-amber-100 rounded-lg px-3 py-2">{{ t('admin.wecom.integrationCopySecretsNote') }}</p>
|
||||
<div v-if="wecomIntegrationManifest" class="grid grid-cols-1 gap-3">
|
||||
<div
|
||||
v-for="item in [
|
||||
{ key: 'public_base_url', label: t('admin.wecom.copyFields.publicBaseUrl') },
|
||||
{ key: 'callback_url', label: t('admin.wecom.copyFields.callbackUrl') },
|
||||
{ key: 'callback_token', label: t('admin.wecom.copyFields.callbackToken') },
|
||||
{ key: 'encoding_aes_key', label: t('admin.wecom.copyFields.encodingAesKey') },
|
||||
{ key: 'oauth_redirect_uri', label: t('admin.wecom.copyFields.oauthRedirectUri') },
|
||||
{ key: 'homepage_url', label: t('admin.wecom.copyFields.homepageUrl') },
|
||||
{ key: 'trusted_domain', label: t('admin.wecom.copyFields.trustedDomain') },
|
||||
{ key: 'authorize_api', label: t('admin.wecom.copyFields.authorizeApi') },
|
||||
{ key: 'login_api', label: t('admin.wecom.copyFields.loginApi') },
|
||||
]"
|
||||
:key="item.key"
|
||||
>
|
||||
<label class="mb-1.5 block text-xs text-muted">{{ item.label }}</label>
|
||||
<div class="flex gap-2">
|
||||
<input :value="(wecomIntegrationManifest as any)[item.key] || ''" readonly class="input-field flex-1 bg-surface-soft font-mono text-xs" />
|
||||
<button type="button" class="btn-secondary px-3" @click="copyText(String((wecomIntegrationManifest as any)[item.key] || ''))">
|
||||
{{ t('admin.wecom.copy') }}
|
||||
</button>
|
||||
<div class="wecom-settings">
|
||||
<section class="wecom-settings__section">
|
||||
<h3 class="wecom-settings__heading">{{ t('admin.wecom.systemSettings') }}</h3>
|
||||
<ElForm label-position="top" :model="wecomSystemSettings" @submit.prevent="saveWecomSystemSettings()">
|
||||
<div class="wecom-settings__grid">
|
||||
<ElFormItem>
|
||||
<template #label>
|
||||
<span class="wecom-settings__label">
|
||||
{{ t('admin.wecom.fields.enabled') }}
|
||||
<ElTooltip :content="t('admin.wecom.tips.enabled')" placement="top">
|
||||
<ElIcon class="wecom-settings__help"><QuestionFilled /></ElIcon>
|
||||
</ElTooltip>
|
||||
</span>
|
||||
</template>
|
||||
<ElSwitch v-model="wecomSystemSettings.enabled" />
|
||||
</ElFormItem>
|
||||
<ElFormItem>
|
||||
<template #label>
|
||||
<span class="wecom-settings__label">
|
||||
{{ t('admin.wecom.fields.autoCreateUser') }}
|
||||
<ElTooltip :content="t('admin.wecom.tips.autoCreateUser')" placement="top">
|
||||
<ElIcon class="wecom-settings__help"><QuestionFilled /></ElIcon>
|
||||
</ElTooltip>
|
||||
</span>
|
||||
</template>
|
||||
<ElSwitch v-model="wecomSystemSettings.auto_create_user" />
|
||||
</ElFormItem>
|
||||
<ElFormItem>
|
||||
<template #label>
|
||||
<span class="wecom-settings__label">
|
||||
{{ t('admin.wecom.fields.corpId') }}
|
||||
<ElTooltip :content="t('admin.wecom.tips.corpId')" placement="top">
|
||||
<ElIcon class="wecom-settings__help"><QuestionFilled /></ElIcon>
|
||||
</ElTooltip>
|
||||
</span>
|
||||
</template>
|
||||
<ElInput v-model="wecomSystemSettings.corp_id" />
|
||||
</ElFormItem>
|
||||
<ElFormItem>
|
||||
<template #label>
|
||||
<span class="wecom-settings__label">
|
||||
{{ t('admin.wecom.fields.agentId') }}
|
||||
<ElTooltip :content="t('admin.wecom.tips.agentId')" placement="top">
|
||||
<ElIcon class="wecom-settings__help"><QuestionFilled /></ElIcon>
|
||||
</ElTooltip>
|
||||
</span>
|
||||
</template>
|
||||
<ElInput v-model="wecomSystemSettings.agent_id" />
|
||||
</ElFormItem>
|
||||
<ElFormItem class="wecom-settings__span">
|
||||
<template #label>
|
||||
<span class="wecom-settings__label">
|
||||
{{ t('admin.wecom.fields.secret') }}
|
||||
<ElTooltip :content="t('admin.wecom.tips.secret')" placement="top">
|
||||
<ElIcon class="wecom-settings__help"><QuestionFilled /></ElIcon>
|
||||
</ElTooltip>
|
||||
</span>
|
||||
</template>
|
||||
<ElInput v-model="wecomSystemSettings.secret" type="password" show-password />
|
||||
</ElFormItem>
|
||||
<ElFormItem class="wecom-settings__span">
|
||||
<template #label>
|
||||
<span class="wecom-settings__label">
|
||||
{{ t('admin.wecom.fields.redirectUri') }}
|
||||
<ElTooltip :content="t('admin.wecom.tips.redirectUri')" placement="top">
|
||||
<ElIcon class="wecom-settings__help"><QuestionFilled /></ElIcon>
|
||||
</ElTooltip>
|
||||
</span>
|
||||
</template>
|
||||
<ElInput v-model="wecomSystemSettings.redirect_uri" />
|
||||
</ElFormItem>
|
||||
<ElFormItem class="wecom-settings__span">
|
||||
<template #label>
|
||||
<span class="wecom-settings__label">
|
||||
{{ t('admin.wecom.fields.publicBaseUrl') }}
|
||||
<ElTooltip :content="t('admin.wecom.tips.publicBaseUrl')" placement="top">
|
||||
<ElIcon class="wecom-settings__help"><QuestionFilled /></ElIcon>
|
||||
</ElTooltip>
|
||||
</span>
|
||||
</template>
|
||||
<div class="wecom-settings__inline">
|
||||
<ElInput
|
||||
v-model="wecomSystemSettings.public_base_url"
|
||||
:placeholder="t('admin.wecom.publicBasePlaceholder')"
|
||||
/>
|
||||
<ElButton @click="generateWecomAddressesFromPublicBase()">
|
||||
{{ t('admin.wecom.generateAddresses') }}
|
||||
</ElButton>
|
||||
</div>
|
||||
</ElFormItem>
|
||||
<ElFormItem>
|
||||
<template #label>
|
||||
<span class="wecom-settings__label">
|
||||
{{ t('admin.wecom.fields.callbackToken') }}
|
||||
<ElTooltip :content="t('admin.wecom.tips.callbackToken')" placement="top">
|
||||
<ElIcon class="wecom-settings__help"><QuestionFilled /></ElIcon>
|
||||
</ElTooltip>
|
||||
</span>
|
||||
</template>
|
||||
<div class="wecom-settings__inline">
|
||||
<ElInput v-model="wecomSystemSettings.callback_token" />
|
||||
<ElButton @click="generateWecomCallbackToken()">{{ t('admin.wecom.generateToken') }}</ElButton>
|
||||
</div>
|
||||
</ElFormItem>
|
||||
<ElFormItem>
|
||||
<template #label>
|
||||
<span class="wecom-settings__label">
|
||||
{{ t('admin.wecom.fields.encodingAesKey') }}
|
||||
<ElTooltip :content="t('admin.wecom.tips.encodingAesKey')" placement="top">
|
||||
<ElIcon class="wecom-settings__help"><QuestionFilled /></ElIcon>
|
||||
</ElTooltip>
|
||||
</span>
|
||||
</template>
|
||||
<div class="wecom-settings__inline">
|
||||
<ElInput v-model="wecomSystemSettings.encoding_aes_key" class="wecom-settings__mono" />
|
||||
<ElButton @click="generateWecomEncodingAesKey()">{{ t('admin.wecom.generateEncodingKey') }}</ElButton>
|
||||
</div>
|
||||
</ElFormItem>
|
||||
<ElFormItem>
|
||||
<template #label>
|
||||
<span class="wecom-settings__label">
|
||||
{{ t('admin.wecom.fields.callbackUrl') }}
|
||||
<ElTooltip :content="t('admin.wecom.tips.callbackUrl')" placement="top">
|
||||
<ElIcon class="wecom-settings__help"><QuestionFilled /></ElIcon>
|
||||
</ElTooltip>
|
||||
</span>
|
||||
</template>
|
||||
<ElInput v-model="wecomSystemSettings.callback_url" />
|
||||
</ElFormItem>
|
||||
<ElFormItem>
|
||||
<template #label>
|
||||
<span class="wecom-settings__label">
|
||||
{{ t('admin.wecom.fields.homepageUrl') }}
|
||||
<ElTooltip :content="t('admin.wecom.tips.homepageUrl')" placement="top">
|
||||
<ElIcon class="wecom-settings__help"><QuestionFilled /></ElIcon>
|
||||
</ElTooltip>
|
||||
</span>
|
||||
</template>
|
||||
<ElInput v-model="wecomSystemSettings.homepage_url" />
|
||||
</ElFormItem>
|
||||
<ElFormItem class="wecom-settings__span">
|
||||
<template #label>
|
||||
<span class="wecom-settings__label">
|
||||
{{ t('admin.wecom.fields.trustedDomain') }}
|
||||
<ElTooltip :content="t('admin.wecom.tips.trustedDomain')" placement="top">
|
||||
<ElIcon class="wecom-settings__help"><QuestionFilled /></ElIcon>
|
||||
</ElTooltip>
|
||||
</span>
|
||||
</template>
|
||||
<ElInput v-model="wecomSystemSettings.trusted_domain" />
|
||||
</ElFormItem>
|
||||
<ElFormItem>
|
||||
<template #label>
|
||||
<span class="wecom-settings__label">
|
||||
{{ t('admin.wecom.fields.matchRules') }}
|
||||
<ElTooltip :content="t('admin.wecom.tips.matchRules')" placement="top">
|
||||
<ElIcon class="wecom-settings__help"><QuestionFilled /></ElIcon>
|
||||
</ElTooltip>
|
||||
</span>
|
||||
</template>
|
||||
<ElInput v-model="wecomSystemSettings.match_rules" />
|
||||
</ElFormItem>
|
||||
<ElFormItem>
|
||||
<template #label>
|
||||
<span class="wecom-settings__label">
|
||||
{{ t('admin.wecom.fields.matchOperator') }}
|
||||
<ElTooltip :content="t('admin.wecom.tips.matchOperator')" placement="top">
|
||||
<ElIcon class="wecom-settings__help"><QuestionFilled /></ElIcon>
|
||||
</ElTooltip>
|
||||
</span>
|
||||
</template>
|
||||
<ElSelect v-model="wecomSystemSettings.match_operator">
|
||||
<ElOption label="AND" value="AND" />
|
||||
<ElOption label="OR" value="OR" />
|
||||
</ElSelect>
|
||||
</ElFormItem>
|
||||
<ElFormItem>
|
||||
<template #label>
|
||||
<span class="wecom-settings__label">
|
||||
{{ t('admin.wecom.fields.firstLoginBindMode') }}
|
||||
<ElTooltip :content="t('admin.wecom.tips.firstLoginBindMode')" placement="top">
|
||||
<ElIcon class="wecom-settings__help"><QuestionFilled /></ElIcon>
|
||||
</ElTooltip>
|
||||
</span>
|
||||
</template>
|
||||
<ElSelect v-model="wecomSystemSettings.first_login_bind_mode">
|
||||
<ElOption :label="t('admin.wecom.bindModes.match_rules')" value="match_rules" />
|
||||
<ElOption :label="t('admin.wecom.bindModes.input_verify')" value="input_verify" />
|
||||
</ElSelect>
|
||||
</ElFormItem>
|
||||
<ElFormItem>
|
||||
<template #label>
|
||||
<span class="wecom-settings__label">
|
||||
{{ t('admin.wecom.fields.firstLoginInputFields') }}
|
||||
<ElTooltip :content="t('admin.wecom.tips.firstLoginInputFields')" placement="top">
|
||||
<ElIcon class="wecom-settings__help"><QuestionFilled /></ElIcon>
|
||||
</ElTooltip>
|
||||
</span>
|
||||
</template>
|
||||
<ElInput v-model="wecomSystemSettings.first_login_input_fields" />
|
||||
</ElFormItem>
|
||||
<ElFormItem>
|
||||
<template #label>
|
||||
<span class="wecom-settings__label">
|
||||
{{ t('admin.wecom.fields.employeeIdSource') }}
|
||||
<ElTooltip :content="t('admin.wecom.tips.employeeIdSource')" placement="top">
|
||||
<ElIcon class="wecom-settings__help"><QuestionFilled /></ElIcon>
|
||||
</ElTooltip>
|
||||
</span>
|
||||
</template>
|
||||
<ElInput v-model="wecomSystemSettings.employee_id_source" />
|
||||
</ElFormItem>
|
||||
<ElFormItem>
|
||||
<template #label>
|
||||
<span class="wecom-settings__label">
|
||||
{{ t('admin.wecom.fields.mobileNormalize') }}
|
||||
<ElTooltip :content="t('admin.wecom.tips.mobileNormalize')" placement="top">
|
||||
<ElIcon class="wecom-settings__help"><QuestionFilled /></ElIcon>
|
||||
</ElTooltip>
|
||||
</span>
|
||||
</template>
|
||||
<ElSwitch v-model="wecomSystemSettings.mobile_normalize" />
|
||||
</ElFormItem>
|
||||
</div>
|
||||
</div>
|
||||
<div class="wecom-settings__submit">
|
||||
<ElButton type="primary" :loading="isSaving" @click="saveWecomSystemSettings()">
|
||||
{{ t('admin.save') }}
|
||||
</ElButton>
|
||||
</div>
|
||||
</ElForm>
|
||||
</section>
|
||||
|
||||
<div class="wecom-settings__split">
|
||||
<section class="wecom-settings__section">
|
||||
<h3 class="wecom-settings__heading">{{ t('admin.wecom.notifySettings') }}</h3>
|
||||
<ElForm label-position="top" :model="wecomNotifySettings" @submit.prevent="saveWecomNotifySettings()">
|
||||
<ElFormItem :label="t('admin.wecom.notifyEnabled')">
|
||||
<ElSwitch v-model="wecomNotifySettings.enabled" />
|
||||
</ElFormItem>
|
||||
<ElFormItem :label="t('admin.wecom.notifyBaseUrl')">
|
||||
<ElInput v-model="wecomNotifySettings.base_url" :placeholder="t('admin.wecom.notifyBaseUrl')" />
|
||||
</ElFormItem>
|
||||
<ElFormItem :label="t('admin.wecom.notifyEvents')">
|
||||
<ElInput v-model="wecomNotifyEventsText" :placeholder="t('admin.wecom.notifyEvents')" />
|
||||
</ElFormItem>
|
||||
<div class="wecom-settings__submit">
|
||||
<ElButton type="primary" :loading="isSaving" @click="saveWecomNotifySettings()">
|
||||
{{ t('admin.save') }}
|
||||
</ElButton>
|
||||
</div>
|
||||
</ElForm>
|
||||
</section>
|
||||
<section class="wecom-settings__section">
|
||||
<h3 class="wecom-settings__heading">{{ t('admin.wecom.notifyMetrics') }}</h3>
|
||||
<div v-if="wecomNotifyMetrics" class="wecom-settings__metrics">
|
||||
<ElCard shadow="never">
|
||||
<ElStatistic :title="t('admin.wecom.metricTotal')" :value="wecomNotifyMetrics.total" />
|
||||
</ElCard>
|
||||
<ElCard shadow="never">
|
||||
<ElStatistic :title="t('admin.wecom.metricSuccessRate')" :value="wecomNotifyMetrics.send_success_rate" suffix="%" />
|
||||
</ElCard>
|
||||
<ElCard shadow="never">
|
||||
<ElStatistic :title="t('admin.wecom.metricOpenedRate')" :value="wecomNotifyMetrics.opened_24h_rate" suffix="%" />
|
||||
</ElCard>
|
||||
<ElCard shadow="never">
|
||||
<ElStatistic :title="t('admin.wecom.metricWindowDays')" :value="wecomNotifyMetrics.window_days" />
|
||||
</ElCard>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section class="wecom-settings__section">
|
||||
<ElCollapse>
|
||||
<ElCollapseItem :title="t('admin.wecom.integrationCopyTitle')" name="copy">
|
||||
<ElText class="wecom-settings__copy-desc" type="info">{{ t('admin.wecom.integrationCopyDesc') }}</ElText>
|
||||
<ElAlert
|
||||
class="wecom-settings__copy-note"
|
||||
type="warning"
|
||||
:closable="false"
|
||||
:title="t('admin.wecom.integrationCopySecretsNote')"
|
||||
/>
|
||||
<ElForm v-if="copyItems.length" label-position="top">
|
||||
<ElFormItem v-for="item in copyItems" :key="item.key" :label="item.label">
|
||||
<div class="wecom-settings__inline">
|
||||
<ElInput :model-value="item.value" readonly class="wecom-settings__mono" />
|
||||
<ElButton @click="copyText(item.value)">{{ t('admin.wecom.copy') }}</ElButton>
|
||||
</div>
|
||||
</ElFormItem>
|
||||
</ElForm>
|
||||
</ElCollapseItem>
|
||||
</ElCollapse>
|
||||
</section>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
</AdminListPage>
|
||||
</ElConfigProvider>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.wecom-settings__section {
|
||||
padding: 16px 32px 8px;
|
||||
border-top: 1px solid var(--el-border-color-lighter);
|
||||
}
|
||||
|
||||
.wecom-settings__heading {
|
||||
margin: 0 0 12px;
|
||||
color: var(--el-text-color-primary);
|
||||
font-size: var(--el-font-size-large);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.wecom-settings__grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
column-gap: 16px;
|
||||
}
|
||||
|
||||
.wecom-settings__label {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.wecom-settings__help {
|
||||
color: var(--el-text-color-secondary);
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.wecom-settings__inline {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.wecom-settings__inline .el-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.wecom-settings__submit {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
|
||||
.wecom-settings__split {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.wecom-settings__metrics {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
padding-bottom: 16px;
|
||||
}
|
||||
|
||||
.wecom-settings__copy-desc,
|
||||
.wecom-settings__copy-note {
|
||||
display: block;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.wecom-settings__mono :deep(.el-input__inner) {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
.wecom-settings__grid {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
|
||||
.wecom-settings__span {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 1280px) {
|
||||
.wecom-settings__split {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1399,6 +1399,19 @@ export async function batchConfirmWorkspaceShippingNoticesUploaded(businessNos:
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动刷新 Crane 分配状态。后端只排队一次状态回查,不重新上传 Excel。
|
||||
* @param businessNo - 对外发货通知单号,同时是 Crane 的 Pull Request #
|
||||
* @returns 已排队的回查结果
|
||||
*/
|
||||
export async function refreshWorkspaceCraneUploadStatus(businessNo: string) {
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-notices/${encodeURIComponent(businessNo)}/refresh-crane-upload`,
|
||||
jsonPost({}),
|
||||
);
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/** 按多个发货通知单号批量受理货代 RPA 上传;RPA 成功仍以回调为准。 */
|
||||
export async function batchStartWorkspaceShippingNoticeRpaUpload(businessNos: string[]) {
|
||||
return requestJson<{ results: Array<Record<string, unknown>> }>(
|
||||
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
executeTransferItems,
|
||||
listEvidenceFiles,
|
||||
reparseCurrentFile,
|
||||
downloadEvidenceFile,
|
||||
retryTransferSourceRpa,
|
||||
retryTransferSourcesRpaBatch,
|
||||
getTransferBacklogSummary,
|
||||
@@ -109,6 +110,13 @@ describe('transfer.api JSON request contract', () => {
|
||||
expect(url).toBe('/api/in-transit-transfer/sources/DSV360/evidence-files?record_kind=outbound');
|
||||
});
|
||||
|
||||
it('单文件下载走站点 evidence-files/{id},不打开 MinIO 地址', () => {
|
||||
// [断言意图] HTTPS 页面不能直接打开 HTTP MinIO 预签名链接,下载必须走当前站点。
|
||||
downloadEvidenceFile('DSV360', 25, 'outbound');
|
||||
const [url] = requestBlob.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('/api/in-transit-transfer/sources/DSV360/evidence-files/25?record_kind=outbound');
|
||||
});
|
||||
|
||||
it('当前文件重解析 POST reparse,body 只有 record_kind', () => {
|
||||
reparseCurrentFile('DSV360_AWSDU', 'outbound');
|
||||
const calls = requestJson.mock.calls as [string, RequestInit][];
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
* 逻辑:薄封装后端 /api/in-transit-transfer 全部端点;二进制下载走 requestBlob。
|
||||
* 来源重试 body 带 record_kind;批量重试与证据打包在带来源类型时带 transfer_type;
|
||||
* 证据清单走 GET sources/{code}/evidence-files;
|
||||
* 单文件下载走 GET sources/{code}/evidence-files/{fileId},由站点回传,
|
||||
* 不打开 HTTP MinIO 预签名地址;
|
||||
* 当前归档重解析走 POST sources/{code}/reparse(body 仅 record_kind,不触发 RPA)。
|
||||
*/
|
||||
import { requestBlob, requestJson } from '@/shared/api/client';
|
||||
@@ -327,6 +329,25 @@ export const listEvidenceFiles = (sourceCode: string, recordKind: TransferRecord
|
||||
{ headers: getAuthHeaders() },
|
||||
);
|
||||
|
||||
/**
|
||||
* 经当前站点下载一份证据文件。
|
||||
* 核心逻辑:GET /sources/{code}/evidence-files/{fileId},带 record_kind。
|
||||
* 页面是 HTTPS,MinIO 公网地址是 HTTP,直接打开预签名链接会被浏览器拦截。
|
||||
* @param sourceCode - 来源实例编码
|
||||
* @param fileId - 归档文件主键
|
||||
* @param recordKind - inbound 或 outbound
|
||||
* @returns 文件内容和 Content-Disposition 中的保存名
|
||||
*/
|
||||
export const downloadEvidenceFile = (
|
||||
sourceCode: string,
|
||||
fileId: number,
|
||||
recordKind: TransferRecordKind,
|
||||
) =>
|
||||
requestBlob(
|
||||
`${BASE}/sources/${encodeURIComponent(sourceCode)}/evidence-files/${fileId}?record_kind=${encodeURIComponent(recordKind)}`,
|
||||
{ headers: getAuthHeaders() },
|
||||
);
|
||||
|
||||
/**
|
||||
* 对来源当前最新归档文件重新解析(不触发 RPA)。
|
||||
* 核心逻辑:POST /sources/{code}/reparse,body 只带 record_kind,后端重放最新归档 Excel。
|
||||
|
||||
@@ -320,7 +320,7 @@ function resultLabelKey(item: TransferBacklogItem): string {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- EP 表格壳:数据=服务端返回的当前页切片;横向滚动由 el-table 内建(列 min-width 撑开) -->
|
||||
<!-- EP 表格:show-overflow-tooltip;左固定勾选,右固定结果+操作;单号/老化可滚 -->
|
||||
<el-table
|
||||
v-if="items.length"
|
||||
:data="items"
|
||||
@@ -330,7 +330,7 @@ function resultLabelKey(item: TransferBacklogItem): string {
|
||||
class="text-xs"
|
||||
data-testid="transfer-backlog-table"
|
||||
>
|
||||
<el-table-column width="48" class-name="whitespace-nowrap">
|
||||
<el-table-column fixed width="48">
|
||||
<template #header>
|
||||
<el-checkbox
|
||||
size="small"
|
||||
@@ -349,40 +349,61 @@ function resultLabelKey(item: TransferBacklogItem): string {
|
||||
/>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colSource')" prop="source_code" min-width="110" class-name="whitespace-nowrap" />
|
||||
<el-table-column :label="$t('chat.transfer.transferTypeLabel')" min-width="140" class-name="whitespace-nowrap">
|
||||
<el-table-column :label="$t('chat.transfer.colSource')" prop="source_code" min-width="120" show-overflow-tooltip />
|
||||
<el-table-column :label="$t('chat.transfer.transferTypeLabel')" min-width="140" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<span :data-testid="`transfer-backlog-type-${row.invoice_no}`">{{ typeLabel(row.transfer_type) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colInvoice')" prop="invoice_no" min-width="130" class-name="whitespace-nowrap">
|
||||
<el-table-column
|
||||
:label="$t('chat.transfer.transferPendingMatchColDocNo')"
|
||||
prop="invoice_no"
|
||||
min-width="130"
|
||||
show-overflow-tooltip
|
||||
>
|
||||
<template #default="{ row }">
|
||||
<span class="font-semibold">{{ row.invoice_no }}</span>
|
||||
<span class="font-semibold">{{ row.invoice_no || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colMovementDate')" min-width="100" class-name="whitespace-nowrap">
|
||||
<el-table-column
|
||||
:label="$t('chat.transfer.transferPendingMatchColExternalDoc')"
|
||||
min-width="130"
|
||||
show-overflow-tooltip
|
||||
>
|
||||
<template #default="{ row }">
|
||||
<span data-testid="transfer-backlog-external-doc">{{ row.external_doc_no || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colMovementDate')" min-width="110" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ row.movement_date || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colMaterial')" prop="material_no" min-width="110" class-name="whitespace-nowrap" />
|
||||
<el-table-column :label="$t('chat.transfer.colName')" min-width="140">
|
||||
<el-table-column :label="$t('chat.transfer.colMaterial')" prop="material_no" min-width="140" show-overflow-tooltip />
|
||||
<el-table-column :label="$t('chat.transfer.colName')" prop="material_name" min-width="160" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ row.material_name || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colFromWarehouse')" min-width="110" class-name="whitespace-nowrap">
|
||||
<el-table-column :label="$t('chat.transfer.colFromWarehouse')" min-width="110" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ row.from_warehouse || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colFromBatch')" min-width="110" class-name="whitespace-nowrap">
|
||||
<el-table-column :label="$t('chat.transfer.colFromBatch')" min-width="120" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ deriveBatchNo(row.lot_no ?? '') || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colFromQty')" min-width="90" class-name="whitespace-nowrap">
|
||||
<el-table-column :label="$t('chat.transfer.colFromQty')" min-width="90" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ formatQuantity(row.external_quantity) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colToWarehouse')" min-width="110" class-name="whitespace-nowrap">
|
||||
<el-table-column :label="$t('chat.transfer.colToWarehouse')" min-width="110" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ row.to_warehouse || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colToQty')" min-width="90" class-name="whitespace-nowrap">
|
||||
<el-table-column :label="$t('chat.transfer.colToQty')" min-width="90" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ formatQuantity(row.movement_quantity) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colResult')" min-width="110">
|
||||
<el-table-column :label="$t('chat.transfer.colAging')" min-width="90" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ $t(agingLabel(row.aging_level)) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column
|
||||
fixed="right"
|
||||
:label="$t('chat.transfer.colResult')"
|
||||
width="100"
|
||||
>
|
||||
<template #default="{ row }">
|
||||
<el-tag
|
||||
size="small"
|
||||
@@ -395,10 +416,11 @@ function resultLabelKey(item: TransferBacklogItem): string {
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colAging')" min-width="90" class-name="whitespace-nowrap">
|
||||
<template #default="{ row }">{{ $t(agingLabel(row.aging_level)) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colAction')" min-width="150" class-name="whitespace-nowrap">
|
||||
<el-table-column
|
||||
fixed="right"
|
||||
:label="$t('chat.transfer.colAction')"
|
||||
width="150"
|
||||
>
|
||||
<template #default="{ row }">
|
||||
<template v-if="isActionable(row as TransferBacklogItem)">
|
||||
<!-- 失效行(文件已移除)只留关闭:重查会被后端拒绝(TRANSFER.RETRY_NOT_ALLOWED)。 -->
|
||||
|
||||
@@ -2,20 +2,18 @@
|
||||
features/chat/components/messages/TransferExecutableCard.vue
|
||||
用途:可调拨明细卡——全局可执行行队列(跨匹配范围):勾选明细行后按行生成调拨单。
|
||||
依赖:Element Plus ElTable/ElTableColumn/ElInput/ElButton/ElTag/ElPagination/
|
||||
ElCheckbox(2026-10-20:勾选列一并 EP;testid 挂 el-checkbox,规格经内层
|
||||
input 读写)、props.items、i18n chat.transfer.*、transferBatch.deriveBatchNo。
|
||||
逻辑:行由后端按业务稳定键排序(异动日期→Invoice→创建时间);勾选为卡片本地态;
|
||||
stale/file_current 行置灰提示(执行门禁在后端,失败经 BusinessError 展示);
|
||||
无 item_id 的历史回放行禁选。
|
||||
客户端分页(2026-10-16):集合天然有界(仅当日成熟可执行行)但为防增长后
|
||||
DOM 失控,50/页切片渲染;关键字筛选变更回第 1 页,勾选集合跨页保留。
|
||||
行定位:el-table 经 row-class-name 注入 transfer-executable-<invoice_no>。
|
||||
调拨类型列取行上 transfer_type,按启用类型配置显示当前语言名称。
|
||||
ElCheckbox/ElAlert、props.items、i18n chat.transfer.*、transferBatch /
|
||||
transferItemTable(明细表密度约定)。
|
||||
逻辑:行由后端按业务稳定键排序;勾选本地态;无 item_id 历史行禁选;50/页分页。
|
||||
表格遵循 transferItemTable:show-overflow-tooltip、左固定勾选、右固定结果+操作、
|
||||
单号可滚、库存数量与查询时刻同行、过期用顶栏 el-alert 汇总批量重查。
|
||||
行定位:row-class-name 注入 transfer-executable-<invoice_no>。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
ElAlert,
|
||||
ElButton,
|
||||
ElCheckbox,
|
||||
ElInput,
|
||||
@@ -27,8 +25,11 @@ import {
|
||||
import type { CheckboxValueType } from 'element-plus';
|
||||
import { deriveBatchNo } from './transferBatch';
|
||||
import { formatQuantity } from './transferFormat';
|
||||
import {
|
||||
formatStockQuantityCell,
|
||||
freshnessHint,
|
||||
} from './transferItemTable';
|
||||
import { transferTypeDisplay } from './transferTypeLabel';
|
||||
import { parseApiUtcDate } from '@/shared/utils/dateTime';
|
||||
import type { TransferMatchingItem, TransferTypeOption } from '../../types/transfer.types';
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
@@ -40,7 +41,7 @@ const props = withDefaults(defineProps<{
|
||||
transferTypes: () => [],
|
||||
});
|
||||
|
||||
const { locale } = useI18n();
|
||||
const { locale, t } = useI18n();
|
||||
|
||||
/**
|
||||
* 把可执行行的调拨类型 code 显示成名称。
|
||||
@@ -70,7 +71,7 @@ const filtered = computed(() =>
|
||||
props.items.filter((item) => {
|
||||
const kw = keyword.value.trim().toLowerCase();
|
||||
if (!kw) return true;
|
||||
const haystack = [item.invoice_no, item.material_no, item.material_name, item.source_code, item.lot_no]
|
||||
const haystack = [item.invoice_no, item.external_doc_no, item.material_no, item.material_name, item.source_code, item.lot_no]
|
||||
.map((value) => String(value ?? '').toLowerCase());
|
||||
return haystack.some((value) => value.includes(kw));
|
||||
}),
|
||||
@@ -80,7 +81,6 @@ const pagedItems = computed(() =>
|
||||
filtered.value.slice((currentPage.value - 1) * PAGE_SIZE, currentPage.value * PAGE_SIZE),
|
||||
);
|
||||
|
||||
// 筛选变更回第 1 页;刷新后行数减少时收拢当前页防空白页
|
||||
watch(keyword, () => {
|
||||
currentPage.value = 1;
|
||||
});
|
||||
@@ -97,6 +97,13 @@ const allFilteredSelected = computed(() =>
|
||||
filtered.value.length > 0 && filtered.value.every((item) => item.item_id != null && selectedIds.value.has(item.item_id)),
|
||||
);
|
||||
|
||||
/** 当前筛选下库存已过期且可重查的行 id。 */
|
||||
const staleItemIds = computed(() =>
|
||||
filtered.value
|
||||
.filter((item) => item.stale === true && item.item_id != null)
|
||||
.map((item) => item.item_id as number),
|
||||
);
|
||||
|
||||
function toggleRow(item: TransferMatchingItem, checkedBox: boolean) {
|
||||
if (item.item_id == null) return;
|
||||
const next = new Set(selectedIds.value);
|
||||
@@ -126,7 +133,7 @@ function rowKey(item: TransferMatchingItem): string {
|
||||
/**
|
||||
* el-table 行类:注入行定位类 + stale/文件过期置灰。
|
||||
* @param row 可执行明细行
|
||||
* @returns 空格分隔的 class 串(含 transfer-executable-<invoice_no>)
|
||||
* @returns 空格分隔的 class 串
|
||||
*/
|
||||
function rowClassName({ row }: { row: TransferMatchingItem }): string {
|
||||
return [
|
||||
@@ -135,12 +142,21 @@ function rowClassName({ row }: { row: TransferMatchingItem }): string {
|
||||
].filter(Boolean).join(' ');
|
||||
}
|
||||
|
||||
/** 查询时刻展示(HH:mm);后端 naive ISO 按 UTC 解析后转浏览器本地时区
|
||||
* (仓库约定 parseApiUtcDate,2026-09-29 修复 UTC+8 展示异常);无 checked_at 不渲染。 */
|
||||
function checkedTime(item: TransferMatchingItem): string {
|
||||
if (!item.checked_at) return '';
|
||||
const date = parseApiUtcDate(item.checked_at);
|
||||
return Number.isNaN(date.getTime()) ? '' : date.toTimeString().slice(0, 5);
|
||||
/**
|
||||
* 库存数量单元格:数量与完整查询时刻同一行。
|
||||
* @param item 可执行明细行
|
||||
*/
|
||||
function stockCell(item: TransferMatchingItem): string {
|
||||
return formatStockQuantityCell(formatQuantity(item.from_quantity), item.checked_at);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量重查当前筛选下全部过期行。
|
||||
* 核心逻辑:顶栏汇总入口,避免结果列刷长文案。
|
||||
*/
|
||||
function requeryStaleRows() {
|
||||
if (!staleItemIds.value.length) return;
|
||||
emit('requery', [...staleItemIds.value]);
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -157,6 +173,30 @@ function checkedTime(item: TransferMatchingItem): string {
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
<el-alert
|
||||
v-if="staleItemIds.length"
|
||||
type="warning"
|
||||
:closable="false"
|
||||
class="mb-2"
|
||||
data-testid="transfer-executable-stale-banner"
|
||||
>
|
||||
<template #title>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span>{{ $t('chat.transfer.staleBanner', { count: staleItemIds.length }) }}</span>
|
||||
<el-button
|
||||
link
|
||||
type="primary"
|
||||
size="small"
|
||||
:disabled="busy"
|
||||
data-testid="transfer-executable-requery-stale"
|
||||
@click="requeryStaleRows"
|
||||
>
|
||||
{{ $t('chat.transfer.staleBannerRequery') }}
|
||||
</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-alert>
|
||||
|
||||
<div class="mb-2 flex flex-wrap items-center gap-2">
|
||||
<div class="w-56 shrink-0">
|
||||
<el-input
|
||||
@@ -189,7 +229,7 @@ function checkedTime(item: TransferMatchingItem): string {
|
||||
class="text-xs"
|
||||
data-testid="transfer-executable-table"
|
||||
>
|
||||
<el-table-column width="48" class-name="whitespace-nowrap">
|
||||
<el-table-column fixed width="48">
|
||||
<template #header>
|
||||
<el-checkbox
|
||||
size="small"
|
||||
@@ -208,52 +248,77 @@ function checkedTime(item: TransferMatchingItem): string {
|
||||
/>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colSource')" prop="source_code" min-width="110" class-name="whitespace-nowrap" />
|
||||
<el-table-column :label="$t('chat.transfer.transferTypeLabel')" min-width="140" class-name="whitespace-nowrap">
|
||||
<el-table-column :label="$t('chat.transfer.colSource')" prop="source_code" min-width="120" show-overflow-tooltip />
|
||||
<el-table-column :label="$t('chat.transfer.transferTypeLabel')" min-width="140" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<span :data-testid="`transfer-executable-type-${row.invoice_no}`">{{ typeLabel(row.transfer_type) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colInvoice')" prop="invoice_no" min-width="130" class-name="whitespace-nowrap">
|
||||
<el-table-column
|
||||
:label="$t('chat.transfer.transferPendingMatchColDocNo')"
|
||||
prop="invoice_no"
|
||||
min-width="130"
|
||||
show-overflow-tooltip
|
||||
>
|
||||
<template #default="{ row }">
|
||||
<span class="font-semibold">{{ row.invoice_no }}</span>
|
||||
<span class="font-semibold">{{ row.invoice_no || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colMovementDate')" min-width="100" class-name="whitespace-nowrap">
|
||||
<el-table-column
|
||||
:label="$t('chat.transfer.transferPendingMatchColExternalDoc')"
|
||||
min-width="130"
|
||||
show-overflow-tooltip
|
||||
>
|
||||
<template #default="{ row }">
|
||||
<span data-testid="transfer-executable-external-doc">{{ row.external_doc_no || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colMovementDate')" min-width="110" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ row.movement_date || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colMaterial')" prop="material_no" min-width="110" class-name="whitespace-nowrap" />
|
||||
<el-table-column :label="$t('chat.transfer.colName')" min-width="140">
|
||||
<template #default="{ row }">{{ row.material_name }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colFromWarehouse')" min-width="110" class-name="whitespace-nowrap">
|
||||
<template #default="{ row }">{{ row.from_warehouse }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colFromBatch')" min-width="110" class-name="whitespace-nowrap">
|
||||
<el-table-column :label="$t('chat.transfer.colMaterial')" prop="material_no" min-width="140" show-overflow-tooltip />
|
||||
<el-table-column :label="$t('chat.transfer.colName')" prop="material_name" min-width="160" show-overflow-tooltip />
|
||||
<el-table-column :label="$t('chat.transfer.colFromWarehouse')" prop="from_warehouse" min-width="110" show-overflow-tooltip />
|
||||
<el-table-column :label="$t('chat.transfer.colFromBatch')" min-width="120" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ deriveBatchNo(row.lot_no ?? '') || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colFromQty')" min-width="90" class-name="whitespace-nowrap">
|
||||
<el-table-column :label="$t('chat.transfer.colFromQty')" min-width="168" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
{{ formatQuantity(row.from_quantity) }}
|
||||
<div v-if="checkedTime(row as TransferMatchingItem)" class="text-[10px] text-muted">{{ checkedTime(row as TransferMatchingItem) }}</div>
|
||||
<span
|
||||
:class="row.stale ? 'text-amber-700' : undefined"
|
||||
:title="freshnessHint(row as TransferMatchingItem, t) || undefined"
|
||||
:data-testid="`transfer-executable-stock-${row.invoice_no}`"
|
||||
>
|
||||
{{ stockCell(row as TransferMatchingItem) }}
|
||||
</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colToWarehouse')" min-width="110" class-name="whitespace-nowrap">
|
||||
<template #default="{ row }">{{ row.to_warehouse }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colToQty')" min-width="90" class-name="whitespace-nowrap">
|
||||
<el-table-column :label="$t('chat.transfer.colToWarehouse')" prop="to_warehouse" min-width="110" show-overflow-tooltip />
|
||||
<el-table-column :label="$t('chat.transfer.colToQty')" min-width="90" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ formatQuantity(row.to_quantity) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colResult')" min-width="120">
|
||||
<el-table-column
|
||||
fixed="right"
|
||||
:label="$t('chat.transfer.colResult')"
|
||||
width="88"
|
||||
>
|
||||
<template #default="{ row }">
|
||||
<el-tag size="small" type="success" effect="light" data-testid="transfer-executable-result">
|
||||
<el-tag
|
||||
size="small"
|
||||
type="success"
|
||||
effect="light"
|
||||
:title="freshnessHint(row as TransferMatchingItem, t) || undefined"
|
||||
data-testid="transfer-executable-result"
|
||||
>
|
||||
{{ $t('chat.transfer.resultExecutable') }}
|
||||
</el-tag>
|
||||
<div v-if="row.stale" class="mt-0.5 text-[10px] text-amber-600">{{ $t('chat.transfer.staleRow') }}</div>
|
||||
<div v-else-if="row.file_current === false" class="mt-0.5 text-[10px] text-amber-600">{{ $t('chat.transfer.fileChangedRow') }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colAction')" min-width="90" class-name="whitespace-nowrap">
|
||||
<el-table-column
|
||||
fixed="right"
|
||||
:label="$t('chat.transfer.colAction')"
|
||||
width="72"
|
||||
>
|
||||
<template #default="{ row }">
|
||||
<el-button
|
||||
link
|
||||
@@ -268,7 +333,6 @@ function checkedTime(item: TransferMatchingItem): string {
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<!-- 客户端分页(单页时隐藏):文案走全局 ElConfigProvider 四语言 locale -->
|
||||
<el-pagination
|
||||
v-if="filtered.length > PAGE_SIZE"
|
||||
v-model:current-page="currentPage"
|
||||
|
||||
@@ -362,7 +362,10 @@ onMounted(async () => {
|
||||
:data-testid="`transfer-executed-items-${order.doc_no}`"
|
||||
>
|
||||
<el-table :data="order.items" size="small" class="text-xs">
|
||||
<el-table-column :label="$t('chat.transfer.colInvoice')" prop="invoice_no" min-width="120" class-name="whitespace-nowrap" />
|
||||
<el-table-column :label="$t('chat.transfer.transferPendingMatchColDocNo')" prop="invoice_no" min-width="120" class-name="whitespace-nowrap" />
|
||||
<el-table-column :label="$t('chat.transfer.transferPendingMatchColExternalDoc')" min-width="120" class-name="whitespace-nowrap">
|
||||
<template #default="{ row }">{{ row.external_doc_no || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colMaterial')" prop="material_no" min-width="110" class-name="whitespace-nowrap" />
|
||||
<el-table-column :label="$t('chat.transfer.colName')" prop="material_name" min-width="140" />
|
||||
<!-- 拨出批号展示外部形态(WTP→HOW 镜像转换,与匹配卡/可调拨明细/待办池同规则;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* features/chat/components/messages/TransferMatchCard.spec.ts
|
||||
* 用途:匹配卡顶栏「来源失败」横幅过滤——路由未解析失败只行内展示,不进顶栏。
|
||||
* 依赖:@vue/test-utils、i18n。
|
||||
* 逻辑:来源失败顶栏(sources[].error_code/error_message)防止“安静全 0”;
|
||||
* 逻辑:来源失败顶栏(sources[].error_code/error_message)防止“安静全 0”。
|
||||
* 后端分层后路由失败保持行级(result=blocked_route_not_resolved),
|
||||
* 顶栏需按 error_code 客户端排除(历史卡片回放同样生效)。
|
||||
*/
|
||||
|
||||
@@ -7,20 +7,11 @@
|
||||
busy)、i18n chat.transfer.*。
|
||||
逻辑:明细表渲染 pagedItems(filtered 经客户端分页切片);阻断项 checkbox 禁用;
|
||||
勾选键 = 明细行 item_id(历史回放行无 item_id 禁用防误选);
|
||||
库存数量下方小字透出查询时刻(checked_at);stale 行置灰 + 重查提示;
|
||||
file_current=false 行提示文件已更新(自动对齐语义);blocked_file_removed
|
||||
徽标独立文案;pending_stock_check 行徽标「待查库存」(el-tag warning);
|
||||
计数卡透出待查库存(pending_stock_check_count)/已失效(invalid_count),
|
||||
历史回放缺省按 0 展示;blocked_file_removed 行退出主视图(表格不渲染),
|
||||
表格下方折叠提示去待处理异常池处理——重查救不了已消失的行,主清单只留
|
||||
可行动项;重查范围含可恢复阻断与可执行行(重查仍按 invoice_no 提交);
|
||||
阻断原因经结果徽标 title 悬浮透出不占行高;无选择或 busy 时生成按钮禁用;
|
||||
emit execute(itemIds);来源级解析/文件失败经 sources.error_code 透出
|
||||
(防"安静全 0"),但路由未解析失败(TRANSFER.ROUTE_NOT_RESOLVED)不进顶栏
|
||||
——路由失败保持行级(result=blocked_route_not_resolved 行内展示),
|
||||
顶栏按 error_code 客户端排除,历史卡片回放同样生效;
|
||||
行定位:el-table 行不支持逐行 attr,经 row-class-name 注入
|
||||
transfer-item-<invoice_no>(spec/e2e 用类选择器等价定位);
|
||||
明细表遵循 transferItemTable(EP show-overflow-tooltip、左固定勾选、
|
||||
右固定结果/重查、单号可滚、库存数量与查询时刻同行、过期顶栏 el-alert 汇总);
|
||||
blocked_file_removed 退出主视图;重查仍按 invoice_no;emit execute(itemIds);
|
||||
来源失败顶栏排除 TRANSFER.ROUTE_NOT_RESOLVED;行定位经 row-class-name
|
||||
注入 transfer-item-<invoice_no>;
|
||||
[2026-10-12 单据数口径修正] 预计 ERP 单据数(计数卡=全部可执行行、
|
||||
生成按钮旁=勾选可执行行)按执行建单五元组 (external_org, source_code,
|
||||
movement_date, from_warehouse, to_warehouse) 去重实时计算(与后端
|
||||
@@ -49,7 +40,10 @@ import {
|
||||
import type { CheckboxValueType } from 'element-plus';
|
||||
import { deriveBatchNo } from './transferBatch';
|
||||
import { formatQuantity } from './transferFormat';
|
||||
import { parseApiUtcDate } from '@/shared/utils/dateTime';
|
||||
import {
|
||||
formatStockQuantityCell,
|
||||
freshnessHint,
|
||||
} from './transferItemTable';
|
||||
import type { TransferMatchingItem, TransferMatchingSummary, TransferSourceProgress } from '../../types/transfer.types';
|
||||
|
||||
const { t } = useI18n();
|
||||
@@ -129,7 +123,7 @@ const filtered = computed(() =>
|
||||
if (isFileRemoved(item)) return false;
|
||||
const kw = keyword.value.trim().toLowerCase();
|
||||
if (kw) {
|
||||
const haystack = [item.material_no, item.material_name, item.invoice_no, item.lot_no]
|
||||
const haystack = [item.material_no, item.material_name, item.invoice_no, item.external_doc_no, item.lot_no]
|
||||
.map((value) => String(value ?? '').toLowerCase());
|
||||
if (!haystack.some((value) => value.includes(kw))) return false;
|
||||
}
|
||||
@@ -179,6 +173,22 @@ function requerySelected(): void {
|
||||
if (nos.length) emit('requery', nos);
|
||||
}
|
||||
|
||||
/** 当前筛选下库存已过期且可重查的单号。 */
|
||||
const staleInvoiceNos = computed(() =>
|
||||
filtered.value
|
||||
.filter((item) => item.stale === true && isRequeryable(item))
|
||||
.map((item) => item.invoice_no),
|
||||
);
|
||||
|
||||
/**
|
||||
* 批量重查当前筛选下全部过期行。
|
||||
* 核心逻辑:顶栏汇总入口,避免结果列刷长文案。
|
||||
*/
|
||||
function requeryStaleRows(): void {
|
||||
if (!staleInvoiceNos.value.length) return;
|
||||
emit('requery', [...staleInvoiceNos.value]);
|
||||
}
|
||||
|
||||
function isChecked(item: TransferMatchingItem): boolean {
|
||||
return item.item_id != null && props.selected.has(item.item_id);
|
||||
}
|
||||
@@ -217,18 +227,11 @@ const estimatedDocumentCountSelected = computed(
|
||||
);
|
||||
|
||||
/**
|
||||
* 库存查询时刻小字(HH:mm);后端 naive ISO 按 UTC 解析后转浏览器本地时区
|
||||
* (仓库约定 parseApiUtcDate,2026-09-29 修复 UTC+8 展示异常);
|
||||
* 无效/缺省 checked_at 返回 null 不渲染。
|
||||
* @param item 匹配明细行;checked_at 为后端 ISO 时间
|
||||
* 库存数量单元格:数量与完整查询时刻同一行。
|
||||
* @param item 匹配明细行
|
||||
*/
|
||||
function checkedAtLabel(item: TransferMatchingItem): string | null {
|
||||
if (!item.checked_at) return null;
|
||||
const date = parseApiUtcDate(item.checked_at);
|
||||
if (Number.isNaN(date.getTime())) return null;
|
||||
const hh = String(date.getHours()).padStart(2, '0');
|
||||
const mm = String(date.getMinutes()).padStart(2, '0');
|
||||
return `${hh}:${mm}`;
|
||||
function stockCell(item: TransferMatchingItem): string {
|
||||
return formatStockQuantityCell(formatQuantity(item.from_quantity), item.checked_at);
|
||||
}
|
||||
|
||||
function resultLabel(result: string): string {
|
||||
@@ -348,6 +351,30 @@ function rowClassName({ row }: { row: TransferMatchingItem }): string {
|
||||
</div>
|
||||
</el-alert>
|
||||
|
||||
<el-alert
|
||||
v-if="staleInvoiceNos.length"
|
||||
type="warning"
|
||||
:closable="false"
|
||||
class="mb-3"
|
||||
data-testid="transfer-match-stale-banner"
|
||||
>
|
||||
<template #title>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span>{{ $t('chat.transfer.staleBanner', { count: staleInvoiceNos.length }) }}</span>
|
||||
<el-button
|
||||
link
|
||||
type="primary"
|
||||
size="small"
|
||||
:disabled="props.requeryBusy"
|
||||
data-testid="transfer-match-requery-stale"
|
||||
@click="requeryStaleRows"
|
||||
>
|
||||
{{ $t('chat.transfer.staleBannerRequery') }}
|
||||
</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-alert>
|
||||
|
||||
<div class="mb-2 flex flex-wrap items-center gap-2">
|
||||
<div class="w-56 shrink-0">
|
||||
<el-input
|
||||
@@ -383,8 +410,7 @@ function rowClassName({ row }: { row: TransferMatchingItem }): string {
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
<!-- EP 表格壳:横向滚动由 el-table 内建(列 min-width 撑开);无行动行时不挂表;
|
||||
表体只挂当前页切片(pagedItems),全量集合仍在 filtered 供筛选/全选/计数 -->
|
||||
<!-- EP 表格:show-overflow-tooltip + 左右固定列;表体仅当前页切片 -->
|
||||
<el-table
|
||||
v-if="filtered.length"
|
||||
:data="pagedItems"
|
||||
@@ -394,7 +420,7 @@ function rowClassName({ row }: { row: TransferMatchingItem }): string {
|
||||
class="text-xs"
|
||||
data-testid="transfer-match-table"
|
||||
>
|
||||
<el-table-column width="48" class-name="whitespace-nowrap">
|
||||
<el-table-column fixed width="48">
|
||||
<template #header>
|
||||
<el-checkbox
|
||||
size="small"
|
||||
@@ -413,49 +439,57 @@ function rowClassName({ row }: { row: TransferMatchingItem }): string {
|
||||
/>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colSource')" prop="source_code" min-width="110" class-name="whitespace-nowrap" />
|
||||
<el-table-column :label="$t('chat.transfer.colInvoice')" prop="invoice_no" min-width="130" class-name="whitespace-nowrap">
|
||||
<el-table-column :label="$t('chat.transfer.colSource')" prop="source_code" min-width="120" show-overflow-tooltip />
|
||||
<el-table-column
|
||||
:label="$t('chat.transfer.transferPendingMatchColDocNo')"
|
||||
prop="invoice_no"
|
||||
min-width="130"
|
||||
show-overflow-tooltip
|
||||
>
|
||||
<template #default="{ row }">
|
||||
<span class="font-semibold">{{ row.invoice_no }}</span>
|
||||
<span class="font-semibold">{{ row.invoice_no || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colMovementDate')" min-width="100" class-name="whitespace-nowrap">
|
||||
<el-table-column
|
||||
:label="$t('chat.transfer.transferPendingMatchColExternalDoc')"
|
||||
min-width="130"
|
||||
show-overflow-tooltip
|
||||
>
|
||||
<template #default="{ row }">
|
||||
<span data-testid="transfer-match-external-doc">{{ row.external_doc_no || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colMovementDate')" min-width="110" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ row.movement_date || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colMaterial')" prop="material_no" min-width="110" class-name="whitespace-nowrap" />
|
||||
<el-table-column :label="$t('chat.transfer.colName')" min-width="140">
|
||||
<template #default="{ row }">{{ row.material_name }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colFromWarehouse')" min-width="110" class-name="whitespace-nowrap">
|
||||
<template #default="{ row }">{{ row.from_warehouse }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colFromBatch')" min-width="110" class-name="whitespace-nowrap">
|
||||
<el-table-column :label="$t('chat.transfer.colMaterial')" prop="material_no" min-width="140" show-overflow-tooltip />
|
||||
<el-table-column :label="$t('chat.transfer.colName')" prop="material_name" min-width="160" show-overflow-tooltip />
|
||||
<el-table-column :label="$t('chat.transfer.colFromWarehouse')" prop="from_warehouse" min-width="110" show-overflow-tooltip />
|
||||
<el-table-column :label="$t('chat.transfer.colFromBatch')" min-width="120" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ deriveBatchNo(row.lot_no) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colFromQty')" min-width="90" class-name="whitespace-nowrap">
|
||||
<el-table-column :label="$t('chat.transfer.colFromQty')" min-width="168" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<div>{{ formatQuantity(row.from_quantity) }}</div>
|
||||
<!-- 库存查询时刻小字:数据新鲜度溯源(stale 门禁的可见依据) -->
|
||||
<div
|
||||
v-if="checkedAtLabel(row as TransferMatchingItem)"
|
||||
class="text-[10px] text-muted"
|
||||
:title="$t('chat.transfer.stockCheckedAtTitle', { time: checkedAtLabel(row as TransferMatchingItem) })"
|
||||
<span
|
||||
:class="row.stale === true ? 'text-amber-700' : undefined"
|
||||
:title="freshnessHint(row as TransferMatchingItem, t) || undefined"
|
||||
:data-testid="`transfer-checked-at-${row.invoice_no}`"
|
||||
>
|
||||
{{ checkedAtLabel(row as TransferMatchingItem) }}
|
||||
</div>
|
||||
{{ stockCell(row as TransferMatchingItem) }}
|
||||
</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colToWarehouse')" min-width="110" class-name="whitespace-nowrap">
|
||||
<template #default="{ row }">{{ row.to_warehouse }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colToQty')" min-width="90" class-name="whitespace-nowrap">
|
||||
<el-table-column :label="$t('chat.transfer.colToWarehouse')" prop="to_warehouse" min-width="110" show-overflow-tooltip />
|
||||
<el-table-column :label="$t('chat.transfer.colToQty')" min-width="90" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ formatQuantity(row.to_quantity) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colResult')" min-width="200">
|
||||
<el-table-column
|
||||
fixed="right"
|
||||
:label="$t('chat.transfer.colResult')"
|
||||
width="200"
|
||||
>
|
||||
<template #default="{ row }">
|
||||
<div class="flex flex-wrap items-center gap-1">
|
||||
<!-- 阻断原因经悬浮提示(title)透出:不占行高;可执行行也提供重查入口 -->
|
||||
<div class="flex flex-nowrap items-center gap-1">
|
||||
<el-tag
|
||||
size="small"
|
||||
effect="light"
|
||||
@@ -465,24 +499,25 @@ function rowClassName({ row }: { row: TransferMatchingItem }): string {
|
||||
>
|
||||
{{ $t(resultLabel(row.result)) }}
|
||||
</el-tag>
|
||||
<!-- 行级警示小标:stale(仅展示提示,不拦截执行——2026-09-25 TTL 退役)/ 文件版本已过期 -->
|
||||
<el-tag
|
||||
v-if="row.stale === true"
|
||||
size="small"
|
||||
type="warning"
|
||||
effect="plain"
|
||||
:title="$t('chat.transfer.staleRow')"
|
||||
data-testid="transfer-item-stale"
|
||||
>
|
||||
{{ $t('chat.transfer.staleRow') }}
|
||||
{{ $t('chat.transfer.staleShort') }}
|
||||
</el-tag>
|
||||
<el-tag
|
||||
v-if="row.file_current === false"
|
||||
size="small"
|
||||
type="warning"
|
||||
effect="plain"
|
||||
:title="$t('chat.transfer.fileChangedRow')"
|
||||
data-testid="transfer-item-file-changed"
|
||||
>
|
||||
{{ $t('chat.transfer.fileChangedRow') }}
|
||||
{{ $t('chat.transfer.fileChangedShort') }}
|
||||
</el-tag>
|
||||
<el-button
|
||||
v-if="isRequeryable(row as TransferMatchingItem)"
|
||||
|
||||
@@ -403,9 +403,12 @@ async function confirmCloseOrder() {
|
||||
<!-- 行明细常驻展开(物料 × 批号聚合行;Invoice 首列对齐可调拨明细列序) -->
|
||||
<div class="border-t border-subtle px-3 py-2" :data-testid="`transfer-order-lines-${order.doc_no}`">
|
||||
<el-table :data="order.lines" size="small" class="text-xs">
|
||||
<el-table-column :label="$t('chat.transfer.colInvoice')" min-width="110">
|
||||
<el-table-column :label="$t('chat.transfer.transferPendingMatchColDocNo')" min-width="110">
|
||||
<template #default="{ row }">{{ row.invoice_no || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.transferPendingMatchColExternalDoc')" min-width="120">
|
||||
<template #default="{ row }">{{ row.external_doc_no || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('chat.transfer.colMaterial')" prop="material_no" min-width="110" />
|
||||
<el-table-column :label="$t('chat.transfer.colName')" prop="material_name" min-width="120" />
|
||||
<el-table-column :label="$t('chat.transfer.colFromBatch')" min-width="100">
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
* 确认门禁=所选类型每条流都是 ready 或 no_data;混合选择先披露未就绪流再确认;
|
||||
* 抓取中与未配置不渲染重试,其余状态可重试(ready 亦可强制重抓);
|
||||
* 证据清单默认只显示最新一份,更早点开后才列出;首行「重新解析」走 reparseCurrentFile,不 emit retry;
|
||||
单文件下载走 downloadEvidenceFile,不再把预签名地址放进 href;
|
||||
* 类型选项=props.transferTypes 接口真相(enabled 过滤与排序在后端契约内,
|
||||
* 前端不过滤),名称 names[locale]→zh-CN→en→code 回退,空列表空态+确认禁用。
|
||||
*/
|
||||
@@ -18,6 +19,7 @@ import i18n from '@/i18n';
|
||||
|
||||
const transferApiMocks = vi.hoisted(() => ({
|
||||
listEvidenceFiles: vi.fn(),
|
||||
downloadEvidenceFile: vi.fn(),
|
||||
reparseCurrentFile: vi.fn(),
|
||||
}));
|
||||
vi.mock('../../api/transfer.api', () => transferApiMocks);
|
||||
@@ -452,7 +454,7 @@ describe('TransferSourceSelectCard', () => {
|
||||
expect(list.text()).not.toContain('TRIG-BATCH');
|
||||
expect(list.get('p').attributes('title')).toContain('outbound_TRIG-BATCH-A629464D_DBS-AWSBI_NA_20261021101739.xlsx');
|
||||
expect(list.get('p').attributes('title')).toContain('2026-10-21 18:00');
|
||||
expect(wrapper.get('[data-testid="transfer-evidence-download-25"]').attributes('href')).toBe('https://files.example/current?filename=DBS-AWSBI_20261021_1800.xlsx');
|
||||
expect(wrapper.get('[data-testid="transfer-evidence-download-25"]').attributes('href')).toBeUndefined();
|
||||
expect(wrapper.text()).not.toContain('older.xlsx');
|
||||
expect(wrapper.text()).not.toContain('abc');
|
||||
const buttons = wrapper.findAll('[data-testid="transfer-evidence-reparse-DBS-AWSBI-inbound"]');
|
||||
@@ -468,6 +470,23 @@ describe('TransferSourceSelectCard', () => {
|
||||
expect(wrapper.emitted('reparsed')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('点击下载走站点接口,不打开预签名地址', async () => {
|
||||
// [断言意图] 下载按钮不再带 MinIO href;点击后按来源、文件和记录类型请求当前站点。
|
||||
transferApiMocks.listEvidenceFiles.mockResolvedValue([
|
||||
{ file_id: 25, original_filename: 'CRANE.xlsx', created_at: '2026-10-26T07:00:00', sha256: 'abc', file_size: 10, presigned_url: 'http://192.168.100.192:9000/file', download_url: 'http://192.168.100.192:9000/file?filename=CRANE.xlsx' },
|
||||
]);
|
||||
transferApiMocks.downloadEvidenceFile.mockResolvedValue({ blob: new Blob(['xlsx']), filename: 'DBS-AWSBI_20261026_1500.xlsx' });
|
||||
const wrapper = mount(TransferSourceSelectCard, {
|
||||
props: { sources: readySources, transferTypes: defaultTransferTypes },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await wrapper.find('[data-testid="transfer-source-status-DBS-AWSBI"]').trigger('click');
|
||||
await flushPromises();
|
||||
await wrapper.get('[data-testid="transfer-evidence-download-25"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(transferApiMocks.downloadEvidenceFile).toHaveBeenCalledWith('DBS-AWSBI', 25, 'inbound');
|
||||
});
|
||||
|
||||
it('按所选类型的 record_kinds 绘制证据流芯片,抓取中无重试,下载按钮为证据文件', async () => {
|
||||
// [断言意图] 方案 A:状态芯片与重试钮分离。hub_to_hub 两种流各一枚芯片;
|
||||
// 出站抓取中无 ↻;入站 ↻ 的 aria-label 为「重试入站」。切回只含 inbound 时不出现「出站」。
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
ElCheckbox(2026-10-20:类型/日期/勾选一并 EP 化;规格改断言 is-active /
|
||||
ElDatePicker modelValue / checkbox 内层 input)、
|
||||
props.sources(含 streams)、props.transferTypes(含 record_kinds)、
|
||||
listEvidenceFiles、reparseCurrentFile、i18n chat.transfer.*。
|
||||
listEvidenceFiles、downloadEvidenceFile、reparseCurrentFile、i18n chat.transfer.*。
|
||||
逻辑:匹配参数区(调拨类型 + 异动日期,确认时一并提交)→ 选择辅助/上下文操作条
|
||||
(有选中时原位替换辅助区,承载一次批量重试/下载证据文件/清空选择)→
|
||||
平台分组来源列表(只画当前类型 record_kinds 里的证据流)→
|
||||
@@ -15,6 +15,7 @@
|
||||
(来源编码 + 入站/出站 + 状态)再提交可匹配来源;
|
||||
行态为方案 A:状态芯片(边框 + ▾/▴,点开当天证据清单)与独立描边 ↻ 钮分隔;
|
||||
清单默认只显示最新一份,一行放下文件名、短时间和操作,更早的当天归档点开才列出;
|
||||
单文件预览和下载都走站点接口再触发一次 blob 保存,不新开 HTTP MinIO 标签;
|
||||
抓取中与未配置不渲染 ↻;调拨类型选项=接口下发数据,名称按
|
||||
names[locale]→zh-CN→en→code 回退;配置为空渲染空态且确认禁用;缺省选中接口列表首项。
|
||||
-->
|
||||
@@ -31,7 +32,8 @@ import {
|
||||
} from 'element-plus';
|
||||
import type { CheckboxValueType } from 'element-plus';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { listEvidenceFiles, reparseCurrentFile } from '../../api/transfer.api';
|
||||
import { triggerBlobDownload } from '@/shared/utils/download';
|
||||
import { downloadEvidenceFile, listEvidenceFiles, reparseCurrentFile } from '../../api/transfer.api';
|
||||
import { defaultMovementDate, formatShanghaiDateTime, formatShanghaiMonthDayTime } from './transferDate';
|
||||
import type {
|
||||
TransferEvidenceFile,
|
||||
@@ -193,6 +195,7 @@ watch(openEvidenceKey, () => {
|
||||
const evidenceByKey = ref<Record<string, TransferEvidenceFile[]>>({});
|
||||
/** 正在执行当前文件重解析的证据流键(source:recordKind),用于禁用对应按钮 */
|
||||
const reparsingKey = ref<string | null>(null);
|
||||
const downloadingEvidenceId = ref<number | null>(null);
|
||||
/** 清单未加载时复用同一空数组,避免模板里每次渲染 new [] 触发递归更新。 */
|
||||
const NO_EVIDENCE_FILES: TransferEvidenceFile[] = [];
|
||||
|
||||
@@ -414,6 +417,31 @@ async function reparseEvidence(sourceCode: string, recordKind: TransferRecordKin
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载或预览清单中的一份证据文件。
|
||||
* 核心逻辑:向当前站点要文件字节,再用 a[download] 保存。
|
||||
* xlsx 无法在浏览器里打开。页面是 HTTPS、MinIO 是 HTTP 时,新开标签会被立刻关掉。
|
||||
* @param sourceCode - 来源实例编码
|
||||
* @param recordKind - inbound 或 outbound
|
||||
* @param file - 清单中的一条归档
|
||||
* @returns 无;失败时弹出错误
|
||||
*/
|
||||
async function downloadEvidence(
|
||||
sourceCode: string,
|
||||
recordKind: TransferRecordKind,
|
||||
file: TransferEvidenceFile,
|
||||
): Promise<void> {
|
||||
downloadingEvidenceId.value = file.file_id;
|
||||
try {
|
||||
const result = await downloadEvidenceFile(sourceCode, file.file_id, recordKind);
|
||||
triggerBlobDownload(result.blob, result.filename || evidenceLabel(file, sourceCode));
|
||||
} catch (err) {
|
||||
notifyError(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
downloadingEvidenceId.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 行内短文件名,对齐排程压缩包条目。
|
||||
* 核心逻辑:包内条目是 `{序号}_{来源}.xlsx`,序号只保证同一压缩包不重名。
|
||||
@@ -903,19 +931,19 @@ watch(selectedRecordKinds, () => {
|
||||
:data-testid="`transfer-evidence-reparse-${source.source_code}-${stream.record_kind}`"
|
||||
@click="reparseEvidence(source.source_code, stream.record_kind)"
|
||||
>{{ t('chat.transfer.reparseCurrentFile') }}</button>
|
||||
<a
|
||||
:href="file.presigned_url"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="font-bold text-brand-700"
|
||||
>{{ t('chat.transfer.previewEvidence') }}</a>
|
||||
<a
|
||||
:href="file.download_url"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="font-bold text-brand-700"
|
||||
<button
|
||||
type="button"
|
||||
class="font-bold text-brand-700 disabled:opacity-50"
|
||||
:disabled="downloadingEvidenceId === file.file_id"
|
||||
@click="downloadEvidence(source.source_code, stream.record_kind, file)"
|
||||
>{{ t('chat.transfer.previewEvidence') }}</button>
|
||||
<button
|
||||
type="button"
|
||||
class="font-bold text-brand-700 disabled:opacity-50"
|
||||
:disabled="downloadingEvidenceId === file.file_id"
|
||||
:data-testid="`transfer-evidence-download-${file.file_id}`"
|
||||
>{{ t('chat.transfer.downloadEvidence') }}</a>
|
||||
@click="downloadEvidence(source.source_code, stream.record_kind, file)"
|
||||
>{{ t('chat.transfer.downloadEvidence') }}</button>
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
|
||||
@@ -108,15 +108,17 @@ describe('TransferMatchCard', () => {
|
||||
expect(wrapper.find('.transfer-item-INV-001').text()).toContain('HOW26082728');
|
||||
});
|
||||
|
||||
it('库存数量下方小字展示查询时刻(HH:mm)', async () => {
|
||||
it('库存数量与完整查询时刻同一行(数量 · YYYY-MM-DD HH:mm)', async () => {
|
||||
// [断言意图] 数量与时刻同行,避免第二行撑高整表;完整日期才能判断新旧。
|
||||
const wrapper = await mountMatchCard({ summary, items, selected: new Set<number>() });
|
||||
const cell = wrapper.find('[data-testid="transfer-checked-at-INV-001"]');
|
||||
expect(cell.exists()).toBe(true);
|
||||
expect(cell.text()).toMatch(/^\d{2}:\d{2}$/);
|
||||
expect(wrapper.find('[data-testid="transfer-checked-at-INV-041"]').exists()).toBe(false);
|
||||
expect(cell.text()).toBe('1200 · 2026-09-23 09:05');
|
||||
// [断言意图] 无查询时刻时仍单行只显示数量,不拆第二行。
|
||||
expect(wrapper.find('[data-testid="transfer-checked-at-INV-041"]').text()).not.toContain('·');
|
||||
});
|
||||
|
||||
it('stale 行置灰 + 重查小标;file_current=false 行展示文件更新小标', async () => {
|
||||
it('stale 行置灰 + 短徽标;file_current=false 行展示文件更新短徽标;顶栏汇总过期', async () => {
|
||||
const flaggedItems = [
|
||||
{ ...items[0], stale: true, file_current: false },
|
||||
];
|
||||
@@ -124,8 +126,12 @@ describe('TransferMatchCard', () => {
|
||||
// [断言意图] el-table 行类经 row-class-name 注入 opacity-60。
|
||||
const row = wrapper.find('.transfer-item-INV-001');
|
||||
expect(row.classes()).toContain('opacity-60');
|
||||
expect(wrapper.find('[data-testid="transfer-item-stale"]').text()).toContain('重查');
|
||||
expect(wrapper.find('[data-testid="transfer-item-file-changed"]').text()).toContain('自动对齐');
|
||||
// [断言意图] 长句只放悬停;行内只留短徽标;顶栏 el-alert 汇总可批量重查。
|
||||
expect(wrapper.find('[data-testid="transfer-item-stale"]').text()).toContain('已过期');
|
||||
expect(wrapper.find('[data-testid="transfer-item-stale"]').attributes('title')).toContain('重查');
|
||||
expect(wrapper.find('[data-testid="transfer-item-file-changed"]').text()).toContain('文件更新');
|
||||
expect(wrapper.find('[data-testid="transfer-item-file-changed"]').attributes('title')).toContain('自动对齐');
|
||||
expect(wrapper.find('[data-testid="transfer-match-stale-banner"]').text()).toContain('1');
|
||||
});
|
||||
|
||||
it('计数卡透出待查库存/已失效计数;历史 payload 缺省按 0 展示', async () => {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* features/chat/components/messages/transferItemTable.spec.ts
|
||||
* 用途:锁住明细表库存单元格与新鲜度提示的统一格式。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
formatStockCheckedAt,
|
||||
formatStockQuantityCell,
|
||||
freshnessHint,
|
||||
} from './transferItemTable';
|
||||
|
||||
describe('transferItemTable', () => {
|
||||
it('完整查询时刻为上海时区 YYYY-MM-DD HH:mm', () => {
|
||||
// [断言意图] +08:00 墙钟原样保留;无时区 naive 按 UTC 再转上海。
|
||||
expect(formatStockCheckedAt('2026-09-23T09:05:00+08:00')).toBe('2026-09-23 09:05');
|
||||
expect(formatStockCheckedAt('2026-10-22T02:57:00')).toBe('2026-10-22 10:57');
|
||||
expect(formatStockCheckedAt('')).toBe('');
|
||||
});
|
||||
|
||||
it('库存单元格数量与时刻同一行', () => {
|
||||
// [断言意图] 禁止拆成两行撑高表格。
|
||||
expect(formatStockQuantityCell('30', '2026-10-20T10:38:00+08:00')).toBe('30 · 2026-10-20 10:38');
|
||||
expect(formatStockQuantityCell('30', null)).toBe('30');
|
||||
});
|
||||
|
||||
it('新鲜度悬停过期优先于文件更新', () => {
|
||||
const t = (key: string) => key;
|
||||
expect(freshnessHint({ stale: true, file_current: false }, t)).toBe('chat.transfer.staleRow');
|
||||
expect(freshnessHint({ stale: false, file_current: false }, t)).toBe('chat.transfer.fileChangedRow');
|
||||
expect(freshnessHint({}, t)).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* features/chat/components/messages/transferItemTable.ts
|
||||
* 用途:在途调拨明细表(可调拨 / 匹配 / 待恢复)的统一展示约定与单元格格式化。
|
||||
* 依赖:transferDate.formatShanghaiDateTime、i18n chat.transfer.*。
|
||||
* 逻辑:三卡共用 Element Plus 密度规则,禁止各卡各自叠第二行或放任折行。
|
||||
*
|
||||
* Element Plus 约定:
|
||||
* 1. 长文本列 show-overflow-tooltip;不够宽就横向滚,不折行。
|
||||
* 2. 左只固定勾选,右固定结果/操作;单号随表横滚(不钉死,避免挤窄中间区)。
|
||||
* 3. 库存数量与查询时刻同一行:「数量 · YYYY-MM-DD HH:mm」。
|
||||
* 4. 过期不占结果列长文;顶栏 el-alert 汇总 + 批量重查。
|
||||
*/
|
||||
|
||||
import { formatShanghaiDateTime } from './transferDate';
|
||||
|
||||
const CHECKED_AT_RE = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/;
|
||||
|
||||
/**
|
||||
* 把后端库存查得时刻格式成上海时区完整墙钟。
|
||||
* @param checkedAt - 后端 ISO(可空)
|
||||
* @returns `YYYY-MM-DD HH:mm`;无法解析则空串
|
||||
*/
|
||||
export function formatStockCheckedAt(checkedAt: string | null | undefined): string {
|
||||
if (!checkedAt) return '';
|
||||
const label = formatShanghaiDateTime(checkedAt);
|
||||
return CHECKED_AT_RE.test(label) ? label : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 库存数量单元格主文案:数量与查询时刻同一行。
|
||||
* @param quantityLabel - 已格式化的数量文本
|
||||
* @param checkedAt - 后端 ISO
|
||||
* @returns 如 `30 · 2026-10-20 18:38`;无时刻则仅数量
|
||||
*/
|
||||
export function formatStockQuantityCell(
|
||||
quantityLabel: string,
|
||||
checkedAt: string | null | undefined,
|
||||
): string {
|
||||
const when = formatStockCheckedAt(checkedAt);
|
||||
return when ? `${quantityLabel} · ${when}` : quantityLabel;
|
||||
}
|
||||
|
||||
export interface TransferFreshnessRow {
|
||||
stale?: boolean;
|
||||
file_current?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 行新鲜度悬停说明(过期优先于文件更新)。
|
||||
* @param row - 带 stale / file_current 的明细行
|
||||
* @param t - vue-i18n t
|
||||
* @returns 悬停全文;无提示时空串
|
||||
*/
|
||||
export function freshnessHint(
|
||||
row: TransferFreshnessRow,
|
||||
t: (key: string) => string,
|
||||
): string {
|
||||
if (row.stale) return t('chat.transfer.staleRow');
|
||||
if (row.file_current === false) return t('chat.transfer.fileChangedRow');
|
||||
return '';
|
||||
}
|
||||
@@ -77,6 +77,8 @@ export interface TransferMatchingItem {
|
||||
material_name: string;
|
||||
specification: string;
|
||||
invoice_no: string;
|
||||
/** 档上的外部单号;没有则为空,列表显示占位 */
|
||||
external_doc_no?: string;
|
||||
/** 明细异动日期(Task 3 序列化键更名,明细 movement 语义;旧名见 git 历史) */
|
||||
movement_date?: string | null;
|
||||
from_warehouse: string;
|
||||
@@ -164,8 +166,10 @@ export type TransferOrderStatus = 'pending' | 'executing' | 'success' | 'duplica
|
||||
|
||||
/** 单内行(ERP 写入行粒度聚合:物料+批号;quantity 为 6 位小数字符串,与 D14 快照口径一致) */
|
||||
export interface TransferOrderLine {
|
||||
/** 行级溯源入站通知号(2026-09-29 契约扩充;一行恒对应一张 invoice,旧 payload 缺省) */
|
||||
/** 行级溯源单号(档 doc_no;旧 payload 缺省) */
|
||||
invoice_no?: string;
|
||||
/** 档上的外部单号;聚合行内多个单号以逗号连接,旧 payload 缺省 */
|
||||
external_doc_no?: string;
|
||||
material_no: string;
|
||||
material_name: string;
|
||||
lot_no: string;
|
||||
@@ -218,6 +222,8 @@ export interface TransferBacklogItem {
|
||||
item_id: number;
|
||||
source_code: string;
|
||||
invoice_no: string;
|
||||
/** 档上的外部单号;没有则为空 */
|
||||
external_doc_no?: string;
|
||||
material_no: string;
|
||||
status: string;
|
||||
reason: string;
|
||||
@@ -388,6 +394,8 @@ export interface TransferOrderGroups {
|
||||
*/
|
||||
export interface TransferExecutedOrderItem {
|
||||
invoice_no: string;
|
||||
/** 档上的外部单号;没有则为空 */
|
||||
external_doc_no?: string;
|
||||
material_no: string;
|
||||
material_name: string;
|
||||
lot_no: string;
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
getWorkspaceShippingFreightNoticeGroups,
|
||||
batchConfirmWorkspaceShippingNoticesUploaded,
|
||||
batchStartWorkspaceShippingNoticeRpaUpload,
|
||||
refreshWorkspaceCraneUploadStatus,
|
||||
retryWorkspaceShippingOrderStpAutoCreate,
|
||||
retryShippingNoticeIntake,
|
||||
decideWorkspaceShippingOrderReviewLineFulfillment,
|
||||
@@ -2542,7 +2543,7 @@ const freightNoticeGroupsLoadFailed = ref(false);
|
||||
/** 货代上传分组请求在途守卫:独立于 loading,避免轮询 tick 与动作后刷新并发重载。 */
|
||||
const freightGroupsInFlight = ref(false);
|
||||
const selectedFreightBusinessNos = ref<string[]>([]);
|
||||
const freightBatchBusy = ref<'download' | 'confirm' | 'rpa' | 'regenerate' | null>(null);
|
||||
const freightBatchBusy = ref<'download' | 'confirm' | 'rpa' | 'regenerate' | 'refresh' | null>(null);
|
||||
/**
|
||||
* 判断货代通知聚合行是否已具备上传成功事实。
|
||||
* 核心逻辑:聚合接口 upload_status 已经过后端 project_notice_upload_status 归一,
|
||||
@@ -3459,7 +3460,7 @@ watch(
|
||||
function hasFreightGroupsInFlightRpa(groups: ShippingFreightNoticeGroup[]): boolean {
|
||||
return (groups || []).some((group) => {
|
||||
const st = String(group.upload_status || '').trim().toLowerCase();
|
||||
return st === 'uploading';
|
||||
return st === 'uploading' || st === 'allocating';
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3524,14 +3525,35 @@ function toggleFreightNoticeSelection(businessNo: string, checked: boolean) {
|
||||
: selectedFreightBusinessNos.value.filter((item) => item !== businessNo);
|
||||
}
|
||||
|
||||
/** 已选通知单中任一已上传时,批量写入动作必须 fail-closed,避免重复提交成功通知。 */
|
||||
/** 已选通知单中任一已上传或仍在 Crane 分配中时,批量写入动作必须停住,避免重复上传。 */
|
||||
const selectedFreightNoticesContainUploaded = computed(() => {
|
||||
const selected = new Set(selectedFreightBusinessNos.value);
|
||||
return freightNoticeGroups.value.some((group) => (
|
||||
selected.has(group.business_no) && isFreightNoticeUploaded(group)
|
||||
selected.has(group.business_no)
|
||||
&& (isFreightNoticeUploaded(group) || String(group.upload_status || '').trim().toLowerCase() === 'allocating')
|
||||
));
|
||||
});
|
||||
|
||||
/**
|
||||
* 手动刷新一张仍在分配中的 Crane 发货单。
|
||||
* @param businessNo - 发货通知单号,即 Pull Request #
|
||||
*/
|
||||
async function refreshCraneUploadStatus(businessNo: string) {
|
||||
if (freightBatchBusy.value) return;
|
||||
freightBatchBusy.value = 'refresh';
|
||||
try {
|
||||
await refreshWorkspaceCraneUploadStatus(businessNo);
|
||||
const taskNo = String(confirmedNoticeTaskNo.value || '').trim();
|
||||
if (taskNo) await loadFreightNoticeGroups(taskNo);
|
||||
freightNoticeGroupsFinalized = false;
|
||||
startWorkflowProgressPolling();
|
||||
} catch (error) {
|
||||
msg.warning(error instanceof Error ? error.message : t('chat.shippingOrderReview.workbench.resultNotReady'));
|
||||
} finally {
|
||||
freightBatchBusy.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadFreightNotice(businessNo: string) {
|
||||
try {
|
||||
await downloadWorkspaceShippingNoticeExcelFile(businessNo);
|
||||
@@ -3824,13 +3846,21 @@ function freightLineNoDisplay(line: { line_no?: string | number | null }): {
|
||||
* @param group - 当前发货通知单聚合行(含 upload_status 与逐单错误字段)。
|
||||
*/
|
||||
function freightUploadStatusDisplay(group: ShippingFreightNoticeGroup): {
|
||||
state: 'uploaded' | 'uploading' | 'failed' | 'needs_human' | 'pending';
|
||||
state: 'uploaded' | 'uploading' | 'allocating' | 'failed' | 'needs_human' | 'pending';
|
||||
label: string;
|
||||
chipClass: string;
|
||||
reason: string | null;
|
||||
} {
|
||||
const status = String(group.upload_status || '').trim().toLowerCase();
|
||||
const reason = group.upload_error_message || group.upload_error_code || null;
|
||||
if (status === 'allocating') {
|
||||
return {
|
||||
state: 'allocating',
|
||||
label: t('chat.shippingOrderReview.lifecycle.freightUpload.uploadStatus.allocating'),
|
||||
chipClass: 'bg-amber-100 text-amber-800 dark:bg-amber-950/50 dark:text-amber-200',
|
||||
reason: null,
|
||||
};
|
||||
}
|
||||
if (status === 'uploaded') {
|
||||
return {
|
||||
state: 'uploaded',
|
||||
@@ -5496,7 +5526,15 @@ watch(
|
||||
<span :class="freightUploadStatusDisplay(group).chipClass" :title="freightUploadStatusDisplay(group).reason || undefined" class="rounded-full px-2 py-0.5 font-medium cursor-help" tabindex="0">{{ freightUploadStatusDisplay(group).label }}</span>
|
||||
<button type="button" class="rounded border border-brand-200 px-2 py-1 font-medium text-brand-700 hover:bg-brand-50" data-testid="review-freight-upload-download" :disabled="saving" @click="void downloadFreightNotice(group.business_no)">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.download') }}</button>
|
||||
<button
|
||||
v-if="canRunFreightNoticeAction(group, 'retry_freight_upload_rpa')"
|
||||
v-if="freightUploadStatusDisplay(group).state === 'allocating'"
|
||||
type="button"
|
||||
class="rounded border border-default px-2 py-1 font-medium text-primary hover:bg-surface-muted disabled:opacity-50"
|
||||
data-testid="review-freight-upload-refresh"
|
||||
:disabled="freightBatchBusy !== null"
|
||||
@click="void refreshCraneUploadStatus(group.business_no)"
|
||||
>{{ t('chat.shippingOrderReview.lifecycle.freightUpload.refreshStatus') }}</button>
|
||||
<button
|
||||
v-if="canRunFreightNoticeAction(group, 'retry_freight_upload_rpa') && freightUploadStatusDisplay(group).state !== 'allocating'"
|
||||
type="button"
|
||||
class="rounded border border-default px-2 py-1 font-medium text-primary hover:bg-surface-muted disabled:opacity-50"
|
||||
data-testid="review-freight-upload-rpa"
|
||||
@@ -5504,7 +5542,7 @@ watch(
|
||||
@click="void runFreightNoticeAction(group, 'rpa')"
|
||||
>{{ t('chat.shippingOrderReview.lifecycle.freightUpload.rpa') }}</button>
|
||||
<button
|
||||
v-if="canRunFreightNoticeAction(group, 'mark_manual_uploaded')"
|
||||
v-if="canRunFreightNoticeAction(group, 'mark_manual_uploaded') && freightUploadStatusDisplay(group).state !== 'allocating'"
|
||||
type="button"
|
||||
class="rounded border border-default px-2 py-1 font-medium text-primary hover:bg-surface-muted disabled:opacity-50"
|
||||
data-testid="review-freight-upload-confirm"
|
||||
|
||||
@@ -877,6 +877,9 @@
|
||||
"cloneTemplateCodeHint": "Enter a new unique template code. The new template starts as a v1 draft.",
|
||||
"cloneTemplateConfirm": "Create new template",
|
||||
"copySuffix": "Copy",
|
||||
"cloneSource": "Copy as new",
|
||||
"cloneSourceAria": "Copy {name} as a new site",
|
||||
"cloneSourceBanner": "Copied from \"{code} · {name}\". Nothing is created until you save. Enter a new source code.",
|
||||
"confirmRetireTemplate": "Retire this template? It can no longer be bound to a new inventory site.",
|
||||
"connectionsHelp": "Manage login URLs and credentials for separate accounts. A connection only handles login; it does not define browser actions.",
|
||||
"credentialsHint": "Usernames and passwords are write-only and are never returned by the UI or API.",
|
||||
@@ -1023,8 +1026,8 @@
|
||||
},
|
||||
"connectionBoundary": "Enter only the login information here. The system handles the required page actions, downloads, and waiting for the selected freight platform.",
|
||||
"uploadConfigTitle": "Shipping Excel Auto Upload",
|
||||
"uploadConfigHint": "Edited from this System Connection and stored as a restricted JSON. No free JavaScript, scripts, URL templates, cookies, or arbitrary browser actions are allowed.",
|
||||
"uploadAutoEnabled": "Enable auto-upload (admin has reviewed this connection's upload behavior)",
|
||||
"uploadConfigHint": "This switch only enables auto-upload. The page, buttons, and success checks are fixed in the freight connector.",
|
||||
"uploadAutoEnabled": "Auto-upload",
|
||||
"uploadEntryUrl": "Upload entry URL",
|
||||
"uploadFileSelector": "File input selector",
|
||||
"uploadSubmitMode": "Submit mode",
|
||||
@@ -1038,7 +1041,7 @@
|
||||
"uploadSuccessTexts": "Success texts (one per line)",
|
||||
"uploadSuccessTextsHint": "Matching any success text marks success",
|
||||
"uploadTimeout": "Timeout (seconds)",
|
||||
"uploadConfigBoundary": "Upload config changes do not increment the inventory RPA config_version; used only for this connection's freight upload, not propagated to inventory/receipt RPA.",
|
||||
"uploadConfigBoundary": "The upload page, buttons, and success checks are fixed in the connector. This switch only turns auto-upload on or off.",
|
||||
"platform": {
|
||||
"dbs": "DBS",
|
||||
"crane": "Crane"
|
||||
@@ -2632,6 +2635,7 @@
|
||||
"platformJobFreightRpaOnhand": "Freight onhand inventory RPA",
|
||||
"platformJobFaqHotAggregate": "FAQ hot aggregate",
|
||||
"platformJobFileAssetCleanup": "Temporary file asset cleanup",
|
||||
"transferTypeCodes": "Transfer types",
|
||||
"transferSourceCodes": "Source instances",
|
||||
"transferRecoverHistory": "Recover retryable history",
|
||||
"transferReceiptDateFrom": "Movement date from (T-N)",
|
||||
@@ -5608,7 +5612,7 @@
|
||||
"types": "Training Types",
|
||||
"typeCount": "{count} configurations",
|
||||
"detail": "Configuration Details",
|
||||
"headerMeta": "Type: {type} · Current version: {version}",
|
||||
"headerMeta": "Type code: {type}",
|
||||
"addType": "Add Training Type",
|
||||
"editType": "Edit Training Type",
|
||||
"empty": "No training configurations",
|
||||
@@ -5659,6 +5663,7 @@
|
||||
},
|
||||
"placeholders": {
|
||||
"onePerLine": "Enter one item per line",
|
||||
"typeCode": "Example: onboarding",
|
||||
"oneQuestionPerLine": "Enter one question per line",
|
||||
"progressItemLabel": "Example: Watch video",
|
||||
"progressHintText": "Example: Training is complete only after the video, knowledge review, and exam are all finished.",
|
||||
@@ -5677,6 +5682,11 @@
|
||||
"progressHintText": "Training progress note",
|
||||
"stepIntroText": "Training step guide copy",
|
||||
"requiredDuration": "Required time (minutes)",
|
||||
"requiredDurationPlaceholder": "0 means no limit",
|
||||
"stageSummaryTitle": "Level summaries (one item per line)",
|
||||
"stageSummaryCompany": "Company summary",
|
||||
"stageSummaryDepartment": "Department summary",
|
||||
"stageSummaryTeam": "Team summary",
|
||||
"summaryPoints": "Review points",
|
||||
"summaryChecklist": "Pre-exam checklist",
|
||||
"employeeQuestions": "Employee FAQs",
|
||||
@@ -5793,12 +5803,6 @@
|
||||
"eyebrow": "Training Operations Center",
|
||||
"pageHint": "Configuration changes take effect after saving",
|
||||
"footerHint": "All configuration items can be adjusted after saving",
|
||||
"stats": {
|
||||
"total": "Total Configs",
|
||||
"published": "Published",
|
||||
"resources": "Current Materials",
|
||||
"levels": "Configured Levels"
|
||||
},
|
||||
"questionBankTitle": "Onboarding Question Bank"
|
||||
},
|
||||
"integrationConnector": {
|
||||
|
||||
@@ -1746,6 +1746,7 @@
|
||||
"download": "Download Excel",
|
||||
"rpa": "RPA upload",
|
||||
"confirm": "Confirm uploaded",
|
||||
"refreshStatus": "Refresh upload status",
|
||||
"lineNo": "Line",
|
||||
"lineNoSourceCustomerPo": "Customer PO line no.",
|
||||
"lineNoSourceSequence": "System sequence (internal line no. not recognized)",
|
||||
@@ -1758,6 +1759,7 @@
|
||||
"uploadStatus": {
|
||||
"pending": "Pending upload",
|
||||
"uploading": "Uploading",
|
||||
"allocating": "Accepted, allocating",
|
||||
"failed": "Upload failed",
|
||||
"uploaded": "Uploaded",
|
||||
"needsHuman": "Manual upload needed"
|
||||
@@ -3805,14 +3807,13 @@
|
||||
"colMaterial": "Material",
|
||||
"colName": "Name",
|
||||
"colSpec": "Spec",
|
||||
"colInvoice": "Invoice",
|
||||
"colMovementDate": "Movement Date",
|
||||
"colFromWarehouse": "From warehouse",
|
||||
"colFromQty": "Stock qty",
|
||||
"stockCheckedAtTitle": "Stock checked at {time}",
|
||||
"colToWarehouse": "To warehouse",
|
||||
"colFromBatch": "Outbound Batch",
|
||||
"filterPlaceholder": "Filter by material / name / Invoice / batch",
|
||||
"filterPlaceholder": "Filter by material / name / doc no. / external doc / batch",
|
||||
"filterAll": "All results",
|
||||
"requerySelected": "Requery selected",
|
||||
"movementDateLabel": "Movement date",
|
||||
@@ -3828,7 +3829,11 @@
|
||||
"resultFileRemoved": "Removed from file",
|
||||
"resultPendingStockCheck": "Pending stock check",
|
||||
"staleRow": "Stale — requery",
|
||||
"staleShort": "Stale",
|
||||
"staleBanner": "{count} rows have stale inventory",
|
||||
"staleBannerRequery": "Requery stale rows",
|
||||
"fileChangedRow": "File updated; data will realign",
|
||||
"fileChangedShort": "File updated",
|
||||
"fileRemovedQuarantined": "{count} more rows were invalidated (removed from the inbound file) and are hidden from this list; handle them under Pending Exceptions (mark as no further action).",
|
||||
"runProgress": "Transfer run progress",
|
||||
"runExecuting": "Executing",
|
||||
|
||||
@@ -17,6 +17,9 @@
|
||||
"ORDER_DELIVERY_REPLY.BATCH_INVALID": "Invalid batch format. Check the date, quantity, or remark.",
|
||||
"ORDER_DELIVERY_REPLY.BATCH_QTY_TOTAL_MISMATCH": "The total of all batch quantities must equal the order quantity. Please adjust and save again.",
|
||||
"SHIPPING.NOTICE_ODM_CHOICE_INVALID": "The selected ODM ID is not among the feasible candidates. Please choose again.",
|
||||
"SHIPPING.UPLOAD_CRANE_ALLOCATING": "The forwarder accepted the file and is still allocating it. Refresh the status instead of uploading again.",
|
||||
"SHIPPING.UPLOAD_CRANE_REFRESH_INFLIGHT": "A status refresh is already queued. Try again shortly.",
|
||||
"SHIPPING.UPLOAD_TRIGGER_UNAVAILABLE": "The upload status-check directory is unavailable. Check the RPA shared folder.",
|
||||
"SHIPPING.FULFILLMENT_POLICY_INVALID": "The fulfillment policy or field capability binding is invalid.",
|
||||
"SHIPPING.FULFILLMENT_POLICY_NOT_FOUND": "The fulfillment policy was not found.",
|
||||
"SHIPPING.FULFILLMENT_POLICY_CONFLICT": "The fulfillment policy was changed by another administrator. Refresh and try again.",
|
||||
|
||||
@@ -877,6 +877,9 @@
|
||||
"cloneTemplateCodeHint": "กรอกรหัสเทมเพลตใหม่ที่ไม่ซ้ำ เทมเพลตใหม่จะเริ่มเป็นฉบับร่าง v1",
|
||||
"cloneTemplateConfirm": "สร้างเทมเพลตใหม่",
|
||||
"copySuffix": "สำเนา",
|
||||
"cloneSource": "คัดลอกเป็นรายการใหม่",
|
||||
"cloneSourceAria": "คัดลอก {name} เป็นไซต์ใหม่",
|
||||
"cloneSourceBanner": "คัดลอกจาก \"{code} · {name}\" ระบบจะยังไม่สร้างไซต์จนกว่าจะบันทึก กรอกรหัสแหล่งสินค้าใหม่",
|
||||
"confirmRetireTemplate": "ต้องการเลิกใช้เทมเพลตนี้หรือไม่ หลังจากนั้นจะผูกกับไซต์สินค้าคงคลังใหม่ไม่ได้",
|
||||
"connectionsHelp": "จัดการ URL เข้าสู่ระบบและข้อมูลรับรองของแต่ละบัญชี การเชื่อมต่อมีหน้าที่เฉพาะการเข้าสู่ระบบ ไม่กำหนดการทำงานของหน้าเว็บ",
|
||||
"credentialsHint": "ชื่อผู้ใช้และรหัสผ่านเขียนได้เท่านั้น และจะไม่ส่งกลับจากหน้าเว็บหรือ API",
|
||||
@@ -1023,8 +1026,8 @@
|
||||
},
|
||||
"connectionBoundary": "กรอกเฉพาะข้อมูลเข้าสู่ระบบ ระบบจะดำเนินการหน้าเว็บ ดาวน์โหลด และรอตามแพลตฟอร์มผู้ให้บริการที่เลือกโดยอัตโนมัติ",
|
||||
"uploadConfigTitle": "อัปโหลด Excel การจัดส่งอัตโนมัติ",
|
||||
"uploadConfigHint": "แก้ไขจากหน้าการเชื่อมต่อระบบนี้และบันทึกเป็น JSON แบบจำกัด; ห้ามใช้ JavaScript/สคริปต์/URL template/Cookie หรือการกระทำเบราว์เซอร์โดยอิสระ",
|
||||
"uploadAutoEnabled": "เปิดใช้งานอัปโหลดอัตโนมัติ (ผู้ดูแลตรวจสอบพฤติกรรมการอัปโหลดของการเชื่อมต่อนี้แล้ว)",
|
||||
"uploadConfigHint": "สวิตช์นี้เปิดเฉพาะการอัปโหลดอัตโนมัติ หน้า ปุ่ม และเงื่อนไขสำเร็จถูกกำหนดไว้ในตัวเชื่อมต่อ",
|
||||
"uploadAutoEnabled": "อัปโหลดอัตโนมัติ",
|
||||
"uploadEntryUrl": "URL หน้าอัปโหลด",
|
||||
"uploadFileSelector": "ตัวเลือกไฟล์ (selector)",
|
||||
"uploadSubmitMode": "โหมดส่ง",
|
||||
@@ -1038,7 +1041,7 @@
|
||||
"uploadSuccessTexts": "ข้อความสำเร็จ (หนึ่งรายการต่อบรรทัด)",
|
||||
"uploadSuccessTextsHint": "หากตรงกับข้อความสำเร็จข้อใดข้อหนึ่งถือว่าสำเร็จ",
|
||||
"uploadTimeout": "ระยะเวลารอ (วินาที)",
|
||||
"uploadConfigBoundary": "การเปลี่ยนค่าอัปโหลดไม่เพิ่ม config_version ของ RPA คลัง; ใช้เฉพาะการอัปโหลดของสายการขนส่งนี้เท่านั้น ไม่แพร่ไปยัง RPA คลัง/รับของ",
|
||||
"uploadConfigBoundary": "หน้า ปุ่ม และเงื่อนไขสำเร็จถูกกำหนดในโปรแกรม สวิตช์นี้เปิดหรือปิดการอัปโหลดอัตโนมัติเท่านั้น",
|
||||
"platform": {
|
||||
"dbs": "DBS",
|
||||
"crane": "Crane"
|
||||
@@ -2512,6 +2515,7 @@
|
||||
"platformJobFreightRpaOnhand": "Freight onhand inventory RPA",
|
||||
"platformJobFaqHotAggregate": "FAQ hot aggregate",
|
||||
"platformJobFileAssetCleanup": "Temporary file asset cleanup",
|
||||
"transferTypeCodes": "ประเภทการโอนย้าย",
|
||||
"transferSourceCodes": "Source instances",
|
||||
"transferRecoverHistory": "Recover retryable history",
|
||||
"transferReceiptDateFrom": "วันที่เคลื่อนไหวเริ่ม (T-N)",
|
||||
@@ -5608,7 +5612,7 @@
|
||||
"types": "ประเภทการฝึกอบรม",
|
||||
"typeCount": "ทั้งหมด {count} การกำหนดค่า",
|
||||
"detail": "รายละเอียดการกำหนดค่า",
|
||||
"headerMeta": "ประเภท: {type} · เวอร์ชันปัจจุบัน: {version}",
|
||||
"headerMeta": "รหัสประเภท: {type}",
|
||||
"addType": "เพิ่มประเภทการฝึกอบรม",
|
||||
"editType": "แก้ไขประเภทการฝึกอบรม",
|
||||
"empty": "ยังไม่มีการกำหนดค่า",
|
||||
@@ -5659,6 +5663,7 @@
|
||||
},
|
||||
"placeholders": {
|
||||
"onePerLine": "กรอกหนึ่งรายการต่อบรรทัด",
|
||||
"typeCode": "ตัวอย่าง: onboarding",
|
||||
"oneQuestionPerLine": "กรอกหนึ่งคำถามต่อบรรทัด",
|
||||
"progressItemLabel": "ตัวอย่าง: ดูวิดีโอ",
|
||||
"progressHintText": "ตัวอย่าง: จะถือว่าเสร็จสิ้นเมื่อทำวิดีโอ ทบทวนความรู้ และข้อสอบครบแล้ว",
|
||||
@@ -5677,6 +5682,11 @@
|
||||
"progressHintText": "คำอธิบายความคืบหน้าการฝึกอบรม",
|
||||
"stepIntroText": "ข้อความแนะนำขั้นตอนการฝึกอบรม",
|
||||
"requiredDuration": "เวลาที่ต้องใช้ (นาที)",
|
||||
"requiredDurationPlaceholder": "0 หมายถึงไม่จำกัด",
|
||||
"stageSummaryTitle": "สรุปตามระดับ (หนึ่งรายการต่อบรรทัด)",
|
||||
"stageSummaryCompany": "สรุประดับบริษัท",
|
||||
"stageSummaryDepartment": "สรุประดับแผนก",
|
||||
"stageSummaryTeam": "สรุประดับทีม",
|
||||
"summaryPoints": "ประเด็นทบทวน",
|
||||
"summaryChecklist": "รายการก่อนสอบ",
|
||||
"employeeQuestions": "คำถามที่พบบ่อยของพนักงาน",
|
||||
@@ -5793,12 +5803,6 @@
|
||||
"eyebrow": "培训运营中心",
|
||||
"pageHint": "配置变更将在保存后生效",
|
||||
"footerHint": "所有配置项均支持保存后继续调整",
|
||||
"stats": {
|
||||
"total": "配置总数",
|
||||
"published": "已发布",
|
||||
"resources": "当前资料",
|
||||
"levels": "已配置级别"
|
||||
},
|
||||
"questionBankTitle": "入职培训题库"
|
||||
},
|
||||
"integrationConnector": {
|
||||
|
||||
@@ -1746,6 +1746,7 @@
|
||||
"download": "ดาวน์โหลด Excel",
|
||||
"rpa": "อัปโหลด RPA",
|
||||
"confirm": "ยืนยันอัปโหลด",
|
||||
"refreshStatus": "รีเฟรชสถานะอัปโหลด",
|
||||
"lineNo": "รายการ",
|
||||
"lineNoSourceCustomerPo": "เลขบรรทัด PO ของลูกค้า",
|
||||
"lineNoSourceSequence": "ลำดับระบบ (ไม่พบเลขรายการภายใน)",
|
||||
@@ -1758,6 +1759,7 @@
|
||||
"uploadStatus": {
|
||||
"pending": "รออัปโหลด",
|
||||
"uploading": "กำลังอัปโหลด",
|
||||
"allocating": "รับไฟล์แล้ว กำลังจัดสรร",
|
||||
"failed": "อัปโหลดล้มเหลว",
|
||||
"uploaded": "อัปโหลดแล้ว",
|
||||
"needsHuman": "ต้องอัปโหลดด้วยตนเอง"
|
||||
@@ -3805,14 +3807,13 @@
|
||||
"colMaterial": "รหัสวัสดุ",
|
||||
"colName": "ชื่อ",
|
||||
"colSpec": "สเปก",
|
||||
"colInvoice": "Invoice",
|
||||
"colMovementDate": "วันที่เคลื่อนไหว",
|
||||
"colFromWarehouse": "คลังต้นทาง",
|
||||
"colFromQty": "จำนวนสต๊อก",
|
||||
"stockCheckedAtTitle": "เวลาตรวจสอบสต๊อก: {time}",
|
||||
"colToWarehouse": "คลังปลายทาง",
|
||||
"colFromBatch": "ล็อตต้นทาง",
|
||||
"filterPlaceholder": "กรองตามรหัสวัสดุ / ชื่อ / Invoice / ล็อต",
|
||||
"filterPlaceholder": "กรองตามรหัสวัสดุ / ชื่อ / เลขที่เอกสาร / เลขที่เอกสารภายนอก / ล็อต",
|
||||
"filterAll": "ทุกผลลัพธ์",
|
||||
"requerySelected": "ตรวจซ้ำที่เลือก",
|
||||
"movementDateLabel": "วันที่เคลื่อนไหว",
|
||||
@@ -3828,7 +3829,11 @@
|
||||
"resultFileRemoved": "ถูกลบออกจากไฟล์",
|
||||
"resultPendingStockCheck": "รอตรวจสอบสต๊อก",
|
||||
"staleRow": "ข้อมูลหมดอายุ กรุณาตรวจซ้ำ",
|
||||
"staleShort": "หมดอายุ",
|
||||
"staleBanner": "มี {count} แถวที่สต๊อกหมดอายุ",
|
||||
"staleBannerRequery": "ตรวจซ้ำแถวที่หมดอายุ",
|
||||
"fileChangedRow": "ไฟล์อัปเดตแล้ว ข้อมูลจะจัดตำแหน่งใหม่อัตโนมัติ",
|
||||
"fileChangedShort": "ไฟล์อัปเดต",
|
||||
"fileRemovedQuarantined": "อีก {count} รายการถือเป็นยกเลิกเนื่องจากถูกลบออกจากไฟล์รับเข้า และถูกซ่อนจากรายการนี้ โปรดดำเนินการใน「ข้อยกเว้นที่รอดำเนินการ」โดยสามารถทำเครื่องหมายว่าไม่จำเป็นต้องดำเนินการต่อ",
|
||||
"runProgress": "ความคืบหน้าการโอน",
|
||||
"runExecuting": "กำลังดำเนินการ",
|
||||
|
||||
@@ -17,6 +17,9 @@
|
||||
"ORDER_DELIVERY_REPLY.BATCH_INVALID": "รูปแบบงวดไม่ถูกต้อง โปรดตรวจสอบวันที่ จำนวน หรือหมายเหตุ",
|
||||
"ORDER_DELIVERY_REPLY.BATCH_QTY_TOTAL_MISMATCH": "ผลรวมจำนวนทุกงวดต้องเท่ากับจำนวนของคำสั่งซื้อ โปรดปรับแล้วบันทึกอีกครั้ง",
|
||||
"SHIPPING.NOTICE_ODM_CHOICE_INVALID": "ODM ID ที่เลือกไม่อยู่ในตัวเลือกที่ทำได้ โปรดเลือกใหม่",
|
||||
"SHIPPING.UPLOAD_CRANE_ALLOCATING": "ผู้รับขนรับไฟล์แล้วและกำลังจัดสรร โปรดรีเฟรชสถานะ อย่าอัปโหลดซ้ำ",
|
||||
"SHIPPING.UPLOAD_CRANE_REFRESH_INFLIGHT": "มีการรีเฟรชสถานะค้างอยู่ในคิว โปรดลองอีกครั้งในอีกสักครู่",
|
||||
"SHIPPING.UPLOAD_TRIGGER_UNAVAILABLE": "โฟลเดอร์ตรวจสถานะการอัปโหลดไม่พร้อม โปรดตรวจโฟลเดอร์ที่ใช้ร่วมกันของ RPA",
|
||||
"SHIPPING.FULFILLMENT_POLICY_INVALID": "นโยบายการปฏิบัติตามหรือการผูกความสามารถของฟิลด์ไม่ถูกต้อง",
|
||||
"SHIPPING.FULFILLMENT_POLICY_NOT_FOUND": "ไม่พบนโยบายการปฏิบัติตาม",
|
||||
"SHIPPING.FULFILLMENT_POLICY_CONFLICT": "นโยบายการปฏิบัติตามถูกแก้ไขโดยผู้ดูแลรายอื่น โปรดรีเฟรชแล้วลองใหม่",
|
||||
|
||||
@@ -1007,6 +1007,9 @@
|
||||
"cloneTemplateCodeHint": "请输入新的唯一模板编码;新模板将从 v1 草稿开始。",
|
||||
"cloneTemplateConfirm": "创建新模板",
|
||||
"copySuffix": "副本",
|
||||
"cloneSource": "复制新增",
|
||||
"cloneSourceAria": "复制新增 {name}",
|
||||
"cloneSourceBanner": "基于「{code} · {name}」复制。保存前不会创建站点。请填写新的库存源编号。",
|
||||
"confirmRetireTemplate": "确定退役这个模板吗?退役后不能再绑定新的库存站点。",
|
||||
"templateLayoutReadFailed": "无法读取 Excel 模板的工作表和表头,请确认文件未损坏后重试。",
|
||||
"connectionsHelp": "维护不同账号的登录地址和凭据;每个连接配置只负责登录,不维护页面点击路径。",
|
||||
@@ -1154,8 +1157,8 @@
|
||||
},
|
||||
"connectionBoundary": "连接配置只填写登录所需信息;系统会按货代平台自动执行页面操作、下载和等待。",
|
||||
"uploadConfigTitle": "发货 Excel 自动上传",
|
||||
"uploadConfigHint": "该配置由系统连接管理端编辑,后端保存为受限 JSON;禁止自由 JavaScript、脚本、URL 模板、Cookie 或任意浏览器动作。",
|
||||
"uploadAutoEnabled": "启用自动上传(代表管理员已审核该连接的上传行为)",
|
||||
"uploadConfigHint": "只控制这条连接是否自动上传。上传页面、按钮和成功判断由对应货代平台的程序固定。",
|
||||
"uploadAutoEnabled": "自动上传",
|
||||
"uploadEntryUrl": "上传入口 URL",
|
||||
"uploadFileSelector": "文件选择器",
|
||||
"uploadSubmitMode": "提交方式",
|
||||
@@ -1169,7 +1172,7 @@
|
||||
"uploadSuccessTexts": "成功文本(每行一条)",
|
||||
"uploadSuccessTextsHint": "命中任一条成功文本即判定成功",
|
||||
"uploadTimeout": "超时时间(秒)",
|
||||
"uploadConfigBoundary": "上传配置变更不递增库存 RPA config_version;仅该连接的货代上传使用,不向库存/收料 RPA 扩散。",
|
||||
"uploadConfigBoundary": "上传页面、按钮和成功判断由货代平台程序固定。这里只开关自动上传,变更不递增库存 RPA config_version。",
|
||||
"platform": {
|
||||
"dbs": "DBS 平台",
|
||||
"crane": "Crane 平台"
|
||||
@@ -2763,6 +2766,7 @@
|
||||
"platformJobFreightRpaOnhand": "货代库存 RPA",
|
||||
"platformJobFaqHotAggregate": "FAQ 热点聚合",
|
||||
"platformJobFileAssetCleanup": "临时文件资产清理",
|
||||
"transferTypeCodes": "调拨类型",
|
||||
"transferSourceCodes": "来源实例",
|
||||
"transferRecoverHistory": "历史可恢复异常复核",
|
||||
"transferReceiptDateFrom": "异动日期起(T-N)",
|
||||
@@ -5622,16 +5626,10 @@
|
||||
"subtitle": "按培训类型管理版本、考试规则、资源与题目",
|
||||
"pageHint": "配置变更将在保存后生效",
|
||||
"footerHint": "所有配置项均支持保存后继续调整",
|
||||
"stats": {
|
||||
"total": "配置总数",
|
||||
"published": "已发布",
|
||||
"resources": "当前资料",
|
||||
"levels": "已配置级别"
|
||||
},
|
||||
"types": "培训类型",
|
||||
"typeCount": "共 {count} 个配置",
|
||||
"detail": "配置详情",
|
||||
"headerMeta": "类型编码:{type} · 当前版本:{version}",
|
||||
"headerMeta": "类型编码:{type}",
|
||||
"addType": "新增培训类型",
|
||||
"editType": "编辑培训类型",
|
||||
"empty": "暂无培训配置",
|
||||
@@ -5683,6 +5681,7 @@
|
||||
},
|
||||
"placeholders": {
|
||||
"onePerLine": "每行填写一项",
|
||||
"typeCode": "例如 onboarding,小写字母开头",
|
||||
"oneQuestionPerLine": "每行填写一个问题",
|
||||
"progressItemLabel": "例如:观看视频",
|
||||
"progressHintText": "例如:按 HR 要求完成视频、知识点、考试三个环节后才能视为完成。",
|
||||
@@ -5701,6 +5700,11 @@
|
||||
"progressHintText": "培训进度说明",
|
||||
"stepIntroText": "培训步骤引导文案",
|
||||
"requiredDuration": "所需时间(分钟)",
|
||||
"requiredDurationPlaceholder": "0 表示不限制",
|
||||
"stageSummaryTitle": "分级培训总结(按行分隔)",
|
||||
"stageSummaryCompany": "公司级总结",
|
||||
"stageSummaryDepartment": "部门级总结",
|
||||
"stageSummaryTeam": "班组级总结",
|
||||
"summaryPoints": "复盘要点",
|
||||
"summaryChecklist": "考前清单",
|
||||
"employeeQuestions": "员工常见问题",
|
||||
|
||||
@@ -1780,6 +1780,7 @@
|
||||
"download": "下载 Excel",
|
||||
"rpa": "RPA 上传",
|
||||
"confirm": "确认上传",
|
||||
"refreshStatus": "刷新上传状态",
|
||||
"lineNo": "项次",
|
||||
"lineNoSourceCustomerPo": "客户 PO 行号",
|
||||
"lineNoSourceSequence": "系统行序(未识别到内部项次)",
|
||||
@@ -1792,6 +1793,7 @@
|
||||
"uploadStatus": {
|
||||
"pending": "待上传",
|
||||
"uploading": "上传中",
|
||||
"allocating": "已接收,分配中",
|
||||
"failed": "上传失败",
|
||||
"uploaded": "已上传",
|
||||
"needsHuman": "需人工上传"
|
||||
@@ -3805,14 +3807,13 @@
|
||||
"colMaterial": "料号",
|
||||
"colName": "品名",
|
||||
"colSpec": "规格",
|
||||
"colInvoice": "Invoice",
|
||||
"colMovementDate": "异动日期",
|
||||
"colFromWarehouse": "拨出仓库",
|
||||
"colFromQty": "库存数量",
|
||||
"stockCheckedAtTitle": "库存查询时刻:{time}",
|
||||
"colToWarehouse": "拨入仓库",
|
||||
"colFromBatch": "拨出批号",
|
||||
"filterPlaceholder": "按料号 / 品名 / Invoice / 批号筛选",
|
||||
"filterPlaceholder": "按料号 / 品名 / 单号 / 外部单号 / 批号筛选",
|
||||
"filterAll": "全部结果",
|
||||
"requerySelected": "重查选中",
|
||||
"movementDateLabel": "异动日期",
|
||||
@@ -3828,7 +3829,11 @@
|
||||
"resultFileRemoved": "文件已移除",
|
||||
"resultPendingStockCheck": "待查库存",
|
||||
"staleRow": "数据已过期,请重查",
|
||||
"staleShort": "已过期",
|
||||
"staleBanner": "{count} 行库存已过期",
|
||||
"staleBannerRequery": "重查过期行",
|
||||
"fileChangedRow": "文件已更新,将自动对齐",
|
||||
"fileChangedShort": "文件更新",
|
||||
"fileRemovedQuarantined": "另有 {count} 行已随入站文件移除而失效,已移出本清单;请到「待处理异常」处理,可标记无需继续处理。",
|
||||
"runProgress": "调拨执行进度",
|
||||
"runExecuting": "执行中",
|
||||
|
||||
@@ -17,6 +17,9 @@
|
||||
"ORDER_DELIVERY_REPLY.BATCH_INVALID": "批次格式不合法,请检查交期、数量或备注。",
|
||||
"ORDER_DELIVERY_REPLY.BATCH_QTY_TOTAL_MISMATCH": "各批次数量合计必须等于订单数量,请调整后重新保存。",
|
||||
"SHIPPING.NOTICE_ODM_CHOICE_INVALID": "所选 ODM ID 不在当前可行候选内,请重新选择。",
|
||||
"SHIPPING.UPLOAD_CRANE_ALLOCATING": "货代已接收文件并正在分配,请刷新状态,不要再次上传。",
|
||||
"SHIPPING.UPLOAD_CRANE_REFRESH_INFLIGHT": "上一次状态刷新还在排队,请稍后再试。",
|
||||
"SHIPPING.UPLOAD_TRIGGER_UNAVAILABLE": "上传回查目录不可用,请检查 RPA 共享目录。",
|
||||
"SHIPPING.FULFILLMENT_POLICY_INVALID": "货代履约策略或字段能力绑定无效。",
|
||||
"SHIPPING.FULFILLMENT_POLICY_NOT_FOUND": "未找到货代履约策略。",
|
||||
"SHIPPING.FULFILLMENT_POLICY_CONFLICT": "货代履约策略已被其他管理员修改,请刷新后重试。",
|
||||
|
||||
@@ -877,6 +877,9 @@
|
||||
"cloneTemplateCodeHint": "請輸入新的唯一範本編碼;新範本將從 v1 草稿開始。",
|
||||
"cloneTemplateConfirm": "建立新範本",
|
||||
"copySuffix": "副本",
|
||||
"cloneSource": "複製新增",
|
||||
"cloneSourceAria": "複製新增 {name}",
|
||||
"cloneSourceBanner": "基於「{code} · {name}」複製。儲存前不會建立站點。請填寫新的庫存源編號。",
|
||||
"confirmRetireTemplate": "確定要退役這個範本嗎?退役後不能再綁定新的庫存站點。",
|
||||
"connectionsHelp": "維護不同帳號的登入網址和憑據;每個連線設定只負責登入,不維護頁面點擊路徑。",
|
||||
"credentialsHint": "帳號與密碼只可寫入,頁面及介面不會回傳。",
|
||||
@@ -1023,8 +1026,8 @@
|
||||
},
|
||||
"connectionBoundary": "連線設定只填寫登入所需資訊;系統會依貨代平台自動執行頁面操作、下載與等待。",
|
||||
"uploadConfigTitle": "發貨 Excel 自動上傳",
|
||||
"uploadConfigHint": "本設定由系統連線管理端編輯,後端儲存為受限 JSON;禁止自由 JavaScript、腳本、URL 範本、Cookie 或任意瀏覽器動作。",
|
||||
"uploadAutoEnabled": "啟用自動上傳(代表管理員已審核該連線的上傳行為)",
|
||||
"uploadConfigHint": "只控制這條連線是否自動上傳。上傳頁面、按鈕和成功判斷由對應貨代平台的程式固定。",
|
||||
"uploadAutoEnabled": "自動上傳",
|
||||
"uploadEntryUrl": "上傳入口 URL",
|
||||
"uploadFileSelector": "檔案選擇器",
|
||||
"uploadSubmitMode": "提交方式",
|
||||
@@ -1038,7 +1041,7 @@
|
||||
"uploadSuccessTexts": "成功文字(每行一條)",
|
||||
"uploadSuccessTextsHint": "命中任一條成功文字即判定成功",
|
||||
"uploadTimeout": "逾時時間(秒)",
|
||||
"uploadConfigBoundary": "上傳設定變更不遞增庫存 RPA config_version;僅該連線的貨代上傳使用,不擴散至庫存/收料 RPA。",
|
||||
"uploadConfigBoundary": "上傳頁面、按鈕和成功判斷由貨代平台程式固定。這裡只開關自動上傳,變更不遞增庫存 RPA config_version。",
|
||||
"platform": {
|
||||
"dbs": "DBS 平台",
|
||||
"crane": "Crane 平台"
|
||||
@@ -2512,6 +2515,7 @@
|
||||
"platformJobFreightRpaOnhand": "貨代庫存 RPA",
|
||||
"platformJobFaqHotAggregate": "FAQ 熱點聚合",
|
||||
"platformJobFileAssetCleanup": "暫存檔案資產清理",
|
||||
"transferTypeCodes": "調撥類型",
|
||||
"transferSourceCodes": "來源實例",
|
||||
"transferRecoverHistory": "歷史可復原異常複核",
|
||||
"transferReceiptDateFrom": "異動日期起(T-N)",
|
||||
@@ -5608,7 +5612,7 @@
|
||||
"types": "培訓類型",
|
||||
"typeCount": "共 {count} 個配置",
|
||||
"detail": "配置詳情",
|
||||
"headerMeta": "類型編碼:{type} · 目前版本:{version}",
|
||||
"headerMeta": "類型編碼:{type}",
|
||||
"addType": "新增培訓類型",
|
||||
"editType": "編輯培訓類型",
|
||||
"empty": "暫無培訓配置",
|
||||
@@ -5659,6 +5663,7 @@
|
||||
},
|
||||
"placeholders": {
|
||||
"onePerLine": "每行填寫一項",
|
||||
"typeCode": "例如 onboarding,小寫字母開頭",
|
||||
"oneQuestionPerLine": "每行填寫一個問題",
|
||||
"progressItemLabel": "例如:觀看影片",
|
||||
"progressHintText": "例如:按 HR 要求完成影片、知識點、考試三個環節後才算完成。",
|
||||
@@ -5677,6 +5682,11 @@
|
||||
"progressHintText": "培訓進度說明",
|
||||
"stepIntroText": "培訓步驟引導文案",
|
||||
"requiredDuration": "所需時間(分鐘)",
|
||||
"requiredDurationPlaceholder": "0 表示不限制",
|
||||
"stageSummaryTitle": "分級培訓總結(按行分隔)",
|
||||
"stageSummaryCompany": "公司級總結",
|
||||
"stageSummaryDepartment": "部門級總結",
|
||||
"stageSummaryTeam": "班組級總結",
|
||||
"summaryPoints": "複盤要點",
|
||||
"summaryChecklist": "考前清單",
|
||||
"employeeQuestions": "員工常見問題",
|
||||
@@ -5793,12 +5803,6 @@
|
||||
"eyebrow": "培训运营中心",
|
||||
"pageHint": "配置变更将在保存后生效",
|
||||
"footerHint": "所有配置项均支持保存后继续调整",
|
||||
"stats": {
|
||||
"total": "配置总数",
|
||||
"published": "已发布",
|
||||
"resources": "当前资料",
|
||||
"levels": "已配置级别"
|
||||
},
|
||||
"questionBankTitle": "入职培训题库"
|
||||
},
|
||||
"integrationConnector": {
|
||||
|
||||
@@ -1746,6 +1746,7 @@
|
||||
"download": "下載 Excel",
|
||||
"rpa": "RPA 上傳",
|
||||
"confirm": "確認上傳",
|
||||
"refreshStatus": "重新整理上傳狀態",
|
||||
"lineNo": "項次",
|
||||
"lineNoSourceCustomerPo": "客戶 PO 行號",
|
||||
"lineNoSourceSequence": "系統行序(未識別到內部項次)",
|
||||
@@ -1758,6 +1759,7 @@
|
||||
"uploadStatus": {
|
||||
"pending": "待上傳",
|
||||
"uploading": "上傳中",
|
||||
"allocating": "已接收,分配中",
|
||||
"failed": "上傳失敗",
|
||||
"uploaded": "已上傳",
|
||||
"needsHuman": "需人工上傳"
|
||||
@@ -3805,14 +3807,13 @@
|
||||
"colMaterial": "料號",
|
||||
"colName": "品名",
|
||||
"colSpec": "規格",
|
||||
"colInvoice": "Invoice",
|
||||
"colMovementDate": "異動日期",
|
||||
"colFromWarehouse": "撥出倉庫",
|
||||
"colFromQty": "庫存數量",
|
||||
"stockCheckedAtTitle": "庫存查詢時刻:{time}",
|
||||
"colToWarehouse": "撥入倉庫",
|
||||
"colFromBatch": "撥出批號",
|
||||
"filterPlaceholder": "按料號 / 品名 / Invoice / 批號篩選",
|
||||
"filterPlaceholder": "按料號 / 品名 / 單號 / 外部單號 / 批號篩選",
|
||||
"filterAll": "全部結果",
|
||||
"requerySelected": "重查選中",
|
||||
"movementDateLabel": "異動日期",
|
||||
@@ -3828,7 +3829,11 @@
|
||||
"resultFileRemoved": "檔案已移除",
|
||||
"resultPendingStockCheck": "待查庫存",
|
||||
"staleRow": "資料已過期,請重查",
|
||||
"staleShort": "已過期",
|
||||
"staleBanner": "{count} 行庫存已過期",
|
||||
"staleBannerRequery": "重查過期行",
|
||||
"fileChangedRow": "檔案已更新,將自動對齊",
|
||||
"fileChangedShort": "檔案更新",
|
||||
"fileRemovedQuarantined": "另有 {count} 筆已隨入站檔案移除而失效,已移出本清單;請到「待處理異常」處理,可標記無需繼續處理。",
|
||||
"runProgress": "調撥執行進度",
|
||||
"runExecuting": "執行中",
|
||||
|
||||
@@ -17,6 +17,9 @@
|
||||
"ORDER_DELIVERY_REPLY.BATCH_INVALID": "批次格式不合法,請檢查交期、數量或備註。",
|
||||
"ORDER_DELIVERY_REPLY.BATCH_QTY_TOTAL_MISMATCH": "各批次數量合計必須等於訂單數量,請調整後重新保存。",
|
||||
"SHIPPING.NOTICE_ODM_CHOICE_INVALID": "所選 ODM ID 不在當前可行候選內,請重新選擇。",
|
||||
"SHIPPING.UPLOAD_CRANE_ALLOCATING": "貨代已接收檔案並正在分配,請重新整理狀態,不要再次上傳。",
|
||||
"SHIPPING.UPLOAD_CRANE_REFRESH_INFLIGHT": "上一次狀態重新整理還在排隊,請稍後再試。",
|
||||
"SHIPPING.UPLOAD_TRIGGER_UNAVAILABLE": "上傳回查目錄不可用,請檢查 RPA 共用目錄。",
|
||||
"SHIPPING.FULFILLMENT_POLICY_INVALID": "貨代履約策略或欄位能力綁定無效。",
|
||||
"SHIPPING.FULFILLMENT_POLICY_NOT_FOUND": "找不到貨代履約策略。",
|
||||
"SHIPPING.FULFILLMENT_POLICY_CONFLICT": "貨代履約策略已被其他管理員修改,請重新整理後再試。",
|
||||
|
||||
@@ -1995,6 +1995,22 @@ def _dsv_upload_result_is_success(state: dict[str, Any]) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def _upload_entry_url(connector_type: str, login_url: str) -> str:
|
||||
"""用登录地址的主机拼出平台固定上传页,不读取管理端保存的入口 URL。"""
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
kind = str(connector_type or '').strip().lower()
|
||||
parsed = urlsplit(str(login_url or '').strip())
|
||||
host = parsed.netloc.strip()
|
||||
if parsed.scheme.lower() != 'https' or not host:
|
||||
raise RuntimeError('upload login_url must be HTTPS')
|
||||
if kind == 'dbs':
|
||||
return f'https://{host}/main/portal/frame/WMSUpload2'
|
||||
if kind == 'crane':
|
||||
return f'https://{host}/#/shipping-order-upload'
|
||||
raise RuntimeError(f'unsupported upload connector_type: {connector_type or "<empty>"}')
|
||||
|
||||
|
||||
def _crane_upload_result_is_success(state: dict[str, Any]) -> bool:
|
||||
"""判断 Crane 发货通知行是否进入 Processing/Shipping Order Allocated。"""
|
||||
return (
|
||||
@@ -2004,6 +2020,15 @@ def _crane_upload_result_is_success(state: dict[str, Any]) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def _crane_upload_result_is_allocating(state: dict[str, Any]) -> bool:
|
||||
"""判断 Crane 是否已接收文件、仍在分配。这一态不是上传成功。"""
|
||||
return (
|
||||
bool(state.get('found'))
|
||||
and str(state.get('order_status') or '').strip().lower() == 'processing'
|
||||
and str(state.get('order_status_description') or '').strip().lower() == 'allocating the shipping order'
|
||||
)
|
||||
|
||||
|
||||
def _wait_for_dsv_upload_result(page: Any, filename: str) -> dict[str, Any]:
|
||||
"""轮询 DSV 上传结果页,不再使用 History 绿图标作为成功依据。
|
||||
|
||||
@@ -2056,12 +2081,19 @@ class _UploadResultUnknownError(RuntimeError):
|
||||
"""上传动作已发生但结果无法确认(未能取得可核验成功证据);必须转人工,禁止自动重试。"""
|
||||
|
||||
|
||||
class _BaseUploadAdapter:
|
||||
"""受控上传适配器基类:由连接级 upload_config 提供页面参数,代码负责浏览器动作与安全边界。
|
||||
class _UploadAcceptedAllocating(Exception):
|
||||
"""Crane 已接收文件,行状态仍是 Allocating。调用方回调 allocating,不视为失败。"""
|
||||
|
||||
设计约束:禁止把任意脚本/URL 模板/Cookie/任意浏览器动作开放到后台配置;config 只决定
|
||||
“该连接使用哪个已支持的受控流程及其页面参数”。Adapter 负责登录、打开 entry 页、选择 Excel、
|
||||
提交与结果判定。Worker 不再根据环境变量拼接 DSV/Crane 页面动作。
|
||||
def __init__(self, pull_request_no: str):
|
||||
self.pull_request_no = pull_request_no
|
||||
super().__init__(pull_request_no)
|
||||
|
||||
|
||||
class _BaseUploadAdapter:
|
||||
"""受控上传适配器基类:页面路径、按钮和成功判断写在连接器里。
|
||||
|
||||
设计约束:系统连接只保存是否启用自动上传。Adapter 负责登录、打开固定上传页、
|
||||
选择 Excel、提交与结果判定。Worker 不再根据环境变量或后台选择器拼接页面动作。
|
||||
"""
|
||||
|
||||
def __init__(self, *, file_path: Path, upload_config: dict[str, Any]):
|
||||
@@ -2089,10 +2121,9 @@ class DsvUploadAdapter(_BaseUploadAdapter):
|
||||
|
||||
def run(self, page: Any, *, login_url: str) -> dict[str, Any]:
|
||||
"""选择 DSV 文件后强制点击 Process File,再读取结果页三项成功条件。"""
|
||||
self._require('entry_url', 'file_input_selector')
|
||||
_ensure_dsv_session(page, login_url)
|
||||
page.goto(str(self.config['entry_url']), wait_until="domcontentloaded", timeout=self._timeout_ms())
|
||||
file_selector = str(self.config.get('file_input_selector') or '#file2').strip()
|
||||
page.goto(_upload_entry_url('dbs', login_url), wait_until="domcontentloaded", timeout=self._timeout_ms())
|
||||
file_selector = 'input#file2'
|
||||
page.locator(file_selector).first.set_input_files(str(self.file_path), timeout=self._timeout_ms())
|
||||
# DSV 页面选择文件后只完成预览;必须点击真实二次确认按钮才会提交上传。
|
||||
submit_selector = 'button.btn.btn-primary.upload-button:has-text("Process File")'
|
||||
@@ -2105,9 +2136,9 @@ class DsvUploadAdapter(_BaseUploadAdapter):
|
||||
|
||||
|
||||
class CraneUploadAdapter(_BaseUploadAdapter):
|
||||
"""Crane 受控上传流程:login_url 登录 → 访问 upload_config.entry_url → 选文件 → 提交 → 结果判定。
|
||||
"""Crane 受控上传流程:login_url 登录后打开固定上传页,选择文件并读发货单行。
|
||||
|
||||
启用前(enabled=true)管理端必须已确认提交按钮与成功判定字段;否则 fail-closed。
|
||||
Processing + Allocating the Shipping Order 表示已接收;只有 Shipping Order Allocated 才算成功。
|
||||
"""
|
||||
|
||||
# SweetAlert2 上传失败弹窗识别(受控 Adapter 内置,禁止开放到 upload_config):Crane 上传
|
||||
@@ -2133,18 +2164,25 @@ class CraneUploadAdapter(_BaseUploadAdapter):
|
||||
)
|
||||
|
||||
def run(self, page: Any, *, login_url: str) -> dict[str, Any]:
|
||||
self._require('entry_url', 'file_input_selector', 'submit_mode')
|
||||
if str(self.config.get('submit_mode') or '').strip() == 'click_submit':
|
||||
self._require('submit_selector')
|
||||
self._require_result_fields()
|
||||
"""选择 Crane 上传文件后读发货单行。分配中立即返回,不等到超时。"""
|
||||
_ensure_crane_session(page, login_url)
|
||||
page.goto(str(self.config['entry_url']), wait_until="domcontentloaded", timeout=self._timeout_ms())
|
||||
page.locator(str(self.config['file_input_selector'])).first.set_input_files(
|
||||
page.goto(_upload_entry_url('crane', login_url), wait_until="domcontentloaded", timeout=self._timeout_ms())
|
||||
page.locator('input[name="OrderFileUpload"]').first.set_input_files(
|
||||
str(self.file_path), timeout=self._timeout_ms(),
|
||||
)
|
||||
if str(self.config.get('submit_mode') or '').strip() == 'click_submit':
|
||||
page.locator(str(self.config['submit_selector'])).first.click(timeout=self._timeout_ms())
|
||||
return self._resolve_result(page)
|
||||
result = self._resolve_result(page)
|
||||
if result.get('outcome') == 'allocating':
|
||||
raise _UploadAcceptedAllocating(self.file_path.stem)
|
||||
return result
|
||||
|
||||
def run_status_check(self, page: Any, *, login_url: str, pull_request_no: str) -> dict[str, Any]:
|
||||
"""重新登录后只按 Pull Request # 读行,不选择、不提交文件。"""
|
||||
_ensure_crane_session(page, login_url)
|
||||
page.goto(_upload_entry_url('crane', login_url), wait_until="domcontentloaded", timeout=self._timeout_ms())
|
||||
found = self._wait_for_order_status(page, f'{pull_request_no}.xlsx', wait_seconds=20)
|
||||
if found and found.get('success_evidence'):
|
||||
return found
|
||||
return {'outcome': 'allocating', 'pull_request_no': pull_request_no}
|
||||
|
||||
def _require_result_fields(self) -> None:
|
||||
result_mode = str(self.config.get('result_mode') or '').strip()
|
||||
@@ -2242,83 +2280,22 @@ class CraneUploadAdapter(_BaseUploadAdapter):
|
||||
return None
|
||||
|
||||
def _resolve_result(self, page: Any) -> dict[str, Any]:
|
||||
result_mode = str(self.config.get('result_mode') or '').strip()
|
||||
"""读发货单行。已分配或分配中立即返回;明确弹窗拒绝则失败。"""
|
||||
filename = self.file_path.name
|
||||
# [STEP 1] Crane 页面成功反馈后仍需核对发货通知列表中的业务状态,
|
||||
# 只有 Processing + Shipping Order Allocated 才视为真正上传成功。
|
||||
status_result = self._wait_for_order_status(page, filename)
|
||||
# [STEP 1] 只有 Processing + Shipping Order Allocated 才是上传成功。
|
||||
# Processing + Allocating the Shipping Order 表示货代已接收,稍后回查。
|
||||
status_result = self._wait_for_order_status(page, filename, wait_seconds=30)
|
||||
if status_result:
|
||||
return status_result
|
||||
# 提交后先探测一次失败/成功弹窗;判定期内仍会持续探测(结果选择器可能晚于弹窗出现)。
|
||||
# [STEP 2] 客户或仓库不存在等明确拒绝记失败。看不到行时不按后台选择器猜成功。
|
||||
self._raise_if_crane_error(page)
|
||||
success = self._success_from_popup(page, filename)
|
||||
if success:
|
||||
return success
|
||||
if result_mode == 'history_record':
|
||||
result_selector = str(self.config.get('result_selector') or '').strip()
|
||||
try:
|
||||
loc = page.locator(result_selector).first
|
||||
loc.wait_for(state='visible', timeout=self._timeout_ms())
|
||||
except Exception as exc:
|
||||
# 判定期内可能出现失败弹窗(如 Customer/Warehouse 未找到);先读取并关闭,
|
||||
# 以真实原因上报失败;否则仍按“结果未知”转人工。
|
||||
self._raise_if_crane_error(page)
|
||||
success = self._success_from_popup(page, filename)
|
||||
if success:
|
||||
return success
|
||||
raise _UploadResultUnknownError(
|
||||
f"无法判断上传是否成功/失败:{filename!r} 历史结果未确认({exc});"
|
||||
f"可能已上传成功但页面未出现成功提示,或 upload_config 的 result_selector/success_texts 配置有误;"
|
||||
f"请人工在 CRANE 核查,或用「确认已上传」登记,或修正配置后重试。"
|
||||
) from exc
|
||||
try:
|
||||
reference = str(loc.text_content(timeout=self._timeout_ms()) or '').strip()
|
||||
except Exception:
|
||||
reference = ''
|
||||
return {
|
||||
'reference': reference,
|
||||
'success_evidence': _capture_success_page_evidence(
|
||||
page, kind='crane_history_record', selector=result_selector,
|
||||
filename=filename, reference=reference or None,
|
||||
),
|
||||
}
|
||||
# page_notice:要求 result_selector 可见且内容命中任一 success_texts。
|
||||
result_selector = str(self.config.get('result_selector') or '').strip()
|
||||
success_texts = [str(t).strip() for t in (self.config.get('success_texts') or []) if str(t).strip()]
|
||||
deadline = time.monotonic() + (self._timeout_ms() / 1000)
|
||||
last_snippet = ''
|
||||
while time.monotonic() < deadline:
|
||||
# 上传失败时 Crane 会先弹错误窗而非成功提示;命中则读取原因、点 OK 关闭并上报失败。
|
||||
self._raise_if_crane_error(page)
|
||||
# 成功也可能以 SweetAlert2 成功弹窗反馈;优先于配置 result_selector 判定,避免配置错误误报 unknown。
|
||||
success = self._success_from_popup(page, filename)
|
||||
if success:
|
||||
return success
|
||||
try:
|
||||
loc = page.locator(result_selector).first
|
||||
if loc.count() > 0 and loc.is_visible():
|
||||
snippet = str(loc.text_content(timeout=1000) or '').strip()
|
||||
last_snippet = snippet
|
||||
if any(text in snippet for text in success_texts):
|
||||
return {
|
||||
'reference': '',
|
||||
'success_evidence': _capture_success_page_evidence(
|
||||
page, kind='crane_page_notice', selector=result_selector,
|
||||
filename=filename, reference=None,
|
||||
),
|
||||
}
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise _UploadResultUnknownError(
|
||||
f"无法判断上传是否成功/失败:{filename!r} 结果未确认(last_snippet={last_snippet!r});"
|
||||
f"可能已上传成功但页面未出现成功提示,或 upload_config 的 result_selector/success_texts 配置有误;"
|
||||
f"请人工在 CRANE 核查,或用「确认已上传」登记,或修正配置后重试。"
|
||||
f"无法判断上传是否成功/失败:{filename!r} 未出现 Processing + Allocating 或 Shipping Order Allocated。"
|
||||
)
|
||||
|
||||
def _wait_for_order_status(self, page: Any, filename: str) -> dict[str, Any] | None:
|
||||
"""轮询 Crane 发货通知表,按上传单号核对 Processing/Shipping Order Allocated。"""
|
||||
result_selector = str(self.config.get('result_selector') or '').strip()
|
||||
def _wait_for_order_status(self, page: Any, filename: str, *, wait_seconds: int = 30) -> dict[str, Any] | None:
|
||||
"""轮询 Crane 发货通知表。看到 Allocating 立刻返回,不等到 Allocated。"""
|
||||
result_selector = ''
|
||||
script = """
|
||||
({ filename, resultSelector }) => {
|
||||
const clean = (v) => String(v || '').replace(/\\s+/g, ' ').trim();
|
||||
@@ -2338,15 +2315,18 @@ class CraneUploadAdapter(_BaseUploadAdapter):
|
||||
return { found: false, order_status: '', order_status_description: '' };
|
||||
}
|
||||
"""
|
||||
deadline = time.monotonic() + (self._timeout_ms() / 1000)
|
||||
deadline = time.monotonic() + max(1, int(wait_seconds))
|
||||
last_state: dict[str, Any] = {}
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
state = page.evaluate(script, {'filename': filename, 'resultSelector': result_selector}) or {}
|
||||
if isinstance(state, dict):
|
||||
last_state = state
|
||||
if _crane_upload_result_is_allocating(state):
|
||||
return {'outcome': 'allocating', 'pull_request_no': Path(filename).stem}
|
||||
if _crane_upload_result_is_success(state):
|
||||
return {
|
||||
'outcome': 'allocated',
|
||||
'reference': '',
|
||||
'success_evidence': _capture_success_page_evidence(
|
||||
page, kind='crane_order_status_dom', selector='tr[id^="shipping-order-"]',
|
||||
@@ -2429,6 +2409,41 @@ def _upload_shipment_with_browser(
|
||||
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
|
||||
|
||||
|
||||
def _check_crane_allocation(upload_source: dict[str, Any], pull_request_no: str) -> dict[str, Any]:
|
||||
"""重新登录 Crane,只按 Pull Request # 读取发货单行。"""
|
||||
login_url = str(upload_source.get('login_url') or '').strip()
|
||||
playwright = context = runtime_profile_dir = None
|
||||
failed = False
|
||||
try:
|
||||
playwright, context, page, runtime_profile_dir = _open_browser(Path('.'), reuse_session=False)
|
||||
adapter = CraneUploadAdapter(file_path=Path(f'{pull_request_no}.xlsx'), upload_config={})
|
||||
with _profile_credentials(upload_source):
|
||||
return adapter.run_status_check(page, login_url=login_url, pull_request_no=pull_request_no)
|
||||
except Exception:
|
||||
failed = True
|
||||
raise
|
||||
finally:
|
||||
if not (failed and _env("FREIGHT_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR", "false").lower() == "true"):
|
||||
if context is not None:
|
||||
context.close()
|
||||
if playwright is not None:
|
||||
playwright.stop()
|
||||
if runtime_profile_dir is not None:
|
||||
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
|
||||
|
||||
|
||||
def _post_allocating_callback(body: dict[str, Any], *, pull_request_no: str) -> None:
|
||||
"""回调 Crane 已接收、仍在分配。不带成功证据。"""
|
||||
_post_callback(UPLOAD_COMPLETE, {
|
||||
"task_no": body.get("task_no"),
|
||||
"attempt_id": body.get("attempt_id"),
|
||||
"callback_id": body.get("callback_id"),
|
||||
"result": "allocating",
|
||||
"success": False,
|
||||
"pull_request_no": pull_request_no,
|
||||
})
|
||||
|
||||
|
||||
def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
|
||||
body = json.loads(trigger_path.read_text(encoding="utf-8"))
|
||||
task_no = str(body.get("task_no") or "").strip()
|
||||
@@ -2436,11 +2451,49 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
|
||||
attempt_id = body.get("attempt_id")
|
||||
callback_id = str(body.get("callback_id") or "").strip()
|
||||
failed_dir = processed_dir.parent / "failed"
|
||||
status_check = str(body.get("mode") or "").strip() == "status_check"
|
||||
if not task_no:
|
||||
trigger_path.unlink(missing_ok=True)
|
||||
return
|
||||
|
||||
mock = _env("FREIGHT_RPA_WORKER_MOCK", "false").lower() == "true"
|
||||
if status_check and not mock:
|
||||
try:
|
||||
upload_source = {
|
||||
"connector_type": str(body.get("connector_type") or "").strip(),
|
||||
"login_url": str(body.get("login_url") or "").strip(),
|
||||
"credential_envelope": body.get("credential_envelope"),
|
||||
"upload_config_json": body.get("upload_config") or {"enabled": True},
|
||||
}
|
||||
pull_request_no = str(body.get("pull_request_no") or Path(file_path).stem).strip()
|
||||
raw = _check_crane_allocation(upload_source, pull_request_no)
|
||||
if raw.get("success_evidence"):
|
||||
_post_callback(UPLOAD_COMPLETE, {
|
||||
"task_no": task_no,
|
||||
"attempt_id": attempt_id,
|
||||
"callback_id": callback_id,
|
||||
"result": "success",
|
||||
"success": True,
|
||||
"success_evidence": raw.get("success_evidence"),
|
||||
})
|
||||
else:
|
||||
_post_allocating_callback(body, pull_request_no=pull_request_no)
|
||||
_move_trigger(trigger_path, processed_dir, "processed")
|
||||
except Exception as exc:
|
||||
try:
|
||||
_post_callback(UPLOAD_COMPLETE, {
|
||||
"task_no": task_no,
|
||||
"attempt_id": attempt_id,
|
||||
"callback_id": callback_id,
|
||||
"result": "allocating",
|
||||
"success": False,
|
||||
"error_message": str(exc)[:500],
|
||||
})
|
||||
_move_trigger(trigger_path, processed_dir, "processed after status check error")
|
||||
except Exception as callback_exc:
|
||||
_report_callback_failure(trigger_path, failed_dir, callback_exc)
|
||||
return
|
||||
|
||||
if not file_path or not Path(file_path).is_file():
|
||||
try:
|
||||
_post_callback(UPLOAD_COMPLETE, {
|
||||
@@ -2502,6 +2555,13 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
|
||||
})
|
||||
_move_trigger(trigger_path, processed_dir, "processed")
|
||||
print(f"[upload] {'mock' if mock else 'browser'} upload done for {task_no} ref={ref or '-'}")
|
||||
except _UploadAcceptedAllocating as exc:
|
||||
try:
|
||||
_post_allocating_callback(body, pull_request_no=exc.pull_request_no)
|
||||
_move_trigger(trigger_path, processed_dir, "processed")
|
||||
print(f"[upload] crane accepted {task_no} pull_request={exc.pull_request_no}; waiting for allocation")
|
||||
except Exception as callback_exc:
|
||||
_report_callback_failure(trigger_path, failed_dir, callback_exc)
|
||||
except Exception as exc:
|
||||
try:
|
||||
_post_callback(UPLOAD_COMPLETE, {
|
||||
|
||||
Reference in new issue
Block a user