Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6ad93e829c | ||
|
|
5ede1cbcc4 | ||
|
|
22b05c91a2 | ||
|
|
d2e7eb678a | ||
|
|
f723732eb5 | ||
|
|
f0ac888d60 | ||
|
|
594d9c22b5 | ||
|
|
d635a2920c | ||
|
|
821bd0a62c | ||
|
|
e87dca85a3 | ||
|
|
42d8b70250 | ||
|
|
298fadf1c8 | ||
|
|
36868f875c | ||
|
|
7fb36b301c | ||
|
|
616034a4cd | ||
|
|
3de24fd373 | ||
|
|
49f6a0f222 |
No files matched your search
@@ -102,7 +102,6 @@ SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
|
||||
# 复核工作台字段级 AI 建议;仅开发环境启用,建议仍须证据校验与人工裁决
|
||||
SHIPPING_NOTICE_LLM_REVIEW_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
@@ -110,7 +109,6 @@ SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
|
||||
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
||||
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||
@@ -135,7 +133,6 @@ SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true
|
||||
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=true
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||
@@ -157,8 +154,6 @@ FREIGHT_RPA_WORKER_MOCK=false
|
||||
# 本机无 Redis 时允许进程内存记录心跳;有 Redis 时优先写 Redis
|
||||
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false
|
||||
FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK=true
|
||||
# 企微心跳告警总开关(默认关闭;需要时改为 true)
|
||||
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
|
||||
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
|
||||
# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=
|
||||
# --- 10. 运维、告警与维护工具 ---
|
||||
|
||||
@@ -25,8 +25,6 @@ HXOPS_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||
AUTH_LOGIN_MODE=casdoor
|
||||
# 如果需要用户密码登录,修改该值为password
|
||||
# AUTH_LOGIN_MODE=password
|
||||
# 是否启用 JWT 认证
|
||||
AUTH_JWT_REQUIRED=true
|
||||
AUTH_JWT_ISSUER=https://auth.well-trust.com
|
||||
AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
|
||||
AUTH_JWT_JWKS_URL=https://auth.well-trust.com/.well-known/jwks
|
||||
@@ -72,7 +70,6 @@ GUNICORN_WORKERS=20
|
||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||
WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
|
||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,training_overseas_thailand_guidelines
|
||||
WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||
|
||||
# --- 5. 数据库与基础设施 ---
|
||||
@@ -116,7 +113,6 @@ SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
|
||||
|
||||
# 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享)
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
@@ -138,7 +134,6 @@ SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=false
|
||||
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=false
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=false
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
|
||||
# RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。
|
||||
# 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。
|
||||
FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
|
||||
@@ -146,8 +141,6 @@ FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
|
||||
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
|
||||
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
||||
# 企微心跳告警总开关(默认关闭;需要时改为 true)
|
||||
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
|
||||
# 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微
|
||||
FREIGHT_RPA_WORKER_ALERT_USERNAMES=
|
||||
FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
|
||||
@@ -162,10 +155,7 @@ FREIGHT_RPA_RECEIPT_ARCHIVE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/arc
|
||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_queue
|
||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_triggers
|
||||
# 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod
|
||||
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
||||
# --- 10. 运维、告警与维护工具 ---
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
+1
-1
@@ -150,7 +150,7 @@ WECOM_TRUSTED_DOMAIN=
|
||||
WECOM_PUBLIC_BASE_URL=
|
||||
WECOM_NOTIFY_ENABLED=true
|
||||
WECOM_NOTIFY_BASE_URL=
|
||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,training_overseas_thailand_guidelines
|
||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,order_delivery_reply_notify,training_overseas_thailand_guidelines
|
||||
WECOM_FEEDBACK_NOTIFY_ENABLED=true
|
||||
WECOM_FEEDBACK_NOTIFY_BASE_URL=http://ai.well-trust.com:8881
|
||||
# 企业微信群机器人 webhook,按环境写入 .env.<env> 或部署平台变量;不要提交真实 URL。
|
||||
|
||||
@@ -24,8 +24,6 @@ HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||
# 如果需要用户密码登录,修改该值为password
|
||||
#AUTH_LOGIN_MODE=casdoor
|
||||
AUTH_LOGIN_MODE=casdoor
|
||||
# 是否启用 JWT 认证
|
||||
AUTH_JWT_REQUIRED=true
|
||||
|
||||
# 必须与 CASDOOR_BASE_URL discovery 返回的 issuer 完全一致,不能填写 HXOPS 地址。
|
||||
AUTH_JWT_ISSUER=https://autht.well-trust.com
|
||||
@@ -72,7 +70,6 @@ GUNICORN_WORKERS=6
|
||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||
WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
|
||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,training_overseas_thailand_guidelines
|
||||
WECOM_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||
HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||
|
||||
@@ -120,13 +117,11 @@ SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
|
||||
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
||||
# 货代专用 Tool API Key(RPA 回调优先读取;真实值请在服务器本地配置,禁止提交真实密钥)
|
||||
@@ -151,7 +146,6 @@ SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true
|
||||
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=true
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐)
|
||||
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
|
||||
@@ -159,8 +153,6 @@ FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||
FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
||||
# 企微心跳告警总开关(默认关闭;需要时改为 true)
|
||||
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
|
||||
# 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微
|
||||
# 两者皆无则告警只写日志、不会发企微
|
||||
FREIGHT_RPA_WORKER_ALERT_USERNAMES=
|
||||
@@ -185,10 +177,7 @@ FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inven
|
||||
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
|
||||
# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=
|
||||
# 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
|
||||
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
||||
# --- 10. 运维、告警与维护工具 ---
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
+13
-1
@@ -122,6 +122,16 @@ def create_app(config_name='default'):
|
||||
ensure_default_contract_payment_schedules()
|
||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||
logger.warning('Failed to ensure contract-payment schedules: %s', exc)
|
||||
try:
|
||||
from app.services.order_delivery_reply.schedule_seed import ensure_default_order_delivery_schedules
|
||||
ensure_default_order_delivery_schedules()
|
||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||
logger.warning('Failed to ensure order-delivery-reply schedule: %s', exc)
|
||||
try:
|
||||
from app.services.order_delivery_reply.app_seed import ensure_builtin_order_delivery_agent
|
||||
ensure_builtin_order_delivery_agent()
|
||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||
logger.warning('Failed to ensure order-delivery-reply agent: %s', exc)
|
||||
try:
|
||||
from app.services.lean_training_schedule_seed import ensure_default_lean_training_schedule
|
||||
ensure_default_lean_training_schedule()
|
||||
@@ -129,7 +139,9 @@ def create_app(config_name='default'):
|
||||
logger.warning('Failed to ensure lean-training schedule: %s', exc)
|
||||
else:
|
||||
logger.info('Skip startup schedule seeding: schedule_tasks table is not ready')
|
||||
# 固资快照同步已迁至独立进程 workers/worker_fixed_assets.py,Web 不再起线程。
|
||||
# 固资快照同步已迁至独立进程 workers/worker_fixed_assets.py,Web 不再起线程;
|
||||
# 排程执行同样由独立 worker 进程(workers/worker_scheduler.py,生产 hxops-schedule-worker 容器)
|
||||
# 负责(dev Wave 4),Web 进程不再兜底扫描。
|
||||
# AUTO_UPLOAD 显式开启时启动级校验货代上传 RPA(仅告警,不阻断启动)。
|
||||
try:
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
|
||||
@@ -49,6 +49,7 @@ def register_blueprints(app: Flask) -> None:
|
||||
)
|
||||
from app.api.files import files_bp
|
||||
from app.api.contract_payment import contract_payment_bp
|
||||
from app.api.order_delivery_reply import order_delivery_reply_bp
|
||||
from app.api.in_transit_transfer import in_transit_transfer_bp
|
||||
from app.api.integration_connector import integration_connector_bp
|
||||
|
||||
@@ -80,5 +81,6 @@ def register_blueprints(app: Flask) -> None:
|
||||
app.register_blueprint(files_bp, url_prefix='/api/files')
|
||||
app.register_blueprint(procurement_contract_bp, url_prefix='/api/procurement-contract')
|
||||
app.register_blueprint(contract_payment_bp, url_prefix='/api/contract-payment')
|
||||
app.register_blueprint(order_delivery_reply_bp, url_prefix='/api/order-delivery-reply')
|
||||
app.register_blueprint(in_transit_transfer_bp, url_prefix='/api/in-transit-transfer')
|
||||
app.register_blueprint(integration_connector_bp, url_prefix='/api/integration-connector')
|
||||
@@ -39,6 +39,7 @@ def chat_completions():
|
||||
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
|
||||
conversation_id = data.get('conversation_id')
|
||||
shipping_task_id = str(data.get('task_id') or '').strip()
|
||||
shipping_batch_no = str(data.get('batch_no') or '').strip()
|
||||
kb_type = data.get('kb_type', '企业知识库')
|
||||
files = data.get('files')
|
||||
request_id = uuid.uuid4().hex[:12]
|
||||
@@ -174,6 +175,7 @@ def chat_completions():
|
||||
normalized_files=normalized_files,
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
),
|
||||
shipping_task_id=shipping_task_id,
|
||||
kb_type=kb_type,
|
||||
@@ -214,6 +216,7 @@ def chat_completions():
|
||||
user_role=user_proxy.role,
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -10,19 +10,21 @@ from __future__ import annotations
|
||||
from .shared import * # noqa: F403
|
||||
|
||||
|
||||
def _build_chat_adapter_hints(*, shipping_task_id: str | None = None) -> dict | None:
|
||||
def _build_chat_adapter_hints(*, shipping_task_id: str | None = None, shipping_batch_no: str | None = None) -> dict | None:
|
||||
"""
|
||||
构建聊天入口分发给领域 adapter 的提示字典。
|
||||
|
||||
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task 提示,
|
||||
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task/batch 提示,
|
||||
统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。
|
||||
"""
|
||||
task_id = str(shipping_task_id or '').strip()
|
||||
if not task_id:
|
||||
batch_no = str(shipping_batch_no or '').strip()
|
||||
if not task_id and not batch_no:
|
||||
return None
|
||||
return {
|
||||
'shipping_notice': {
|
||||
'task_id': task_id or None,
|
||||
'batch_no': batch_no or None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
"""
|
||||
backend/app/api/order_delivery_reply.py
|
||||
|
||||
用途:订单交期回复工作台 API——列表筛选分页、单行详情、最近同步时间、保存交期批次、单行通知、
|
||||
联合回复保存与批量通知、手动全量同步。
|
||||
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError/NotFoundError/ValidationError、
|
||||
services/order_delivery_reply(query_service 查询、reply_service 保存批次、
|
||||
notify_service 通知锁定、sync_service 同步状态)。
|
||||
逻辑:读取只打本地快照,不触碰 ERP;保存批次只写批次与 save 审计,不通知不锁定;
|
||||
通知与锁定在 notify_service 中同事务完成(企微成功才锁定)。
|
||||
权限要求 access 或 manage(manage 隐含 access),键常量与技术文档 §7.2 一致;写接口要求 manage。
|
||||
鉴权:GET 系列要求 `order_delivery_reply.access` 或 `order_delivery_reply.manage`;
|
||||
保存批次 / 单行通知 / 联合回复 / 批量通知 / 手动同步要求 `order_delivery_reply.manage`;
|
||||
部门批量发放仅 admin 角色。两键 admin 默认开(User._role_default_feature_permissions)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, g, request
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.extensions import db
|
||||
from app.models import User
|
||||
from app.services.order_delivery_reply import notify_service, query_service, reply_service
|
||||
from app.services.order_delivery_reply.sync_service import OrderDeliverySyncService
|
||||
|
||||
order_delivery_reply_bp = Blueprint("order_delivery_reply", __name__)
|
||||
|
||||
|
||||
def _utc_to_shanghai(value) -> str | None:
|
||||
"""
|
||||
把后端 naive-UTC 时间转为北京时间的展示字符串(YYYY-MM-DD HH:MM:SS)。
|
||||
|
||||
用途:sync_runs / notified_at 等以 utcnow 落库,直接 isoformat 会把 UTC 当本地时间误导用户。
|
||||
约束:仅用于展示序列化,不改变库内存储;无法解析时原样返回。
|
||||
"""
|
||||
from datetime import timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
local = value.replace(tzinfo=timezone.utc).astimezone(ZoneInfo("Asia/Shanghai"))
|
||||
return local.strftime("%Y-%m-%d %H:%M:%S")
|
||||
except (AttributeError, ValueError):
|
||||
return value.isoformat() if hasattr(value, "isoformat") else str(value)
|
||||
|
||||
# 功能权限键(与 docs/features/order-delivery-reply/technical-design.md §7.2 对齐)。
|
||||
PERMISSION_MANAGE = "order_delivery_reply.manage"
|
||||
PERMISSION_ACCESS = "order_delivery_reply.access"
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""返回当前登录用户;未认证抛 UnauthorizedError。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _has_order_delivery_permission(user, key: str) -> bool:
|
||||
"""
|
||||
判定功能权限:统一走 User.has_feature_permission(角色默认 + 显式勾选合并)。
|
||||
|
||||
核心逻辑:admin 角色两键默认开(User._role_default_feature_permissions);
|
||||
普通用户按用户管理表单勾选;每次请求只看勾选,不拿部门当门禁(技术文档 §7.2)。
|
||||
"""
|
||||
return user.has_feature_permission(key)
|
||||
|
||||
|
||||
def _require_access():
|
||||
"""
|
||||
确保当前用户可访问订单交期回复(查看)。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 未登录。
|
||||
ForbiddenError: 已登录但既无 manage 也无 access(manage 命中视为有 access)。
|
||||
"""
|
||||
user = _require_user()
|
||||
if not (_has_order_delivery_permission(user, PERMISSION_MANAGE) or _has_order_delivery_permission(user, PERMISSION_ACCESS)):
|
||||
raise ForbiddenError(
|
||||
"Order delivery reply access required",
|
||||
code="ORDER_DELIVERY_REPLY.FORBIDDEN",
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
def _require_manage():
|
||||
"""
|
||||
确保当前用户可写订单交期回复(保存批次 / 通知 / 手动同步)。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 未登录。
|
||||
ForbiddenError: 已登录但无 manage(仅有 access 的业务用户只读)。
|
||||
"""
|
||||
user = _require_user()
|
||||
if not _has_order_delivery_permission(user, PERMISSION_MANAGE):
|
||||
raise ForbiddenError(
|
||||
"Order delivery reply manage permission required",
|
||||
code="ORDER_DELIVERY_REPLY.MANAGE_FORBIDDEN",
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
@order_delivery_reply_bp.get("/lines")
|
||||
def list_lines():
|
||||
"""
|
||||
订单行列表(筛选 + 分页)。
|
||||
|
||||
用途与触发时机:工作台首屏与筛选刷新;全选仅作用于本页返回的 items。
|
||||
|
||||
参数与输出约束:查询参数 keyword/order_date/status/page/page_size——keyword 为合并搜索
|
||||
(订单单号/客户订单/客户编号/客户简称/公司全名/产品编号/品名/客户产品编号
|
||||
命中任一即返回);status ∈ 空(全部) | replied(已回复) | not_fully_replied(未完全回复);
|
||||
返回统一 envelope,data.items 为行序列化(含批次、状态、未交数量)。
|
||||
"""
|
||||
_require_access()
|
||||
data = query_service.list_lines(request.args.to_dict(flat=True))
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@order_delivery_reply_bp.get("/lines/<order_no>/<int:line_no>")
|
||||
def get_line(order_no: str, line_no: int):
|
||||
"""
|
||||
单行详情:快照 + 批次 + 状态 + 审计事件。
|
||||
|
||||
参数与输出约束:order_no/line_no 为行唯一键;不存在或已标 erp_missing(已不在同步范围)
|
||||
的行一律按不存在处理返回 404,不在工作台展示。
|
||||
"""
|
||||
_require_access()
|
||||
payload = query_service.get_line(order_no, line_no)
|
||||
if payload is None:
|
||||
raise NotFoundError(
|
||||
"Order delivery line not found",
|
||||
code="ORDER_DELIVERY_REPLY.LINE_NOT_FOUND",
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@order_delivery_reply_bp.put("/lines/<order_no>/<int:line_no>/batches")
|
||||
def save_line_batches(order_no: str, line_no: int):
|
||||
"""
|
||||
保存单行交期批次(未锁定行整表替换)。
|
||||
|
||||
用途与触发时机:单行弹窗「回复交期/修改回复」提交;联合回复保存逐行复用同一服务入口。
|
||||
|
||||
参数与输出约束:body {"batches": [{planned_date, qty, remark?}]};交期必填 YYYY-MM-DD、
|
||||
数量 > 0、备注 ≤ 200、批次 1..20 条且交期不重复;各批次合计必须等于订单数量,
|
||||
不等返回 422 BATCH_QTY_TOTAL_MISMATCH(2026-09-23 由「超额仅提醒」修订)。
|
||||
已锁定行返回 409 LINE_LOCKED;erp_missing 行按 404。
|
||||
"""
|
||||
user = _require_manage()
|
||||
payload = request.get_json(silent=True) or {}
|
||||
data = reply_service.save_batches(order_no, line_no, payload.get("batches"), user.id)
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@order_delivery_reply_bp.post("/lines/<order_no>/<int:line_no>/notify")
|
||||
def notify_line(order_no: str, line_no: int):
|
||||
"""
|
||||
单行发送通知业务部门(企微),成功后行级锁定。
|
||||
|
||||
用途与触发时机:生管在行内点「发送通知业务部门」(该行已有批次且未锁定时可用)。
|
||||
|
||||
参数与输出约束:无 body;无批次 422(请先回复交期)、已锁定 409、业务员对不上
|
||||
User.employee_id 或企微发送失败 503(该行不锁定);成功返回
|
||||
locked=true 与交期回复人员(生管工号+姓名)、通知时间、trace_id。
|
||||
"""
|
||||
user = _require_manage()
|
||||
data = notify_service.notify_line(order_no, line_no, user)
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@order_delivery_reply_bp.post("/batch-reply")
|
||||
def batch_reply():
|
||||
"""
|
||||
联合回复交期:对勾选多行逐行保存批次(只保存,不通知、不锁定)。
|
||||
|
||||
用途与触发时机:勾选多行 →「+ 联合回复交期」→ 按行填批次 → 保存回复(R-REPLY-02)。
|
||||
|
||||
参数与输出约束:body {"items": [{order_no, line_no, batches: [{planned_date, qty, remark?}]}]},
|
||||
单次 ≤ 200 行;每行各批次合计必须等于订单数量(不等该行失败,2026-09-23 修订);
|
||||
单行失败不回滚其它行,响应按行给 ok/error;
|
||||
全部行保存成功 success 才为 true 语义由 data.succeeded/failed 表达。
|
||||
"""
|
||||
user = _require_manage()
|
||||
payload = request.get_json(silent=True) or {}
|
||||
data = reply_service.batch_reply(payload.get("items"), user.id)
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@order_delivery_reply_bp.post("/notify-batch")
|
||||
def notify_batch():
|
||||
"""
|
||||
批量通知:对勾选中「已有批次且未锁定」的行逐行发送企微通知并锁定。
|
||||
|
||||
用途与触发时机:勾选多行 → 工具栏「批量通知」(R-NOTIFY-02);与联合回复是两个独立操作。
|
||||
|
||||
参数与输出约束:body {"lines": [{order_no, line_no}]},单次 ≤ 200 行;
|
||||
无批次或已锁定的勾选行 skipped(带 reason)不计成败;
|
||||
单行失败不回滚其它行;返回 succeeded/failed/skipped 与逐行结果。
|
||||
"""
|
||||
user = _require_manage()
|
||||
payload = request.get_json(silent=True) or {}
|
||||
data = notify_service.notify_batch(payload.get("lines"), user)
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@order_delivery_reply_bp.get("/sync/latest")
|
||||
def latest_sync():
|
||||
"""
|
||||
最近一次同步运行记录,供页面展示同步时间与结果。
|
||||
|
||||
参数与输出约束:无参数;从未同步过时 data 为 null(前端展示「尚未同步」),
|
||||
失败时返回 failed 状态与错误摘要,前端明示同步失败并保留上次快照口径。
|
||||
"""
|
||||
_require_access()
|
||||
run = OrderDeliverySyncService.latest_run()
|
||||
if run is None:
|
||||
return ok(None, request_id=getattr(g, "request_id", None))
|
||||
return ok(
|
||||
{
|
||||
"id": run.id,
|
||||
"trigger": run.trigger,
|
||||
"status": run.status,
|
||||
"started_at": _utc_to_shanghai(run.started_at),
|
||||
"finished_at": _utc_to_shanghai(run.finished_at),
|
||||
"line_count": run.line_count,
|
||||
"error_message": run.error_message,
|
||||
},
|
||||
request_id=getattr(g, "request_id", None),
|
||||
)
|
||||
|
||||
|
||||
@order_delivery_reply_bp.post("/sync")
|
||||
def run_sync():
|
||||
"""
|
||||
手动触发一次 ERP 全量同步(范围与 07:00 排程完全一致)。
|
||||
|
||||
用途与触发时机:生管在工作台点「手动刷新」(需求 §15);同步互斥——排程正在跑时
|
||||
返回 skipped,不并发执行。
|
||||
|
||||
参数与输出约束:无 body;同步在本请求内同步执行(一期口径,行量在万级内可控),
|
||||
返回 {run_id, status: success|skipped, line_count};失败原样抛 AppError
|
||||
(上次快照保留,页面明示失败原因)。
|
||||
"""
|
||||
_require_manage()
|
||||
data = OrderDeliverySyncService.run_sync(trigger="manual")
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@order_delivery_reply_bp.post("/admin/permissions/grant-by-department")
|
||||
def grant_permissions_by_department():
|
||||
"""
|
||||
按部门批量发放订单交期回复功能权限(可选能力,仅 admin)。
|
||||
|
||||
用途与触发时机:用户量大时管理员选部门一次性把勾选写到当时该部门成员账号上(需求 §3)。
|
||||
|
||||
参数与输出约束:body {"department": "<部门名>", "permission": "manage" | "access"};
|
||||
这是一次性发放——调岗后权限不随部门字段变化自动增减,需再勾或再跑一次;
|
||||
只做授予(置 true),不撤销;返回 {"department", "permission", "granted"}。
|
||||
部门无成员时 granted=0,不视为错误。
|
||||
"""
|
||||
user = _require_user()
|
||||
if getattr(user, "role", None) != "admin":
|
||||
raise ForbiddenError(
|
||||
"Admin privilege required for department permission grant",
|
||||
code="ORDER_DELIVERY_REPLY.ADMIN_REQUIRED",
|
||||
)
|
||||
payload = request.get_json(silent=True) or {}
|
||||
department = str(payload.get("department") or "").strip()
|
||||
permission = str(payload.get("permission") or "").strip()
|
||||
if not department:
|
||||
raise ValidationError("department 必填", code="ORDER_DELIVERY_REPLY.GRANT_DEPARTMENT_REQUIRED")
|
||||
if permission not in (PERMISSION_MANAGE, PERMISSION_ACCESS):
|
||||
raise ValidationError("permission 须为 manage 或 access", code="ORDER_DELIVERY_REPLY.GRANT_PERMISSION_INVALID")
|
||||
|
||||
members = User.query.filter(User.department == department).all()
|
||||
granted = 0
|
||||
for member in members:
|
||||
# [STEP] 经 set_feature_permissions 归一化:只持久化与角色默认不同的覆盖项。
|
||||
raw = dict(member.feature_permissions) if isinstance(member.feature_permissions, dict) else {}
|
||||
raw[permission] = True
|
||||
member.set_feature_permissions(raw)
|
||||
granted += 1
|
||||
db.session.commit()
|
||||
return ok(
|
||||
{"department": department, "permission": permission, "granted": granted},
|
||||
request_id=getattr(g, "request_id", None),
|
||||
)
|
||||
@@ -499,7 +499,7 @@ class Config:
|
||||
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
|
||||
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,training_overseas_thailand_guidelines')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,order_delivery_reply_notify,training_lean_video_push,training_overseas_thailand_guidelines')
|
||||
# 精益培训企微提醒卡片跳转的员工培训聊天页 agent id(前端路由 /chat/<id>)。
|
||||
# 缺省 0 = 不显式指定,由后端按 handler_config.content_profile='training' 动态解析各环境的培训 Agent
|
||||
# (测试/正式环境 Agent ID 不同,动态解析保证卡片均可定位「员工培训-精益管理」);
|
||||
@@ -553,6 +553,13 @@ class Config:
|
||||
SCHEDULE_WORKER_ENABLED = os.getenv('SCHEDULE_WORKER_ENABLED', 'true').lower() == 'true'
|
||||
SCHEDULE_WORKER_POLL_SECONDS = float(os.getenv('SCHEDULE_WORKER_POLL_SECONDS', '30') or '30')
|
||||
SCHEDULE_JOB_RUNNING_TIMEOUT_SECONDS = float(os.getenv('SCHEDULE_JOB_RUNNING_TIMEOUT_SECONDS', '7200') or '7200')
|
||||
# Web 进程内排程兜底扫描:仅本地开发(ENV_NAME=dev,无 schedule-worker 容器)默认开启;
|
||||
# test/prod 由 hxops-schedule-worker 容器负责(run.py 固定走 DevelopmentConfig,不能按配置类判定)。
|
||||
_scanner_env_raw = str(os.getenv('SCHEDULE_WEB_SCANNER_ENABLED') or '').strip().lower()
|
||||
if _scanner_env_raw:
|
||||
SCHEDULE_WEB_SCANNER_ENABLED = _scanner_env_raw in ('1', 'true', 'yes', 'on')
|
||||
else:
|
||||
SCHEDULE_WEB_SCANNER_ENABLED = _normalize_env_name(os.getenv('ENV_NAME') or ACTIVE_ENV_NAME) == 'dev'
|
||||
# Cron 表达式按此时区解读(如 0 12 * * * 表示该时区 12:00);入库 next_run_at 仍为 UTC。
|
||||
SCHEDULE_TIMEZONE = (os.getenv('SCHEDULE_TIMEZONE') or 'Asia/Shanghai').strip()
|
||||
SRM_SQLSERVER_HOST = os.getenv('SRM_SQLSERVER_HOST', '')
|
||||
@@ -778,6 +785,7 @@ class TestingConfig(Config):
|
||||
WTF_CSRF_ENABLED = False
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {}
|
||||
SCHEDULE_WORKER_ENABLED = False
|
||||
SCHEDULE_WEB_SCANNER_ENABLED = False
|
||||
FIXED_ASSETS_SYNC_ENABLED = False
|
||||
FIXED_ASSETS_EXPORT_TO_DOCS = False
|
||||
ENV_NAME = 'dev'
|
||||
|
||||
@@ -238,6 +238,13 @@ from app.models.contract_payment import (
|
||||
ContractPaymentSyncState,
|
||||
ContractPaymentVendorRequest,
|
||||
)
|
||||
from app.models.order_delivery_reply import (
|
||||
OrderDeliveryAuditEvent,
|
||||
OrderDeliveryBatch,
|
||||
OrderDeliveryErpLine,
|
||||
OrderDeliveryLineState,
|
||||
OrderDeliverySyncRun,
|
||||
)
|
||||
from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit
|
||||
|
||||
__all__ = [
|
||||
@@ -440,4 +447,9 @@ __all__ = [
|
||||
'IntegrationInterfaceDefinition',
|
||||
'IntegrationBinding',
|
||||
'IntegrationCall',
|
||||
'OrderDeliveryErpLine',
|
||||
'OrderDeliveryBatch',
|
||||
'OrderDeliveryLineState',
|
||||
'OrderDeliveryAuditEvent',
|
||||
'OrderDeliverySyncRun',
|
||||
]
|
||||
@@ -0,0 +1,146 @@
|
||||
"""
|
||||
backend/app/models/order_delivery_reply.py
|
||||
|
||||
用途:订单交期回复域模型,保存 ERP 订单行快照、交期批次、行级锁定状态、审计与同步运行记录。
|
||||
依赖:models.base.Base、users。
|
||||
逻辑:同步服务只写 erp_lines 的 ERP 快照列;保存回复只写 batches;通知成功路径才写
|
||||
line_states.locked;audit_events 记录保存/通知/锁定/同步;sync_runs 记录每次同步。
|
||||
工作台所有读取只打本地库,禁止回写 ERP。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import Boolean, Date, DateTime, ForeignKey, Index, JSON, Numeric, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class OrderDeliveryErpLine(Base):
|
||||
"""ERP 销售订单行快照(订单单号+项次唯一);仅同步服务写入 ERP 列,不覆盖批次与锁定。"""
|
||||
|
||||
__tablename__ = "order_delivery_erp_lines"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("order_no", "line_no", name="uq_order_delivery_erp_lines_order_line"),
|
||||
Index("ix_order_delivery_erp_lines_order_date", "order_date"),
|
||||
Index("ix_order_delivery_erp_lines_customer_no", "customer_no"),
|
||||
Index("ix_order_delivery_erp_lines_salesperson", "salesperson_code"),
|
||||
Index("ix_order_delivery_erp_lines_slip_code", "slip_code"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
order_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
line_no: Mapped[int] = mapped_column(nullable=False)
|
||||
order_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
customer_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
customer_short_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
customer_full_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
# salesperson_code 对 HXOPS User.employee_id,供企微收件人映射;列表展示 salesperson_name。
|
||||
salesperson_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
salesperson_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
dept_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
dept_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
customer_po: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
part_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
part_name: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
|
||||
spec: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
|
||||
customer_part_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
agreed_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
qty: Mapped[Optional[Decimal]] = mapped_column(Numeric(18, 4), nullable=True)
|
||||
delivered_qty: Mapped[Optional[Decimal]] = mapped_column(Numeric(18, 4), nullable=True)
|
||||
# 单别取 oea01 连字符前段(8301-1605280014 → 8301);一期只落库预留,不展示不过滤。
|
||||
slip_code: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
# 本轮同步未命中但已有批次或锁定的行不删除,置 true 后默认列表不展示。
|
||||
erp_missing: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False, index=True)
|
||||
last_synced_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class OrderDeliveryBatch(Base):
|
||||
"""订单行的交期批次(计划交期+数量+备注);未锁定行保存时整表替换。仅保存回复路径写入。"""
|
||||
|
||||
__tablename__ = "order_delivery_batches"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("line_id", "seq", name="uq_order_delivery_batches_line_seq"),
|
||||
Index("ix_order_delivery_batches_line", "line_id"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
line_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("order_delivery_erp_lines.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
seq: Mapped[int] = mapped_column(nullable=False)
|
||||
planned_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||
qty: Mapped[Decimal] = mapped_column(Numeric(18, 4), nullable=False)
|
||||
# 备注 ≤ 200 字符,由 API 层校验。
|
||||
remark: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class OrderDeliveryLineState(Base):
|
||||
"""订单行锁定状态(一行一态);仅通知成功路径写入 locked=true,与通知同一事务。"""
|
||||
|
||||
__tablename__ = "order_delivery_line_states"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("line_id", name="uq_order_delivery_line_states_line"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
line_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("order_delivery_erp_lines.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
locked: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
# 交期回复人员 = 最近一次发送成功的生管;存快照工号+姓名便于审计回溯。
|
||||
notified_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
||||
notified_employee_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
notified_user_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
notified_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class OrderDeliveryAuditEvent(Base):
|
||||
"""订单交期回复审计:保存批次、发送通知、锁定、同步、出货提醒、未回复提醒六类动作。"""
|
||||
|
||||
__tablename__ = "order_delivery_audit_events"
|
||||
__table_args__ = (
|
||||
Index("ix_order_delivery_audit_events_line", "line_id"),
|
||||
Index("ix_order_delivery_audit_events_action", "action", "created_at"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
# sync 事件无具体行时 line_id 为空。
|
||||
line_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey("order_delivery_erp_lines.id", ondelete="CASCADE"), nullable=True
|
||||
)
|
||||
order_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
line_no: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
# save | notify | lock | sync | ship_remind(出货提醒,payload.ok=true 参与去重)| unreplied_remind(未回复再提醒)
|
||||
action: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
operator_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
||||
payload_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class OrderDeliverySyncRun(Base):
|
||||
"""订单交期同步运行记录;同步作业每次运行写一行,失败保留上次快照。"""
|
||||
|
||||
__tablename__ = "order_delivery_sync_runs"
|
||||
__table_args__ = (
|
||||
Index("ix_order_delivery_sync_runs_started", "started_at"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
trigger: Mapped[str] = mapped_column(String(16), nullable=False) # scheduled | manual
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False) # running | success | failed
|
||||
started_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
line_count: Mapped[int] = mapped_column(default=0, nullable=False)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
@@ -30,8 +30,9 @@ class ShippingDocumentProfileAutoFreezeQualification(Base):
|
||||
"status IN ('manual_confirmation', 'auto_freeze_approved', 'auto_freeze_suspended')",
|
||||
name='ck_shipping_document_profile_auto_freeze_qualification_status',
|
||||
),
|
||||
# 索引名沿用迁移 0aa34b5c6d7e 的短名;PostgreSQL 标识符上限 63 字符,超长名会导致建库失败。
|
||||
Index(
|
||||
'ix_shipping_document_profile_auto_freeze_qualification_profile_status',
|
||||
'ix_ship_doc_prof_auto_freeze_profile_status',
|
||||
'profile_id', 'status',
|
||||
),
|
||||
)
|
||||
|
||||
@@ -204,9 +204,10 @@ class ShippingOrderDocumentProfileSuggestionDecision(Base):
|
||||
|
||||
__tablename__ = 'shipping_order_document_profile_suggestion_decisions'
|
||||
__table_args__ = (
|
||||
CheckConstraint("decision IN ('accepted', 'accepted_adjusted', 'rejected')", name='ck_shipping_order_document_profile_suggestion_decisions_decision'),
|
||||
UniqueConstraint('profile_id', 'suggestion_id', name='uq_shipping_order_document_profile_suggestion_decisions_suggestion'),
|
||||
Index('ix_shipping_order_document_profile_suggestion_decisions_profile_revision', 'profile_id', 'revision_no'),
|
||||
# 约束/索引名沿用迁移的短名;PostgreSQL 标识符上限 63 字符,超长名会导致建库失败。
|
||||
CheckConstraint("decision IN ('accepted', 'accepted_adjusted', 'rejected')", name='ck_order_profile_suggestion_decision'),
|
||||
UniqueConstraint('profile_id', 'suggestion_id', name='uq_order_profile_suggestion'),
|
||||
Index('ix_order_profile_suggestion_revision', 'profile_id', 'revision_no'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
@@ -238,8 +239,8 @@ class ShippingOrderDocumentProfileValidationRun(Base):
|
||||
name='ck_shipping_order_document_profile_validation_runs_type',
|
||||
),
|
||||
CheckConstraint("status IN ('pending', 'running', 'passed', 'failed')", name='ck_shipping_order_document_profile_validation_runs_status'),
|
||||
Index('ix_shipping_order_document_profile_validation_runs_profile_created', 'profile_id', 'created_at'),
|
||||
Index('ix_shipping_order_document_profile_validation_runs_checksum', 'profile_id', 'definition_checksum'),
|
||||
Index('ix_order_profile_validation_created', 'profile_id', 'created_at'),
|
||||
Index('ix_order_profile_validation_checksum', 'profile_id', 'definition_checksum'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
@@ -268,10 +269,10 @@ class ShippingOrderDocumentProfilePublishCheckReport(Base):
|
||||
|
||||
__tablename__ = 'shipping_order_document_profile_publish_check_reports'
|
||||
__table_args__ = (
|
||||
CheckConstraint("status IN ('valid', 'invalidated', 'consumed')", name='ck_shipping_order_document_profile_publish_check_reports_status'),
|
||||
UniqueConstraint('profile_id', 'operation_id', name='uq_shipping_order_document_profile_publish_check_reports_operation'),
|
||||
Index('ix_shipping_order_document_profile_publish_check_reports_profile_created', 'profile_id', 'created_at'),
|
||||
Index('ix_shipping_order_document_profile_publish_check_reports_report_no', 'report_no', unique=True),
|
||||
CheckConstraint("status IN ('valid', 'invalidated', 'consumed')", name='ck_sodppcr_status'),
|
||||
UniqueConstraint('profile_id', 'operation_id', name='uq_sodppcr_profile_operation'),
|
||||
Index('ix_sodppcr_profile_created', 'profile_id', 'created_at'),
|
||||
Index('ix_sodppcr_report_no', 'report_no', unique=True),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
|
||||
@@ -100,6 +100,11 @@ class User(Base):
|
||||
'shipping_notice.xfa_split_rule_preview': admin,
|
||||
'shipping_notice.xfa_split_rule_publish': admin,
|
||||
'maintenance.ledger_write': admin,
|
||||
# 合同付款预警已改走 Agent 授权(agent_code=contract_payment),不再占用功能权限键。
|
||||
# 订单交期回复:manage=生管可写(保存/通知/同步),access=业务只读;
|
||||
# manage 命中视为有 access(判定见 api/order_delivery_reply.py)。
|
||||
'order_delivery_reply.manage': admin,
|
||||
'order_delivery_reply.access': admin,
|
||||
}
|
||||
|
||||
def is_platform_admin(self) -> bool:
|
||||
|
||||
@@ -228,10 +228,10 @@ def _section_type_for_line(line: str) -> str | None:
|
||||
|
||||
|
||||
def _extract_repeated_section_answers(lines: list[str]) -> dict[str, list[str]]:
|
||||
"""提取 PDF 后半段按小节重复出现的填空标准答案,避免把答案行当作新题目。"""
|
||||
"""提取 PDF 后半段按小节重复出现的填空/判断标准答案,避免把答案行当作新题目。"""
|
||||
occurrences: dict[str, int] = {}
|
||||
active_type: str | None = None
|
||||
answers: dict[str, list[str]] = {'fill': []}
|
||||
answers: dict[str, list[str]] = {'fill': [], 'boolean': []}
|
||||
in_answer_sheet = False
|
||||
for line in lines:
|
||||
if _is_answer_section_heading(line):
|
||||
@@ -241,17 +241,34 @@ def _extract_repeated_section_answers(lines: list[str]) -> dict[str, list[str]]:
|
||||
section_type = _section_type_for_line(line)
|
||||
if section_type:
|
||||
occurrences[section_type] = occurrences.get(section_type, 0) + 1
|
||||
if occurrences[section_type] > 1:
|
||||
in_answer_sheet = True
|
||||
active_type = section_type if occurrences[section_type] > 1 or in_answer_sheet else None
|
||||
repeated = occurrences[section_type] > 1
|
||||
in_answer_sheet = in_answer_sheet or repeated
|
||||
active_type = section_type if (repeated or in_answer_sheet) else None
|
||||
# 小节标题行自带答案内容(如「二、判断题:1-2、√ ×」):去掉标题前缀后按判断答案表解析
|
||||
if in_answer_sheet and section_type == 'boolean':
|
||||
remainder = _BOOLEAN_SECTION_PATTERN.sub('', _normalize_spaces(line), count=1)
|
||||
remainder = remainder.lstrip('一二三四五六七八九十、..::\t (()) ')
|
||||
if remainder and not _QUESTION_START_PATTERN.match(remainder):
|
||||
for raw_token in _BOOLEAN_TOKEN_PATTERN.findall(remainder):
|
||||
answer = _normalize_answer_token(raw_token)
|
||||
if answer:
|
||||
answers['boolean'].append(answer)
|
||||
continue
|
||||
if not in_answer_sheet or active_type != 'fill':
|
||||
if not in_answer_sheet or active_type not in {'fill', 'boolean'}:
|
||||
continue
|
||||
match = _QUESTION_START_PATTERN.match(line)
|
||||
if match:
|
||||
value = _normalize_spaces(match.group(2))
|
||||
if value:
|
||||
answers['fill'].append(value)
|
||||
if not match:
|
||||
continue
|
||||
value = _normalize_spaces(match.group(2))
|
||||
if not value:
|
||||
continue
|
||||
if active_type == 'fill':
|
||||
answers['fill'].append(value)
|
||||
elif ' ' not in value:
|
||||
# 判断答案行只接受整行单 token(如「1、√」);带空格的多题答案表交由题号映射解析
|
||||
answer = _normalize_answer_token(value)
|
||||
if answer:
|
||||
answers['boolean'].append(answer)
|
||||
return answers
|
||||
|
||||
|
||||
@@ -320,11 +337,12 @@ def _split_question_blocks(lines: list[str]) -> list[tuple[int, str, str | None]
|
||||
continue
|
||||
if current_section_type == 'answer_sheet' or (current_section_type and current_section_type.startswith('answer_')):
|
||||
continue
|
||||
if _is_answer_sheet_line(line):
|
||||
continue
|
||||
# 题干匹配必须先于答案表过滤:行内答案题干(如「1. 题干… 答案:C 解析:…」)整行含「答案」,
|
||||
# 若先走答案表过滤会被整体丢弃导致整卷解析为空(2026-09-29 修复,原顺序该分支为死代码)。
|
||||
question_match = _QUESTION_START_PATTERN.match(line)
|
||||
if question_match:
|
||||
if _is_answer_sheet_line(line) and '答案' not in line:
|
||||
# 疑似答案表行(如「1.B 2.A 3.正确」)即使形如题干也不生成题目
|
||||
continue
|
||||
if current_no is not None and current_lines:
|
||||
blocks.append((current_no, ' '.join(current_lines).strip(), current_section_type))
|
||||
@@ -480,6 +498,7 @@ def parse_training_question_bank_text(text: str) -> dict[str, Any]:
|
||||
question_bank: list[dict[str, Any]] = []
|
||||
skipped_questions: list[int] = []
|
||||
fill_answer_index = 0
|
||||
boolean_answer_index = 0
|
||||
|
||||
# [STEP 1] 先按题号切块,再对每一块做题型、答案和解析判定,避免跨题串行污染。
|
||||
answer_sequence_index = 0
|
||||
@@ -497,6 +516,17 @@ def parse_training_question_bank_text(text: str) -> dict[str, Any]:
|
||||
mapped_answer=answer_map.get(question_no, ''),
|
||||
ordered_answer=ordered_answer,
|
||||
)
|
||||
if section_type == 'boolean':
|
||||
# 分节重复答案区(如「二、判断题 1、√」「二、判断题:1-2、√ ×」)提取到的判断答案
|
||||
# 作为兜底候选补入;内联/题号映射/整卷顺序命中时仍优先。
|
||||
repeated_answer = (
|
||||
repeated_section_answers['boolean'][boolean_answer_index]
|
||||
if boolean_answer_index < len(repeated_section_answers['boolean'])
|
||||
else ''
|
||||
)
|
||||
boolean_answer_index += 1
|
||||
if repeated_answer and repeated_answer not in answer_candidates:
|
||||
answer_candidates.append(repeated_answer)
|
||||
if section_type == 'boolean':
|
||||
for answer in answer_candidates:
|
||||
question_payload = _build_boolean_question(
|
||||
|
||||
@@ -5,8 +5,10 @@ backend/app/services/lean_training_push_service.py
|
||||
同时承担"每周自动滚动创建当周任务"与"推送成功后立即提醒已延期人员"两项周任务规则。
|
||||
依赖:LeanTrainingWeeklyTask/LeanTrainingVideoPushLog/LeanTrainingReminder/User、lean_training_service(受训对象/当周边界)、lean_training_reminder_service(企微发送模板/延期提醒)、wecom_notify。
|
||||
逻辑:以 task.pushed_video_count 为游标,每次从游标向后取 weekly_count 个"未被任何任务推送过"的视频(跨任务
|
||||
按已推送前缀并集去重,推过的视频绝不重复推);员工端展示已推送前缀;
|
||||
企微 event_key 按"批次区间"幂等防止重复打扰;每轮执行写入 lean_training_video_push_logs 便于管理端查看失败明细;
|
||||
按已推送前缀并集去重,推过的视频绝不重复推);员工端展示与考核口径为本任务首次推送的视频
|
||||
(上一期已推送视频不重复展示、不要求重学,见 lean_training_service._own_pushed_video_ids);
|
||||
企微 event_key 按"批次区间"幂等防止重复打扰(推送后的延期提醒与排程扫描共用"每人每天最多一条"去重,
|
||||
由 lean_training_reminder_service 统一生成事件键);每轮执行写入 lean_training_video_push_logs 便于管理端查看失败明细;
|
||||
排程入口每周一 09:00 先自动滚动创建当周任务(复制最近一期配置并自动追加配置新增视频,无需人工维护;
|
||||
视频库全部推完且无新增视频时暂停滚动、不创建内容重复的新一期),再对各任务推进一批推送。
|
||||
"""
|
||||
@@ -234,10 +236,10 @@ def push_lean_training_videos(
|
||||
)
|
||||
db.session.add(log)
|
||||
db.session.commit()
|
||||
# [STEP 4] 消息推送规则:本批推送成功后立马对任务中"已延期"(过截止未提交)的受训人员发送企微提醒
|
||||
# [STEP 4] 消息推送规则:本批推送成功后立马对任务中"已延期"(过截止未提交)的受训人员发送企微提醒;
|
||||
# 延期提醒与排程扫描共用"每人每天最多一条"判定(event_key 由提醒服务按北京日期统一生成)
|
||||
notify_overdue_users_after_push(
|
||||
task,
|
||||
event_key=f"overdue-after-push-{start_index}-{start_index + len(batch)}",
|
||||
current=current,
|
||||
)
|
||||
return serialize_push_log(log)
|
||||
|
||||
@@ -4,12 +4,15 @@ backend/app/services/lean_training_reminder_service.py
|
||||
用途:执行精益管理周度培训的企微提醒生成与发送。
|
||||
依赖:精益培训任务/完成/提醒模型、User、wecom_notify。
|
||||
逻辑:排程按周日截止、周一/周三/周五催学规则写入幂等提醒,再由统一企微服务发送并落审计。
|
||||
催办文案携带期次标签(第N期+周次区间)供员工区分期次;多期过期任务对同一员工合并为
|
||||
一条汇总提醒,且所有自动催办(排程扫描/推送后延期)共用"每人每天最多一条"判定,
|
||||
历史期任务过截止超过 OVERDUE_REMINDER_STOP_AFTER_DAYS 天后停止催办。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from datetime import date, datetime, time, timedelta, timezone
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
@@ -19,9 +22,75 @@ from app.models import LeanTrainingCompletion, LeanTrainingReminder, LeanTrainin
|
||||
from app.services.lean_training_service import (
|
||||
resolve_lean_training_jump_agent_id,
|
||||
target_user_ids_for_task,
|
||||
week_index_for_task,
|
||||
)
|
||||
from app.services.integrations.wecom.notify import send_wecom_event_message
|
||||
from app.services.schedule.timezone_util import resolve_schedule_tzinfo, utc_now_naive
|
||||
from app.services.schedule.timezone_util import resolve_schedule_tzinfo, to_utc_naive, utc_now_naive
|
||||
|
||||
# 历史期任务停止催办的宽限天数:过截止超过该天数后不再发送任何逾期/延期提醒。
|
||||
# 任务仍保持 published 供管理端查询与统计,仅静默催办(2026-09-30 用户反馈旧期任务永久催办造成重复打扰)。
|
||||
OVERDUE_REMINDER_STOP_AFTER_DAYS = 100
|
||||
# 周中催学发送日(周一/周三/周五,Asia/Shanghai),与排程契约一致。
|
||||
OVERDUE_REMINDER_WEEKDAYS = {0, 2, 4}
|
||||
|
||||
|
||||
def _period_labels(task: LeanTrainingWeeklyTask) -> tuple[str, str]:
|
||||
"""
|
||||
返回周任务的期次标签二元组,供催办文案区分期次。
|
||||
|
||||
用途:多期任务并存扫描时,各期提醒文案完全相同,员工完成当期后仍会收到历史期催办,
|
||||
无法分辨提醒归属哪一期而误以为系统误推(2026-09-30 正式环境用户反馈)。
|
||||
期号与学员端"第N期"口径一致(week_key 全局升序,最早为第 1 期)。
|
||||
Returns:
|
||||
(短标签「第N期」用于标题后缀, 完整标签「第N期(MM-DD至MM-DD)」用于内容前缀);
|
||||
week_key 脏数据解析失败时返回 ("", ""),调用方回退历史文案,提醒不因标签失败而中断。
|
||||
"""
|
||||
try:
|
||||
week_start = date.fromisoformat(task.week_key)
|
||||
except ValueError:
|
||||
return "", ""
|
||||
week_end = week_start + timedelta(days=6)
|
||||
index = week_index_for_task(task)
|
||||
return f"第{index}期", f"第{index}期({week_start.strftime('%m-%d')}至{week_end.strftime('%m-%d')})"
|
||||
|
||||
|
||||
def _overdue_event_key(now: datetime) -> str | None:
|
||||
"""
|
||||
返回催办轮次唯一键(overdue-<北京日期>),仅周一/周三/周五返回键,其余日期返回 None。
|
||||
|
||||
排程扫描与推送后延期提醒共用同一键空间:同一员工同一自然天的全部自动催办只允许一条,
|
||||
LeanTrainingReminder 唯一约束 + 发送前"当天已催办"前置查询双重拦截重复推送
|
||||
(2026-09-30 用户反馈同一员工同一天收到多条相同催办)。
|
||||
"""
|
||||
local_now = now.replace(tzinfo=timezone.utc).astimezone(resolve_schedule_tzinfo("Asia/Shanghai"))
|
||||
if local_now.weekday() not in OVERDUE_REMINDER_WEEKDAYS:
|
||||
return None
|
||||
return f"overdue-{local_now.date().isoformat()}"
|
||||
|
||||
|
||||
def _is_overdue_active(task: LeanTrainingWeeklyTask, now: datetime) -> bool:
|
||||
"""判断任务处于"可催办"窗口:已过截止、且过截止未超过宽限期(超期历史期停止催办)。"""
|
||||
return task.due_at < now <= task.due_at + timedelta(days=OVERDUE_REMINDER_STOP_AFTER_DAYS)
|
||||
|
||||
|
||||
def _has_overdue_reminder_today(user_id: int, now: datetime) -> bool:
|
||||
"""
|
||||
判断员工北京时间当天是否已收到过任意精益自动催办(逾期/延期),实现"每人每天最多一条"。
|
||||
|
||||
用途:多期过期任务并存、排程扫描与批次推送两条催办路径同天先后执行时,
|
||||
后执行的一方据此跳过,避免同一员工同一天收到多条相同催办。
|
||||
"""
|
||||
local_tz = resolve_schedule_tzinfo("Asia/Shanghai")
|
||||
local_now = now.replace(tzinfo=timezone.utc).astimezone(local_tz)
|
||||
day_floor_utc = to_utc_naive(datetime.combine(local_now.date(), time(0, 0, 0), tzinfo=local_tz))
|
||||
existing = db.session.execute(
|
||||
select(LeanTrainingReminder.id).where(
|
||||
LeanTrainingReminder.recipient_user_id == user_id,
|
||||
LeanTrainingReminder.event_key.like("overdue-%"),
|
||||
LeanTrainingReminder.created_at >= day_floor_utc,
|
||||
).limit(1)
|
||||
).scalar_one_or_none()
|
||||
return existing is not None
|
||||
|
||||
|
||||
def _send_reminder(
|
||||
@@ -126,6 +195,9 @@ def send_targeted_reminders(task_id: int, user_ids: list[int], *, now: datetime
|
||||
if forbidden_ids:
|
||||
raise ValueError("Some reminder recipients are outside the task target")
|
||||
totals = {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
|
||||
short_label, full_label = _period_labels(task)
|
||||
title_suffix = f"({short_label})" if short_label else ""
|
||||
content_prefix = full_label if full_label else "本周"
|
||||
for recipient in recipients:
|
||||
if recipient.id in completed_user_ids:
|
||||
totals["skipped"] += 1
|
||||
@@ -135,8 +207,8 @@ def send_targeted_reminders(task_id: int, user_ids: list[int], *, now: datetime
|
||||
recipient=recipient,
|
||||
event_key=f"targeted-{uuid.uuid4().hex}",
|
||||
event_type="training_lean_targeted_reminder",
|
||||
title="精益管理培训定向提醒",
|
||||
content="您尚未完成本周精益管理培训,请观看指定视频并提交不少于50字的学习感悟。",
|
||||
title=f"精益管理培训定向提醒{title_suffix}",
|
||||
content=f"您尚未完成{content_prefix}精益管理培训,请观看指定视频并提交不少于50字的学习感悟。",
|
||||
current=current,
|
||||
)
|
||||
totals["created"] += result != "skipped"
|
||||
@@ -148,25 +220,27 @@ def send_targeted_reminders(task_id: int, user_ids: list[int], *, now: datetime
|
||||
def notify_overdue_users_after_push(
|
||||
task: LeanTrainingWeeklyTask,
|
||||
*,
|
||||
event_key: str,
|
||||
current: datetime | None = None,
|
||||
) -> dict[str, int]:
|
||||
"""
|
||||
视频批次推送成功后,立即对该任务中"已延期"(已过截止时间且未提交感悟)的受训人员发送企微提醒。
|
||||
|
||||
对应周任务消息推送规则:每次推送周任务成功后立马推送延期提醒(与批次 event_key 绑定幂等,同批重推不重复打扰)。
|
||||
对应周任务消息推送规则:每次推送周任务成功后立马推送延期提醒。
|
||||
去重规则(2026-09-30 用户反馈消息太多):与排程扫描共用 overdue-<北京日期> 事件键与
|
||||
"每人每天最多一条自动催办"前置判定——员工当天已收到过任意精益催办(含排程扫描、
|
||||
其它批次延期提醒)时本路径静默跳过,确保同一员工同一自然天只收到一条催办。
|
||||
已过截止超过 OVERDUE_REMINDER_STOP_AFTER_DAYS 天的历史期任务不再发送(历史期补推不再催办旧账)。
|
||||
|
||||
Args:
|
||||
task: 刚完成视频推送的周任务(必须已发布)。
|
||||
event_key: 幂等键,建议携带批次区间(如 overdue-after-push-0-2),与推送批次一一对应。
|
||||
current: 覆盖当前时间(UTC naive,测试用)。
|
||||
Returns:
|
||||
{"created", "sent", "skipped", "failed"} 汇总统计。
|
||||
"""
|
||||
now = current or utc_now_naive()
|
||||
totals = {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
|
||||
# 未过截止时间不存在"已延期"人员,直接返回,避免无意义扫描
|
||||
if now <= task.due_at:
|
||||
# 未过截止时间不存在"已延期"人员;超宽限期的历史期任务同样跳过,避免对旧账无限催办
|
||||
if not _is_overdue_active(task, now):
|
||||
return totals
|
||||
completed_user_ids = set(
|
||||
db.session.execute(
|
||||
@@ -178,14 +252,21 @@ def notify_overdue_users_after_push(
|
||||
)
|
||||
overdue_ids = target_user_ids_for_task(task) - completed_user_ids
|
||||
users = db.session.execute(select(User).where(User.id.in_(overdue_ids), User.status == "active")).scalars().all() if overdue_ids else []
|
||||
event_key = _overdue_event_key(now)
|
||||
short_label, full_label = _period_labels(task)
|
||||
title_suffix = f"({short_label})" if short_label else ""
|
||||
content_prefix = full_label if full_label else "本周"
|
||||
for user in users:
|
||||
if _has_overdue_reminder_today(user.id, now):
|
||||
totals["skipped"] += 1
|
||||
continue
|
||||
result = _send_reminder(
|
||||
task=task,
|
||||
recipient=user,
|
||||
event_key=event_key,
|
||||
event_key=event_key or f"overdue-after-push-{uuid.uuid4().hex}",
|
||||
event_type="training_lean_overdue",
|
||||
title="精益管理培训延期提醒",
|
||||
content="您本周精益管理培训已延期,尚未完成视频观看与学习感悟提交,请尽快完成。",
|
||||
title=f"精益管理培训延期提醒{title_suffix}",
|
||||
content=f"您{content_prefix}精益管理培训已延期,尚未完成视频观看与学习感悟提交,请尽快完成。",
|
||||
current=now,
|
||||
)
|
||||
totals["created"] += result != "skipped"
|
||||
@@ -194,45 +275,65 @@ def notify_overdue_users_after_push(
|
||||
return totals
|
||||
|
||||
|
||||
def _event_key(task: LeanTrainingWeeklyTask, now: datetime) -> str | None:
|
||||
"""按周日截止后的周一、周三、周五计算本轮逾期提醒唯一键。"""
|
||||
if now <= task.due_at:
|
||||
return None
|
||||
local_now = now.replace(tzinfo=timezone.utc).astimezone(resolve_schedule_tzinfo("Asia/Shanghai"))
|
||||
weekday = local_now.weekday()
|
||||
if weekday not in {0, 2, 4}:
|
||||
return None
|
||||
return f"overdue-{local_now.date().isoformat()}"
|
||||
|
||||
|
||||
def run_lean_training_reminders(*, now: datetime | None = None) -> dict[str, int]:
|
||||
"""扫描未完成人员并发送本轮提醒,重复运行由唯一约束确保不重复推送。"""
|
||||
"""扫描全部已发布任务,按"每人每天一条"发送合并逾期提醒,重复运行由当天去重与唯一约束兜底。
|
||||
|
||||
合并规则(2026-09-30 用户反馈多期并存时每人收到多条相同催办):周一/周三/周五扫描时,
|
||||
同一员工名下全部可催办期次(已过截止且未超宽限期、本人未完成)合并为一条提醒——单期文案
|
||||
携带该期次标签,多期汇总各期标签并注明期数;卡片跳转定位到其最近一期未完成任务。
|
||||
提醒文案携带期次标签(第N期+周次区间)供员工区分期次,避免完成当期后仍收到历史期
|
||||
相同提醒而被误认为系统误推。
|
||||
"""
|
||||
current = now or utc_now_naive()
|
||||
event_key = _overdue_event_key(current)
|
||||
if not event_key:
|
||||
return {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
|
||||
tasks = db.session.execute(select(LeanTrainingWeeklyTask).where(LeanTrainingWeeklyTask.status == "published")).scalars().all()
|
||||
created = sent = skipped = failed = 0
|
||||
# [STEP 1] 汇总各员工全部可催办期次:已过截止、未超宽限期、本人属于受训对象且未完成
|
||||
pending: dict[int, list[LeanTrainingWeeklyTask]] = {}
|
||||
for task in tasks:
|
||||
event_key = _event_key(task, current)
|
||||
if not event_key:
|
||||
if not _is_overdue_active(task, current):
|
||||
continue
|
||||
completed_user_ids = set(db.session.execute(select(LeanTrainingCompletion.user_id).where(LeanTrainingCompletion.weekly_task_id == task.id, LeanTrainingCompletion.status == "completed")).scalars())
|
||||
target_user_ids = target_user_ids_for_task(task)
|
||||
users = db.session.execute(select(User).where(User.id.in_(target_user_ids - completed_user_ids))).scalars().all() if target_user_ids else []
|
||||
for user in users:
|
||||
result = _send_reminder(
|
||||
task=task,
|
||||
recipient=user,
|
||||
event_key=event_key,
|
||||
event_type="training_lean_overdue",
|
||||
title="精益管理培训逾期提醒",
|
||||
content="本周精益管理培训尚未完成,请观看指定视频并提交不少于50字的学习感悟。",
|
||||
current=current,
|
||||
)
|
||||
created += result != "skipped"
|
||||
if result == "sent":
|
||||
sent += 1
|
||||
elif result == "failed":
|
||||
failed += 1
|
||||
else:
|
||||
skipped += 1
|
||||
for user_id in sorted(target_user_ids_for_task(task) - completed_user_ids):
|
||||
pending.setdefault(user_id, []).append(task)
|
||||
if not pending:
|
||||
return {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
|
||||
# [STEP 2] 每人仅发一条:按周次倒序取最近一期未完成任务作卡片跳转主任务,多期时汇总各期标签
|
||||
users = db.session.execute(select(User).where(User.id.in_(list(pending)))).scalars().all()
|
||||
created = sent = skipped = failed = 0
|
||||
for user in users:
|
||||
if _has_overdue_reminder_today(user.id, current):
|
||||
skipped += 1
|
||||
continue
|
||||
user_tasks = sorted(pending[user.id], key=lambda item: item.week_key, reverse=True)
|
||||
primary = user_tasks[0]
|
||||
period_labels = [_period_labels(item) for item in reversed(user_tasks)]
|
||||
if len(user_tasks) == 1:
|
||||
short_label, full_label = period_labels[0]
|
||||
title_suffix = f"({short_label})" if short_label else ""
|
||||
content_prefix = full_label if full_label else "本周"
|
||||
title = f"精益管理培训逾期提醒{title_suffix}"
|
||||
content = f"{content_prefix}精益管理培训尚未完成,请观看指定视频并提交不少于50字的学习感悟。"
|
||||
else:
|
||||
joined_labels = "、".join(full for _, full in period_labels if full)
|
||||
title = f"精益管理培训逾期提醒(共{len(user_tasks)}期未完成)"
|
||||
content = f"您共有{len(user_tasks)}期精益管理培训尚未完成:{joined_labels},请观看指定视频并提交不少于50字的学习感悟。"
|
||||
result = _send_reminder(
|
||||
task=primary,
|
||||
recipient=user,
|
||||
event_key=event_key,
|
||||
event_type="training_lean_overdue",
|
||||
title=title,
|
||||
content=content,
|
||||
current=current,
|
||||
)
|
||||
created += result != "skipped"
|
||||
if result == "sent":
|
||||
sent += 1
|
||||
elif result == "failed":
|
||||
failed += 1
|
||||
else:
|
||||
skipped += 1
|
||||
db.session.commit()
|
||||
return {"created": created, "sent": sent, "skipped": skipped, "failed": failed}
|
||||
@@ -3,8 +3,9 @@ backend/app/services/lean_training_service.py
|
||||
|
||||
用途:精益管理培训的周任务、员工提交、看板和提醒规则服务。
|
||||
依赖:TrainingConfig/Resource、精益培训模型、User、统一 ValidationError。
|
||||
逻辑:管理端冻结每周视频列表、每周推送数量与受训对象;员工仅对已推送批次提交观看事实与学习感悟;
|
||||
服务端按 50 字门槛判定完成,管理看板只读取已授权范围。
|
||||
逻辑:管理端冻结每周视频列表、每周推送数量与受训对象;学员端"本期视频"口径为本任务首次推送的
|
||||
视频(已推送前缀扣除其它更早期任务已推送部分,推过的视频不重复展示、不要求重学);
|
||||
员工仅对本期视频提交观看事实与学习感悟,服务端按 50 字门槛判定完成,管理看板只读取已授权范围。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -267,15 +268,21 @@ def is_task_targeted_to_user(task: LeanTrainingWeeklyTask, user: User) -> bool:
|
||||
return user.status == "active" and (user.id in set(task.target_user_ids or []) or user.role in set(task.target_roles or []))
|
||||
|
||||
|
||||
def serialize_weekly_task(task: LeanTrainingWeeklyTask, *, learner_view: bool = False) -> dict[str, Any]:
|
||||
"""序列化精益周任务;员工端视图仅含已推送视频前缀(游标内),管理端返回全量选择列表。
|
||||
def serialize_weekly_task(task: LeanTrainingWeeklyTask, *, learner_view: bool = False, own_pushed_ids: list[int] | None = None) -> dict[str, Any]:
|
||||
"""
|
||||
序列化精益周任务;管理端返回全量选择列表,学员端视图仅含本任务首次推送的视频(本期视频)。
|
||||
|
||||
videos 每项附带 file_url(MinIO 公开地址),供学员端视频缩略图与点击播放使用。
|
||||
附带 week_index(第 N 期)与 week_end(周日),供前后端拼装"第N周 MM-DD至MM-DD"周次标签。
|
||||
Args:
|
||||
own_pushed_ids: 调用方已批量算好的本任务首推视频列表(如列表页一次归一遍历);
|
||||
缺省时内部单任务计算,避免调用方重复查询。
|
||||
"""
|
||||
visible_ids = list(task.video_resource_ids or [])
|
||||
if learner_view:
|
||||
visible_ids = visible_ids[: task.pushed_video_count]
|
||||
# [RULE] 学员端"本期视频"不含其它更早期任务已推送的视频:自动滚动复制上一期冻结列表时,
|
||||
# 上一期已推送视频不再重复展示、也不要求重学(推过的视频不能重复再推)
|
||||
visible_ids = own_pushed_ids if own_pushed_ids is not None else _own_pushed_video_ids(task)
|
||||
resources = db.session.execute(
|
||||
select(TrainingConfigResource).where(TrainingConfigResource.id.in_(visible_ids))
|
||||
).scalars().all()
|
||||
@@ -327,6 +334,46 @@ def _already_pushed_resource_ids(*, exclude_task_id: int | None = None) -> set[i
|
||||
return pushed
|
||||
|
||||
|
||||
def _first_pushed_video_ids_map() -> dict[int, list[int]]:
|
||||
"""
|
||||
一次性计算全部已发布周任务的"本任务首次推送视频"归属映射。
|
||||
|
||||
用途:修复自动滚动把上一期冻结列表原样复制进新一期后,学员端按累积前缀(video_resource_ids[:pushed_video_count])
|
||||
展示与考核,导致上一期已推送视频在第2期重复出现、并要求员工重看重写感悟的问题
|
||||
(对应"前面任务中推送过的视频不能重复再推"规则,2026-09-29 方案 A)。
|
||||
核心逻辑:按周次升序(同期唯一)遍历已发布任务,维护"此前已被推送过"的全局集合;
|
||||
各任务已推送前缀中首次出现的视频归属本任务,与更早期任务重复的视频不属于本任务(本期无需重学)。
|
||||
Returns:
|
||||
{task_id: 本任务首次推送的视频资源 ID 顺序列表(保持冻结列表内的相对顺序)}。
|
||||
"""
|
||||
tasks = db.session.execute(
|
||||
select(LeanTrainingWeeklyTask)
|
||||
.where(LeanTrainingWeeklyTask.status == "published")
|
||||
.order_by(LeanTrainingWeeklyTask.week_key, LeanTrainingWeeklyTask.id)
|
||||
).scalars().all()
|
||||
seen: set[int] = set()
|
||||
ownership: dict[int, list[int]] = {}
|
||||
for task in tasks:
|
||||
prefix_ids = [int(resource_id) for resource_id in list(task.video_resource_ids or [])[: task.pushed_video_count]]
|
||||
ownership[task.id] = [resource_id for resource_id in prefix_ids if resource_id not in seen]
|
||||
seen.update(prefix_ids)
|
||||
return ownership
|
||||
|
||||
|
||||
def _own_pushed_video_ids(task: LeanTrainingWeeklyTask) -> list[int]:
|
||||
"""
|
||||
返回指定任务的"本期视频":已推送前缀中本任务首次推送(此前其它任务未推送过)的部分。
|
||||
|
||||
用途:学员端展示、观看/完成校验、管理看板视频列统一按此口径取"本周期实际布置的视频",
|
||||
保证自动滚动复制上一期列表后,上一期已推送视频不再重复出现在新一期。
|
||||
Args:
|
||||
task: 精益周任务。
|
||||
Returns:
|
||||
本任务首次推送的视频资源 ID 顺序列表。
|
||||
"""
|
||||
return _first_pushed_video_ids_map().get(task.id, [])
|
||||
|
||||
|
||||
def _inherited_pushed_video_count(video_ids: list[int]) -> int:
|
||||
"""
|
||||
计算手动新建周任务应继承的推送游标:新视频列表的"最长已推送前缀"长度。
|
||||
@@ -436,7 +483,7 @@ def list_my_weekly_tasks(user: User) -> list[dict[str, Any]]:
|
||||
"""
|
||||
返回当前员工被指派的全部已发布精益周任务(按周期倒序,最新在最上),供员工端时间树展示。
|
||||
|
||||
每项为学员视角序列化(仅已推送视频前缀),并附加:
|
||||
每项为学员视角序列化(仅本任务首次推送的视频),并附加:
|
||||
- task_status: completed=已完成感悟提交(completed_at 非空);overdue=未完成且已过截止时间;in_progress=未完成且未到截止;
|
||||
- completion: 观看草稿(仅记录了视频观看、感悟未提交)或完成记录的总结/观看时间/完成时间摘要,两者均无时为 None。
|
||||
"""
|
||||
@@ -446,6 +493,8 @@ def list_my_weekly_tasks(user: User) -> list[dict[str, Any]]:
|
||||
targeted = [item for item in tasks if is_task_targeted_to_user(item, user)]
|
||||
if not targeted:
|
||||
return []
|
||||
# [STEP] 一次遍历算出各任务首推视频归属,列表页逐任务序列化复用,避免 N 个任务各查一遍全表
|
||||
own_pushed_map = _first_pushed_video_ids_map()
|
||||
completions = {
|
||||
item.weekly_task_id: item
|
||||
for item in db.session.execute(
|
||||
@@ -459,7 +508,7 @@ def list_my_weekly_tasks(user: User) -> list[dict[str, Any]]:
|
||||
items: list[dict[str, Any]] = []
|
||||
for task in targeted:
|
||||
completion = completions.get(task.id)
|
||||
item = serialize_weekly_task(task, learner_view=True)
|
||||
item = serialize_weekly_task(task, learner_view=True, own_pushed_ids=own_pushed_map.get(task.id, []))
|
||||
# 只有感悟提交完成(completed_at 非空)才算"已完成";仅有观看草稿时仍按截止时间判定进行中/已延期
|
||||
item["task_status"] = "completed" if completion and completion.completed_at else ("overdue" if now > task.due_at else "in_progress")
|
||||
item["completion"] = {
|
||||
@@ -478,19 +527,19 @@ def mark_video_watched(user: User, data: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
Args:
|
||||
user: 当前登录员工。
|
||||
data: 需包含 weekly_task_id 与 resource_id;resource_id 必须属于该任务已推送的前缀视频。
|
||||
data: 需包含 weekly_task_id 与 resource_id;resource_id 必须属于本任务首次推送(本期要求学习)的视频。
|
||||
Returns:
|
||||
{"watched_at": {resource_id: 观看时间iso字符串}},该任务当前的全部观看记录。
|
||||
Raises:
|
||||
NotFoundError: 任务不存在、未发布、未指派给该员工或视频不在已推送范围。
|
||||
NotFoundError: 任务不存在、未发布、未指派给该员工或视频不属于本期学习范围。
|
||||
"""
|
||||
task_id = int(data.get("weekly_task_id") or 0)
|
||||
resource_id = int(data.get("resource_id") or 0)
|
||||
task = db.session.get(LeanTrainingWeeklyTask, task_id)
|
||||
if not task or task.status != "published" or not is_task_targeted_to_user(task, user):
|
||||
raise NotFoundError("Lean training weekly task not found")
|
||||
# 员工只能记录已推送前缀视频的观看,防止越权观看未发布视频
|
||||
if resource_id not in list(task.video_resource_ids or [])[: task.pushed_video_count]:
|
||||
# 员工只能记录本期视频的观看:其它更早期任务已推送的视频不属于本周期学习范围,防止越权观看未布置内容
|
||||
if resource_id not in _own_pushed_video_ids(task):
|
||||
raise NotFoundError("Video resource not in pushed scope")
|
||||
completion = db.session.execute(
|
||||
select(LeanTrainingCompletion).where(LeanTrainingCompletion.weekly_task_id == task.id, LeanTrainingCompletion.user_id == user.id)
|
||||
@@ -514,8 +563,9 @@ def save_completion(user: User, data: dict[str, Any]) -> dict[str, Any]:
|
||||
raise NotFoundError("Lean training weekly task not found")
|
||||
if not is_task_targeted_to_user(task, user):
|
||||
raise NotFoundError("Lean training weekly task not found")
|
||||
# 员工只能观看已推送的前缀视频,完成校验同样基于已推送范围而非全量选择列表
|
||||
required_ids = list(task.video_resource_ids or [])[: task.pushed_video_count]
|
||||
# 员工只能观看本期视频,完成校验同样只考核本任务首次推送的视频:
|
||||
# 自动滚动复制的上一期已推送视频不要求重学,防止重复学习(推过的视频不能重复再推)
|
||||
required_ids = _own_pushed_video_ids(task)
|
||||
# 观看记录以服务端持久化为准(mark_video_watched 已逐个保存),客户端仅作回显兜底,防止伪造观看
|
||||
# 兜底值入库前归一为 UTC:客户端可能提交北京时间(+08:00)或 UTC(Z)格式,存储一律 UTC
|
||||
watched = {str(key): parse_client_iso_to_utc_text(value) for key, value in (data.get("watched_at") or {}).items()}
|
||||
@@ -539,28 +589,29 @@ def save_completion(user: User, data: dict[str, Any]) -> dict[str, Any]:
|
||||
return serialize_completion(completion, task, user)
|
||||
|
||||
|
||||
def _task_video_rows(task: LeanTrainingWeeklyTask, completion: LeanTrainingCompletion | None) -> list[dict[str, Any]]:
|
||||
def _task_video_rows(task: LeanTrainingWeeklyTask, completion: LeanTrainingCompletion | None, own_video_ids: list[int] | None = None) -> list[dict[str, Any]]:
|
||||
"""
|
||||
生成看板行的视频明细:仅展示本周期内已推送、要求员工学习的视频(推送游标前缀),与学员端可见范围一致。
|
||||
生成看板行的视频明细:仅展示本周期内布置、要求员工学习的视频(本任务首次推送部分),与学员端可见范围一致。
|
||||
|
||||
Args:
|
||||
task: 当前周任务,视频顺序按管理端冻结时的选择顺序展示(截断到推送游标)。
|
||||
task: 当前周任务,视频顺序按冻结列表内的相对顺序展示。
|
||||
completion: 该员工的完成记录;从未观看(无完成记录)时传 None,仅返回视频名称清单(观看时间为 None)。
|
||||
own_video_ids: 调用方已批量算好的本任务首推视频列表(看板逐行透传,避免每行重算);缺省时内部单任务计算。
|
||||
Returns:
|
||||
[{"name": 视频名, "watched_at": 观看时间iso或None}];尚未推送任何视频(游标为 0)时返回空列表,前端展示 "--"。
|
||||
[{"name": 视频名, "watched_at": 观看时间iso或None}];本任务无首推视频(游标为 0 或前缀全为历史视频)时返回空列表,前端展示 "--"。
|
||||
"""
|
||||
titles = {resource.id: resource.title or (resource.agent_guide.file_name if resource.agent_guide else "") for resource in task.config.resources}
|
||||
watched = dict(completion.watched_at_json or {}) if completion else {}
|
||||
# [RULE] 看板视频列只展示已推送前缀(video_resource_ids[:pushed_video_count]):未推送视频不属于本周期学习范围,避免名单出现从未布置过的视频
|
||||
visible_ids = task.video_resource_ids[: task.pushed_video_count]
|
||||
# [RULE] 看板视频列只展示本期布置的视频(本任务首推部分):上一期已推送的视频不属于本周期学习范围,避免要求重学
|
||||
visible_ids = own_video_ids if own_video_ids is not None else _own_pushed_video_ids(task)
|
||||
return [
|
||||
{"name": titles.get(resource_id, ""), "watched_at": format_beijing_iso(watched.get(str(resource_id)))}
|
||||
for resource_id in visible_ids
|
||||
]
|
||||
|
||||
|
||||
def serialize_completion(completion: LeanTrainingCompletion, task: LeanTrainingWeeklyTask, user: User) -> dict[str, Any]:
|
||||
"""组合看板所需人员、视频观看、总结和完成状态字段。"""
|
||||
def serialize_completion(completion: LeanTrainingCompletion, task: LeanTrainingWeeklyTask, user: User, own_video_ids: list[int] | None = None) -> dict[str, Any]:
|
||||
"""组合看板所需人员、视频观看、总结和完成状态字段;own_video_ids 供看板批量透传本期视频口径。"""
|
||||
# 状态三态归一:已提交感悟为 completed;未完成时按截止时间区分进行中/已延期,管理端状态列直接展示中文
|
||||
if completion.status == "completed":
|
||||
status = "completed"
|
||||
@@ -572,7 +623,7 @@ def serialize_completion(completion: LeanTrainingCompletion, task: LeanTrainingW
|
||||
"employee_id": user.employee_id,
|
||||
"name": user.real_name or user.username,
|
||||
"department": user.department,
|
||||
"videos": _task_video_rows(task, completion),
|
||||
"videos": _task_video_rows(task, completion, own_video_ids=own_video_ids),
|
||||
"summary_text": completion.summary_text,
|
||||
"status": status,
|
||||
"completed_at": format_beijing_iso(completion.completed_at),
|
||||
@@ -595,12 +646,14 @@ def list_dashboard(task_id: int | None) -> dict[str, Any]:
|
||||
target_user_ids = target_user_ids_for_task(task)
|
||||
users = db.session.execute(select(User).where(User.id.in_(target_user_ids)).order_by(User.department, User.employee_id)).scalars().all() if target_user_ids else []
|
||||
completions = {item.user_id: item for item in db.session.execute(select(LeanTrainingCompletion).where(LeanTrainingCompletion.weekly_task_id == task.id)).scalars().all()}
|
||||
# [STEP] 本期视频口径一次算好逐行透传:看板按人逐行输出,避免每行重算首推归属
|
||||
own_video_ids = _own_pushed_video_ids(task)
|
||||
completed: list[dict[str, Any]] = []
|
||||
incomplete: list[dict[str, Any]] = []
|
||||
for user in users:
|
||||
item = completions.get(user.id)
|
||||
# 无完成记录的指派对象同样三态归一:截止前进行中、截止后已延期;视频列全员一致(仅已推送前缀),仅观看时间为空
|
||||
row = serialize_completion(item, task, user) if item else {"user_id": user.id, "employee_id": user.employee_id, "name": user.real_name or user.username, "department": user.department, "videos": _task_video_rows(task, None), "summary_text": None, "status": "overdue" if utc_now_naive() > task.due_at else "in_progress", "completed_at": None}
|
||||
# 无完成记录的指派对象同样三态归一:截止前进行中、截止后已延期;视频列全员一致(仅本期布置视频),仅观看时间为空
|
||||
row = serialize_completion(item, task, user, own_video_ids=own_video_ids) if item else {"user_id": user.id, "employee_id": user.employee_id, "name": user.real_name or user.username, "department": user.department, "videos": _task_video_rows(task, None, own_video_ids=own_video_ids), "summary_text": None, "status": "overdue" if utc_now_naive() > task.due_at else "in_progress", "completed_at": None}
|
||||
(completed if row["status"] == "completed" else incomplete).append(row)
|
||||
return {"task": serialize_weekly_task(task), "completed": completed, "incomplete": incomplete, "periods": periods}
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
"""
|
||||
backend/app/services/order_delivery_reply/__init__.py
|
||||
|
||||
用途:订单交期回复域服务包入口;聚合导出同步服务与 SQL 常量。
|
||||
依赖:本包 sql / sync_service。
|
||||
逻辑:API 层(app/api/order_delivery_reply.py)与排程种子经此包调用同步;scripts/order_delivery_query.py
|
||||
复用 ORDER_DELIVERY_SQL 保持取数口径一致。
|
||||
"""
|
||||
|
||||
from app.services.order_delivery_reply.sql import ORDER_DELIVERY_SQL
|
||||
from app.services.order_delivery_reply.sync_service import OrderDeliverySyncService
|
||||
|
||||
__all__ = ["ORDER_DELIVERY_SQL", "OrderDeliverySyncService"]
|
||||
@@ -0,0 +1,57 @@
|
||||
"""
|
||||
backend/app/services/order_delivery_reply/app_seed.py
|
||||
|
||||
用途:把「订单交期回复」注册为应用管理中的内置 iframe 应用(不接 Dify)。
|
||||
依赖:models.Agent;启动时由 app/__init__.py 幂等调用。
|
||||
逻辑:按 agent_code 幂等创建一条 runtime_provider='iframe' 的 Agent 记录,
|
||||
iframe_url 指向前端免布局嵌入路由 /apps/order-delivery-reply;
|
||||
在聊天壳内整页渲染工作台操作页。应用的可见性走 Agent 权限
|
||||
(admin 自动可见,普通用户在用户管理授权);页面与 API 仍由
|
||||
order_delivery_reply.access/manage 功能权限守卫,两层各司其职。
|
||||
管理员可在应用管理中修改名称/描述/图标/排序,但不应把
|
||||
runtime_provider 改回 dify(本应用没有 Dify 绑定)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import Agent
|
||||
|
||||
ORDER_DELIVERY_AGENT_CODE = 'order_delivery_reply'
|
||||
ORDER_DELIVERY_IFRAME_URL = '/apps/order-delivery-reply'
|
||||
|
||||
|
||||
def ensure_builtin_order_delivery_agent(*, commit: bool = True):
|
||||
"""
|
||||
幂等创建订单交期回复内置应用(iframe 型,非 Dify)。
|
||||
|
||||
Args:
|
||||
commit: 是否提交;测试或外层事务可传 False。
|
||||
Returns:
|
||||
新建的 Agent;已存在时返回 None。
|
||||
"""
|
||||
existing = Agent.query.filter_by(agent_code=ORDER_DELIVERY_AGENT_CODE).first()
|
||||
if existing:
|
||||
return None
|
||||
agent = Agent(
|
||||
name='订单交期回复',
|
||||
description='查单 → 填交期 → 通知业务员;ERP 订单交期回复工作台',
|
||||
agent_code=ORDER_DELIVERY_AGENT_CODE,
|
||||
runtime_provider='iframe',
|
||||
conversation_mode='embedded',
|
||||
iframe_url=ORDER_DELIVERY_IFRAME_URL,
|
||||
dify_app_id=None,
|
||||
dify_api_key=None,
|
||||
is_active=True,
|
||||
category='业务应用',
|
||||
sort_order=0,
|
||||
created_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(agent)
|
||||
if commit:
|
||||
db.session.commit()
|
||||
else:
|
||||
db.session.flush()
|
||||
return agent
|
||||
@@ -0,0 +1,281 @@
|
||||
"""
|
||||
backend/app/services/order_delivery_reply/notify_service.py
|
||||
|
||||
用途:订单交期回复的通知与锁定——按行通知订单业务员(企微)、成功后行级锁定并留痕。
|
||||
依赖:wecom_notify.send_wecom_event_message(平台统一 textcard,本域只传业务参数)、
|
||||
models/order_delivery_reply、models.User(employee_id → wecom_userid 映射)、extensions.db。
|
||||
逻辑:发送成功与 locked=true 在同一事务提交(禁止「已通知未锁定」);失败不锁定;
|
||||
收件人是订单业务员(oea14 → User.employee_id),与操作人(生管)无关;
|
||||
交期回复人员 = 最近一次发送成功的生管工号+姓名(R-NOTIFY-03)。
|
||||
批量通知(第 5 步)逐行复用本模块,单行失败不回滚其它行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.core.errors import (
|
||||
ConflictError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
ValidationError,
|
||||
)
|
||||
from app.extensions import db
|
||||
from app.models import User
|
||||
from app.models.order_delivery_reply import (
|
||||
OrderDeliveryAuditEvent,
|
||||
OrderDeliveryBatch,
|
||||
OrderDeliveryErpLine,
|
||||
OrderDeliveryLineState,
|
||||
)
|
||||
from app.services.integrations.wecom.notify import send_wecom_event_message
|
||||
|
||||
# 企微事件开关名;与 settings.WECOM_NOTIFY_EVENTS 默认值条目一致(同 contract_payment_warning 命名风格)。
|
||||
WECOM_EVENT_TYPE = "order_delivery_reply_notify"
|
||||
# 工作台跳转路由(前端第 8 步落地,带上该行查询参数直开行)。
|
||||
JUMP_PATH = "/apps/order-delivery-reply" # 免布局嵌入路由:企微内打开不带工作台侧栏
|
||||
|
||||
|
||||
def _load_line(order_no: str, line_no: int) -> OrderDeliveryErpLine:
|
||||
"""按行唯一键取未 erp_missing 的快照行;不存在/不在同步范围抛 404。"""
|
||||
line = db.session.scalar(
|
||||
select(OrderDeliveryErpLine).where(
|
||||
OrderDeliveryErpLine.order_no == order_no,
|
||||
OrderDeliveryErpLine.line_no == line_no,
|
||||
OrderDeliveryErpLine.erp_missing.is_(False),
|
||||
)
|
||||
)
|
||||
if not line:
|
||||
raise NotFoundError(
|
||||
"Order delivery line not found",
|
||||
code="ORDER_DELIVERY_REPLY.LINE_NOT_FOUND",
|
||||
)
|
||||
return line
|
||||
|
||||
|
||||
def _load_state(line_id: int) -> OrderDeliveryLineState | None:
|
||||
return db.session.scalar(
|
||||
select(OrderDeliveryLineState).where(OrderDeliveryLineState.line_id == line_id)
|
||||
)
|
||||
|
||||
|
||||
def _resolve_recipient(line: OrderDeliveryErpLine) -> User:
|
||||
"""
|
||||
订单业务员 → HXOPS 用户:salesperson_code(oea14) 对 User.employee_id。
|
||||
|
||||
Returns:
|
||||
对应 User。
|
||||
Raises:
|
||||
ServiceUnavailableError: 对不上或账号未绑企微——该行通知失败、不锁定(需求 §13)。
|
||||
"""
|
||||
recipient = db.session.scalar(
|
||||
select(User).where(User.employee_id == (line.salesperson_code or "").strip())
|
||||
)
|
||||
if recipient is None or not (recipient.wecom_userid or "").strip():
|
||||
raise ServiceUnavailableError(
|
||||
f"业务员工号 {line.salesperson_code} 未关联 HXOPS 用户或未绑定企微,无法通知",
|
||||
code="ORDER_DELIVERY_REPLY.SALESPERSON_UNMAPPED",
|
||||
)
|
||||
return recipient
|
||||
|
||||
|
||||
def _send_line_notification(line: OrderDeliveryErpLine, recipient: User) -> dict[str, Any]:
|
||||
"""
|
||||
调平台既有 send_wecom_event_message 发送单行通知(textcard 壳、按钮、回执全用现成实现)。
|
||||
|
||||
参数与输出约束:content 按需求 §13 固定文案;jump_params 带该行唯一键供企微直达;
|
||||
返回 {ok, trace_id, ...},成败以函数返回为准(回执只留痕不改状态)。
|
||||
"""
|
||||
return send_wecom_event_message(
|
||||
event_type=WECOM_EVENT_TYPE,
|
||||
user=recipient,
|
||||
title="订单交期回复",
|
||||
content=f"您有订单号:项次{line.order_no}:{line.line_no}的订单需要填写/确认/查看交期。",
|
||||
jump_path=JUMP_PATH,
|
||||
jump_params={"order_no": line.order_no, "line_no": line.line_no},
|
||||
)
|
||||
|
||||
|
||||
def notify_line(order_no: str, line_no: int, operator: User) -> dict[str, Any]:
|
||||
"""
|
||||
单行通知 + 锁定 + 审计(行内「发送通知业务部门」入口)。
|
||||
|
||||
用途与触发时机:生管在行内点「发送通知业务部门」;AI/排程不触发。
|
||||
批量通知逐行复用本函数,外层保证单行失败不影响其它行。
|
||||
|
||||
核心逻辑:[STEP 1] 行存在校验;无批次 → 422(请先回复交期);已锁定 → 409;
|
||||
[STEP 2] 解析收件人(订单业务员),对不上 → 该行失败不锁定;
|
||||
[STEP 3] 发企微;发送失败 → 该行失败不锁定(503 NOTIFY_FAILED);
|
||||
[STEP 4] 发送成功后同一事务写 locked + 交期回复人员快照 + notify/lock 审计并提交。
|
||||
|
||||
Args:
|
||||
order_no / line_no: 行唯一键。
|
||||
operator: 操作的生管(HXOPS 用户);交期回复人员取其工号+姓名。
|
||||
Returns:
|
||||
{"order_no", "line_no", "locked": true, "notified_user_name", "notified_at"}。
|
||||
"""
|
||||
# [STEP 1] 前置校验:无批次不能通知;已锁定不能重复通知。
|
||||
line = _load_line(order_no, line_no)
|
||||
state = _load_state(line.id)
|
||||
if state and state.locked:
|
||||
raise ConflictError(
|
||||
"该订单行已通知锁定,无需重复通知",
|
||||
code="ORDER_DELIVERY_REPLY.LINE_LOCKED",
|
||||
)
|
||||
batch_count = len(
|
||||
db.session.scalars(
|
||||
select(OrderDeliveryBatch.id).where(OrderDeliveryBatch.line_id == line.id)
|
||||
).all()
|
||||
)
|
||||
if batch_count == 0:
|
||||
raise ValidationError("请先回复交期再发送通知", code="ORDER_DELIVERY_REPLY.BATCHES_REQUIRED")
|
||||
|
||||
# [STEP 2] 收件人 = 订单业务员,与操作权限无关。
|
||||
recipient = _resolve_recipient(line)
|
||||
|
||||
# [STEP 3] 先发送:成败以 send_wecom_event_message 返回为准;失败不写任何锁定状态。
|
||||
result = _send_line_notification(line, recipient)
|
||||
if not result.get("ok"):
|
||||
raise ServiceUnavailableError(
|
||||
"企微通知发送失败,该行未锁定",
|
||||
code="ORDER_DELIVERY_REPLY.NOTIFY_FAILED",
|
||||
details={"trace_id": result.get("trace_id"), "reason": result.get("reason")},
|
||||
)
|
||||
|
||||
# [STEP 4] 发送成功 → 同一事务锁定 + 快照 + 审计;提交失败会整体回滚(宁可不锁定,禁止已通知未锁定)。
|
||||
notified_at = datetime.utcnow()
|
||||
if state is None:
|
||||
state = OrderDeliveryLineState(line_id=line.id)
|
||||
db.session.add(state)
|
||||
state.locked = True
|
||||
state.notified_user_id = operator.id
|
||||
state.notified_employee_id = (operator.employee_id or "").strip() or None
|
||||
state.notified_user_name = operator.real_name
|
||||
state.notified_at = notified_at
|
||||
|
||||
db.session.add_all(
|
||||
[
|
||||
OrderDeliveryAuditEvent(
|
||||
line_id=line.id,
|
||||
order_no=line.order_no,
|
||||
line_no=line.line_no,
|
||||
action="notify",
|
||||
operator_user_id=operator.id,
|
||||
payload_json={
|
||||
"recipient_employee_id": line.salesperson_code,
|
||||
"recipient_wecom_userid": recipient.wecom_userid,
|
||||
"trace_id": result.get("trace_id"),
|
||||
"notified_at": notified_at.isoformat(),
|
||||
},
|
||||
),
|
||||
OrderDeliveryAuditEvent(
|
||||
line_id=line.id,
|
||||
order_no=line.order_no,
|
||||
line_no=line.line_no,
|
||||
action="lock",
|
||||
operator_user_id=operator.id,
|
||||
payload_json={
|
||||
"notified_employee_id": state.notified_employee_id,
|
||||
"notified_user_name": state.notified_user_name,
|
||||
"notified_at": notified_at.isoformat(),
|
||||
},
|
||||
),
|
||||
]
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
return {
|
||||
"order_no": line.order_no,
|
||||
"line_no": line.line_no,
|
||||
"locked": True,
|
||||
"notified_employee_id": state.notified_employee_id,
|
||||
"notified_user_name": state.notified_user_name,
|
||||
"notified_at": notified_at.isoformat(),
|
||||
"wecom_trace_id": result.get("trace_id"),
|
||||
}
|
||||
|
||||
|
||||
def notify_batch(raw_lines: list, operator: User) -> dict[str, Any]:
|
||||
"""
|
||||
批量通知:对勾选行逐行发送通知并锁定(无批次或已锁定的行跳过)。
|
||||
|
||||
用途与触发时机:工作台勾选多行后点工具栏「批量通知」(R-NOTIFY-02);
|
||||
与「联合回复交期」是两个独立操作,本函数不做任何批次保存。
|
||||
|
||||
核心逻辑:[STEP 1] 校验请求结构(非空数组、每项含 order_no/line_no,上限 200);
|
||||
[STEP 2] 逐行:无批次 → skipped;已锁定 → skipped;其余调 notify_line;
|
||||
单行失败不回滚其它行(notify_line 每行独立事务),失败行带原因返回;
|
||||
[STEP 3] 汇总 succeeded / failed / skipped 与各行结果。
|
||||
|
||||
Args:
|
||||
raw_lines: [{"order_no", "line_no"}]。
|
||||
operator: 操作的生管(HXOPS 用户)。
|
||||
Returns:
|
||||
{"succeeded": N, "failed": N, "skipped": N,
|
||||
"items": [{order_no, line_no, ok, skipped?, reason?, data?}]}。
|
||||
"""
|
||||
from app.core.errors import AppError
|
||||
|
||||
if not isinstance(raw_lines, list) or not raw_lines:
|
||||
raise ValidationError("lines 必须为非空数组", code="ORDER_DELIVERY_REPLY.NOTIFY_BATCH_EMPTY")
|
||||
if len(raw_lines) > 200:
|
||||
raise ValidationError("单次批量通知行数超过上限 200", code="ORDER_DELIVERY_REPLY.NOTIFY_BATCH_EMPTY")
|
||||
|
||||
def _key(item: dict) -> tuple[str, int] | None:
|
||||
try:
|
||||
order_no = str(item.get("order_no") or "").strip()
|
||||
line_no = int(item.get("line_no"))
|
||||
return (order_no, line_no) if order_no else None
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
results: list[dict[str, Any]] = []
|
||||
for item in raw_lines:
|
||||
if not isinstance(item, dict):
|
||||
results.append({"ok": False, "error": "行格式不合法"})
|
||||
continue
|
||||
key = _key(item)
|
||||
if key is None:
|
||||
results.append({"ok": False, "error": "行唯一键缺失或格式不合法"})
|
||||
continue
|
||||
order_no, line_no = key
|
||||
|
||||
# [STEP 2] 跳过语义:无批次(不能通知)/ 已锁定(无需重复通知)不计入成败。
|
||||
line = db.session.scalar(
|
||||
select(OrderDeliveryErpLine).where(
|
||||
OrderDeliveryErpLine.order_no == order_no,
|
||||
OrderDeliveryErpLine.line_no == line_no,
|
||||
OrderDeliveryErpLine.erp_missing.is_(False),
|
||||
)
|
||||
)
|
||||
if line is None:
|
||||
results.append({"order_no": order_no, "line_no": line_no, "ok": False, "error": "订单行不存在"})
|
||||
continue
|
||||
state = _load_state(line.id)
|
||||
if state and state.locked:
|
||||
results.append({"order_no": order_no, "line_no": line_no, "ok": True, "skipped": True, "reason": "already_locked"})
|
||||
continue
|
||||
has_batch = db.session.scalar(
|
||||
select(OrderDeliveryBatch.id).where(OrderDeliveryBatch.line_id == line.id).limit(1)
|
||||
)
|
||||
if has_batch is None:
|
||||
results.append({"order_no": order_no, "line_no": line_no, "ok": True, "skipped": True, "reason": "no_batches"})
|
||||
continue
|
||||
|
||||
try:
|
||||
data = notify_line(order_no, line_no, operator)
|
||||
results.append({"order_no": order_no, "line_no": line_no, "ok": True, "data": data})
|
||||
except AppError as exc:
|
||||
# 单行失败不回滚其它行:notify_line 内部已按行提交或未写入。
|
||||
db.session.rollback()
|
||||
results.append({"order_no": order_no, "line_no": line_no, "ok": False, "error": exc.message})
|
||||
|
||||
return {
|
||||
"succeeded": sum(1 for r in results if r.get("ok") and not r.get("skipped")),
|
||||
"failed": sum(1 for r in results if not r.get("ok")),
|
||||
"skipped": sum(1 for r in results if r.get("skipped")),
|
||||
"items": results,
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
"""
|
||||
backend/app/services/order_delivery_reply/query_service.py
|
||||
|
||||
用途:订单交期回复工作台只读查询——列表筛选分页、单行详情、状态推导与序列化。
|
||||
依赖:models/order_delivery_reply(快照/批次/状态)、extensions.db。
|
||||
逻辑:所有读取只打本地快照;行状态为读时推导(无批次=未回复,有批次未锁定=部分回复,
|
||||
已锁定=已回复),筛选「已回复/未完全回复」据此下推到 SQL;erp_missing 行一律不返回。
|
||||
本服务不做任何写操作,也不访问 ERP。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import Select, func, or_, select
|
||||
|
||||
from app.extensions import db
|
||||
from app.models.order_delivery_reply import (
|
||||
OrderDeliveryAuditEvent,
|
||||
OrderDeliveryBatch,
|
||||
OrderDeliveryErpLine,
|
||||
OrderDeliveryLineState,
|
||||
)
|
||||
|
||||
# 状态筛选合法值:空/None = 全部。
|
||||
STATUS_FILTER_VALUES = {"replied", "not_fully_replied"}
|
||||
|
||||
DEFAULT_PAGE_SIZE = 50
|
||||
MAX_PAGE_SIZE = 200
|
||||
|
||||
|
||||
def _utc_to_shanghai(value) -> str | None:
|
||||
"""naive-UTC 时间转北京时间展示串;仅用于序列化,详情见 api 层同名 helper 注释。"""
|
||||
from datetime import timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
return value.replace(tzinfo=timezone.utc).astimezone(ZoneInfo("Asia/Shanghai")).strftime("%Y-%m-%d %H:%M:%S")
|
||||
except (AttributeError, ValueError):
|
||||
return value.isoformat() if hasattr(value, "isoformat") else str(value)
|
||||
|
||||
|
||||
def _dec_str(value: Decimal | None) -> str | None:
|
||||
"""
|
||||
Numeric 序列化为去尾零的十进制字符串(80.0000 → "80",7.5000 → "7.5")。
|
||||
|
||||
用途:数量/未交数量展示;Postgres Numeric 保留列 scale,直接 str() 会带多余尾零。
|
||||
约束:仅用于展示序列化,不改变库内精度。
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
text = format(value, "f")
|
||||
if "." in text:
|
||||
text = text.rstrip("0").rstrip(".")
|
||||
return text or "0"
|
||||
|
||||
|
||||
def _has_batch_subquery():
|
||||
"""该订单行是否已存在交期批次的 EXISTS 子查询(状态推导用)。"""
|
||||
return select(OrderDeliveryBatch.line_id).where(OrderDeliveryBatch.line_id == OrderDeliveryErpLine.id).exists()
|
||||
|
||||
|
||||
def _locked_subquery():
|
||||
"""该订单行是否已通知锁定的 EXISTS 子查询(状态推导用)。"""
|
||||
return (
|
||||
select(OrderDeliveryLineState.line_id)
|
||||
.where(
|
||||
OrderDeliveryLineState.line_id == OrderDeliveryErpLine.id,
|
||||
OrderDeliveryLineState.locked.is_(True),
|
||||
)
|
||||
.exists()
|
||||
)
|
||||
|
||||
|
||||
def _reply_person_subquery(like: str):
|
||||
"""该订单行的交期回复人员(姓名/工号,存于行状态快照)命中关键词的 EXISTS 子查询。"""
|
||||
return (
|
||||
select(OrderDeliveryLineState.line_id)
|
||||
.where(
|
||||
OrderDeliveryLineState.line_id == OrderDeliveryErpLine.id,
|
||||
or_(
|
||||
OrderDeliveryLineState.notified_user_name.ilike(like),
|
||||
OrderDeliveryLineState.notified_employee_id.ilike(like),
|
||||
),
|
||||
)
|
||||
.exists()
|
||||
)
|
||||
|
||||
|
||||
def _base_query() -> Select:
|
||||
"""列表基础查询:只取未标 erp_missing 的已同步行(默认列表不展示已不在同步范围的行)。"""
|
||||
return select(OrderDeliveryErpLine).where(OrderDeliveryErpLine.erp_missing.is_(False))
|
||||
|
||||
|
||||
def _apply_filters(stmt: Select, params: dict[str, Any]) -> Select:
|
||||
"""
|
||||
应用列表筛选(AND 语义)与状态筛选下推。
|
||||
|
||||
核心逻辑:keyword 关键词合并搜索——订单单号/客户订单/客户编号/客户简称/公司全名/
|
||||
产品编号/品名/客户产品编号/业务员(姓名、工号)/交期回复人员(姓名、工号,
|
||||
2026-09-23 增补,按行状态快照 EXISTS)命中任一字段即返回(OR,工作台单搜索框口径);
|
||||
order_date 精确单日;status=replied → 已锁定,
|
||||
status=not_fully_replied → 未锁定(未回复∪部分回复)。
|
||||
"""
|
||||
keyword = str(params.get("keyword") or "").strip()
|
||||
if keyword:
|
||||
like = f"%{keyword}%"
|
||||
stmt = stmt.where(
|
||||
or_(
|
||||
OrderDeliveryErpLine.order_no.ilike(like),
|
||||
OrderDeliveryErpLine.customer_po.ilike(like),
|
||||
OrderDeliveryErpLine.customer_no.ilike(like),
|
||||
OrderDeliveryErpLine.customer_short_name.ilike(like),
|
||||
OrderDeliveryErpLine.customer_full_name.ilike(like),
|
||||
OrderDeliveryErpLine.part_no.ilike(like),
|
||||
OrderDeliveryErpLine.part_name.ilike(like),
|
||||
OrderDeliveryErpLine.customer_part_no.ilike(like),
|
||||
OrderDeliveryErpLine.salesperson_name.ilike(like),
|
||||
OrderDeliveryErpLine.salesperson_code.ilike(like),
|
||||
_reply_person_subquery(like),
|
||||
)
|
||||
)
|
||||
|
||||
order_date_raw = params.get("order_date")
|
||||
if order_date_raw:
|
||||
parsed = _parse_date(order_date_raw)
|
||||
if parsed is None:
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
raise ValidationError("订单日期格式须为 YYYY-MM-DD")
|
||||
stmt = stmt.where(OrderDeliveryErpLine.order_date == parsed)
|
||||
|
||||
status = (params.get("status") or "").strip()
|
||||
if status and status not in STATUS_FILTER_VALUES:
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
raise ValidationError(f"不支持的状态筛选:{status}")
|
||||
if status == "replied":
|
||||
stmt = stmt.where(_locked_subquery())
|
||||
elif status == "not_fully_replied":
|
||||
# 未完全回复 = 未回复 ∪ 部分回复,统一口径为「尚未通知锁定」。
|
||||
stmt = stmt.where(~_locked_subquery())
|
||||
|
||||
return stmt
|
||||
|
||||
|
||||
def _parse_date(raw: Any) -> date | None:
|
||||
"""解析 YYYY-MM-DD 单日;非法返回 None(由调用方决定是否报错)。"""
|
||||
if isinstance(raw, date) and not isinstance(raw, datetime):
|
||||
return raw
|
||||
try:
|
||||
return date.fromisoformat(str(raw))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _serialize_line(
|
||||
line: OrderDeliveryErpLine,
|
||||
batches: list[OrderDeliveryBatch],
|
||||
state: OrderDeliveryLineState | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
序列化一行工作台列表/详情数据。
|
||||
|
||||
核心逻辑:行状态读时推导(见模块 docstring);未交数量 = 数量 − 已交数量(None 当 0),
|
||||
只做展示派生,不落库;不输出 slip_code(一期列表不出单别列)。
|
||||
"""
|
||||
locked = bool(state and state.locked)
|
||||
if locked:
|
||||
status = "replied"
|
||||
elif batches:
|
||||
status = "partial_replied"
|
||||
else:
|
||||
status = "not_replied"
|
||||
|
||||
qty = line.qty or Decimal(0)
|
||||
delivered = line.delivered_qty or Decimal(0)
|
||||
|
||||
return {
|
||||
"id": line.id,
|
||||
"order_no": line.order_no,
|
||||
"line_no": line.line_no,
|
||||
"order_date": line.order_date.isoformat() if line.order_date else None,
|
||||
"customer_no": line.customer_no,
|
||||
"customer_short_name": line.customer_short_name,
|
||||
"customer_full_name": line.customer_full_name,
|
||||
"salesperson_code": line.salesperson_code,
|
||||
"salesperson_name": line.salesperson_name,
|
||||
"dept_code": line.dept_code,
|
||||
"dept_name": line.dept_name,
|
||||
"customer_po": line.customer_po,
|
||||
"part_no": line.part_no,
|
||||
"part_name": line.part_name,
|
||||
"spec": line.spec,
|
||||
"customer_part_no": line.customer_part_no,
|
||||
"agreed_date": line.agreed_date.isoformat() if line.agreed_date else None,
|
||||
"unit": line.unit,
|
||||
"qty": _dec_str(line.qty),
|
||||
"delivered_qty": _dec_str(line.delivered_qty),
|
||||
"undelivered_qty": _dec_str(qty - delivered),
|
||||
"status": status,
|
||||
"locked": locked,
|
||||
"batches": [
|
||||
{
|
||||
"seq": batch.seq,
|
||||
"planned_date": batch.planned_date.isoformat() if batch.planned_date else None,
|
||||
"qty": _dec_str(batch.qty),
|
||||
"remark": batch.remark,
|
||||
}
|
||||
for batch in batches
|
||||
],
|
||||
"notified_employee_id": state.notified_employee_id if state else None,
|
||||
"notified_user_name": state.notified_user_name if state else None,
|
||||
"notified_at": _utc_to_shanghai(state.notified_at if state else None),
|
||||
}
|
||||
|
||||
|
||||
def list_lines(params: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
订单行列表查询(筛选 + 分页 + 默认排序)。
|
||||
|
||||
用途与触发时机:GET /api/order-delivery-reply/lines 的服务层实现;工作台首屏与筛选刷新。
|
||||
|
||||
核心逻辑:[STEP 1] 组装基础查询(排除 erp_missing)并应用筛选;
|
||||
[STEP 2] count 总数后按默认排序分页取本页行;
|
||||
[STEP 3] 批量预取本页行的批次与锁定状态,避免 N+1,再逐行序列化。
|
||||
|
||||
Args:
|
||||
params: keyword / order_date / status / page / page_size。
|
||||
Returns:
|
||||
{"items": [...], "page", "page_size", "total"};items 含批次与状态(见 _serialize_line)。
|
||||
"""
|
||||
stmt = _apply_filters(_base_query(), params)
|
||||
|
||||
total = db.session.scalar(select(func.count()).select_from(stmt.subquery()))
|
||||
|
||||
try:
|
||||
page = max(int(params.get("page") or 1), 1)
|
||||
page_size = min(max(int(params.get("page_size") or DEFAULT_PAGE_SIZE), 1), MAX_PAGE_SIZE)
|
||||
except (TypeError, ValueError):
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
raise ValidationError("分页参数须为整数")
|
||||
|
||||
stmt = stmt.order_by(
|
||||
OrderDeliveryErpLine.order_date.asc(),
|
||||
OrderDeliveryErpLine.customer_no.asc(),
|
||||
OrderDeliveryErpLine.order_no.asc(),
|
||||
OrderDeliveryErpLine.line_no.asc(),
|
||||
OrderDeliveryErpLine.part_no.asc(),
|
||||
).limit(page_size).offset((page - 1) * page_size)
|
||||
|
||||
lines = list(db.session.scalars(stmt).all())
|
||||
line_ids = [line.id for line in lines]
|
||||
|
||||
batches_by_line: dict[int, list[OrderDeliveryBatch]] = {}
|
||||
states_by_line: dict[int, OrderDeliveryLineState] = {}
|
||||
if line_ids:
|
||||
for batch in db.session.scalars(
|
||||
select(OrderDeliveryBatch)
|
||||
.where(OrderDeliveryBatch.line_id.in_(line_ids))
|
||||
.order_by(OrderDeliveryBatch.line_id, OrderDeliveryBatch.seq)
|
||||
).all():
|
||||
batches_by_line.setdefault(batch.line_id, []).append(batch)
|
||||
for state in db.session.scalars(
|
||||
select(OrderDeliveryLineState).where(OrderDeliveryLineState.line_id.in_(line_ids))
|
||||
).all():
|
||||
states_by_line[state.line_id] = state
|
||||
|
||||
items = [
|
||||
_serialize_line(line, batches_by_line.get(line.id, []), states_by_line.get(line.id))
|
||||
for line in lines
|
||||
]
|
||||
return {"items": items, "page": page, "page_size": page_size, "total": total or 0}
|
||||
|
||||
|
||||
def get_line(order_no: str, line_no: int) -> dict[str, Any] | None:
|
||||
"""
|
||||
单行详情:快照 + 批次 + 锁定状态 + 该行审计事件。
|
||||
|
||||
Args:
|
||||
order_no / line_no: 行唯一键;erp_missing 行按不存在处理(返回 None → API 404)。
|
||||
Returns:
|
||||
序列化 dict;不存在或已不在同步范围返回 None。
|
||||
"""
|
||||
line = db.session.scalar(
|
||||
_base_query().where(
|
||||
OrderDeliveryErpLine.order_no == order_no,
|
||||
OrderDeliveryErpLine.line_no == line_no,
|
||||
)
|
||||
)
|
||||
if not line:
|
||||
return None
|
||||
|
||||
batches = list(
|
||||
db.session.scalars(
|
||||
select(OrderDeliveryBatch).where(OrderDeliveryBatch.line_id == line.id).order_by(OrderDeliveryBatch.seq)
|
||||
).all()
|
||||
)
|
||||
state = db.session.scalar(select(OrderDeliveryLineState).where(OrderDeliveryLineState.line_id == line.id))
|
||||
|
||||
payload = _serialize_line(line, batches, state)
|
||||
payload["audit_events"] = [
|
||||
{
|
||||
"action": event.action,
|
||||
"operator_user_id": event.operator_user_id,
|
||||
"payload_json": event.payload_json,
|
||||
"created_at": _utc_to_shanghai(event.created_at),
|
||||
}
|
||||
for event in db.session.scalars(
|
||||
select(OrderDeliveryAuditEvent)
|
||||
.where(OrderDeliveryAuditEvent.line_id == line.id)
|
||||
.order_by(OrderDeliveryAuditEvent.created_at.desc())
|
||||
).all()
|
||||
]
|
||||
return payload
|
||||
@@ -0,0 +1,362 @@
|
||||
"""
|
||||
backend/app/services/order_delivery_reply/reminder_service.py
|
||||
|
||||
用途:订单交期回复的定时提醒扫描——已回复行按回复交期提前 N 天提醒业务员出货;
|
||||
未回复行超过 N 天再次提醒生管。由排程 order-delivery-remind(日批)调用。
|
||||
依赖:models/order_delivery_reply(快照/批次/锁定/审计)、models.User(工号 → 企微映射)、
|
||||
wecom_notify.send_wecom_event_message、services/schedule/timezone_util(北京时区业务日)。
|
||||
逻辑:[出货提醒] 已锁定(已回复)行的批次 planned_date 落在 [今天, 今天+N] 时,按业务员聚合
|
||||
发一条企微;同一 (行, 交期) 只提醒一次(audit_events action=ship_remind 去重),发送失败
|
||||
不落成功记录,次日扫描自动补发。
|
||||
[未回复提醒] 未锁定行的订单日期(order_date,取 ERP oea02)距今 ≥ N 天时再次提醒生管
|
||||
(收件人 = 任务参数 unreplied_remind_user_ids,留空回退任务通知人),同一行每 N 天最多
|
||||
提醒一次(action=unreplied_remind 去重),多行聚合成一条通知避免刷屏。
|
||||
提醒只读业务数据 + 写审计,绝不改动批次/锁定状态。
|
||||
(2026-09-23 修订:超期锚点由快照首次入库 created_at 改为订单日期,按业务确认以订单日期计超期。)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import User
|
||||
from app.models.order_delivery_reply import (
|
||||
OrderDeliveryAuditEvent,
|
||||
OrderDeliveryBatch,
|
||||
OrderDeliveryErpLine,
|
||||
OrderDeliveryLineState,
|
||||
)
|
||||
from app.services.integrations.wecom.notify import send_wecom_event_message
|
||||
|
||||
# 企微事件开关名:与行级通知共用同一事件(WECOM_NOTIFY_EVENTS 已包含,无需新增配置)。
|
||||
WECOM_EVENT_TYPE = "order_delivery_reply_notify"
|
||||
JUMP_PATH = "/apps/order-delivery-reply" # 免布局嵌入路由:企微内打开不带工作台侧栏
|
||||
|
||||
# 通知正文最多列出的订单条数;超出的折叠为「…等 N 笔」,避免超出企微卡片描述上限。
|
||||
MAX_LISTED_ORDERS = 8
|
||||
|
||||
# 审计动作名(models.order_delivery_reply.OrderDeliveryAuditEvent.action,String(32))。
|
||||
ACTION_SHIP_REMIND = "ship_remind"
|
||||
ACTION_UNREPLIED_REMIND = "unreplied_remind"
|
||||
|
||||
|
||||
def _business_today():
|
||||
"""北京时间业务日(约定交货日/回复交期都是业务日期,不能拿 UTC 日期比较)。"""
|
||||
return datetime.now(ZoneInfo("Asia/Shanghai")).date()
|
||||
|
||||
|
||||
def _resolve_salesperson_user(salesperson_code: str | None) -> User | None:
|
||||
"""订单业务员工号 → HXOPS 用户(须已绑企微);对不上返回 None,由调用方记录失败。"""
|
||||
code = (salesperson_code or "").strip()
|
||||
if not code:
|
||||
return None
|
||||
user = db.session.scalar(select(User).where(User.employee_id == code))
|
||||
if user is None or not (user.wecom_userid or "").strip():
|
||||
return None
|
||||
return user
|
||||
|
||||
|
||||
def _audit_reminded_keys(action: str, since_days: int) -> dict[int, set[str]]:
|
||||
"""
|
||||
读取历史上「发送成功」的已提醒 (line_id → planned_date 集合),供去重。
|
||||
|
||||
核心逻辑:只认 payload.ok=true 的审计——发送失败不算已提醒,次日扫描自动补发;
|
||||
Args:
|
||||
action: ship_remind(payload 带 planned_date 与 ok)。
|
||||
since_days: 只回看最近 N 天的审计(窗口远大于提醒周期,足够去重且避免全表扫描)。
|
||||
"""
|
||||
since = datetime.utcnow() - timedelta(days=since_days)
|
||||
events = db.session.scalars(
|
||||
select(OrderDeliveryAuditEvent).where(
|
||||
OrderDeliveryAuditEvent.action == action,
|
||||
OrderDeliveryAuditEvent.created_at >= since,
|
||||
)
|
||||
).all()
|
||||
reminded: dict[int, set[str]] = {}
|
||||
for event in events:
|
||||
payload = event.payload_json if isinstance(event.payload_json, dict) else {}
|
||||
if payload.get("ok") is not True:
|
||||
continue
|
||||
key = str(payload.get("planned_date") or "")
|
||||
reminded.setdefault(event.line_id or 0, set()).add(key)
|
||||
return reminded
|
||||
|
||||
|
||||
def _last_successful_unreplied_remind_at(since_days: int) -> dict[int, datetime]:
|
||||
"""
|
||||
每行最近一次「发送成功」的未回复提醒时间(控制 N 天一次的再次提醒节奏)。
|
||||
|
||||
核心逻辑:只统计 payload.ok=true 的事件;窗口外的旧事件等价于「从未提醒」
|
||||
(超过 N 天本来就该再次提醒),因此按窗口过滤不改变节奏语义。
|
||||
"""
|
||||
since = datetime.utcnow() - timedelta(days=since_days)
|
||||
events = db.session.scalars(
|
||||
select(OrderDeliveryAuditEvent).where(
|
||||
OrderDeliveryAuditEvent.action == ACTION_UNREPLIED_REMIND,
|
||||
OrderDeliveryAuditEvent.created_at >= since,
|
||||
)
|
||||
).all()
|
||||
last_by_line: dict[int, datetime] = {}
|
||||
for event in events:
|
||||
payload = event.payload_json if isinstance(event.payload_json, dict) else {}
|
||||
if payload.get("ok") is not True or event.line_id is None or event.created_at is None:
|
||||
continue
|
||||
line_id = int(event.line_id)
|
||||
if line_id not in last_by_line or event.created_at > last_by_line[line_id]:
|
||||
last_by_line[line_id] = event.created_at
|
||||
return last_by_line
|
||||
|
||||
|
||||
def _truncate_orders(entries: list[str]) -> str:
|
||||
"""订单清单截断:最多列 MAX_LISTED_ORDERS 条,其余折叠为「…等 N 笔」。"""
|
||||
if len(entries) <= MAX_LISTED_ORDERS:
|
||||
return "\n".join(entries)
|
||||
listed = "\n".join(entries[:MAX_LISTED_ORDERS])
|
||||
return f"{listed}\n…等共 {len(entries)} 笔"
|
||||
|
||||
|
||||
def _send_remind_card(user: User, content: str, jump_params: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
"""发提醒卡片;返回 {ok, trace_id?/reason?},成败以 send_wecom_event_message 返回为准。"""
|
||||
result = send_wecom_event_message(
|
||||
event_type=WECOM_EVENT_TYPE,
|
||||
user=user,
|
||||
title="订单交期回复",
|
||||
content=content,
|
||||
jump_path=JUMP_PATH,
|
||||
jump_params=jump_params,
|
||||
)
|
||||
return {"ok": bool(result.get("ok")), "trace_id": result.get("trace_id"), "reason": result.get("reason")}
|
||||
|
||||
|
||||
def run_ship_reminders(advance_days: int) -> dict[str, Any]:
|
||||
"""
|
||||
出货提醒:已回复(已锁定)行中,回复交期距今 ≤ advance_days 天的,提醒对应业务员出货。
|
||||
|
||||
核心逻辑:[STEP 1] 业务窗口 [today, today+advance_days];查已锁定且未标 erp_missing 的
|
||||
行批次候选;[STEP 2] 按 (line_id, planned_date) 去重(历史 ship_remind 审计);
|
||||
[STEP 3] 按业务员聚合发一条企微(一条多单,避免逐单刷屏),发送失败不计成功;
|
||||
[STEP 4] 逐行写 ship_remind 审计(含 trace/成败),供下次去重与追溯。
|
||||
Returns:
|
||||
{"advance_days", "candidate_lines", "notified_salespersons", "notified_lines",
|
||||
"failed_salespersons", "skipped_unmapped"}。
|
||||
"""
|
||||
today = _business_today()
|
||||
window_end = today + timedelta(days=max(0, int(advance_days)))
|
||||
|
||||
candidates: dict[int, list[dict[str, Any]]] = {}
|
||||
rows = db.session.execute(
|
||||
select(OrderDeliveryBatch, OrderDeliveryErpLine)
|
||||
.join(OrderDeliveryErpLine, OrderDeliveryErpLine.id == OrderDeliveryBatch.line_id)
|
||||
.join(OrderDeliveryLineState, OrderDeliveryLineState.line_id == OrderDeliveryErpLine.id)
|
||||
.where(
|
||||
OrderDeliveryErpLine.erp_missing.is_(False),
|
||||
OrderDeliveryLineState.locked.is_(True),
|
||||
OrderDeliveryBatch.planned_date >= today,
|
||||
OrderDeliveryBatch.planned_date <= window_end,
|
||||
)
|
||||
.order_by(OrderDeliveryBatch.planned_date.asc())
|
||||
).all()
|
||||
for batch, line in rows:
|
||||
candidates.setdefault(line.id, []).append(
|
||||
{
|
||||
"planned_date": batch.planned_date,
|
||||
"qty": batch.qty,
|
||||
"line": line,
|
||||
}
|
||||
)
|
||||
if not candidates:
|
||||
return {"advance_days": advance_days, "candidate_lines": 0, "notified_salespersons": 0,
|
||||
"notified_lines": 0, "failed_salespersons": 0, "skipped_unmapped": 0}
|
||||
|
||||
# [STEP 2] 去重:同 (行, 回复交期) 只提醒一次;回看窗口取 3 倍提前天数(至少 30 天)。
|
||||
reminded = _audit_reminded_keys(ACTION_SHIP_REMIND, since_days=max(30, int(advance_days) * 3))
|
||||
|
||||
# 按业务员聚合并过滤已提醒的 (行, 交期)。
|
||||
by_salesperson: dict[str, dict[str, Any]] = {}
|
||||
notified_lines = 0
|
||||
for line_id, entries in candidates.items():
|
||||
fresh = [e for e in entries if e["planned_date"].isoformat() not in reminded.get(line_id, set())]
|
||||
if not fresh:
|
||||
continue
|
||||
line = fresh[0]["line"]
|
||||
code = (line.salesperson_code or "").strip()
|
||||
bucket = by_salesperson.setdefault(
|
||||
code, {"entries": [], "line_ids": set()},
|
||||
)
|
||||
for entry in fresh:
|
||||
bucket["entries"].append(entry)
|
||||
bucket["line_ids"].add(line_id)
|
||||
|
||||
notified_persons = 0
|
||||
failed_persons = 0
|
||||
skipped_unmapped = 0
|
||||
for code, bucket in by_salesperson.items():
|
||||
user = _resolve_salesperson_user(code)
|
||||
if user is None:
|
||||
# 业务员未映射企微:记失败审计(不带 trace),次日扫描同样会重试。
|
||||
skipped_unmapped += 1
|
||||
for entry in bucket["entries"]:
|
||||
db.session.add(OrderDeliveryAuditEvent(
|
||||
line_id=entry["line"].id,
|
||||
order_no=entry["line"].order_no,
|
||||
line_no=entry["line"].line_no,
|
||||
action=ACTION_SHIP_REMIND,
|
||||
payload_json={
|
||||
"kind": "ship",
|
||||
"planned_date": entry["planned_date"].isoformat(),
|
||||
"ok": False,
|
||||
"reason": "salesperson_unmapped",
|
||||
"salesperson_code": code,
|
||||
},
|
||||
))
|
||||
db.session.commit()
|
||||
continue
|
||||
|
||||
lines_text = _truncate_orders([
|
||||
f"{entry['line'].order_no}:{entry['line'].line_no} 交期 {entry['planned_date'].isoformat()}"
|
||||
for entry in bucket["entries"]
|
||||
])
|
||||
content = (
|
||||
f"您有 {len(bucket['entries'])} 笔订单将在 {advance_days} 天内交货,请及时安排出货:\n{lines_text}"
|
||||
)
|
||||
# 卡片带 status=replied:业务员点开直达「已回复」视图(出货提醒行必然已回复锁定)。
|
||||
result = _send_remind_card(user, content, jump_params={"status": "replied"})
|
||||
if result["ok"]:
|
||||
notified_persons += 1
|
||||
notified_lines += len(bucket["line_ids"])
|
||||
else:
|
||||
failed_persons += 1
|
||||
for entry in bucket["entries"]:
|
||||
db.session.add(OrderDeliveryAuditEvent(
|
||||
line_id=entry["line"].id,
|
||||
order_no=entry["line"].order_no,
|
||||
line_no=entry["line"].line_no,
|
||||
action=ACTION_SHIP_REMIND,
|
||||
payload_json={
|
||||
"kind": "ship",
|
||||
"planned_date": entry["planned_date"].isoformat(),
|
||||
"ok": result["ok"],
|
||||
"reason": result.get("reason"),
|
||||
"recipient_employee_id": code,
|
||||
"recipient_wecom_userid": user.wecom_userid,
|
||||
"trace_id": result.get("trace_id"),
|
||||
},
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
return {
|
||||
"advance_days": advance_days,
|
||||
"candidate_lines": len(candidates),
|
||||
"notified_salespersons": notified_persons,
|
||||
"notified_lines": notified_lines,
|
||||
"failed_salespersons": failed_persons,
|
||||
"skipped_unmapped": skipped_unmapped,
|
||||
}
|
||||
|
||||
|
||||
def run_unreplied_reminders(unreplied_days: int, notify_user_ids: list[int]) -> dict[str, Any]:
|
||||
"""
|
||||
未回复再提醒:订单日期距今超 N 天仍未回复的订单行,聚合提醒生管(收件人 = 排程任务通知人配置)。
|
||||
|
||||
核心逻辑:[STEP 1] 候选 = 未锁定且未标 erp_missing、订单日期(order_date)距今
|
||||
≥ unreplied_days 的行(订单日期为空不参与提醒);
|
||||
[STEP 2] 同行距上次提醒 ≥ unreplied_days 才再次提醒
|
||||
(audit action=unreplied_remind 的 max(created_at) 控制,未提醒过则立即提醒);
|
||||
[STEP 3] 汇总为一
|
||||
条企微发给每个配置的生管收件人;无收件人时跳过并如实返回。
|
||||
Returns:
|
||||
{"unreplied_days", "due_lines", "notified_recipients", "failed_recipients", "skipped_no_recipient"}。
|
||||
"""
|
||||
today = _business_today()
|
||||
threshold_date = today - timedelta(days=max(0, int(unreplied_days)))
|
||||
|
||||
locked_subq = (
|
||||
select(OrderDeliveryLineState.line_id)
|
||||
.where(OrderDeliveryLineState.line_id == OrderDeliveryErpLine.id,
|
||||
OrderDeliveryLineState.locked.is_(True))
|
||||
.exists()
|
||||
)
|
||||
due_lines = list(
|
||||
db.session.scalars(
|
||||
select(OrderDeliveryErpLine)
|
||||
.where(
|
||||
OrderDeliveryErpLine.erp_missing.is_(False),
|
||||
~locked_subq,
|
||||
# 超期锚点 = ERP 订单日期(oea02,2026-09-23 由 created_at 改来,按业务确认口径):
|
||||
# 订单日期距今 ≥ N 天仍未锁定即入选;订单日期为空无法判定,不参与提醒。
|
||||
OrderDeliveryErpLine.order_date.is_not(None),
|
||||
OrderDeliveryErpLine.order_date <= threshold_date,
|
||||
)
|
||||
.order_by(OrderDeliveryErpLine.order_date.asc())
|
||||
).all()
|
||||
)
|
||||
if not due_lines:
|
||||
return {"unreplied_days": unreplied_days, "due_lines": 0, "notified_recipients": 0,
|
||||
"failed_recipients": 0, "skipped_no_recipient": False}
|
||||
|
||||
# [STEP 2] 同一行 N 天内不重复提醒(只看发送成功的记录;失败不算已提醒)。
|
||||
last_reminded = _last_successful_unreplied_remind_at(since_days=max(30, int(unreplied_days) * 3))
|
||||
pending_lines = [
|
||||
line for line in due_lines
|
||||
if line.id not in last_reminded
|
||||
or (datetime.utcnow() - last_reminded[line.id]) >= timedelta(days=max(1, int(unreplied_days)))
|
||||
]
|
||||
if not pending_lines:
|
||||
return {"unreplied_days": unreplied_days, "due_lines": len(due_lines), "notified_recipients": 0,
|
||||
"failed_recipients": 0, "skipped_no_recipient": False}
|
||||
|
||||
recipient_ids = [int(uid) for uid in (notify_user_ids or []) if uid]
|
||||
if not recipient_ids:
|
||||
return {"unreplied_days": unreplied_days, "due_lines": len(due_lines), "notified_recipients": 0,
|
||||
"failed_recipients": 0, "skipped_no_recipient": True}
|
||||
recipients = [u for u in User.query.filter(User.id.in_(recipient_ids)).all() if (u.wecom_userid or "").strip()]
|
||||
if not recipients:
|
||||
return {"unreplied_days": unreplied_days, "due_lines": len(due_lines), "notified_recipients": 0,
|
||||
"failed_recipients": 0, "skipped_no_recipient": True}
|
||||
|
||||
lines_text = _truncate_orders([
|
||||
f"{line.order_no}:{line.line_no} 客户 {line.customer_no or '—'} 下单 {line.order_date.isoformat() if line.order_date else '—'}"
|
||||
for line in pending_lines
|
||||
])
|
||||
content = (
|
||||
f"有 {len(pending_lines)} 笔订单交期已超过 {unreplied_days} 天未回复,请及时查看并回复交期:\n{lines_text}"
|
||||
)
|
||||
|
||||
notified = 0
|
||||
failed = 0
|
||||
for user in recipients:
|
||||
result = _send_remind_card(user, content, jump_params={"status": "not_fully_replied"})
|
||||
if result["ok"]:
|
||||
notified += 1
|
||||
else:
|
||||
failed += 1
|
||||
# 提醒节奏按「发送时间」记(成功失败都记,失败下次扫描重试不叠加节奏)。
|
||||
for line in pending_lines:
|
||||
db.session.add(OrderDeliveryAuditEvent(
|
||||
line_id=line.id,
|
||||
order_no=line.order_no,
|
||||
line_no=line.line_no,
|
||||
action=ACTION_UNREPLIED_REMIND,
|
||||
payload_json={
|
||||
"kind": "unreplied",
|
||||
"unreplied_days": unreplied_days,
|
||||
"ok": result["ok"],
|
||||
"reason": result.get("reason"),
|
||||
"recipient_user_id": user.id,
|
||||
"trace_id": result.get("trace_id"),
|
||||
},
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
return {
|
||||
"unreplied_days": unreplied_days,
|
||||
"due_lines": len(pending_lines),
|
||||
"notified_recipients": notified,
|
||||
"failed_recipients": failed,
|
||||
"skipped_no_recipient": False,
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
"""
|
||||
backend/app/services/order_delivery_reply/reply_service.py
|
||||
|
||||
用途:订单交期回复的写路径——单行/联合保存交期批次(未锁定行整表替换)。
|
||||
依赖:models/order_delivery_reply(快照/批次/状态/审计)、extensions.db、core.errors。
|
||||
逻辑:保存与通知是两步(需求 §5):本服务只写批次与 save 审计,不通知、不锁定;
|
||||
已锁定行拒绝写入(409);批次校验(交期必填、数量>0、备注≤200、各批次合计必须
|
||||
等于订单数量——2026-09-23 由「超额仅提醒」修订,BATCH_QTY_TOTAL_MISMATCH)在此层完成。
|
||||
后续通知/锁定在 notify_service 中与企微发送同事务实现,禁止在本文件锁定。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models.order_delivery_reply import (
|
||||
OrderDeliveryAuditEvent,
|
||||
OrderDeliveryBatch,
|
||||
OrderDeliveryErpLine,
|
||||
OrderDeliveryLineState,
|
||||
)
|
||||
|
||||
# 批次数量上限:单行允许维护的批次条数(需求 §10「1..N 批」,N 收敛为 20 防误操作)。
|
||||
MAX_BATCH_COUNT = 20
|
||||
REMARK_MAX_LENGTH = 200
|
||||
|
||||
|
||||
def _parse_batches(raw_batches: Any) -> list[dict[str, Any]]:
|
||||
"""
|
||||
校验并规范化请求中的批次列表。
|
||||
|
||||
用途与触发时机:单行保存与联合回复保存共用;在触碰数据库之前先做全量校验。
|
||||
|
||||
核心逻辑:必须为非空 list(1..MAX_BATCH_COUNT 条);每条交期必填且为合法日期、
|
||||
数量 > 0、备注 ≤ 200;同一次提交内不允许重复交期(重复即录入错误)。
|
||||
|
||||
Args:
|
||||
raw_batches: 请求 body 中的 batches 数组,元素 {planned_date, qty, remark?}。
|
||||
Returns:
|
||||
规范化后的 [{planned_date: date, qty: Decimal, remark: str|None}],按提交顺序。
|
||||
Raises:
|
||||
ValidationError: 结构、日期、数量、备注长度、重复交期不合法。
|
||||
"""
|
||||
if not isinstance(raw_batches, list) or not raw_batches:
|
||||
raise ValidationError("batches 必须为非空数组", code="ORDER_DELIVERY_REPLY.BATCHES_REQUIRED")
|
||||
if len(raw_batches) > MAX_BATCH_COUNT:
|
||||
raise ValidationError(f"单行批次数量超过上限 {MAX_BATCH_COUNT}", code="ORDER_DELIVERY_REPLY.BATCH_COUNT_EXCEEDED")
|
||||
|
||||
normalized: list[dict[str, Any]] = []
|
||||
seen_dates: set[date] = set()
|
||||
for idx, item in enumerate(raw_batches, start=1):
|
||||
if not isinstance(item, dict):
|
||||
raise ValidationError(f"第 {idx} 条批次格式不合法", code="ORDER_DELIVERY_REPLY.BATCH_INVALID")
|
||||
|
||||
planned_raw = item.get("planned_date")
|
||||
try:
|
||||
planned_date = date.fromisoformat(str(planned_raw))
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError(
|
||||
f"第 {idx} 条批次交期必填且须为 YYYY-MM-DD",
|
||||
code="ORDER_DELIVERY_REPLY.BATCH_INVALID",
|
||||
)
|
||||
if planned_date in seen_dates:
|
||||
raise ValidationError(
|
||||
f"第 {idx} 条批次交期 {planned_date} 重复",
|
||||
code="ORDER_DELIVERY_REPLY.BATCH_INVALID",
|
||||
)
|
||||
seen_dates.add(planned_date)
|
||||
|
||||
qty_raw = item.get("qty")
|
||||
try:
|
||||
qty = Decimal(str(qty_raw))
|
||||
except (TypeError, InvalidOperation):
|
||||
raise ValidationError(f"第 {idx} 条批次数量不合法", code="ORDER_DELIVERY_REPLY.BATCH_INVALID")
|
||||
if qty <= 0:
|
||||
raise ValidationError(f"第 {idx} 条批次数量必须大于 0", code="ORDER_DELIVERY_REPLY.BATCH_INVALID")
|
||||
|
||||
remark = item.get("remark")
|
||||
if remark is not None:
|
||||
remark = str(remark).strip() or None
|
||||
if len(remark) > REMARK_MAX_LENGTH:
|
||||
raise ValidationError(
|
||||
f"第 {idx} 条批次备注超过 {REMARK_MAX_LENGTH} 字符",
|
||||
code="ORDER_DELIVERY_REPLY.BATCH_INVALID",
|
||||
)
|
||||
|
||||
normalized.append({"planned_date": planned_date, "qty": qty, "remark": remark})
|
||||
return normalized
|
||||
|
||||
|
||||
def get_line_for_write(order_no: str, line_no: int) -> tuple[OrderDeliveryErpLine, OrderDeliveryLineState | None]:
|
||||
"""
|
||||
取可写的订单行与其锁定状态(写路径统一入口)。
|
||||
|
||||
Args:
|
||||
order_no / line_no: 行唯一键。
|
||||
Returns:
|
||||
(行, 状态或None)。
|
||||
Raises:
|
||||
NotFoundError: 行不存在或已标 erp_missing(直链按不存在处理)。
|
||||
ConflictError: 行已通知锁定,禁止再改批次。
|
||||
"""
|
||||
line = db.session.scalar(
|
||||
select(OrderDeliveryErpLine).where(
|
||||
OrderDeliveryErpLine.order_no == order_no,
|
||||
OrderDeliveryErpLine.line_no == line_no,
|
||||
OrderDeliveryErpLine.erp_missing.is_(False),
|
||||
)
|
||||
)
|
||||
if not line:
|
||||
raise NotFoundError(
|
||||
"Order delivery line not found",
|
||||
code="ORDER_DELIVERY_REPLY.LINE_NOT_FOUND",
|
||||
)
|
||||
state = db.session.scalar(
|
||||
select(OrderDeliveryLineState).where(OrderDeliveryLineState.line_id == line.id)
|
||||
)
|
||||
if state and state.locked:
|
||||
raise ConflictError(
|
||||
"该订单行交期已通知锁定,不能修改批次",
|
||||
code="ORDER_DELIVERY_REPLY.LINE_LOCKED",
|
||||
)
|
||||
return line, state
|
||||
|
||||
|
||||
def save_batches(order_no: str, line_no: int, raw_batches: Any, operator_user_id: int | None) -> dict[str, Any]:
|
||||
"""
|
||||
保存一行交期批次(未锁定行整表替换:删旧批 → 写新批 → 记审计)。
|
||||
|
||||
用途与触发时机:单行「回复交期/修改回复」与联合回复保存逐行复用本入口;
|
||||
AI/排程不触发本函数(无自动回复语义)。
|
||||
|
||||
核心逻辑:[STEP 1] 校验批次结构(_parse_batches);
|
||||
[STEP 2] get_line_for_write 确认行存在且未锁定;数量守恒校验:各批次合计必须
|
||||
等于订单数量(2026-09-23 由「超额仅提醒」修订),不等抛 422 BATCH_QTY_TOTAL_MISMATCH;
|
||||
[STEP 3] 事务内删除旧批次、按序号写入新批次;
|
||||
[STEP 4] 写 action=save 审计(含批次快照)。
|
||||
保存后行仍为部分回复;通知与锁定走 notify 路径,本函数不触碰 line_states。
|
||||
|
||||
Args:
|
||||
order_no / line_no: 行唯一键。
|
||||
raw_batches: [{planned_date, qty, remark?}]。
|
||||
operator_user_id: 保存人(HXOPS 用户 id),审计用。
|
||||
Returns:
|
||||
{"order_no", "line_no", "batches": [...], "total_qty"} 序列化结果。
|
||||
"""
|
||||
normalized = _parse_batches(raw_batches)
|
||||
line, _state = get_line_for_write(order_no, line_no)
|
||||
|
||||
# [STEP 2] 数量守恒:各批次合计必须等于订单数量(保存口径 2026-09-23 修订,原允许超额仅提醒);
|
||||
# 校验在任何写操作之前,失败时不落批次也不落审计。
|
||||
total_qty = sum((batch["qty"] for batch in normalized), Decimal(0))
|
||||
order_qty = line.qty if line.qty is not None else Decimal(0)
|
||||
if total_qty != order_qty:
|
||||
raise ValidationError(
|
||||
f"各批次数量合计({total_qty})必须等于订单数量({order_qty}),请调整后重新保存",
|
||||
code="ORDER_DELIVERY_REPLY.BATCH_QTY_TOTAL_MISMATCH",
|
||||
)
|
||||
|
||||
# [STEP 3] 整表替换:未锁定行的旧批次全部作废,以本次提交为准。
|
||||
db.session.query(OrderDeliveryBatch).filter(OrderDeliveryBatch.line_id == line.id).delete()
|
||||
for seq, batch in enumerate(normalized, start=1):
|
||||
db.session.add(
|
||||
OrderDeliveryBatch(
|
||||
line_id=line.id,
|
||||
seq=seq,
|
||||
planned_date=batch["planned_date"],
|
||||
qty=batch["qty"],
|
||||
remark=batch["remark"],
|
||||
created_by=operator_user_id,
|
||||
)
|
||||
)
|
||||
|
||||
db.session.add(
|
||||
OrderDeliveryAuditEvent(
|
||||
line_id=line.id,
|
||||
order_no=line.order_no,
|
||||
line_no=line.line_no,
|
||||
action="save",
|
||||
operator_user_id=operator_user_id,
|
||||
payload_json={
|
||||
"batch_count": len(normalized),
|
||||
"total_qty": str(total_qty),
|
||||
"batches": [
|
||||
{
|
||||
"seq": seq,
|
||||
"planned_date": batch["planned_date"].isoformat(),
|
||||
"qty": str(batch["qty"]),
|
||||
"remark": batch["remark"],
|
||||
}
|
||||
for seq, batch in enumerate(normalized, start=1)
|
||||
],
|
||||
"saved_at": datetime.utcnow().isoformat(),
|
||||
},
|
||||
)
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
return {
|
||||
"order_no": line.order_no,
|
||||
"line_no": line.line_no,
|
||||
"batches": [
|
||||
{
|
||||
"seq": seq,
|
||||
"planned_date": batch["planned_date"].isoformat(),
|
||||
"qty": str(batch["qty"]),
|
||||
"remark": batch["remark"],
|
||||
}
|
||||
for seq, batch in enumerate(normalized, start=1)
|
||||
],
|
||||
"total_qty": str(total_qty),
|
||||
}
|
||||
|
||||
|
||||
def batch_reply(raw_items: Any, operator_user_id: int | None) -> dict[str, Any]:
|
||||
"""
|
||||
联合回复:对勾选的多行逐行保存批次(只保存,不通知、不锁定)。
|
||||
|
||||
用途与触发时机:工作台勾选多行后点「+ 联合回复交期」并逐行填批次提交(R-REPLY-02)。
|
||||
|
||||
核心逻辑:[STEP 1] 校验请求结构(非空数组、每项含 order_no/line_no/batches);
|
||||
[STEP 2] 逐行调用 save_batches;单行失败不回滚已成功的行(草稿语义,
|
||||
部分保存优于整体失败),失败行带错误信息返回由前端标红重试;
|
||||
[STEP 3] 汇总 succeeded/failed 与各行结果。
|
||||
|
||||
Args:
|
||||
raw_items: [{"order_no", "line_no", "batches": [{planned_date, qty, remark?}]}]。
|
||||
operator_user_id: 保存人。
|
||||
Returns:
|
||||
{"succeeded": N, "failed": N, "items": [{order_no, line_no, ok, error?, data?}]}。
|
||||
"""
|
||||
from app.core.errors import AppError
|
||||
|
||||
if not isinstance(raw_items, list) or not raw_items:
|
||||
raise ValidationError("items 必须为非空数组", code="ORDER_DELIVERY_REPLY.BATCH_REPLY_EMPTY")
|
||||
if len(raw_items) > 200:
|
||||
raise ValidationError("单次联合回复行数超过上限 200", code="ORDER_DELIVERY_REPLY.BATCH_REPLY_EMPTY")
|
||||
|
||||
results: list[dict[str, Any]] = []
|
||||
for item in raw_items:
|
||||
if not isinstance(item, dict) or not item.get("order_no") or item.get("line_no") is None:
|
||||
results.append({"ok": False, "error": "行唯一键缺失(order_no/line_no)"})
|
||||
continue
|
||||
order_no = str(item["order_no"]).strip()
|
||||
try:
|
||||
line_no = int(item["line_no"])
|
||||
except (TypeError, ValueError):
|
||||
results.append({"order_no": order_no, "ok": False, "error": "line_no 须为整数"})
|
||||
continue
|
||||
try:
|
||||
data = save_batches(order_no, line_no, item.get("batches"), operator_user_id)
|
||||
results.append({"order_no": order_no, "line_no": line_no, "ok": True, "data": data})
|
||||
except AppError as exc:
|
||||
# [STEP 2] 单行失败只记结果,不回滚其它行(save_batches 每行独立事务)。
|
||||
db.session.rollback()
|
||||
results.append(
|
||||
{"order_no": order_no, "line_no": line_no, "ok": False, "error": exc.message}
|
||||
)
|
||||
|
||||
return {
|
||||
"succeeded": sum(1 for r in results if r.get("ok")),
|
||||
"failed": sum(1 for r in results if not r.get("ok")),
|
||||
"items": results,
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
"""订单交期回复默认排程种子:每天 07:00(Asia/Shanghai)ERP 全量同步 + 07:10 每日提醒。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleTask, User
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
|
||||
_DEFAULTS = (
|
||||
('SCH-ORDER-DELIVERY-SYNC', 'order-delivery-sync', '订单交期回复 ERP 同步(日批 07:00)', '0 7 * * *'),
|
||||
# 提醒排在同步之后:扫描的是当天刚同步的最新快照。
|
||||
('SCH-ORDER-DELIVERY-REMIND', 'order-delivery-remind', '订单交期回复 提醒(日批 07:10)', '10 7 * * *'),
|
||||
)
|
||||
|
||||
|
||||
def ensure_default_order_delivery_schedules(*, commit: bool = True):
|
||||
"""
|
||||
幂等创建订单交期回复每日同步默认排程。
|
||||
|
||||
Args:
|
||||
commit: 是否提交新建排程;测试或外层事务可传 False。
|
||||
Returns:
|
||||
新建的 ScheduleTask 列表;无用户时返回空列表。
|
||||
"""
|
||||
owner = db.session.query(User).filter(User.role == 'admin').order_by(User.id.asc()).first() or db.session.query(User).order_by(User.id.asc()).first()
|
||||
if owner is None:
|
||||
return []
|
||||
created = []
|
||||
for schedule_no, platform_path, name, cron in _DEFAULTS:
|
||||
existing = db.session.query(ScheduleTask).filter((ScheduleTask.schedule_no == schedule_no) | (ScheduleTask.platform_api_path == platform_path)).first()
|
||||
if existing:
|
||||
continue
|
||||
now = datetime.utcnow()
|
||||
task = ScheduleTask(
|
||||
schedule_no=schedule_no, name=name, schedule_type='platform_job', owner_user_id=owner.id,
|
||||
cron_expr=cron, schedule_timezone='Asia/Shanghai', wait_seconds=0,
|
||||
platform_api_path=platform_path, job_params={}, kb_sync_enabled=False,
|
||||
notify_user_ids_json=[], notify_enabled=False, enabled=True,
|
||||
next_run_at=compute_next_run_at(cron, timezone_name='Asia/Shanghai') or now,
|
||||
created_by=owner.id, updated_by=owner.id, created_at=now, updated_at=now,
|
||||
)
|
||||
db.session.add(task); created.append(task)
|
||||
if commit and created:
|
||||
db.session.commit()
|
||||
elif not commit:
|
||||
db.session.flush()
|
||||
return created
|
||||
@@ -0,0 +1,45 @@
|
||||
"""
|
||||
backend/app/services/order_delivery_reply/sql.py
|
||||
|
||||
用途:订单交期回复 ERP(鼎捷 topprod)取数 SQL 唯一权威定义;同步服务与原型脚本共用。
|
||||
依赖:无(纯常量);连接约定见 services/text2sql.py(ERP_DB_DSN / ERP_DB_USER / ERP_DB_PASSWORD)。
|
||||
逻辑:一期同步全部「已审核 oeaconf='Y' + 已核准 oea49='1' + 未结案 oeb70≠Y」合格订单行,
|
||||
不按单别过滤;后期单别白名单在此基础上追加 IN 条件。业务约束:仅只读 SELECT,
|
||||
禁止改写为 INSERT/UPDATE/DELETE。
|
||||
"""
|
||||
|
||||
# 基础 SELECT:不带分页/排序,同步服务按 oea01 keyset 分页时在外层包装。
|
||||
# 关联:oea01=oeb01;oeb04=ima01 且 oeb06=ima02;oea03=occ01;oea14=gen01;oea15=gem01。
|
||||
# 别名与 docs/features/order-delivery-reply/technical-design.md §3.5 标准 SELECT 逐列一致。
|
||||
ORDER_DELIVERY_SQL = """
|
||||
SELECT
|
||||
a.oea01 AS order_no,
|
||||
b.oeb03 AS line_no,
|
||||
a.oea02 AS order_date,
|
||||
a.oea03 AS customer_no,
|
||||
d.occ02 AS customer_short_name,
|
||||
d.occ18 AS customer_full_name,
|
||||
a.oea14 AS salesperson_code,
|
||||
e.gen02 AS salesperson_name,
|
||||
a.oea15 AS dept_code,
|
||||
f.gem02 AS dept_name,
|
||||
a.oea10 AS customer_po,
|
||||
b.oeb04 AS part_no,
|
||||
b.oeb06 AS part_name,
|
||||
c.ima021 AS spec,
|
||||
b.oeb11 AS customer_part_no,
|
||||
b.oeb15 AS agreed_date,
|
||||
b.oeb05 AS unit,
|
||||
b.oeb12 AS qty,
|
||||
NVL(b.oeb24, 0) AS delivered_qty
|
||||
FROM HXJM.OEA_FILE a
|
||||
INNER JOIN HXJM.OEB_FILE b ON a.oea01 = b.oeb01
|
||||
LEFT JOIN HXJM.IMA_FILE c ON b.oeb04 = c.ima01 AND b.oeb06 = c.ima02
|
||||
LEFT JOIN HXJM.OCC_FILE d ON a.oea03 = d.occ01
|
||||
LEFT JOIN HXJM.GEN_FILE e ON a.oea14 = e.gen01
|
||||
LEFT JOIN HXJM.GEM_FILE f ON a.oea15 = f.gem01
|
||||
WHERE a.oeaconf = 'Y'
|
||||
AND a.oea49 = '1'
|
||||
AND NVL(b.oeb70, 'N') = 'N'
|
||||
AND NVL(b.oeb24, 0) = 0
|
||||
"""
|
||||
@@ -0,0 +1,306 @@
|
||||
"""
|
||||
backend/app/services/order_delivery_reply/sync_service.py
|
||||
|
||||
用途:订单交期回复 ERP 全量同步服务(07:00 排程与手动刷新共用);只读 ERP、upsert 本地快照。
|
||||
依赖:services/order_delivery_reply/sql(取数口径)、services/text2sql(Oracle thick 模式初始化)、
|
||||
models/order_delivery_reply(本地表)、extensions.db。
|
||||
逻辑:按 oea01 keyset 分页拉取合格订单行 → 对 (order_no, line_no) 做 upsert 且只更新 ERP 列白名单
|
||||
(绝不覆盖批次/锁定)→ 本轮未命中的本地行置 erp_missing=true(不删除)→ 写 sync_runs。
|
||||
全程模块级锁保证同时只有一个同步;失败保留上次快照并记录错误。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select, update
|
||||
|
||||
from app.extensions import db
|
||||
from app.models.order_delivery_reply import (
|
||||
OrderDeliveryAuditEvent,
|
||||
OrderDeliveryErpLine,
|
||||
OrderDeliverySyncRun,
|
||||
)
|
||||
from app.services.order_delivery_reply.sql import ORDER_DELIVERY_SQL
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 同步 upsert 只允许更新这些 ERP 快照列;触碰批次/锁定列会覆盖业务回复,禁止扩充业务列进来。
|
||||
ERP_LINE_COLUMNS = (
|
||||
"order_date",
|
||||
"customer_no",
|
||||
"customer_short_name",
|
||||
"customer_full_name",
|
||||
"salesperson_code",
|
||||
"salesperson_name",
|
||||
"dept_code",
|
||||
"dept_name",
|
||||
"customer_po",
|
||||
"part_no",
|
||||
"part_name",
|
||||
"spec",
|
||||
"customer_part_no",
|
||||
"agreed_date",
|
||||
"unit",
|
||||
"qty",
|
||||
"delivered_qty",
|
||||
"slip_code",
|
||||
)
|
||||
|
||||
_FETCH_SIZE = 500
|
||||
|
||||
_thick_init_lock = threading.Lock()
|
||||
_thick_initialized = False
|
||||
|
||||
|
||||
def _ensure_thick_client(oracledb) -> None:
|
||||
"""按 ORACLE_CLIENT_LIB_DIR(或 backend/oracle_client 约定)初始化 thick 模式;幂等且失败不掩埋。"""
|
||||
global _thick_initialized
|
||||
with _thick_init_lock:
|
||||
if _thick_initialized or not getattr(oracledb, "is_thin_mode", lambda: True)():
|
||||
_thick_initialized = True
|
||||
return
|
||||
candidates = []
|
||||
env_dir = (os.getenv("ORACLE_CLIENT_LIB_DIR") or "").strip()
|
||||
if env_dir:
|
||||
candidates.append(os.path.normpath(env_dir))
|
||||
backend_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
candidates.append(os.path.join(backend_dir, "oracle_client"))
|
||||
marker = {"oci.dll", "libclntsh.so", "libclntsh.dylib"}
|
||||
lib_dir = None
|
||||
for root in candidates:
|
||||
if not root or not os.path.isdir(root):
|
||||
continue
|
||||
if marker & {n.lower() for n in os.listdir(root)}:
|
||||
lib_dir = root
|
||||
break
|
||||
sub = [d for d in os.listdir(root) if d.startswith("instantclient_") and os.path.isdir(os.path.join(root, d))]
|
||||
if sub:
|
||||
lib_dir = os.path.join(root, sub[0])
|
||||
break
|
||||
if lib_dir:
|
||||
os.environ["PATH"] = lib_dir + os.pathsep + os.environ.get("PATH", "")
|
||||
if hasattr(os, "add_dll_directory"):
|
||||
os.add_dll_directory(lib_dir)
|
||||
oracledb.init_oracle_client(lib_dir=lib_dir)
|
||||
else:
|
||||
oracledb.init_oracle_client()
|
||||
_thick_initialized = True
|
||||
|
||||
# 进程内互斥:同一 worker 同时只跑一个同步(多 worker 由 sync_runs running 行兜底,一期单机足够)。
|
||||
_sync_lock = threading.Lock()
|
||||
|
||||
|
||||
def _extract_slip_code(order_no: str | None) -> str | None:
|
||||
"""从订单单号取连字符前的单别(8301-1605280014 → 8301);无连字符返回整号前缀。"""
|
||||
if not order_no:
|
||||
return None
|
||||
return order_no.split("-", 1)[0]
|
||||
|
||||
|
||||
class OrderDeliverySyncService:
|
||||
"""ERP → 本地 Postgres 的订单行全量同步;所有方法不回写 ERP。"""
|
||||
|
||||
@staticmethod
|
||||
def _connect():
|
||||
"""
|
||||
建立 ERP Oracle 连接(凭据复用合同付款预警的 CONTRACT_PAYMENT_ERP_* 配置)。
|
||||
|
||||
核心逻辑:账号/密码优先专用键 ERP_DB_USER / ERP_DB_PASSWORD(或 ERP_USERNAME/ERP_PASSWORD),
|
||||
缺省回退 .env.shared 已有的 CONTRACT_PAYMENT_ERP_USERNAME / CONTRACT_PAYMENT_ERP_PASSWORD
|
||||
(hxjm 账号,与合同付款预警同一连接口径,技术文档 §3.1);DSN 用 ERP_DB_DSN。
|
||||
thin 优先,失败时按 Text2SQL 既有路径切 thick(本地 Instant Client)。
|
||||
|
||||
Returns:
|
||||
oracledb.Connection;凭据缺失时抛 RuntimeError 提示配置来源。
|
||||
"""
|
||||
import oracledb
|
||||
|
||||
user = (
|
||||
os.getenv("ERP_DB_USER")
|
||||
or os.getenv("ERP_USERNAME")
|
||||
or os.getenv("CONTRACT_PAYMENT_ERP_USERNAME")
|
||||
or "EXT_VIEW_USER"
|
||||
)
|
||||
password = (
|
||||
os.getenv("ERP_DB_PASSWORD")
|
||||
or os.getenv("ERP_PASSWORD")
|
||||
or os.getenv("CONTRACT_PAYMENT_ERP_PASSWORD")
|
||||
)
|
||||
dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod")
|
||||
if not password:
|
||||
raise RuntimeError(
|
||||
"ERP 口令未配置:请设置 ERP_DB_PASSWORD,或复用 .env.shared 的 "
|
||||
"CONTRACT_PAYMENT_ERP_PASSWORD(与合同付款预警同一 topprod 连接)"
|
||||
)
|
||||
try:
|
||||
return oracledb.connect(user=user, password=password, dsn=dsn)
|
||||
except oracledb.DatabaseError:
|
||||
# thin 模式连不上(topprod 为 11g 必走 thick):用 ORACLE_CLIENT_LIB_DIR 自初始化,
|
||||
# 不再依赖 services/text2sql——worker 进程 sys.path 差异曾致
|
||||
# "No module named app.services.text2sql"(2026-09-22 排程同步失败根因)。
|
||||
_ensure_thick_client(oracledb)
|
||||
return oracledb.connect(user=user, password=password, dsn=dsn)
|
||||
|
||||
@classmethod
|
||||
def _fetch_page(cls, cursor, last_order_no: str | None) -> list[dict[str, Any]]:
|
||||
"""
|
||||
按 oea01 keyset 分页拉取一页订单行。
|
||||
|
||||
Args:
|
||||
cursor: oracledb 游标。
|
||||
last_order_no: 上一页最后一条订单单号;None 表示从头发起。
|
||||
Returns:
|
||||
本页行字典列表(列为 sql.ORDER_DELIVERY_SQL 的别名)。
|
||||
"""
|
||||
# Oracle 空串即 NULL:首页不能带 `order_no > ''`(与 NULL 比较恒 UNKNOWN 会滤掉全部行),
|
||||
# 因此首页与续页使用两个 SQL 变体。
|
||||
if last_order_no:
|
||||
page_sql = (
|
||||
f"SELECT * FROM ({ORDER_DELIVERY_SQL} ORDER BY a.oea01) "
|
||||
f"WHERE order_no > :last_order_no AND ROWNUM <= {_FETCH_SIZE}"
|
||||
)
|
||||
cursor.execute(page_sql, last_order_no=last_order_no)
|
||||
else:
|
||||
page_sql = f"SELECT * FROM ({ORDER_DELIVERY_SQL} ORDER BY a.oea01) WHERE ROWNUM <= {_FETCH_SIZE}"
|
||||
cursor.execute(page_sql)
|
||||
columns = [col[0].lower() for col in cursor.description]
|
||||
return [dict(zip(columns, row)) for row in cursor.fetchall()]
|
||||
|
||||
@classmethod
|
||||
def _upsert_page(cls, rows: list[dict[str, Any]], synced_at: datetime) -> set[tuple[str, int]]:
|
||||
"""
|
||||
upsert 一页快照行:只更新 ERP 列白名单并复位 erp_missing,绝不覆盖批次/锁定。
|
||||
|
||||
Returns:
|
||||
本页命中的 (order_no, line_no) 集合,供整轮结束后标记 erp_missing。
|
||||
"""
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
|
||||
hit_keys: set[tuple[str, int]] = set()
|
||||
for raw in rows:
|
||||
order_no = str(raw["order_no"] or "").strip()
|
||||
if not order_no or raw["line_no"] is None:
|
||||
continue
|
||||
line_no = int(raw["line_no"])
|
||||
values = {
|
||||
"order_no": order_no,
|
||||
"line_no": line_no,
|
||||
"slip_code": _extract_slip_code(order_no),
|
||||
"erp_missing": False,
|
||||
"last_synced_at": synced_at,
|
||||
}
|
||||
for col in ERP_LINE_COLUMNS:
|
||||
if col == "slip_code":
|
||||
continue
|
||||
value = raw.get(col)
|
||||
if isinstance(value, datetime):
|
||||
value = value.date()
|
||||
values[col] = value
|
||||
|
||||
stmt = insert(OrderDeliveryErpLine).values(**values)
|
||||
stmt = stmt.on_conflict_do_update(
|
||||
constraint="uq_order_delivery_erp_lines_order_line",
|
||||
set_={**{col: stmt.excluded[col] for col in ERP_LINE_COLUMNS},
|
||||
"erp_missing": False,
|
||||
"last_synced_at": synced_at},
|
||||
)
|
||||
db.session.execute(stmt)
|
||||
hit_keys.add((order_no, line_no))
|
||||
return hit_keys
|
||||
|
||||
@classmethod
|
||||
def run_sync(cls, trigger: str = "manual") -> dict[str, Any]:
|
||||
"""
|
||||
执行一次全量同步(排程传 'scheduled',手动传 'manual')。
|
||||
|
||||
用途与触发时机:07:00 定时任务与生管手动刷新共用入口;AI/脚本也可直调验证取数。
|
||||
|
||||
核心逻辑:[STEP 1] 抢互斥锁并写 running 状态的 sync_runs;
|
||||
[STEP 2] 按 oea01 分页拉 ERP 合格行,逐页 upsert(仅 ERP 列白名单);
|
||||
[STEP 3] 本轮未命中的本地行统一置 erp_missing=true(不删除,默认列表不展示);
|
||||
[STEP 4] 写审计与终态 sync_runs;任何异常保留上次快照、记 failed。
|
||||
|
||||
Args:
|
||||
trigger: 'scheduled' | 'manual'。
|
||||
Returns:
|
||||
{"run_id", "status", "line_count"};并发冲突返回 status='skipped'。
|
||||
"""
|
||||
if not _sync_lock.acquire(blocking=False):
|
||||
return {"run_id": None, "status": "skipped", "line_count": 0}
|
||||
|
||||
synced_at = datetime.utcnow()
|
||||
run = OrderDeliverySyncRun(trigger=trigger, status="running", started_at=synced_at)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
hit_keys: set[tuple[str, int]] = set()
|
||||
try:
|
||||
with cls._connect() as conn:
|
||||
with conn.cursor() as cursor:
|
||||
last_order_no: str | None = None
|
||||
while True:
|
||||
page = cls._fetch_page(cursor, last_order_no)
|
||||
if not page:
|
||||
break
|
||||
hit_keys |= cls._upsert_page(page, synced_at)
|
||||
db.session.commit()
|
||||
last_order_no = str(page[-1]["order_no"])
|
||||
|
||||
# [STEP 3] 未命中行标记 erp_missing:已有批次/锁定的行保留可追,纯快照行同样不再展示。
|
||||
missing_ids = [
|
||||
row_id
|
||||
for row_id, order_no, line_no, _missing in db.session.execute(
|
||||
select(
|
||||
OrderDeliveryErpLine.id,
|
||||
OrderDeliveryErpLine.order_no,
|
||||
OrderDeliveryErpLine.line_no,
|
||||
OrderDeliveryErpLine.erp_missing,
|
||||
)
|
||||
).all()
|
||||
if (order_no, line_no) not in hit_keys
|
||||
]
|
||||
if missing_ids:
|
||||
db.session.execute(
|
||||
update(OrderDeliveryErpLine)
|
||||
.where(OrderDeliveryErpLine.id.in_(missing_ids))
|
||||
.values(erp_missing=True)
|
||||
)
|
||||
|
||||
run.status = "success"
|
||||
run.line_count = len(hit_keys)
|
||||
run.finished_at = datetime.utcnow()
|
||||
db.session.add(
|
||||
OrderDeliveryAuditEvent(
|
||||
action="sync",
|
||||
payload_json={"trigger": trigger, "line_count": len(hit_keys), "missing_count": len(missing_ids)},
|
||||
)
|
||||
)
|
||||
db.session.commit()
|
||||
logger.info("order-delivery-reply sync done: trigger=%s lines=%s missing=%s", trigger, len(hit_keys), len(missing_ids))
|
||||
return {"run_id": run.id, "status": "success", "line_count": len(hit_keys)}
|
||||
except Exception as exc: # noqa: BLE001 — 同步失败必须落库留痕并保留上次快照
|
||||
db.session.rollback()
|
||||
run.status = "failed"
|
||||
run.error_message = str(exc)[:4000]
|
||||
run.finished_at = datetime.utcnow()
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
logger.exception("order-delivery-reply sync failed (trigger=%s)", trigger)
|
||||
raise
|
||||
finally:
|
||||
_sync_lock.release()
|
||||
|
||||
@staticmethod
|
||||
def latest_run() -> OrderDeliverySyncRun | None:
|
||||
"""最近一次同步运行记录,供页面展示同步时间与结果。"""
|
||||
return (
|
||||
db.session.execute(
|
||||
select(OrderDeliverySyncRun).order_by(OrderDeliverySyncRun.started_at.desc()).limit(1)
|
||||
)
|
||||
.scalar_one_or_none()
|
||||
)
|
||||
@@ -19,6 +19,9 @@ KNOWN_FEATURE_KEYS: tuple[str, ...] = (
|
||||
'shipping_notice.xfa_split_rule_preview',
|
||||
'shipping_notice.xfa_split_rule_publish',
|
||||
'maintenance.ledger_write',
|
||||
# 订单交期回复(2026-09-29 合并登记):manage 命中视为有 access,两键须一并授予。
|
||||
'order_delivery_reply.manage',
|
||||
'order_delivery_reply.access',
|
||||
)
|
||||
|
||||
FEATURE_CATALOG: tuple[dict[str, Any], ...] = (
|
||||
@@ -64,6 +67,18 @@ FEATURE_CATALOG: tuple[dict[str, Any], ...] = (
|
||||
'name': '台账与维修维护',
|
||||
'hint': '维护设备台账与维修记录',
|
||||
},
|
||||
{
|
||||
'key': 'order_delivery_reply.manage',
|
||||
'bind': 'agent_code:order_delivery_reply',
|
||||
'name': '订单交期回复管理',
|
||||
'hint': '生管回复交期、发送通知并手动同步',
|
||||
},
|
||||
{
|
||||
'key': 'order_delivery_reply.access',
|
||||
'bind': 'agent_code:order_delivery_reply',
|
||||
'name': '订单交期回复查看',
|
||||
'hint': '业务只读查看已同步订单与回复结果',
|
||||
},
|
||||
)
|
||||
|
||||
# 现网 users.role 枚举对应的标准权限组。admin/user/hr 为内置;rd/shipping 可后续增删应用。
|
||||
|
||||
@@ -3,24 +3,57 @@ backend/app/services/schedule/file_asset_cleanup_job.py
|
||||
|
||||
用途:排程平台 Job —— 清理过期未引用的临时文件资产。
|
||||
依赖:file_assets.cleanup。
|
||||
逻辑:platform_api_path=file-asset-cleanup 时由 job_registry 调用。
|
||||
逻辑:platform_api_path=file-asset-cleanup 时由 job_registry 调用;
|
||||
包装 cleanup_expired_temporary_assets 的统计字典为平台标准七元组
|
||||
(total/success/failed/skipped/details/errors/step_logs),对齐其它平台 Job 契约。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.file_assets.cleanup import cleanup_expired_temporary_assets
|
||||
|
||||
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
|
||||
|
||||
def run_file_asset_cleanup_schedule(task: Any, run: Any) -> dict[str, Any]:
|
||||
|
||||
def run_file_asset_cleanup_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""
|
||||
执行临时文件资产 TTL 清理。
|
||||
执行临时文件资产 TTL 清理并返回平台标准审计七元组。
|
||||
|
||||
统计口径:total=scanned(本批扫描数)、success=deleted(物理删除数)、
|
||||
failed=errors(删除失败数)、skipped=expired 未删除部分。
|
||||
|
||||
Args:
|
||||
task: ScheduleTask。
|
||||
task: ScheduleTask(job_params.limit 可调单批上限,缺省 200)。
|
||||
run: ScheduleRun。
|
||||
Returns:
|
||||
清理统计。
|
||||
(total, success, failed, skipped, details, errors, step_logs)。
|
||||
"""
|
||||
_ = task, run
|
||||
return cleanup_expired_temporary_assets(limit=200)
|
||||
_ = run
|
||||
params = task.job_params if isinstance(task.job_params, dict) else {}
|
||||
try:
|
||||
limit = int(params.get("limit") or 200)
|
||||
except (TypeError, ValueError):
|
||||
limit = 200
|
||||
|
||||
stats = cleanup_expired_temporary_assets(limit=limit)
|
||||
scanned = int(stats.get("scanned") or 0)
|
||||
deleted = int(stats.get("deleted") or 0)
|
||||
errors_count = int(stats.get("errors") or 0)
|
||||
expired = int(stats.get("expired") or 0)
|
||||
skipped = max(0, expired - deleted)
|
||||
|
||||
errors: list[str] = []
|
||||
if errors_count:
|
||||
errors.append(f"临时文件资产清理有 {errors_count} 个对象删除失败,详见 step_logs 统计")
|
||||
|
||||
step_logs: list[dict[str, Any]] = [
|
||||
{
|
||||
"step": "file_asset_cleanup",
|
||||
"status": "success" if errors_count == 0 else "partial",
|
||||
"detail": stats,
|
||||
}
|
||||
]
|
||||
return (scanned, deleted, errors_count, skipped, [stats], errors, step_logs)
|
||||
@@ -64,6 +64,21 @@ def _shipping_receipt_sources_options() -> list[dict[str, Any]]:
|
||||
} for source, _config in rows]
|
||||
|
||||
|
||||
def _hxops_users_options() -> list[dict[str, Any]]:
|
||||
"""全部启用用户(value=users.id);订单交期回复未回复提醒收件人等场景用。"""
|
||||
from app.models import User
|
||||
|
||||
users = User.query.filter(User.status == "active").order_by(User.real_name.asc(), User.id.asc()).all()
|
||||
return [
|
||||
{
|
||||
"label": f"{u.real_name or u.username}({u.employee_id or '-'})",
|
||||
"value": u.id,
|
||||
"description": u.department or None,
|
||||
}
|
||||
for u in users
|
||||
]
|
||||
|
||||
|
||||
def _users_options() -> list[dict[str, Any]]:
|
||||
"""启用中的用户列表(value=user.id),供排程通知人类参数选择。"""
|
||||
from app.models import User
|
||||
@@ -88,6 +103,7 @@ _OPTIONS_PROVIDERS: dict[str, Callable[[], list[dict[str, Any]]]] = {
|
||||
"agent_apps": _agent_apps_options,
|
||||
"shipping_inventory_sources": _shipping_inventory_sources_options,
|
||||
"shipping_receipt_sources": _shipping_receipt_sources_options,
|
||||
"hxops_users": _hxops_users_options,
|
||||
"users": _users_options,
|
||||
}
|
||||
|
||||
|
||||
@@ -162,6 +162,96 @@ def _register_builtin_platform_jobs() -> None:
|
||||
key="contract-payment-sync", label="合同付款 OA 同步", handler=run_contract_payment_sync_schedule,
|
||||
description="同步 OA 合同归档、验收归档和厂商预付款请款作业。", category="contract_payment",
|
||||
))
|
||||
from app.services.schedule.order_delivery_reply_job import run_order_delivery_sync_schedule
|
||||
from app.services.schedule.order_delivery_remind_job import (
|
||||
DEFAULT_SHIP_ADVANCE_DAYS,
|
||||
DEFAULT_SHIP_REMIND_ENABLED,
|
||||
DEFAULT_UNREPLIED_DAYS,
|
||||
DEFAULT_UNREPLIED_REMIND_ENABLED,
|
||||
run_order_delivery_remind_schedule,
|
||||
)
|
||||
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="order-delivery-sync", label="订单交期回复 ERP 同步", handler=run_order_delivery_sync_schedule,
|
||||
description=(
|
||||
"每天 07:00 全量同步已审核、已核准、未结案的 ERP 销售订单行快照;"
|
||||
"同步成功后按任务参数「同步完成提醒收件人」提醒生管查看回复(未配置时回退本任务通知人)。"
|
||||
),
|
||||
category="order_delivery_reply",
|
||||
params_schema=(
|
||||
{
|
||||
"key": "sync_remind_user_ids",
|
||||
"type": "multi_select",
|
||||
"label": "同步完成提醒收件人(生管)",
|
||||
"required": False,
|
||||
"default": [],
|
||||
"options_source": "hxops_users",
|
||||
"help": "同步完成提醒的生管收件人,可从全部启用用户中搜索选择;"
|
||||
"与本任务「通知人」(运行结果通知)互相独立;留空时回退通知人名单以兼容旧配置。",
|
||||
},
|
||||
),
|
||||
defaults={"sync_remind_user_ids": []},
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="order-delivery-remind", label="订单交期回复 提醒", handler=run_order_delivery_remind_schedule,
|
||||
description=(
|
||||
"每天扫描:已回复行按回复交期提前 N 天企微提醒对应业务员出货;"
|
||||
"超 N 天未回复的行再次企微提醒生管(收件人取任务参数「未回复提醒收件人」,"
|
||||
"未配置时回退本任务通知人)。两类提醒可通过任务参数独立启停。"
|
||||
),
|
||||
category="order_delivery_reply",
|
||||
params_schema=(
|
||||
{
|
||||
"key": "ship_remind_enabled",
|
||||
"type": "boolean",
|
||||
"label": "启用出货提醒",
|
||||
"required": False,
|
||||
"default": DEFAULT_SHIP_REMIND_ENABLED,
|
||||
"help": "关闭后不再按回复交期提前提醒业务员出货;未回复提醒不受影响。",
|
||||
},
|
||||
{
|
||||
"key": "ship_remind_advance_days",
|
||||
"type": "number",
|
||||
"label": "出货提醒提前天数",
|
||||
"required": False,
|
||||
"default": DEFAULT_SHIP_ADVANCE_DAYS,
|
||||
"help": "已回复订单的回复交期距今 ≤ 该天数时,企微提醒对应业务员安排出货。取值 0-3650。",
|
||||
},
|
||||
{
|
||||
"key": "unreplied_remind_enabled",
|
||||
"type": "boolean",
|
||||
"label": "启用未回复提醒",
|
||||
"required": False,
|
||||
"default": DEFAULT_UNREPLIED_REMIND_ENABLED,
|
||||
"help": "关闭后不再对超期未回复的订单行再次提醒生管;出货提醒不受影响。",
|
||||
},
|
||||
{
|
||||
"key": "unreplied_remind_days",
|
||||
"type": "number",
|
||||
"label": "未回复再次提醒天数",
|
||||
"required": False,
|
||||
"default": DEFAULT_UNREPLIED_DAYS,
|
||||
"help": "订单日期距今超过该天数仍未回复交期时再次提醒生管;同一行每达到该天数最多提醒一次。取值 0-3650。",
|
||||
},
|
||||
{
|
||||
"key": "unreplied_remind_user_ids",
|
||||
"type": "multi_select",
|
||||
"label": "未回复提醒收件人(生管)",
|
||||
"required": False,
|
||||
"default": [],
|
||||
"options_source": "hxops_users",
|
||||
"help": "超期未回复提醒的生管收件人,可从全部启用用户中搜索选择;"
|
||||
"与本任务「通知人」(运行结果通知)互相独立;留空时回退通知人名单以兼容旧配置。",
|
||||
},
|
||||
),
|
||||
defaults={
|
||||
"ship_remind_enabled": DEFAULT_SHIP_REMIND_ENABLED,
|
||||
"ship_remind_advance_days": DEFAULT_SHIP_ADVANCE_DAYS,
|
||||
"unreplied_remind_enabled": DEFAULT_UNREPLIED_REMIND_ENABLED,
|
||||
"unreplied_remind_days": DEFAULT_UNREPLIED_DAYS,
|
||||
"unreplied_remind_user_ids": [],
|
||||
},
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="lean-training-reminder", label="精益管理培训逾期提醒", handler=run_lean_training_reminder_schedule,
|
||||
description="周日截止后,于周一、周三、周五向未完成员工推送精益培训提醒。", category="training",
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
"""
|
||||
backend/app/services/schedule/order_delivery_remind_job.py
|
||||
|
||||
用途:将订单交期回复的每日提醒适配到平台排程(ScheduleTask platform_job,job key
|
||||
order-delivery-remind,默认日批 07:10 在同步之后执行)。
|
||||
依赖:services/order_delivery_reply/reminder_service(出货提醒 + 未回复再提醒)、
|
||||
ScheduleTask/ScheduleRun。
|
||||
逻辑:从 task.job_params 读取配置(管理端排程表单「任务参数」可改,均有默认值):
|
||||
ship_remind_enabled / unreplied_remind_enabled 布尔开关独立启停两类提醒;
|
||||
ship_remind_advance_days 默认 3、unreplied_remind_days 默认 3。
|
||||
未回复提醒收件人优先取 job_params 的 unreplied_remind_user_ids(管理端「未回复提醒收件人」
|
||||
多选参数,与平台运行结果通知的「通知人」互相独立);未配置时回退任务 notify_user_ids_json
|
||||
兼容旧配置。天数统一钳制在 0-3650,防止表单误填巨大值导致 today+timedelta 溢出
|
||||
(OverflowError: date value out of range,2026-09-22 出货提醒扫描事故根因)。
|
||||
两个扫描互相独立:单个扫描抛错回滚后继续另一个,最终把错误计入 errors
|
||||
(failed_count>0 时平台排程标 partial_failed/failed,不影响数据快照);
|
||||
开关关闭的一侧直接跳过(summary 记 skipped=disabled),不影响另一侧。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable
|
||||
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
|
||||
|
||||
# 配置键与默认值:与 job_registry 中 order-delivery-remind 的 params_schema 一致。
|
||||
SHIP_REMIND_ENABLED_KEY = "ship_remind_enabled"
|
||||
UNREPLIED_REMIND_ENABLED_KEY = "unreplied_remind_enabled"
|
||||
SHIP_REMIND_ADVANCE_DAYS_KEY = "ship_remind_advance_days"
|
||||
UNREPLIED_REMIND_DAYS_KEY = "unreplied_remind_days"
|
||||
DEFAULT_SHIP_REMIND_ENABLED = True
|
||||
DEFAULT_UNREPLIED_REMIND_ENABLED = True
|
||||
DEFAULT_UNREPLIED_USER_IDS_KEY = "unreplied_remind_user_ids"
|
||||
DEFAULT_SHIP_ADVANCE_DAYS = 3
|
||||
DEFAULT_UNREPLIED_DAYS = 3
|
||||
# 天数上限(约 10 年):date + timedelta 超过 9999 年会抛 OverflowError: date value out of range。
|
||||
MAX_REMIND_DAYS = 3650
|
||||
|
||||
|
||||
def _read_days(task: ScheduleTask, key: str, default: int) -> int:
|
||||
"""读取 job_params 中的天数配置;非法值回退默认,并钳制到 [0, MAX_REMIND_DAYS]。
|
||||
|
||||
上限原因:today + timedelta(days=N) 在 N 巨大时溢出抛
|
||||
OverflowError: date value out of range(2026-09-22 出货提醒扫描失败根因)。
|
||||
"""
|
||||
params = task.job_params if isinstance(task.job_params, dict) else {}
|
||||
try:
|
||||
value = int(params.get(key, default))
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
return min(max(value, 0), MAX_REMIND_DAYS)
|
||||
|
||||
|
||||
def _read_unreplied_recipients(task: ScheduleTask) -> list[int]:
|
||||
"""读取未回复提醒的生管收件人:优先任务参数多选名单,留空回退任务通知人(旧配置兼容)。"""
|
||||
params = task.job_params if isinstance(task.job_params, dict) else {}
|
||||
raw = params.get(DEFAULT_UNREPLIED_USER_IDS_KEY)
|
||||
ids = [int(uid) for uid in raw if uid] if isinstance(raw, list) else []
|
||||
if ids:
|
||||
return ids
|
||||
if task.notify_enabled:
|
||||
return [int(uid) for uid in (task.notify_user_ids_json or []) if uid]
|
||||
return []
|
||||
|
||||
|
||||
def _read_bool(task: ScheduleTask, key: str, default: bool) -> bool:
|
||||
"""读取 job_params 中的开关配置;非法值回退默认(参数类型已由契约层校验)。"""
|
||||
params = task.job_params if isinstance(task.job_params, dict) else {}
|
||||
value = params.get(key, default)
|
||||
return value if isinstance(value, bool) else default
|
||||
|
||||
|
||||
def _run_scan(errors: list[str], label: str, scan: Callable[[], dict[str, Any]]) -> dict[str, Any]:
|
||||
"""执行单个扫描:异常回滚后记入 errors(failed+1),不吞掉另一侧扫描。"""
|
||||
from app.extensions import db
|
||||
|
||||
try:
|
||||
return scan()
|
||||
except Exception as exc: # noqa: BLE001 — 扫描失败计入运行结果,由排程页展示
|
||||
db.session.rollback()
|
||||
errors.append(f"{label}扫描失败: {exc}")
|
||||
return {"error": str(exc)}
|
||||
|
||||
|
||||
def run_order_delivery_remind_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""
|
||||
执行每日提醒扫描:已回复行提前 N 天提醒业务员出货;超 N 天未回复行再次提醒生管。
|
||||
|
||||
两类提醒由 job_params 的布尔开关独立启停(ship_remind_enabled / unreplied_remind_enabled);
|
||||
关闭的一侧跳过并在 summary 标记 skipped=disabled,不影响另一侧。
|
||||
|
||||
Args:
|
||||
task: 当前排程任务定义(job_params 带天数/开关配置,notify_user_ids_json 带生管收件人)。
|
||||
run: 当前排程执行记录。
|
||||
Returns:
|
||||
通用排程审计七元组;total/success/failed 按两侧扫描的发送对象计数汇总。
|
||||
"""
|
||||
from app.services.order_delivery_reply.reminder_service import (
|
||||
run_ship_reminders,
|
||||
run_unreplied_reminders,
|
||||
)
|
||||
|
||||
ship_enabled = _read_bool(task, SHIP_REMIND_ENABLED_KEY, DEFAULT_SHIP_REMIND_ENABLED)
|
||||
unreplied_enabled = _read_bool(task, UNREPLIED_REMIND_ENABLED_KEY, DEFAULT_UNREPLIED_REMIND_ENABLED)
|
||||
advance_days = _read_days(task, SHIP_REMIND_ADVANCE_DAYS_KEY, DEFAULT_SHIP_ADVANCE_DAYS)
|
||||
unreplied_days = _read_days(task, UNREPLIED_REMIND_DAYS_KEY, DEFAULT_UNREPLIED_DAYS)
|
||||
|
||||
errors: list[str] = []
|
||||
if ship_enabled:
|
||||
ship_result = _run_scan(errors, "出货提醒", lambda: run_ship_reminders(advance_days))
|
||||
if ship_result.get("skipped_unmapped"):
|
||||
errors.append(
|
||||
f"出货提醒有 {ship_result['skipped_unmapped']} 名业务员工号未映射 HXOPS 企微用户,未送达"
|
||||
)
|
||||
else:
|
||||
ship_result = {"skipped": "disabled", "advance_days": advance_days}
|
||||
|
||||
unreplied_recipients = _read_unreplied_recipients(task)
|
||||
if unreplied_enabled:
|
||||
unreplied_result = _run_scan(errors, "未回复提醒", lambda: run_unreplied_reminders(unreplied_days, unreplied_recipients))
|
||||
if unreplied_result.get("skipped_no_recipient"):
|
||||
errors.append("存在超期未回复订单,但未配置「未回复提醒收件人」(且任务通知人未配置或开关关闭),未发送提醒")
|
||||
else:
|
||||
unreplied_result = {"skipped": "disabled", "unreplied_days": unreplied_days}
|
||||
|
||||
# 统计口径:出货提醒按业务员(人)、未回复提醒按收件人生管(人);扫描异常各计 1 笔失败。
|
||||
success = int(ship_result.get("notified_salespersons") or 0) + int(unreplied_result.get("notified_recipients") or 0)
|
||||
failed = (
|
||||
int(ship_result.get("failed_salespersons") or 0)
|
||||
+ int(unreplied_result.get("failed_recipients") or 0)
|
||||
+ sum(1 for result in (ship_result, unreplied_result) if result.get("error"))
|
||||
)
|
||||
skipped = int(ship_result.get("skipped_unmapped") or 0)
|
||||
total = success + failed + skipped
|
||||
|
||||
summary = {
|
||||
"ship_remind": ship_result,
|
||||
"unreplied_remind": unreplied_result,
|
||||
"ship_remind_enabled": ship_enabled,
|
||||
"unreplied_remind_enabled": unreplied_enabled,
|
||||
"advance_days": advance_days,
|
||||
"unreplied_days": unreplied_days,
|
||||
"unreplied_recipients": unreplied_recipients,
|
||||
}
|
||||
step_logs = [{"step": "order_delivery_remind", "status": "success" if failed == 0 else "partial", "detail": summary}]
|
||||
return (total, success, failed, skipped, [summary], errors, step_logs)
|
||||
@@ -0,0 +1,113 @@
|
||||
"""
|
||||
backend/app/services/schedule/order_delivery_reply_job.py
|
||||
|
||||
用途:将订单交期回复 ERP 全量同步适配到平台排程(ScheduleTask platform_job)。
|
||||
依赖:services/order_delivery_reply/sync_service(同步本体)、notify_service(企微事件类型与跳转路径)、
|
||||
wecom_notify.send_wecom_event_message、ScheduleTask/ScheduleRun。
|
||||
逻辑:排程 worker 每天 07:00(Asia/Shanghai)触发 handler,内部以 trigger='scheduled'
|
||||
复用与手动刷新完全相同的 run_sync;同步成功后按任务参数 sync_remind_user_ids
|
||||
(管理端「同步完成提醒收件人」多选,与运行结果通知的「通知人」互相独立;
|
||||
留空回退 notify_user_ids_json 兼容旧配置)给生管发提醒,
|
||||
并把 domain_notification_managed 写入 run 摘要,抑制通用「排程执行结果」通知避免重复;
|
||||
通知失败不改变同步结果(同步已成功落库,仅记录失败原因)。
|
||||
同步失败向上抛出,由平台排程标记本次运行失败并保留上次快照(sync_runs 已各自留痕)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.models import ScheduleRun, ScheduleTask, User
|
||||
|
||||
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
|
||||
|
||||
|
||||
SYNC_REMIND_USER_IDS_KEY = "sync_remind_user_ids"
|
||||
|
||||
|
||||
def _read_sync_remind_recipients(task: ScheduleTask) -> list[int]:
|
||||
"""同步完成提醒收件人:优先任务参数 sync_remind_user_ids,留空回退任务通知人(旧配置兼容)。"""
|
||||
params = task.job_params if isinstance(task.job_params, dict) else {}
|
||||
raw = params.get(SYNC_REMIND_USER_IDS_KEY)
|
||||
ids = [int(uid) for uid in raw if uid] if isinstance(raw, list) else []
|
||||
if ids:
|
||||
return ids
|
||||
if task.notify_enabled:
|
||||
return [int(uid) for uid in (task.notify_user_ids_json or []) if uid]
|
||||
return []
|
||||
|
||||
|
||||
def _notify_production_after_sync(task: ScheduleTask, line_count: int) -> list[dict[str, Any]]:
|
||||
"""
|
||||
同步成功后提醒生管查看订单交期回复(收件人 = 任务参数 sync_remind_user_ids,回退通知人)。
|
||||
|
||||
Args:
|
||||
task: 触发本次同步的排程任务。
|
||||
line_count: 本次同步的订单行数量,用于通知文案。
|
||||
Returns:
|
||||
逐人发送结果列表 [{user_id, ok, reason?}];未配置收件人时返回空列表。
|
||||
"""
|
||||
from app.services.order_delivery_reply.notify_service import (
|
||||
WECOM_EVENT_TYPE,
|
||||
JUMP_PATH,
|
||||
)
|
||||
from app.services.integrations.wecom.notify import send_wecom_event_message
|
||||
|
||||
user_ids = _read_sync_remind_recipients(task)
|
||||
if not user_ids:
|
||||
return []
|
||||
|
||||
users = User.query.filter(User.id.in_(user_ids)).all()
|
||||
results: list[dict[str, Any]] = []
|
||||
for user in users:
|
||||
result = send_wecom_event_message(
|
||||
event_type=WECOM_EVENT_TYPE,
|
||||
user=user,
|
||||
title="订单交期回复",
|
||||
content=f"今日订单交期数据已同步完成(共 {line_count} 行),请及时查看并回复交期。",
|
||||
jump_path=JUMP_PATH,
|
||||
# 卡片带 status=not_fully_replied:生管点开直达「未完全回复」视图(待回复行)。
|
||||
jump_params={"status": "not_fully_replied"},
|
||||
)
|
||||
entry: dict[str, Any] = {"user_id": user.id, "ok": bool(result.get("ok"))}
|
||||
if not entry["ok"]:
|
||||
entry["reason"] = result.get("reason")
|
||||
results.append(entry)
|
||||
return results
|
||||
|
||||
|
||||
def run_order_delivery_sync_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""
|
||||
执行订单交期回复 ERP 全量同步(已审核 + 已核准 + 未结案订单行)并提醒生管。
|
||||
|
||||
Args:
|
||||
task: 当前排程任务定义。
|
||||
run: 当前排程执行记录。
|
||||
Returns:
|
||||
通用排程审计七元组;同步异常原样抛出,交由平台排程记录失败运行。
|
||||
"""
|
||||
from app.extensions import db
|
||||
from app.services.order_delivery_reply.sync_service import OrderDeliverySyncService
|
||||
|
||||
summary = OrderDeliverySyncService.run_sync(trigger="scheduled")
|
||||
count = int(summary.get("line_count") or 0)
|
||||
|
||||
# [STEP 2] 域内已自行通知生管:写入标记,抑制通用「排程执行结果」企微通知避免双重打扰。
|
||||
# 直调(run=None,脚本/测试)时跳过 run 摘要写入。
|
||||
if run is not None:
|
||||
run.response_summary_json = {"domain_notification_managed": True}
|
||||
db.session.commit()
|
||||
|
||||
notify_results = _notify_production_after_sync(task, count)
|
||||
failed_notify = [item for item in notify_results if not item["ok"]]
|
||||
step_logs = [
|
||||
{
|
||||
"step": "order_delivery_sync",
|
||||
"status": "success",
|
||||
"detail": {**summary, "production_notify": notify_results},
|
||||
}
|
||||
]
|
||||
errors: list[str] = [
|
||||
f"生管通知发送失败 user_id={item['user_id']} reason={item.get('reason')}" for item in failed_notify
|
||||
]
|
||||
return (count, count, 0, 0, [summary], errors, step_logs)
|
||||
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
backend/app/services/schedule/web_scanner.py
|
||||
|
||||
用途:Web 进程内的排程扫描兜底线程——让开发环境(只跑 run.py,没有独立 schedule-worker
|
||||
容器)也能按 cron 触发到期排程(如订单交期回复每天 07:00 的 ERP 全量同步)。
|
||||
依赖:app.jobs.runner.run_forever、app.jobs.store.claim_next(schedule 队列)、JobContext。
|
||||
逻辑:create_app 启动时按 SCHEDULE_WEB_SCANNER_ENABLED 决定是否拉起守护线程;线程内
|
||||
推送 app context 后复用与 workers/worker_scheduler.py 完全相同的消费路径
|
||||
(claim_next('schedule') → prepare_schedule_queue 扫描到期任务 → handler 执行)。
|
||||
多进程并发安全由 enqueue_due_schedule_runs 的 FOR UPDATE SKIP LOCKED 与
|
||||
schedule_runs 活动 run 去重保证,与独立 worker 并存不会重复执行。
|
||||
生产环境默认关闭(compose 已有 hxops-schedule-worker 专职容器),可用环境变量覆盖。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
|
||||
_web_scanner_started = False
|
||||
_web_scanner_lock = threading.Lock()
|
||||
|
||||
|
||||
def start_web_schedule_scanner(app) -> None:
|
||||
"""
|
||||
按配置在 Web 进程内启动排程扫描守护线程(幂等;重复调用直接返回)。
|
||||
|
||||
用途与触发时机:create_app 启动阶段调用;AI/请求路径不触发。
|
||||
开发环境默认开启(SCHEDULE_WEB_SCANNER_ENABLED 缺省 true),
|
||||
生产环境默认关闭(缺省 false,由 hxops-schedule-worker 容器负责)。
|
||||
|
||||
核心逻辑:[STEP 1] 读 SCHEDULE_WEB_SCANNER_ENABLED,关闭则不打扰;
|
||||
[STEP 2] 进程内单例锁后起 daemon 线程,线程内推送 app context、
|
||||
导入 handlers、复用 run_forever(queues=['schedule']) 主循环。
|
||||
"""
|
||||
global _web_scanner_started
|
||||
|
||||
enabled = bool(app.config.get("SCHEDULE_WEB_SCANNER_ENABLED", False))
|
||||
if not enabled:
|
||||
app.logger.info("Web schedule scanner disabled by SCHEDULE_WEB_SCANNER_ENABLED=false")
|
||||
return
|
||||
|
||||
with _web_scanner_lock:
|
||||
if _web_scanner_started:
|
||||
return
|
||||
|
||||
def _loop(app_ref=app):
|
||||
with app_ref.app_context():
|
||||
import app.jobs.handlers # noqa: F401 — 触发 @register_handler
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.runner import run_forever
|
||||
|
||||
ctx = JobContext(
|
||||
config=dict(app_ref.config),
|
||||
logger=app_ref.logger,
|
||||
extras={"queues": ["schedule"]},
|
||||
)
|
||||
app_ref.logger.info("Web schedule scanner starting (queues=['schedule'])")
|
||||
run_forever(ctx)
|
||||
|
||||
thread = threading.Thread(target=_loop, name="web-schedule-scanner", daemon=True)
|
||||
thread.start()
|
||||
_web_scanner_started = True
|
||||
app.logger.info("Web schedule scanner started")
|
||||
@@ -0,0 +1,24 @@
|
||||
"""merge order-delivery-reply and dev heads
|
||||
|
||||
Revision ID: 959afe816337
|
||||
Revises: a7c1d2e3f4b9, rc2b3c4d5e6f
|
||||
Create Date: 2026-09-22 09:21:43.949845
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '959afe816337'
|
||||
down_revision = ('a7c1d2e3f4b9', 'rc2b3c4d5e6f')
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
pass
|
||||
|
||||
|
||||
def downgrade():
|
||||
pass
|
||||
@@ -0,0 +1,24 @@
|
||||
"""merge migration heads after dev auto-transfer merge
|
||||
|
||||
Revision ID: 9e5045511198
|
||||
Revises: b8baf0905ec6, t5a6b7c8d9e0f
|
||||
Create Date: 2026-09-30 08:38:49.231759
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '9e5045511198'
|
||||
down_revision = ('b8baf0905ec6', 't5a6b7c8d9e0f')
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
pass
|
||||
|
||||
|
||||
def downgrade():
|
||||
pass
|
||||
@@ -0,0 +1,155 @@
|
||||
"""add order delivery reply tables
|
||||
|
||||
Revision ID: a7c1d2e3f4b9
|
||||
Revises: 353ebb6187ce
|
||||
Create Date: 2026-09-16
|
||||
|
||||
用途:订单交期回复一期建表迁移,对应模型 app/models/order_delivery_reply.py。
|
||||
依赖:users 表(批次/状态/审计的操作人与通知人外键);基线 353ebb6187ce(多分支 merge head)。
|
||||
逻辑:up 建五张本地表(ERP 行快照 / 交期批次 / 行级锁定 / 审计 / 同步运行);
|
||||
down 逆序整域回滚。手写原因:autogenerate 被既有 shipping 超长索引名问题阻断,与本域无关。
|
||||
红线:改列/改表必须出新迁移,禁止改动本文件已上线的 upgrade/downgrade。
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = 'a7c1d2e3f4b9'
|
||||
down_revision = '353ebb6187ce'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
"""
|
||||
建表:五张表按依赖顺序创建(快照表先行,其余三表以 line_id 外键挂靠)。
|
||||
|
||||
写边界约定(与模型层一致,供后续迁移审查对照):
|
||||
- erp_lines 仅同步服务写 ERP 快照列;batches 仅保存回复路径写;
|
||||
line_states.locked 仅通知成功事务写;audit_events / sync_runs 各自路径留痕。
|
||||
- slip_code 一期只落库预留(单别白名单后期启用),列表不出该列。
|
||||
- erp_missing 默认 false;本轮同步未命中的行由同步服务置 true,不物理删除。
|
||||
"""
|
||||
# ERP 订单行快照:唯一键 (order_no, line_no);(order_no, line_no) 上的业务行均由此表派生。
|
||||
op.create_table(
|
||||
'order_delivery_erp_lines',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('order_no', sa.String(length=64), nullable=False),
|
||||
sa.Column('line_no', sa.Integer(), nullable=False),
|
||||
sa.Column('order_date', sa.Date(), nullable=True),
|
||||
sa.Column('customer_no', sa.String(length=64), nullable=True),
|
||||
sa.Column('customer_short_name', sa.String(length=255), nullable=True),
|
||||
sa.Column('customer_full_name', sa.String(length=255), nullable=True),
|
||||
sa.Column('salesperson_code', sa.String(length=64), nullable=True),
|
||||
sa.Column('salesperson_name', sa.String(length=255), nullable=True),
|
||||
sa.Column('dept_code', sa.String(length=64), nullable=True),
|
||||
sa.Column('dept_name', sa.String(length=255), nullable=True),
|
||||
sa.Column('customer_po', sa.String(length=128), nullable=True),
|
||||
sa.Column('part_no', sa.String(length=128), nullable=True),
|
||||
sa.Column('part_name', sa.String(length=512), nullable=True),
|
||||
sa.Column('spec', sa.String(length=512), nullable=True),
|
||||
sa.Column('customer_part_no', sa.String(length=128), nullable=True),
|
||||
sa.Column('agreed_date', sa.Date(), nullable=True),
|
||||
sa.Column('unit', sa.String(length=32), nullable=True),
|
||||
sa.Column('qty', sa.Numeric(18, 4), nullable=True),
|
||||
sa.Column('delivered_qty', sa.Numeric(18, 4), nullable=True),
|
||||
sa.Column('slip_code', sa.String(length=32), nullable=True),
|
||||
sa.Column('erp_missing', sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||
sa.Column('last_synced_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('order_no', 'line_no', name='uq_order_delivery_erp_lines_order_line'),
|
||||
)
|
||||
op.create_index('ix_order_delivery_erp_lines_order_date', 'order_delivery_erp_lines', ['order_date'])
|
||||
op.create_index('ix_order_delivery_erp_lines_customer_no', 'order_delivery_erp_lines', ['customer_no'])
|
||||
op.create_index('ix_order_delivery_erp_lines_salesperson', 'order_delivery_erp_lines', ['salesperson_code'])
|
||||
op.create_index('ix_order_delivery_erp_lines_slip_code', 'order_delivery_erp_lines', ['slip_code'])
|
||||
op.create_index('ix_order_delivery_erp_lines_erp_missing', 'order_delivery_erp_lines', ['erp_missing'])
|
||||
|
||||
# 交期批次:未锁定行保存时整表替换(line_id + seq 唯一);remark ≤200 由 API 层校验,库层只限长。
|
||||
op.create_table(
|
||||
'order_delivery_batches',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('line_id', sa.Integer(), nullable=False),
|
||||
sa.Column('seq', sa.Integer(), nullable=False),
|
||||
sa.Column('planned_date', sa.Date(), nullable=False),
|
||||
sa.Column('qty', sa.Numeric(18, 4), nullable=False),
|
||||
sa.Column('remark', sa.String(length=200), nullable=True),
|
||||
sa.Column('created_by', sa.Integer(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['line_id'], ['order_delivery_erp_lines.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['created_by'], ['users.id']),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('line_id', 'seq', name='uq_order_delivery_batches_line_seq'),
|
||||
)
|
||||
op.create_index('ix_order_delivery_batches_line', 'order_delivery_batches', ['line_id'])
|
||||
|
||||
# 行级锁定状态:一行一态(line_id 唯一);locked 只在「企微通知成功」同一事务内置 true,
|
||||
# 快照字段存最近一次通知成功的生管工号/姓名,满足 R-NOTIFY-03 审计回溯。
|
||||
op.create_table(
|
||||
'order_delivery_line_states',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('line_id', sa.Integer(), nullable=False),
|
||||
sa.Column('locked', sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||
sa.Column('notified_user_id', sa.Integer(), nullable=True),
|
||||
sa.Column('notified_employee_id', sa.String(length=64), nullable=True),
|
||||
sa.Column('notified_user_name', sa.String(length=255), nullable=True),
|
||||
sa.Column('notified_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['line_id'], ['order_delivery_erp_lines.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['notified_user_id'], ['users.id']),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('line_id', name='uq_order_delivery_line_states_line'),
|
||||
)
|
||||
|
||||
# 审计:action ∈ save | notify | lock | sync;sync 类事件无具体行,line_id/order_no 允许为空。
|
||||
op.create_table(
|
||||
'order_delivery_audit_events',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('line_id', sa.Integer(), nullable=True),
|
||||
sa.Column('order_no', sa.String(length=64), nullable=True),
|
||||
sa.Column('line_no', sa.Integer(), nullable=True),
|
||||
sa.Column('action', sa.String(length=32), nullable=False),
|
||||
sa.Column('operator_user_id', sa.Integer(), nullable=True),
|
||||
sa.Column('payload_json', sa.JSON(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['line_id'], ['order_delivery_erp_lines.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['operator_user_id'], ['users.id']),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
)
|
||||
op.create_index('ix_order_delivery_audit_events_line', 'order_delivery_audit_events', ['line_id'])
|
||||
op.create_index('ix_order_delivery_audit_events_action', 'order_delivery_audit_events', ['action', 'created_at'])
|
||||
|
||||
# 同步运行记录:每次 07:00 排程或手动刷新各写一行;失败保留上次快照,仅状态置 failed 留痕。
|
||||
op.create_table(
|
||||
'order_delivery_sync_runs',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('trigger', sa.String(length=16), nullable=False),
|
||||
sa.Column('status', sa.String(length=16), nullable=False),
|
||||
sa.Column('started_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('finished_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('line_count', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.Column('error_message', sa.Text(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
)
|
||||
op.create_index('ix_order_delivery_sync_runs_started', 'order_delivery_sync_runs', ['started_at'])
|
||||
|
||||
|
||||
def downgrade():
|
||||
"""逆序回滚:先删挂靠表(索引随表,但显式 drop index 与 upgrade 对称),最后删快照主表。"""
|
||||
op.drop_index('ix_order_delivery_sync_runs_started', table_name='order_delivery_sync_runs')
|
||||
op.drop_table('order_delivery_sync_runs')
|
||||
op.drop_index('ix_order_delivery_audit_events_action', table_name='order_delivery_audit_events')
|
||||
op.drop_index('ix_order_delivery_audit_events_line', table_name='order_delivery_audit_events')
|
||||
op.drop_table('order_delivery_audit_events')
|
||||
op.drop_table('order_delivery_line_states')
|
||||
op.drop_index('ix_order_delivery_batches_line', table_name='order_delivery_batches')
|
||||
op.drop_table('order_delivery_batches')
|
||||
op.drop_index('ix_order_delivery_erp_lines_erp_missing', table_name='order_delivery_erp_lines')
|
||||
op.drop_index('ix_order_delivery_erp_lines_slip_code', table_name='order_delivery_erp_lines')
|
||||
op.drop_index('ix_order_delivery_erp_lines_salesperson', table_name='order_delivery_erp_lines')
|
||||
op.drop_index('ix_order_delivery_erp_lines_customer_no', table_name='order_delivery_erp_lines')
|
||||
op.drop_index('ix_order_delivery_erp_lines_order_date', table_name='order_delivery_erp_lines')
|
||||
op.drop_table('order_delivery_erp_lines')
|
||||
@@ -0,0 +1,24 @@
|
||||
"""merge migration heads after dev role merge
|
||||
|
||||
Revision ID: b8baf0905ec6
|
||||
Revises: d0304d47d364, mh3b4c5d6e7f
|
||||
Create Date: 2026-09-29 15:32:31.593063
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'b8baf0905ec6'
|
||||
down_revision = ('d0304d47d364', 'mh3b4c5d6e7f')
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
pass
|
||||
|
||||
|
||||
def downgrade():
|
||||
pass
|
||||
@@ -0,0 +1,24 @@
|
||||
"""merge migration heads after dev merge
|
||||
|
||||
Revision ID: d0304d47d364
|
||||
Revises: 6d7b0d04ac25, d425edfa336c, p1b2c3d4e5f6
|
||||
Create Date: 2026-09-29 14:39:03.805744
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'd0304d47d364'
|
||||
down_revision = ('6d7b0d04ac25', 'd425edfa336c', 'p1b2c3d4e5f6')
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
pass
|
||||
|
||||
|
||||
def downgrade():
|
||||
pass
|
||||
@@ -0,0 +1,24 @@
|
||||
"""merge migration heads
|
||||
|
||||
Revision ID: d425edfa336c
|
||||
Revises: 43a8179cdd88, 959afe816337
|
||||
Create Date: 2026-09-23 11:59:11.702696
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'd425edfa336c'
|
||||
down_revision = ('43a8179cdd88', '959afe816337')
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
pass
|
||||
|
||||
|
||||
def downgrade():
|
||||
pass
|
||||
@@ -0,0 +1,72 @@
|
||||
"""
|
||||
scripts/order_delivery_query.py
|
||||
|
||||
Purpose: 订单交期回复(order-delivery-reply)功能的 ERP 取数查询原型——按目标展示顺序关联
|
||||
订单头/身/料件/客户/员工/部门,过滤已审核、已核准、未结案订单行。
|
||||
Dependencies: python-oracledb;连接约定与 services/text2sql.py 一致(ERP_DB_DSN,默认 192.168.8.24:1521/topprod)。
|
||||
Flow: 本脚本可独立运行验证 SQL 与数据;后续 order-delivery-reply 后端服务应引用
|
||||
ORDER_DELIVERY_SQL 常量(或迁移为 service 方法),保持口径一致。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# [STEP 1] 让脚本可独立运行:把 backend/ 加入 sys.path 后复用服务包中的权威 SQL 常量。
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from app.services.order_delivery_reply.sql import ORDER_DELIVERY_SQL # noqa: E402
|
||||
|
||||
# 订单交期查询列的中文展示名,顺序与服务层 ORDER_DELIVERY_SQL 别名一一对应(仅本脚本预览使用)。
|
||||
COLUMN_LABELS = [
|
||||
"订单单号", "项次", "订单日期", "客户编号", "客户简称", "公司全名",
|
||||
"业务员工号", "业务员", "部门编码", "部门", "客户订单",
|
||||
"产品编号", "品名", "规格", "客户产品编号", "约定交货日", "单位", "数量", "已交数量",
|
||||
]
|
||||
|
||||
# 预览用 SQL:按目标展示顺序排序。业务约束:仅做只读 SELECT,禁止改写为 INSERT/UPDATE/DELETE。
|
||||
PREVIEW_SQL = f"{ORDER_DELIVERY_SQL} ORDER BY a.oea02, a.oea03, a.oea01, b.oeb03"
|
||||
|
||||
|
||||
def fetch_order_delivery(limit=None):
|
||||
"""
|
||||
执行订单交期查询并返回列名与数据行。
|
||||
|
||||
用途与触发时机:验证/预览订单交期明细;联调 order-delivery-reply 功能时用于人工核对 ERP 数据。
|
||||
|
||||
核心逻辑:[STEP 1] 读取 ERP_DB_USER / ERP_DB_PASSWORD / ERP_DB_DSN 连接 topprod;
|
||||
[STEP 2] 执行 PREVIEW_SQL(可选 ROWNUM 限行预览),SQL 本体复用服务包权威常量;
|
||||
[STEP 3] 返回 (columns, rows);连接或执行异常原样抛出。
|
||||
|
||||
参数与输出约束:limit 为可选最大行数(业务约束:仅限人工预览使用,禁止在正式服务链路传 None 全量拉取);
|
||||
返回 (list[str], list[tuple]),列名为目标展示顺序的中文字段名(COLUMN_LABELS)。
|
||||
"""
|
||||
import oracledb
|
||||
|
||||
# 凭据回退链与服务层 sync_service._connect 一致:专用键 → 合同付款预警的共享配置。
|
||||
user = os.getenv("ERP_DB_USER") or os.getenv("CONTRACT_PAYMENT_ERP_USERNAME", "EXT_VIEW_USER")
|
||||
password = os.getenv("ERP_DB_PASSWORD") or os.getenv("CONTRACT_PAYMENT_ERP_PASSWORD")
|
||||
dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod")
|
||||
if not password:
|
||||
raise RuntimeError(
|
||||
"ERP 口令未配置:请设置 ERP_DB_PASSWORD,或复用 .env.shared 的 "
|
||||
"CONTRACT_PAYMENT_ERP_PASSWORD(与合同付款预警同一 topprod 连接)"
|
||||
)
|
||||
|
||||
sql = PREVIEW_SQL
|
||||
if limit:
|
||||
sql = f"SELECT * FROM ({sql}) WHERE ROWNUM <= {int(limit)}"
|
||||
|
||||
with oracledb.connect(user=user, password=password, dsn=dsn) as conn:
|
||||
with conn.cursor() as cursor:
|
||||
cursor.execute(sql)
|
||||
rows = cursor.fetchall()
|
||||
# 列名以常量映射为权威,不依赖 DB 返回的英文别名。
|
||||
return list(COLUMN_LABELS), rows
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
cols, data = fetch_order_delivery(limit=50)
|
||||
print(" | ".join(cols))
|
||||
for row in data:
|
||||
print(" | ".join("" if v is None else str(v) for v in row))
|
||||
print(f"-- 共 {len(data)} 行")
|
||||
@@ -2,11 +2,11 @@
|
||||
tests/services/admin/test_dashboard_service.py
|
||||
|
||||
用途:dashboard_service 统计聚合单元测试。
|
||||
说明:侧栏角标(pending_approvals / pending_requests)已随用户审批功能下线一并删除
|
||||
(dev commit 07e83132「删除用户审批功能」),2026-09-29 删除对应失效用例,
|
||||
legacy 统计断言对齐现役四键(total_users / active_agents / total_conversations / avg_score)。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import Agent, ChatLog, Feedback, PermissionRequest, User
|
||||
from app.services.admin.dashboard_service import (
|
||||
compute_dashboard_badges,
|
||||
compute_dashboard_summary,
|
||||
compute_legacy_dashboard_stats,
|
||||
)
|
||||
@@ -21,24 +21,10 @@ def test_compute_dashboard_summary_empty(app):
|
||||
assert summary['avg_score'] == 0.0
|
||||
|
||||
|
||||
def test_compute_dashboard_badges_counts_pending(app):
|
||||
with app.app_context():
|
||||
user = User(username='pending-u', email='p@example.com', status='pending', role='user')
|
||||
agent = Agent(name='a1', is_active=True)
|
||||
db.session.add_all([user, agent])
|
||||
db.session.flush()
|
||||
req = PermissionRequest(user_id=user.id, agent_id=agent.id, status='pending', reason='test')
|
||||
db.session.add(req)
|
||||
db.session.commit()
|
||||
|
||||
badges = compute_dashboard_badges()
|
||||
assert badges['pending_approvals'] >= 1
|
||||
assert badges['pending_requests'] >= 1
|
||||
|
||||
|
||||
def test_compute_legacy_dashboard_stats_keys(app):
|
||||
with app.app_context():
|
||||
stats = compute_legacy_dashboard_stats()
|
||||
assert 'total_users' in stats
|
||||
assert 'pending_approvals' in stats
|
||||
assert 'pending_requests' in stats
|
||||
assert 'active_agents' in stats
|
||||
assert 'total_conversations' in stats
|
||||
assert 'avg_score' in stats
|
||||
@@ -1,13 +1,15 @@
|
||||
"""
|
||||
tests/services/admin/test_permission_service.py
|
||||
|
||||
用途:permission_service 批量授权与权限申请审批单元测试。
|
||||
用途:permission_service 批量授权单元测试。
|
||||
说明:权限申请审批后端已随 dev 重构整体下线(approve_permission_request/list_permission_requests
|
||||
已删除,PermissionRequest 仅保留删 Agent/用户时的级联清理),2026-09-29 删除对应失效用例。
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ForbiddenError, NotFoundError, ValidationError
|
||||
from app.models import Agent, PermissionRequest, User
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import Agent, User
|
||||
from app.services.admin import permission_service
|
||||
|
||||
|
||||
@@ -48,32 +50,3 @@ def test_batch_update_permissions_no_users(app):
|
||||
with app.app_context():
|
||||
with pytest.raises(ValidationError):
|
||||
permission_service.batch_update_permissions({'user_ids': [], 'agent_ids': [1]})
|
||||
|
||||
|
||||
def test_permission_request_approve(app, monkeypatch):
|
||||
with app.app_context():
|
||||
agent = Agent(name='req-agent', type='api', dify_app_id='app-r', dify_api_key='key-r')
|
||||
user = User(username='req-user', email='req@example.com', role='user')
|
||||
db.session.add_all([agent, user])
|
||||
db.session.flush()
|
||||
req = PermissionRequest(user_id=user.id, agent_id=agent.id, reason='need access', status='pending')
|
||||
db.session.add(req)
|
||||
db.session.commit()
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.admin.permission_service.send_wecom_event_message',
|
||||
lambda **kwargs: None,
|
||||
)
|
||||
|
||||
permission_service.approve_permission_request(req.id)
|
||||
db.session.refresh(req)
|
||||
db.session.refresh(user)
|
||||
assert req.status == 'approved'
|
||||
assert req.reviewed_at is not None
|
||||
assert agent in user.agents
|
||||
|
||||
|
||||
def test_permission_request_not_found(app):
|
||||
with app.app_context():
|
||||
with pytest.raises(NotFoundError):
|
||||
permission_service.approve_permission_request(999999)
|
||||
@@ -109,8 +109,7 @@ def test_build_feedback_report(app):
|
||||
|
||||
|
||||
def test_build_application_report(app):
|
||||
"""应用运营报表应聚合对话 / 授权 / 待审 / 评分,且不含配置敏感字段。"""
|
||||
from app.models import PermissionRequest
|
||||
"""应用运营报表应聚合对话 / 授权 / 评分,且不含配置敏感字段。"""
|
||||
from app.models.base import user_agent_permissions
|
||||
|
||||
with app.app_context():
|
||||
@@ -126,8 +125,9 @@ def test_build_application_report(app):
|
||||
db.session.execute(
|
||||
user_agent_permissions.insert().values(user_id=user.id, agent_id=hot.id)
|
||||
)
|
||||
db.session.add(
|
||||
PermissionRequest(user_id=user.id, agent_id=cold.id, reason='need', status='pending')
|
||||
# cold-app 授权但零对话:验证「授权闲置」标记(原 pending_requests 断言已随审批功能下线删除)
|
||||
db.session.execute(
|
||||
user_agent_permissions.insert().values(user_id=user.id, agent_id=cold.id)
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
@@ -136,7 +136,6 @@ def test_build_application_report(app):
|
||||
assert data['summary']['agent_total'] >= 2
|
||||
assert data['summary']['used_agents'] >= 1
|
||||
assert data['summary']['unused_agents'] >= 1
|
||||
assert data['summary']['pending_permission_total'] >= 1
|
||||
|
||||
by_name = {item['name']: item for item in data['items']}
|
||||
assert 'hot-app' in by_name
|
||||
@@ -145,7 +144,8 @@ def test_build_application_report(app):
|
||||
assert by_name['hot-app']['authorized_users'] == 1
|
||||
assert by_name['hot-app']['avg_score'] == 4.0
|
||||
assert by_name['cold-app']['chat_count'] == 0
|
||||
assert by_name['cold-app']['pending_requests'] == 1
|
||||
# 断言:已授权但零对话的应用标记为授权闲置(pending_requests 断言已随审批功能下线删除)
|
||||
assert by_name['cold-app']['authorized_unused'] is True
|
||||
# 断言:导出字段不含 API Key
|
||||
assert 'dify_api_key' not in by_name['hot-app']
|
||||
assert 'api_base_url' not in by_name['hot-app']
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,51 @@
|
||||
"""
|
||||
tests/services/permission_roles/test_catalog.py
|
||||
|
||||
用途:角色包能力目录与订单交期回复权限键的回归测试。
|
||||
依赖:conftest 的 app 夹具(testing + sqlite create_all)、permission_roles catalog/service。
|
||||
逻辑:[防回归] KNOWN_FEATURE_KEYS / FEATURE_CATALOG / User 旧默认值三处必须都包含
|
||||
order_delivery_reply.manage|access——角色包启用后 effective_feature_permissions
|
||||
只输出 KNOWN_FEATURE_KEYS 内的键,catalog 漏登记会导致该功能权限全员失效
|
||||
(2026-09-29 合并 dev 角色包时发现并登记)。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import PermissionRole, User
|
||||
from app.services.permission_roles.catalog import FEATURE_CATALOG, KNOWN_FEATURE_KEYS
|
||||
from app.services.permission_roles.service import effective_feature_permissions, roles_configured
|
||||
|
||||
ODR_KEYS = {'order_delivery_reply.manage', 'order_delivery_reply.access'}
|
||||
|
||||
|
||||
def test_catalog_covers_order_delivery_reply_keys():
|
||||
"""catalog 双登记(KNOWN_FEATURE_KEYS + FEATURE_CATALOG)不漂移,且包含订单交期回复两键。"""
|
||||
assert ODR_KEYS <= set(KNOWN_FEATURE_KEYS)
|
||||
catalog_keys = {entry['key'] for entry in FEATURE_CATALOG}
|
||||
assert ODR_KEYS <= catalog_keys
|
||||
# 断言:两处键集合一致,防止只改一处导致角色包展示与实际输出不一致
|
||||
assert set(KNOWN_FEATURE_KEYS) == catalog_keys
|
||||
|
||||
|
||||
def test_effective_permissions_include_odr_keys_when_packaged(app):
|
||||
"""角色包启用后:平台管理包隐式全开含 odr 两键;非管理员包按勾选精确输出。"""
|
||||
with app.app_context():
|
||||
admin_role = PermissionRole(
|
||||
code='admin', name='管理员', is_platform_admin=True, is_system=True,
|
||||
)
|
||||
manager_role = PermissionRole(
|
||||
code='production', name='生管',
|
||||
feature_permissions={'order_delivery_reply.manage': True},
|
||||
)
|
||||
admin_user = User(username='odr-admin', email='odr-a@example.com', role='admin')
|
||||
manager_user = User(username='odr-manager', email='odr-m@example.com', role='production')
|
||||
db.session.add_all([admin_role, manager_role, admin_user, manager_user])
|
||||
db.session.commit()
|
||||
|
||||
assert roles_configured() is True
|
||||
admin_perms = effective_feature_permissions(admin_user)
|
||||
# 断言:平台管理包隐式全开 KNOWN_FEATURE_KEYS,订单交期回复两键为 True
|
||||
assert ODR_KEYS <= {key for key, value in admin_perms.items() if value}
|
||||
|
||||
manager_perms = effective_feature_permissions(manager_user)
|
||||
# 断言:非管理员包只开勾选键——manage=True,access 未勾=False(两键独立授予)
|
||||
assert manager_perms['order_delivery_reply.manage'] is True
|
||||
assert manager_perms['order_delivery_reply.access'] is False
|
||||
@@ -0,0 +1,555 @@
|
||||
"""
|
||||
backend/tests/test_lean_training_push.py
|
||||
|
||||
用途:覆盖精益管理培训"推过的视频绝不重复推"的跨任务推送契约与企微提醒催办规则。
|
||||
依赖:pytest、Flask test client、LeanTrainingWeeklyTask/TrainingConfig/AgentGuide 模型、lean_training_* 服务。
|
||||
逻辑:验证 HR 手动新建下一期周任务必须继承上一期推送游标(不从 0 重推首批),
|
||||
且推送分批时跳过其它任务已推送的视频,自动从上一任务断点继续向后推进直至全部推完;
|
||||
逾期/延期提醒文案携带期次标签(第N期+周次区间)供员工区分期次,多期过期任务对同一员工
|
||||
合并为一条汇总提醒且每人每天最多一条自动催办(排程扫描/推送后延期双路径当天去重),
|
||||
历史期任务过截止超过 100 天宽限期后停止催办。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytest
|
||||
from flask import current_app
|
||||
from sqlalchemy import select
|
||||
|
||||
from app import db
|
||||
from app.api import training as training_api
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import Agent, AgentGuide, LeanTrainingWeeklyTask, TrainingConfig, TrainingConfigResource, User
|
||||
from app.services import lean_training_push_service, lean_training_reminder_service, lean_training_service
|
||||
|
||||
|
||||
def _create_hr_user(*, username: str) -> User:
|
||||
"""创建具备培训管理权限的用户,兼作受训对象(role=user)。"""
|
||||
user = User(
|
||||
username=username,
|
||||
email=f"{username}@example.com",
|
||||
role="user",
|
||||
status="active",
|
||||
real_name=f"{username}-实名",
|
||||
employee_id=f"{username.upper()}-EMP",
|
||||
department="生产一部",
|
||||
)
|
||||
user.set_feature_permissions({"training_hr_manage": True})
|
||||
user.set_password("password123")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
db.session.expunge(user)
|
||||
return user
|
||||
|
||||
|
||||
def _create_lean_video_config(*, video_count: int) -> tuple[int, list[int]]:
|
||||
"""
|
||||
创建已发布精益培训配置并挂 video_count 个视频资源。
|
||||
|
||||
Returns:
|
||||
(config_id, desc_resource_ids):desc_resource_ids 为按上传时间倒序的自动填充顺序(新视频在前)。
|
||||
"""
|
||||
agent = Agent(name="lean_video_agent", type="api")
|
||||
db.session.add(agent)
|
||||
db.session.flush()
|
||||
config = TrainingConfig(training_type="lean_management", name="精益管理培训", version="v1", status="published")
|
||||
db.session.add(config)
|
||||
db.session.flush()
|
||||
asc_ids: list[int] = []
|
||||
base = datetime.utcnow() - timedelta(days=30)
|
||||
for index in range(video_count):
|
||||
guide = AgentGuide(
|
||||
agent_id=agent.id,
|
||||
file_name=f"lean-video-{index}.mp4",
|
||||
file_type="video",
|
||||
file_path=f"lean/video-{index}.mp4",
|
||||
created_at=base + timedelta(days=index),
|
||||
)
|
||||
db.session.add(guide)
|
||||
db.session.flush()
|
||||
resource = TrainingConfigResource(
|
||||
config_id=config.id,
|
||||
resource_type="agent_guide",
|
||||
training_level="company",
|
||||
agent_guide_id=guide.id,
|
||||
title=f"精益视频{index + 1}",
|
||||
created_at=base + timedelta(days=index),
|
||||
)
|
||||
db.session.add(resource)
|
||||
db.session.flush()
|
||||
asc_ids.append(resource.id)
|
||||
db.session.commit()
|
||||
return config.id, list(reversed(asc_ids))
|
||||
|
||||
|
||||
def _create_last_week_task(*, config_id: int, video_resource_ids: list[int], pushed_video_count: int) -> None:
|
||||
"""直接落库一期"上一周"已发布任务,冻结视频列表并写入指定推送游标。"""
|
||||
week_start, due_at = lean_training_service._current_week_bounds()
|
||||
db.session.add(LeanTrainingWeeklyTask(
|
||||
config_id=config_id,
|
||||
week_key=(week_start - timedelta(days=7)).isoformat(),
|
||||
due_at=due_at - timedelta(days=7),
|
||||
video_resource_ids=video_resource_ids,
|
||||
weekly_count=1,
|
||||
pushed_video_count=pushed_video_count,
|
||||
target_roles=["user"],
|
||||
target_user_ids=[],
|
||||
status="published",
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _create_published_task(
|
||||
*,
|
||||
config_id: int,
|
||||
video_resource_ids: list[int],
|
||||
week_key: str,
|
||||
due_utc: datetime,
|
||||
target_user_ids: list[int],
|
||||
) -> LeanTrainingWeeklyTask:
|
||||
"""
|
||||
落库一期指定周次的已发布任务(提醒文案/停止催办测试用),冻结列表并整体置为已推送。
|
||||
|
||||
Args:
|
||||
week_key: 该周周一的 ISO 日期文本(固定日期保证期号与 weekday 断言确定)。
|
||||
due_utc: 截止时间(UTC naive,如北京周日 23:59:59 对应 UTC 15:59:59)。
|
||||
target_user_ids: 显式受训对象(不经角色匹配,避免误圈其它测试用户)。
|
||||
"""
|
||||
task = LeanTrainingWeeklyTask(
|
||||
config_id=config_id,
|
||||
week_key=week_key,
|
||||
due_at=due_utc,
|
||||
video_resource_ids=video_resource_ids,
|
||||
weekly_count=1,
|
||||
pushed_video_count=len(video_resource_ids),
|
||||
target_roles=[],
|
||||
target_user_ids=target_user_ids,
|
||||
status="published",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
return task
|
||||
|
||||
|
||||
def _auth_headers(user: User) -> dict[str, str]:
|
||||
"""生成管理端接口测试鉴权头,显式携带 user_id 以稳定命中 legacy 用户解析。"""
|
||||
return {"X-User-Id": str(user.id), "X-Username": user.username, "Content-Type": "application/json"}
|
||||
|
||||
|
||||
def test_manual_new_week_task_inherits_cursor_and_skips_auto_push(client, app, monkeypatch):
|
||||
"""关键断言:上一期视频全部推送后,手动新建下一期必须继承游标——不自动重推首批、不重复发企微。"""
|
||||
push_messages: list[dict] = []
|
||||
initial_messages: list[dict] = []
|
||||
monkeypatch.setattr(
|
||||
lean_training_push_service,
|
||||
"_send_reminder",
|
||||
lambda **kwargs: push_messages.append(kwargs) or "sent",
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
lean_training_reminder_service,
|
||||
"_send_reminder",
|
||||
lambda **kwargs: initial_messages.append(kwargs) or "sent",
|
||||
)
|
||||
with app.app_context():
|
||||
hr = _create_hr_user(username="lean_hr_inherit")
|
||||
config_id, desc_ids = _create_lean_video_config(video_count=2)
|
||||
# [STEP] 上一期已按自动填充顺序把 2 个视频全部推完(游标=2)
|
||||
_create_last_week_task(config_id=config_id, video_resource_ids=list(desc_ids), pushed_video_count=2)
|
||||
week_start, _ = lean_training_service._current_week_bounds()
|
||||
|
||||
response = client.post("/api/admin/lean-training/weekly-tasks", headers=_auth_headers(hr), json={
|
||||
"week_key": week_start.isoformat(),
|
||||
"video_resource_ids": [],
|
||||
"target_roles": ["user"],
|
||||
"target_user_ids": [],
|
||||
"weekly_count": 1,
|
||||
})
|
||||
|
||||
assert response.status_code == 201
|
||||
body = response.get_json()
|
||||
# [ASSERT] 新任务游标必须继承上一期的全部推送进度,而非从 0 开始
|
||||
assert body["data"]["pushed_video_count"] == 2
|
||||
# [ASSERT] 游标非 0 时不触发发布首批推送,员工不会收到重复的"精益管理培训视频推送"企微通知
|
||||
assert push_messages == []
|
||||
assert len(initial_messages) == 1
|
||||
|
||||
|
||||
def test_new_week_task_continues_from_last_cursor_and_never_repushes(client, app, monkeypatch):
|
||||
"""关键断言:存在未推送视频时从断点只推新视频;剩余全是已推送视频时游标直接推到末尾且不再发企微。"""
|
||||
push_messages: list[dict] = []
|
||||
monkeypatch.setattr(
|
||||
lean_training_push_service,
|
||||
"_send_reminder",
|
||||
lambda **kwargs: push_messages.append(kwargs) or "sent",
|
||||
)
|
||||
monkeypatch.setattr(lean_training_reminder_service, "_send_reminder", lambda **kwargs: "sent")
|
||||
with app.app_context():
|
||||
hr = _create_hr_user(username="lean_hr_continue")
|
||||
config_id, desc_ids = _create_lean_video_config(video_count=3)
|
||||
# [STEP] 资源按上传倒序为 desc_ids=[r3, r2, r1];上一期冻结 [r2, r1] 并已全部推完
|
||||
r3, r2, r1 = desc_ids
|
||||
_create_last_week_task(config_id=config_id, video_resource_ids=[r2, r1], pushed_video_count=2)
|
||||
week_start, _ = lean_training_service._current_week_bounds()
|
||||
|
||||
create_response = client.post("/api/admin/lean-training/weekly-tasks", headers=_auth_headers(hr), json={
|
||||
"week_key": week_start.isoformat(),
|
||||
"video_resource_ids": [],
|
||||
"target_roles": ["user"],
|
||||
"target_user_ids": [],
|
||||
"weekly_count": 1,
|
||||
})
|
||||
|
||||
assert create_response.status_code == 201
|
||||
task = create_response.get_json()["data"]
|
||||
assert task["video_resource_ids"] == [r3, r2, r1]
|
||||
# [ASSERT] 新列表首个视频未被推送过 → 继承游标 0 并自动推首批,但批次只含"新视频 r3",绝不重推 r1/r2
|
||||
assert task["pushed_video_count"] == 1
|
||||
assert len(push_messages) == 1
|
||||
assert push_messages[0]["event_key"] == "video-push-0-1"
|
||||
|
||||
# [STEP] HR 手动推送下一批:待推区间 [r2, r1] 全部已被上一期推送过 → 视为推完,不发企微
|
||||
push_response = client.post(f"/api/admin/lean-training/weekly-tasks/{task['id']}/push", headers=_auth_headers(hr))
|
||||
|
||||
assert push_response.status_code == 200
|
||||
push_result = push_response.get_json()
|
||||
assert push_result["data"]["status"] == "completed"
|
||||
assert push_result["data"]["pushed_count"] == 0
|
||||
# [ASSERT] 游标越过重复视频推进到列表末尾,企微通知始终只有首批新视频那一轮
|
||||
refreshed = client.get(f"/api/admin/lean-training/weekly-tasks/{task['id']}", headers=_auth_headers(hr))
|
||||
assert refreshed.get_json()["data"]["pushed_video_count"] == 3
|
||||
assert len(push_messages) == 1
|
||||
|
||||
|
||||
def test_auto_roll_appends_new_videos_and_continues_push_from_cursor(app, monkeypatch):
|
||||
"""关键断言:每周自动滚动继承游标并自动追加配置新增视频,推送只从断点继续推新视频、绝不重推旧视频。"""
|
||||
push_messages: list[dict] = []
|
||||
monkeypatch.setattr(
|
||||
lean_training_push_service,
|
||||
"_send_reminder",
|
||||
lambda **kwargs: push_messages.append(kwargs) or "sent",
|
||||
)
|
||||
monkeypatch.setattr(lean_training_reminder_service, "_send_reminder", lambda **kwargs: "sent")
|
||||
with app.app_context():
|
||||
_create_hr_user(username="lean_hr_roll")
|
||||
config_id, desc_ids = _create_lean_video_config(video_count=4)
|
||||
# [STEP] 等价"手动勾选补齐并推完"后的状态:上一期冻结 4 个视频、游标 4/4;配置随后新上传第 5 个视频
|
||||
_create_last_week_task(config_id=config_id, video_resource_ids=list(desc_ids), pushed_video_count=4)
|
||||
agent = db.session.execute(select(Agent).where(Agent.name == "lean_video_agent")).scalars().first()
|
||||
new_guide = AgentGuide(
|
||||
agent_id=agent.id,
|
||||
file_name="lean-video-new.mp4",
|
||||
file_type="video",
|
||||
file_path="lean/video-new.mp4",
|
||||
created_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(new_guide)
|
||||
db.session.flush()
|
||||
new_resource = TrainingConfigResource(
|
||||
config_id=config_id,
|
||||
resource_type="agent_guide",
|
||||
training_level="company",
|
||||
agent_guide_id=new_guide.id,
|
||||
title="精益视频新增",
|
||||
created_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(new_resource)
|
||||
db.session.commit()
|
||||
new_resource_id = new_resource.id
|
||||
|
||||
with app.app_context():
|
||||
rolled = lean_training_push_service.ensure_current_week_task()
|
||||
|
||||
assert rolled is not None
|
||||
rolled_ids = list(rolled.video_resource_ids)
|
||||
# [ASSERT] 已推送前缀原样保留在列表头部,新视频自动追加到末尾,游标继承不受追加影响
|
||||
assert rolled_ids == [*desc_ids, new_resource_id]
|
||||
assert rolled.pushed_video_count == 4
|
||||
rolled_id = rolled.id
|
||||
|
||||
push_result = lean_training_push_service.push_lean_training_videos(rolled.id, trigger="schedule")
|
||||
|
||||
# [ASSERT] 首次推送只含新视频(断点续推),旧视频一个都不重推
|
||||
assert push_result["status"] == "sent"
|
||||
assert push_result["pushed_resource_ids"] == [new_resource_id]
|
||||
assert len(push_messages) == 1
|
||||
assert push_messages[0]["event_key"] == "video-push-4-5"
|
||||
refreshed = db.session.get(LeanTrainingWeeklyTask, rolled_id)
|
||||
assert refreshed.pushed_video_count == 5
|
||||
|
||||
# [STEP] 再次推送:待推区间为空 → 推完即停,不再发企微
|
||||
second_result = lean_training_push_service.push_lean_training_videos(rolled.id, trigger="manual")
|
||||
|
||||
assert second_result["status"] == "completed"
|
||||
assert len(push_messages) == 1
|
||||
|
||||
|
||||
def test_lean_reminders_jump_to_training_agent_dynamically(app, monkeypatch):
|
||||
"""关键断言:精益企微卡片必须动态解析各环境的「员工培训」Agent(content_profile=training),不得依赖固定 ID 27。"""
|
||||
sent: list[dict] = []
|
||||
monkeypatch.setattr(
|
||||
lean_training_reminder_service,
|
||||
"send_wecom_event_message",
|
||||
lambda **kwargs: sent.append(kwargs) or {"ok": True, "trace_id": "lean-jump-trace"},
|
||||
)
|
||||
with app.app_context():
|
||||
hr = _create_hr_user(username="lean_hr_jump")
|
||||
config_id, desc_ids = _create_lean_video_config(video_count=1)
|
||||
training_agent = Agent(name="员工培训", type="api", handler_config={"content_profile": "training"})
|
||||
db.session.add(training_agent)
|
||||
db.session.flush()
|
||||
week_start, due_at = lean_training_service._current_week_bounds()
|
||||
task = LeanTrainingWeeklyTask(
|
||||
config_id=config_id,
|
||||
week_key=week_start.isoformat(),
|
||||
due_at=due_at,
|
||||
video_resource_ids=list(desc_ids),
|
||||
weekly_count=1,
|
||||
pushed_video_count=0,
|
||||
target_roles=[],
|
||||
target_user_ids=[hr.id],
|
||||
status="published",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
task_id, training_agent_id = task.id, training_agent.id
|
||||
|
||||
totals = lean_training_reminder_service.send_initial_target_notifications(task_id)
|
||||
|
||||
assert totals["sent"] == 1
|
||||
assert len(sent) == 1
|
||||
# [ASSERT] 跳转路径动态指向本环境培训 Agent(即使 ID≠27 也正确),并携带精益页签深链参数
|
||||
assert sent[0]["jump_path"] == f"/chat/{training_agent_id}"
|
||||
assert sent[0]["jump_params"]["training_type"] == "lean_management"
|
||||
assert sent[0]["jump_params"]["weekly_task_id"] == task_id
|
||||
|
||||
|
||||
def test_lean_jump_agent_id_config_override_and_legacy_fallback(app, monkeypatch):
|
||||
"""关键断言:显式配置优先于动态解析;无配置且无培训 Agent 时回退历史默认 27 保持兼容。"""
|
||||
with app.app_context():
|
||||
# [ASSERT] 显式配置覆盖动态解析(运维固定指向特定 Agent 的逃生通道)
|
||||
monkeypatch.setitem(current_app.config, "WECOM_LEAN_TRAINING_JUMP_AGENT_ID", 999)
|
||||
assert lean_training_service.resolve_lean_training_jump_agent_id() == 999
|
||||
|
||||
with app.app_context():
|
||||
monkeypatch.setitem(current_app.config, "WECOM_LEAN_TRAINING_JUMP_AGENT_ID", 0)
|
||||
# [ASSERT] 系统内不存在培训 Agent 时回退历史默认 27
|
||||
assert lean_training_service.resolve_lean_training_jump_agent_id() == 27
|
||||
|
||||
|
||||
def test_auto_roll_pauses_when_all_videos_pushed_and_no_new_videos(app):
|
||||
"""关键断言:视频库全部推完且配置无新增视频时,自动滚动不再创建内容重复的新一期任务(暂停)。"""
|
||||
with app.app_context():
|
||||
_create_hr_user(username="lean_hr_pause")
|
||||
config_id, desc_ids = _create_lean_video_config(video_count=2)
|
||||
# [STEP] 等价"每周推 2 个、库内共 2 个视频":上一期已把全部视频推完(游标 2/2)
|
||||
_create_last_week_task(config_id=config_id, video_resource_ids=list(desc_ids), pushed_video_count=2)
|
||||
|
||||
with app.app_context():
|
||||
rolled = lean_training_push_service.ensure_current_week_task()
|
||||
|
||||
# [ASSERT] 无新视频可推时滚动暂停(返回 None),不创建重复内容的新一期任务
|
||||
assert rolled is None
|
||||
with app.app_context():
|
||||
remaining = db.session.execute(select(LeanTrainingWeeklyTask)).scalars().all()
|
||||
assert len(remaining) == 1
|
||||
|
||||
|
||||
def test_format_beijing_iso_converts_utc_storage_to_beijing_display():
|
||||
"""关键断言:序列化输出的观看/完成/截止时间必须为北京时间(+08:00)——UTC naive 10:47 对应北京 18:47,
|
||||
此前 UTC 直出导致页面显示比实际早 8 小时(18:47 完成显示 10:47)。"""
|
||||
# [ASSERT] UTC naive(数据库存储口径)→ 北京时间 +08:00
|
||||
assert lean_training_service.format_beijing_iso(datetime(2026, 9, 22, 10, 47, 33)) == "2026-09-22T18:47:33+08:00"
|
||||
# [ASSERT] UTC 带 Z 文本(老数据/客户端口径)→ 北京时间
|
||||
assert lean_training_service.format_beijing_iso("2026-09-22T10:47:33+00:00") == "2026-09-22T18:47:33+08:00"
|
||||
# [ASSERT] 已是北京时间的文本保持墙钟不变(幂等,前端回显值二次进入不重复偏移)
|
||||
assert lean_training_service.format_beijing_iso("2026-09-22T18:47:33+08:00") == "2026-09-22T18:47:33+08:00"
|
||||
# [ASSERT] 空值返回 None,非法文本原样返回(历史脏数据不阻塞展示)
|
||||
assert lean_training_service.format_beijing_iso(None) is None
|
||||
assert lean_training_service.format_beijing_iso("") is None
|
||||
assert lean_training_service.format_beijing_iso("not-a-time") == "not-a-time"
|
||||
|
||||
|
||||
def test_parse_client_iso_to_utc_text_normalizes_client_echo_to_utc_storage():
|
||||
"""关键断言:save_completion 兜底入库的客户端回显时间必须归一为 UTC naive 文本,
|
||||
保证 watched_at_json"存储一律 UTC"约定不被北京时间回显值破坏。"""
|
||||
# [ASSERT] 北京时间(+08:00)→ UTC naive
|
||||
assert lean_training_service.parse_client_iso_to_utc_text("2026-09-22T18:47:33+08:00") == "2026-09-22T10:47:33"
|
||||
# [ASSERT] UTC 带 Z(老版客户端 toISOString 口径)→ 去时区 UTC
|
||||
assert lean_training_service.parse_client_iso_to_utc_text("2026-09-22T10:47:33Z") == "2026-09-22T10:47:33"
|
||||
# [ASSERT] naive 按北京时间墙钟解释 → UTC
|
||||
assert lean_training_service.parse_client_iso_to_utc_text("2026-09-22T18:47:33") == "2026-09-22T10:47:33"
|
||||
# [ASSERT] 非法文本原样返回,不阻塞感悟提交
|
||||
assert lean_training_service.parse_client_iso_to_utc_text("garbage") == "garbage"
|
||||
|
||||
|
||||
def test_learner_period_videos_only_own_first_pushed(app):
|
||||
"""关键断言:自动滚动复制上一期冻结列表后(第2期前缀含上一期已推视频的脏数据),
|
||||
学员端/看板/完成校验的"本期视频"只含本任务首次推送的部分——上一期已推送视频不再重复展示、不要求重学;
|
||||
第1期自身展示不受影响;管理端任务详情仍返回全量冻结列表。"""
|
||||
with app.app_context():
|
||||
learner = _create_hr_user(username="lean_learner_own")
|
||||
config_id, desc_ids = _create_lean_video_config(video_count=4)
|
||||
# [STEP] 复刻生产事故数据:资源按上传倒序 desc_ids=[r4, r3, r2, r1];
|
||||
# 第1期冻结 [r2, r1] 已推完,自动滚动第2期 = [r2, r1, r4, r3]、继承游标 2 后推完新视频 → 游标 4
|
||||
r4, r3, r2, r1 = desc_ids
|
||||
_create_last_week_task(config_id=config_id, video_resource_ids=[r2, r1], pushed_video_count=2)
|
||||
week_start, due_at = lean_training_service._current_week_bounds()
|
||||
current_task = LeanTrainingWeeklyTask(
|
||||
config_id=config_id,
|
||||
week_key=week_start.isoformat(),
|
||||
due_at=due_at,
|
||||
video_resource_ids=[r2, r1, r4, r3],
|
||||
weekly_count=2,
|
||||
pushed_video_count=4,
|
||||
target_roles=["user"],
|
||||
target_user_ids=[],
|
||||
status="published",
|
||||
)
|
||||
db.session.add(current_task)
|
||||
db.session.commit()
|
||||
current_task_id = current_task.id
|
||||
|
||||
# [ASSERT] 第1期不受影响:本任务首推的 [r2, r1] 全量展示
|
||||
mine = {item["week_key"]: item for item in lean_training_service.list_my_weekly_tasks(learner)}
|
||||
assert mine[(week_start - timedelta(days=7)).isoformat()]["video_resource_ids"] == [r2, r1]
|
||||
# [ASSERT] 第2期学员端只展示本任务首次推送的 [r4, r3],上一期已推的 r2/r1 不再出现(推过的视频不能重复再推)
|
||||
assert mine[week_start.isoformat()]["video_resource_ids"] == [r4, r3]
|
||||
assert [video["id"] for video in mine[week_start.isoformat()]["videos"]] == [r4, r3]
|
||||
|
||||
# [ASSERT] 管理看板任务详情仍是全量冻结列表,但人员行视频列只列本期布置的 [r4, r3]
|
||||
dashboard = lean_training_service.list_dashboard(current_task_id)
|
||||
assert dashboard["task"]["video_resource_ids"] == [r2, r1, r4, r3]
|
||||
assert dashboard["incomplete"][0]["videos"] == [
|
||||
{"name": "精益视频4", "watched_at": None},
|
||||
{"name": "精益视频3", "watched_at": None},
|
||||
]
|
||||
|
||||
# [ASSERT] 其它任务首推的视频(r2)不在本期学习范围,观看记录被拒绝
|
||||
with pytest.raises(NotFoundError):
|
||||
lean_training_service.mark_video_watched(learner, {"weekly_task_id": current_task_id, "resource_id": r2})
|
||||
|
||||
# [ASSERT] 完成校验只考核本任务首推视频:仅观看 r4/r3 并提交达标感悟即完成,不要求重看上一期的 r1/r2
|
||||
result = lean_training_service.save_completion(learner, {
|
||||
"weekly_task_id": current_task_id,
|
||||
"watched_at": {str(r4): "2026-09-28T10:00:00", str(r3): "2026-09-28T11:00:00"},
|
||||
"summary_text": "通过本期两个新视频的学习,我认识到持续改善要从小处着手,先改变思维再改变行动,后续会在日常工作中主动发现问题并逐步优化,让改善真正落地。",
|
||||
})
|
||||
assert result["status"] == "completed"
|
||||
assert [video["name"] for video in result["videos"]] == ["精益视频4", "精益视频3"]
|
||||
assert all(video["watched_at"] for video in result["videos"])
|
||||
|
||||
# [ASSERT] 看板行同步反映本期口径与完成状态
|
||||
refreshed = lean_training_service.list_dashboard(current_task_id)
|
||||
assert [row["videos"] for row in refreshed["completed"]] != []
|
||||
assert refreshed["completed"][0]["status"] == "completed"
|
||||
|
||||
|
||||
def test_lean_overdue_reminder_texts_carry_period_labels(app, monkeypatch):
|
||||
"""关键断言:多期任务并存扫描时,逾期提醒标题/内容必须携带期次标签(第N期+周次区间),
|
||||
员工可分辨催办归属哪一期,避免"完成当期后仍收到历史期相同提醒"被误认为系统误推
|
||||
(2026-09-30 正式环境用户反馈);未过截止的当期任务不产生逾期提醒。"""
|
||||
sent: list[dict] = []
|
||||
monkeypatch.setattr(
|
||||
lean_training_reminder_service,
|
||||
"send_wecom_event_message",
|
||||
lambda **kwargs: sent.append(kwargs) or {"ok": True, "trace_id": "period-trace"},
|
||||
)
|
||||
with app.app_context():
|
||||
hr = _create_hr_user(username="lean_hr_period")
|
||||
config_id, desc_ids = _create_lean_video_config(video_count=1)
|
||||
# [STEP] 第1期(9-21周)已过截止,第2期(9-28当期)未过截止;扫描时刻=2026-09-30(周三)北京 09:00(UTC 01:00)
|
||||
_create_published_task(
|
||||
config_id=config_id, video_resource_ids=list(desc_ids),
|
||||
week_key="2026-09-21", due_utc=datetime(2026, 9, 27, 15, 59, 59), target_user_ids=[hr.id])
|
||||
_create_published_task(
|
||||
config_id=config_id, video_resource_ids=list(desc_ids),
|
||||
week_key="2026-09-28", due_utc=datetime(2026, 10, 4, 15, 59, 59), target_user_ids=[hr.id])
|
||||
|
||||
result = lean_training_reminder_service.run_lean_training_reminders(now=datetime(2026, 9, 30, 1, 0, 0))
|
||||
|
||||
# [ASSERT] 仅已过截止的第1期触发一轮提醒,且标题带期次、内容以完整周次区间开头
|
||||
assert result["sent"] == 1
|
||||
assert sent[0]["title"] == "精益管理培训逾期提醒(第1期)"
|
||||
assert sent[0]["content"].startswith("第1期(09-21至09-27)")
|
||||
# [ASSERT] 未过截止的第2期不发送任何逾期提醒
|
||||
assert all("第2期" not in message["title"] for message in sent)
|
||||
|
||||
|
||||
def test_lean_overdue_reminders_stop_after_grace_days(app, monkeypatch):
|
||||
"""关键断言:已过截止超过 100 天宽限期的历史期任务停止催办——排程扫描与推送后延期提醒
|
||||
两条路径均静默,任务保持 published 供管理端查询,但不再对旧账无限期发送企微。"""
|
||||
sent: list[dict] = []
|
||||
monkeypatch.setattr(
|
||||
lean_training_reminder_service,
|
||||
"send_wecom_event_message",
|
||||
lambda **kwargs: sent.append(kwargs) or {"ok": True, "trace_id": "stop-trace"},
|
||||
)
|
||||
with app.app_context():
|
||||
hr = _create_hr_user(username="lean_hr_stop")
|
||||
config_id, desc_ids = _create_lean_video_config(video_count=1)
|
||||
# [STEP] 截止 2026-05-31(北京),早于扫描时刻 2026-09-30 已 122 天,超出 100 天宽限期
|
||||
stale_task = _create_published_task(
|
||||
config_id=config_id, video_resource_ids=list(desc_ids),
|
||||
week_key="2026-05-25", due_utc=datetime(2026, 5, 31, 15, 59, 59), target_user_ids=[hr.id])
|
||||
stale_task_id = stale_task.id
|
||||
|
||||
scan_result = lean_training_reminder_service.run_lean_training_reminders(now=datetime(2026, 9, 30, 1, 0, 0))
|
||||
|
||||
# [ASSERT] 排程扫描对超宽限期任务静默(event_key 直接不生成)
|
||||
assert scan_result["sent"] == 0
|
||||
|
||||
# [ASSERT] HR 对历史期手动补推视频触发的"推送后延期提醒"同样受宽限期约束
|
||||
overdue_result = lean_training_reminder_service.notify_overdue_users_after_push(
|
||||
db.session.get(LeanTrainingWeeklyTask, stale_task_id),
|
||||
current=datetime(2026, 9, 30, 1, 0, 0),
|
||||
)
|
||||
assert overdue_result["sent"] == 0
|
||||
assert sent == []
|
||||
|
||||
|
||||
def test_lean_overdue_reminder_merges_periods_per_user_per_day(app, monkeypatch):
|
||||
"""关键断言:多期过期任务并存时,同一员工同一天只收到一条精益催办——
|
||||
排程扫描把多期未完成合并为一条汇总提醒(文案列明各期次);
|
||||
同天再触发推送后延期提醒或重复扫描均静默跳过(2026-09-30 用户反馈一人一天收到多条相同催办)。"""
|
||||
sent: list[dict] = []
|
||||
monkeypatch.setattr(
|
||||
lean_training_reminder_service,
|
||||
"send_wecom_event_message",
|
||||
lambda **kwargs: sent.append(kwargs) or {"ok": True, "trace_id": "merge-trace"},
|
||||
)
|
||||
with app.app_context():
|
||||
hr = _create_hr_user(username="lean_hr_merge")
|
||||
config_id, desc_ids = _create_lean_video_config(video_count=1)
|
||||
# [STEP] 两期均已过截止(9-14 期、9-21 期)且该员工都未完成;扫描时刻=2026-09-30(周三)北京 09:00
|
||||
week1_task = _create_published_task(
|
||||
config_id=config_id, video_resource_ids=list(desc_ids),
|
||||
week_key="2026-09-14", due_utc=datetime(2026, 9, 20, 15, 59, 59), target_user_ids=[hr.id])
|
||||
week2_task = _create_published_task(
|
||||
config_id=config_id, video_resource_ids=list(desc_ids),
|
||||
week_key="2026-09-21", due_utc=datetime(2026, 9, 27, 15, 59, 59), target_user_ids=[hr.id])
|
||||
|
||||
result = lean_training_reminder_service.run_lean_training_reminders(now=datetime(2026, 9, 30, 1, 0, 0))
|
||||
|
||||
# [ASSERT] 两期合并为一条汇总提醒:标题注明期数,内容列明各期周次区间,卡片跳转最近一期
|
||||
assert result["sent"] == 1
|
||||
assert len(sent) == 1
|
||||
assert sent[0]["title"] == "精益管理培训逾期提醒(共2期未完成)"
|
||||
assert "第1期(09-14至09-20)" in sent[0]["content"]
|
||||
assert "第2期(09-21至09-27)" in sent[0]["content"]
|
||||
assert sent[0]["jump_params"]["weekly_task_id"] == week2_task.id
|
||||
|
||||
# [ASSERT] 同天批次推送触发的延期提醒被"当天已催办"判定拦截,不再发送
|
||||
pushed_overdue = lean_training_reminder_service.notify_overdue_users_after_push(
|
||||
db.session.get(LeanTrainingWeeklyTask, week1_task.id),
|
||||
current=datetime(2026, 9, 30, 3, 0, 0),
|
||||
)
|
||||
assert pushed_overdue["sent"] == 0
|
||||
assert pushed_overdue["skipped"] == 1
|
||||
|
||||
# [ASSERT] 同天重复运行排程扫描同样静默(幂等,不产生第二条)
|
||||
rerun = lean_training_reminder_service.run_lean_training_reminders(now=datetime(2026, 9, 30, 5, 0, 0))
|
||||
assert rerun["sent"] == 0
|
||||
assert len(sent) == 1
|
||||
@@ -0,0 +1,103 @@
|
||||
"""
|
||||
tests/test_order_delivery_query.py
|
||||
|
||||
用途:订单交期回复列表合并关键词搜索(keyword OR 语义)的单测。
|
||||
依赖:conftest 的 app 夹具(testing + sqlite create_all)、query_service.list_lines。
|
||||
逻辑:keyword 命中订单单号/客户编号/产品编号/品名等任一字段即返回该行;
|
||||
订单维度命中时该订单全部项次返回;日期与状态筛选行为不回归。
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
from app.extensions import db
|
||||
from app.models.order_delivery_reply import OrderDeliveryErpLine
|
||||
from app.services.order_delivery_reply.query_service import list_lines
|
||||
|
||||
|
||||
def _line(order_no, line_no, *, cust_no="C001", part_no="P-1", part_name="标准物料", cust_part="CP-1"):
|
||||
"""构造一行最小快照(字段名/值供 keyword 断言用)。"""
|
||||
row = OrderDeliveryErpLine(
|
||||
order_no=order_no,
|
||||
line_no=line_no,
|
||||
order_date=date(2024, 6, 1),
|
||||
customer_no=cust_no,
|
||||
customer_short_name="恒远电子",
|
||||
part_no=part_no,
|
||||
part_name=part_name,
|
||||
customer_part_no=cust_part,
|
||||
qty=Decimal("100"),
|
||||
delivered_qty=Decimal("0"),
|
||||
erp_missing=False,
|
||||
)
|
||||
db.session.add(row)
|
||||
return row
|
||||
|
||||
|
||||
def test_keyword_matches_any_field_or_semantics(app):
|
||||
"""keyword 命中订单单号/客户编号/品名任一字段即返回(OR)。"""
|
||||
_line("8301-A", 1, part_name="驱动齿轮")
|
||||
_line("8301-B", 1, cust_no="C999")
|
||||
_line("8301-C", 1, part_no="P-XYZ")
|
||||
db.session.commit()
|
||||
|
||||
# 断言:品名命中 → 只返回 8301-A
|
||||
assert [i["order_no"] for i in list_lines({"keyword": "齿轮"})["items"]] == ["8301-A"]
|
||||
# 断言:客户编号命中 → 只返回 8301-B
|
||||
assert [i["order_no"] for i in list_lines({"keyword": "C999"})["items"]] == ["8301-B"]
|
||||
# 断言:产品编号命中 → 只返回 8301-C(大小写不敏感)
|
||||
assert [i["order_no"] for i in list_lines({"keyword": "p-xyz"})["items"]] == ["8301-C"]
|
||||
# 断言:订单单号片段命中 → 8301-A
|
||||
assert [i["order_no"] for i in list_lines({"keyword": "8301-A"})["items"]] == ["8301-A"]
|
||||
# 断言:无命中 → 空
|
||||
assert list_lines({"keyword": "不存在"})["items"] == []
|
||||
# 断言:空关键词 = 全部
|
||||
assert list_lines({})["total"] == 3
|
||||
|
||||
|
||||
def test_keyword_and_date_status_filters_stack(app):
|
||||
"""keyword 与 order_date/status 叠加时仍为 AND 语义。"""
|
||||
_line("8301-D", 1, part_name="齿轮")
|
||||
_line("8301-E", 1, part_name="齿轮")
|
||||
db.session.commit()
|
||||
|
||||
from app.models.order_delivery_reply import OrderDeliveryBatch
|
||||
|
||||
db.session.add(OrderDeliveryBatch(line_id=2, seq=1, planned_date=date(2024, 7, 1), qty=1))
|
||||
db.session.commit()
|
||||
|
||||
# 断言:关键词 + 日期叠加 → 只留同时满足的行
|
||||
result = list_lines({"keyword": "齿轮", "order_date": "2024-06-01"})
|
||||
assert result["total"] == 2
|
||||
result = list_lines({"keyword": "齿轮", "order_date": "2024-06-02"})
|
||||
assert result["total"] == 0
|
||||
# 断言:status=not_fully_replied(未锁定)两行都算;有批次的行仍是未锁定(部分回复)
|
||||
assert list_lines({"keyword": "齿轮", "status": "not_fully_replied"})["total"] == 2
|
||||
|
||||
|
||||
def test_keyword_matches_salesperson_and_reply_person(app):
|
||||
"""keyword 命中业务员(姓名/工号)与交期回复人员(姓名/工号)即返回(2026-09-23 增补)。"""
|
||||
from app.models.order_delivery_reply import OrderDeliveryLineState
|
||||
|
||||
salesperson_line = _line("8301-P1", 1, cust_no="C-A")
|
||||
salesperson_line.salesperson_name = "王瑞雪"
|
||||
salesperson_line.salesperson_code = "26070045"
|
||||
replied_line = _line("8301-P2", 2, cust_no="C-B")
|
||||
replied_line.salesperson_name = "张小奇"
|
||||
db.session.flush()
|
||||
# 交期回复人员快照存于行状态表(notified_user_name / notified_employee_id)
|
||||
db.session.add(OrderDeliveryLineState(
|
||||
line_id=replied_line.id, notified_user_name="李生", notified_employee_id="10002",
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
# 断言:业务员姓名命中 → 只返回 8301-P1
|
||||
assert [i["order_no"] for i in list_lines({"keyword": "王瑞雪"})["items"]] == ["8301-P1"]
|
||||
# 断言:业务员工号命中 → 只返回 8301-P1
|
||||
assert [i["order_no"] for i in list_lines({"keyword": "26070045"})["items"]] == ["8301-P1"]
|
||||
# 断言:交期回复人员姓名命中(状态表 EXISTS 子查询)→ 只返回 8301-P2
|
||||
assert [i["order_no"] for i in list_lines({"keyword": "李生"})["items"]] == ["8301-P2"]
|
||||
# 断言:交期回复人员工号命中 → 只返回 8301-P2
|
||||
assert [i["order_no"] for i in list_lines({"keyword": "10002"})["items"]] == ["8301-P2"]
|
||||
# 断言:未命中任何人员 → 空
|
||||
assert list_lines({"keyword": "不存在的名字"})["items"] == []
|
||||
@@ -0,0 +1,335 @@
|
||||
"""
|
||||
tests/test_order_delivery_reminder.py
|
||||
|
||||
用途:订单交期回复每日提醒(出货提醒 / 未回复再提醒)与 Web 排程兜底扫描的单测。
|
||||
依赖:conftest 的 app 夹具(testing + sqlite create_all)、reminder_service、web_scanner。
|
||||
逻辑:出货提醒验证「窗口内锁定行按业务员聚合一、去重只发一次、未映射业务员记失败审计」;
|
||||
未回复提醒验证「超期行聚合提醒生管、N 天内不重复提醒、无收件人跳过」;
|
||||
企微发送以 monkeypatch 替身控制成败,不触网。
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.extensions import db as db_ext
|
||||
from app.models import User
|
||||
from app.models.order_delivery_reply import (
|
||||
OrderDeliveryAuditEvent,
|
||||
OrderDeliveryBatch,
|
||||
OrderDeliveryErpLine,
|
||||
OrderDeliveryLineState,
|
||||
)
|
||||
from app.services.order_delivery_reply.reminder_service import (
|
||||
ACTION_SHIP_REMIND,
|
||||
ACTION_UNREPLIED_REMIND,
|
||||
run_ship_reminders,
|
||||
run_unreplied_reminders,
|
||||
)
|
||||
|
||||
|
||||
def _make_line(order_no="8301-1605280014", line_no=1, salesperson="10001", order_days_ago=0):
|
||||
"""构造一行已同步快照(order_days_ago 控制订单日期距今天数,即未回复超期判定的锚点)。"""
|
||||
line = OrderDeliveryErpLine(
|
||||
order_no=order_no,
|
||||
line_no=line_no,
|
||||
order_date=datetime.utcnow().date() - timedelta(days=order_days_ago),
|
||||
customer_no="C001",
|
||||
salesperson_code=salesperson,
|
||||
qty=Decimal("100"),
|
||||
delivered_qty=Decimal("0"),
|
||||
erp_missing=False,
|
||||
)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
return line
|
||||
|
||||
|
||||
def _lock_line(line, planned_date):
|
||||
"""锁定行 + 一个批次:出货提醒候选(已回复 = 已锁定)。"""
|
||||
db.session.add(OrderDeliveryBatch(line_id=line.id, seq=1, planned_date=planned_date, qty=Decimal("100")))
|
||||
db.session.add(OrderDeliveryLineState(line_id=line.id, locked=True))
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def _make_user(employee_id, wecom_userid="wx_10001"):
|
||||
"""构造已绑企微的用户(出货提醒收件人按 employee_id 映射)。"""
|
||||
user = User(
|
||||
username=f"u_{employee_id}",
|
||||
email=f"u_{employee_id}@test.local",
|
||||
real_name=f"业务{employee_id}",
|
||||
employee_id=employee_id,
|
||||
wecom_userid=wecom_userid,
|
||||
role="user",
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
return user
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def send_recorder(monkeypatch):
|
||||
"""替身企微发送:记录 (收件人, 正文) 并可 scripted 控制成败;断言「发送过几条、发给谁」。"""
|
||||
calls = {"list": [], "ok": True}
|
||||
|
||||
def _fake_send(event_type, user, title, content, jump_path="/workspace", jump_params=None, **_kw):
|
||||
calls["list"].append({"user": user, "content": content, "jump_path": jump_path})
|
||||
return {"ok": calls["ok"], "trace_id": "t-" + str(len(calls["list"]))}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.order_delivery_reply.reminder_service.send_wecom_event_message", _fake_send
|
||||
)
|
||||
return calls
|
||||
|
||||
|
||||
def test_ship_reminder_groups_by_salesperson_and_dedupes(app, send_recorder):
|
||||
"""窗口内两行同业务员 → 只发 1 条聚合卡片;再次扫描同 (行, 交期) 不重发。"""
|
||||
from datetime import date
|
||||
|
||||
_make_user("10001")
|
||||
today = date.today()
|
||||
line_a = _make_line(order_no="8301-A", line_no=1)
|
||||
line_b = _make_line(order_no="8301-B", line_no=2)
|
||||
_lock_line(line_a, today + timedelta(days=3))
|
||||
_lock_line(line_b, today + timedelta(days=2))
|
||||
db.session.commit()
|
||||
|
||||
result = run_ship_reminders(advance_days=3)
|
||||
# 断言:候选 2 行、聚合后只发 1 人 1 条
|
||||
assert result["candidate_lines"] == 2
|
||||
assert result["notified_salespersons"] == 1
|
||||
assert len(send_recorder["list"]) == 1
|
||||
assert "8301-A:1" in send_recorder["list"][0]["content"]
|
||||
assert "8301-B:2" in send_recorder["list"][0]["content"]
|
||||
|
||||
# 再次扫描:同 (行, 交期) 已成功提醒过,不得重发
|
||||
second = run_ship_reminders(advance_days=3)
|
||||
assert second["candidate_lines"] == 2
|
||||
assert second["notified_salespersons"] == 0
|
||||
assert len(send_recorder["list"]) == 1
|
||||
|
||||
|
||||
def test_ship_reminder_retries_after_failed_send(app, send_recorder):
|
||||
"""发送失败不算已提醒:次日(再次扫描)应自动补发。"""
|
||||
from datetime import date
|
||||
|
||||
_make_user("10001")
|
||||
line = _make_line(order_no="8301-C", line_no=1)
|
||||
_lock_line(line, date.today() + timedelta(days=1))
|
||||
db.session.commit()
|
||||
|
||||
send_recorder["ok"] = False
|
||||
failed = run_ship_reminders(advance_days=3)
|
||||
# 断言:失败发送计入 failed 且仍落审计(ok=false 不参与去重)
|
||||
assert failed["notified_salespersons"] == 0
|
||||
assert failed["failed_salespersons"] == 1
|
||||
ok_events = [
|
||||
e for e in OrderDeliveryAuditEvent.query.filter_by(action=ACTION_SHIP_REMIND).all()
|
||||
if (e.payload_json or {}).get("ok") is True
|
||||
]
|
||||
assert ok_events == []
|
||||
|
||||
send_recorder["ok"] = True
|
||||
retried = run_ship_reminders(advance_days=3)
|
||||
# 断言:第二次扫描补发成功
|
||||
assert retried["notified_salespersons"] == 1
|
||||
assert len(send_recorder["list"]) == 2
|
||||
|
||||
|
||||
def test_ship_reminder_records_unmapped_salesperson(app, send_recorder):
|
||||
"""业务员工号对不上已绑企微用户:不发送、计入 skipped_unmapped 并留失败审计。"""
|
||||
from datetime import date
|
||||
|
||||
line = _make_line(order_no="8301-D", line_no=1, salesperson="99999")
|
||||
_lock_line(line, date.today() + timedelta(days=3))
|
||||
db.session.commit()
|
||||
|
||||
result = run_ship_reminders(advance_days=3)
|
||||
# 断言:无发送、无成功审计
|
||||
assert result["notified_salespersons"] == 0
|
||||
assert result["skipped_unmapped"] == 1
|
||||
assert send_recorder["list"] == []
|
||||
|
||||
|
||||
def test_unreplied_reminder_notifies_recipients_with_cadence(app, send_recorder):
|
||||
"""超期未回复行提醒配置的生管;N 天内第二次扫描不重复提醒。"""
|
||||
_make_user("10001", "wx_admin1") # 生管收件人
|
||||
_make_line(order_no="8301-E", line_no=1, order_days_ago=5) # 订单日期超 3 天未回复
|
||||
_make_line(order_no="8301-F", line_no=2, order_days_ago=1) # 未超期,不应入选
|
||||
db.session.commit()
|
||||
|
||||
result = run_unreplied_reminders(unreplied_days=3, notify_user_ids=[1])
|
||||
# 断言:只有超期行入选(due_lines=1),发送 1 个收件人 1 条
|
||||
assert result["due_lines"] == 1
|
||||
assert result["notified_recipients"] == 1
|
||||
assert len(send_recorder["list"]) == 1
|
||||
assert "8301-E:1" in send_recorder["list"][0]["content"]
|
||||
|
||||
# 同行 3 天内不重复提醒
|
||||
again = run_unreplied_reminders(unreplied_days=3, notify_user_ids=[1])
|
||||
assert again["notified_recipients"] == 0
|
||||
assert len(send_recorder["list"]) == 1
|
||||
|
||||
|
||||
def test_unreplied_reminder_skips_without_recipients(app, send_recorder):
|
||||
"""未配置生管收件人(开关关闭或名单为空):跳过发送并如实标记。"""
|
||||
_make_line(order_no="8301-G", line_no=1, order_days_ago=10)
|
||||
db.session.commit()
|
||||
|
||||
result = run_unreplied_reminders(unreplied_days=3, notify_user_ids=[])
|
||||
# 断言:有到期行但无收件人 → skipped_no_recipient=True 且不发送
|
||||
assert result["due_lines"] == 1
|
||||
assert result["skipped_no_recipient"] is True
|
||||
assert send_recorder["list"] == []
|
||||
|
||||
|
||||
def test_unreplied_reminder_failed_send_does_not_advance_cadence(app, send_recorder):
|
||||
"""发送失败不推进提醒节奏:紧接着的再次扫描仍会尝试提醒(不做 N 天静默)。"""
|
||||
_make_user("10001", "wx_admin2")
|
||||
_make_line(order_no="8301-H", line_no=1, order_days_ago=5)
|
||||
db.session.commit()
|
||||
|
||||
send_recorder["ok"] = False
|
||||
run_unreplied_reminders(unreplied_days=3, notify_user_ids=[1])
|
||||
# 断言:首次发送失败
|
||||
assert len(send_recorder["list"]) == 1
|
||||
|
||||
send_recorder["ok"] = True
|
||||
retried = run_unreplied_reminders(unreplied_days=3, notify_user_ids=[1])
|
||||
# 断言:失败后不静默,立即重试成功
|
||||
assert retried["notified_recipients"] == 1
|
||||
assert len(send_recorder["list"]) == 2
|
||||
|
||||
|
||||
def test_web_scanner_respects_disabled_flag(app):
|
||||
"""SCHEDULE_WEB_SCANNER_ENABLED=false 时不启动线程(幂等入口可重复调用)。"""
|
||||
from app.services.schedule import web_scanner
|
||||
|
||||
app.config["SCHEDULE_WEB_SCANNER_ENABLED"] = False
|
||||
web_scanner.start_web_schedule_scanner(app) # 不应抛错、不启动线程
|
||||
import threading
|
||||
|
||||
names = [t.name for t in threading.enumerate()]
|
||||
# 断言:关闭开关时没有新的 web-schedule-scanner 线程
|
||||
assert names.count("web-schedule-scanner") == 0
|
||||
|
||||
|
||||
# ============ 提醒任务独立启停(布尔任务参数) ============
|
||||
|
||||
|
||||
def _make_remind_task(job_params, notify_enabled=True, notify_user_ids=None):
|
||||
"""构造内存态提醒排程任务(不落库,handler 只读 job_params 与通知配置)。"""
|
||||
from app.models import ScheduleTask
|
||||
|
||||
return ScheduleTask(
|
||||
schedule_no="SCH-TEST-REMIND",
|
||||
name="提醒测试",
|
||||
schedule_type="platform_job",
|
||||
platform_api_path="order-delivery-remind",
|
||||
job_params=job_params,
|
||||
notify_enabled=notify_enabled,
|
||||
notify_user_ids_json=notify_user_ids or [],
|
||||
)
|
||||
|
||||
|
||||
def test_remind_params_defaults_backfill_both_enabled(app):
|
||||
"""契约层对空 job_params 回填默认值:两类提醒默认开启、天数默认 3。"""
|
||||
from app.services.schedule.job_params import validate_task_params
|
||||
|
||||
normalized = validate_task_params("order-delivery-remind", {}, check_options=False)
|
||||
# 断言:五个参数齐全,开关默认 True、天数默认 3;未回复提醒收件人默认空(回退任务通知人)
|
||||
assert normalized == {
|
||||
"ship_remind_enabled": True,
|
||||
"ship_remind_advance_days": 3,
|
||||
"unreplied_remind_enabled": True,
|
||||
"unreplied_remind_days": 3,
|
||||
"unreplied_remind_user_ids": [],
|
||||
}
|
||||
|
||||
|
||||
def test_disabled_ship_reminder_skips_only_ship(app, send_recorder):
|
||||
"""ship_remind_enabled=false:出货提醒跳过,未回复提醒照常发送。"""
|
||||
from datetime import date
|
||||
|
||||
recipient = _make_user("10001", "wx_admin")
|
||||
today = date.today()
|
||||
locked_line = _make_line(order_no="8301-S1", line_no=1)
|
||||
_lock_line(locked_line, today + timedelta(days=2)) # 出货提醒候选
|
||||
_make_line(order_no="8301-S2", line_no=2, order_days_ago=5) # 未回复候选
|
||||
db.session.commit()
|
||||
|
||||
task = _make_remind_task(
|
||||
{"ship_remind_enabled": False},
|
||||
notify_enabled=True,
|
||||
notify_user_ids=[recipient.id],
|
||||
)
|
||||
from app.services.schedule.order_delivery_remind_job import run_order_delivery_remind_schedule
|
||||
|
||||
total, success, failed, skipped, details, errors, _logs = run_order_delivery_remind_schedule(task, None)
|
||||
|
||||
summary = details[0]
|
||||
# 断言:出货侧跳过(skipped=disabled),未回复侧正常发送 1 条
|
||||
assert summary["ship_remind"].get("skipped") == "disabled"
|
||||
assert summary["unreplied_remind"].get("notified_recipients") == 1
|
||||
assert len(send_recorder["list"]) == 1
|
||||
assert "8301-S2:2" in send_recorder["list"][0]["content"]
|
||||
assert (total, success, failed) == (1, 1, 0)
|
||||
|
||||
|
||||
def test_disabled_unreplied_reminder_skips_only_unreplied(app, send_recorder):
|
||||
"""unreplied_remind_enabled=false:未回复提醒跳过,出货提醒照常发送。"""
|
||||
from datetime import date
|
||||
|
||||
_make_user("10001", "wx_sales")
|
||||
today = date.today()
|
||||
locked_line = _make_line(order_no="8301-U1", line_no=1)
|
||||
_lock_line(locked_line, today + timedelta(days=2)) # 出货提醒候选
|
||||
_make_line(order_no="8301-U2", line_no=2, order_days_ago=5) # 未回复候选(应被跳过不提醒)
|
||||
db.session.commit()
|
||||
|
||||
task = _make_remind_task(
|
||||
{"unreplied_remind_enabled": False},
|
||||
notify_enabled=True,
|
||||
notify_user_ids=[1],
|
||||
)
|
||||
from app.services.schedule.order_delivery_remind_job import run_order_delivery_remind_schedule
|
||||
|
||||
total, success, failed, skipped, details, errors, _logs = run_order_delivery_remind_schedule(task, None)
|
||||
|
||||
summary = details[0]
|
||||
# 断言:未回复侧跳过,出货侧正常发送 1 条;无未回复提醒相关错误
|
||||
assert summary["unreplied_remind"].get("skipped") == "disabled"
|
||||
assert summary["ship_remind"].get("notified_salespersons") == 1
|
||||
assert len(send_recorder["list"]) == 1
|
||||
assert "8301-U1:1" in send_recorder["list"][0]["content"]
|
||||
assert (total, success, failed) == (1, 1, 0)
|
||||
|
||||
|
||||
def test_both_disabled_no_scan_no_send(app, send_recorder):
|
||||
"""两类提醒都关闭:不扫描不发送,计数全零且无错误。"""
|
||||
from datetime import date
|
||||
|
||||
_make_user("10001", "wx_any")
|
||||
locked_line = _make_line(order_no="8301-X1", line_no=1)
|
||||
_lock_line(locked_line, date.today() + timedelta(days=2))
|
||||
_make_line(order_no="8301-X2", line_no=2, order_days_ago=5)
|
||||
db.session.commit()
|
||||
|
||||
task = _make_remind_task(
|
||||
{"ship_remind_enabled": False, "unreplied_remind_enabled": False},
|
||||
notify_enabled=True,
|
||||
notify_user_ids=[1],
|
||||
)
|
||||
from app.services.schedule.order_delivery_remind_job import run_order_delivery_remind_schedule
|
||||
|
||||
total, success, failed, skipped, details, errors, _logs = run_order_delivery_remind_schedule(task, None)
|
||||
|
||||
summary = details[0]
|
||||
# 断言:两侧都标记 disabled、无任何发送、计数全零
|
||||
assert summary["ship_remind"].get("skipped") == "disabled"
|
||||
assert summary["unreplied_remind"].get("skipped") == "disabled"
|
||||
assert send_recorder["list"] == []
|
||||
assert (total, success, failed, skipped) == (0, 0, 0, 0)
|
||||
assert errors == []
|
||||
@@ -0,0 +1,81 @@
|
||||
"""
|
||||
tests/test_order_delivery_reply_validation.py
|
||||
|
||||
用途:订单交期回复保存「数量守恒」校验的单测——每行各批次合计必须等于订单数量
|
||||
(2026-09-23 由「超额仅提醒」修订)。
|
||||
依赖:conftest 的 app 夹具(testing + sqlite create_all)、reply_service.save_batches/batch_reply。
|
||||
逻辑:合计 ≠ 订单数量 → ValidationError(BATCH_QTY_TOTAL_MISMATCH)且不落任何批次/审计;
|
||||
合计 = 订单数量 → 正常保存(多批次拆分亦同);联合回复中单行不等 → 该行按行失败,
|
||||
不影响其它行(部分成功语义)。
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.extensions import db
|
||||
from app.models.order_delivery_reply import OrderDeliveryBatch, OrderDeliveryErpLine
|
||||
from app.services.order_delivery_reply.reply_service import batch_reply, save_batches
|
||||
|
||||
|
||||
def _line(order_no, line_no=1, qty="100"):
|
||||
"""构造一行最小快照(qty 即订单数量,未回复提醒/保存校验的对照基准)。"""
|
||||
row = OrderDeliveryErpLine(
|
||||
order_no=order_no,
|
||||
line_no=line_no,
|
||||
order_date=date(2024, 6, 1),
|
||||
customer_no="C001",
|
||||
qty=Decimal(qty),
|
||||
delivered_qty=Decimal("0"),
|
||||
erp_missing=False,
|
||||
)
|
||||
db.session.add(row)
|
||||
return row
|
||||
|
||||
|
||||
def test_save_batches_rejects_total_not_equal_order_qty(app):
|
||||
"""各批次合计 90 ≠ 订单数量 100 → 422 数量守恒错误,且不落任何批次。"""
|
||||
_line("8301-V1", qty="100")
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
save_batches("8301-V1", 1, [{"planned_date": "2026-10-01", "qty": "90"}], operator_user_id=None)
|
||||
# 断言:错误码为数量守恒专用码,便于前端与 errors.json 四语言文案对应
|
||||
assert exc.value.code == "ORDER_DELIVERY_REPLY.BATCH_QTY_TOTAL_MISMATCH"
|
||||
# 断言:校验在任何写操作之前,失败不落批次
|
||||
assert OrderDeliveryBatch.query.count() == 0
|
||||
|
||||
|
||||
def test_save_batches_accepts_exact_total_with_multi_batches(app):
|
||||
"""60 + 40 = 订单数量 100 → 保存成功,多批次拆分合法。"""
|
||||
_line("8301-V2", qty="100")
|
||||
db.session.commit()
|
||||
|
||||
data = save_batches("8301-V2", 1, [
|
||||
{"planned_date": "2026-10-01", "qty": "60"},
|
||||
{"planned_date": "2026-11-01", "qty": "40"},
|
||||
], operator_user_id=None)
|
||||
# 断言:保存成功且 total_qty 与订单数量一致
|
||||
assert data["total_qty"] == "100"
|
||||
assert len(data["batches"]) == 2
|
||||
assert OrderDeliveryBatch.query.count() == 2
|
||||
|
||||
|
||||
def test_batch_reply_mismatch_line_fails_others_succeed(app):
|
||||
"""联合回复:单行合计不等按行失败,另一行正常保存(部分成功语义不回归)。"""
|
||||
_line("8301-V3", line_no=1, qty="100")
|
||||
_line("8301-V3", line_no=2, qty="200")
|
||||
db.session.commit()
|
||||
|
||||
summary = batch_reply([
|
||||
{"order_no": "8301-V3", "line_no": 1, "batches": [{"planned_date": "2026-10-01", "qty": "100"}]},
|
||||
{"order_no": "8301-V3", "line_no": 2, "batches": [{"planned_date": "2026-10-01", "qty": "150"}]},
|
||||
], operator_user_id=None)
|
||||
# 断言:行 2 合计 150 ≠ 200 失败;行 1 保存成功
|
||||
assert summary["succeeded"] == 1
|
||||
assert summary["failed"] == 1
|
||||
assert summary["items"][1]["ok"] is False
|
||||
# 断言:仅成功行落批次
|
||||
assert OrderDeliveryBatch.query.count() == 1
|
||||
@@ -0,0 +1,21 @@
|
||||
# 调试记录:访问不可用
|
||||
|
||||
- 状态:OPEN
|
||||
- 会话:access-unavailable
|
||||
- 日期:2026-09-09
|
||||
|
||||
## 症状
|
||||
|
||||
用户反馈“无法访问”,尚未明确是前端页面、后端接口、登录链路还是企微消息访问失败。
|
||||
|
||||
## 假设
|
||||
|
||||
1. 前端开发服务器未启动或端口 8881 不可达。
|
||||
2. 后端 Flask 服务未启动或端口 5052 不可达。
|
||||
3. 前端代理、环境地址或跨域配置指向了错误的后端地址。
|
||||
4. 服务启动后因数据库或外部集成初始化异常退出。
|
||||
5. 浏览器会话、认证或路由守卫导致访问被拒绝。
|
||||
|
||||
## 证据与下一步
|
||||
|
||||
待确认访问目标、访问地址、浏览器报错或网络响应后,再收集运行时证据。
|
||||
@@ -0,0 +1,37 @@
|
||||
---
|
||||
session_id: training-video-push-duplicate
|
||||
status: RESOLVED
|
||||
---
|
||||
|
||||
# 员工培训视频重复推送调试记录
|
||||
|
||||
## 症状
|
||||
|
||||
测试环境只有 2 个可推送视频,但第 1 期和第 2 期任务向员工展示了相同的 2 个视频。预期是全部视频推送完成后暂停,不再重复推送。
|
||||
|
||||
## 假设
|
||||
|
||||
1. 推送游标没有跨任务继承,新任务重新从第一个视频开始。
|
||||
2. 已推送判断只按任务 ID,而不是按视频资源 ID。
|
||||
3. 推送完成后游标没有持久化或读取错误。
|
||||
4. 前端资源快照映射错误,后端实际推送资源与页面展示资源不一致。
|
||||
5. 发布与补推并发读取同一游标,产生重复批次。
|
||||
|
||||
## 当前阶段
|
||||
|
||||
已定位根因并修复(2026-09-18,用户确认后实施);2026-09-29 生产环境复现变体(每周自动推送路径),已按方案 A 二次修复。
|
||||
|
||||
## 结论
|
||||
|
||||
- **根因(假设 1 成立)**:HR 在管理端手动新建下一期周任务走 `create_or_update_weekly_task`,新实例 `pushed_video_count=0`,API 层因游标为 0 自动推首批——视频从第 1 个重新推起;视频总数 ≤ 每周推送数量时两期展示完全相同。自动滚动路径(周一排程 `ensure_current_week_task`)本就继承游标,不受影响。
|
||||
- **修复**:
|
||||
1. `lean_training_service.create_or_update_weekly_task`:新建任务游标改为继承历史推送进度——取新冻结列表的"最长已推送前缀"长度(`_inherited_pushed_video_count`,以全部已发布任务已推送前缀并集为基线),从上一任务断点续推;
|
||||
2. `lean_training_push_service.push_lean_training_videos`:分批时跨任务绝对去重(`_already_pushed_resource_ids`),已被其它任务推送过的视频绝不进批次(游标越过);待推区间全部重复时游标推进到末尾、返回 completed 且不发企微。
|
||||
- **回归保障**:`backend/tests/test_lean_training_push.py` 两条契约测试(继承游标不重推首批 / 断点续推只推新视频且重复区间推完即停)。
|
||||
|
||||
## 第二轮(2026-09-29):自动滚动路径的"内容重复"变体
|
||||
|
||||
- **现象**:生产环境第 2 期(每周一自动推送)又出现第 1 期已推送视频(如 17、18)。数据库实况:第 2 期 `video_resource_ids=[17,18,25,24,23,22,21,20,19]`、`pushed_video_count=4`、`weekly_count=2`。
|
||||
- **根因**:与第一轮不同——**企微推送并未重发旧视频**(批次实为 [25,24] 新视频,游标=继承 2 + 本期 2 = 4 属正常绝对游标语义)。重复发生在**任务内容层**:`ensure_current_week_task` 自动滚动时把上一期冻结列表原样复制进新一期(复制 + 尾部追加新视频),而学员端展示(`serialize_weekly_task(learner_view)`)、观看/完成校验(`mark_video_watched` / `save_completion`)、管理看板视频列(`_task_video_rows`)全部按**累积已推送前缀** `video_resource_ids[:pushed_video_count]` 取数——上一期已推送视频出现在第 2 期且要求重看重写感悟,员工感知即"重复推送"。
|
||||
- **修复(方案 A,2026-09-29)**:新增 `_first_pushed_video_ids_map()` / `_own_pushed_video_ids()`(按周次升序遍历已发布任务,已推送前缀中"此前其它任务未推送过"的视频才归属本任务),并把上述四处口径统一改为"本任务首次推送的部分"。游标与数据结构不动;已产生的脏数据(第 2 期前缀含旧视频)自动恢复正常展示,无需修库。
|
||||
- **回归保障**:新增契约测试 `test_learner_period_videos_only_own_first_pushed`(复刻生产脏数据:第 2 期学员端只见/只考本期新增视频、第 1 期展示不受影响、看板口径一致、越权观看被拒)。
|
||||
@@ -1,5 +1,11 @@
|
||||
# 智能HR请假管理需求
|
||||
|
||||
## 订单交期回复 Agent(2026-09)
|
||||
|
||||
生管在工作台按 ERP 已审核、已核准、未结案的销售订单行回复交期(可拆多批次),保存后经行内或批量企微通知对应业务员并锁定;具备只读权限的业务人员可查看,回执不改状态。系统只读 ERP,不回写。操作权限按用户功能权限划分。每天 07:00(北京时间)全量同步全部合格订单,可手动刷新。一期不做单别白名单管理,操作页不出单别列。细则见 [features/order-delivery-reply/demand.md](features/order-delivery-reply/demand.md)。
|
||||
|
||||
定时提醒(2026-09-21 增补):07:00 同步成功后企微提醒生管查看当天回复(收件人=排程通知人配置);新日批 07:10 提醒排程——已回复行按回复交期提前 N 天(默认 3)提醒对应业务员出货,超 N 天(默认 3)未回复的行再次提醒生管;天数与生管收件人都在管理端排程表单配置,不新增配置页面。
|
||||
|
||||
## 可配置权限组(2026-09)
|
||||
|
||||
- 每位用户只选一个权限组(角色包);角色 = 可用应用入口 + 应用内能力。部门只用于选人筛选,不自动授权。
|
||||
@@ -467,6 +473,7 @@
|
||||
|
||||
## 4. 业务角色
|
||||
|
||||
|
||||
| 角色 | 说明 |
|
||||
| -------------------- | -------------------------------------------------------------------------------------------------------------- |
|
||||
| 管理员 | 平台管理员,默认拥有所有功能权限,包括设备台账配置和维修记录维护 |
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
| 域 | 说明 | 入口 |
|
||||
| --- | --- | --- |
|
||||
| [shipping-notice](shipping-notice/README.md) | 货代发货通知 Agent | [technical.md](shipping-notice/technical.md) · [客户识别规则改造方案](shipping-notice/customer_identity_rules_plan.md) |
|
||||
| [order-delivery-reply](order-delivery-reply/README.md) | 订单交期回复 Agent | [需求说明](order-delivery-reply/demand.md) · [技术设计](order-delivery-reply/technical-design.md) · [原型 v4](order-delivery-reply/order-delivery-reply-prototype.html) |
|
||||
| [in-transit-transfer](in-transit-transfer/) | 在途仓自动调拨 Agent | [开发部门需求与原型评审包](in-transit-transfer/mvp-requirements-and-prototype-review-pack.md) · [来源实例 Lean UX Canvas](in-transit-transfer/mvp-source-instance-lean-ux-canvas.md) · [可点击原型](../platform/in-transit-transfer-source-instance-mvp.html) · [PRD](in-transit-transfer/prd.md) · [路线图](in-transit-transfer/roadmap.md) · [完整规格](in-transit-transfer/minimum-implementation-spec.md) · [一期 TDD](in-transit-transfer/in-transit-transfer-tdd.md) · [运维手册](in-transit-transfer/technical.md) |
|
||||
| [auth](auth/README.md) | Casdoor 登录与产品内平级服务无感登录 | [hxops-peer-service-sso.md](auth/hxops-peer-service-sso.md) |
|
||||
| [shipping-notice](shipping-notice/README.md) | 货代发货通知 Agent | [technical.md](shipping-notice/technical.md) · [原型](shipping-notice/shipping_notice_agent_prototype.md) |
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# 订单交期回复(order-delivery-reply)
|
||||
|
||||
| 文档 | 读者 | 路径 |
|
||||
| --- | --- | --- |
|
||||
| **需求说明** | 产品、业务、测试、研发 | [demand.md](demand.md) |
|
||||
| **技术设计** | 研发 | [technical-design.md](technical-design.md) |
|
||||
| **原型 v4** | 产品、业务、测试 | [order-delivery-reply-prototype.html](order-delivery-reply-prototype.html) |
|
||||
|
||||
**定位**:工作台型 Agent。生管按 ERP 销售订单行回复交期(可拆多批次),经企业微信通知对应业务员后行级锁定,形成可审计记录。
|
||||
|
||||
**要解决的问题**:交期目前靠线下沟通,缺少按「订单单号:项次」落库的回复、通知与锁定事实。
|
||||
|
||||
**一期形态**:独立菜单页「订单交期回复」;只读 ERP,不回写;不做 Chat 对话,不做已锁定行的纠正 / 解锁。
|
||||
|
||||
**状态**:需求 v0.9、技术设计 v1.0(2026-09-21)。一期同步全部合格订单,不做单别白名单管理(后期再加)。企微复用平台 `send_wecom_event_message`。操作权限按用户功能权限(`manage` / `access`)。操作页不出单别列。原型已去掉订单类型 / 已转请购 / 排定交货日;联合回复只保存,另用批量通知。
|
||||
|
||||
**2026-09-21 增补**:① 07:00 到期排程在开发环境由 Web 进程内兜底扫描触发(生产走 schedule-worker 容器);② 同步成功后按排程通知配置企微提醒生管;③ 新增日批 07:10 提醒排程——已回复行按回复交期提前 N 天提醒业务员出货、超 N 天未回复再次提醒生管,天数可配、两类提醒可独立启停(排程任务参数);④ 工作台列顺序按业务指定调整,产品编号+品名、业务员+部门合并为上下两行展示(以 demand.md §8 修订为准)。
|
||||
|
||||
**实现状态**:见 [funclist.md](../../funclist.md)(已实现)。
|
||||
@@ -0,0 +1,328 @@
|
||||
# 订单交期回复 — 需求说明
|
||||
|
||||
| 项目 | 说明 |
|
||||
|------|------|
|
||||
| 版本 | v0.9(2026-09-21;§8 列顺序与合并展示修订、§13.1 定时提醒增补、§15 兜底触发说明) |
|
||||
| 状态 | 已拍板,可按本文与技术设计实现 |
|
||||
| 形态 | 工作台独立页;聊天侧栏/首页提供跳转入口(R-ENTRY-02),不做对话式填写 |
|
||||
| 关联 | [原型](order-delivery-reply-prototype.html) · [技术设计](technical-design.md) |
|
||||
|
||||
---
|
||||
|
||||
## 1. 背景与目标
|
||||
|
||||
### 1.1 背景
|
||||
|
||||
销售订单交期目前由生管与业务员线下沟通,缺少按「订单行」落库的回复记录,也无法证明何时通知、谁回复、是否已锁定。ERP(鼎捷 `axmt410`)保存约定交货日与已交数量,但不承担「生管承诺交期 → 通知业务 → 锁定」这条协作链。
|
||||
|
||||
### 1.2 目标
|
||||
|
||||
1. 生管按 ERP 销售订单行回复交期,允许拆成多个「交期 + 数量 + 备注」批次。
|
||||
2. 通过企业微信通知该订单对应业务员;通知成功后行级锁定。
|
||||
3. 具备只读权限的业务人员可查看回复结果;企微回执仅留痕,不改变交期回复状态。
|
||||
4. 形成可审计记录:谁在何时对哪一行发送了通知并锁定。
|
||||
|
||||
### 1.3 成功标准
|
||||
|
||||
- 生管可在系统内完成「查单 → 填交期 → 通知业务 → 锁定」。
|
||||
- 任意一行的批次、状态、是否锁定、回复人员可在工作台直接看到。
|
||||
- 已锁定行不能再改批次;纠正 / 解锁本期不做。
|
||||
|
||||
---
|
||||
|
||||
## 2. 范围
|
||||
|
||||
### 2.1 本期范围
|
||||
|
||||
| 编号 | 能力 |
|
||||
|------|------|
|
||||
| R-ENTRY-01 | 工作台独立操作页「订单交期回复」(直链 `/workspace/order-delivery-reply`;不在工作台侧栏货代分组下设置菜单) |
|
||||
| R-ENTRY-02 | 以**独立应用**形态接入应用管理:注册一条 `runtime_provider='iframe'`、`iframe_url=/apps/order-delivery-reply` 的 Agent(不接 Dify);出现在应用管理与全部应用/聊天侧栏列表,点击在聊天壳内整页打开操作页。可见性走 Agent 权限(admin 自动可见,普通用户在用户管理授权);页面与 API 仍受 `access`/`manage` 功能权限守卫 |
|
||||
| R-DATA-01 | 只读同步已审核、已核准、未结案的全部合格 ERP 订单行到本地库,不回写 ERP |
|
||||
| R-LIST-01 | 组合查询 + 重置;默认排序;空结果提示 |
|
||||
| R-LIST-02 | 行唯一键 `订单单号:项次`;全选三态 |
|
||||
| R-REPLY-01 | 单行回复 / 修改:弹窗维护批次 |
|
||||
| R-REPLY-02 | 勾选多行「联合回复交期」:只保存批次,不自动通知 |
|
||||
| R-NOTIFY-02 | 工具栏「批量通知」:对已勾选且已填批次、未锁定的行发送通知并锁定(唯一通知入口) |
|
||||
| R-NOTIFY-04 | 每天 07:00 排程同步成功后企微提醒生管查看当天交期回复;收件人=排程任务通知人配置(2026-09-21 增补) |
|
||||
| R-NOTIFY-05 | 每日提醒排程(07:10):已回复行按回复交期提前 N 天(默认 3)提醒对应业务员出货;超 N 天(默认 3)未回复的行再次提醒生管;天数可配、两类提醒可独立启停、生管收件人可配(2026-09-21 增补,详见 §13.1) |
|
||||
| R-STATUS-01 | 行上仍分未回复 / 部分回复 / 已回复(已回复 = 已通知并锁定);筛选选项为已回复、未完全回复(含未回复+部分回复) |
|
||||
| R-NOTIFY-01 | 通知统一走工具栏「批量通知」(行内不再提供发送按钮);成功后行级锁定,行内列显示已通知对象与时间 |
|
||||
| R-NOTIFY-03 | 交期回复人员 = 最近一次发送成功的生管工号 + 姓名 |
|
||||
| R-AUDIT-01 | 发送通知与锁定记入审计 |
|
||||
| R-RBAC-01 | 用户功能权限:`manage` 生管可写,`access` 业务只读;可选按部门批量发放勾选 |
|
||||
|
||||
### 2.2 非本期范围
|
||||
|
||||
- 纠正已锁定交期、解锁、作废通知
|
||||
- 回写 ERP;对话式填交期(在 Chat 对话中直接填写/修改批次——区别于 R-ENTRY-02 的跳转入口)
|
||||
- 邮件通知;撤回已发企微
|
||||
- 回执改变交期回复状态
|
||||
- **订单类型列、已转请购 / 已转采购、排定交货日**(已取消,不上操作页列表)
|
||||
- 工作台单别列
|
||||
- **单别白名单管理配置**(R-ADM-01,后期再做;一期默认同步全部合格订单)
|
||||
- 每次请求按部门名称判定操作权限(已废止)
|
||||
- 本 Agent 自绘企微卡片样式 / 按钮 / 模板卡片
|
||||
- 原型 v2 左侧统计侧栏
|
||||
|
||||
---
|
||||
|
||||
## 3. 角色与权限
|
||||
|
||||
操作权限按 **HXOPS 用户功能权限** 判定,不按所属部门名称每次比对。不新增系统角色。
|
||||
|
||||
| 身份 | 如何判定 | 权限 |
|
||||
| --- | --- | --- |
|
||||
| 生管 | 用户勾选 `order_delivery_reply.manage` | 查看已同步订单;回复;单行/批量通知;手动同步 |
|
||||
| 业务 | 用户勾选 `order_delivery_reply.access`(无 `manage`) | 查看已同步订单;只读 |
|
||||
| 未授权 | 两键均未勾选 | 无入口、无 API |
|
||||
| 平台管理员 | `admin` 角色默认两键均开 | 等同生管;可在用户管理勾选或按部门批量发放 |
|
||||
|
||||
`manage` 同时视为有 `access`。权限在用户管理勾选,与合同付款预警 `contract_payment.access` 同一机制。人多时管理员可按部门一次性把勾选写到该部门成员账号上;此后仍以用户勾选为准,调岗不会自动改权限。
|
||||
|
||||
企微通知对象仍是订单业务员,与工作台操作权限无关。有权进入的人看已同步全量,不按「是否本人的单」裁行。
|
||||
|
||||
---
|
||||
|
||||
## 4. 术语
|
||||
|
||||
| 术语 | 含义 |
|
||||
|------|------|
|
||||
| 订单行 | ERP 销售订单单身一行,唯一键 `订单单号:项次` |
|
||||
| 未交数量 | `数量 − 已交数量` |
|
||||
| 已回复数量 | 已保存各批次数量之和 |
|
||||
| 批次 | 计划交期 + 数量 + 可选备注 |
|
||||
| 锁定 | 该行通知成功后不可再改批次 |
|
||||
| 交期回复人员 | 最近一次发送通知成功的生管:工号 + 真实姓名 |
|
||||
| 客户简称 / 公司全名 | `OCC_FILE.occ02` / `occ18`,展示在客户编号旁 |
|
||||
| 单别 | 订单单号连字符前的编码(如 `8301` 外销)。一期列表不出此列、无管理勾选;后期可用白名单约束同步 |
|
||||
|
||||
---
|
||||
|
||||
## 5. 业务流程
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
syncJob[每天07:00或手动同步ERP] --> showList[工作台列表]
|
||||
showList --> fillReply[生管单行或联合填写并保存批次]
|
||||
fillReply --> notifyBiz[行内通知或批量通知]
|
||||
notifyBiz --> lockRow[该行锁定且状态为已回复]
|
||||
lockRow --> receipt[业务员企微回执仅留痕]
|
||||
```
|
||||
|
||||
- 保存批次与发送通知是两步。联合回复保存后**不**自动通知。
|
||||
- 未锁定前可反复修改批次。
|
||||
- 不回写 ERP。
|
||||
|
||||
---
|
||||
|
||||
## 6. 数据来源与字段
|
||||
|
||||
### 6.1 写边界
|
||||
|
||||
订单事实只读 ERP。批次、状态、锁定、通知、审计只存在于 HXOPS。禁止对 ERP 做 INSERT / UPDATE / DELETE。
|
||||
|
||||
### 6.2 关联
|
||||
|
||||
- `oea01 = oeb01`
|
||||
- `oeb04 = ima01` 且 `oeb06 = ima02`
|
||||
- `oea03 = occ01`(对照表曾写 `ooc01`,按客户主档主键 `occ01`)
|
||||
- `oea14 = gen01`(业务员姓名)
|
||||
- `oea15 = gem01`(部门名称)
|
||||
|
||||
### 6.3 展示字段
|
||||
|
||||
| 展示名 | 取值列 | 表 |
|
||||
| --- | --- | --- |
|
||||
| 订单单号 | `oea01` | `HXJM.OEA_FILE` |
|
||||
| 订单日期 | `oea02` | `HXJM.OEA_FILE` |
|
||||
| 客户编号 | `oea03` / `occ01` | `OEA_FILE` / `OCC_FILE` |
|
||||
| 客户简称 | `occ02` | `HXJM.OCC_FILE` |
|
||||
| 公司全名 | `occ18` | `HXJM.OCC_FILE` |
|
||||
| 业务员 | 编码 `oea14`,名称 `gen02` | `OEA_FILE` / `GEN_FILE` |
|
||||
| 部门 | 编码 `oea15`,名称 `gem02` | `OEA_FILE` / `GEM_FILE` |
|
||||
| 客户订单 | `oea10` | `OEA_FILE` |
|
||||
| 项次 | `oeb03` | `OEB_FILE` |
|
||||
| 产品编号 | `oeb04` | `OEB_FILE` |
|
||||
| 品名 | `oeb06` | `OEB_FILE` |
|
||||
| 规格 | `ima021` | `IMA_FILE` |
|
||||
| 客户产品编号 | `oeb11` | `OEB_FILE` |
|
||||
| 约定交货日 | `oeb15` | `OEB_FILE` |
|
||||
| 单位 | `oeb05` | `OEB_FILE` |
|
||||
| 数量 | `oeb12` | `OEB_FILE` |
|
||||
| 已交数量 | `oeb24` | `OEB_FILE` |
|
||||
|
||||
派生:`订单单号:项次`、未交数量(仅内部计算,列表不再展示已交/未交两列)、交期回复状态、批次、通知、交期回复人员。
|
||||
|
||||
列表**不展示**:订单类型、单别、已转请购 / 已转采购、排定交货日。一期无单别管理勾选。
|
||||
|
||||
### 6.4 同步范围
|
||||
|
||||
只同步同时满足的订单行:
|
||||
|
||||
- 已审核:`oeaconf = 'Y'`
|
||||
- 已核准:`oea49 = '1'`
|
||||
- 未结案:`oeb70` 结案否为 N(`NVL(oeb70, 'N') = 'N'`)
|
||||
- 完全未交:已交数量为 0(`NVL(oeb24, 0) = 0`,2026-09-17 增补——已有交货的行不再进入同步与列表)
|
||||
|
||||
一期**不按单别过滤**,上述条件命中的订单行全部同步。
|
||||
|
||||
本地已有批次或已锁定、但本轮 ERP 不再命中的行:保留不删,标记为 ERP 已不在同步范围,默认列表不展示。
|
||||
|
||||
---
|
||||
|
||||
## 7. 查询与列表
|
||||
|
||||
筛选(AND):**关键词**(合并搜索:订单单号/客户订单/客户编号/客户简称/公司全名/产品编号/品名/客户产品编号/业务员(姓名、工号)/交期回复人员(姓名、工号)命中任一即返回;2026-09-21 由三个独立搜索框合并,2026-09-23 增补人员搜索)、订单日期(单日)、交期回复状态。
|
||||
|
||||
交期回复状态筛选项:
|
||||
|
||||
| 选项 | 包含的行状态 |
|
||||
| --- | --- |
|
||||
| 全部 | 不限 |
|
||||
| 已回复 | 已通知并锁定 |
|
||||
| 未完全回复 | 未回复 + 部分回复(尚未通知锁定) |
|
||||
|
||||
列表行上仍用未回复(红)/ 部分回复(橙)/ 已回复(绿)徽标,不把「未完全回复」画成第四种行状态。
|
||||
|
||||
工作台列出当前已同步且未标「已不在同步范围」的行。一期不按单别裁行。
|
||||
|
||||
默认排序:订单日期 → 客户编号 → 订单单号 → 项次 / 产品编号,升序。分页默认 50。
|
||||
|
||||
全选作用于当前筛选结果的**本页**。未勾选时「联合回复交期」「批量通知」不可用。
|
||||
|
||||
---
|
||||
|
||||
## 8. 列表列
|
||||
|
||||
(2026-09-21 修订列顺序与合并展示,按业务指定顺序;独立「部门」「品名」列取消,与业务员/产品编号合并为上下两行展示,样式同客户编号+简称。)
|
||||
|
||||
1. 勾选
|
||||
2. 客户编号(副文案:客户简称;可悬停看公司全名)
|
||||
3. 订单日期
|
||||
4. 订单单号:项次
|
||||
5. 产品编号(副文案:品名)
|
||||
6. 客户产品编号
|
||||
7. 数量
|
||||
8. 约定交货日
|
||||
9. 交期回复状态
|
||||
10. 交期回复
|
||||
11. 交期回复人员(锁定行在姓名下附带「已通知 {业务员} + 时间」;原「通知业务部门」列已取消)
|
||||
12. 业务员(显示姓名;副文案:部门名称)
|
||||
13. 客户订单
|
||||
14. 规格
|
||||
15. 单位
|
||||
|
||||
(2026-09-17 增补同步条件 `NVL(oeb24,0)=0` 后,「已交数量 / 未交数量」两列信息量归零,已取消展示;数量与未交口径仍由后端派生,供回复弹窗数量守恒校验使用。)
|
||||
|
||||
不增加单别列。一期无单别管理勾选。
|
||||
|
||||
交期回复:无批次显示「回复交期」;有批次可展开;未锁定可「修改回复」;已锁定显示「交期已锁定」。
|
||||
|
||||
通知:列已取消(行内不设发送按钮);发送统一走工具栏「批量通知」;已通知对象与时间并入「交期回复人员」列展示。
|
||||
|
||||
---
|
||||
|
||||
## 9. 显示规则
|
||||
|
||||
- (2026-09-23 修订)回复弹窗**数量守恒**:每行各批次填写合计必须**等于订单数量**才能保存——弹窗内实时红字提示已填合计、保存时拦截,后端 422(`BATCH_QTY_TOTAL_MISMATCH`)兜底;原「超额显示『超』,不拦截保存」废止。列表行「超」标记仅对历史超额数据展示。
|
||||
- 状态:未回复红、部分回复橙、已回复绿;保存或通知后即时刷新。
|
||||
|
||||
---
|
||||
|
||||
## 10. 单行回复
|
||||
|
||||
弹窗维护 1..N 批:交期必填有效日期,数量 > 0,备注 ≤ 200;各批次数量合计必须等于订单数量,否则不能保存(2026-09-23 增补);已填批次的交期/数量缺填、同一订单单号:项次的不同批次交期重复,均实时提示并随填写内容切换(2026-09-23 增补;交期重复后端 BATCH_INVALID 既有校验)。可增删批次,可快速统一交期。锁定行不可编辑。行上徽标展示「订单数量:X 单位」(2026-09-23 由「未交 X」改来)。
|
||||
|
||||
---
|
||||
|
||||
## 11. 联合回复与批量通知
|
||||
|
||||
1. 勾选多行 →「+ 联合回复交期」→ 按行填批次 → **保存回复**(只写批次,不通知、不锁定);每行各批次合计必须等于订单数量,不等的行按行保存失败(2026-09-23 增补)。
|
||||
2. 工具栏另设「批量通知」:对当前勾选中「已有批次且未锁定」的行逐行发送通知并锁定。
|
||||
3. 无批次或已锁定的勾选行跳过;全部失败则提示,部分成功则成功行锁定、失败行保持未锁定。
|
||||
4. 行内不再提供发送按钮,通知统一走工具栏「批量通知」,单行/锁定/失败规则相同。
|
||||
|
||||
---
|
||||
|
||||
## 12. 状态机
|
||||
|
||||
| 状态 | 判定 |
|
||||
| --- | --- |
|
||||
| 未回复 | 无任何已保存批次 |
|
||||
| 部分回复 | 已有批次,尚未通知锁定 |
|
||||
| 已回复 | 已发送通知并锁定 |
|
||||
|
||||
已回复**必须**已通知锁定。批次数量是否盖住未交、未交是否为 0,都不单独变成已回复。
|
||||
|
||||
筛选「未完全回复」= 上表未回复 ∪ 部分回复。
|
||||
|
||||
---
|
||||
|
||||
## 13. 通知与锁定
|
||||
|
||||
- 渠道:企业微信;**复用平台既有通知**(`send_wecom_event_message`),不单独做卡片样式/按钮/模板。
|
||||
- 接收人:该订单业务员(`oea14` 对应 HXOPS `User.employee_id`,再取 `wecom_userid`)。对得上。匹配失败则该行通知失败、不锁定。
|
||||
- 正文参数:`您有订单号:项次{订单单号}:{项次}的订单需要填写/确认/查看交期。`(只作 content,卡片壳走平台。)
|
||||
- 发送成功后行级锁定;失败不锁定。
|
||||
- 回执走既有企微审计,只留痕,不改状态。
|
||||
|
||||
### 13.1 定时提醒(2026-09-21 增补)
|
||||
|
||||
| 提醒 | 触发 | 收件人 | 天数配置 |
|
||||
| --- | --- | --- | --- |
|
||||
| 同步完成提醒 | 每天 07:00 排程同步成功后 | 生管(任务参数「同步完成提醒收件人」,可从全部用户搜索选择;留空回退「通知人」) | — |
|
||||
| 出货提醒 | 已回复行的回复交期距今 ≤ N 天 | 对应订单业务员(按人聚合成一条) | 默认 3,排程任务参数可配 |
|
||||
| 未回复再提醒 | 订单日期距今超 N 天仍未回复(同一行每 N 天最多提醒一次;2026-09-23 明确以 ERP 订单日期计超期,非入库时间) | 生管(任务参数「未回复提醒收件人」,按收件人聚合成一条) | 默认 3,排程任务参数可配 |
|
||||
|
||||
实现:新排程 `order-delivery-remind`(日批 07:10,紧随同步)。天数在管理端排程表单「任务参数」修改(`ship_remind_advance_days` / `unreplied_remind_days`);两类提醒由任务参数 `ship_remind_enabled` / `unreplied_remind_enabled`(布尔,默认开)**独立启停**;生管收件人在排程表单「任务参数 → 未回复提醒收件人(生管)」多选配置(候选=全部启用用户,支持按姓名/工号/部门搜索;留空回退「通知人」兼容旧配置)——与平台运行结果通知的「通知人」**互相独立**(2026-09-22 增补,两类通知人分离)。出货提醒同一(行,交期)只发一次,发送失败次日自动补发;两类提醒逐行写审计(`ship_remind` / `unreplied_remind`),只读业务数据、不改批次/锁定。
|
||||
|
||||
---
|
||||
|
||||
## 14. 审计
|
||||
|
||||
记录保存批次、发送通知、锁定、同步。字段:操作人、时间、动作、订单单号、项次、必要快照。
|
||||
|
||||
---
|
||||
|
||||
## 15. 非功能
|
||||
|
||||
- 每天 **Asia/Shanghai 07:00** 自动全量同步,生管可手动全量刷新。页面展示最近同步时间。(2026-09-29 更新:到期排程由独立 worker 进程 `workers/worker_scheduler.py` / 生产 `hxops-schedule-worker` 容器执行;合并 dev 主线后 Web 进程不再兜底扫描,本地需另起 worker 进程。)
|
||||
- 通知成功与锁定同一事务,禁止「已通知未锁定」。
|
||||
- 正式产品四语言 i18n。
|
||||
|
||||
---
|
||||
|
||||
## 16. 已关闭的原开放问题
|
||||
|
||||
| 原编号 | 结论 |
|
||||
| --- | --- |
|
||||
| Q-01 | 已回复 = 已通知并锁定 |
|
||||
| Q-02 | 联合回复只保存;另用批量通知 |
|
||||
| Q-03 | 应用管理注册 iframe 应用(不接 Dify),聊天壳内整页打开操作页;不在货代发货通知下加菜单,不做对话式填写 |
|
||||
| Q-04 / Q-05 | 取消订单类型、已转请购、排定交货日 |
|
||||
| Q-07 / D-03 | `oea14` 能对上 HXOPS 工号 / 企微 |
|
||||
| Q-08 | 企微复用 `send_wecom_event_message`;正文参数见 §13,不单独定卡片样式 |
|
||||
| D-01 / D-02 | 已审核 `oeaconf='Y'` + 已核准 `oea49='1'` + 未结案 `oeb70='N'`;每天 07:00 + 手动 |
|
||||
| D-04 | 业务员、部门显示名称 |
|
||||
| D-07 | 操作权限用用户功能权限 `manage` / `access`;部门仅可选批量发放,不作每次请求的门禁 |
|
||||
| D-08 | 一期不按单别过滤、无单别管理配置,默认同步全部合格订单;后期再做白名单(方案 A:同步 WHERE + 新勾选增量同步;操作页始终不出单别列) |
|
||||
|
||||
---
|
||||
|
||||
## 17. 验收要点
|
||||
|
||||
1. 勾选 `manage` 可回复/通知/同步;仅 `access` 只读;两键都无则无入口。`admin` 默认可写。
|
||||
2. 列表无订单类型、单别、已转请购、排定交货日;列顺序按 §8(2026-09-21 修订):客户编号→订单日期→订单单号:项次→产品编号→客户产品编号→数量→约定交货日→交期回复状态→交期回复→交期回复人员→业务员→客户订单→规格→单位;产品编号与品名、业务员与部门均为上下两行合并展示(同客户编号+简称样式)。
|
||||
3. 同步范围:`oeaconf='Y'` 且 `oea49='1'` 且 `oeb70` 不为已结案;一期不按单别过滤;07:00 与手动刷新都可跑;到期排程由独立 worker 进程触发(2026-09-29 合并 dev 主线,Web 进程不再兜底扫描)。
|
||||
4. 一期无单别白名单管理页;列表不出单别列。
|
||||
5. 状态筛选仅「全部 / 已回复 / 未完全回复」;未完全回复同时命中未回复与部分回复。
|
||||
6. 无批次 = 未回复,不能通知。
|
||||
7. 有批次未通知 = 部分回复,可修改。
|
||||
8. 通知成功 = 已回复且锁定,不能再改批次。
|
||||
9. 联合回复保存后仍是部分回复(属未完全回复);点批量通知成功后才锁定。
|
||||
10. 企微走平台既有通知;正文为「您有订单号:项次{单号}:{项次}的订单需要填写/确认/查看交期。」;不自绘卡片。
|
||||
11. 通知失败不锁定;回执不改状态。
|
||||
12. 不写 ERP。
|
||||
13. (2026-09-21)07:00 同步成功后按排程通知配置提醒生管;发送失败不影响同步结果,且不重复收到通用「排程执行结果」通知。
|
||||
14. (2026-09-21)已回复行交期前 N 天业务员收到出货提醒,同一(行,交期)只提醒一次、发送失败次日补发;超 N 天未回复的行每 N 天再次提醒生管;两类提醒可在排程任务参数中独立启停、天数可改。
|
||||
@@ -0,0 +1,732 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta http-equiv="Cache-Control" content="no-store, no-cache, must-revalidate" />
|
||||
<meta http-equiv="Pragma" content="no-cache" />
|
||||
<title>交期回复 - 原型设计</title>
|
||||
<style>
|
||||
:root{
|
||||
--primary:#1677ff;
|
||||
--primary-hover:#0958d9;
|
||||
--primary-weak:#e6f0ff;
|
||||
--primary-weak2:#f0f6ff;
|
||||
--bg:#eef2f8;
|
||||
--card:#ffffff;
|
||||
--border:#e3e9f2;
|
||||
--border-strong:#d5dce8;
|
||||
--text:#1f2329;
|
||||
--muted:#86909c;
|
||||
--ok:#18a058;
|
||||
--ok-weak:#e8f6ee;
|
||||
--warn:#fa8c16;
|
||||
--warn-weak:#fff3e6;
|
||||
--danger:#f53f3f;
|
||||
--danger-weak:#fdeaea;
|
||||
--brand-weak:#eef2ff;
|
||||
--brand:#4338ca;
|
||||
--radius:12px;
|
||||
--radius-s:7px;
|
||||
--shadow:0 1px 2px rgba(16,24,40,.04),0 6px 18px rgba(16,24,40,.05);
|
||||
}
|
||||
*{box-sizing:border-box}
|
||||
html,body{height:100%}
|
||||
body{
|
||||
margin:0;background:var(--bg);color:var(--text);
|
||||
font-family:"Segoe UI","Microsoft YaHei",system-ui,-apple-system,sans-serif;
|
||||
font-size:13px;
|
||||
}
|
||||
.app{display:flex;flex-direction:column;height:100vh}
|
||||
|
||||
/* ===== Top bar (图4 light header) ===== */
|
||||
header.topbar{
|
||||
background:#fff;padding:12px 22px;display:flex;align-items:center;gap:12px;
|
||||
border-bottom:1px solid var(--border);flex-wrap:wrap;
|
||||
}
|
||||
.tb-badge{background:var(--primary);color:#fff;font-weight:700;font-size:13px;padding:5px 12px;border-radius:8px;letter-spacing:.5px}
|
||||
header.topbar h1{font-size:16px;margin:0;font-weight:700;color:var(--text)}
|
||||
header.topbar .sub{font-size:12px;color:var(--muted)}
|
||||
header.topbar .spacer{flex:1}
|
||||
.tb-hint{font-size:11px;color:var(--primary);background:var(--primary-weak);padding:4px 11px;border-radius:14px}
|
||||
|
||||
/* ===== Rules note ===== */
|
||||
.ruleband{
|
||||
background:var(--primary-weak2);border-bottom:1px solid var(--border);padding:9px 22px;
|
||||
font-size:11.5px;color:var(--muted);
|
||||
}
|
||||
.ruleband b{color:var(--text)}
|
||||
.ruleband .sep{color:var(--border-strong);margin:0 8px}
|
||||
.ruleband .dotcolor{display:inline-block;width:8px;height:8px;border-radius:50%;margin-right:4px;vertical-align:middle}
|
||||
|
||||
/* ===== Search ===== */
|
||||
.searchbar{
|
||||
background:var(--card);margin:14px 22px 0;border:1px solid var(--border);border-radius:var(--radius);
|
||||
box-shadow:var(--shadow);padding:14px 16px;
|
||||
display:flex;flex-wrap:wrap;align-items:flex-end;gap:14px;
|
||||
}
|
||||
.field{display:flex;flex-direction:column;gap:5px}
|
||||
.field label{font-size:11px;color:var(--muted)}
|
||||
.field input,.field select{
|
||||
height:34px;padding:0 11px;border:1px solid var(--border-strong);border-radius:var(--radius-s);
|
||||
font-size:13px;min-width:168px;outline:none;background:#fff;color:var(--text);
|
||||
}
|
||||
.field input:focus,.field select:focus{border-color:var(--primary);box-shadow:0 0 0 2px var(--primary-weak)}
|
||||
.btn{
|
||||
height:34px;padding:0 15px;border-radius:var(--radius-s);border:1px solid var(--border-strong);
|
||||
background:#fff;color:var(--text);cursor:pointer;font-size:13px;white-space:nowrap;
|
||||
display:inline-flex;align-items:center;gap:6px;transition:.15s;
|
||||
}
|
||||
.btn:hover{background:#f5f8fd;border-color:var(--primary)}
|
||||
.btn.primary{background:var(--primary);border-color:var(--primary);color:#fff}
|
||||
.btn.primary:hover{background:var(--primary-hover)}
|
||||
.btn.ghost{border-color:transparent;background:transparent;color:var(--muted)}
|
||||
.btn:disabled{opacity:.45;cursor:not-allowed}
|
||||
.btn.sm{height:27px;padding:0 10px;font-size:12px;border-radius:6px}
|
||||
.searchbar .spacer{flex:1}
|
||||
.searchbar .count{font-size:12px;color:var(--muted)}
|
||||
|
||||
/* ===== Layout ===== */
|
||||
.main{flex:1;display:flex;min-height:0;margin:14px 22px 0;padding-bottom:14px}
|
||||
|
||||
/* ===== Sidebar ===== */
|
||||
|
||||
/* ===== Content / toolbar ===== */
|
||||
section.content{flex:1;display:flex;flex-direction:column;min-width:0;min-height:0}
|
||||
.toolbar{
|
||||
background:var(--card);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow);
|
||||
padding:11px 16px;display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:12px;
|
||||
}
|
||||
.toolbar .sel-count{font-size:13px;color:var(--muted)}
|
||||
.toolbar .sel-count b{color:var(--primary)}
|
||||
.toolbar .spacer{flex:1}
|
||||
.toolbar .mutually{font-size:11px;color:var(--muted);background:#f4f7fb;padding:4px 10px;border-radius:14px}
|
||||
|
||||
/* ===== 单层横向订单产品表 ===== */
|
||||
.tablewrap{flex:1;overflow:auto;min-width:0;min-height:0;background:var(--card);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow)}
|
||||
.master-table{width:100%;border-collapse:collapse;min-width:2500px}
|
||||
.master-table thead th{
|
||||
position:sticky;top:0;background:#f7fafe;color:var(--muted);font-weight:600;font-size:12px;
|
||||
padding:9px 10px;text-align:left;border-bottom:1px solid var(--border);white-space:nowrap;z-index:2;
|
||||
}
|
||||
.order-row:hover td{background:#f7fafe}
|
||||
.order-row td{padding:9px 10px;border-bottom:1px solid var(--border);white-space:nowrap;font-variant-numeric:tabular-nums}
|
||||
.cell-sub{font-size:11px;color:var(--muted);font-weight:400}
|
||||
.master-table tbody tr.selected{background:var(--primary-weak)}
|
||||
.pill{display:inline-block;padding:2px 10px;border-radius:14px;font-size:11px;font-weight:600;line-height:1.6;white-space:nowrap}
|
||||
.pill.brand{background:var(--brand-weak);color:var(--brand)}
|
||||
.pill.ok{background:var(--ok-weak);color:var(--ok)}
|
||||
.pill.warn{background:var(--warn-weak);color:var(--warn)}
|
||||
.pill.danger{background:var(--danger-weak);color:var(--danger)}
|
||||
.ph-mid{flex:1;min-width:200px}
|
||||
.ph-no{font-size:14px;font-weight:700;font-variant-numeric:tabular-nums}
|
||||
.ph-no em{font-style:normal;font-weight:400;color:var(--muted);font-size:12px;margin-left:8px}
|
||||
.ph-sub{font-size:11.5px;color:var(--muted);margin-top:3px}
|
||||
.ph-sub b{color:var(--text);font-weight:600}
|
||||
.ph-agg{display:flex;align-items:center;gap:14px;flex-wrap:wrap}
|
||||
.agg{text-align:right}
|
||||
.agg span{display:block;font-size:10.5px;color:var(--muted)}
|
||||
.agg b{font-size:15px;font-variant-numeric:tabular-nums;font-weight:700}
|
||||
.agg b.ok{color:var(--ok)}
|
||||
.agg b.warn{color:var(--warn)}
|
||||
.agg b.muted{color:var(--muted)}
|
||||
|
||||
.num{text-align:right}
|
||||
.num.ok-num{color:var(--ok);font-weight:700}
|
||||
.remain-orange{color:var(--warn);font-weight:700}
|
||||
.remain-gray{color:var(--muted)}
|
||||
.mono{font-family:Consolas,"Courier New",monospace;font-size:12px;color:#0f172a}
|
||||
|
||||
/* ===== Custom checkbox (图1/图2) ===== */
|
||||
.cx{position:relative;display:inline-flex;align-items:center;cursor:pointer;padding:3px 2px}
|
||||
.cx input{position:absolute;opacity:0;width:18px;height:18px;margin:0;cursor:pointer}
|
||||
.cx-box{width:18px;height:18px;border:1.5px solid var(--border-strong);border-radius:4px;background:#fff;position:relative;transition:.15s;flex-shrink:0}
|
||||
.cx:hover .cx-box{border-color:var(--primary)}
|
||||
.cx-box::after{
|
||||
content:"";position:absolute;left:5px;top:2px;width:5px;height:9px;
|
||||
border:solid #fff;border-width:0 2px 2px 0;transform:rotate(45deg);opacity:0;transition:opacity .12s;
|
||||
}
|
||||
.cx input:checked + .cx-box{background:var(--primary);border-color:var(--primary)}
|
||||
.cx input:checked + .cx-box::after{opacity:1}
|
||||
.cx input:indeterminate + .cx-box{background:var(--primary);border-color:var(--primary)}
|
||||
.cx input:indeterminate + .cx-box::after{left:3px;top:7px;width:10px;height:2px;background:#fff;border:0;transform:none;opacity:1}
|
||||
.cx .cx-label{margin-left:7px;font-size:13px;color:var(--text)}
|
||||
.cx.cx-master .cx-label{font-weight:600}
|
||||
|
||||
/* ===== transfer text (plain) ===== */
|
||||
.transfer-txt{font-size:12px;color:var(--text)}
|
||||
.transfer-txt.none{color:var(--muted)}
|
||||
|
||||
/* ===== reply cell ===== */
|
||||
td.reply-cell{min-width:250px;max-width:300px}
|
||||
.rc{display:flex;flex-direction:column;gap:5px}
|
||||
.rc-top{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
|
||||
.rc-meta{font-size:11px;color:var(--muted);white-space:nowrap;border:1px solid var(--border);background:#f7fafe;border-radius:14px;padding:2px 9px}
|
||||
.rc-meta b{color:var(--text)}
|
||||
.rc-toggle{
|
||||
border:1px solid var(--border-strong);background:#fff;border-radius:14px;font-size:11px;
|
||||
color:var(--primary);cursor:pointer;padding:2px 9px;white-space:nowrap;
|
||||
}
|
||||
.rc-toggle:hover{border-color:var(--primary);background:var(--primary-weak)}
|
||||
.rc-list{display:flex;flex-direction:column;gap:3px}
|
||||
.rc-batch{
|
||||
font-size:11px;line-height:1.4;padding:3px 9px;background:var(--primary-weak2);border-left:3px solid var(--primary);
|
||||
border-radius:4px;white-space:normal;color:var(--text);
|
||||
}
|
||||
.rc-batch b{color:var(--primary)}
|
||||
.rc-batch i{color:var(--muted);font-style:normal;font-size:10.5px}
|
||||
.rc.folded .rc-list .rc-batch:not(:first-child){display:none}
|
||||
|
||||
.empty{padding:60px;text-align:center;color:var(--muted)}
|
||||
|
||||
/* ===== Modal ===== */
|
||||
.overlay{position:fixed;inset:0;background:rgba(15,42,91,.42);display:none;align-items:center;justify-content:center;z-index:50}
|
||||
.overlay.show{display:flex}
|
||||
.modal{
|
||||
background:#fff;width:min(960px,94vw);max-height:88vh;border-radius:14px;box-shadow:0 20px 60px rgba(0,0,0,.22);
|
||||
display:flex;flex-direction:column;overflow:hidden;
|
||||
}
|
||||
.modal .m-head{display:flex;align-items:center;gap:10px;padding:16px 20px;border-bottom:1px solid var(--border)}
|
||||
.modal .m-head h3{margin:0;font-size:15px}
|
||||
.modal .m-head .spacer{flex:1}
|
||||
.modal .m-body{flex:1;overflow:auto;padding:16px 20px}
|
||||
.modal .m-foot{padding:12px 20px;border-top:1px solid var(--border);display:flex;justify-content:flex-end;gap:10px;background:#fbfcfe}
|
||||
.close-x{border:none;background:transparent;font-size:20px;line-height:1;cursor:pointer;color:var(--muted)}
|
||||
.close-x:hover{color:var(--text)}
|
||||
|
||||
.quick-band{background:var(--primary-weak2);border:1px solid var(--border);border-radius:10px;padding:12px 14px;margin-bottom:16px;display:flex;gap:14px;flex-wrap:wrap;align-items:flex-end}
|
||||
.relay-item{border:1px solid var(--border);border-radius:11px;margin-bottom:14px;overflow:hidden}
|
||||
.relay-item .obj{padding:10px 12px;background:#f7fafe;display:flex;gap:8px;align-items:center;flex-wrap:wrap;font-size:12px}
|
||||
.relay-item .obj .k{color:var(--muted)}
|
||||
.relay-item .obj .tag{padding:2px 9px;border-radius:6px;background:var(--brand-weak);color:var(--brand);font-weight:600}
|
||||
.relay-item .obj .remain{margin-left:auto;font-size:12px}
|
||||
.relay-item .obj .remain b{color:var(--warn)}
|
||||
.relay-list{padding:6px 12px 12px}
|
||||
.relay-row{display:grid;grid-template-columns:170px 110px 1fr 90px 34px;gap:10px;align-items:center;padding:6px 0;border-bottom:1px dashed var(--border)}
|
||||
.relay-row:last-child{border-bottom:none}
|
||||
.relay-row input,.relay-row select{border:1px solid var(--border-strong);border-radius:7px;padding:7px 9px;font-size:12.5px;outline:none}
|
||||
.relay-row input:focus,.relay-row select:focus{border-color:var(--primary);box-shadow:0 0 0 2px var(--primary-weak)}
|
||||
.relay-row .r-remark{grid-column:3}
|
||||
.relay-row .del{background:var(--danger-weak);color:var(--danger);border:none;border-radius:7px;cursor:pointer;height:32px}
|
||||
.add-relay{border:1px dashed var(--border-strong);background:#fff;border-radius:8px;color:var(--primary);padding:8px;width:100%;cursor:pointer;font-size:12.5px;margin-top:8px}
|
||||
.add-relay:hover{border-color:var(--primary);background:var(--primary-weak2)}
|
||||
.relay-sum{float:right;font-size:12px;color:var(--muted)}
|
||||
.relay-sum b{color:var(--warn)}
|
||||
.warn-text{font-size:11px;color:var(--warn)}
|
||||
.ok-text{font-size:11px;color:var(--ok)}
|
||||
.err-text{font-size:11px;color:var(--danger)}
|
||||
|
||||
footer{background:transparent;padding:10px 22px 0;font-size:11px;color:var(--muted);display:flex;gap:20px;flex-wrap:wrap}
|
||||
footer b{color:var(--text)}
|
||||
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="app">
|
||||
|
||||
<header class="topbar">
|
||||
<span class="tb-badge">交期回复</span>
|
||||
<h1>订单交期回复</h1>
|
||||
<span class="sub">Order Delivery Reply · 多订单联合回复 + 单产品拆分交期分批回复</span>
|
||||
<span class="spacer"></span>
|
||||
<span class="tb-hint">原型 v5 | 未交=橙 | 已回复=已通知锁定 | 联合回复只保存</span>
|
||||
</header>
|
||||
|
||||
<!-- 业务口径说明 -->
|
||||
<div class="ruleband">
|
||||
<b>口径:</b>未交数量 = 数量 − 已交;未交 > 0 显<span class="dotcolor" style="background:var(--warn)"></span>橙色,未交 = 0 显<span class="dotcolor" style="background:var(--muted)"></span>灰色。
|
||||
<span class="sep">|</span>交期回复状态:未回复=<span class="dotcolor" style="background:var(--danger)"></span>红、部分回复=<span class="dotcolor" style="background:var(--warn)"></span>橙(已填未通知)、已回复=<span class="dotcolor" style="background:var(--ok)"></span>绿(已通知并锁定)。
|
||||
<span class="sep">|</span>联合回复只保存批次;勾选后点「批量通知」才发送并锁定。
|
||||
<span class="sep">|</span>拆分「交期+数量」允许超额,仅橙色提醒、不拦截保存。
|
||||
</div>
|
||||
|
||||
<!-- ============ 搜索区 ============ -->
|
||||
<div class="searchbar">
|
||||
<div class="field">
|
||||
<label>订单单号</label>
|
||||
<input id="qOrder" placeholder="输入订单单号,如 O20240601-001" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>产品编号 / 品名 / 客户料号</label>
|
||||
<input id="qProd" placeholder="输入产品编号、品名或客户产品编号" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>客户编号</label>
|
||||
<input id="qCust" placeholder="客户编号" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>订单日期</label>
|
||||
<input type="date" id="qOrderDate" title="按订单日期筛选" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>交期回复状态</label>
|
||||
<select id="qStatus">
|
||||
<option value="">全部</option>
|
||||
<option value="已回复">已回复</option>
|
||||
<option value="未完全回复">未完全回复</option>
|
||||
</select>
|
||||
</div>
|
||||
<button class="btn primary" onclick="doSearch()">查询</button>
|
||||
<button class="btn" onclick="doReset()">重置</button>
|
||||
<span class="spacer"></span>
|
||||
<span class="count">共 <b id="totalCount" style="color:var(--text)">0</b> 条产品行</span>
|
||||
</div>
|
||||
|
||||
<div class="main">
|
||||
|
||||
<!-- ============ 订单产品内容 ============ -->
|
||||
<section class="content">
|
||||
<div class="toolbar">
|
||||
<label class="cx cx-master" title="全选当前筛选结果">
|
||||
<input type="checkbox" id="chkAll" onchange="toggleAll(this)" />
|
||||
<span class="cx-box"></span><span class="cx-label">全选</span>
|
||||
</label>
|
||||
<span class="sel-count">已勾选 <b id="tbSel">0</b> 行</span>
|
||||
<button class="btn primary" id="btnBatch" onclick="openBatch()" disabled>+ 联合回复交期</button>
|
||||
<button class="btn primary" id="btnNotifyBatch" onclick="notifySelected()" disabled>批量通知</button>
|
||||
<span class="spacer"></span>
|
||||
<span class="mutually">勾选后可联合填写并保存;保存后点「批量通知」才发给业务员并锁定。</span>
|
||||
</div>
|
||||
|
||||
<div class="tablewrap">
|
||||
<table class="master-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width:44px"></th><th>订单单号:项次</th><th>订单日期</th><th>客户编号</th>
|
||||
<th>业务员</th><th>部门</th><th>客户订单</th><th>产品编号</th><th>品名</th><th>规格</th><th>客户产品编号</th>
|
||||
<th>约定交货日</th><th>单位</th><th class="num">数量</th><th class="num">已交数量</th><th class="num">未交数量</th>
|
||||
<th>交期回复状态</th><th>交期回复</th><th>通知业务部门</th><th>交期回复人员</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="masterBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="empty" id="emptyBox" style="display:none">没有符合条件的订单行</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<footer>
|
||||
<span>未交数量 = 数量 − 已交;待回复数量 = 未交数量 − 已回复数量。</span>
|
||||
<span>交期回复状态随保存即时更新;点击「N 批」可展开查看每批交期与备注。</span>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
<!-- ============ 联合/拆分 回复交期 弹窗 ============ -->
|
||||
<div class="overlay" id="overlay">
|
||||
<div class="modal">
|
||||
<div class="m-head">
|
||||
<h3 id="modalTitle">回复交期</h3>
|
||||
<span class="spacer"></span>
|
||||
<button class="close-x" onclick="closeModal()">×</button>
|
||||
</div>
|
||||
<div class="m-body">
|
||||
<div class="quick-band">
|
||||
<div class="field">
|
||||
<label>快速统一交期(应用到下方所有行)</label>
|
||||
<input type="date" id="quickDate" />
|
||||
</div>
|
||||
<button class="btn sm" onclick="applyQuickDate()">应用到全部</button>
|
||||
<div class="field" style="flex:1">
|
||||
<label>提示</label>
|
||||
<span style="font-size:11px;color:var(--muted)" id="quickHint">可为单个产品填 1 个交期,或点「+ 增加批次」拆成多个「交期 + 数量」;允许超额,仅提醒不拦截。</span>
|
||||
</div>
|
||||
</div>
|
||||
<div id="relayItems"></div>
|
||||
</div>
|
||||
<div class="m-foot">
|
||||
<span id="modalMsg" style="margin-right:auto;align-self:center;font-size:12px"></span>
|
||||
<button class="btn" onclick="closeModal()">取消</button>
|
||||
<button class="btn primary" onclick="saveReplies()">保存回复</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
/* ================= 演示数据:订单(含多个产品) ================= */
|
||||
const ORDERS = [
|
||||
{
|
||||
orderNo:"O20240601-001", orderDate:"2024-06-01",
|
||||
custNo:"C-0001", custName:"恒远电子", custFull:"恒远电子股份有限公司", sales:"王业务", dept:"华东一部", custOrder:"PO-1001",
|
||||
items:[
|
||||
{item:"10", prodNo:"P-1001", name:"驱动齿轮", spec:"M8", custProdNo:"A-GEAR-8", needDate:"2024-07-15", unit:"pcs", qty:1200, delivered:500, replies:[{planDate:"2024-07-15", qty:300, remark:"首批"},{planDate:"2024-07-30", qty:300, remark:""}]},
|
||||
{item:"20", prodNo:"P-1002", name:"连接器", spec:"2P", custProdNo:"A-CONN-2P", needDate:"2024-08-01", unit:"pcs", qty:800, delivered:800, replies:[{planDate:"2024-08-01", qty:800, remark:""}]},
|
||||
{item:"30", prodNo:"P-1005", name:"电机外壳", spec:"Φ60", custProdNo:"A-MOT-60", needDate:"2024-09-10", unit:"pcs", qty:300, delivered:0, replies:[{planDate:"2024-09-10", qty:200, remark:"分两批"}]}
|
||||
]
|
||||
},
|
||||
{
|
||||
orderNo:"O20240602-002", orderDate:"2024-06-02",
|
||||
custNo:"C-0002", custName:"Global Tech", custFull:"Global Tech Co.", sales:"李业务", dept:"华南二部", custOrder:"PO-2001",
|
||||
items:[
|
||||
{item:"10", prodNo:"P-1003", name:"传感器", spec:"12V", custProdNo:"B-SEN-12", needDate:"2024-07-30", unit:"set", qty:50, delivered:20, replies:[]},
|
||||
{item:"20", prodNo:"P-1008", name:"密封圈", spec:"NBR70", custProdNo:"B-SEAL-70", needDate:"2024-08-20", unit:"pcs", qty:5000, delivered:0, replies:[]}
|
||||
]
|
||||
},
|
||||
{
|
||||
orderNo:"O20240605-003", orderDate:"2024-06-05",
|
||||
custNo:"C-0001", custName:"恒远电子", custFull:"恒远电子股份有限公司", sales:"王业务", dept:"华东一部", custOrder:"PO-1012",
|
||||
items:[
|
||||
{item:"10", prodNo:"P-1001", name:"驱动齿轮", spec:"M8", custProdNo:"A-GEAR-8", needDate:"2024-08-15", unit:"pcs", qty:600, delivered:100, replies:[{planDate:"2024-08-15", qty:500, remark:""}]},
|
||||
{item:"20", prodNo:"P-1021", name:"轴承座", spec:"6204", custProdNo:"A-BRG-204", needDate:"2024-10-01", unit:"pcs", qty:150, delivered:0, replies:[{planDate:"2024-10-01", qty:150, remark:""}]}
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
const ALL_ITEMS = [];
|
||||
ORDERS.forEach(o=> o.items.forEach(it=> ALL_ITEMS.push(Object.assign(it, {order:o}))));
|
||||
/* 当前登录演示账号:发送通知时作为交期回复人员写入审计字段。 */
|
||||
const CURRENT_USER = {employeeId:"E20240618", realName:"陈交期"};
|
||||
function itemId(o,it){ return o.orderNo+"-"+it.item; }
|
||||
function findItem(id){
|
||||
for(const o of ORDERS){ for(const it of o.items){ if(itemId(o,it)===id) return it; } }
|
||||
return null;
|
||||
}
|
||||
|
||||
/* ================= 业务口径 ================= */
|
||||
const remain = r => Number(r.qty) - Number(r.delivered);
|
||||
const repliedQty = r => (r.replies||[]).reduce((s,x)=>s+Number(x.qty||0),0);
|
||||
function statusOf(r){
|
||||
if(r.deliveryLocked) return "已回复";
|
||||
if((r.replies||[]).length>0) return "部分回复";
|
||||
return "未回复";
|
||||
}
|
||||
function orderStatus(o){
|
||||
const sts = o.items.map(statusOf);
|
||||
if(sts.every(s=>s==="已回复")) return "已回复"; // 整单已全部回复
|
||||
if(sts.every(s=>s==="未回复")) return "未回复"; // 整单均未回复
|
||||
return "部分回复"; // 有回复/有分批回复但未全部完成
|
||||
}
|
||||
const stPill = st => st==="已回复"?"ok":(st==="部分回复"?"warn":"danger");
|
||||
|
||||
/* ================= 过滤(按订单分组) ================= */
|
||||
const qAll = {order:"", prod:"", cust:"", orderDate:"", status:""};
|
||||
let filtered = []; // [{...order, items:[...]}]
|
||||
|
||||
function applyFilter(){
|
||||
filtered = ORDERS.map(o=>{
|
||||
const items = o.items.filter(r=>{
|
||||
if(qAll.orderDate && o.orderDate !== qAll.orderDate) return false;
|
||||
if(qAll.order && !(o.orderNo.toLowerCase().includes(qAll.order.toLowerCase()) ||
|
||||
(o.custOrder||"").toLowerCase().includes(qAll.order.toLowerCase()))) return false;
|
||||
if(qAll.cust && !(o.custNo.toLowerCase().includes(qAll.cust.toLowerCase()) ||
|
||||
o.custName.toLowerCase().includes(qAll.cust.toLowerCase()))) return false;
|
||||
if(qAll.status==="已回复" && statusOf(r)!=="已回复") return false;
|
||||
if(qAll.status==="未完全回复" && statusOf(r)==="已回复") return false;
|
||||
if(qAll.prod){
|
||||
const p = qAll.prod.toLowerCase();
|
||||
const hit = r.prodNo.toLowerCase().includes(p) || r.name.toLowerCase().includes(p) ||
|
||||
(r.custProdNo||"").toLowerCase().includes(p);
|
||||
if(!hit) return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return Object.assign({}, o, {items});
|
||||
}).filter(o=>o.items.length);
|
||||
filtered.sort((a,b)=> a.orderDate.localeCompare(b.orderDate) || a.custNo.localeCompare(b.custNo) || a.orderNo.localeCompare(b.orderNo));
|
||||
filtered.forEach(o=>o.items.sort((a,b)=> Number(a.item)-Number(b.item) || a.prodNo.localeCompare(b.prodNo)));
|
||||
render();
|
||||
}
|
||||
|
||||
function doSearch(){
|
||||
qAll.order = document.getElementById("qOrder").value.trim();
|
||||
qAll.prod = document.getElementById("qProd").value.trim();
|
||||
qAll.cust = document.getElementById("qCust").value.trim();
|
||||
qAll.orderDate = document.getElementById("qOrderDate").value;
|
||||
qAll.status= document.getElementById("qStatus").value;
|
||||
applyFilter();
|
||||
}
|
||||
function doReset(){
|
||||
["qOrder","qProd","qCust","qOrderDate"].forEach(id=>document.getElementById(id).value="");
|
||||
document.getElementById("qStatus").value="";
|
||||
qAll.order=qAll.prod=qAll.cust=qAll.orderDate=qAll.status="";
|
||||
applyFilter();
|
||||
}
|
||||
|
||||
/* ================= 状态容器 ================= */
|
||||
const sel = new Set(); // 勾选的产品行 id
|
||||
const bOpen = new Set(); // 展开批次的产品行 id
|
||||
|
||||
/* ================= 渲染 ================= */
|
||||
function render(){
|
||||
const list = document.getElementById("masterBody");
|
||||
let html="";
|
||||
let rowCount=0;
|
||||
filtered.forEach(o=>{
|
||||
o.items.forEach(r=>{
|
||||
rowCount++;
|
||||
const id = itemId(o,r);
|
||||
const st = statusOf(r), rem = remain(r), stP = stPill(st);
|
||||
const selCls = sel.has(id)?" selected":"";
|
||||
html += `<tr class="order-row${selCls}" data-id="${id}">
|
||||
<td><label class="cx"><input type="checkbox" class="check" ${sel.has(id)?"checked":""} onchange="toggleRow('${id}',this.checked)"><span class="cx-box"></span></label></td>
|
||||
<td class="mono">${o.orderNo}:${r.item}</td>
|
||||
<td>${o.orderDate}</td>
|
||||
<td title="${o.custFull||o.custName||''}">${o.custNo}<div class="cell-sub">${o.custName||''}</div></td>
|
||||
<td>${o.sales}</td><td>${o.dept}</td><td class="mono">${o.custOrder||'-'}</td>
|
||||
<td class="mono">${r.prodNo}</td>
|
||||
<td>${r.name}</td>
|
||||
<td>${r.spec}</td>
|
||||
<td class="mono">${r.custProdNo||''}</td>
|
||||
<td>${r.needDate}</td>
|
||||
<td>${r.unit}</td>
|
||||
<td class="num">${r.qty}</td>
|
||||
<td class="num">${r.delivered}</td>
|
||||
<td class="num ${rem>0?'remain-orange':'remain-gray'}">${rem}</td>
|
||||
<td><span class="pill ${stP}">${st}</span></td>
|
||||
<td class="reply-cell">${replyCell(r,id)}</td>
|
||||
<td>${notifyCell(r,id)}</td>
|
||||
<td>${r.replyPerson ? `<span class="mono">${r.replyPerson.employeeId}</span><div class="cell-sub">${r.replyPerson.realName}</div>` : '<span style="color:var(--muted)">待通知后记录</span>'}</td>
|
||||
</tr>`;
|
||||
});
|
||||
});
|
||||
list.innerHTML = html;
|
||||
document.getElementById("emptyBox").style.display = filtered.length ? "none" : "block";
|
||||
document.getElementById("totalCount").textContent = rowCount;
|
||||
renderToolbar();
|
||||
}
|
||||
|
||||
/* 交期回复单元格:状态摘要 + 可展开批次 + 回复按钮 */
|
||||
function replyCell(r,id){
|
||||
const bCount = r.replies.length;
|
||||
const rem = remain(r), rep = repliedQty(r);
|
||||
if(bCount===0){
|
||||
return `<span style="color:var(--muted)">未回复</span>
|
||||
<div><button class="btn sm primary reply-btn" style="margin-top:4px" onclick="openReply('${id}')">回复交期</button></div>`;
|
||||
}
|
||||
const open = bCount===1 || bOpen.has(id);
|
||||
const bHtml = r.replies.map(x=>`<span class="rc-batch">${x.planDate} · <b>${x.qty}</b> ${r.unit}${x.remark?` <i>${x.remark}</i>`:""}</span>`).join("");
|
||||
const tgl = bCount>1 ? `<button class="rc-toggle" onclick="toggleBatches('${id}')">${open?"收起 ▲":"+"+(bCount-1)+" 批 ▾"}</button>` : "";
|
||||
return `<div class="rc${open?"":" folded"}">
|
||||
<div class="rc-top">
|
||||
<span class="rc-meta"><b>${bCount}</b> 批 · 已回复 <b>${rep}</b>/${rem}</span>
|
||||
${tgl}
|
||||
</div>
|
||||
<div class="rc-list">${bHtml}</div>
|
||||
<div>${r.deliveryLocked ? '<span class="pill ok">交期已锁定</span>' : `<button class="btn sm primary reply-btn" style="margin-top:4px" onclick="openReply('${id}')">修改回复</button>`}</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** 发送通知给订单业务员;成功后记录回复人员并锁定该产品行交期。 */
|
||||
function notifyCell(r,id){
|
||||
if(r.deliveryLocked){
|
||||
return `<span class="pill ok">已通知 ${r.notifyTo}</span><div class="cell-sub">${r.notifiedAt}</div>`;
|
||||
}
|
||||
if(!r.replies.length) return '<span style="color:var(--muted)">请先回复交期</span>';
|
||||
return `<button class="btn sm primary" onclick="sendNotification('${id}')">发送通知业务部门</button>`;
|
||||
}
|
||||
|
||||
function renderToolbar(){
|
||||
const n = sel.size;
|
||||
const allItems = filtered.flatMap(o=>o.items);
|
||||
document.getElementById("tbSel").textContent = n;
|
||||
const chk = document.getElementById("chkAll");
|
||||
chk.checked = n>0 && n===allItems.length;
|
||||
chk.indeterminate = n>0 && n<allItems.length;
|
||||
document.getElementById("btnBatch").disabled = n===0;
|
||||
const canNotify = selectedItems().some(r=> (r.replies||[]).length && !r.deliveryLocked);
|
||||
document.getElementById("btnNotifyBatch").disabled = !canNotify;
|
||||
}
|
||||
|
||||
/* ================= 勾选 / 展开 ================= */
|
||||
function toggleRow(id,on){ on? sel.add(id):sel.delete(id); render(); }
|
||||
function toggleAll(cb){
|
||||
filtered.forEach(o=> o.items.forEach(r=>{ const id=itemId(o,r); cb.checked? sel.add(id):sel.delete(id); }));
|
||||
render();
|
||||
}
|
||||
function toggleBatches(id){
|
||||
bOpen.has(id) ? bOpen.delete(id) : bOpen.add(id);
|
||||
render();
|
||||
}
|
||||
|
||||
/* ================= 弹窗:联合/拆分回复 ================= */
|
||||
function selectedItems(){ return [...sel].map(findItem).filter(Boolean); }
|
||||
function openBatch(){
|
||||
const rows = selectedItems();
|
||||
if(!rows.length) return;
|
||||
buildModal(rows, "联合回复交期(" + rows.length + " 个产品 / 覆盖 " + new Set(rows.map(r=>r.order.orderNo)).size + " 笔订单)");
|
||||
}
|
||||
function openReply(id){
|
||||
const r = findItem(id);
|
||||
if(!r || r.deliveryLocked) return;
|
||||
const o = r.order;
|
||||
buildModal([r], "回复交期 · " + o.orderNo + " / 项次 " + r.item + " · " + r.prodNo + " " + r.name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 向该订单对应业务员发送交期通知,并将当前账号工号和姓名写入回复人员字段。
|
||||
* 已通知的交期不可再修改,避免通知内容与后续交期不一致。
|
||||
*/
|
||||
function sendNotification(id){
|
||||
const r = findItem(id);
|
||||
if(!r || r.deliveryLocked || !r.replies.length) return;
|
||||
const sales = r.order.sales;
|
||||
const key = r.order.orderNo + ":" + r.item;
|
||||
if(!confirm(`确认向业务员「${sales}」发送?\n您有订单号:项次${key}的订单需要填写/确认/查看交期。\n发送后交期将锁定。`)) return;
|
||||
r.replyPerson = {...CURRENT_USER};
|
||||
r.deliveryLocked = true;
|
||||
r.notifyTo = sales;
|
||||
r.notifiedAt = new Date().toLocaleString('zh-CN', {hour12:false});
|
||||
render();
|
||||
alert(`已向业务员「${sales}」发送:您有订单号:项次${key}的订单需要填写/确认/查看交期。`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 对勾选行中已填批次且未锁定的行批量通知并锁定。
|
||||
*/
|
||||
function notifySelected(){
|
||||
const rows = selectedItems().filter(r=> (r.replies||[]).length && !r.deliveryLocked);
|
||||
if(!rows.length) return;
|
||||
if(!confirm(`将向 ${rows.length} 行对应业务员发送交期通知,发送成功的行将锁定。继续?`)) return;
|
||||
rows.forEach(r=>{
|
||||
r.replyPerson = {...CURRENT_USER};
|
||||
r.deliveryLocked = true;
|
||||
r.notifyTo = r.order.sales;
|
||||
r.notifiedAt = new Date().toLocaleString('zh-CN', {hour12:false});
|
||||
});
|
||||
render();
|
||||
alert(`已批量通知 ${rows.length} 行并锁定。`);
|
||||
}
|
||||
|
||||
function buildModal(rows, title){
|
||||
document.getElementById("modalTitle").textContent = title;
|
||||
document.getElementById("quickDate").value = "";
|
||||
document.getElementById("modalMsg").textContent = "";
|
||||
const wrap = document.getElementById("relayItems");
|
||||
wrap.innerHTML = "";
|
||||
rows.forEach(r=>{
|
||||
const o = r.order;
|
||||
const rem = remain(r);
|
||||
const initial = r.replies.length? JSON.parse(JSON.stringify(r.replies)) : [];
|
||||
const item = document.createElement("div");
|
||||
item.className = "relay-item";
|
||||
item.dataset.id = itemId(o,r);
|
||||
item.innerHTML = `
|
||||
<div class="obj">
|
||||
<span class="tag">${o.orderNo}</span>
|
||||
<span>项次 ${r.item}</span>
|
||||
<span class="k">${o.custNo} · ${o.custName}</span>
|
||||
<span class="k">${r.prodNo} · ${r.name} / ${r.spec}</span>
|
||||
<span class="k">客户料号 ${r.custProdNo}</span>
|
||||
<span class="k">约定交期 ${r.needDate}</span>
|
||||
<span class="remain">未交 <b>${rem}</b> ${r.unit}</span>
|
||||
</div>
|
||||
<div class="relay-list"></div>
|
||||
`;
|
||||
wrap.appendChild(item);
|
||||
const list = item.querySelector(".relay-list");
|
||||
if(initial.length){ initial.forEach(x=>addRelayRow(list, x)); }
|
||||
else{ addRelayRow(list, {}); }
|
||||
const addBtn = document.createElement("button");
|
||||
addBtn.type = "button";
|
||||
addBtn.className = "add-relay";
|
||||
addBtn.innerHTML = "+ 增加拆分批次(多个交期 + 数量 + 备注)";
|
||||
addBtn.onclick = ()=> addRelayRow(list, {});
|
||||
list.appendChild(addBtn);
|
||||
});
|
||||
document.getElementById("overlay").classList.add("show");
|
||||
}
|
||||
|
||||
function addRelayRow(list, data){
|
||||
const row = document.createElement("div");
|
||||
row.className = "relay-row";
|
||||
row.innerHTML = `
|
||||
<input type="date" class="r-date" value="${data.planDate||''}">
|
||||
<input type="number" class="r-qty" placeholder="数量" min="0" value="${data.qty!=null?data.qty:''}">
|
||||
<input type="text" class="r-remark" placeholder="备注(可选)" value="${data.remark||''}">
|
||||
<span class="relay-sum"></span>
|
||||
<button class="del" title="删除本行回复">✕</button>
|
||||
`;
|
||||
row.querySelector(".del").onclick = ()=> row.remove();
|
||||
[".r-date",".r-qty",".r-remark"].forEach(s=> row.querySelector(s).oninput = refreshItem);
|
||||
const addBtn = list.querySelector(".add-relay");
|
||||
if(addBtn) list.insertBefore(row, addBtn);
|
||||
else list.appendChild(row);
|
||||
refreshItem();
|
||||
}
|
||||
|
||||
function applyQuickDate(){
|
||||
const d = document.getElementById("quickDate").value;
|
||||
if(!d){ document.getElementById("modalMsg").textContent="请先选择统一交期日期"; return; }
|
||||
document.querySelectorAll("#relayItems .relay-item .r-date").forEach(i=>i.value=d);
|
||||
document.getElementById("modalMsg").textContent="已应用统一交期 "+d;
|
||||
}
|
||||
|
||||
function refreshItem(){
|
||||
document.querySelectorAll("#relayItems .relay-item").forEach(item=>{
|
||||
const r = findItem(item.dataset.id);
|
||||
const rem = remain(r);
|
||||
const list = item.querySelector(".relay-list");
|
||||
const qtyRows = [...list.querySelectorAll(".relay-row")].map(tr=>Number(tr.querySelector(".r-qty").value)||0);
|
||||
const total = qtyRows.reduce((s,x)=>s+x,0);
|
||||
list.querySelectorAll(".relay-row .relay-sum").forEach(span=>{
|
||||
const t = Number(span.parentElement.querySelector(".r-qty").value)||0;
|
||||
span.innerHTML = t? `<b>${t}</b> ${r.unit}` : "";
|
||||
});
|
||||
const label = item.querySelector(".remain");
|
||||
if(label){
|
||||
const cls = total>rem ? " style='color:var(--warn)'" : "";
|
||||
label.innerHTML = `未交 <b>${rem}</b> ${r.unit} · 已拆分 <b${cls}>${total}</b>${total>rem?" <span style='color:var(--warn)'>超</span>":""}`;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function saveReplies(){
|
||||
let full=0, partial=0;
|
||||
const warnOverQty=[], warnNoData=[];
|
||||
const items = document.querySelectorAll("#relayItems .relay-item");
|
||||
items.forEach(item=>{
|
||||
const id = item.dataset.id;
|
||||
const row = findItem(id);
|
||||
if(row.deliveryLocked) return;
|
||||
const rem = remain(row);
|
||||
const replies = [];
|
||||
let hasContent = false;
|
||||
item.querySelectorAll(".relay-row").forEach(tr=>{
|
||||
const d = tr.querySelector(".r-date").value;
|
||||
const q = parseInt(tr.querySelector(".r-qty").value,10)||0;
|
||||
const rm = tr.querySelector(".r-remark").value.trim();
|
||||
if(d || q || rm) hasContent = true;
|
||||
if(d && q>0) replies.push({planDate:d, qty:q, remark:rm});
|
||||
});
|
||||
if(!replies.length){
|
||||
if(hasContent) warnNoData.push(row);
|
||||
return;
|
||||
}
|
||||
const total = replies.reduce((s,x)=>s+x.qty,0);
|
||||
row.replies = replies;
|
||||
bOpen.add(id);
|
||||
if(total>rem) warnOverQty.push({row, total, rem});
|
||||
if(total>=rem) full++; else partial++;
|
||||
});
|
||||
|
||||
const msg = [];
|
||||
if(warnOverQty.length){
|
||||
msg.push(`<span class="warn-text">⚠ 以下产品拆分合计超出未交(已保存,仅提醒):${warnOverQty.map(x=>`${x.row.order.orderNo}-${x.row.item} 合计${x.total} > 未交${x.rem}`).join(";")}</span>`);
|
||||
}
|
||||
if(warnNoData.length){
|
||||
msg.push(`<span class="err-text">✕ 以下产品填了备注/交期但缺数量,未保存:${warnNoData.map(r=>`${r.order.orderNo}-${r.item}`).join(";")}</span>`);
|
||||
document.getElementById("modalMsg").innerHTML = msg.join("<br>");
|
||||
render();
|
||||
return;
|
||||
}
|
||||
if(warnOverQty.length){
|
||||
document.getElementById("modalMsg").innerHTML = msg.join("<br>");
|
||||
}else{
|
||||
document.getElementById("overlay").classList.remove("show");
|
||||
}
|
||||
applyFilter();
|
||||
render();
|
||||
if(!warnOverQty.length){
|
||||
alert(`已保存交期回复:完整回复 ${full} 行,部分回复 ${partial} 行。`);
|
||||
}
|
||||
}
|
||||
|
||||
function closeModal(){
|
||||
document.getElementById("overlay").classList.remove("show");
|
||||
}
|
||||
|
||||
/* 初始渲染 */
|
||||
applyFilter();
|
||||
renderToolbar();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,322 @@
|
||||
# 订单交期回复 — 技术设计
|
||||
|
||||
| 项目 | 说明 |
|
||||
|------|------|
|
||||
| 版本 | v1.0(2026-09-21;增补 07:00 同步兜底触发、同步完成提醒生管、每日出货/未回复提醒排程与新列顺序) |
|
||||
| 状态 | 已拍板,可按本文实现 |
|
||||
| 需求基线 | [demand.md](demand.md) v0.9(§8 列顺序 2026-09-21 修订、§13.1 定时提醒增补) |
|
||||
| 原型 | [order-delivery-reply-prototype.html](order-delivery-reply-prototype.html) |
|
||||
|
||||
已定:一期同步 `oeaconf='Y'` 且 `oea49='1'` 且 `oeb70='N'` 且 `NVL(oeb24,0)=0`(完全未交)的**全部**合格订单行,**不按单别过滤**;不做单别白名单管理配置(后期再加)。每天 07:00(北京时间)+ 手动刷新。业务员/部门显示名称且工号能对上企微;已回复必须已通知锁定;联合回复只保存,另用批量通知;企微**复用** `send_wecom_event_message`,本 Agent 不单独定卡片样式。**操作权限按用户功能权限**,不按部门名称每次判定。筛选为全部 / 已回复 / 未完全回复。列表**不出**单别列。取消订单类型、已转请购、排定交货日。客户取 `OCC_FILE`。
|
||||
|
||||
---
|
||||
|
||||
## 1. 设计目标
|
||||
|
||||
1. ERP Oracle **只读**。本地 Postgres 存 ERP 快照 + 批次 / 锁定 / 通知 / 审计。
|
||||
2. 工作台只读本地库。同步只更新快照上的 ERP 列,不得覆盖回复与锁定。
|
||||
3. 禁止对 ERP 做 INSERT / UPDATE / DELETE。
|
||||
4. 一期:工作台独立页 + Flask API,复用 User、排程、企微;不新开 FastAPI。
|
||||
|
||||
---
|
||||
|
||||
## 2. 总体架构
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
erpOracle[ERP_Oracle_HXJM] -->|只读SELECT| syncJob[同步服务]
|
||||
syncJob -->|upsert快照列| localPg[本地Postgres]
|
||||
localPg --> api[Flask_API]
|
||||
api --> ui[工作台]
|
||||
ui -->|保存批次_通知锁定| api
|
||||
api -->|企微通知| wecom[企业微信]
|
||||
```
|
||||
|
||||
| 层 | 落点 |
|
||||
| --- | --- |
|
||||
| ERP | `HXJM.OEA_FILE` / `OEB_FILE` / `IMA_FILE` / `OCC_FILE` / `GEN_FILE` / `GEM_FILE`;连接复用 `ERP_DB_*` |
|
||||
| 同步 | `app/services/order_delivery_reply/`;07:00 + 手动全量;一期拉全部合格订单,不按单别过滤 |
|
||||
| 本地库 | 新表 + Alembic |
|
||||
| API | Flask Blueprint `/api/order-delivery-reply/`;列表读已同步快照 |
|
||||
| 前端 | `frontend/src/features/order-delivery-reply/`(操作页 + api + constants);路由/侧栏/聊天侧栏入口/首页入口卡片见 §8 |
|
||||
| 企微 | 复用 `wecom_notify.send_wecom_event_message`(平台统一 textcard);本 Agent 不自绘卡片 |
|
||||
|
||||
页面展示最近同步时间。同步失败保留上次快照并明示失败。
|
||||
|
||||
---
|
||||
|
||||
## 3. ERP 取数
|
||||
|
||||
### 3.1 连接
|
||||
|
||||
与 Text2SQL / 立账检核相同:`ERP_DB_DSN`、`ERP_DB_USER` / `ERP_USERNAME`、`ERP_DB_PASSWORD` / `ERP_PASSWORD`;**缺省回退合同付款预警的共享配置 `CONTRACT_PAYMENT_ERP_USERNAME` / `CONTRACT_PAYMENT_ERP_PASSWORD`**(`.env.shared`,hxjm 账号同一 topprod 连接)。DSN 与口令不进仓库。复用 `Text2SQLService._init_oracle_client`(thin 优先、失败切 thick)。
|
||||
|
||||
### 3.2 关联
|
||||
|
||||
| 条件 | 含义 |
|
||||
| --- | --- |
|
||||
| `oea01 = oeb01` | 订单头 ↔ 身 |
|
||||
| `oeb04 = ima01` 且 `oeb06 = ima02` | 料件;LEFT JOIN,无料件仍保留行 |
|
||||
| `oea03 = occ01` | 客户主档。对照表写 `oea03=ooc01`,按 `OCC_FILE.occ01` |
|
||||
| `oea14 = gen01` | 业务员姓名 `gen02` |
|
||||
| `oea15 = gem01` | 部门名称 `gem02` |
|
||||
|
||||
员工 / 部门表优先 `HXJM.GEN_FILE` / `HXJM.GEM_FILE`。若套账无表,回退已验证的 `ERP_VIEW_USER.ERP_GEN_FILE_V` / `ERP_GEM_FILE_V`(`gen01`/`gen02`、`gem01`/`gem02` 同义)。
|
||||
|
||||
### 3.3 字段映射
|
||||
|
||||
| 系统字段 | 取值列 | 来源表 | 转换 |
|
||||
| --- | --- | --- | --- |
|
||||
| 订单单号 | `oea01` | `OEA_FILE` | 字符串 |
|
||||
| 订单日期 | `oea02` | `OEA_FILE` | → `date` |
|
||||
| 客户编号 | `oea03` | `OEA_FILE` | 字符串 |
|
||||
| 客户简称 | `occ02` | `OCC_FILE` | 字符串;LEFT JOIN 可空 |
|
||||
| 公司全名 | `occ18` | `OCC_FILE` | 字符串;可空 |
|
||||
| 业务员工号 | `oea14` | `OEA_FILE` | 字符串;对 HXOPS `User.employee_id` |
|
||||
| 业务员姓名 | `gen02` | `GEN_FILE` | 列表展示此列 |
|
||||
| 部门编码 | `oea15` | `OEA_FILE` | 字符串 |
|
||||
| 部门名称 | `gem02` | `GEM_FILE` | 列表展示此列 |
|
||||
| 客户订单 | `oea10` | `OEA_FILE` | 可空 |
|
||||
| 项次 | `oeb03` | `OEB_FILE` | int |
|
||||
| 产品编号 | `oeb04` | `OEB_FILE` | 字符串 |
|
||||
| 品名 | `oeb06` | `OEB_FILE` | 字符串 |
|
||||
| 规格 | `ima021` | `IMA_FILE` | 可空 |
|
||||
| 客户产品编号 | `oeb11` | `OEB_FILE` | 可空 |
|
||||
| 约定交货日 | `oeb15` | `OEB_FILE` | → `date` |
|
||||
| 单位 | `oeb05` | `OEB_FILE` | 字符串 |
|
||||
| 数量 | `oeb12` | `OEB_FILE` | Numeric |
|
||||
| 已交数量 | `oeb24` | `OEB_FILE` | Numeric;空当 0 |
|
||||
|
||||
未交数量 = `数量 − 已交数量`,计算列。
|
||||
|
||||
**取消、不同步、不上列表:** 订单类型、已转请购 / 已转采购、排定交货日。
|
||||
|
||||
### 3.4 同步过滤(已拍板)
|
||||
|
||||
业务:只拉 **已审核、已核准、未结案** 的订单行。现场已确认:
|
||||
|
||||
| 业务条件 | ERP 口径 |
|
||||
| --- | --- |
|
||||
| 已审核 | `a.oeaconf = 'Y'` |
|
||||
| 已核准 | `a.oea49 = '1'` |
|
||||
| 未结案 | `oeb70` 结案否(Y/N),`NVL(b.oeb70, 'N') = 'N'` |
|
||||
| 完全未交 | 已交数量为 0,`NVL(b.oeb24, 0) = 0`(2026-09-17 增补) |
|
||||
|
||||
上表四者同时满足(AND)。一期**不按单别缩小同步**,凡合格行都进本地快照(含样品/退货等单别)。
|
||||
|
||||
本轮未命中、但本地已有批次或已锁定的行:不删除,`erp_missing = true`,默认列表不展示,可提示「已不在同步范围」。
|
||||
|
||||
### 3.5 标准 SELECT
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
a.oea01 AS order_no,
|
||||
b.oeb03 AS line_no,
|
||||
a.oea02 AS order_date,
|
||||
a.oea03 AS customer_no,
|
||||
d.occ02 AS customer_short_name,
|
||||
d.occ18 AS customer_full_name,
|
||||
a.oea14 AS salesperson_code,
|
||||
e.gen02 AS salesperson_name,
|
||||
a.oea15 AS dept_code,
|
||||
f.gem02 AS dept_name,
|
||||
a.oea10 AS customer_po,
|
||||
b.oeb04 AS part_no,
|
||||
b.oeb06 AS part_name,
|
||||
c.ima021 AS spec,
|
||||
b.oeb11 AS customer_part_no,
|
||||
b.oeb15 AS agreed_date,
|
||||
b.oeb05 AS unit,
|
||||
b.oeb12 AS qty,
|
||||
NVL(b.oeb24, 0) AS delivered_qty
|
||||
FROM HXJM.OEA_FILE a
|
||||
INNER JOIN HXJM.OEB_FILE b ON a.oea01 = b.oeb01
|
||||
LEFT JOIN HXJM.IMA_FILE c ON b.oeb04 = c.ima01 AND b.oeb06 = c.ima02
|
||||
LEFT JOIN HXJM.OCC_FILE d ON a.oea03 = d.occ01
|
||||
LEFT JOIN HXJM.GEN_FILE e ON a.oea14 = e.gen01
|
||||
LEFT JOIN HXJM.GEM_FILE f ON a.oea15 = f.gem01
|
||||
WHERE a.oeaconf = 'Y'
|
||||
AND a.oea49 = '1'
|
||||
AND NVL(b.oeb70, 'N') = 'N'
|
||||
AND NVL(b.oeb24, 0) = 0
|
||||
```
|
||||
|
||||
同步服务与 [`backend/scripts/order_delivery_query.py`](../../../backend/scripts/order_delivery_query.py) 共用同一 SQL 常量。后期单别白名单再给 WHERE 追加 `IN` 启用编码。
|
||||
|
||||
---
|
||||
|
||||
## 4. 本地库
|
||||
|
||||
```mermaid
|
||||
erDiagram
|
||||
order_delivery_erp_lines ||--o{ order_delivery_batches : has
|
||||
order_delivery_erp_lines ||--o| order_delivery_line_states : has
|
||||
order_delivery_erp_lines ||--o{ order_delivery_audit_events : has
|
||||
order_delivery_sync_runs ||--o{ order_delivery_erp_lines : writes
|
||||
```
|
||||
|
||||
| 表 | 谁写 |
|
||||
| --- | --- |
|
||||
| `order_delivery_erp_lines` | 仅同步 |
|
||||
| `order_delivery_batches` | 仅保存回复 |
|
||||
| `order_delivery_line_states` | 仅通知成功路径 |
|
||||
| `order_delivery_audit_events` | 保存 / 通知 / 锁定 / 同步 |
|
||||
| `order_delivery_sync_runs` | 同步作业 |
|
||||
|
||||
### 4.1 `order_delivery_erp_lines`
|
||||
|
||||
唯一键 `(order_no, line_no)`。
|
||||
|
||||
相对 v0.1 增加:`customer_short_name`、`customer_full_name`、`salesperson_name`、`dept_name`、`slip_code`。仍存 `salesperson_code`、`dept_code` 供企微映射与排错。同步 upsert **只更新本节 ERP 列**。
|
||||
|
||||
`slip_code`:从 `oea01` 取连字符前的单别(`8301-1605280014` → `8301`)。一期只落库预留,**不展示、不过滤、无管理端勾选**。后期白名单可直接用此列。
|
||||
|
||||
### 4.2 批次 / 状态 / 审计
|
||||
|
||||
与 v0.1 相同:未锁定按行整表替换批次;锁定后拒绝写入。
|
||||
|
||||
读时推导行状态:无批次 → 未回复;有批次未 `locked` → 部分回复;`locked` → 已回复。
|
||||
|
||||
列表筛选 `status`:`已回复` 只返回已锁定行;`未完全回复` 返回未回复 ∪ 部分回复。默认只列 `erp_missing = false` 的行。一期不按单别裁行。
|
||||
|
||||
---
|
||||
|
||||
## 5. 同步作业与定时提醒
|
||||
|
||||
- **定时全量:** `ScheduleTask` cron `0 7 * * *`,时区 `Asia/Shanghai`;拉全部已审核+已核准+未结案行。
|
||||
- **手动全量:** 生管 POST `/sync`,范围同上。
|
||||
- **到期排程触发(2026-09-29 更新):** 排程扫描由独立进程 `workers/worker_scheduler.py`(compose `hxops-schedule-worker` 容器)执行——只跑 `run.py` 的本地环境不会有进程自动触发 07:00/07:10,需另起 worker 进程或手动执行。本功能 2026-09-21 曾加过 Web 进程内兜底扫描(`services/schedule/web_scanner.py`,`SCHEDULE_WEB_SCANNER_ENABLED`),2026-09-29 合并 dev 主线(Wave 4 scheduler 迁移)后 `create_app` 不再启动它(模块保留备用)。
|
||||
- **同步完成提醒生管(2026-09-21):** 排程同步成功后按任务 `notify_enabled` + `notify_user_ids_json`(管理端排程表单现成字段)给生管发企微「今日订单交期数据已同步完成(共 N 行),请及时查看并回复交期。」,并写 `run.response_summary_json.domain_notification_managed=true` 抑制通用「排程执行结果」通知避免双重打扰;通知失败只记入运行 errors,不改变同步成功状态。
|
||||
- **每日提醒排程(2026-09-21):** `order-delivery-remind`(日批 07:10,种子 `SCH-ORDER-DELIVERY-REMIND`),实现见 `services/order_delivery_reply/reminder_service.py`:
|
||||
- **启停开关(2026-09-21 增补):** 任务参数 `ship_remind_enabled` / `unreplied_remind_enabled`(布尔,默认开)**独立启停**两类提醒;关闭的一侧跳过(summary 记 `skipped=disabled`),不影响另一侧。
|
||||
- **出货提醒:** 已锁定(已回复)行批次 `planned_date` 落在 [今天, 今天+N](N=`ship_remind_advance_days`,默认 3)→ 按业务员聚合一条企微提醒安排出货;同一 (行,交期) 以 `audit_events action=ship_remind payload.ok=true` 去重,发送失败不落成功记录、次日自动补发;业务员工号对不上企微的记失败审计并在运行 errors 提示。
|
||||
- **未回复再提醒:** 未锁定行订单日期(快照 `order_date`,取 ERP `oea02`;2026-09-23 由快照首次入库 `created_at` 改来)距今 ≥ N(N=`unreplied_remind_days`,默认 3)→ 按收件人聚合一条企微提醒生管(订单日期为空不参与);收件人取任务参数 `unreplied_remind_user_ids`(留空回退本任务 `notify_enabled` + `notify_user_ids_json`);同一行距上次成功提醒 ≥ N 天才再次提醒(节奏锚点同为审计,`ok=true` 才计入)。
|
||||
- 两个扫描互相独立:单侧异常回滚后继续另一侧,错误计入运行 errors;提醒只读业务数据 + 写审计,绝不改批次/锁定。
|
||||
- **配置复用:** 开关与天数在管理端排程表单「任务参数」修改(boolean/number 字段);生管收件人在排程表单「通知开关 + 通知人」配置——不新增配置页面。
|
||||
- 同时只跑一个同步。Oracle 按 `oea01` 分页。失败保留快照并记 `sync_runs`。
|
||||
- - **收件人分离(2026-09-22):** 未回复提醒的生管收件人改用任务参数 `unreplied_remind_user_ids`(multi_select,候选 `hxops_users`=全部启用用户,表单内支持按姓名/工号/部门关键词搜索),与平台运行结果通知的「通知人」(`notify_user_ids_json`)互相独立;参数留空回退通知人兼容旧配置。
|
||||
- **天数钳制(2026-09-22):** 提醒天数统一钳制 0-3650——表单误填巨大值时 `today + timedelta(N)` 溢出抛 `OverflowError: date value out of range`,导致 2026-09-22 出货提醒扫描失败(未回复提醒不受影响)。
|
||||
|
||||
---
|
||||
|
||||
## 6. API
|
||||
|
||||
统一 `{ success, data, request_id }`,失败 `raise AppError`。
|
||||
|
||||
| 方法 | 路径 | 作用 |
|
||||
| --- | --- | --- |
|
||||
| GET | `/lines` | 筛选分页。查询条件见下;只返回未 `erp_missing` 的已同步行 |
|
||||
| POST | `/admin/permissions/grant-by-department` | 可选:按部门给成员批量写入功能权限(一次性发放,之后仍按用户勾选判定) |
|
||||
| GET | `/lines/:orderNo/:lineNo` | 单行 + 批次 + 状态 |
|
||||
| PUT | `/lines/:orderNo/:lineNo/batches` | 保存该行批次;各批次合计必须等于订单数量(422 `BATCH_QTY_TOTAL_MISMATCH`),锁定 409 |
|
||||
| POST | `/lines/:orderNo/:lineNo/notify` | 单行通知;成功则锁定(前端不出行内按钮,接口保留:批量通知逐行复用同一服务入口,也可外部调用) |
|
||||
| POST | `/batch-reply` | 联合回复,**只保存批次** |
|
||||
| POST | `/notify-batch` | 批量通知勾选行;无批次或已锁定跳过 |
|
||||
| POST | `/sync` | 手动同步 |
|
||||
| GET | `/sync/latest` | 最近一次同步 |
|
||||
|
||||
GET `/lines` 查询:`keyword`(合并搜索:订单单号/客户订单/客户编号/客户简称/公司全名/产品编号/品名/客户产品编号/业务员(姓名、工号)/交期回复人员(姓名、工号,行状态快照 EXISTS,2026-09-23 增补)OR 命中)、`order_date`、`status`(空=`全部` / `已回复` / `未完全回复`)、`page`、`page_size`。默认排序 `order_date, customer_no, order_no, line_no, part_no` 升序。`page_size` 默认 50。全选仅本页。
|
||||
|
||||
直链打开 `erp_missing` 的行:按不存在处理,不在工作台展示。
|
||||
|
||||
`notify` / `notify-batch`:通知与锁定同一事务。单行失败不回滚其它行。
|
||||
|
||||
---
|
||||
|
||||
## 7. 通知与权限
|
||||
|
||||
### 7.1 企微
|
||||
|
||||
`salesperson_code` → `User.employee_id` → `wecom_userid`。已确认能对上。对不上则该行失败、不锁定。
|
||||
|
||||
走平台既有 `send_wecom_event_message`:textcard 壳、按钮「查看详情」、跳转 URL 拼装、`WecomNotifyAudit` 回执,全部用现成实现。本 Agent **只传业务参数**,不另定卡片样式、按钮文案、markdown、图文或模板卡片。
|
||||
|
||||
| 参数 | 取值 |
|
||||
| --- | --- |
|
||||
| `event_type` | `order_delivery_reply_notify`(下划线命名;已加入 `WECOM_NOTIFY_EVENTS` 默认清单,与其它事件同一配置。2026-09-21 修正:此前文档误写为点号 `order_delivery_reply.notify`,与代码不符) |
|
||||
| `title` | `订单交期回复` |
|
||||
| `content` | `您有订单号:项次{order_no}:{line_no}的订单需要填写/确认/查看交期。` |
|
||||
| `jump_path` | 工作台路由,带该行查询参数 |
|
||||
|
||||
批量通知按行各调一次同一接口。发送成败以该函数返回为准;回执只记既有审计,不改交期回复状态。
|
||||
|
||||
**定时提醒复用同一 `event_type`**,文案与触发规则见 §5「同步完成提醒生管 / 每日提醒排程」(同步完成、出货提醒、未回复再提醒三类;卡片同样跳工作台,逐行写 `ship_remind` / `unreplied_remind` 审计)。
|
||||
|
||||
### 7.2 功能权限
|
||||
|
||||
操作权限挂在用户 `feature_permissions` 上,与合同付款预警的 `contract_payment.access` 同一套机制。**每次请求只看用户勾选,不拿 `User.department` 当门禁。** 不新增 `User.role`。
|
||||
|
||||
| 键 | 默认 | 能力 |
|
||||
| --- | --- | --- |
|
||||
| `order_delivery_reply.manage` | `admin` 开,其他人关 | 查看已同步订单;回复批次;单行/批量通知;手动同步 |
|
||||
| `order_delivery_reply.access` | `admin` 开,其他人关 | 查看已同步订单;只读 |
|
||||
|
||||
判定:`manage` 命中 → 可写(同时视为有 `access`);否则仅 `access` → 只读;否则无菜单、API 403。侧栏与路由只负责展示,后端仍 403。
|
||||
|
||||
菜单与 GET 需 `access` 或 `manage`;保存 / 通知 / 同步需 `manage`。
|
||||
|
||||
企微收件人仍按订单业务员 `oea14` → `User.employee_id`,与这两个勾选无关。具备 `access` 的人看**已同步全量**,不按「是否本人业务员」裁行。
|
||||
|
||||
用户管理表单提供上述两键勾选(文案四语言)。人多时管理员可选用部门批量授权:选部门 + 授予 `manage` 或 `access`,把勾选写到当时该部门成员的用户记录上。这是一次性发放;调岗后权限不会因部门字段变化自动增减,需再勾或再跑一次发放。
|
||||
|
||||
---
|
||||
|
||||
## 8. 前端
|
||||
|
||||
`frontend/src/features/order-delivery-reply/`:`constants.ts`(权限键)、`api/orderDeliveryReply.api.ts`(统一 `requestJson`)、`views/OrderDeliveryReplyPage.vue`(操作页)。交互以更新后的原型 v5 为准。工具栏:「联合回复交期」与「批量通知」分开;**通知唯一入口为「批量通知」**,列表不出「通知业务部门」列(行内不设发送按钮;已通知对象与时间并入「交期回复人员」列)。状态徽标按需求 §12,不用旧原型按数量覆盖的脚本。
|
||||
|
||||
列表(2026-09-21 修订列顺序,独立「部门」「品名」列取消)按序为:勾选、客户编号(副文案客户简称,全名 title)、订单日期、订单单号:项次、产品编号(副文案品名)、客户产品编号、数量、约定交货日、交期回复状态、交期回复、交期回复人员、业务员(副文案部门)、客户订单、规格、单位。表格浏览体验(2026-09-21):页面高度收敛至视口(滚动全部发生在表格容器内 → 列头 sticky 固定、横向滚动条常驻表格底缘);左侧冻结前四列标识区(勾选/客户编号/订单日期/订单单号:项次,冻结单元格实色背景防透出,宽度已收窄至 2/8/6/10rem);行高紧凑(表体 py-1.5,产品编号/品名/规格/客户订单/客户简称长文本单行截断 + title 悬停看全文,交期回复批次条不折行);筛选区与工具栏字号与表格统一(text-sm 14px,状态徽标例外保持 text-xs 12px 加粗)并压缩高度。列项与顺序不变。不渲染订单类型、单别、已转请购、排定交货日,亦不出「已交数量 / 未交数量」列(`NVL(oeb24,0)=0` 过滤后无信息量;未交口径仍由后端计算,供回复弹窗数量守恒校验——各批次合计必须等于订单数量,2026-09-23 由「超额仅提醒」修订);表头与工具栏提示不换行(`whitespace-nowrap`,避免窄列中文竖排)。分页复用共享 `PaginationBar`(与管理控制台-数据报表同一组件:摘要 + 每页条数 20/50/100/200 + 页码按钮)。客户列:编号 + 简称,全名作 title;产品编号列:编号 + 品名;业务员列:姓名 + 部门,同款上下两行合并展示。仅 `access` 时隐藏回复、通知、同步按钮与手动刷新。用户管理勾选两键功能权限。一期无单别管理页。
|
||||
|
||||
### 8.1 路由与入口
|
||||
|
||||
- **路由**:`workspace-order-delivery-reply`(`workspace.routes.ts`),`meta.requiresFeaturePermission = order_delivery_reply.access`,由既有 `guards.ts` 守卫;路径常量 `WORKSPACE_PATHS.orderDeliveryReply`。
|
||||
- **工作台侧栏**:**不设菜单项**(需求 Q-03 修订:不在「货代发货通知」分组下挂入口,导航一律走应用入口)。
|
||||
- **应用入口(R-ENTRY-02)**:注册到应用管理——`app_seed.py` 幂等创建 `Agent(agent_code='order_delivery_reply', runtime_provider='iframe', iframe_url='/apps/order-delivery-reply')`(**不接 Dify**,`dify_app_id/api_key` 为空);admin 自动可见全部启用应用,普通用户经用户管理 Agent 权限授权后可见;点击进入 `/chat/{id}` 由聊天壳按 iframe provider 整页渲染免布局嵌入路由 `app-order-delivery-reply`(`routes/index.ts` 顶层注册,同页组件 + 同功能权限守卫)。管理员可在应用管理改名称/描述/图标/排序,但不应把 runtime_provider 改回 dify。页面与 API 仍受 access/manage 功能权限守卫(两层各司其职:Agent 权限管入口可见性,功能权限管页面/接口)。
|
||||
- **企微直达**:四类卡片 `jump_path` 均为 `/apps/order-delivery-reply`(免布局嵌入路由,企微内打开不带工作台侧栏;2026-09-22 由 /workspace 路由改来),带查询参数定位「该 Agent 对应的内容及位置」,点击后未登录先走 `/login?redirect=深链`、登录成功原样回跳:
|
||||
- 行级通知卡:`order_no` + `line_no` → 页面自动填关键词筛选、按行滚动定位并高亮 8 秒(提示 toast);
|
||||
- 未回复提醒卡:`status=not_fully_replied` → 还原「未完全回复」筛选;
|
||||
- 出货提醒卡:`status=replied` → 还原「已回复」筛选;
|
||||
- 同步完成提醒卡:`status=not_fully_replied` → 还原「未完全回复」筛选(生管待回复行)。
|
||||
所有卡片另带 `wecom_trace`,操作页加载后调 `/api/user/wecom/deeplink-opened` 上报打开回执(与工作台 deeplink 同一接口,失败静默)。
|
||||
|
||||
### 8.2 提示与刷新(需求 §9 即时刷新)
|
||||
|
||||
- 保存/单行通知/批量通知/手动同步完成后均重新拉取列表与最近同步时间。
|
||||
- 单行通知失败:catch `BusinessError` → `useMessage().error()`(errors.json 四语言文案,累计 14 个 `ORDER_DELIVERY_REPLY.*` 键)。
|
||||
- 批量通知按 `succeeded/failed/skipped` 分级:部分成功 warning 汇总(含失败行明细)、全部失败 error、全成功 success。
|
||||
- 联合回复保存提示明确「未通知,可继续修改」。
|
||||
|
||||
### 8.3 i18n
|
||||
|
||||
页面文案集中于 `locales/*/workspace.json` 的 `workspace.orderDeliveryReply.*`(约 91 键/语言,含 nav 键与入口副标题 `entryHint`),四语言同步;禁止硬编码中文。
|
||||
|
||||
---
|
||||
|
||||
## 9. 实现顺序(2026-09-17 一期落地;2026-09-21 增补第 8 项)
|
||||
|
||||
1. 模型 + 迁移 + 同步(含 WHERE 与客户/姓名 JOIN)
|
||||
2. GET 列表
|
||||
3. 保存批次与状态
|
||||
4. 单行通知 + 锁定 + 审计
|
||||
5. 联合回复保存 + 批量通知
|
||||
6. 07:00 排程
|
||||
7. 功能权限键 + 用户表单勾选 + 菜单守卫(可选部门批量发放)
|
||||
8. (2026-09-21)07:00 到期排程 Web 进程内兜底扫描(`SCHEDULE_WEB_SCANNER_ENABLED`)+ 同步完成提醒生管 + `order-delivery-remind` 日批提醒(出货/未回复,布尔开关独立启停 + 天数可配)+ 工作台列顺序修订与合并展示
|
||||
|
||||
---
|
||||
|
||||
## 10. 风险
|
||||
|
||||
| 风险 | 处理 |
|
||||
| --- | --- |
|
||||
| `HXJM.GEN_FILE` 不存在 | 回退 `ERP_GEN_FILE_V` |
|
||||
| 新员工未勾权限 | 无入口;可用用户管理单人勾选或部门批量发放 |
|
||||
| 同步覆盖回复 | upsert 白名单仅 ERP 列 |
|
||||
|
||||
---
|
||||
|
||||
## 11. 不在本期 / 后期
|
||||
|
||||
回写 ERP、解锁、对话式填交期(Chat 内直接填写批次)、邮件、撤回企微、订单类型列 / 已转请购 / 排定交货日、工作台单别列、每次请求按部门名称判定操作权限(已废止)、本 Agent 自绘企微卡片样式、v2 侧栏统计、独立 FastAPI。聊天侧栏与工作台首页的**跳转入口**已纳入一期(R-ENTRY-02):前端固定入口项,点击路由到工作台操作页,不新增 Dify 应用。
|
||||
|
||||
**后期:单别白名单管理配置。** 一期不做该页、不做同步 `IN` 过滤。后续加上时沿用已拍板的方案 A:配置表 `order_delivery_slip_settings`;GET/PUT `/admin/slips`;同步 WHERE 带启用 `slip_code`;空名单不拉行;新勾选保存后增量同步这些单别;取消勾选立即从列表隐藏并标 `erp_missing`;操作页始终不出单别列。预留列 `slip_code` 一期已写入快照。
|
||||
@@ -18,7 +18,7 @@
|
||||
| 6 | 推送过的视频默认勾选且不能取消勾选 | 已推送前缀(游标内)视频 checkbox 禁用,取消勾选请求被忽略 |
|
||||
| 7 | 【发布周任务】仅首次自动推首批 | 新建任务继承历史推送游标,仅当继承后游标为 0(无可继承进度)时按冻结顺序自动推首批 N 个;失败可用【立即新增任务补推】补发/增推 |
|
||||
| 8 | 定时脚本自动更新推送 | 平台排程每周一 09:00(Asia/Shanghai)自动滚动创建当周任务(继承游标并自动追加配置新增视频)并推送下一批,无需人工维护;视频库全部推完且配置无新增视频时**暂停滚动**,不创建内容重复的新一期任务,新视频上传后自动恢复 |
|
||||
| 9 | 消息推送规则(企微) | 任务发布即通知;每批推送成功立即通知;已延期(过截止未提交)人员在每批推送成功后立即收到延期提醒 |
|
||||
| 9 | 消息推送规则(企微) | 任务发布即通知;每批推送成功立即通知;已延期(过截止未提交)人员在每批推送成功后立即收到延期提醒;逾期/延期/定向催办文案携带期次标签(第N期+周次区间)供员工区分期次;同一员工同一自然天最多收到一条自动催办(多期未完成合并为一条汇总提醒),历史期任务过截止超过 100 天停止催办 |
|
||||
|
||||
---
|
||||
|
||||
@@ -37,6 +37,7 @@
|
||||
- `LeanTrainingWeeklyTask.pushed_video_count` 为游标:`video_resource_ids[0:pushed_video_count]` 是已推送前缀,`[pushed_video_count:]` 是待推送队列。
|
||||
- 每次推送从游标向后扫描,取 `weekly_count` 个**未被任何任务推送过**的新视频(跨任务按已推送前缀并集去重,已推送视频仅越过、绝不进批);推送成功后游标前进(越过跳过项与本批新视频;企微发送失败不影响游标,员工端已可见视频,失败明细记录在推送日志)。待推区间全部重复时游标直接推进到末尾并返回“全部推完”,不发送企微。
|
||||
- 已推送前缀中的视频即“推送过的视频”:管理端默认勾选且不可取消;跨周滚动创建新任务时游标继承最近一期进度,**HR 手动新建下一期任务同样继承游标**(取新冻结列表的“最长已推送前缀”长度,以全部已发布任务已推送前缀并集为基线),保证从上一任务断点续推,绝不从 0 重推首批,全局不重复推。
|
||||
- **本期视频口径(首推归属)**:自动滚动会把上一期冻结列表原样复制进新一期,若按累积前缀展示/考核,上一期已推送视频会在新一期重复出现并要求重学。因此学员端展示、观看/完成校验、管理看板视频列统一按“**本任务首次推送**”口径取数(`_own_pushed_video_ids()`:已推送前缀中此前其它更早期任务未推送过的部分);上一期已推送视频不再重复展示、不要求重学。游标本身保持跨周连续推进的绝对进度语义(`pushed_video_count` ≠ 本周推送数量)。
|
||||
|
||||
实现:`pending_video_ids()` / `push_lean_training_videos()`([lean_training_push_service.py](../../../backend/app/services/lean_training_push_service.py))。
|
||||
|
||||
@@ -78,16 +79,19 @@
|
||||
| --- | --- | --- |
|
||||
| 任务发布通知 | 周任务发布(手动发布或排程滚动创建)后立即发送 | `training_lean_task_initial` / `task-initial` |
|
||||
| 视频批次推送 | 每批 N 个视频推送成功后立即发送 | `training_lean_video_push` / `video-push-<游标起>-<游标止>` |
|
||||
| 延期提醒 | 每批推送成功后,立即对该任务中已过截止且未提交感悟的受训人员发送 | `training_lean_overdue` / `overdue-after-push-<游标起>-<游标止>` |
|
||||
| 周中催学(既有) | 每日 09:00 扫描,截止后的周一/周三/周五发送 | `training_lean_overdue` / `overdue-<日期>` |
|
||||
| 延期提醒 | 每批推送成功后,立即对该任务中已过截止且未提交感悟的受训人员发送 | `training_lean_overdue` / `overdue-<北京日期>`(与周中催学共用,每人每天一条) |
|
||||
| 周中催学(既有) | 每日 09:00 扫描,截止后的周一/周三/周五发送;多期未完成对同一员工合并为一条汇总提醒 | `training_lean_overdue` / `overdue-<日期>` |
|
||||
| 定向提醒(既有) | HR 在管理端对指定未完成员工手动发送 | `training_lean_targeted_reminder` / `targeted-<uuid>`(每次点击唯一) |
|
||||
|
||||
- 所有提醒经 `LeanTrainingReminder`(`weekly_task_id + recipient_user_id + event_key` 唯一约束)幂等,同批重推/补发不会重复打扰。
|
||||
- **每人每天最多一条自动催办(2026-09-30 新增)**:排程扫描与推送后延期提醒共用同一事件键 `overdue-<北京日期>` 与"当天已催办"前置查询——多期过期任务并存、两条催办路径同天先后执行、批次重复推送等场景下,同一员工同一自然天只会收到一条精益催办企微;多期未完成时文案汇总各期次标签(标题注明"共N期未完成",卡片跳转其最近一期未完成任务)。
|
||||
- **例外**:定向提醒由 HR 手动触发,每次点击都应真实触达员工,因此 `event_key` 每次唯一化(`targeted-<uuid>`),不参与幂等去重;其余事件键保持稳定,保证重推/补发不重复打扰。
|
||||
- 全部提醒卡片消息发送至企微「和信AI智能工作台」应用会话,点击卡片跳转员工培训聊天页并自动展开精益管理页签:跳转路径 `/chat/<agentId>?training_type=lean_management&weekly_task_id=<id>`,agent id **按环境动态解析**:优先取配置 `WECOM_LEAN_TRAINING_JUMP_AGENT_ID` 显式覆盖,否则按启用 Agent 中 `handler_config.content_profile='training'` 自动定位「员工培训」(测试/正式环境 Agent ID 不同,动态解析保证均可直达精益页签;解析失败回退历史默认 27);前端由 [TrainingWorkspacePanel.vue](../../../frontend/src/features/chat/components/TrainingWorkspacePanel.vue) 消费 query 参数自动展开(管理员进管理端精益看板、学员进学员侧精益学习页)。
|
||||
- "已延期"判定:当前时间 > 任务 `due_at` 且该用户未提交(`LeanTrainingCompletion.status != 'completed'`)的在职受训人员,与管理端看板"已延期"状态口径一致。
|
||||
- **期次标签(2026-09-30 新增)**:逾期提醒、延期提醒、定向提醒的标题追加「(第N期)」、内容以「第N期(MM-DD至MM-DD)」开头(期号与学员端"第N期"口径一致);多期任务并存扫描时各期催办文案可被员工区分,避免"完成当期后仍收到历史期相同提醒"被误认为系统误推。周中催学对同一员工的多期未完成合并为一条(单期保持单期文案,多期标题注明"共N期未完成"、内容列明各期区间);`week_key` 解析失败时回退历史文案("本周…"),提醒不因标签失败而中断。
|
||||
- **催办宽限期(2026-09-30 新增)**:任务过截止超过 100 天(`OVERDUE_REMINDER_STOP_AFTER_DAYS`)后停止催办——周中催学扫描不再为其生成事件键,历史期手动补推触发的推送后延期提醒同样静默;任务仍保持 published 供管理端查询与统计,仅不再对旧账发送企微。
|
||||
|
||||
实现:`_send_reminder()` / `notify_overdue_users_after_push()`([lean_training_reminder_service.py](../../../backend/app/services/lean_training_reminder_service.py))。
|
||||
实现:`_period_labels()` / `_overdue_event_key()` / `_has_overdue_reminder_today()` / `_send_reminder()` / `notify_overdue_users_after_push()` / `run_lean_training_reminders()`([lean_training_reminder_service.py](../../../backend/app/services/lean_training_reminder_service.py))。
|
||||
|
||||
---
|
||||
|
||||
@@ -98,7 +102,7 @@
|
||||
- **每周任务数量**:设置 N,提示文案展示"每周一 09:00 按该数量从视频列表顺序推送下一批(已推送 {pushed}/{total})"。
|
||||
- **视频勾选锁定**:已推送前缀视频 checkbox 禁用并带绿色「第X周 MM-DD至MM-DD」标签;未推送视频可自由勾选/取消(未全选时保存走"自动倒序冻结"或按所选冻结)。
|
||||
- **完成名单看板**(学员工作区「培训管理 → 精益管理」页签,`GET /lean-training/dashboard`):
|
||||
- 视频名称列仅展示**本周期已推送、要求学习的视频**(`video_resource_ids[:pushed_video_count]` 游标前缀),与学员端可见范围一致;未推送视频不出现,游标为 0 时显示 `--`;
|
||||
- 视频名称列仅展示**本周期布置、要求学习的视频**(本任务首次推送的部分,见 2.2「本期视频口径」),与学员端可见范围一致;历史期已推送视频与未推送视频均不出现,无首推视频时显示 `--`;
|
||||
- 总结列最多预览 15 个字,超出截断显示省略号,点击弹框查看完整文案(无总结显示 `--`);
|
||||
- 名单合为单一明细表(状态列区分已完成/已延期/进行中),表头铺满容器宽度。
|
||||
- **【发布周任务】**:保存并发布**所选周**任务;首次发布(游标为 0)立即推送首批 N 个视频,编辑已推过的任务不重复触发。
|
||||
@@ -112,7 +116,7 @@
|
||||
## 6. 学员端(员工工作台「精益管理培训」)
|
||||
|
||||
- 时间树按发布周期倒序展示各期任务,**期号采用后端 `week_index`**(第 1 期最早),与管理端口径一致。
|
||||
- 每期任务展示:周次区间(week_key ~ 截止日)、任务状态徽章(进行中/已延期/已完成)、当期已推送视频列表(仅游标内前缀,新批次推送后立即可学)、观看打卡与学习感悟提交(字数下限校验)。
|
||||
- 每期任务展示:周次区间(week_key ~ 截止日)、任务状态徽章(进行中/已延期/已完成)、当期视频列表(仅本任务首次推送的部分——自动滚动复制的上一期已推送视频不重复展示、不要求重学)、观看打卡与学习感悟提交(字数下限校验;完成校验同样只考核本期视频)。
|
||||
- 学员端接口:`GET /api/user/lean-training/my-tasks`、`POST /api/user/lean-training/my-tasks/watched`、`PUT /api/user/lean-training/completions`。
|
||||
- 联动关系:排程/管理员推送成功后,`pushed_video_count` 前进,学员端下次拉取即看到新视频;企微通知点击跳转 `/workspace`(`training_type=lean_management`)。
|
||||
|
||||
|
||||
+19
-2
@@ -1,5 +1,21 @@
|
||||
# 智能HR请假管理功能清单
|
||||
|
||||
## 订单交期回复 Agent
|
||||
|
||||
| 功能项 | 状态 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| ERP 订单行同步 | 已实现 | 每天 07:00(Asia/Shanghai)排程 + 生管手动全量同步,同步成功后按任务参数「同步完成提醒收件人」提醒生管(与「通知人」互相独立,留空回退通知人);到期排程由独立 worker 进程执行(`workers/worker_scheduler.py` / 生产 `hxops-schedule-worker` 容器;2026-09-29 合并 dev 主线后 Web 进程不再兜底扫描);只拉已审核(`oeaconf='Y'`)+ 已核准(`oea49='1'`)+ 未结案(`oeb70≠Y`)+ 完全未交(`NVL(oeb24,0)=0`,已有交货的行不同步)的订单行到本地快照(`order_delivery_erp_lines`),upsert 仅更新 ERP 列白名单不覆盖回复;本轮未命中行标 `erp_missing` 不删除;失败保留上次快照并展示最近同步时间。 |
|
||||
| 同步完成提醒生管 | 已实现 | 07:00 排程同步成功后,按该排程任务的「通知开关 + 通知人」(管理端排程表单现成配置,人员可配置)给生管发企微提醒查看当天交期回复(复用 `send_wecom_event_message`,事件 `order_delivery_reply_notify`);通知失败不影响同步结果;已置 `domain_notification_managed` 抑制通用排程完成通知避免双重打扰。 |
|
||||
| 订单行查询台 | 已实现 | 工作台操作页筛选分页:**关键词合并搜索**(订单单号/客户订单/客户编号/客户简称/公司全名/产品编号/品名/客户产品编号/业务员/交期回复人员命中任一,2026-09-21 由三框合并、2026-09-23 增补人员搜索)+ 订单日期 + 状态(全部·已回复·未完全回复),默认排序订单日期→客户→单号→项次,分页默认 50;列顺序:客户编号(副文案简称) → 订单日期 → 订单单号:项次 → 产品编号(副文案品名) → 客户产品编号 → 数量 → 约定交货日 → 交期回复状态 → 交期回复 → 交期回复人员 → 业务员(副文案部门) → 客户订单 → 规格 → 单位(独立的部门列/品名列已取消,与业务员/产品编号合并展示);表格浏览体验:页面高度收敛至视口(列头固定、横向滚动条常驻)、左侧冻结前四列标识区(勾选/客户编号/订单日期/订单单号:项次,已收窄)、行高紧凑(长文本截断悬停看全文、批次条不折行)、筛选区与工具栏字号与表格统一并压缩高度(全页 text-sm 14px,状态徽标例外 text-xs 12px 加粗);列表不出已交/未交两列(完全未交过滤后无信息量);行状态读时推导未回复/部分回复/已回复;列表不出单别、订单类型、已转请购、排定交货日。 |
|
||||
| 每日提醒(出货 + 未回复) | 已实现 | 新排程 `order-delivery-remind`(日批 07:10,种子 `SCH-ORDER-DELIVERY-REMIND`):① 已回复(已锁定)行的回复交期距今 ≤「出货提醒提前天数」(默认 3,任务参数可配)时按业务员聚合发一条企微提醒安排出货,同一(行,交期)只提醒一次、发送失败次日自动补发;② 超过「未回复再次提醒天数」(默认 3,任务参数可配)仍未回复的行按收件人聚合一并企微提醒生管(收件人=任务参数「未回复提醒收件人」多选,候选全部启用用户可搜索,与运行结果通知的「通知人」互相独立,留空回退通知人),同一行每 N 天最多提醒一次;两类提醒由任务参数 `ship_remind_enabled` / `unreplied_remind_enabled`(布尔,默认开)独立启停;提醒逐行写审计 `ship_remind` / `unreplied_remind`,只读业务数据不改批次/锁定;提醒天数钳制 0-3650(防日期溢出崩溃,2026-09-22 修复)。 |
|
||||
| 单行 / 拆分回复 | 已实现 | 弹窗维护 1..20 批「交期 + 数量 + 备注」,交期必填、数量>0、备注≤200、交期不重复,支持快速统一交期;行徽标展示「订单数量:X 单位」;**数量守恒**:各批次合计必须等于订单数量才能保存;缺交期/缺数量、同单批次交期重复均按批次序号实时提示并随填写切换(2026-09-23 由「超额仅提醒」修订,后端 422 `BATCH_QTY_TOTAL_MISMATCH` / `BATCH_INVALID` 兜底);未锁定行整表替换批次;已锁定行 409。 |
|
||||
| 联合回复与批量通知 | 已实现 | 勾选多行(全选仅本页)「联合回复交期」逐行保存批次(单次≤200 行,单行失败不回滚其它行;每行各批次合计须等于订单数量,不等行按行失败);通知唯一入口为工具栏「批量通知」(列表不出通知列,已通知对象与时间并入「交期回复人员」列),对已有批次且未锁定的行逐行发送并锁定,无批次/已锁定跳过并汇总提示。 |
|
||||
| 企微通知与行级锁定 | 已实现 | 复用平台 `send_wecom_event_message`(textcard 壳 + 既有回执审计,不自绘卡片);收件人按订单业务员 `oea14`→`User.employee_id`→企微 userid,对不上该行失败不锁定;发送成功与 locked 同事务(禁止已通知未锁定);正文「您有订单号:项次{单号}:{项次}的订单需要填写/确认/查看交期。」;四类卡片按类型带参直达操作页(行通知带单号+项次定位高亮、提醒卡带状态筛选),未登录先登录后原样回跳。 |
|
||||
| 功能权限与审计 | 已实现 | 用户功能权限 `order_delivery_reply.manage`(生管可写)/ `access`(业务只读),admin 默认开,用户管理表单勾选(四语言),可选按部门一次性批量发放;保存/通知/锁定/同步/出货提醒/未回复提醒六类审计(`order_delivery_audit_events`)。单别白名单管理为后期(`slip_code` 已落库预留)。 |
|
||||
| 入口(独立应用) | 已实现 | 应用管理注册内置 iframe 应用(`agent_code=order_delivery_reply`,不接 Dify):出现在应用管理/全部应用/聊天侧栏,点击在聊天壳内整页打开操作页(免布局嵌入路由);入口可见性走 Agent 权限(admin 自动可见),页面与 API 仍受 `access`/`manage` 功能权限守卫;工作台侧栏货代分组不设菜单项。 |
|
||||
|
||||
需求权威:[docs/features/order-delivery-reply/demand.md](features/order-delivery-reply/demand.md)。
|
||||
|
||||
## 可配置权限组(2026-09)
|
||||
|
||||
| 功能项 | 状态 | 说明 |
|
||||
@@ -10,6 +26,7 @@
|
||||
| 用户只选角色 | 已实现 | 新建用户默认普通用户;改角色须确认;按人勾应用、应用页按人授权、权限申请通过加应用,在角色包启用后一律拒绝(`ROLE.DIRECT_GRANT_DISABLED`)。 |
|
||||
| 工作台进入管理控制台 | 已实现 | AI 工作台侧栏底部「返回聊天」上方,仅平台管理员(`is_platform_admin`)显示「管理控制台」并跳转 `/admin`;普通用户不渲染入口。 |
|
||||
|
||||
|
||||
## 合同付款预警 Agent
|
||||
|
||||
| 功能项 | 状态 | 说明 |
|
||||
@@ -81,8 +98,8 @@
|
||||
| 首页培训推荐入口 | 前端已实现 | 当 Agent 开启培训模式后,工作台首页会在应用列表上方展示培训强入口卡片 |
|
||||
| 培训记录后端落库 | 已实现 | 已新增培训记录模型、迁移与用户/管理端 API,考试进度、结果、统计与导出均可走后端数据源 |
|
||||
| 培训配置管理 | 已实现 | `TrainingConfigResource` 增加 `training_level`;管理端按公司级、部门级、班组级卡片独立增删资料;知识库候选仅允许“员工培训”分组内未删除文档的当前版本;员工端按 `safetyStage` 动态展示当前级别资料;培训资料区直接上传的视频列表超过 3 条时默认收起(仅展示前 3 条),底部可展开查看全部/收起,切换培训类型恢复收起、上传新视频后自动展开 |
|
||||
| 精益培训对象化任务与提醒 | 已实现 | HR 按系统角色或指定用户(并集)发布精益周任务;任务、看板和提醒只处理冻结对象,首次发布与定向催学均复用企微提醒审计幂等去重。学员端“精益管理”按时间树展示全部已发布任务(按任务周期倒序、最新在上),每期任务带状态徽章(进行中/已延期/已完成,由服务端按截止时间与完成记录判定)、任务周期区间与视频缩略图(点击弹窗播放,须播放到结尾才判定观看完成并由服务端持久化,提前关闭或拖拽跳过不计);提交学习感悟前校验:未观看全部已推送视频或感悟字数不达标时拦截并友好提示;任务"已完成"仅在感悟提交后落定。 |
|
||||
| 精益周任务规则化推送 | 已实现 | 任务周(周一)与截止时间默认按当周计算且**支持修改**(可指定任意自然周与截止时刻,须为周一且截止不早于所选周周一;修改后【发布周任务】/【立即新增任务补推】均作用于所选周任务);培训视频列表分页展示(4 条/页),已推送视频默认勾选、不可取消并带"第X周 MM-DD至MM-DD"周次标签,推过的视频不重复推直至全部推完(跨任务按已推送前缀并集去重,手动新建下一期任务同样继承历史推送游标、绝不从 0 重推首批);【发布周任务】对所选周任务发布并仅当继承游标为 0 时自动推首批,【立即新增任务补推】按游标对所选周任务增推(点击时若表单勾选/规则与已保存任务不一致,自动先保存再推送,避免按旧冻结清单推送误报全部推完);平台排程每周一 09:00(Asia/Shanghai)自动滚动创建当周任务(模板取严格早于当周的最近一期,游标继承进度,并自动追加配置新增视频到冻结列表末尾,前缀与游标不变、从断点只推新视频;视频库全部推完且无新增视频时暂停滚动、不再创建内容重复的新一期,新视频上传后自动恢复)并推送下一批,无需人工维护;每批推送成功后立即向受训人员发送企微通知,并对"已延期"(过截止未提交)人员立即发送延期提醒(event_key 幂等防重);学员端任务期号统一采用后端 week_index 口径。规则手册见 [docs/features/training/精益管理周任务规则手册.md](features/training/精益管理周任务规则手册.md) |
|
||||
| 精益培训对象化任务与提醒 | 已实现 | HR 按系统角色或指定用户(并集)发布精益周任务;任务、看板和提醒只处理冻结对象,首次发布与定向催学均复用企微提醒审计幂等去重。学员端“精益管理”按时间树展示全部已发布任务(按任务周期倒序、最新在上),每期任务带状态徽章(进行中/已延期/已完成,由服务端按截止时间与完成记录判定)、任务周期区间与视频缩略图(点击弹窗播放,须播放到结尾才判定观看完成并由服务端持久化,提前关闭或拖拽跳过不计);提交学习感悟前校验:未观看全部本期视频(本任务首次推送的部分,上一期已推送视频不重复展示、不要求重学)或感悟字数不达标时拦截并友好提示;任务"已完成"仅在感悟提交后落定。 |
|
||||
| 精益周任务规则化推送 | 已实现 | 任务周(周一)与截止时间默认按当周计算且**支持修改**(可指定任意自然周与截止时刻,须为周一且截止不早于所选周周一;修改后【发布周任务】/【立即新增任务补推】均作用于所选周任务);培训视频列表分页展示(4 条/页),已推送视频默认勾选、不可取消并带"第X周 MM-DD至MM-DD"周次标签,推过的视频不重复推直至全部推完(跨任务按已推送前缀并集去重,手动新建下一期任务同样继承历史推送游标、绝不从 0 重推首批);【发布周任务】对所选周任务发布并仅当继承游标为 0 时自动推首批,【立即新增任务补推】按游标对所选周任务增推(点击时若表单勾选/规则与已保存任务不一致,自动先保存再推送,避免按旧冻结清单推送误报全部推完);平台排程每周一 09:00(Asia/Shanghai)自动滚动创建当周任务(模板取严格早于当周的最近一期,游标继承进度,并自动追加配置新增视频到冻结列表末尾,前缀与游标不变、从断点只推新视频;视频库全部推完且无新增视频时暂停滚动、不再创建内容重复的新一期,新视频上传后自动恢复)并推送下一批,无需人工维护;每批推送成功后立即向受训人员发送企微通知,并对"已延期"(过截止未提交)人员立即发送延期提醒(event_key 幂等防重;逾期/延期/定向催办文案携带期次标签「第N期+周次区间」供员工区分期次;同一员工同一自然天最多收到一条自动催办,多期未完成合并为一条汇总提醒,排程扫描与推送后延期提醒共用当天去重;历史期任务过截止超过 100 天停止催办、任务保持可查询但不再推送企微);学员端任务期号统一采用后端 week_index 口径;学员端"本期视频"为本任务首次推送的部分(自动滚动复制上一期冻结列表后,上一期已推送视频不在新一期重复展示、不要求重学,游标保持跨周绝对进度语义)。规则手册见 [docs/features/training/精益管理周任务规则手册.md](features/training/精益管理周任务规则手册.md) |
|
||||
| 培训分享入口 | 前端已实现 | 员工培训页培训类型页签行右侧新增分享按钮,仅具备 `training_hr_manage`(培训管理)权限的用户可见;点击弹出分享弹窗,支持复制链接或下载二维码,链接指向 `/chat/<agentId>?training_type=<当前培训类型>` 深链,接收者点击或扫码后在登录页登录,登录成功自动回跳员工培训页并定位到对应培训类型(如“出国规章培训”);文案覆盖 zh-CN/zh-TW/en/th 四语言 |
|
||||
| 培训主链推荐架构 | 已文档化 | 推荐采用“受控考试主链 + Dify 辅助问答/ChatBI”的混合方案;培训 Agent 对接 Dify 时会额外透传后台账号 `role`,便于区分学员/HR 问答分支,见 [docs/新人入职培训Agent_推荐落地方案.md](新人入职培训Agent_推荐落地方案.md) |
|
||||
| 培训业务闭环整改清单 | 已文档化 | 见[docs/新人入职培训Agent_闭环整改清单.md](新人入职培训Agent_闭环整改清单.md) |
|
||||
|
||||
@@ -8,6 +8,7 @@ import { authRoutes } from './auth.routes';
|
||||
import { chatRoutes } from './chat.routes';
|
||||
import { kbRoutes } from './kb.routes';
|
||||
import { workspaceRoutes } from './workspace.routes';
|
||||
import { orderDeliveryReplyEmbedRoute } from './workspace.routes';
|
||||
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
||||
import { DEFAULT_CHAT_AGENT_ID } from '@/shared/constants/routes';
|
||||
|
||||
@@ -21,6 +22,7 @@ export const appRoutes: RouteRecordRaw[] = [
|
||||
},
|
||||
},
|
||||
...authRoutes,
|
||||
orderDeliveryReplyEmbedRoute,
|
||||
...workspaceRoutes,
|
||||
...chatRoutes,
|
||||
...adminRoutes,
|
||||
|
||||
@@ -5,10 +5,20 @@
|
||||
* 逻辑:WorkspaceLayout 嵌套应用首页、知识库、排程、反馈等子页;合同付款、立账凭证旧地址重定向到 Chat Agent。
|
||||
*/
|
||||
import type { RouteRecordRaw } from 'vue-router';
|
||||
import { ORDER_DELIVERY_REPLY_ACCESS_PERMISSION } from '@/features/order-delivery-reply/constants';
|
||||
|
||||
// 合同付款 / 立账凭证旧工作台地址 → 聊天 Agent 重定向壳(dev 侧重构引入)。
|
||||
const contractPaymentChatRedirect = () => import('@/features/contract-payment/views/ContractPaymentChatRedirect.vue');
|
||||
const voucherCheckChatRedirect = () => import('@/features/voucher-check/views/VoucherCheckChatRedirect.vue');
|
||||
|
||||
// 订单交期回复嵌入路由:应用管理 iframe 应用的目标(无工作台布局壳,聊天壳内整页渲染)。
|
||||
export const orderDeliveryReplyEmbedRoute: RouteRecordRaw = {
|
||||
path: '/apps/order-delivery-reply',
|
||||
name: 'app-order-delivery-reply',
|
||||
component: () => import('@/features/order-delivery-reply/views/OrderDeliveryReplyPage.vue'),
|
||||
meta: { title: 'workspace.nav.orderDeliveryReply', requiresFeaturePermission: ORDER_DELIVERY_REPLY_ACCESS_PERMISSION },
|
||||
};
|
||||
|
||||
export const workspaceRoutes: RouteRecordRaw[] = [
|
||||
{
|
||||
path: '/workspace',
|
||||
@@ -92,6 +102,12 @@ export const workspaceRoutes: RouteRecordRaw[] = [
|
||||
component: voucherCheckChatRedirect,
|
||||
meta: { title: 'workspace.voucherCheck.detailTitle' },
|
||||
},
|
||||
{
|
||||
path: 'order-delivery-reply',
|
||||
name: 'workspace-order-delivery-reply',
|
||||
component: () => import('@/features/order-delivery-reply/views/OrderDeliveryReplyPage.vue'),
|
||||
meta: { title: 'workspace.nav.orderDeliveryReply', requiresFeaturePermission: ORDER_DELIVERY_REPLY_ACCESS_PERMISSION },
|
||||
},
|
||||
{
|
||||
path: 'contract-payment',
|
||||
name: 'workspace-contract-payment',
|
||||
|
||||
@@ -133,6 +133,20 @@ const loadOptions = async (source: string): Promise<void> => {
|
||||
}
|
||||
};
|
||||
|
||||
/** multi_select 选项本地搜索词(按字段 key 隔离)。 */
|
||||
const multiSearch = reactive<Record<string, string>>({});
|
||||
|
||||
/** multi_select 选项按关键词过滤(匹配 label/描述,大小写不敏感)。 */
|
||||
const filteredMultiOptions = (field: PlatformTaskParamField) => {
|
||||
const keyword = (multiSearch[field.key] || '').trim().toLowerCase();
|
||||
const all = optionsCache[field.options_source || ''] || [];
|
||||
if (!keyword) return all;
|
||||
return all.filter((o) =>
|
||||
String(o.label || '').toLowerCase().includes(keyword) ||
|
||||
String(o.description || '').toLowerCase().includes(keyword),
|
||||
);
|
||||
};
|
||||
|
||||
/** multi_select 勾选切换。 */
|
||||
const toggleMultiValue = (key: string, value: string | number): void => {
|
||||
const current: Array<string | number> = Array.isArray(params.value[key]) ? [...params.value[key]] : [];
|
||||
@@ -323,6 +337,12 @@ watch(
|
||||
v-else-if="field.type === 'multi_select'"
|
||||
class="max-h-52 space-y-1 overflow-y-auto rounded-xl border border-default bg-surface p-2"
|
||||
>
|
||||
<input
|
||||
v-model="multiSearch[field.key]"
|
||||
type="text"
|
||||
class="mb-1 w-full rounded-lg border border-default px-2 py-1.5 text-sm outline-none focus:border-blue-500"
|
||||
:placeholder="$t('admin.schedule.form.dynamicParamsSearchPlaceholder')"
|
||||
/>
|
||||
<p v-if="optionsLoading[field.options_source || '']" class="px-2 py-1 text-xs text-muted">
|
||||
{{ $t('admin.schedule.form.dynamicParamsOptionsLoading') }}
|
||||
</p>
|
||||
@@ -332,8 +352,14 @@ watch(
|
||||
>
|
||||
{{ $t('admin.schedule.form.dynamicParamsNoOptions') }}
|
||||
</p>
|
||||
<p
|
||||
v-else-if="!filteredMultiOptions(field).length"
|
||||
class="px-2 py-1 text-xs text-muted"
|
||||
>
|
||||
{{ $t('admin.schedule.form.dynamicParamsSearchNoMatch') }}
|
||||
</p>
|
||||
<label
|
||||
v-for="option in optionsCache[field.options_source || ''] || []"
|
||||
v-for="option in filteredMultiOptions(field)"
|
||||
:key="String(option.value)"
|
||||
class="flex cursor-pointer items-start gap-2 rounded-lg px-2 py-1.5 text-sm transition hover:bg-surface-soft"
|
||||
>
|
||||
|
||||
@@ -120,6 +120,39 @@ const { t } = useI18n();
|
||||
<span class="block text-xs leading-5 text-muted">{{ t('admin.user.fields.trainingHrManageHint') }}</span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="flex items-start gap-3 rounded-xl border border-default bg-white px-4 py-3">
|
||||
<input
|
||||
v-model="form.feature_permissions['contract_payment.access']"
|
||||
type="checkbox"
|
||||
class="mt-0.5 h-4 w-4 rounded border-default text-brand-600 focus:ring-brand-500"
|
||||
/>
|
||||
<span class="space-y-1">
|
||||
<span class="block text-sm font-medium text-primary">{{ t('admin.user.fields.contractPaymentAccess') }}</span>
|
||||
<span class="block text-xs leading-5 text-muted">{{ t('admin.user.fields.contractPaymentAccessHint') }}</span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="flex items-start gap-3 rounded-xl border border-default bg-white px-4 py-3">
|
||||
<input
|
||||
v-model="form.feature_permissions['order_delivery_reply.manage']"
|
||||
type="checkbox"
|
||||
class="mt-0.5 h-4 w-4 rounded border-default text-brand-600 focus:ring-brand-500"
|
||||
/>
|
||||
<span class="space-y-1">
|
||||
<span class="block text-sm font-medium text-primary">{{ t('admin.user.fields.orderDeliveryReplyManage') }}</span>
|
||||
<span class="block text-xs leading-5 text-muted">{{ t('admin.user.fields.orderDeliveryReplyManageHint') }}</span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="flex items-start gap-3 rounded-xl border border-default bg-white px-4 py-3">
|
||||
<input
|
||||
v-model="form.feature_permissions['order_delivery_reply.access']"
|
||||
type="checkbox"
|
||||
class="mt-0.5 h-4 w-4 rounded border-default text-brand-600 focus:ring-brand-500"
|
||||
/>
|
||||
<span class="space-y-1">
|
||||
<span class="block text-sm font-medium text-primary">{{ t('admin.user.fields.orderDeliveryReplyAccess') }}</span>
|
||||
<span class="block text-xs leading-5 text-muted">{{ t('admin.user.fields.orderDeliveryReplyAccessHint') }}</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
|
||||
|
||||
@@ -236,6 +236,9 @@ export function useUsersAdmin() {
|
||||
phone_number: user.phone_number || '',
|
||||
feature_permissions: {
|
||||
training_hr_manage: Boolean(user.feature_permissions?.training_hr_manage),
|
||||
'order_delivery_reply.manage': Boolean(user.feature_permissions?.['order_delivery_reply.manage']),
|
||||
'order_delivery_reply.access': Boolean(user.feature_permissions?.['order_delivery_reply.access']),
|
||||
'contract_payment.access': Boolean(user.feature_permissions?.['contract_payment.access']),
|
||||
},
|
||||
agent_ids: user.agent_ids || [],
|
||||
};
|
||||
|
||||
@@ -15,6 +15,9 @@ export interface UserFormState {
|
||||
phone_number: string;
|
||||
feature_permissions: {
|
||||
training_hr_manage: boolean;
|
||||
'order_delivery_reply.manage': boolean;
|
||||
'order_delivery_reply.access': boolean;
|
||||
'contract_payment.access': boolean;
|
||||
};
|
||||
agent_ids: number[];
|
||||
}
|
||||
@@ -53,6 +56,9 @@ export const createEmptyUserForm = (): UserFormState => ({
|
||||
phone_number: '',
|
||||
feature_permissions: {
|
||||
training_hr_manage: false,
|
||||
'order_delivery_reply.manage': false,
|
||||
'order_delivery_reply.access': false,
|
||||
'contract_payment.access': false,
|
||||
},
|
||||
agent_ids: [],
|
||||
});
|
||||
|
||||
@@ -420,6 +420,7 @@ watch(() => page.currentAgentId, () => {
|
||||
|
||||
@go-workspace="page.goToWorkspace()"
|
||||
|
||||
|
||||
@go-admin="page.goToAdmin"
|
||||
|
||||
@logout="page.handleLogout"
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* 订单交期回复 API 类型与请求封装。
|
||||
* 依赖:统一 requestJson(失败抛 BusinessError);后端 /api/order-delivery-reply。
|
||||
* 逻辑:列表筛选分页、保存批次(单行/联合)、单行与批量通知、手动同步与最近同步状态。
|
||||
*/
|
||||
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
|
||||
/** 已保存的交期批次(计划交期 + 数量 + 可选备注)。 */
|
||||
export interface DeliveryBatch {
|
||||
seq?: number;
|
||||
planned_date: string;
|
||||
qty: string;
|
||||
remark?: string | null;
|
||||
}
|
||||
|
||||
/** 工作台订单行:ERP 快照 + 读时推导的回复状态。 */
|
||||
export interface OrderDeliveryLine {
|
||||
id: number;
|
||||
order_no: string;
|
||||
line_no: number;
|
||||
order_date?: string | null;
|
||||
customer_no?: string | null;
|
||||
customer_short_name?: string | null;
|
||||
customer_full_name?: string | null;
|
||||
salesperson_code?: string | null;
|
||||
salesperson_name?: string | null;
|
||||
dept_code?: string | null;
|
||||
dept_name?: string | null;
|
||||
customer_po?: string | null;
|
||||
part_no?: string | null;
|
||||
part_name?: string | null;
|
||||
spec?: string | null;
|
||||
customer_part_no?: string | null;
|
||||
agreed_date?: string | null;
|
||||
unit?: string | null;
|
||||
qty?: string | null;
|
||||
delivered_qty?: string | null;
|
||||
undelivered_qty?: string | null;
|
||||
status: 'not_replied' | 'partial_replied' | 'replied';
|
||||
locked: boolean;
|
||||
batches: DeliveryBatch[];
|
||||
notified_employee_id?: string | null;
|
||||
notified_user_name?: string | null;
|
||||
notified_at?: string | null;
|
||||
}
|
||||
|
||||
export interface OrderDeliveryListParams {
|
||||
/** 合并搜索关键词:订单单号/客户订单/客户编号/客户简称/公司全名/产品编号/品名/客户产品编号命中任一 */
|
||||
keyword?: string;
|
||||
order_date?: string;
|
||||
status?: '' | 'replied' | 'not_fully_replied';
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export interface OrderDeliveryListResponse {
|
||||
items: OrderDeliveryLine[];
|
||||
page: number;
|
||||
page_size: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface OrderDeliverySyncRun {
|
||||
id: number;
|
||||
trigger: 'scheduled' | 'manual';
|
||||
status: 'running' | 'success' | 'failed';
|
||||
started_at?: string | null;
|
||||
finished_at?: string | null;
|
||||
line_count: number;
|
||||
error_message?: string | null;
|
||||
}
|
||||
|
||||
/** 批量操作逐行结果:ok=false 带 error 文案;skipped 带 reason(already_locked / no_batches)。 */
|
||||
export interface BatchItemResult {
|
||||
order_no?: string;
|
||||
line_no?: number;
|
||||
ok: boolean;
|
||||
skipped?: boolean;
|
||||
reason?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface BatchSummary {
|
||||
succeeded: number;
|
||||
failed: number;
|
||||
skipped: number;
|
||||
items: BatchItemResult[];
|
||||
}
|
||||
|
||||
/** 分页查询已同步订单行(erp_missing 行由后端排除;keyword 为合并搜索关键词)。 */
|
||||
export const listOrderDeliveryLines = (params?: OrderDeliveryListParams) => {
|
||||
const query = new URLSearchParams();
|
||||
if (params?.keyword) query.set('keyword', params.keyword);
|
||||
if (params?.order_date) query.set('order_date', params.order_date);
|
||||
if (params?.status) query.set('status', params.status);
|
||||
if (params?.page) query.set('page', String(params.page));
|
||||
if (params?.page_size) query.set('page_size', String(params.page_size));
|
||||
const suffix = query.toString() ? `?${query.toString()}` : '';
|
||||
return requestJson<OrderDeliveryListResponse>(`/api/order-delivery-reply/lines${suffix}`);
|
||||
};
|
||||
|
||||
/** 保存单行交期批次(未锁定行整表替换)。 */
|
||||
export const saveOrderDeliveryBatches = (
|
||||
orderNo: string,
|
||||
lineNo: number,
|
||||
batches: { planned_date: string; qty: string | number; remark?: string | null }[],
|
||||
) =>
|
||||
requestJson<{ order_no: string; line_no: number; batches: DeliveryBatch[]; total_qty: string }>(
|
||||
`/api/order-delivery-reply/lines/${encodeURIComponent(orderNo)}/${lineNo}/batches`,
|
||||
{ method: 'PUT', body: JSON.stringify({ batches }) },
|
||||
);
|
||||
|
||||
/** 联合回复:对多行逐行保存批次(只保存,不通知不锁定)。 */
|
||||
export const batchReplyOrderDelivery = (
|
||||
items: { order_no: string; line_no: number; batches: { planned_date: string; qty: string | number; remark?: string | null }[] }[],
|
||||
) =>
|
||||
requestJson<BatchSummary>('/api/order-delivery-reply/batch-reply', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ items }),
|
||||
});
|
||||
|
||||
/** 单行发送通知业务部门(企微),成功后行级锁定。 */
|
||||
export const notifyOrderDeliveryLine = (orderNo: string, lineNo: number) =>
|
||||
requestJson<{ order_no: string; line_no: number; locked: boolean; notified_user_name?: string | null; notified_at?: string | null }>(
|
||||
`/api/order-delivery-reply/lines/${encodeURIComponent(orderNo)}/${lineNo}/notify`,
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
/** 批量通知勾选行;无批次/已锁定跳过,单行失败不回滚其它行。 */
|
||||
export const notifyOrderDeliveryBatch = (lines: { order_no: string; line_no: number }[]) =>
|
||||
requestJson<BatchSummary>('/api/order-delivery-reply/notify-batch', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ lines }),
|
||||
});
|
||||
|
||||
/** 手动触发 ERP 全量同步(范围与 07:00 排程一致)。 */
|
||||
export const runOrderDeliverySync = () =>
|
||||
requestJson<{ run_id: number | null; status: 'success' | 'skipped'; line_count: number }>(
|
||||
'/api/order-delivery-reply/sync',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
/** 最近一次同步运行记录;从未同步过返回 null。 */
|
||||
export const getLatestOrderDeliverySync = () =>
|
||||
requestJson<OrderDeliverySyncRun | null>('/api/order-delivery-reply/sync/latest');
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* features/order-delivery-reply/constants.ts
|
||||
* 用途:订单交期回复域共享常量(功能权限键)。
|
||||
* 依赖:与后端 app/models/user.py._role_default_feature_permissions 的键名一一对应。
|
||||
* 逻辑:manage=生管可写(保存/通知/同步),access=业务只读;manage 命中视为有 access。
|
||||
*/
|
||||
|
||||
export const ORDER_DELIVERY_REPLY_MANAGE_PERMISSION = 'order_delivery_reply.manage';
|
||||
export const ORDER_DELIVERY_REPLY_ACCESS_PERMISSION = 'order_delivery_reply.access';
|
||||
@@ -0,0 +1,691 @@
|
||||
/**
|
||||
* features/order-delivery-reply/views/OrderDeliveryReplyPage.vue
|
||||
* 用途:订单交期回复工作台操作页——筛选分页、单行/联合回复批次、单行/批量通知、手动同步。
|
||||
* 依赖:api/orderDeliveryReply.api(统一 requestJson)、useMessage、auth store(manage/access 权限)。
|
||||
* 逻辑:所有数据只读本地快照;保存与通知是两步(联合回复只保存,批量通知才发送并锁定);
|
||||
* 保存/通知成功后即时刷新列表(需求 §9);仅 access 用户隐藏全部写操作。
|
||||
* 回复弹窗数量守恒(2026-09-23 由「超额仅提醒」修订):每行各批次合计必须等于订单数量
|
||||
* 才能保存,弹窗实时红字提示 + 保存拦截,后端 422 兜底。
|
||||
* 企微卡片直达:登录回跳后 query 仍在,按 status/order_no/line_no 还原筛选并滚动高亮目标行,
|
||||
* wecom_trace 上报打开回执——保证「点卡片 → 登录 → 直达该 Agent 对应内容与位置」。
|
||||
* 列顺序:客户编号(简称副文案) → 订单日期 → 订单单号:项次 → 产品编号(品名副文案) →
|
||||
* 客户产品编号 → 数量 → 约定交货日 → 交期回复状态 → 交期回复 → 交期回复人员 →
|
||||
* 业务员(部门副文案) → 客户订单 → 规格 → 单位;独立的部门列/品名列已并入合并展示。
|
||||
* 浏览体验:页面高度收敛至视口(滚动全部发生在表格容器内 → 列头 sticky 固定、横向滚动条
|
||||
* 常驻表格底缘);左侧冻结前四列标识区(勾选/客户编号/订单日期/订单单号:项次,
|
||||
* 冻结单元格用实色背景防透出);筛选区与工具栏字号与表格统一(text-sm 14px)并压缩高度。
|
||||
*/
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, reactive, ref } from 'vue';
|
||||
import { useRoute } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
||||
import {
|
||||
ORDER_DELIVERY_REPLY_MANAGE_PERMISSION,
|
||||
} from '@/features/order-delivery-reply/constants';
|
||||
import {
|
||||
batchReplyOrderDelivery,
|
||||
getLatestOrderDeliverySync,
|
||||
listOrderDeliveryLines,
|
||||
notifyOrderDeliveryBatch,
|
||||
runOrderDeliverySync,
|
||||
saveOrderDeliveryBatches,
|
||||
type BatchSummary,
|
||||
type OrderDeliveryLine,
|
||||
type OrderDeliverySyncRun,
|
||||
} from '@/features/order-delivery-reply/api/orderDeliveryReply.api';
|
||||
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
const auth = useAuthStore();
|
||||
|
||||
/** manage 可写(保存/通知/同步);access 或 manage 可看(路由与侧栏已按 access 守卫)。 */
|
||||
const canManage = computed(() => auth.hasFeaturePermission(ORDER_DELIVERY_REPLY_MANAGE_PERMISSION));
|
||||
|
||||
/* ============ 列表查询 ============ */
|
||||
const filters = reactive({ keyword: '', order_date: '', status: '' as '' | 'replied' | 'not_fully_replied' });
|
||||
const appliedFilters = reactive({ ...filters });
|
||||
const items = ref<OrderDeliveryLine[]>([]);
|
||||
const total = ref(0);
|
||||
const page = ref(1);
|
||||
const pageSize = ref(50);
|
||||
const pageSizeOptions = [20, 50, 100, 200];
|
||||
const loading = ref(false);
|
||||
const latestSync = ref<OrderDeliverySyncRun | null>(null);
|
||||
|
||||
async function loadLines() {
|
||||
loading.value = true;
|
||||
try {
|
||||
const data = await listOrderDeliveryLines({ ...appliedFilters, page: page.value, page_size: pageSize.value });
|
||||
items.value = data.items;
|
||||
total.value = data.total;
|
||||
if (data.page !== page.value) page.value = data.page;
|
||||
} catch (error) {
|
||||
msg.error(error instanceof Error ? error.message : t('workspace.orderDeliveryReply.loadFailed'));
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadLatestSync() {
|
||||
try {
|
||||
latestSync.value = await getLatestOrderDeliverySync();
|
||||
} catch {
|
||||
latestSync.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
function doSearch() {
|
||||
clearHighlight();
|
||||
Object.assign(appliedFilters, filters);
|
||||
page.value = 1;
|
||||
void loadLines();
|
||||
}
|
||||
|
||||
function doReset() {
|
||||
Object.assign(filters, { keyword: '', order_date: '', status: '' });
|
||||
doSearch();
|
||||
}
|
||||
|
||||
/** 分页条:页码跳转(与管理控制台数据报表同一 PaginationBar 组件)。 */
|
||||
function goToPage(next: number) {
|
||||
if (next === page.value) return;
|
||||
page.value = next;
|
||||
void loadLines();
|
||||
}
|
||||
|
||||
/** 切换每页条数:回到第 1 页并重查。 */
|
||||
function changePageSize(size: number) {
|
||||
if (size === pageSize.value) return;
|
||||
pageSize.value = size;
|
||||
page.value = 1;
|
||||
void loadLines();
|
||||
}
|
||||
|
||||
/** 手动同步(manage):同步执行完成后刷新列表与最近同步时间。 */
|
||||
const syncing = ref(false);
|
||||
async function doSync() {
|
||||
syncing.value = true;
|
||||
try {
|
||||
const result = await runOrderDeliverySync();
|
||||
if (result.status === 'skipped') {
|
||||
msg.warning(t('workspace.orderDeliveryReply.syncSkipped'));
|
||||
} else {
|
||||
msg.success(t('workspace.orderDeliveryReply.syncDone', { count: result.line_count }));
|
||||
}
|
||||
await Promise.all([loadLines(), loadLatestSync()]);
|
||||
} catch (error) {
|
||||
msg.error(error instanceof Error ? error.message : t('workspace.orderDeliveryReply.syncFailedTitle'));
|
||||
} finally {
|
||||
syncing.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============ 勾选(全选仅本页) ============ */
|
||||
const selected = ref<string[]>([]);
|
||||
const expanded = ref<string[]>([]);
|
||||
const lineKey = (line: OrderDeliveryLine) => `${line.order_no}:${line.line_no}`;
|
||||
const selectedLines = computed(() => items.value.filter((line) => selected.value.includes(lineKey(line))));
|
||||
const allChecked = computed(() => items.value.length > 0 && items.value.every((line) => selected.value.includes(lineKey(line))));
|
||||
const someChecked = computed(() => !allChecked.value && items.value.some((line) => selected.value.includes(lineKey(line))));
|
||||
/** 勾选中「已有批次且未锁定」的行才可批量通知(无批次/已锁定会被后端 skipped)。 */
|
||||
const notifiableSelected = computed(() => selectedLines.value.filter((line) => line.batches.length > 0 && !line.locked));
|
||||
|
||||
function toggleLine(line: OrderDeliveryLine, on: boolean) {
|
||||
const key = lineKey(line);
|
||||
selected.value = on ? [...selected.value, key] : selected.value.filter((k) => k !== key);
|
||||
}
|
||||
|
||||
function togglePageAll(on: boolean) {
|
||||
if (on) {
|
||||
const keys = new Set(selected.value);
|
||||
items.value.forEach((line) => keys.add(lineKey(line)));
|
||||
selected.value = [...keys];
|
||||
} else {
|
||||
const pageKeys = new Set(items.value.map(lineKey));
|
||||
selected.value = selected.value.filter((k) => !pageKeys.has(k));
|
||||
}
|
||||
}
|
||||
|
||||
function toggleExpand(key: string) {
|
||||
expanded.value = expanded.value.includes(key)
|
||||
? expanded.value.filter((k) => k !== key)
|
||||
: [...expanded.value, key];
|
||||
}
|
||||
|
||||
/* ============ 派生展示 ============ */
|
||||
const repliedQty = (line: OrderDeliveryLine) =>
|
||||
line.batches.reduce((sum, batch) => sum + Number(batch.qty || 0), 0);
|
||||
const undelivered = (line: OrderDeliveryLine) => Number(line.undelivered_qty || 0);
|
||||
type LineStatus = OrderDeliveryLine['status'];
|
||||
const statusMeta = (status: LineStatus) => {
|
||||
const map: Record<LineStatus, { label: string; cls: string }> = {
|
||||
not_replied: { label: t('workspace.orderDeliveryReply.statusNotReplied'), cls: 'bg-rose-50 text-rose-600' },
|
||||
partial_replied: { label: t('workspace.orderDeliveryReply.statusPartial'), cls: 'bg-orange-50 text-orange-600' },
|
||||
replied: { label: t('workspace.orderDeliveryReply.statusReplied'), cls: 'bg-emerald-50 text-emerald-600' },
|
||||
};
|
||||
return map[status];
|
||||
};
|
||||
|
||||
/* ============ 回复弹窗(单行 / 联合) ============ */
|
||||
interface EditableBatch { planned_date: string; qty: string; remark: string }
|
||||
interface EditableLine { line: OrderDeliveryLine; batches: EditableBatch[] }
|
||||
|
||||
const modalVisible = ref(false);
|
||||
const modalTitle = ref('');
|
||||
const modalLines = ref<EditableLine[]>([]);
|
||||
const quickDate = ref('');
|
||||
const saving = ref(false);
|
||||
|
||||
function openReplyModal(lines: OrderDeliveryLine[], title: string) {
|
||||
modalLines.value = lines.map((line) => ({
|
||||
line,
|
||||
batches: line.batches.map((batch) => ({
|
||||
planned_date: batch.planned_date,
|
||||
qty: String(Number(batch.qty)),
|
||||
remark: batch.remark || '',
|
||||
})),
|
||||
}));
|
||||
// 无批次的行默认给一条空批次,便于快速填写。
|
||||
modalLines.value.forEach((entry) => {
|
||||
if (entry.batches.length === 0) entry.batches.push({ planned_date: '', qty: '', remark: '' });
|
||||
});
|
||||
modalTitle.value = title;
|
||||
quickDate.value = '';
|
||||
modalVisible.value = true;
|
||||
}
|
||||
|
||||
function openSingleReply(line: OrderDeliveryLine) {
|
||||
openReplyModal([line], t('workspace.orderDeliveryReply.modalTitleSingle', { order: line.order_no, item: line.line_no }));
|
||||
}
|
||||
|
||||
function openBatchReply() {
|
||||
const lines = selectedLines.value.filter((line) => !line.locked);
|
||||
if (!lines.length) return;
|
||||
openReplyModal(lines, t('workspace.orderDeliveryReply.modalTitleBatch', { count: lines.length }));
|
||||
}
|
||||
|
||||
function applyQuickDate() {
|
||||
if (!quickDate.value) return;
|
||||
modalLines.value.forEach((entry) => entry.batches.forEach((batch) => { batch.planned_date = quickDate.value; }));
|
||||
}
|
||||
|
||||
/**
|
||||
* 行填写问题文案(实时校验,2026-09-23):
|
||||
* [规则 1] 已填数量但未填交期的批次 → 「第 N 批未填交期」;
|
||||
* [规则 2] 已填交期但未填数量的批次 → 「第 N 批未填数量」;
|
||||
* [规则 3] 同一订单行不同批次交期重复 → 「同一订单单号:项次的不同批次交期时间不能相同」;
|
||||
* [规则 4] 批次填写完整时合计 ≠ 订单数量 → 「各批次合计 X,须等于订单数量 Y」。
|
||||
* 只有交期与数量都齐全的批次计入合计;完全空白的批次忽略;缺填/重复错误优先于数量错误展示,
|
||||
* 保证报错随填写内容实时切换。锁定行不可编辑不校验。
|
||||
*/
|
||||
function lineIssueText(entry: EditableLine): string {
|
||||
if (entry.line.locked) return '';
|
||||
const missingDates: number[] = [];
|
||||
const missingQtys: number[] = [];
|
||||
let total = 0;
|
||||
let hasInput = false;
|
||||
entry.batches.forEach((batch, idx) => {
|
||||
const hasDate = !!batch.planned_date;
|
||||
const hasQty = batch.qty !== '' && Number(batch.qty) > 0;
|
||||
if (!hasDate && !hasQty) return; // 空白批次忽略
|
||||
hasInput = true;
|
||||
if (hasDate && hasQty) {
|
||||
total += Number(batch.qty);
|
||||
} else if (!hasDate) {
|
||||
missingDates.push(idx + 1);
|
||||
} else {
|
||||
missingQtys.push(idx + 1);
|
||||
}
|
||||
});
|
||||
if (!hasInput) return '';
|
||||
const parts: string[] = [];
|
||||
if (missingDates.length) parts.push(t('workspace.orderDeliveryReply.batchMissingDate', { batches: missingDates.join('、') }));
|
||||
if (missingQtys.length) parts.push(t('workspace.orderDeliveryReply.batchMissingQty', { batches: missingQtys.join('、') }));
|
||||
// 同单不同批次交期重复(后端 _parse_batches 亦拒绝重复交期,此处实时提示)
|
||||
const filledDates = entry.batches.filter((batch) => batch.planned_date).map((batch) => batch.planned_date);
|
||||
const duplicatedDates = [...new Set(filledDates.filter((d, i) => filledDates.indexOf(d) !== i))];
|
||||
if (duplicatedDates.length) parts.push(t('workspace.orderDeliveryReply.batchDuplicateDate', { dates: duplicatedDates.join('、') }));
|
||||
if (!parts.length && Math.abs(total - Number(entry.line.qty || 0)) > 1e-6) {
|
||||
parts.push(t('workspace.orderDeliveryReply.qtyTotalMismatchLine', { total, qty: Number(entry.line.qty || 0) }));
|
||||
}
|
||||
return parts.join(';');
|
||||
}
|
||||
|
||||
async function saveReplies() {
|
||||
const validItems: { order_no: string; line_no: number; batches: { planned_date: string; qty: string; remark: string | null }[] }[] = [];
|
||||
for (const { line, batches } of modalLines.value) {
|
||||
const cleaned = batches
|
||||
.filter((batch) => batch.planned_date && Number(batch.qty) > 0)
|
||||
.map((batch) => ({ planned_date: batch.planned_date, qty: batch.qty, remark: batch.remark.trim() || null }));
|
||||
if (line.locked) continue; // 锁定行不允许再改(后端也会 409)
|
||||
if (!cleaned.length) continue;
|
||||
validItems.push({ order_no: line.order_no, line_no: line.line_no, batches: cleaned });
|
||||
}
|
||||
// 填写校验(2026-09-23,与实时提示同口径):缺交期/缺数量、合计≠订单数量都按行拦截。
|
||||
const issueTexts: string[] = [];
|
||||
for (const entry of modalLines.value) {
|
||||
if (entry.line.locked) continue;
|
||||
const text = lineIssueText(entry);
|
||||
if (text) issueTexts.push(`${entry.line.order_no}:${entry.line.line_no} ${text}`);
|
||||
}
|
||||
if (issueTexts.length) {
|
||||
msg.warning(t('workspace.orderDeliveryReply.saveBlocked', { detail: issueTexts.join(';') }));
|
||||
return;
|
||||
}
|
||||
if (!validItems.length) {
|
||||
msg.warning(t('workspace.orderDeliveryReply.noValidBatches'));
|
||||
return;
|
||||
}
|
||||
saving.value = true;
|
||||
try {
|
||||
const [singleItem] = validItems;
|
||||
if (validItems.length === 1 && singleItem) {
|
||||
// 仅一行时走单行接口;多行必须走批量接口逐行保存(此前误判为 if (singleItem),
|
||||
// 恒为真导致联合回复只保存第一行,批量分支成死代码)。
|
||||
await saveOrderDeliveryBatches(singleItem.order_no, singleItem.line_no, singleItem.batches);
|
||||
msg.success(t('workspace.orderDeliveryReply.saveSingleDone'));
|
||||
} else {
|
||||
const summary: BatchSummary = await batchReplyOrderDelivery(validItems);
|
||||
if (summary.failed > 0) {
|
||||
const failedText = summary.items.filter((item) => !item.ok).map((item) => `${item.order_no}:${item.line_no} ${item.error || ''}`).join(';');
|
||||
msg.warning(t('workspace.orderDeliveryReply.saveBatchPartial', { ok: summary.succeeded, fail: summary.failed, detail: failedText }));
|
||||
} else {
|
||||
msg.success(t('workspace.orderDeliveryReply.saveBatchDone', { ok: summary.succeeded }));
|
||||
}
|
||||
}
|
||||
modalVisible.value = false;
|
||||
selected.value = [];
|
||||
await loadLines(); // 保存或通知后即时刷新(需求 §9)
|
||||
} catch (error) {
|
||||
msg.error(error instanceof Error ? error.message : t('workspace.orderDeliveryReply.saveFailedTitle'));
|
||||
// 行已不在同步范围(erp_missing/被新同步剔除):旧列表过期,自动刷新让该行消失。
|
||||
const message = error instanceof Error ? error.message : '';
|
||||
if (message.includes('LINE_NOT_FOUND') || message.includes('不在同步范围') || message.includes('not found')) {
|
||||
await loadLines();
|
||||
}
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============ 通知 ============ */
|
||||
const notifying = ref(false);
|
||||
|
||||
/** 批量通知:部分成功 warning 汇总,全部失败 error;提示后刷新列表让锁定即时生效。 */
|
||||
async function doNotifyBatch() {
|
||||
const lines = notifiableSelected.value;
|
||||
if (!lines.length) return;
|
||||
const ok = window.confirm(t('workspace.orderDeliveryReply.notifyBatchConfirm', { count: lines.length }));
|
||||
if (!ok) return;
|
||||
notifying.value = true;
|
||||
try {
|
||||
const summary = await notifyOrderDeliveryBatch(lines.map((line) => ({ order_no: line.order_no, line_no: line.line_no })));
|
||||
const failedText = summary.items.filter((item) => !item.ok).map((item) => `${item.order_no}:${item.line_no} ${item.error || ''}`).join(';');
|
||||
if (summary.failed > 0 && summary.succeeded > 0) {
|
||||
msg.warning(t('workspace.orderDeliveryReply.notifyPartial', { ok: summary.succeeded, fail: summary.failed, skip: summary.skipped, detail: failedText }));
|
||||
} else if (summary.failed > 0 && summary.succeeded === 0) {
|
||||
msg.error(t('workspace.orderDeliveryReply.notifyAllFailed', { fail: summary.failed, detail: failedText }));
|
||||
} else {
|
||||
msg.success(t('workspace.orderDeliveryReply.notifyBatchDone', { ok: summary.succeeded, skip: summary.skipped }));
|
||||
}
|
||||
selected.value = [];
|
||||
await loadLines();
|
||||
} catch (error) {
|
||||
msg.error(error instanceof Error ? error.message : t('workspace.orderDeliveryReply.notifyFailedTitle'));
|
||||
} finally {
|
||||
notifying.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============ 同步状态展示 ============ */
|
||||
const latestSyncText = computed(() => {
|
||||
const run = latestSync.value;
|
||||
if (!run) return t('workspace.orderDeliveryReply.syncNever');
|
||||
const time = (run.finished_at || run.started_at || '').replace('T', ' ').slice(0, 19);
|
||||
if (run.status === 'success') return t('workspace.orderDeliveryReply.syncAt', { time });
|
||||
if (run.status === 'running') return t('workspace.orderDeliveryReply.syncRunning');
|
||||
return t('workspace.orderDeliveryReply.syncFailedAt', { time });
|
||||
});
|
||||
const latestSyncFailed = computed(() => latestSync.value?.status === 'failed');
|
||||
|
||||
/* ============ 企微卡片直达定位 ============ */
|
||||
// 企微卡片「查看详情」→(未登录先登录,守卫以 redirect 原样回跳)→ 本页按 query 还原内容与位置:
|
||||
// status=交期回复状态筛选(提醒卡)、order_no=关键词筛选、line_no=滚动定位并高亮该行(行通知卡);
|
||||
// wecom_trace 上报卡片打开回执(与工作台 deeplink 同一后端接口,失败静默只留痕)。
|
||||
const route = useRoute();
|
||||
const highlightKey = ref('');
|
||||
let highlightTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
function clearHighlight() {
|
||||
if (highlightTimer) {
|
||||
clearTimeout(highlightTimer);
|
||||
highlightTimer = null;
|
||||
}
|
||||
highlightKey.value = '';
|
||||
}
|
||||
|
||||
const isLineHighlighted = (line: OrderDeliveryLine) => highlightKey.value === lineKey(line);
|
||||
const rowCls = (line: OrderDeliveryLine) =>
|
||||
isLineHighlighted(line) ? 'bg-amber-50' : selected.value.includes(lineKey(line)) ? 'bg-blue-50/60' : '';
|
||||
/** 冻结单元格必须实色背景(防透出滚动内容),且与整行高亮/勾选色联动;高亮优先于勾选。 */
|
||||
const frozenCellCls = (line: OrderDeliveryLine) =>
|
||||
isLineHighlighted(line)
|
||||
? 'bg-amber-100 group-hover:bg-amber-200'
|
||||
: selected.value.includes(lineKey(line))
|
||||
? 'bg-blue-100 group-hover:bg-blue-200'
|
||||
: 'bg-white group-hover:bg-slate-100';
|
||||
|
||||
/** 列表就绪后定位目标行:滚动到视口中央 + 高亮 8 秒;行不在当前筛选结果中时静默跳过。 */
|
||||
async function focusTargetLine(orderNo: string, lineNo: number) {
|
||||
const key = `${orderNo}:${lineNo}`;
|
||||
if (!items.value.some((line) => lineKey(line) === key)) return;
|
||||
highlightKey.value = key;
|
||||
await nextTick();
|
||||
document.querySelector(`[data-line-key="${key}"]`)?.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
msg.success(t('workspace.orderDeliveryReply.deepLinkLocated', { order: orderNo, item: lineNo }));
|
||||
if (highlightTimer) clearTimeout(highlightTimer);
|
||||
highlightTimer = setTimeout(clearHighlight, 8000);
|
||||
}
|
||||
|
||||
/** 上报企微卡片打开回执(WecomNotifyAudit.opened_at);仅留痕,失败不影响页面使用。 */
|
||||
async function reportWecomTraceOpened(traceId: string) {
|
||||
try {
|
||||
await requestJson('/api/user/wecom/deeplink-opened', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ trace_id: traceId }),
|
||||
});
|
||||
} catch {
|
||||
// 回执只留痕:失败不打扰用户。
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
const query = route.query;
|
||||
const orderNo = typeof query.order_no === 'string' ? query.order_no.trim() : '';
|
||||
const lineNo = typeof query.line_no === 'string' ? Number(query.line_no) : NaN;
|
||||
const status = typeof query.status === 'string' ? query.status : '';
|
||||
const traceId = typeof query.wecom_trace === 'string' ? query.wecom_trace : '';
|
||||
|
||||
// [STEP 1] 还原筛选(登录回跳后 query 仍在):关键词命中订单单号;状态筛选定位提醒卡对应视图。
|
||||
if (orderNo) filters.keyword = orderNo;
|
||||
if (status === 'replied' || status === 'not_fully_replied') filters.status = status;
|
||||
if (orderNo || status) Object.assign(appliedFilters, filters);
|
||||
|
||||
if (traceId) void reportWecomTraceOpened(traceId);
|
||||
|
||||
// [STEP 2] 加载列表后按 line_no 滚动定位 + 高亮(行级通知卡直达场景)。
|
||||
await loadLines();
|
||||
void loadLatestSync();
|
||||
if (orderNo && Number.isInteger(lineNo) && lineNo > 0) await focusTargetLine(orderNo, lineNo);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- 全页统一字号:与表头一致(text-sm 14px),根容器设定基准,子元素不再覆写;
|
||||
唯一例外:交期回复状态/交期已锁定徽标保持 text-xs(12px)加粗 -->
|
||||
<!-- 高度收敛至视口(h-screen + overflow-hidden):页面自身不滚动,滚动全部在表格容器内,
|
||||
列头 sticky 固定、横向滚动条常驻表格底缘;聊天壳 iframe 与独立路由均适用 -->
|
||||
<div class="flex h-screen flex-col gap-4 overflow-hidden p-6 text-sm">
|
||||
<!-- 页头:标题 + 最近同步 + 手动刷新 -->
|
||||
<div class="flex flex-wrap items-center gap-3">
|
||||
<h1 class="font-bold text-primary">{{ t('workspace.nav.orderDeliveryReply') }}</h1>
|
||||
<span class="rounded-full px-3 py-1" :class="latestSyncFailed ? 'bg-rose-50 text-rose-600' : 'bg-blue-50 text-blue-600'">
|
||||
{{ latestSyncText }}
|
||||
</span>
|
||||
<div class="flex-1" />
|
||||
<button v-if="canManage" type="button" class="btn-ghost" :disabled="syncing" @click="doSync">
|
||||
{{ syncing ? t('workspace.orderDeliveryReply.syncing') : t('workspace.orderDeliveryReply.syncNow') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 搜索区:合并关键词搜索(订单/产品/客户命中任一字段),字号与表格统一(text-sm),shrink-0 防压缩 -->
|
||||
<div class="flex shrink-0 flex-wrap items-end gap-3 rounded-2xl border border-default bg-surface px-4 py-2.5">
|
||||
<label class="flex flex-col gap-1 text-muted">
|
||||
{{ t('workspace.orderDeliveryReply.filterKeyword') }}
|
||||
<input v-model="filters.keyword" class="h-8 min-w-[340px] rounded-lg border border-default px-3 text-primary outline-none focus:border-blue-500" :placeholder="t('workspace.orderDeliveryReply.filterKeywordPh')" @keyup.enter="doSearch" />
|
||||
</label>
|
||||
<label class="flex flex-col gap-1 text-muted">
|
||||
{{ t('workspace.orderDeliveryReply.filterOrderDate') }}
|
||||
<input v-model="filters.order_date" type="date" class="h-8 rounded-lg border border-default px-3 text-primary outline-none focus:border-blue-500" />
|
||||
</label>
|
||||
<label class="flex flex-col gap-1 text-muted">
|
||||
{{ t('workspace.orderDeliveryReply.filterStatus') }}
|
||||
<!-- 状态筛选选择即生效(无需再点查询);其余条件仍由「查询」统一提交 -->
|
||||
<select v-model="filters.status" class="min-w-[140px] rounded-lg border border-default bg-white px-3 py-[5px] text-sm leading-5 text-primary outline-none focus:border-blue-500" @change="doSearch">
|
||||
<option value="">{{ t('workspace.orderDeliveryReply.statusAll') }}</option>
|
||||
<option value="replied">{{ t('workspace.orderDeliveryReply.statusReplied') }}</option>
|
||||
<option value="not_fully_replied">{{ t('workspace.orderDeliveryReply.statusNotFully') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<button type="button" class="btn-primary h-8" @click="doSearch">{{ t('workspace.orderDeliveryReply.search') }}</button>
|
||||
<button type="button" class="btn-ghost h-8" @click="doReset">{{ t('workspace.orderDeliveryReply.reset') }}</button>
|
||||
<div class="flex-1" />
|
||||
<span class="text-muted">{{ t('workspace.orderDeliveryReply.totalCount', { count: total }) }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 工具栏:全选 + 联合回复 + 批量通知(shrink-0 防压缩,py-2 紧凑高度) -->
|
||||
<div class="flex shrink-0 flex-wrap items-center gap-3 rounded-2xl border border-default bg-surface px-4 py-2">
|
||||
<label class="flex items-center gap-2 text-primary">
|
||||
<input type="checkbox" class="h-4 w-4 rounded border-default text-blue-600" :checked="allChecked" :indeterminate.prop="someChecked" @change="togglePageAll(($event.target as HTMLInputElement).checked)" />
|
||||
{{ t('workspace.orderDeliveryReply.selectAll') }}
|
||||
</label>
|
||||
<span class="text-muted">{{ t('workspace.orderDeliveryReply.selectedCount', { count: selectedLines.length }) }}</span>
|
||||
<template v-if="canManage">
|
||||
<button type="button" class="btn-primary h-8" :disabled="selectedLines.length === 0" @click="openBatchReply">
|
||||
{{ t('workspace.orderDeliveryReply.batchReply') }}
|
||||
</button>
|
||||
<button type="button" class="btn-primary h-8" :disabled="notifiableSelected.length === 0 || notifying" @click="doNotifyBatch">
|
||||
{{ t('workspace.orderDeliveryReply.batchNotify') }}
|
||||
</button>
|
||||
</template>
|
||||
<div class="flex-1" />
|
||||
<span class="whitespace-nowrap rounded-full bg-slate-100 px-3 py-1 text-muted">{{ t('workspace.orderDeliveryReply.toolbarHint') }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 列表 -->
|
||||
<div class="min-h-0 flex-1 overflow-auto rounded-2xl border border-default bg-surface">
|
||||
<table class="w-full border-collapse">
|
||||
<!-- z-30 高于表体冻结单元格(z-20):纵向滚动时冻结列不会盖住表头 -->
|
||||
<thead class="sticky top-0 z-30 bg-slate-50 text-muted [&_th]:whitespace-nowrap">
|
||||
<tr>
|
||||
<!-- 左侧冻结标识区(前四列):勾选/客户编号/订单日期/订单单号:项次,宽度固定保证偏移对齐 -->
|
||||
<th class="sticky left-0 z-30 w-8 bg-slate-50 px-2 py-2" />
|
||||
<th class="sticky left-8 z-30 w-32 min-w-[8rem] bg-slate-50 px-2 py-2 text-left">{{ t('workspace.orderDeliveryReply.colCustomer') }}</th>
|
||||
<th class="sticky left-[10rem] z-30 w-24 bg-slate-50 px-2 py-2 text-left">{{ t('workspace.orderDeliveryReply.colOrderDate') }}</th>
|
||||
<th class="sticky left-[16rem] z-30 w-40 min-w-[10rem] border-r border-default bg-slate-50 px-2 py-2 text-left shadow-[2px_0_6px_-2px_rgba(15,23,42,0.12)]">{{ t('workspace.orderDeliveryReply.colOrderLine') }}</th>
|
||||
<th class="px-2 py-2 text-left">{{ t('workspace.orderDeliveryReply.colPartNo') }}</th>
|
||||
<th class="px-2 py-2 text-left">{{ t('workspace.orderDeliveryReply.colCustomerPartNo') }}</th>
|
||||
<th class="px-2 py-2 text-right">{{ t('workspace.orderDeliveryReply.colQty') }}</th>
|
||||
<th class="px-2 py-2 text-left">{{ t('workspace.orderDeliveryReply.colAgreedDate') }}</th>
|
||||
<th class="px-2 py-2 text-left">{{ t('workspace.orderDeliveryReply.colStatus') }}</th>
|
||||
<th class="px-2 py-2 text-left">{{ t('workspace.orderDeliveryReply.colReply') }}</th>
|
||||
<th class="px-2 py-2 text-left">{{ t('workspace.orderDeliveryReply.colReplyPerson') }}</th>
|
||||
<th class="px-2 py-2 text-left">{{ t('workspace.orderDeliveryReply.colSalesperson') }}</th>
|
||||
<th class="px-2 py-2 text-left">{{ t('workspace.orderDeliveryReply.colCustomerPo') }}</th>
|
||||
<th class="px-2 py-2 text-left">{{ t('workspace.orderDeliveryReply.colSpec') }}</th>
|
||||
<th class="px-2 py-2 text-left">{{ t('workspace.orderDeliveryReply.colUnit') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="line in items"
|
||||
:key="lineKey(line)"
|
||||
:data-line-key="lineKey(line)"
|
||||
class="group border-t border-default hover:bg-slate-50"
|
||||
:class="rowCls(line)"
|
||||
>
|
||||
<!-- 冻结单元格必须实色背景(半透明会透出滚动内容),并用 group-hover 与整行悬停/选中/直达高亮联动 -->
|
||||
<td
|
||||
class="sticky left-0 z-20 px-2 py-1.5"
|
||||
:class="frozenCellCls(line)"
|
||||
>
|
||||
<input type="checkbox" class="h-4 w-4 rounded border-default text-blue-600" :checked="selected.includes(lineKey(line))" @change="toggleLine(line, ($event.target as HTMLInputElement).checked)" />
|
||||
</td>
|
||||
<td
|
||||
class="sticky left-8 z-20 w-32 min-w-[8rem] max-w-[8rem] px-2 py-1.5"
|
||||
:class="frozenCellCls(line)"
|
||||
:title="line.customer_full_name || line.customer_short_name || ''"
|
||||
>
|
||||
<div>{{ line.customer_no || '—' }}</div>
|
||||
<div class="truncate text-muted">{{ line.customer_short_name || '' }}</div>
|
||||
</td>
|
||||
<td
|
||||
class="sticky left-[10rem] z-20 w-24 min-w-[6rem] max-w-[6rem] overflow-hidden px-2 py-1.5"
|
||||
:class="frozenCellCls(line)"
|
||||
>{{ line.order_date || '—' }}</td>
|
||||
<td
|
||||
class="sticky left-[16rem] z-20 w-40 min-w-[10rem] max-w-[10rem] overflow-hidden whitespace-nowrap border-r border-default px-2 py-1.5 font-mono shadow-[2px_0_6px_-2px_rgba(15,23,42,0.12)]"
|
||||
:class="frozenCellCls(line)"
|
||||
>{{ line.order_no }}:{{ line.line_no }}</td>
|
||||
<td class="px-2 py-1.5" :title="line.part_name || ''">
|
||||
<div class="max-w-[10rem] truncate font-mono">{{ line.part_no || '—' }}</div>
|
||||
<div class="max-w-[14rem] truncate text-muted">{{ line.part_name || '' }}</div>
|
||||
</td>
|
||||
<td class="whitespace-nowrap px-2 py-1.5 font-mono">{{ line.customer_part_no || '—' }}</td>
|
||||
<td class="px-2 py-2 text-right tabular-nums">{{ line.qty ?? '—' }}</td>
|
||||
<td class="whitespace-nowrap px-2 py-1.5">{{ line.agreed_date || '—' }}</td>
|
||||
<td class="px-2 py-1.5">
|
||||
<span class="whitespace-nowrap rounded-full px-2.5 py-0.5 text-xs font-semibold" :class="statusMeta(line.status).cls">
|
||||
{{ statusMeta(line.status).label }}
|
||||
</span>
|
||||
</td>
|
||||
<!-- 交期回复:无批次=回复交期;有批次可展开;锁定=已锁定 -->
|
||||
<td class="px-2 py-1.5 align-top">
|
||||
<template v-if="line.batches.length === 0">
|
||||
<span class="text-muted">{{ t('workspace.orderDeliveryReply.statusNotReplied') }}</span>
|
||||
<div v-if="canManage" class="mt-0.5">
|
||||
<button type="button" class="rounded-md border border-blue-200 bg-blue-50 px-2 py-0.5 text-blue-600" @click="openSingleReply(line)">
|
||||
{{ t('workspace.orderDeliveryReply.replyAction') }}
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="whitespace-nowrap rounded-full border border-default bg-slate-50 px-2 py-0.5 text-muted">
|
||||
{{ t('workspace.orderDeliveryReply.batchCount', { count: line.batches.length }) }} ·
|
||||
{{ t('workspace.orderDeliveryReply.repliedOf', { replied: repliedQty(line), remain: undelivered(line) }) }}
|
||||
<span v-if="repliedQty(line) > undelivered(line)" class="ml-1 font-semibold text-orange-500">{{ t('workspace.orderDeliveryReply.overTag') }}</span>
|
||||
</span>
|
||||
<button v-if="line.batches.length > 1" type="button" class="rounded-full border border-default px-2 py-0.5 text-blue-600" @click="toggleExpand(lineKey(line))">
|
||||
{{ expanded.includes(lineKey(line)) ? t('workspace.orderDeliveryReply.collapse') : t('workspace.orderDeliveryReply.expand', { count: line.batches.length - 1 }) }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="mt-0.5 flex flex-col gap-0.5">
|
||||
<div
|
||||
v-for="(batch, idx) in line.batches"
|
||||
:key="batch.seq ?? idx"
|
||||
v-show="expanded.includes(lineKey(line)) || idx === 0"
|
||||
class="max-w-[230px] truncate rounded border-l-[3px] border-blue-500 bg-blue-50/50 px-2 py-0.5 text-secondary"
|
||||
>
|
||||
{{ batch.planned_date }} · <b class="text-blue-600">{{ batch.qty }}</b> {{ line.unit }}
|
||||
<i v-if="batch.remark" class="ml-1 not-italic text-muted">{{ batch.remark }}</i>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-0.5">
|
||||
<span v-if="line.locked" class="rounded-full bg-emerald-50 px-2.5 py-0.5 text-xs font-semibold text-emerald-600">{{ t('workspace.orderDeliveryReply.lockedTag') }}</span>
|
||||
<button v-else-if="canManage" type="button" class="rounded-md border border-blue-200 bg-blue-50 px-2 py-0.5 text-blue-600" @click="openSingleReply(line)">
|
||||
{{ t('workspace.orderDeliveryReply.editReplyAction') }}
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
</td>
|
||||
<!-- 交期回复人员:锁定行附带已通知对象与时间(原「通知业务部门」列已取消,信息并入此处) -->
|
||||
<td class="px-2 py-1.5">
|
||||
<template v-if="line.notified_employee_id || line.notified_user_name">
|
||||
<div class="font-mono">{{ line.notified_employee_id || '' }}</div>
|
||||
<div class="text-muted">{{ line.notified_user_name || '' }}</div>
|
||||
<div v-if="line.locked" class="text-emerald-600">
|
||||
{{ t('workspace.orderDeliveryReply.notifiedTag', { name: line.salesperson_name || line.salesperson_code || '' }) }}
|
||||
<span class="text-muted">{{ line.notified_at || '' }}</span>
|
||||
</div>
|
||||
</template>
|
||||
<span v-else class="text-muted">{{ t('workspace.orderDeliveryReply.pendingNotify') }}</span>
|
||||
</td>
|
||||
<!-- 业务员(副文案部门):与客户编号/简称同款合并展示,独立部门列已取消 -->
|
||||
<td class="px-2 py-1.5" :title="line.salesperson_code || ''">
|
||||
<div class="whitespace-nowrap">{{ line.salesperson_name || line.salesperson_code || '—' }}</div>
|
||||
<div class="text-muted">{{ line.dept_name || line.dept_code || '' }}</div>
|
||||
</td>
|
||||
<td class="px-2 py-1.5 font-mono" :title="line.customer_po || ''"><span class="block max-w-[10rem] truncate">{{ line.customer_po || '—' }}</span></td>
|
||||
<td class="px-2 py-1.5" :title="line.spec || ''"><span class="block max-w-[10rem] truncate">{{ line.spec || '—' }}</span></td>
|
||||
<td class="px-2 py-1.5">{{ line.unit || '—' }}</td>
|
||||
</tr>
|
||||
<tr v-if="!loading && items.length === 0">
|
||||
<td colspan="15" class="px-4 py-16 text-center text-muted">{{ t('workspace.orderDeliveryReply.empty') }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- 分页:复用管理控制台-数据报表的 PaginationBar(摘要 + 每页条数 + 页码按钮) -->
|
||||
<PaginationBar
|
||||
class="[&_*]:!text-sm"
|
||||
:page="page"
|
||||
:page-size="pageSize"
|
||||
:total="total"
|
||||
:page-size-options="pageSizeOptions"
|
||||
@update:page="goToPage"
|
||||
@update:page-size="changePageSize"
|
||||
/>
|
||||
|
||||
<!-- 回复弹窗 -->
|
||||
<div v-if="modalVisible" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40" @click.self="modalVisible = false">
|
||||
<div class="flex max-h-[88vh] w-[min(960px,94vw)] flex-col overflow-hidden rounded-2xl bg-white shadow-2xl">
|
||||
<div class="flex items-center gap-3 border-b border-default px-5 py-4">
|
||||
<h3 class="font-bold text-primary">{{ modalTitle }}</h3>
|
||||
<div class="flex-1" />
|
||||
<button type="button" class="text-muted" @click="modalVisible = false">×</button>
|
||||
</div>
|
||||
<div class="flex-1 overflow-auto px-5 py-4">
|
||||
<!-- 快速统一交期 -->
|
||||
<div class="mb-4 flex flex-wrap items-end gap-3 rounded-xl border border-default bg-blue-50/40 px-4 py-3">
|
||||
<label class="flex flex-col gap-1 text-muted">
|
||||
{{ t('workspace.orderDeliveryReply.quickDate') }}
|
||||
<input v-model="quickDate" type="date" class="h-9 rounded-lg border border-default px-3 text-primary" />
|
||||
</label>
|
||||
<button type="button" class="h-9 rounded-lg border border-default px-3 text-primary" @click="applyQuickDate">
|
||||
{{ t('workspace.orderDeliveryReply.applyQuickDate') }}
|
||||
</button>
|
||||
<span class="text-muted">{{ t('workspace.orderDeliveryReply.modalHint') }}</span>
|
||||
</div>
|
||||
<!-- 每行批次编辑器 -->
|
||||
<div v-for="entry in modalLines" :key="lineKey(entry.line)" class="mb-4 overflow-hidden rounded-xl border border-default">
|
||||
<div class="flex flex-wrap items-center gap-2 bg-slate-50 px-3 py-2">
|
||||
<span class="rounded bg-indigo-50 px-2 py-0.5 font-semibold text-indigo-600">{{ entry.line.order_no }}</span>
|
||||
<span>{{ t('workspace.orderDeliveryReply.itemLabel', { item: entry.line.line_no }) }}</span>
|
||||
<span class="text-muted">{{ entry.line.customer_no }} · {{ entry.line.customer_short_name }}</span>
|
||||
<span class="text-muted">{{ entry.line.part_no }} · {{ entry.line.part_name }}</span>
|
||||
<span class="ml-auto whitespace-nowrap">
|
||||
{{ t('workspace.orderDeliveryReply.orderQtyLabel', { qty: entry.line.qty ?? 0, unit: entry.line.unit || '' }) }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex flex-col gap-2 px-3 py-3">
|
||||
<div v-for="(batch, idx) in entry.batches" :key="idx" class="grid grid-cols-[170px_120px_1fr_36px] items-center gap-2">
|
||||
<input v-model="batch.planned_date" type="date" class="h-9 rounded-lg border border-default px-2 text-primary" />
|
||||
<input v-model="batch.qty" type="number" min="0" :placeholder="t('workspace.orderDeliveryReply.qtyPh')" class="h-9 rounded-lg border border-default px-2 text-primary" />
|
||||
<input v-model="batch.remark" :placeholder="t('workspace.orderDeliveryReply.remarkPh')" class="h-9 rounded-lg border border-default px-2 text-primary" />
|
||||
<button type="button" class="h-9 rounded-lg bg-rose-50 text-rose-600" :title="t('workspace.orderDeliveryReply.removeBatch')" @click="entry.batches.splice(idx, 1)">✕</button>
|
||||
</div>
|
||||
<button type="button" class="w-full rounded-lg border border-dashed border-slate-300 py-2 text-blue-600" @click="entry.batches.push({ planned_date: '', qty: '', remark: '' })">
|
||||
{{ t('workspace.orderDeliveryReply.addBatch') }}
|
||||
</button>
|
||||
<!-- 行级实时校验提示:缺交期/缺数量按批次序号指出,合计不等给出已填/应填;随填写实时切换 -->
|
||||
<p v-if="lineIssueText(entry)" class="text-rose-500">{{ lineIssueText(entry) }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-end gap-3 border-t border-default bg-slate-50 px-5 py-3">
|
||||
<button type="button" class="btn-ghost" @click="modalVisible = false">{{ t('common.cancel') }}</button>
|
||||
<button type="button" class="btn-primary" :disabled="saving" @click="saveReplies">
|
||||
{{ saving ? t('workspace.orderDeliveryReply.saving') : t('workspace.orderDeliveryReply.saveReply') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -58,12 +58,10 @@ const identityMeta = computed(() => {
|
||||
</div>
|
||||
|
||||
<div v-else class="space-y-6">
|
||||
<div class="rounded-2xl border border-default bg-surface px-5 py-5 shadow-sm md:px-6">
|
||||
<div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div class="flex min-w-0 items-center gap-4">
|
||||
<div
|
||||
class="flex h-14 w-14 shrink-0 items-center justify-center rounded-full bg-brand-100 text-xl font-semibold text-brand-600 md:h-16 md:w-16 md:text-2xl"
|
||||
>
|
||||
<div class="rounded-3xl border border-default bg-surface px-6 py-6 shadow-sm md:px-8">
|
||||
<div class="flex flex-col gap-6 lg:flex-row lg:items-start lg:justify-between">
|
||||
<div class="flex flex-1 flex-col gap-6 sm:flex-row sm:items-center sm:justify-start">
|
||||
<div class="flex h-24 w-24 shrink-0 items-center justify-center rounded-full bg-brand-100 text-4xl font-bold text-brand-600" :class="userProfile.isMobile ? 'h-14 w-14 text-2xl' : ''">
|
||||
{{ getUserAvatarLabel(userProfile.profileUser) }}
|
||||
</div>
|
||||
<div class="min-w-0 space-y-0.5">
|
||||
|
||||
@@ -19,6 +19,7 @@ export const WORKSPACE_PATHS = {
|
||||
accountingVoucherCheck: '/workspace/accounting-voucher-check',
|
||||
accountingVoucherCheckDetail: (runId: number | string) => `/workspace/accounting-voucher-check/runs/${runId}`,
|
||||
contractPayment: '/workspace/contract-payment',
|
||||
orderDeliveryReply: '/workspace/order-delivery-reply',
|
||||
contractPaymentReview: '/workspace/contract-payment/review',
|
||||
contractPaymentWeeklyBatches: '/workspace/contract-payment/weekly-batches',
|
||||
contractPaymentDetail: (contractId: number) => `/workspace/contract-payment/contracts/${contractId}`,
|
||||
@@ -38,6 +39,7 @@ export const LEGACY_VIEW_TO_PATH: Record<string, string> = {
|
||||
shipping_notice: WORKSPACE_PATHS.shippingNotice,
|
||||
accounting_voucher_check: WORKSPACE_PATHS.accountingVoucherCheck,
|
||||
contract_payment: WORKSPACE_PATHS.contractPayment,
|
||||
order_delivery_reply: WORKSPACE_PATHS.orderDeliveryReply,
|
||||
history: WORKSPACE_PATHS.history,
|
||||
};
|
||||
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"linkedServices": "Linked Services",
|
||||
"procurementContract": "Procurement Contract Review",
|
||||
"trainingConfig": "Training Config",
|
||||
"integrationConnector": "Integration Connector"
|
||||
"integrationConnector": "Integration Connector",
|
||||
"contractPayment": "Contract Payment Alerts"
|
||||
},
|
||||
"shippingOrderExtractionRuns": {
|
||||
"eyebrow": "READ-ONLY RUN DIAGNOSTICS",
|
||||
@@ -1139,7 +1140,12 @@
|
||||
"status": "Status",
|
||||
"enable": "Enable",
|
||||
"disable": "Disable",
|
||||
"save": "Save"
|
||||
"save": "Save",
|
||||
"guideUsage": "Material Usage",
|
||||
"generalGuide": "General Guide",
|
||||
"trainingVideo": "Employee Training Video",
|
||||
"trainingExamPdf": "Employee Training Exam PDF",
|
||||
"guideUsageHint": "The training workspace prioritizes \"Employee Training Video\" and \"Employee Training Exam PDF\" materials."
|
||||
},
|
||||
"dash": {
|
||||
"activeAgents": "Active Agents",
|
||||
@@ -1208,6 +1214,10 @@
|
||||
"trainingLeanTeamManage": "Lean training team management",
|
||||
"contractPaymentAccess": "Contract payment alert access",
|
||||
"contractPaymentAccessHint": "Allows this user to open the contract payment workbench (ledger, review, weekly batches). Syncing OA, scanning alerts, and sending weekly alerts remain admin-only.",
|
||||
"orderDeliveryReplyManage": "Order Delivery Reply Manage",
|
||||
"orderDeliveryReplyManageHint": "Grants replying delivery batches, sending/batch notifications and manual ERP sync (production planning).",
|
||||
"orderDeliveryReplyAccess": "Order Delivery Reply Access",
|
||||
"orderDeliveryReplyAccessHint": "Grants read-only access to synced orders and replies (business users); managing requires the manage permission.",
|
||||
"password": "Password",
|
||||
"passwordHint": "(leave blank to keep)",
|
||||
"noAgents": "No agents available."
|
||||
@@ -1249,7 +1259,11 @@
|
||||
"delete": "Delete",
|
||||
"viewMembers": "View department members"
|
||||
},
|
||||
"members": { "title": "{name} Members", "count": "{count} members", "empty": "No members" },
|
||||
"members": {
|
||||
"title": "{name} Members",
|
||||
"count": "{count} members",
|
||||
"empty": "No members"
|
||||
},
|
||||
"fields": {
|
||||
"name": "Name",
|
||||
"namePlaceholder": "e.g. IT Department",
|
||||
@@ -1796,7 +1810,12 @@
|
||||
"employeeIdSource": "Employee ID Source",
|
||||
"mobileNormalize": "Normalize mobile number",
|
||||
"publicBaseUrl": "Public HTTPS base (extranet)",
|
||||
"userSelect": "Select user"
|
||||
"userSelect": "Select user",
|
||||
"callbackToken": "Callback Token",
|
||||
"encodingAesKey": "EncodingAESKey",
|
||||
"callbackUrl": "Callback URL",
|
||||
"homepageUrl": "Homepage URL",
|
||||
"trustedDomain": "Trusted Domain"
|
||||
},
|
||||
"bindModes": {
|
||||
"match_rules": "Match automatically",
|
||||
@@ -1909,8 +1928,23 @@
|
||||
"filterName": "Filter by Name/Username",
|
||||
"filterDept": "Filter by Department",
|
||||
"allRoles": "All Roles",
|
||||
"views": { "apps": "By Application", "members": "By Member" },
|
||||
"appHeaders": { "app": "Application", "type": "Type", "authorized": "Authorized", "actions": "Actions", "viewMembers": "View members", "accessHint": "Open member permissions", "memberHint": "Add or remove access to this application", "memberSearch": "Search name, username, employee ID, or department", "addMember": "Grant access", "removeMember": "Remove access", "noMembers": "No matching members" },
|
||||
"views": {
|
||||
"apps": "By Application",
|
||||
"members": "By Member"
|
||||
},
|
||||
"appHeaders": {
|
||||
"app": "Application",
|
||||
"type": "Type",
|
||||
"authorized": "Authorized",
|
||||
"actions": "Actions",
|
||||
"viewMembers": "View members",
|
||||
"accessHint": "Open member permissions",
|
||||
"memberHint": "Add or remove access to this application",
|
||||
"memberSearch": "Search name, username, employee ID, or department",
|
||||
"addMember": "Grant access",
|
||||
"removeMember": "Remove access",
|
||||
"noMembers": "No matching members"
|
||||
},
|
||||
"headers": {
|
||||
"user": "User",
|
||||
"realName": "Real Name",
|
||||
@@ -2147,7 +2181,7 @@
|
||||
"tokens_completion": "Completion Tokens",
|
||||
"total_tokens": "Total Tokens",
|
||||
"latency_ms": "Latency (ms)",
|
||||
"latency": "Latency",
|
||||
"latency": "Latency (ms)",
|
||||
"cost": "Cost",
|
||||
"ip": "IP",
|
||||
"user_agent": "User Agent",
|
||||
@@ -2166,7 +2200,6 @@
|
||||
"source_page": "Source Page",
|
||||
"risk_status": "Risk Status",
|
||||
"risk_score": "Risk Score",
|
||||
"latency": "Latency (ms)",
|
||||
"is_empty_answer": "Empty Answer",
|
||||
"is_system_failure": "System Failure",
|
||||
"feedback_score": "Rating",
|
||||
@@ -2183,7 +2216,8 @@
|
||||
"agents": "App Ops",
|
||||
"ops_overview": "Ops Overview",
|
||||
"issue_analysis": "Issue Analysis",
|
||||
"usage_analysis": "Usage Analytics"
|
||||
"usage_analysis": "Usage Analytics",
|
||||
"permission_requests": "Permission Requests"
|
||||
},
|
||||
"feedbackValues": {
|
||||
"types": {
|
||||
@@ -2391,6 +2425,14 @@
|
||||
"topApp": "App to optimize",
|
||||
"topAppHint": "Attention signal share {ratio}%"
|
||||
}
|
||||
},
|
||||
"usageRangeLabel": "Time range",
|
||||
"usageRanges": {
|
||||
"7d": "Last 7 days",
|
||||
"30d": "Last 30 days",
|
||||
"90d": "Last 3 months",
|
||||
"180d": "Last 6 months",
|
||||
"365d": "Last 12 months"
|
||||
}
|
||||
},
|
||||
"batchEdit": {
|
||||
@@ -2650,7 +2692,9 @@
|
||||
"voucherCheckNotifyMissing": "Notify on missing materials",
|
||||
"voucherCheckNotifyMissingHint": "Master switch. Set missing-file recipients in Chat “Accounting voucher check → Notification config” by file type. The schedule people picker is only for failure alerts.",
|
||||
"voucherCheckNotifyFailure": "Failure alert",
|
||||
"voucherCheckNotifyFailureHint": "Technical failures go to the people selected below."
|
||||
"voucherCheckNotifyFailureHint": "Technical failures go to the people selected below.",
|
||||
"dynamicParamsSearchPlaceholder": "Search options (name / ID / dept)…",
|
||||
"dynamicParamsSearchNoMatch": "No matching options"
|
||||
},
|
||||
"testRun": {
|
||||
"title": "Test run — {name}",
|
||||
@@ -2734,7 +2778,8 @@
|
||||
"notConfiguredUseDefault": "(Not configured; using Dify workflow default prompt)",
|
||||
"notEnabledTest": "Dify was not enabled for this test",
|
||||
"notEnabledRun": "Dify Agent was not enabled for this run"
|
||||
}
|
||||
},
|
||||
"excelExportFailedHint": "Inventory source succeeded, but schedule Excel generation failed"
|
||||
},
|
||||
"shippingIdentityRules": {
|
||||
"eyebrow": "Shipping customer governance",
|
||||
@@ -4380,7 +4425,8 @@
|
||||
"rejected": "Rejected",
|
||||
"needs_review": "Needs review"
|
||||
},
|
||||
"confirmRequiresNativePreview": "Load the native PDF preview before confirming a visual binding"
|
||||
"confirmRequiresNativePreview": "Load the native PDF preview before confirming a visual binding",
|
||||
"createBlockersTitle": "Pre-creation Blockers"
|
||||
},
|
||||
"xfaAutoMark": {
|
||||
"title": "Auto-mark suggestions",
|
||||
@@ -5422,7 +5468,17 @@
|
||||
"trainingAgentRequired": "The Employee Training agent was not found, so a video resource cannot be created",
|
||||
"videoUploaded": "Training video uploaded and added to configuration resources",
|
||||
"videoUploadFailed": "Failed to upload training video"
|
||||
}
|
||||
},
|
||||
"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": {
|
||||
"title": "Integration Connector",
|
||||
|
||||
@@ -1188,7 +1188,11 @@
|
||||
"departmentLabel": "Department",
|
||||
"allStatuses": "All statuses",
|
||||
"allDepartments": "All departments",
|
||||
"noLimit": "No limit"
|
||||
"noLimit": "No limit",
|
||||
"typeLabel": "Training Type",
|
||||
"allTypes": "All Training",
|
||||
"typeOnboarding": "Onboarding Training",
|
||||
"typeSafety": "Safety Training"
|
||||
},
|
||||
"columns": {
|
||||
"joinDate": "Join date",
|
||||
@@ -1543,6 +1547,75 @@
|
||||
"Which employees have not finished training?",
|
||||
"I want this month training score statistics"
|
||||
]
|
||||
},
|
||||
"safety": {
|
||||
"tabs": {
|
||||
"onboarding": "入职培训",
|
||||
"safety": "安全培训"
|
||||
},
|
||||
"progressTitle": "三级安全教育培训进度",
|
||||
"progressHint": "按国家安全生产法要求,新员工须依次完成公司级、部门级、班组级三级安全教育。学完三级的全部资料/视频后,进入1次统一考试,≥90分及格方可结业。",
|
||||
"steps": {
|
||||
"company": "01 · 公司级",
|
||||
"department": "02 · 部门级",
|
||||
"team": "03 · 班组级",
|
||||
"exam": "04 · 统一考试"
|
||||
},
|
||||
"stepStatus": {
|
||||
"watchVideo": "观看视频",
|
||||
"examReq": "≥90 分及格",
|
||||
"completed": "已完成",
|
||||
"inProgress": "进行中",
|
||||
"pending": "待学习",
|
||||
"examPending": "需先学完三级"
|
||||
},
|
||||
"videoPanelTitle": "{level} 第{step}步",
|
||||
"videoPanelSubtitle": "观看安全教育培训视频",
|
||||
"videoPanelPassLine": "及格线:≥ 90分方可进入考试",
|
||||
"videoTitle": "部门安全生产管理制度宣导",
|
||||
"videoDuration": "时长 35 分钟 · 已完成 12%",
|
||||
"materialsTitle": "培训资料清单 (共 3 个文件/视频)",
|
||||
"materials": {
|
||||
"m1": "部门安全生产管理制度宣导.mp4",
|
||||
"m2": "危险化学品安全操作规程.pdf",
|
||||
"m3": "消防应急疏散演练视频.mp4"
|
||||
},
|
||||
"flowTitle": "学习与考试流程",
|
||||
"flowSteps": {
|
||||
"company": "公司级安全教育",
|
||||
"department": "部门级安全教育",
|
||||
"team": "班组级安全教育",
|
||||
"exam": "统一考试 ≥90分"
|
||||
},
|
||||
"summaryTitle": "培训总结",
|
||||
"summaryContent": {
|
||||
"company": [
|
||||
"1公司教育:国家有关安全生产方针、政策、法律、法规和有关规定。",
|
||||
"2公司安全生产特点、有关安全管理标准和制度、安全生产情况及安全生产基本知识。",
|
||||
"3企业安全生产规章制度、安全纪律和劳动纪律。",
|
||||
"4安全生产和职业卫生的基本知识(防机械伤害、安全用电、防火防爆、防尘防毒、急救、危险因素、应急预案等)。",
|
||||
"5作业场所和工作岗位存在的危险因素、防范措施及事故应急措施;",
|
||||
"6安全生产正反方面的经验和教训,及重大事故安全案例教训。",
|
||||
"7从业人员安全生产权利和义务;"
|
||||
],
|
||||
"department": [
|
||||
"1部门概况、生产或作业特点、可能存在的不安全因素及必须遵守的事项。",
|
||||
"2公司、部门安全生产状况、管理制度规定和安全注意事项。",
|
||||
"3所从事工种的安全技术操作规程、安全职责、操作技能及强制性标准。",
|
||||
"4一般的机械设备、电气、触电、中暑、中毒急救安全基础知识",
|
||||
"5作业场所和工作岗位存在的风险、部门危险因素分布、安全通道、职业危害、伤亡事故、应急救缓预案内容。防火、防毒、防尘、防爆知识及紧急情况安全处置、自救互救、急救方法、疏散和现场紧急情况的处理。",
|
||||
"6部门安全设施(工具)、安全警示标志、急救器材、消防器材和个人防护用品的性能、使用方法和维护。",
|
||||
"7部门以往发生的典型安全和职业危害事故教育、岗位预防措施等。",
|
||||
"8有关事故案例。"
|
||||
],
|
||||
"team": [
|
||||
"1本班组(岗位)生产工艺流程、作业特点和注意事项、安全操作规程及细则。",
|
||||
"2本班组安全活动制度及纪律、岗位之间工作衔接配合的安全与职业卫生事项。",
|
||||
"3本班组(岗位)设备、工具的性能和安全装置、安全设施、监控仪器的作用原理、正确使用方法、防护用品及消防器材的使用和保管方法等。",
|
||||
"4危害因素及防范、应急措施,本岗位易发生事故的不安全因素及其防范对策,本工种事故案例剖析。",
|
||||
"5本岗位发现紧急情况应采取的应救措施和报告办法。"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"shippingOrderReview": {
|
||||
@@ -2679,7 +2752,8 @@
|
||||
"inventory_source_unresolved": "Inventory source unresolved",
|
||||
"effective_reservation_missing": "A valid reservation number is missing",
|
||||
"unknown": "The system found an item that needs confirmation"
|
||||
}
|
||||
},
|
||||
"autoCreateBlocked": "Manual creation qualified, but auto-creation is not; after confirmation it will proceed manually."
|
||||
},
|
||||
"inventoryCandidates": {
|
||||
"title": "Manual inventory selection",
|
||||
|
||||
@@ -1,6 +1,21 @@
|
||||
{
|
||||
"generic": "Request failed.",
|
||||
"codes": {
|
||||
"ORDER_DELIVERY_REPLY.FORBIDDEN": "You do not have permission to view order delivery replies. Contact an administrator.",
|
||||
"ORDER_DELIVERY_REPLY.LINE_NOT_FOUND": "Order delivery line not found or no longer in sync scope.",
|
||||
"ORDER_DELIVERY_REPLY.ADMIN_REQUIRED": "Only platform administrators can grant permissions by department.",
|
||||
"ORDER_DELIVERY_REPLY.GRANT_DEPARTMENT_REQUIRED": "Please specify the department to grant permissions to.",
|
||||
"ORDER_DELIVERY_REPLY.GRANT_PERMISSION_INVALID": "Permission type must be manage or access.",
|
||||
"ORDER_DELIVERY_REPLY.BATCH_REPLY_EMPTY": "Batch reply requires at least one line and at most 200 per request.",
|
||||
"ORDER_DELIVERY_REPLY.NOTIFY_BATCH_EMPTY": "Batch notify requires at least one line and at most 200 per request.",
|
||||
"ORDER_DELIVERY_REPLY.SALESPERSON_UNMAPPED": "The salesperson has no linked account or WeCom binding; notification cannot be sent.",
|
||||
"ORDER_DELIVERY_REPLY.NOTIFY_FAILED": "WeCom notification failed. The line remains unlocked; please retry later.",
|
||||
"ORDER_DELIVERY_REPLY.LINE_LOCKED": "The delivery schedule of this line is locked after notification and cannot be modified.",
|
||||
"ORDER_DELIVERY_REPLY.MANAGE_FORBIDDEN": "You do not have manage permission for order delivery replies.",
|
||||
"ORDER_DELIVERY_REPLY.BATCHES_REQUIRED": "Please provide at least one delivery batch.",
|
||||
"ORDER_DELIVERY_REPLY.BATCH_COUNT_EXCEEDED": "Too many batches for a single line.",
|
||||
"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.FULFILLMENT_POLICY_INVALID": "The fulfillment policy or field capability binding is invalid.",
|
||||
"SHIPPING.FULFILLMENT_POLICY_NOT_FOUND": "The fulfillment policy was not found.",
|
||||
|
||||
@@ -113,7 +113,8 @@
|
||||
"contractPayment": "Contract Payment Alerts",
|
||||
"contractPaymentLedger": "Contract Ledger",
|
||||
"contractPaymentReview": "Contracts for Confirmation",
|
||||
"contractPaymentWeeklyBatches": "Weekly Summary Batches"
|
||||
"contractPaymentWeeklyBatches": "Weekly Summary Batches",
|
||||
"orderDeliveryReply": "Order Delivery Reply"
|
||||
},
|
||||
"kb": {
|
||||
"accessDenied": "Administrator access is required to open the knowledge base."
|
||||
@@ -202,7 +203,21 @@
|
||||
"resend": "Resend to WeCom",
|
||||
"failedUnits": "Failed receipt units",
|
||||
"retry": "Retry with reason",
|
||||
"retryReasonPrompt": "Enter the reason for retrying {target}"
|
||||
"retryReasonPrompt": "Enter the reason for retrying {target}",
|
||||
"batch": {
|
||||
"selectAll": "全選目前頁通知單",
|
||||
"selected": "已選 {count} 張",
|
||||
"download": "批次下載 Excel",
|
||||
"confirm": "批次確認已上傳",
|
||||
"rpa": "批次啟動 RPA",
|
||||
"downloadStarted": "已開始下載所選發貨通知 Excel",
|
||||
"success": "{action}:已處理 {count} 張通知單",
|
||||
"partialResult": "{action}:成功 {accepted} 張,阻斷 {blocked} 張,請查看重新整理後的通知狀態。",
|
||||
"lines": "項次",
|
||||
"parts": "料號",
|
||||
"quantities": "本次發貨 / 可用庫存",
|
||||
"uploadStatus": "貨代狀態"
|
||||
}
|
||||
},
|
||||
"shippingNotice": {
|
||||
"title": "Shipping Notice Tasks",
|
||||
@@ -968,5 +983,100 @@
|
||||
"notifyExcel": "Excel",
|
||||
"downloadExcel": "Download Excel",
|
||||
"downloadExcelFailed": "Failed to download Excel"
|
||||
},
|
||||
"orderDeliveryReply": {
|
||||
"deepLinkLocated": "Located the order line from the notification: {order}:{item}",
|
||||
"search": "Search",
|
||||
"reset": "Reset",
|
||||
"saving": "Saving…",
|
||||
"syncNow": "Refresh now",
|
||||
"syncing": "Syncing…",
|
||||
"syncNever": "Never synced",
|
||||
"syncAt": "Last sync: {time}",
|
||||
"syncRunning": "Sync in progress…",
|
||||
"syncFailedAt": "Last sync failed ({time}); list shows the last successful snapshot",
|
||||
"syncDone": "Sync completed, {count} lines",
|
||||
"syncSkipped": "A sync is already running; try again later",
|
||||
"syncFailedTitle": "Sync failed; last snapshot kept",
|
||||
"filterKeyword": "Keyword (order / product / customer / salesperson / replier)",
|
||||
"filterKeywordPh": "Search by order no., part no., name, customer part no., customer, salesperson, or reply person",
|
||||
"filterOrderDate": "Order Date",
|
||||
"filterStatus": "Reply Status",
|
||||
"statusAll": "All",
|
||||
"statusReplied": "Replied",
|
||||
"statusNotFully": "Not fully replied",
|
||||
"statusNotReplied": "Not replied",
|
||||
"statusPartial": "Partially replied",
|
||||
"totalCount": "{count} product lines",
|
||||
"selectAll": "Select all (this page)",
|
||||
"selectedCount": "{count} lines selected",
|
||||
"batchReply": "+ Batch reply",
|
||||
"batchNotify": "Batch notify",
|
||||
"toolbarHint": "Batch reply only saves; click \"Batch notify\" to send and lock.",
|
||||
"colOrderLine": "Order : Item",
|
||||
"colOrderDate": "Order Date",
|
||||
"colCustomer": "Customer",
|
||||
"colSalesperson": "Salesperson",
|
||||
"colDept": "Department",
|
||||
"colCustomerPo": "Customer PO",
|
||||
"colPartNo": "Part No.",
|
||||
"colPartName": "Part Name",
|
||||
"colSpec": "Spec",
|
||||
"colCustomerPartNo": "Customer Part No.",
|
||||
"colAgreedDate": "Agreed Date",
|
||||
"colUnit": "Unit",
|
||||
"colQty": "Qty",
|
||||
"colDelivered": "Delivered",
|
||||
"colUndelivered": "Undelivered",
|
||||
"colStatus": "Reply Status",
|
||||
"colReply": "Delivery Reply",
|
||||
"colNotify": "Notify",
|
||||
"colReplyPerson": "Replied By",
|
||||
"batchCount": "{count} batches",
|
||||
"repliedOf": "replied {replied}/{remain}",
|
||||
"overTag": "OVER",
|
||||
"collapse": "Collapse ▲",
|
||||
"expand": "+{count} more ▾",
|
||||
"lockedTag": "Locked",
|
||||
"replyAction": "Reply",
|
||||
"editReplyAction": "Edit reply",
|
||||
"notifiedTag": "Notified {name}",
|
||||
"replyFirst": "Reply first",
|
||||
"notifyAction": "Send notification",
|
||||
"pendingNotify": "Recorded after notify",
|
||||
"empty": "No matching order lines",
|
||||
"pageInfo": "Page {page} / {pages}",
|
||||
"modalTitleSingle": "Reply · {order} / item {item}",
|
||||
"modalTitleBatch": "Batch reply ({count} lines)",
|
||||
"quickDate": "Quick unified date",
|
||||
"applyQuickDate": "Apply to all",
|
||||
"modalHint": "Fill one date, or split into multiple date+qty batches; the batch quantity total must equal the order quantity.",
|
||||
"itemLabel": "Item {item}",
|
||||
"qtyPh": "Qty",
|
||||
"remarkPh": "Remark (optional)",
|
||||
"removeBatch": "Remove batch",
|
||||
"addBatch": "+ Add batch (date + qty + remark)",
|
||||
"saveReply": "Save reply",
|
||||
"noValidBatches": "Fill a date and quantity for at least one line",
|
||||
"saveSingleDone": "Batches saved (not notified; still editable)",
|
||||
"saveBatchDone": "Saved batches for {ok} lines (not notified)",
|
||||
"saveBatchPartial": "Saved: {ok} ok, {fail} failed: {detail}",
|
||||
"saveFailedTitle": "Save failed",
|
||||
"loadFailed": "Failed to load order lines",
|
||||
"notifyConfirm": "Send to salesperson \"{salesperson}\"?\nYou have order {order}:{item} to fill/confirm/check delivery.\nThe schedule will be locked after sending.",
|
||||
"notifyDone": "Notified and locked: {order}:{item}",
|
||||
"notifyBatchConfirm": "Send notifications for {count} lines; successful lines will be locked. Continue?",
|
||||
"notifyPartial": "Partial success: {ok} ok, {fail} failed, {skip} skipped. Failed: {detail}",
|
||||
"notifyAllFailed": "All failed ({fail} lines): {detail}",
|
||||
"notifyBatchDone": "Notified and locked {ok} lines, skipped {skip}",
|
||||
"notifyFailedTitle": "Notification failed; line not locked",
|
||||
"entryHint": "Query orders, reply delivery, notify sales",
|
||||
"notNotified": "Not notified",
|
||||
"orderQtyLabel": "Order qty: {qty} {unit}",
|
||||
"batchMissingDate": "Batch {batches}: delivery date missing",
|
||||
"batchMissingQty": "Batch {batches}: quantity missing",
|
||||
"qtyTotalMismatchLine": "Batch total {total} must equal order quantity {qty}",
|
||||
"saveBlocked": "These lines are incomplete and cannot be saved: {detail}",
|
||||
"batchDuplicateDate": "Different batches of the same order line cannot have the same delivery date (duplicates: {dates})"
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,8 @@
|
||||
"platformApps": "แอปแพลตฟอร์ม",
|
||||
"procurementContract": "ตรวจสอบสัญญาจัดซื้อ",
|
||||
"trainingConfig": "การกำหนดค่าการฝึกอบรม",
|
||||
"integrationConnector": "ตัวเชื่อมต่อระบบ"
|
||||
"integrationConnector": "ตัวเชื่อมต่อระบบ",
|
||||
"contractPayment": "合同付款预警"
|
||||
},
|
||||
"shippingOrderExtractionRuns": {
|
||||
"eyebrow": "การวินิจฉัยการทำงานแบบอ่านอย่างเดียว",
|
||||
@@ -1139,7 +1140,12 @@
|
||||
"status": "สถานะ",
|
||||
"enable": "เปิดใช้",
|
||||
"disable": "ปิดใช้",
|
||||
"save": "บันทึก"
|
||||
"save": "บันทึก",
|
||||
"guideUsage": "资料用途",
|
||||
"generalGuide": "通用指南",
|
||||
"trainingVideo": "员工培训视频",
|
||||
"trainingExamPdf": "员工培训试题 PDF",
|
||||
"guideUsageHint": "培训工作区会优先读取“员工培训视频”和“员工培训试题 PDF”这两类资料。"
|
||||
},
|
||||
"dash": {
|
||||
"activeAgents": "ตัวแทนที่ใช้งานอยู่",
|
||||
@@ -1208,6 +1214,10 @@
|
||||
"trainingLeanTeamManage": "จัดการการฝึกอบรม Lean ระดับทีม",
|
||||
"contractPaymentAccess": "สิทธิ์แจ้งเตือนการชำระเงินตามสัญญา",
|
||||
"contractPaymentAccessHint": "เมื่อเปิดแล้ว ผู้ใช้นี้จะเข้าโต๊ะทำงานแจ้งเตือนการชำระเงินตามสัญญา (บัญชีสัญญา รายการรอยืนยัน และชุดสรุปรายสัปดาห์) ได้ การซิงก์ OA สแกนแจ้งเตือน และส่งสรุปรายสัปดาห์ใช้ได้เฉพาะผู้ดูแลระบบ",
|
||||
"orderDeliveryReplyManage": "จัดการการตอบกลับกำหนดส่ง",
|
||||
"orderDeliveryReplyManageHint": "เปิดสิทธิ์บันทึกงวดการส่ง ส่ง/แจ้งเตือนหลายรายการ และซิงค์ ERP ด้วยตนเอง (ฝ่ายวางแผนการผลิต)",
|
||||
"orderDeliveryReplyAccess": "ดูการตอบกลับกำหนดส่ง",
|
||||
"orderDeliveryReplyAccessHint": "เปิดสิทธิ์ดูอย่างอ่านอย่างเดียวสำหรับคำสั่งซื้อที่ซิงค์แล้ว (เจ้าหน้าที่ธุรกิจ)",
|
||||
"password": "รหัสผ่าน",
|
||||
"passwordHint": "(เว้นว่างไว้หากไม่ต้องการเปลี่ยน)",
|
||||
"noAgents": "ไม่มีตัวแทนที่ใช้ได้"
|
||||
@@ -1241,11 +1251,13 @@
|
||||
"name": "ชื่อ",
|
||||
"code": "รหัส",
|
||||
"company": "บริษัท",
|
||||
"actions": "การกระทำ"
|
||||
"actions": "การกระทำ",
|
||||
"members": "Members"
|
||||
},
|
||||
"actions": {
|
||||
"edit": "แก้ไข",
|
||||
"delete": "ลบ"
|
||||
"delete": "ลบ",
|
||||
"viewMembers": "View department members"
|
||||
},
|
||||
"fields": {
|
||||
"name": "ชื่อ",
|
||||
@@ -1260,6 +1272,11 @@
|
||||
"confirmDelete": "ลบแผนกนี้หรือไม่?",
|
||||
"msg": {
|
||||
"nameRequired": "กรุณากรอกชื่อแผนก"
|
||||
},
|
||||
"members": {
|
||||
"title": "{name} Members",
|
||||
"count": "{count} members",
|
||||
"empty": "No members"
|
||||
}
|
||||
},
|
||||
"agent": {
|
||||
@@ -1792,12 +1809,13 @@
|
||||
"firstLoginInputFields": "ฟิลด์ที่ใช้กรอกในครั้งแรก",
|
||||
"employeeIdSource": "แหล่งที่มาของรหัสพนักงาน",
|
||||
"mobileNormalize": "ปรับรูปแบบเบอร์โทรศัพท์",
|
||||
"callbackToken": "Callback Token",
|
||||
"callbackToken": "โทเคนคอลแบ็ก",
|
||||
"encodingAesKey": "EncodingAESKey",
|
||||
"callbackUrl": "Callback URL",
|
||||
"homepageUrl": "Application Homepage URL",
|
||||
"trustedDomain": "Trusted Domain",
|
||||
"publicBaseUrl": "Public HTTPS base"
|
||||
"callbackUrl": "URL คอลแบ็ก",
|
||||
"homepageUrl": "URL หน้าแรกแอป",
|
||||
"trustedDomain": "โดเมนที่เชื่อถือ",
|
||||
"publicBaseUrl": "Public HTTPS base",
|
||||
"userId": "User ID (user_id)"
|
||||
},
|
||||
"bindModes": {
|
||||
"match_rules": "จับคู่อัตโนมัติ",
|
||||
@@ -1910,8 +1928,23 @@
|
||||
"filterName": "กรองตามชื่อ/ชื่อผู้ใช้",
|
||||
"filterDept": "กรองตามแผนก",
|
||||
"allRoles": "ทุกบทบาท",
|
||||
"views": { "apps": "ตามแอปพลิเคชัน", "members": "ตามสมาชิก" },
|
||||
"appHeaders": { "app": "แอปพลิเคชัน", "type": "ประเภท", "authorized": "ผู้ได้รับอนุญาต", "actions": "การดำเนินการ", "viewMembers": "ดูสมาชิก", "accessHint": "เปิดสิทธิ์ของสมาชิก", "memberHint": "เพิ่มหรือลบสิทธิ์ของแอปนี้", "memberSearch": "ค้นหาชื่อ ชื่อผู้ใช้ รหัสพนักงาน หรือแผนก", "addMember": "มอบสิทธิ์", "removeMember": "ยกเลิกสิทธิ์", "noMembers": "ไม่พบสมาชิกที่ตรงกัน" },
|
||||
"views": {
|
||||
"apps": "ตามแอปพลิเคชัน",
|
||||
"members": "ตามสมาชิก"
|
||||
},
|
||||
"appHeaders": {
|
||||
"app": "แอปพลิเคชัน",
|
||||
"type": "ประเภท",
|
||||
"authorized": "ผู้ได้รับอนุญาต",
|
||||
"actions": "การดำเนินการ",
|
||||
"viewMembers": "ดูสมาชิก",
|
||||
"accessHint": "เปิดสิทธิ์ของสมาชิก",
|
||||
"memberHint": "เพิ่มหรือลบสิทธิ์ของแอปนี้",
|
||||
"memberSearch": "ค้นหาชื่อ ชื่อผู้ใช้ รหัสพนักงาน หรือแผนก",
|
||||
"addMember": "มอบสิทธิ์",
|
||||
"removeMember": "ยกเลิกสิทธิ์",
|
||||
"noMembers": "ไม่พบสมาชิกที่ตรงกัน"
|
||||
},
|
||||
"headers": {
|
||||
"user": "ผู้ใช้",
|
||||
"realName": "ชื่อจริง",
|
||||
@@ -2148,7 +2181,7 @@
|
||||
"tokens_completion": "โทเค็นผลลัพธ์",
|
||||
"total_tokens": "โทเค็นรวม",
|
||||
"latency_ms": "ความหน่วง (ms)",
|
||||
"latency": "ความหน่วง",
|
||||
"latency": "เวลาแฝง (ms)",
|
||||
"cost": "ค่าใช้จ่าย",
|
||||
"ip": "IP",
|
||||
"user_agent": "User Agent",
|
||||
@@ -2164,13 +2197,15 @@
|
||||
"reset_token_expiry": "เวลาหมดอายุโทเค็นรีเซ็ต",
|
||||
"risk_status": "สถานะความเสี่ยง",
|
||||
"risk_score": "คะแนนความเสี่ยง",
|
||||
"latency": "เวลาแฝง (ms)",
|
||||
"is_empty_answer": "คำตอบว่าง",
|
||||
"is_system_failure": "ระบบล้มเหลว",
|
||||
"feedback_score": "คะแนน",
|
||||
"feedback_comment": "หมายเหตุคะแนน",
|
||||
"negative_feedback_count": "จำนวนข้อเสนอแนะเชิงลบ",
|
||||
"actions": "การทำงาน"
|
||||
"actions": "การทำงาน",
|
||||
"feedback_module": "Feedback Module",
|
||||
"feedback_type": "Feedback Type",
|
||||
"source_page": "Source Page"
|
||||
},
|
||||
"tables": {
|
||||
"users": "ผู้ใช้",
|
||||
@@ -2181,7 +2216,8 @@
|
||||
"agents": "แอปปฏิบัติการ",
|
||||
"ops_overview": "ภาพรวมการดำเนินงาน",
|
||||
"issue_analysis": "การวิเคราะห์ปัญหา",
|
||||
"usage_analysis": "วิเคราะห์การใช้งาน"
|
||||
"usage_analysis": "วิเคราะห์การใช้งาน",
|
||||
"permission_requests": "คำขอสิทธิ์"
|
||||
},
|
||||
"usageIntro": "ดูแนวโน้มการเรียกใช้แอป AI ผู้ใช้ที่ใช้งาน แอปที่ใช้น้อย และช่วงพีคผิดปกติ",
|
||||
"usageTotalSessions": "จำนวนแชทรวม",
|
||||
@@ -2371,6 +2407,32 @@
|
||||
"topApp": "แอปที่ควรปรับปรุง",
|
||||
"topAppHint": "สัดส่วนสัญญาณที่ต้องให้ความสนใจ {ratio}%"
|
||||
}
|
||||
},
|
||||
"usageRangeLabel": "ช่วงเวลา",
|
||||
"usageRanges": {
|
||||
"7d": "7 วันล่าสุด",
|
||||
"30d": "30 วันล่าสุด",
|
||||
"90d": "3 เดือนล่าสุด",
|
||||
"180d": "6 เดือนล่าสุด",
|
||||
"365d": "12 เดือนล่าสุด"
|
||||
},
|
||||
"feedbackValues": {
|
||||
"types": {
|
||||
"feature_suggestion": "Feature Suggestion",
|
||||
"issue_feedback": "Issue Feedback",
|
||||
"experience_optimization": "Experience Optimization"
|
||||
},
|
||||
"modules": {
|
||||
"knowledge_base": "Knowledge Base",
|
||||
"general": "General",
|
||||
"workflow": "Workflow",
|
||||
"account_permission": "Account & Permissions"
|
||||
},
|
||||
"pages": {
|
||||
"workspace": "Workspace",
|
||||
"chat": "Chat",
|
||||
"unknown": "Unknown"
|
||||
}
|
||||
}
|
||||
},
|
||||
"batchEdit": {
|
||||
@@ -2517,7 +2579,35 @@
|
||||
"voucherCheckNotifyMissing": "แจ้งเตือนเมื่อขาดเอกสาร",
|
||||
"voucherCheckNotifyMissingHint": "สวิตช์หลัก กำหนดผู้รับไฟล์ขาดในแชท 「ตรวจเอกสารบัญชี → ตั้งค่าการแจ้งเตือน」 ตามประเภทไฟล์ การเลือกคนด้านล่างใช้สำหรับแจ้งเตือนเมื่อล้มเหลวเท่านั้น",
|
||||
"voucherCheckNotifyFailure": "แจ้งเตือนเมื่อล้มเหลว",
|
||||
"voucherCheckNotifyFailureHint": "เมื่อล้มเหลวทางเทคนิคจะส่งให้ผู้ที่เลือกด้านล่าง"
|
||||
"voucherCheckNotifyFailureHint": "เมื่อล้มเหลวทางเทคนิคจะส่งให้ผู้ที่เลือกด้านล่าง",
|
||||
"editTitle": "Edit schedule",
|
||||
"createTitle": "Add schedule",
|
||||
"name": "Schedule name",
|
||||
"namePlaceholder": "e.g. RoHS auto review schedule",
|
||||
"owner": "Schedule owner",
|
||||
"noUsers": "No users available",
|
||||
"selectOwner": "Select an owner",
|
||||
"faqHotAggregate": "FAQ hot aggregate",
|
||||
"querying": "Querying...",
|
||||
"testQuery": "Test query",
|
||||
"expandConfig": "Expand config",
|
||||
"collapseConfig": "Collapse config",
|
||||
"dataSourceSection": "Data source config",
|
||||
"waitSeconds": "Wait time (seconds)",
|
||||
"noAgents": "No agents available",
|
||||
"agentDisabled": "Disabled",
|
||||
"minuteInterval": "Minute interval",
|
||||
"minuteOfHour": "Minute of hour",
|
||||
"weekday": "Weekday",
|
||||
"notifyEnabled": "Enable notifications",
|
||||
"selectNotifyUsers": "Select notification recipients...",
|
||||
"enableOnCreate": "Enable after creation",
|
||||
"cancel": "Cancel",
|
||||
"saving": "Saving...",
|
||||
"saveChanges": "Save changes",
|
||||
"createSchedule": "Create schedule",
|
||||
"dynamicParamsSearchPlaceholder": "ค้นหาตัวเลือก (ชื่อ/รหัส/แผนก)…",
|
||||
"dynamicParamsSearchNoMatch": "ไม่มีตัวเลือกที่ตรง"
|
||||
},
|
||||
"status": {
|
||||
"all": "ทุกสถานะ",
|
||||
@@ -2554,7 +2644,25 @@
|
||||
"noKbGroupHint": "โปรดเปิดใช้การซิงค์คลังความรู้และเลือกกลุ่มในการแก้ไขตารางเวลาก่อน",
|
||||
"kbSyncNoStatus": "มีการขอเขียนคลังความรู้แล้ว แต่ไม่ได้รับสถานะซิงค์ โปรดตรวจการตั้งค่าคลังความรู้หรือบันทึก backend",
|
||||
"baseFetchSqlReadonly": "SQL ดึงข้อมูลพื้นฐาน (base_fetch_sql) — อ่านอย่างเดียว",
|
||||
"limitRows": "จำกัดจำนวนแถว (limit)"
|
||||
"limitRows": "จำกัดจำนวนแถว (limit)",
|
||||
"title": "Test run — {name}",
|
||||
"subtitle": "Edit WHERE clause, limit rows, run quickly and inspect each step",
|
||||
"close": "Close",
|
||||
"running": "Running...",
|
||||
"start": "Start test run",
|
||||
"waitingHint": "Dify calls may take a while, please wait...",
|
||||
"total": "Total",
|
||||
"success": "Success",
|
||||
"failed": "Failed",
|
||||
"skipped": "Skipped",
|
||||
"limitSummary": "Limit {limit} rows | Dify Agent ID: {agentId}",
|
||||
"noAgent": "None",
|
||||
"stepLogs": "Step logs",
|
||||
"viewSql": "View execution SQL",
|
||||
"errors": "Errors ({count})",
|
||||
"queryResult": "Query result",
|
||||
"resultSummary": "{total} total, showing {showing}",
|
||||
"viewGeneratedSql": "View generated SQL"
|
||||
},
|
||||
"deleteDialogTitle": "ลบตารางเวลา",
|
||||
"excelExportFailedHint": "แหล่งสต็อกสำเร็จแล้ว แต่การส่งออก Excel ของตารางเวลาล้มเหลว",
|
||||
@@ -2572,8 +2680,19 @@
|
||||
"receiptRawZip": "ใบรับดิบ",
|
||||
"columns": {
|
||||
"skippedCount": "ข้าม",
|
||||
"skippedCountReceipt": "ไม่มีใบรับ/ข้าม",
|
||||
"skippedCountInventory": "ไม่มีสต็อก/ข้าม"
|
||||
"runNo": "Run ID",
|
||||
"startedAt": "Started at",
|
||||
"finishedAt": "Finished at",
|
||||
"status": "Status",
|
||||
"totalCount": "Processed",
|
||||
"successCount": "Success",
|
||||
"failedCount": "Failed",
|
||||
"excelExportFailedHint": "Inventory sources succeeded, but schedule Excel export failed",
|
||||
"wecomNotified": "WeCom notify",
|
||||
"detail": "Detail",
|
||||
"log": "Log",
|
||||
"skippedCountReceipt": "ไม่มีใบรับ/ข้าม",
|
||||
"skippedCountInventory": "ไม่มีสต็อก/ข้าม"
|
||||
},
|
||||
"deleteConfirmMessage": "ยืนยันการลบตารางเวลา \"{name}\"?",
|
||||
"msg": {
|
||||
@@ -2587,8 +2706,9 @@
|
||||
"runNowWaitTimeout": "รอการรันเสร็จสิ้นเกินเวลาที่กำหนด (ประมาณ 15 นาที) หยุดรีเฟรชอัตโนมัติแล้ว โปรดค้นหาบันทึกด้วยตนเอง",
|
||||
"downloadExcelFailed": "ดาวน์โหลด Excel ล้มเหลว",
|
||||
"downloadInventoryRawZipFailed": "ดาวน์โหลด ZIP สต็อกดิบล้มเหลว",
|
||||
"downloadReceiptRawZipFailed": "ดาวน์โหลด ZIP ใบรับดิบล้มเหลว",
|
||||
"deleteFailed": "ลบตารางเวลาล้มเหลว"
|
||||
"deleteFailed": "ลบตารางเวลาล้มเหลว",
|
||||
"testQueryFailed": "Test query failed",
|
||||
"downloadReceiptRawZipFailed": "ดาวน์โหลด ZIP ใบรับดิบล้มเหลว"
|
||||
},
|
||||
"difySnapshot": {
|
||||
"title": "สแนปช็อตการทำงาน Dify (ตรวจสอบ)",
|
||||
@@ -2600,6 +2720,65 @@
|
||||
"notConfiguredUseDefault": "(ยังไม่ได้ตั้งค่า ใช้ prompt เริ่มต้นใน Dify workflow)",
|
||||
"notEnabledTest": "การทดสอบนี้ไม่ได้เปิดใช้ Dify",
|
||||
"notEnabledRun": "การรันนี้ไม่ได้เปิดใช้ Dify Agent"
|
||||
},
|
||||
"overviewTitle": "Schedule Management Overview",
|
||||
"workbenchTitle": "Schedule Management Workbench",
|
||||
"overviewSubtitle": "Click a schedule card to open the workbench.",
|
||||
"workbenchSubtitle": "Schedule list on the left, run records on the right.",
|
||||
"refresh": "Refresh schedules",
|
||||
"stats": {
|
||||
"total": "Total schedules",
|
||||
"enabled": "Enabled",
|
||||
"disabled": "Disabled",
|
||||
"running": "Running"
|
||||
},
|
||||
"sectionOverview": "Schedule Management Overview",
|
||||
"switchByCard": "Switch by card",
|
||||
"addTitle": "Add schedule",
|
||||
"addHint": "Click the button to fill in schedule fields in a dialog.",
|
||||
"addButton": "Add schedule",
|
||||
"emptyList": "No schedules yet. Create one first.",
|
||||
"loading": "Loading...",
|
||||
"enabled": "Enabled",
|
||||
"disabled": "Disabled",
|
||||
"scheduleNo": "No.",
|
||||
"config": "Config",
|
||||
"owner": "Owner",
|
||||
"lastRun": "Last run",
|
||||
"nextRun": "Next run",
|
||||
"nextRunDisabled": "Disabled",
|
||||
"nextRunPending": "Not computed (save or restart schedule)",
|
||||
"noSelection": "No schedule selected",
|
||||
"selectedHint": "Selected schedule · Last run {time}",
|
||||
"runBatches": "Run batches",
|
||||
"totalProcessed": "Total processed",
|
||||
"totalSuccess": "Total success",
|
||||
"totalFailed": "Total failed",
|
||||
"listTitle": "Schedule list",
|
||||
"recordsTitle": "{name} · Run records",
|
||||
"recordsSubtitle": "Run record details are shown below.",
|
||||
"noSelectionHint": "Select a schedule from the list on the left first.",
|
||||
"filterStart": "Start",
|
||||
"filterEnd": "End",
|
||||
"query": "Search",
|
||||
"reset": "Reset",
|
||||
"queryingRuns": "Loading records...",
|
||||
"noRunRecords": "No run records yet.",
|
||||
"runLogs": "Run logs",
|
||||
"stepsCount": "{count} steps",
|
||||
"viewDetail": "View details",
|
||||
"resizeColumn": "Drag to resize {label} column",
|
||||
"notified": "Notified",
|
||||
"notifyError": "Error",
|
||||
"download": "Download",
|
||||
"log": "Log",
|
||||
"actions": {
|
||||
"edit": "Edit",
|
||||
"start": "Start",
|
||||
"pause": "Pause",
|
||||
"run": "Run",
|
||||
"test": "Test",
|
||||
"delete": "Delete"
|
||||
}
|
||||
},
|
||||
"shippingIdentityRules": {
|
||||
@@ -4246,7 +4425,8 @@
|
||||
"rejected": "ปฏิเสธแล้ว",
|
||||
"needs_review": "ต้องตรวจ"
|
||||
},
|
||||
"confirmRequiresNativePreview": "โหลดตัวอย่าง PDF ดั้งเดิมก่อนยืนยันการผูกภาพ"
|
||||
"confirmRequiresNativePreview": "โหลดตัวอย่าง PDF ดั้งเดิมก่อนยืนยันการผูกภาพ",
|
||||
"createBlockersTitle": "创建前阻断项"
|
||||
},
|
||||
"xfaAutoMark": {
|
||||
"title": "คำแนะนำทำเครื่องหมายอัตโนมัติ",
|
||||
@@ -5288,7 +5468,17 @@
|
||||
"trainingAgentRequired": "ไม่พบ Agent การฝึกอบรมพนักงาน จึงไม่สามารถสร้างทรัพยากรวิดีโอได้",
|
||||
"videoUploaded": "อัปโหลดวิดีโอการฝึกอบรมและเพิ่มในทรัพยากรการกำหนดค่าแล้ว",
|
||||
"videoUploadFailed": "อัปโหลดวิดีโอการฝึกอบรมไม่สำเร็จ"
|
||||
}
|
||||
},
|
||||
"eyebrow": "培训运营中心",
|
||||
"pageHint": "配置变更将在保存后生效",
|
||||
"footerHint": "所有配置项均支持保存后继续调整",
|
||||
"stats": {
|
||||
"total": "配置总数",
|
||||
"published": "已发布",
|
||||
"resources": "当前资料",
|
||||
"levels": "已配置级别"
|
||||
},
|
||||
"questionBankTitle": "入职培训题库"
|
||||
},
|
||||
"integrationConnector": {
|
||||
"title": "ตัวเชื่อมต่อระบบ",
|
||||
|
||||
@@ -129,7 +129,17 @@
|
||||
"notInScopeAction": "ให้ผู้ดูแลเพิ่มสมาชิกคนนี้หรือแผนกของสมาชิกเข้าไปในขอบเขตการมองเห็นของแอป WeCom",
|
||||
"retryLogin": "เริ่มต้นการเข้าสู่ระบบ WeCom ใหม่อีกครั้ง",
|
||||
"contactAdmin": "กรุณาติดต่อผู้ดูแลระบบเพื่อขอความช่วยเหลือ"
|
||||
}
|
||||
},
|
||||
"newPassword": "New Password",
|
||||
"passwordResetSuccess": "Password reset successfully. Please login.",
|
||||
"featuredAgents": "Featured AI Agents",
|
||||
"pleaseLoginFirst": "Please login to access this agent.",
|
||||
"userNotFound": "User not found",
|
||||
"incorrectPassword": "Incorrect password",
|
||||
"accountDisabled": "Account is disabled",
|
||||
"dbConnectionFailed": "Database connection failed. Please check if the database service is running.",
|
||||
"internalError": "Internal server error. Please try again later.",
|
||||
"passwordResetEmailSent": "If the account exists, a reset link has been sent to your email."
|
||||
},
|
||||
"landing": {
|
||||
"hero": {
|
||||
@@ -156,7 +166,8 @@
|
||||
"realName": "ชื่อจริง",
|
||||
"employeeId": "รหัสพนักงาน",
|
||||
"phone": "หมายเลขโทรศัพท์"
|
||||
}
|
||||
},
|
||||
"emailRequired": "Email is required"
|
||||
},
|
||||
"resetPassword": {
|
||||
"title": "รีเซ็ตรหัสผ่าน",
|
||||
|
||||
@@ -1188,7 +1188,11 @@
|
||||
"departmentLabel": "แผนก",
|
||||
"allStatuses": "ทุกสถานะ",
|
||||
"allDepartments": "ทุกแผนก",
|
||||
"noLimit": "ไม่จำกัด"
|
||||
"noLimit": "ไม่จำกัด",
|
||||
"typeLabel": "培训类型",
|
||||
"allTypes": "全部培训",
|
||||
"typeOnboarding": "入职培训",
|
||||
"typeSafety": "安全培训"
|
||||
},
|
||||
"columns": {
|
||||
"joinDate": "วันที่เริ่มงาน",
|
||||
@@ -1543,6 +1547,75 @@
|
||||
"พนักงานคนไหนยังไม่จบการอบรม?",
|
||||
"อยากดูสถิติคะแนนอบรมเดือนนี้"
|
||||
]
|
||||
},
|
||||
"safety": {
|
||||
"tabs": {
|
||||
"onboarding": "入职培训",
|
||||
"safety": "安全培训"
|
||||
},
|
||||
"progressTitle": "三级安全教育培训进度",
|
||||
"progressHint": "按国家安全生产法要求,新员工须依次完成公司级、部门级、班组级三级安全教育。学完三级的全部资料/视频后,进入1次统一考试,≥90分及格方可结业。",
|
||||
"steps": {
|
||||
"company": "01 · 公司级",
|
||||
"department": "02 · 部门级",
|
||||
"team": "03 · 班组级",
|
||||
"exam": "04 · 统一考试"
|
||||
},
|
||||
"stepStatus": {
|
||||
"watchVideo": "观看视频",
|
||||
"examReq": "≥90 分及格",
|
||||
"completed": "已完成",
|
||||
"inProgress": "进行中",
|
||||
"pending": "待学习",
|
||||
"examPending": "需先学完三级"
|
||||
},
|
||||
"videoPanelTitle": "{level} 第{step}步",
|
||||
"videoPanelSubtitle": "观看安全教育培训视频",
|
||||
"videoPanelPassLine": "及格线:≥ 90分方可进入考试",
|
||||
"videoTitle": "部门安全生产管理制度宣导",
|
||||
"videoDuration": "时长 35 分钟 · 已完成 12%",
|
||||
"materialsTitle": "培训资料清单 (共 3 个文件/视频)",
|
||||
"materials": {
|
||||
"m1": "部门安全生产管理制度宣导.mp4",
|
||||
"m2": "危险化学品安全操作规程.pdf",
|
||||
"m3": "消防应急疏散演练视频.mp4"
|
||||
},
|
||||
"flowTitle": "学习与考试流程",
|
||||
"flowSteps": {
|
||||
"company": "公司级安全教育",
|
||||
"department": "部门级安全教育",
|
||||
"team": "班组级安全教育",
|
||||
"exam": "统一考试 ≥90分"
|
||||
},
|
||||
"summaryTitle": "培训总结",
|
||||
"summaryContent": {
|
||||
"company": [
|
||||
"1公司教育:国家有关安全生产方针、政策、法律、法规和有关规定。",
|
||||
"2公司安全生产特点、有关安全管理标准和制度、安全生产情况及安全生产基本知识。",
|
||||
"3企业安全生产规章制度、安全纪律和劳动纪律。",
|
||||
"4安全生产和职业卫生的基本知识(防机械伤害、安全用电、防火防爆、防尘防毒、急救、危险因素、应急预案等)。",
|
||||
"5作业场所和工作岗位存在的危险因素、防范措施及事故应急措施;",
|
||||
"6安全生产正反方面的经验和教训,及重大事故安全案例教训。",
|
||||
"7从业人员安全生产权利和义务;"
|
||||
],
|
||||
"department": [
|
||||
"1部门概况、生产或作业特点、可能存在的不安全因素及必须遵守的事项。",
|
||||
"2公司、部门安全生产状况、管理制度规定和安全注意事项。",
|
||||
"3所从事工种的安全技术操作规程、安全职责、操作技能及强制性标准。",
|
||||
"4一般的机械设备、电气、触电、中暑、中毒急救安全基础知识",
|
||||
"5作业场所和工作岗位存在的风险、部门危险因素分布、安全通道、职业危害、伤亡事故、应急救缓预案内容。防火、防毒、防尘、防爆知识及紧急情况安全处置、自救互救、急救方法、疏散和现场紧急情况的处理。",
|
||||
"6部门安全设施(工具)、安全警示标志、急救器材、消防器材和个人防护用品的性能、使用方法和维护。",
|
||||
"7部门以往发生的典型安全和职业危害事故教育、岗位预防措施等。",
|
||||
"8有关事故案例。"
|
||||
],
|
||||
"team": [
|
||||
"1本班组(岗位)生产工艺流程、作业特点和注意事项、安全操作规程及细则。",
|
||||
"2本班组安全活动制度及纪律、岗位之间工作衔接配合的安全与职业卫生事项。",
|
||||
"3本班组(岗位)设备、工具的性能和安全装置、安全设施、监控仪器的作用原理、正确使用方法、防护用品及消防器材的使用和保管方法等。",
|
||||
"4危害因素及防范、应急措施,本岗位易发生事故的不安全因素及其防范对策,本工种事故案例剖析。",
|
||||
"5本岗位发现紧急情况应采取的应救措施和报告办法。"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"shippingOrderReview": {
|
||||
@@ -2679,7 +2752,8 @@
|
||||
"inventory_source_unresolved": "ยังไม่ระบุแหล่งสต็อก",
|
||||
"effective_reservation_missing": "ไม่มีหมายเลขการจองที่ถูกต้อง",
|
||||
"unknown": "ระบบพบรายการที่ต้องยืนยันด้วยตนเอง"
|
||||
}
|
||||
},
|
||||
"autoCreateBlocked": "人工建单资格已通过,但自动建单资格未通过;确认后将由人工推进。"
|
||||
},
|
||||
"inventoryCandidates": {
|
||||
"title": "เลือกแหล่งสต็อกด้วยตนเอง",
|
||||
|
||||
@@ -1,6 +1,21 @@
|
||||
{
|
||||
"generic": "คำขอล้มเหลว",
|
||||
"codes": {
|
||||
"ORDER_DELIVERY_REPLY.FORBIDDEN": "คุณไม่มีสิทธิ์ดูการตอบกลับกำหนดส่งคำสั่งซื้อ โปรดติดต่อผู้ดูแลระบบ",
|
||||
"ORDER_DELIVERY_REPLY.LINE_NOT_FOUND": "ไม่พบรายการคำสั่งซื้อ หรือไม่อยู่ในขอบเขตการซิงค์แล้ว",
|
||||
"ORDER_DELIVERY_REPLY.ADMIN_REQUIRED": "เฉพาะผู้ดูแลระบบเท่านั้นที่ออกสิทธิ์ตามแผนกได้",
|
||||
"ORDER_DELIVERY_REPLY.GRANT_DEPARTMENT_REQUIRED": "โปรดระบุแผนกที่จะออกสิทธิ์",
|
||||
"ORDER_DELIVERY_REPLY.GRANT_PERMISSION_INVALID": "ประเภทสิทธิ์ต้องเป็น manage หรือ access",
|
||||
"ORDER_DELIVERY_REPLY.BATCH_REPLY_EMPTY": "การตอบกลับหลายรายการต้องมีอย่างน้อยหนึ่งรายการ และไม่เกิน 200 รายการต่อครั้ง",
|
||||
"ORDER_DELIVERY_REPLY.NOTIFY_BATCH_EMPTY": "การแจ้งเตือนหลายรายการต้องมีอย่างน้อยหนึ่งรายการ และไม่เกิน 200 รายการต่อครั้ง",
|
||||
"ORDER_DELIVERY_REPLY.SALESPERSON_UNMAPPED": "พนักงานขายไม่ได้เชื่อมโยงบัญชีระบบหรือยังไม่ได้ผูก WeCom จึงส่งแจ้งเตือนไม่ได้",
|
||||
"ORDER_DELIVERY_REPLY.NOTIFY_FAILED": "ส่งแจ้งเตือน WeCom ไม่สำเร็จ รายการยังไม่ถูกล็อก โปรดลองอีกครั้ง",
|
||||
"ORDER_DELIVERY_REPLY.LINE_LOCKED": "กำหนดส่งของรายการนี้ถูกล็อกหลังแจ้งแล้ว ไม่สามารถแก้ไขได้",
|
||||
"ORDER_DELIVERY_REPLY.MANAGE_FORBIDDEN": "คุณไม่มีสิทธิ์ดำเนินการตอบกลับกำหนดส่งคำสั่งซื้อ",
|
||||
"ORDER_DELIVERY_REPLY.BATCHES_REQUIRED": "กรุณาระบุอย่างน้อยหนึ่งงวดการส่งมอบ",
|
||||
"ORDER_DELIVERY_REPLY.BATCH_COUNT_EXCEEDED": "จำนวนงวดเกินขีดจำกัดของรายการเดียว",
|
||||
"ORDER_DELIVERY_REPLY.BATCH_INVALID": "รูปแบบงวดไม่ถูกต้อง โปรดตรวจสอบวันที่ จำนวน หรือหมายเหตุ",
|
||||
"ORDER_DELIVERY_REPLY.BATCH_QTY_TOTAL_MISMATCH": "ผลรวมจำนวนทุกงวดต้องเท่ากับจำนวนของคำสั่งซื้อ โปรดปรับแล้วบันทึกอีกครั้ง",
|
||||
"SHIPPING.NOTICE_ODM_CHOICE_INVALID": "ODM ID ที่เลือกไม่อยู่ในตัวเลือกที่ทำได้ โปรดเลือกใหม่",
|
||||
"SHIPPING.FULFILLMENT_POLICY_INVALID": "นโยบายการปฏิบัติตามหรือการผูกความสามารถของฟิลด์ไม่ถูกต้อง",
|
||||
"SHIPPING.FULFILLMENT_POLICY_NOT_FOUND": "ไม่พบนโยบายการปฏิบัติตาม",
|
||||
|
||||
@@ -104,7 +104,8 @@
|
||||
"contractPayment": "การแจ้งเตือนการชำระเงินตามสัญญา",
|
||||
"contractPaymentLedger": "ทะเบียนสัญญา",
|
||||
"contractPaymentReview": "สัญญาที่รอยืนยัน",
|
||||
"contractPaymentWeeklyBatches": "ชุดสรุปรายสัปดาห์"
|
||||
"contractPaymentWeeklyBatches": "ชุดสรุปรายสัปดาห์",
|
||||
"orderDeliveryReply": "ตอบกลับกำหนดส่งคำสั่งซื้อ"
|
||||
},
|
||||
"receiptReports": {
|
||||
"title": "ไฟล์รับสินค้า",
|
||||
@@ -904,5 +905,178 @@
|
||||
"notifyExcel": "Excel",
|
||||
"downloadExcel": "ดาวน์โหลด Excel",
|
||||
"downloadExcelFailed": "ดาวน์โหลด Excel ไม่สำเร็จ"
|
||||
},
|
||||
"orderDeliveryReply": {
|
||||
"deepLinkLocated": "พบบรรทัดคำสั่งขายจากการแจ้งเตือนแล้ว: {order}:{item}",
|
||||
"search": "ค้นหา",
|
||||
"reset": "ล้าง",
|
||||
"saving": "กำลังบันทึก…",
|
||||
"syncNow": "รีเฟรชตอนนี้",
|
||||
"syncing": "กำลังซิงค์…",
|
||||
"syncNever": "ยังไม่เคยซิงค์",
|
||||
"syncAt": "ซิงค์ล่าสุด: {time}",
|
||||
"syncRunning": "กำลังซิงค์…",
|
||||
"syncFailedAt": "ซิงค์ล่าสุดล้มเหลว ({time}) รายการเป็นภาพรวมครั้งล่าสุดที่สำเร็จ",
|
||||
"syncDone": "ซิงค์สำเร็จ รวม {count} รายการ",
|
||||
"syncSkipped": "มีการซิงค์กำลังทำงานอยู่ โปรดลองอีกครั้งภายหลัง",
|
||||
"syncFailedTitle": "ซิงค์ล้มเหลว ยังคงภาพรวมเดิมไว้",
|
||||
"filterKeyword": "คำค้นหา (คำสั่งซื้อ / ผลิตภัณฑ์ / ลูกค้า / พนักงานขาย / ผู้ตอบกำหนดส่ง)",
|
||||
"filterKeywordPh": "ค้นหาด้วยเลขที่คำสั่งซื้อ รหัสสินค้า ชื่อสินค้า รหัสสินค้าลูกค้า ลูกค้า พนักงานขาย หรือผู้ตอบกำหนดส่งได้",
|
||||
"filterOrderDate": "วันที่สั่งซื้อ",
|
||||
"filterStatus": "สถานะการตอบกลับ",
|
||||
"statusAll": "ทั้งหมด",
|
||||
"statusReplied": "ตอบกลับแล้ว",
|
||||
"statusNotFully": "ยังตอบไม่ครบ",
|
||||
"statusNotReplied": "ยังไม่ตอบกลับ",
|
||||
"statusPartial": "ตอบบางส่วน",
|
||||
"totalCount": "รวม {count} รายการสินค้า",
|
||||
"selectAll": "เลือกทั้งหมด (หน้านี้)",
|
||||
"selectedCount": "เลือกแล้ว {count} รายการ",
|
||||
"batchReply": "+ ตอบกลับหลายรายการ",
|
||||
"batchNotify": "แจ้งเตือนหลายรายการ",
|
||||
"toolbarHint": "การตอบกลับหลายรายการเป็นเพียงบันทึก ต้องกดแจ้งเตือนจึงจะส่งและล็อก",
|
||||
"colOrderLine": "เลขที่ : รายการ",
|
||||
"colOrderDate": "วันที่สั่งซื้อ",
|
||||
"colCustomer": "ลูกค้า",
|
||||
"colSalesperson": "พนักงานขาย",
|
||||
"colDept": "แผนก",
|
||||
"colCustomerPo": "PO ลูกค้า",
|
||||
"colPartNo": "รหัสสินค้า",
|
||||
"colPartName": "ชื่อสินค้า",
|
||||
"colSpec": "สเปก",
|
||||
"colCustomerPartNo": "รหัสสินค้าลูกค้า",
|
||||
"colAgreedDate": "กำหนดส่งตามข้อตกลง",
|
||||
"colUnit": "หน่วย",
|
||||
"colQty": "จำนวน",
|
||||
"colDelivered": "ส่งแล้ว",
|
||||
"colUndelivered": "ยังไม่ส่ง",
|
||||
"colStatus": "สถานะตอบกลับ",
|
||||
"colReply": "การตอบกลับกำหนดส่ง",
|
||||
"colNotify": "แจ้งเตือน",
|
||||
"colReplyPerson": "ผู้ตอบกลับ",
|
||||
"batchCount": "{count} งวด",
|
||||
"repliedOf": "ตอบแล้ว {replied}/{remain}",
|
||||
"overTag": "เกิน",
|
||||
"collapse": "ย่อ ▲",
|
||||
"expand": "+{count} งวด ▾",
|
||||
"lockedTag": "ล็อกแล้ว",
|
||||
"replyAction": "ตอบกลับ",
|
||||
"editReplyAction": "แก้ไขการตอบกลับ",
|
||||
"notifiedTag": "แจ้งแล้ว {name}",
|
||||
"replyFirst": "กรุณาตอบกลับก่อน",
|
||||
"notifyAction": "ส่งการแจ้งเตือน",
|
||||
"pendingNotify": "บันทึกหลังแจ้งเตือน",
|
||||
"empty": "ไม่พบรายการที่ตรงเงื่อนไข",
|
||||
"pageInfo": "หน้า {page} / {pages}",
|
||||
"modalTitleSingle": "ตอบกลับ · {order} / รายการ {item}",
|
||||
"modalTitleBatch": "ตอบกลับหลายรายการ ({count} รายการ)",
|
||||
"quickDate": "วันที่รวมด่วน",
|
||||
"applyQuickDate": "ใช้กับทั้งหมด",
|
||||
"modalHint": "กรอกวันที่เดียว หรือแยกเป็นหลายงวด (วันที่+จำนวน) ได้ โดยผลรวมจำนวนทุกงวดต้องเท่ากับจำนวนของคำสั่งซื้อ",
|
||||
"itemLabel": "รายการ {item}",
|
||||
"qtyPh": "จำนวน",
|
||||
"remarkPh": "หมายเหตุ (ไม่บังคับ)",
|
||||
"removeBatch": "ลบงวดนี้",
|
||||
"addBatch": "+ เพิ่มงวด (วันที่ + จำนวน + หมายเหตุ)",
|
||||
"saveReply": "บันทึกการตอบกลับ",
|
||||
"noValidBatches": "กรุณากรอกวันที่และจำนวนอย่างน้อยหนึ่งรายการ",
|
||||
"saveSingleDone": "บันทึกงวดแล้ว (ยังไม่แจ้งเตือน แก้ไขได้)",
|
||||
"saveBatchDone": "บันทึก {ok} รายการแล้ว (ยังไม่แจ้งเตือน)",
|
||||
"saveBatchPartial": "บันทึกแล้ว: สำเร็จ {ok} ล้มเหลว {fail}: {detail}",
|
||||
"saveFailedTitle": "บันทึกไม่สำเร็จ",
|
||||
"loadFailed": "โหลดรายการไม่สำเร็จ",
|
||||
"notifyConfirm": "ยืนยันส่งถึงพนักงานขาย \"{salesperson}\"?\nคุณมีคำสั่งซื้อ {order}:{item} ที่ต้องกรอก/ยืนยัน/ตรวจสอบกำหนดส่ง\nหลังส่งแล้วกำหนดส่งจะถูกล็อก",
|
||||
"notifyDone": "แจ้งเตือนและล็อกแล้ว: {order}:{item}",
|
||||
"notifyBatchConfirm": "จะส่งแจ้งเตือน {count} รายการ รายการที่ส่งสำเร็จจะถูกล็อก ดำเนินการต่อ?",
|
||||
"notifyPartial": "สำเร็จบางส่วน: สำเร็จ {ok} ล้มเหลว {fail} ข้าม {skip} รายการ ที่ล้มเหลว: {detail}",
|
||||
"notifyAllFailed": "ล้มเหลวทั้งหมด ({fail} รายการ): {detail}",
|
||||
"notifyBatchDone": "แจ้งเตือนและล็อก {ok} รายการ ข้าม {skip} รายการ",
|
||||
"notifyFailedTitle": "ส่งแจ้งเตือนไม่สำเร็จ รายการยังไม่ถูกล็อก",
|
||||
"entryHint": "ค้นคำสั่งซื้อ ตอบกำหนดส่ง แจ้งพนักงานขาย",
|
||||
"notNotified": "ยังไม่แจ้ง",
|
||||
"orderQtyLabel": "จำนวนคำสั่งซื้อ: {qty} {unit}",
|
||||
"batchMissingDate": "งวดที่ {batches}: ยังไม่ได้กรอกวันที่",
|
||||
"batchMissingQty": "งวดที่ {batches}: ยังไม่ได้กรอกจำนวน",
|
||||
"qtyTotalMismatchLine": "ผลรวมทุกงวด {total} ต้องเท่ากับจำนวนคำสั่งซื้อ {qty}",
|
||||
"saveBlocked": "รายการต่อไปนี้กรอกไม่ครบถ้วน จึงบันทึกไม่ได้: {detail}",
|
||||
"batchDuplicateDate": "งวดต่างๆ ของคำสั่งซื้อ:รายการเดียวกันต้องไม่มีวันที่กำหนดส่งเดียวกัน (ซ้ำ: {dates})"
|
||||
},
|
||||
"lang": {
|
||||
"zhCN": "Simplified Chinese",
|
||||
"zhTW": "Traditional Chinese"
|
||||
},
|
||||
"schedule": {
|
||||
"title": "Schedule Runs",
|
||||
"refresh": "Refresh",
|
||||
"batch": {
|
||||
"selectAll": "Select all notices on this page",
|
||||
"selected": "{count} selected",
|
||||
"download": "Download Excel",
|
||||
"confirm": "Confirm uploaded",
|
||||
"rpa": "Start RPA upload",
|
||||
"downloadStarted": "Downloading the selected shipping-notice Excel files.",
|
||||
"success": "{action}: {count} notice(s) processed.",
|
||||
"partialResult": "{action}: {accepted} accepted and {blocked} blocked. Refresh to see the latest notice status.",
|
||||
"lines": "Lines",
|
||||
"parts": "Parts",
|
||||
"quantities": "Shipment / available",
|
||||
"uploadStatus": "Freight status"
|
||||
},
|
||||
"uploadNotices": "Upload shipping notices",
|
||||
"search": "Search",
|
||||
"reset": "Reset",
|
||||
"loading": "Loading...",
|
||||
"empty": "No schedule runs",
|
||||
"download": "Download",
|
||||
"noPendingData": "No pending data",
|
||||
"filters": {
|
||||
"name": "Schedule Name",
|
||||
"namePlaceholder": "Enter schedule name",
|
||||
"start": "Start Time",
|
||||
"end": "End Time",
|
||||
"status": "Status"
|
||||
},
|
||||
"columns": {
|
||||
"name": "Schedule Name",
|
||||
"runNo": "Run No.",
|
||||
"triggerType": "Trigger",
|
||||
"start": "Start Time",
|
||||
"end": "End Time",
|
||||
"duration": "Duration",
|
||||
"status": "Status",
|
||||
"total": "Total",
|
||||
"success": "Success",
|
||||
"failed": "Failed",
|
||||
"detail": "Detail"
|
||||
},
|
||||
"trigger": {
|
||||
"manual": "Manual",
|
||||
"test": "Test",
|
||||
"timed": "Scheduled"
|
||||
},
|
||||
"status": {
|
||||
"all": "All",
|
||||
"success": "Success",
|
||||
"partialFailed": "Partial Success",
|
||||
"failed": "Failed",
|
||||
"running": "Running",
|
||||
"queued": "Queued"
|
||||
},
|
||||
"msg": {
|
||||
"downloadExcelFailed": "Failed to download Excel"
|
||||
}
|
||||
},
|
||||
"profile": {
|
||||
"msg": {
|
||||
"loadFailed": "Failed to load profile",
|
||||
"saveFailed": "Failed to save profile",
|
||||
"saved": "Profile saved",
|
||||
"changePasswordFailed": "Failed to change password"
|
||||
}
|
||||
},
|
||||
"msg": {
|
||||
"casdoorNotMatchedContactAdmin": "Casdoor login succeeded, but no local account matched. Please contact the administrator.",
|
||||
"casdoorNotMatchedNeedLocalUser": "Casdoor login succeeded, but no local account matched. Ask the administrator to create a local user with the same username or email.",
|
||||
"localAccountDisabled": "This local account is disabled. Please contact the administrator."
|
||||
}
|
||||
}
|
||||
@@ -1342,6 +1342,10 @@
|
||||
"trainingLeanTeamManage": "精益培训班组管理",
|
||||
"contractPaymentAccess": "合同付款预警访问",
|
||||
"contractPaymentAccessHint": "勾选后可进入工作台合同付款预警(台账、待确认、周汇总)。同步 OA、扫描预警和发送预警仅管理员可用。",
|
||||
"orderDeliveryReplyManage": "订单交期回复操作",
|
||||
"orderDeliveryReplyManageHint": "勾选后可回复交期批次、发送/批量通知业务员并手动同步 ERP 订单(生管)。",
|
||||
"orderDeliveryReplyAccess": "订单交期回复查看",
|
||||
"orderDeliveryReplyAccessHint": "勾选后可只读查看已同步订单与回复结果(业务人员);回复与通知需另勾「操作」权限。",
|
||||
"password": "密码",
|
||||
"passwordHint": "(留空表示不修改)",
|
||||
"noAgents": "暂无可用应用"
|
||||
@@ -1383,7 +1387,11 @@
|
||||
"delete": "删除",
|
||||
"viewMembers": "查看部门员工"
|
||||
},
|
||||
"members": { "title": "{name}员工", "count": "共 {count} 人", "empty": "暂无员工" },
|
||||
"members": {
|
||||
"title": "{name}员工",
|
||||
"count": "共 {count} 人",
|
||||
"empty": "暂无员工"
|
||||
},
|
||||
"fields": {
|
||||
"name": "名称",
|
||||
"namePlaceholder": "例如:信息技术部",
|
||||
@@ -1929,7 +1937,13 @@
|
||||
"firstLoginInputFields": "首次登录可输入字段",
|
||||
"employeeIdSource": "工号来源字段",
|
||||
"mobileNormalize": "手机号归一化",
|
||||
"publicBaseUrl": "外网 HTTPS 基地址"
|
||||
"publicBaseUrl": "外网 HTTPS 基地址",
|
||||
"callbackToken": "回调Token",
|
||||
"encodingAesKey": "EncodingAESKey",
|
||||
"callbackUrl": "回调URL",
|
||||
"homepageUrl": "应用主页URL",
|
||||
"trustedDomain": "可信域名",
|
||||
"userId": "用户 ID(user_id)"
|
||||
},
|
||||
"bindModes": {
|
||||
"match_rules": "按规则自动匹配",
|
||||
@@ -2042,8 +2056,23 @@
|
||||
"filterName": "筛选 姓名/用户名",
|
||||
"filterDept": "筛选 部门",
|
||||
"allRoles": "所有角色",
|
||||
"views": { "apps": "按应用查看", "members": "按成员查看" },
|
||||
"appHeaders": { "app": "应用", "type": "类型", "authorized": "已授权人数", "actions": "操作", "viewMembers": "查看成员", "accessHint": "点击查看成员权限", "memberHint": "可添加或取消此应用的访问权限", "memberSearch": "搜索姓名、用户名、工号或部门", "addMember": "添加权限", "removeMember": "取消权限", "noMembers": "没有匹配的人员" },
|
||||
"views": {
|
||||
"apps": "按应用查看",
|
||||
"members": "按成员查看"
|
||||
},
|
||||
"appHeaders": {
|
||||
"app": "应用",
|
||||
"type": "类型",
|
||||
"authorized": "已授权人数",
|
||||
"actions": "操作",
|
||||
"viewMembers": "查看成员",
|
||||
"accessHint": "点击查看成员权限",
|
||||
"memberHint": "可添加或取消此应用的访问权限",
|
||||
"memberSearch": "搜索姓名、用户名、工号或部门",
|
||||
"addMember": "添加权限",
|
||||
"removeMember": "取消权限",
|
||||
"noMembers": "没有匹配的人员"
|
||||
},
|
||||
"headers": {
|
||||
"user": "用户",
|
||||
"realName": "真实姓名",
|
||||
@@ -2280,7 +2309,7 @@
|
||||
"tokens_completion": "补全 Token",
|
||||
"total_tokens": "总 Token",
|
||||
"latency_ms": "延迟(毫秒)",
|
||||
"latency": "延迟",
|
||||
"latency": "耗时(毫秒)",
|
||||
"cost": "费用",
|
||||
"ip": "IP",
|
||||
"user_agent": "用户代理",
|
||||
@@ -2296,13 +2325,15 @@
|
||||
"reset_token_expiry": "重置令牌过期时间",
|
||||
"risk_status": "风险状态",
|
||||
"risk_score": "风险分",
|
||||
"latency": "耗时(毫秒)",
|
||||
"is_empty_answer": "空回答",
|
||||
"is_system_failure": "系统失败",
|
||||
"feedback_score": "评分",
|
||||
"feedback_comment": "评分备注",
|
||||
"negative_feedback_count": "负面反馈数",
|
||||
"actions": "操作"
|
||||
"actions": "操作",
|
||||
"feedback_module": "反馈模块",
|
||||
"feedback_type": "反馈类型",
|
||||
"source_page": "来源页面"
|
||||
},
|
||||
"tables": {
|
||||
"users": "用户",
|
||||
@@ -2313,7 +2344,8 @@
|
||||
"agents": "应用运营",
|
||||
"ops_overview": "运营总览",
|
||||
"issue_analysis": "问题分析",
|
||||
"usage_analysis": "使用分析"
|
||||
"usage_analysis": "使用分析",
|
||||
"permission_requests": "权限申请"
|
||||
},
|
||||
"usageIntro": "查看 AI 应用调用趋势、活跃用户、低使用应用与异常高峰。",
|
||||
"usageTotalSessions": "对话总量",
|
||||
@@ -2503,6 +2535,32 @@
|
||||
"topApp": "优先优化应用",
|
||||
"topAppHint": "需要关注信号占比 {ratio}%"
|
||||
}
|
||||
},
|
||||
"usageRangeLabel": "统计范围",
|
||||
"usageRanges": {
|
||||
"7d": "近一周",
|
||||
"30d": "近一月",
|
||||
"90d": "近三月",
|
||||
"180d": "近半年",
|
||||
"365d": "近一年"
|
||||
},
|
||||
"feedbackValues": {
|
||||
"types": {
|
||||
"feature_suggestion": "功能建议",
|
||||
"issue_feedback": "问题反馈",
|
||||
"experience_optimization": "体验优化"
|
||||
},
|
||||
"modules": {
|
||||
"knowledge_base": "知识库",
|
||||
"general": "通用",
|
||||
"workflow": "工作流",
|
||||
"account_permission": "账号与权限"
|
||||
},
|
||||
"pages": {
|
||||
"workspace": "工作台",
|
||||
"chat": "聊天",
|
||||
"unknown": "未知"
|
||||
}
|
||||
}
|
||||
},
|
||||
"batchEdit": {
|
||||
@@ -2762,7 +2820,9 @@
|
||||
"voucherCheckNotifyMissing": "缺资料通知",
|
||||
"voucherCheckNotifyMissingHint": "总开关。缺件接收人请到 Chat「立账凭证 → 通知配置」按文件类型设置;排程选人只用于技术失败告警。",
|
||||
"voucherCheckNotifyFailure": "失败告警",
|
||||
"voucherCheckNotifyFailureHint": "技术失败发给下方「选择通知人员」。"
|
||||
"voucherCheckNotifyFailureHint": "技术失败发给下方「选择通知人员」。",
|
||||
"dynamicParamsSearchPlaceholder": "搜索选项(姓名/工号/部门)…",
|
||||
"dynamicParamsSearchNoMatch": "没有匹配的选项"
|
||||
},
|
||||
"testRun": {
|
||||
"title": "测试执行 — {name}",
|
||||
@@ -2846,7 +2906,8 @@
|
||||
"notConfiguredUseDefault": "(未配置,使用 Dify 编排内默认提示词)",
|
||||
"notEnabledTest": "本次测试未启用 Dify",
|
||||
"notEnabledRun": "本次执行未启用 Dify Agent"
|
||||
}
|
||||
},
|
||||
"excelExportFailedHint": "库存来源已成功,但排程 Excel 生成失败"
|
||||
},
|
||||
"shippingIdentityRules": {
|
||||
"eyebrow": "货代客户治理",
|
||||
|
||||
@@ -1,188 +1,189 @@
|
||||
{
|
||||
"title": "企业级 AI 网关",
|
||||
"login": {
|
||||
"username": "用户名",
|
||||
"password": "密码",
|
||||
"submit": "登录",
|
||||
"registerLink": "点击注册",
|
||||
"noAccount": "没有账号?",
|
||||
"subtitle": "欢迎回来!请输入您的详细信息。",
|
||||
"placeholder": {
|
||||
"username": "请输入用户名",
|
||||
"password": "密码"
|
||||
"title": "企业级 AI 网关",
|
||||
"login": {
|
||||
"username": "用户名",
|
||||
"password": "密码",
|
||||
"submit": "登录",
|
||||
"registerLink": "点击注册",
|
||||
"noAccount": "没有账号?",
|
||||
"subtitle": "欢迎回来!请输入您的详细信息。",
|
||||
"placeholder": {
|
||||
"username": "请输入用户名",
|
||||
"password": "密码"
|
||||
},
|
||||
"failed": "登录失败",
|
||||
"inputError": "请输入用户名和密码",
|
||||
"usernameRequired": "用户名不能为空",
|
||||
"usernameRequiredHint": "请输入用户名",
|
||||
"passwordRequired": "密码不能为空",
|
||||
"passwordRequiredHint": "请输入密码",
|
||||
"loginRequired": "请先登录",
|
||||
"sessionExpired": "登录已失效",
|
||||
"sessionExpiredHint": "请重新登录后继续使用。",
|
||||
"requestFailed": "登录请求失败",
|
||||
"forgotPassword": "忘记密码?",
|
||||
"newPassword": "新密码",
|
||||
"passwordResetSuccess": "密码重置成功,请重新登录。",
|
||||
"featuredAgents": "推荐 AI 应用",
|
||||
"pleaseLoginFirst": "请先登录以使用此应用。",
|
||||
"userNotFound": "用户不存在",
|
||||
"incorrectPassword": "密码错误",
|
||||
"accountDisabled": "账号已禁用",
|
||||
"dbConnectionFailed": "数据库连接失败,请检查数据库服务是否运行。",
|
||||
"internalError": "服务器内部错误,请稍后重试。",
|
||||
"rememberMe": "记住我",
|
||||
"forgotPasswordDesc": "输入工号和用户名,重置链接将发送到您的企业微信",
|
||||
"findPassword": "找回密码",
|
||||
"employeeIdRequired": "请输入工号",
|
||||
"passwordResetWecomSent": "若账号存在且已绑定企业微信,重置链接已发送到您的企业微信。",
|
||||
"passwordResetEmailSent": "若账号存在,重置链接已发送到您的邮箱。",
|
||||
"passwordResetRequestFailed": "请求密码重置失败",
|
||||
"passwordResetRateLimited": "操作过于频繁,请 {minutes} 分钟后再试",
|
||||
"announcements": "公告",
|
||||
"casdoorLogin": "Casdoor 登录",
|
||||
"casdoorErrors": {
|
||||
"invalidCredentials": "用户名或密码错误",
|
||||
"codeExpired": "登录会话已过期,请重新登录",
|
||||
"stateExpired": "登录会话已过期,请重试",
|
||||
"accessDenied": "登录已取消或被拒绝",
|
||||
"configError": "认证服务暂不可用,请联系管理员",
|
||||
"authFailed": "登录失败,请稍后重试",
|
||||
"passwordPolicy": "新密码不符合安全要求",
|
||||
"setPasswordFailed": "修改密码失败,请稍后重试或联系管理员",
|
||||
"incorrectCurrentPassword": "原:当前密码不正确,新:您输入的原密码有误,请重新输入",
|
||||
"passwordUnchanged": "新密码不能与当前密码相同",
|
||||
"userNotInIdp": "您的账号尚未在统一认证系统中开通,请联系管理员同步账号后再修改密码。"
|
||||
},
|
||||
"casdoorDialogTitles": {
|
||||
"userNotFound": "未匹配到本地账号",
|
||||
"userNotInIdp": "认证系统中无此账号",
|
||||
"accountDisabled": "账号已禁用",
|
||||
"sessionExpired": "登录会话已过期",
|
||||
"configError": "认证服务异常",
|
||||
"accessDenied": "登录未完成",
|
||||
"loginFailed": "登录失败"
|
||||
},
|
||||
"casdoorDialogDetails": {
|
||||
"contactAdmin": "若问题持续出现,请联系管理员处理。",
|
||||
"retryLogin": "请关闭此窗口后重新登录。"
|
||||
},
|
||||
"wecomLogin": "企业微信登录",
|
||||
"wecomComingSoon": "企业微信登录功能正在开发中,敬请期待",
|
||||
"wecomConnecting": "正在连接企业微信...",
|
||||
"wecomStartFailed": "启动企业微信登录失败",
|
||||
"wecomInvalidState": "企业微信登录状态无效",
|
||||
"wecomStateExpired": "企业微信登录会话已过期,请重试。",
|
||||
"wecomBindRequired": "当前企业微信账号未绑定本地用户,请联系管理员。",
|
||||
"wecomAccountDisabled": "账号已禁用,请联系管理员。",
|
||||
"wecomLoginFailed": "企业微信登录失败",
|
||||
"wecomMatchAmbiguous": "该企业微信账号匹配到多个本地账号,请联系管理员处理。",
|
||||
"wecomMatchAttrMissing": "企业微信缺少必要匹配字段,请联系管理员。",
|
||||
"wecomRetry": "重新发起企业微信登录",
|
||||
"wecomTechnicalInfo": "技术信息:{detail}",
|
||||
"wecomBindPromptTitle": "首次登录请校验并绑定本站账号",
|
||||
"wecomBindPromptDesc": "当前企业微信身份为 {name}。请输入一个允许的字段,用来绑定你已有的本站账号。",
|
||||
"wecomBindField": "校验字段",
|
||||
"wecomBindValue": "校验值",
|
||||
"wecomBindValuePlaceholder": "请输入你的{field}",
|
||||
"wecomBindPromptHint": "输入值必须和本站已有账号完全匹配。绑定成功后,当前企业微信账号会自动写回该用户表。",
|
||||
"wecomBindSubmit": "校验并登录",
|
||||
"wecomBindInputNotFound": "没有找到与你输入内容匹配的本站账号。",
|
||||
"wecomBindInputAmbiguous": "你输入的内容匹配到了多个本站账号,请联系管理员处理。",
|
||||
"wecomBindSessionExpired": "本次企业微信绑定会话已过期,请重新发起企业微信登录。",
|
||||
"wecomBindConflict": "当前企业微信账号已绑定到其他本站账号。",
|
||||
"wecomBindFieldNotAllowed": "当前选择的校验字段不被允许。",
|
||||
"wecomBindValueRequired": "请输入校验值。",
|
||||
"wecomFieldLabels": {
|
||||
"employee_id": "工号",
|
||||
"mobile": "手机号",
|
||||
"email": "邮箱",
|
||||
"match_rules": "匹配规则"
|
||||
},
|
||||
"wecomRuleJoin": {
|
||||
"and": "且",
|
||||
"or": "或"
|
||||
},
|
||||
"wecomFieldGuides": {
|
||||
"employee_id": "请管理员检查“工号来源字段”配置,并确认该成员在企业微信里能返回工号。",
|
||||
"mobile": "请管理员在企业微信通讯录中补齐该成员手机号,或调整匹配规则,不再强依赖手机号。",
|
||||
"email": "请管理员在企业微信通讯录中维护该成员邮箱,或调整匹配规则。",
|
||||
"default": "请管理员检查企业微信通讯录字段是否齐全,以及当前匹配规则是否合理。"
|
||||
},
|
||||
"wecomDialogTitles": {
|
||||
"matchAttrMissing": "企业微信资料不完整",
|
||||
"matchAmbiguous": "匹配到了多个本站账号",
|
||||
"bindRequired": "未找到可绑定的本站账号",
|
||||
"bindInputRequired": "首次绑定前需要人工校验",
|
||||
"bindConflict": "该企业微信账号已绑定到别的账号",
|
||||
"notInScope": "当前成员未被该应用授权",
|
||||
"stateExpired": "企业微信登录已过期",
|
||||
"accountDisabled": "本地账号已被禁用",
|
||||
"loginFailed": "企业微信登录失败"
|
||||
},
|
||||
"wecomDialogSummaries": {
|
||||
"matchAttrMissing": "企业微信没有返回“{field}”,所以系统无法按当前规则自动匹配你的本站账号。",
|
||||
"matchAmbiguous": "当前企业微信账号匹配到了多个本站账号,系统无法自动判断该登录哪一个。",
|
||||
"matchAmbiguousWithCount": "当前企业微信账号匹配到了 {count} 个本站账号,系统无法自动判断该登录哪一个。",
|
||||
"bindRequired": "企业微信侧认证已经成功,但本站没有找到符合当前规则的账号。",
|
||||
"bindInputRequired": "企业微信侧认证已经成功,请先输入一个本站字段完成首次绑定。",
|
||||
"bindConflict": "当前企业微信账号已经绑定到其他本站账号。",
|
||||
"notInScope": "当前成员不在企业微信应用可见范围内,或不是本企业成员。"
|
||||
},
|
||||
"wecomDialogDetails": {
|
||||
"currentRules": "当前匹配规则:{rules}",
|
||||
"bindFallback": "如果你已经有本站账号,可以请管理员先手动绑定当前企业微信账号。",
|
||||
"ambiguousAction": "请管理员清理重复的工号、手机号或邮箱数据,或者收紧匹配规则。",
|
||||
"bindRequiredAction": "请管理员先创建或绑定本站账号,或者开启自动创建用户。",
|
||||
"bindInputRequiredAction": "下一步请输入你的工号、手机号或邮箱中的一个,校验成功后就会把当前企业微信账号绑定到已有本站账号。",
|
||||
"bindConflictAction": "请管理员先解除旧绑定,再重新绑定当前企业微信账号。",
|
||||
"notInScopeAction": "请管理员到企业微信后台,把该成员或其所在部门加入该应用的可见范围。",
|
||||
"retryLogin": "请重新发起一次企业微信登录。",
|
||||
"contactAdmin": "如需帮助,请联系管理员。"
|
||||
}
|
||||
},
|
||||
"failed": "登录失败",
|
||||
"inputError": "请输入用户名和密码",
|
||||
"usernameRequired": "用户名不能为空",
|
||||
"usernameRequiredHint": "请输入用户名",
|
||||
"passwordRequired": "密码不能为空",
|
||||
"passwordRequiredHint": "请输入密码",
|
||||
"loginRequired": "请先登录",
|
||||
"sessionExpired": "登录已失效",
|
||||
"sessionExpiredHint": "请重新登录后继续使用。",
|
||||
"requestFailed": "登录请求失败",
|
||||
"forgotPassword": "忘记密码?",
|
||||
"newPassword": "新密码",
|
||||
"passwordResetSuccess": "密码重置成功,请重新登录。",
|
||||
"featuredAgents": "推荐 AI 应用",
|
||||
"pleaseLoginFirst": "请先登录以使用此应用。",
|
||||
"userNotFound": "用户不存在",
|
||||
"incorrectPassword": "密码错误",
|
||||
"accountDisabled": "账号已禁用",
|
||||
"dbConnectionFailed": "数据库连接失败,请检查数据库服务是否运行。",
|
||||
"internalError": "服务器内部错误,请稍后重试。",
|
||||
"rememberMe": "记住我",
|
||||
"forgotPasswordDesc": "输入工号和用户名,重置链接将发送到您的企业微信",
|
||||
"findPassword": "找回密码",
|
||||
"employeeIdRequired": "请输入工号",
|
||||
"passwordResetWecomSent": "若账号存在且已绑定企业微信,重置链接已发送到您的企业微信。",
|
||||
"passwordResetEmailSent": "若账号存在,重置链接已发送到您的邮箱。",
|
||||
"passwordResetRequestFailed": "请求密码重置失败",
|
||||
"passwordResetRateLimited": "操作过于频繁,请 {minutes} 分钟后再试",
|
||||
"announcements": "公告",
|
||||
"casdoorLogin": "Casdoor 登录",
|
||||
"casdoorErrors": {
|
||||
"invalidCredentials": "用户名或密码错误",
|
||||
"codeExpired": "登录会话已过期,请重新登录",
|
||||
"stateExpired": "登录会话已过期,请重试",
|
||||
"accessDenied": "登录已取消或被拒绝",
|
||||
"configError": "认证服务暂不可用,请联系管理员",
|
||||
"authFailed": "登录失败,请稍后重试",
|
||||
"passwordPolicy": "新密码不符合安全要求",
|
||||
"setPasswordFailed": "修改密码失败,请稍后重试或联系管理员",
|
||||
"incorrectCurrentPassword": "原:当前密码不正确,新:您输入的原密码有误,请重新输入",
|
||||
"passwordUnchanged": "新密码不能与当前密码相同",
|
||||
"userNotInIdp": "您的账号尚未在统一认证系统中开通,请联系管理员同步账号后再修改密码。"
|
||||
"landing": {
|
||||
"hero": {
|
||||
"prefix": "和信精密",
|
||||
"highlight": "AI智能体 应用平台",
|
||||
"subtitle": "AI的世界,期望让你开心工作,快乐生活。"
|
||||
},
|
||||
"agent": {
|
||||
"role": "AI 助手"
|
||||
}
|
||||
},
|
||||
"casdoorDialogTitles": {
|
||||
"userNotFound": "未匹配到本地账号",
|
||||
"userNotInIdp": "认证系统中无此账号",
|
||||
"accountDisabled": "账号已禁用",
|
||||
"sessionExpired": "登录会话已过期",
|
||||
"configError": "认证服务异常",
|
||||
"accessDenied": "登录未完成",
|
||||
"loginFailed": "登录失败"
|
||||
"register": {
|
||||
"title": "注册新账号",
|
||||
"username": "用户名",
|
||||
"password": "密码",
|
||||
"email": "邮箱",
|
||||
"cancel": "取消",
|
||||
"submit": "提交注册",
|
||||
"success": "注册申请已提交,请等待管理员审批",
|
||||
"failed": "注册失败",
|
||||
"inputError": "请输入用户名和密码",
|
||||
"requestFailed": "请求失败",
|
||||
"fields": {
|
||||
"realName": "真实姓名",
|
||||
"employeeId": "工号",
|
||||
"phone": "手机号"
|
||||
},
|
||||
"emailRequired": "请输入邮箱"
|
||||
},
|
||||
"casdoorDialogDetails": {
|
||||
"contactAdmin": "若问题持续出现,请联系管理员处理。",
|
||||
"retryLogin": "请关闭此窗口后重新登录。"
|
||||
},
|
||||
"wecomLogin": "企业微信登录",
|
||||
"wecomComingSoon": "企业微信登录功能正在开发中,敬请期待",
|
||||
"wecomConnecting": "正在连接企业微信...",
|
||||
"wecomStartFailed": "启动企业微信登录失败",
|
||||
"wecomInvalidState": "企业微信登录状态无效",
|
||||
"wecomStateExpired": "企业微信登录会话已过期,请重试。",
|
||||
"wecomBindRequired": "当前企业微信账号未绑定本地用户,请联系管理员。",
|
||||
"wecomAccountDisabled": "账号已禁用,请联系管理员。",
|
||||
"wecomLoginFailed": "企业微信登录失败",
|
||||
"wecomMatchAmbiguous": "该企业微信账号匹配到多个本地账号,请联系管理员处理。",
|
||||
"wecomMatchAttrMissing": "企业微信缺少必要匹配字段,请联系管理员。",
|
||||
"wecomRetry": "重新发起企业微信登录",
|
||||
"wecomTechnicalInfo": "技术信息:{detail}",
|
||||
"wecomBindPromptTitle": "首次登录请校验并绑定本站账号",
|
||||
"wecomBindPromptDesc": "当前企业微信身份为 {name}。请输入一个允许的字段,用来绑定你已有的本站账号。",
|
||||
"wecomBindField": "校验字段",
|
||||
"wecomBindValue": "校验值",
|
||||
"wecomBindValuePlaceholder": "请输入你的{field}",
|
||||
"wecomBindPromptHint": "输入值必须和本站已有账号完全匹配。绑定成功后,当前企业微信账号会自动写回该用户表。",
|
||||
"wecomBindSubmit": "校验并登录",
|
||||
"wecomBindInputNotFound": "没有找到与你输入内容匹配的本站账号。",
|
||||
"wecomBindInputAmbiguous": "你输入的内容匹配到了多个本站账号,请联系管理员处理。",
|
||||
"wecomBindSessionExpired": "本次企业微信绑定会话已过期,请重新发起企业微信登录。",
|
||||
"wecomBindConflict": "当前企业微信账号已绑定到其他本站账号。",
|
||||
"wecomBindFieldNotAllowed": "当前选择的校验字段不被允许。",
|
||||
"wecomBindValueRequired": "请输入校验值。",
|
||||
"wecomFieldLabels": {
|
||||
"employee_id": "工号",
|
||||
"mobile": "手机号",
|
||||
"email": "邮箱",
|
||||
"match_rules": "匹配规则"
|
||||
},
|
||||
"wecomRuleJoin": {
|
||||
"and": "且",
|
||||
"or": "或"
|
||||
},
|
||||
"wecomFieldGuides": {
|
||||
"employee_id": "请管理员检查“工号来源字段”配置,并确认该成员在企业微信里能返回工号。",
|
||||
"mobile": "请管理员在企业微信通讯录中补齐该成员手机号,或调整匹配规则,不再强依赖手机号。",
|
||||
"email": "请管理员在企业微信通讯录中维护该成员邮箱,或调整匹配规则。",
|
||||
"default": "请管理员检查企业微信通讯录字段是否齐全,以及当前匹配规则是否合理。"
|
||||
},
|
||||
"wecomDialogTitles": {
|
||||
"matchAttrMissing": "企业微信资料不完整",
|
||||
"matchAmbiguous": "匹配到了多个本站账号",
|
||||
"bindRequired": "未找到可绑定的本站账号",
|
||||
"bindInputRequired": "首次绑定前需要人工校验",
|
||||
"bindConflict": "该企业微信账号已绑定到别的账号",
|
||||
"notInScope": "当前成员未被该应用授权",
|
||||
"stateExpired": "企业微信登录已过期",
|
||||
"accountDisabled": "本地账号已被禁用",
|
||||
"loginFailed": "企业微信登录失败"
|
||||
},
|
||||
"wecomDialogSummaries": {
|
||||
"matchAttrMissing": "企业微信没有返回“{field}”,所以系统无法按当前规则自动匹配你的本站账号。",
|
||||
"matchAmbiguous": "当前企业微信账号匹配到了多个本站账号,系统无法自动判断该登录哪一个。",
|
||||
"matchAmbiguousWithCount": "当前企业微信账号匹配到了 {count} 个本站账号,系统无法自动判断该登录哪一个。",
|
||||
"bindRequired": "企业微信侧认证已经成功,但本站没有找到符合当前规则的账号。",
|
||||
"bindInputRequired": "企业微信侧认证已经成功,请先输入一个本站字段完成首次绑定。",
|
||||
"bindConflict": "当前企业微信账号已经绑定到其他本站账号。",
|
||||
"notInScope": "当前成员不在企业微信应用可见范围内,或不是本企业成员。"
|
||||
},
|
||||
"wecomDialogDetails": {
|
||||
"currentRules": "当前匹配规则:{rules}",
|
||||
"bindFallback": "如果你已经有本站账号,可以请管理员先手动绑定当前企业微信账号。",
|
||||
"ambiguousAction": "请管理员清理重复的工号、手机号或邮箱数据,或者收紧匹配规则。",
|
||||
"bindRequiredAction": "请管理员先创建或绑定本站账号,或者开启自动创建用户。",
|
||||
"bindInputRequiredAction": "下一步请输入你的工号、手机号或邮箱中的一个,校验成功后就会把当前企业微信账号绑定到已有本站账号。",
|
||||
"bindConflictAction": "请管理员先解除旧绑定,再重新绑定当前企业微信账号。",
|
||||
"notInScopeAction": "请管理员到企业微信后台,把该成员或其所在部门加入该应用的可见范围。",
|
||||
"retryLogin": "请重新发起一次企业微信登录。",
|
||||
"contactAdmin": "如需帮助,请联系管理员。"
|
||||
"resetPassword": {
|
||||
"title": "重置密码",
|
||||
"desc": "请在下方输入新密码",
|
||||
"newPassword": "新密码",
|
||||
"confirmPassword": "确认密码",
|
||||
"newPasswordPlaceholder": "请输入新密码",
|
||||
"confirmPasswordPlaceholder": "请再次输入新密码",
|
||||
"submit": "重置密码",
|
||||
"submitting": "正在重置...",
|
||||
"backToLogin": "返回登录",
|
||||
"fillAllFields": "请填写所有字段",
|
||||
"passwordMismatch": "两次输入的密码不一致",
|
||||
"successRedirect": "密码重置成功,即将跳转到登录页...",
|
||||
"failed": "密码重置失败",
|
||||
"invalidLink": "重置链接无效或缺少 token,请重新申请找回密码",
|
||||
"tokenInvalid": "链接已失效或已过期(可能已使用过或重新申请过),请回到登录页重新发起找回密码"
|
||||
}
|
||||
},
|
||||
"landing": {
|
||||
"hero": {
|
||||
"prefix": "和信精密",
|
||||
"highlight": "AI智能体 应用平台",
|
||||
"subtitle": "AI的世界,期望让你开心工作,快乐生活。"
|
||||
},
|
||||
"agent": {
|
||||
"role": "AI 助手"
|
||||
}
|
||||
},
|
||||
"register": {
|
||||
"title": "注册新账号",
|
||||
"username": "用户名",
|
||||
"password": "密码",
|
||||
"email": "邮箱",
|
||||
"cancel": "取消",
|
||||
"submit": "提交注册",
|
||||
"success": "注册申请已提交,请等待管理员审批",
|
||||
"failed": "注册失败",
|
||||
"inputError": "请输入用户名和密码",
|
||||
"requestFailed": "请求失败",
|
||||
"fields": {
|
||||
"realName": "真实姓名",
|
||||
"employeeId": "工号",
|
||||
"phone": "手机号"
|
||||
}
|
||||
},
|
||||
"resetPassword": {
|
||||
"title": "重置密码",
|
||||
"desc": "请在下方输入新密码",
|
||||
"newPassword": "新密码",
|
||||
"confirmPassword": "确认密码",
|
||||
"newPasswordPlaceholder": "请输入新密码",
|
||||
"confirmPasswordPlaceholder": "请再次输入新密码",
|
||||
"submit": "重置密码",
|
||||
"submitting": "正在重置...",
|
||||
"backToLogin": "返回登录",
|
||||
"fillAllFields": "请填写所有字段",
|
||||
"passwordMismatch": "两次输入的密码不一致",
|
||||
"successRedirect": "密码重置成功,即将跳转到登录页...",
|
||||
"failed": "密码重置失败",
|
||||
"invalidLink": "重置链接无效或缺少 token,请重新申请找回密码",
|
||||
"tokenInvalid": "链接已失效或已过期(可能已使用过或重新申请过),请回到登录页重新发起找回密码"
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,21 @@
|
||||
{
|
||||
"generic": "请求失败。",
|
||||
"codes": {
|
||||
"ORDER_DELIVERY_REPLY.FORBIDDEN": "无订单交期回复查看权限,请联系管理员开通。",
|
||||
"ORDER_DELIVERY_REPLY.LINE_NOT_FOUND": "订单行不存在或已不在同步范围。",
|
||||
"ORDER_DELIVERY_REPLY.ADMIN_REQUIRED": "仅平台管理员可按部门批量发放权限。",
|
||||
"ORDER_DELIVERY_REPLY.GRANT_DEPARTMENT_REQUIRED": "请填写要发放权限的部门。",
|
||||
"ORDER_DELIVERY_REPLY.GRANT_PERMISSION_INVALID": "权限类型须为 manage 或 access。",
|
||||
"ORDER_DELIVERY_REPLY.BATCH_REPLY_EMPTY": "联合回复至少包含一行,且单次不超过 200 行。",
|
||||
"ORDER_DELIVERY_REPLY.NOTIFY_BATCH_EMPTY": "批量通知至少包含一行,且单次不超过 200 行。",
|
||||
"ORDER_DELIVERY_REPLY.SALESPERSON_UNMAPPED": "订单业务员未关联系统账号或未绑定企微,无法发送通知。",
|
||||
"ORDER_DELIVERY_REPLY.NOTIFY_FAILED": "企微通知发送失败,该行未锁定,请稍后重试。",
|
||||
"ORDER_DELIVERY_REPLY.LINE_LOCKED": "该订单行交期已通知锁定,不能修改批次。",
|
||||
"ORDER_DELIVERY_REPLY.MANAGE_FORBIDDEN": "无订单交期回复操作权限,仅生管可保存或通知。",
|
||||
"ORDER_DELIVERY_REPLY.BATCHES_REQUIRED": "请至少填写一条交期批次。",
|
||||
"ORDER_DELIVERY_REPLY.BATCH_COUNT_EXCEEDED": "单行批次数量超过上限。",
|
||||
"ORDER_DELIVERY_REPLY.BATCH_INVALID": "批次格式不合法,请检查交期、数量或备注。",
|
||||
"ORDER_DELIVERY_REPLY.BATCH_QTY_TOTAL_MISMATCH": "各批次数量合计必须等于订单数量,请调整后重新保存。",
|
||||
"SHIPPING.NOTICE_ODM_CHOICE_INVALID": "所选 ODM ID 不在当前可行候选内,请重新选择。",
|
||||
"SHIPPING.FULFILLMENT_POLICY_INVALID": "货代履约策略或字段能力绑定无效。",
|
||||
"SHIPPING.FULFILLMENT_POLICY_NOT_FOUND": "未找到货代履约策略。",
|
||||
|
||||
@@ -113,7 +113,8 @@
|
||||
"contractPayment": "合同付款预警",
|
||||
"contractPaymentLedger": "合同台账",
|
||||
"contractPaymentReview": "待确认合同",
|
||||
"contractPaymentWeeklyBatches": "周汇总批次"
|
||||
"contractPaymentWeeklyBatches": "周汇总批次",
|
||||
"orderDeliveryReply": "订单交期回复"
|
||||
},
|
||||
"kb": {
|
||||
"accessDenied": "需要管理员权限才能访问知识库。"
|
||||
@@ -202,7 +203,21 @@
|
||||
"resend": "重发企微",
|
||||
"failedUnits": "失败的收料单元",
|
||||
"retry": "填写原因后重试",
|
||||
"retryReasonPrompt": "请填写重试 {target} 的原因"
|
||||
"retryReasonPrompt": "请填写重试 {target} 的原因",
|
||||
"batch": {
|
||||
"selectAll": "全选当前页通知单",
|
||||
"selected": "已选 {count} 张",
|
||||
"download": "批量下载 Excel",
|
||||
"confirm": "批量确认已上传",
|
||||
"rpa": "批量启动 RPA",
|
||||
"downloadStarted": "已开始下载所选发货通知 Excel",
|
||||
"success": "{action}:已处理 {count} 张通知单",
|
||||
"partialResult": "{action}:成功 {accepted} 张,阻断 {blocked} 张,请查看刷新后的通知状态。",
|
||||
"lines": "项次",
|
||||
"parts": "料号",
|
||||
"quantities": "本次发货 / 可用库存",
|
||||
"uploadStatus": "货代状态"
|
||||
}
|
||||
},
|
||||
"shippingNotice": {
|
||||
"title": "货代发货通知",
|
||||
@@ -968,5 +983,100 @@
|
||||
"notifyExcel": "Excel",
|
||||
"downloadExcel": "下载 Excel",
|
||||
"downloadExcelFailed": "下载 Excel 失败"
|
||||
},
|
||||
"orderDeliveryReply": {
|
||||
"deepLinkLocated": "已定位到通知对应的订单行 {order}:{item}",
|
||||
"search": "查询",
|
||||
"reset": "重置",
|
||||
"saving": "保存中…",
|
||||
"syncNow": "手动刷新",
|
||||
"syncing": "同步中…",
|
||||
"syncNever": "尚未同步",
|
||||
"syncAt": "最近同步:{time}",
|
||||
"syncRunning": "同步进行中…",
|
||||
"syncFailedAt": "上次同步失败({time}),列表为上次成功快照",
|
||||
"syncDone": "同步完成,共 {count} 行",
|
||||
"syncSkipped": "已有同步正在进行,请稍后再试",
|
||||
"syncFailedTitle": "同步失败,已保留上次快照",
|
||||
"filterKeyword": "关键词(订单 / 产品 / 客户 / 业务员 / 回复人员)",
|
||||
"filterKeywordPh": "订单单号、产品编号、品名、客户料号、客户编号、业务员、交期回复人员均可搜索",
|
||||
"filterOrderDate": "订单日期",
|
||||
"filterStatus": "交期回复状态",
|
||||
"statusAll": "全部",
|
||||
"statusReplied": "已回复",
|
||||
"statusNotFully": "未完全回复",
|
||||
"statusNotReplied": "未回复",
|
||||
"statusPartial": "部分回复",
|
||||
"totalCount": "共 {count} 条产品行",
|
||||
"selectAll": "全选(本页)",
|
||||
"selectedCount": "已勾选 {count} 行",
|
||||
"batchReply": "+ 联合回复交期",
|
||||
"batchNotify": "批量通知",
|
||||
"toolbarHint": "联合回复只保存批次;点「批量通知」才发送并锁定。",
|
||||
"colOrderLine": "订单单号:项次",
|
||||
"colOrderDate": "订单日期",
|
||||
"colCustomer": "客户编号",
|
||||
"colSalesperson": "业务员",
|
||||
"colDept": "部门",
|
||||
"colCustomerPo": "客户订单",
|
||||
"colPartNo": "产品编号",
|
||||
"colPartName": "品名",
|
||||
"colSpec": "规格",
|
||||
"colCustomerPartNo": "客户产品编号",
|
||||
"colAgreedDate": "约定交货日",
|
||||
"colUnit": "单位",
|
||||
"colQty": "数量",
|
||||
"colDelivered": "已交数量",
|
||||
"colUndelivered": "未交数量",
|
||||
"colStatus": "交期回复状态",
|
||||
"colReply": "交期回复",
|
||||
"colNotify": "通知业务部门",
|
||||
"colReplyPerson": "交期回复人员",
|
||||
"batchCount": "{count} 批",
|
||||
"repliedOf": "已回复 {replied}/{remain}",
|
||||
"overTag": "超",
|
||||
"collapse": "收起 ▲",
|
||||
"expand": "+{count} 批 ▾",
|
||||
"lockedTag": "交期已锁定",
|
||||
"replyAction": "回复交期",
|
||||
"editReplyAction": "修改回复",
|
||||
"notifiedTag": "已通知 {name}",
|
||||
"replyFirst": "请先回复交期",
|
||||
"notifyAction": "发送通知业务部门",
|
||||
"pendingNotify": "待通知后记录",
|
||||
"empty": "没有符合条件的订单行",
|
||||
"pageInfo": "第 {page} / {pages} 页",
|
||||
"modalTitleSingle": "回复交期 · {order} / 项次 {item}",
|
||||
"modalTitleBatch": "联合回复交期({count} 行)",
|
||||
"quickDate": "快速统一交期",
|
||||
"applyQuickDate": "应用到全部",
|
||||
"modalHint": "可填 1 个交期,或点「增加批次」拆成多个「交期+数量」;各批次数量合计须等于订单数量。",
|
||||
"itemLabel": "项次 {item}",
|
||||
"qtyPh": "数量",
|
||||
"remarkPh": "备注(可选)",
|
||||
"removeBatch": "删除本行批次",
|
||||
"addBatch": "+ 增加拆分批次(交期 + 数量 + 备注)",
|
||||
"saveReply": "保存回复",
|
||||
"noValidBatches": "请至少为一行填写交期和数量",
|
||||
"saveSingleDone": "交期批次已保存(未通知,可继续修改)",
|
||||
"saveBatchDone": "已保存 {ok} 行交期批次(未通知)",
|
||||
"saveBatchPartial": "保存完成:成功 {ok} 行,失败 {fail} 行:{detail}",
|
||||
"saveFailedTitle": "保存失败",
|
||||
"loadFailed": "加载订单行失败",
|
||||
"notifyConfirm": "确认向业务员「{salesperson}」发送?\n您有订单号:项次{order}:{item}的订单需要填写/确认/查看交期。\n发送后交期将锁定。",
|
||||
"notifyDone": "已通知并锁定:{order}:{item}",
|
||||
"notifyBatchConfirm": "将向 {count} 行对应业务员发送交期通知,发送成功的行将锁定。继续?",
|
||||
"notifyPartial": "部分成功:成功 {ok} 行,失败 {fail} 行,跳过 {skip} 行。失败:{detail}",
|
||||
"notifyAllFailed": "全部失败({fail} 行):{detail}",
|
||||
"notifyBatchDone": "已通知并锁定 {ok} 行,跳过 {skip} 行",
|
||||
"notifyFailedTitle": "通知发送失败,该行未锁定",
|
||||
"entryHint": "查单 → 填交期 → 通知业务员",
|
||||
"notNotified": "未通知",
|
||||
"orderQtyLabel": "订单数量:{qty} {unit}",
|
||||
"batchMissingDate": "第 {batches} 批未填交期",
|
||||
"batchMissingQty": "第 {batches} 批未填数量",
|
||||
"qtyTotalMismatchLine": "各批次合计 {total},须等于订单数量 {qty}",
|
||||
"saveBlocked": "以下行填写未完成,无法保存:{detail}",
|
||||
"batchDuplicateDate": "同一订单单号:项次的不同批次交期时间不能相同(重复:{dates})"
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,8 @@
|
||||
"platformApps": "平台應用說明",
|
||||
"procurementContract": "採購合同審查",
|
||||
"trainingConfig": "培訓配置",
|
||||
"integrationConnector": "整合連接器"
|
||||
"integrationConnector": "整合連接器",
|
||||
"contractPayment": "合同付款预警"
|
||||
},
|
||||
"shippingOrderExtractionRuns": {
|
||||
"eyebrow": "唯讀執行診斷",
|
||||
@@ -1213,6 +1214,10 @@
|
||||
"trainingLeanTeamManage": "精益培訓班組管理",
|
||||
"contractPaymentAccess": "合約付款預警存取",
|
||||
"contractPaymentAccessHint": "勾選後可進入工作臺合約付款預警(臺帳、待確認、週彙總)。同步 OA、掃描預警與發送預警僅管理員可用。",
|
||||
"orderDeliveryReplyManage": "訂單交期回覆操作",
|
||||
"orderDeliveryReplyManageHint": "勾選後可回覆交期批次、發送/批量通知業務員並手動同步 ERP 訂單(生管)。",
|
||||
"orderDeliveryReplyAccess": "訂單交期回覆查看",
|
||||
"orderDeliveryReplyAccessHint": "勾選後可唯讀查看已同步訂單與回覆結果(業務人員);回覆與通知需另勾「操作」權限。",
|
||||
"password": "密碼",
|
||||
"passwordHint": "(留空表示不修改)",
|
||||
"noAgents": "暫無可用應用"
|
||||
@@ -1246,11 +1251,13 @@
|
||||
"name": "名稱",
|
||||
"code": "編碼",
|
||||
"company": "公司",
|
||||
"actions": "操作"
|
||||
"actions": "操作",
|
||||
"members": "Members"
|
||||
},
|
||||
"actions": {
|
||||
"edit": "編輯",
|
||||
"delete": "刪除"
|
||||
"delete": "刪除",
|
||||
"viewMembers": "View department members"
|
||||
},
|
||||
"fields": {
|
||||
"name": "名稱",
|
||||
@@ -1265,6 +1272,11 @@
|
||||
"confirmDelete": "確定刪除該部門嗎?",
|
||||
"msg": {
|
||||
"nameRequired": "部門名稱必填"
|
||||
},
|
||||
"members": {
|
||||
"title": "{name} Members",
|
||||
"count": "{count} members",
|
||||
"empty": "No members"
|
||||
}
|
||||
},
|
||||
"agent": {
|
||||
@@ -1797,12 +1809,13 @@
|
||||
"firstLoginInputFields": "首次登入可輸入字段",
|
||||
"employeeIdSource": "工號來源字段",
|
||||
"mobileNormalize": "手機號歸一化",
|
||||
"callbackToken": "回調 Token",
|
||||
"callbackToken": "回呼Token",
|
||||
"encodingAesKey": "EncodingAESKey",
|
||||
"callbackUrl": "回調URL",
|
||||
"callbackUrl": "回呼URL",
|
||||
"homepageUrl": "應用主頁URL",
|
||||
"trustedDomain": "可信域名",
|
||||
"publicBaseUrl": "外網 HTTPS 基地址"
|
||||
"trustedDomain": "可信任網域",
|
||||
"publicBaseUrl": "外網 HTTPS 基地址",
|
||||
"userId": "User ID (user_id)"
|
||||
},
|
||||
"bindModes": {
|
||||
"match_rules": "按規則自動匹配",
|
||||
@@ -1915,8 +1928,23 @@
|
||||
"filterName": "篩選 姓名/用戶名",
|
||||
"filterDept": "篩選 部門",
|
||||
"allRoles": "所有角色",
|
||||
"views": { "apps": "按應用查看", "members": "按成員查看" },
|
||||
"appHeaders": { "app": "應用", "type": "類型", "authorized": "已授權人數", "actions": "操作", "viewMembers": "查看成員", "accessHint": "點擊查看成員權限", "memberHint": "可新增或取消此應用的存取權限", "memberSearch": "搜尋姓名、用戶名、工號或部門", "addMember": "新增權限", "removeMember": "取消權限", "noMembers": "沒有符合的成員" },
|
||||
"views": {
|
||||
"apps": "按應用查看",
|
||||
"members": "按成員查看"
|
||||
},
|
||||
"appHeaders": {
|
||||
"app": "應用",
|
||||
"type": "類型",
|
||||
"authorized": "已授權人數",
|
||||
"actions": "操作",
|
||||
"viewMembers": "查看成員",
|
||||
"accessHint": "點擊查看成員權限",
|
||||
"memberHint": "可新增或取消此應用的存取權限",
|
||||
"memberSearch": "搜尋姓名、用戶名、工號或部門",
|
||||
"addMember": "新增權限",
|
||||
"removeMember": "取消權限",
|
||||
"noMembers": "沒有符合的成員"
|
||||
},
|
||||
"headers": {
|
||||
"user": "用戶",
|
||||
"realName": "真實姓名",
|
||||
@@ -2153,7 +2181,7 @@
|
||||
"tokens_completion": "補全 Token",
|
||||
"total_tokens": "總 Token",
|
||||
"latency_ms": "延遲(毫秒)",
|
||||
"latency": "延遲",
|
||||
"latency": "耗時(毫秒)",
|
||||
"cost": "費用",
|
||||
"ip": "IP",
|
||||
"user_agent": "用戶代理",
|
||||
@@ -2169,13 +2197,15 @@
|
||||
"reset_token_expiry": "重置令牌過期時間",
|
||||
"risk_status": "風險狀態",
|
||||
"risk_score": "風險分",
|
||||
"latency": "耗時(毫秒)",
|
||||
"is_empty_answer": "空回答",
|
||||
"is_system_failure": "系統失敗",
|
||||
"feedback_score": "評分",
|
||||
"feedback_comment": "評分備註",
|
||||
"negative_feedback_count": "負面反饋數",
|
||||
"actions": "操作"
|
||||
"actions": "操作",
|
||||
"feedback_module": "Feedback Module",
|
||||
"feedback_type": "Feedback Type",
|
||||
"source_page": "Source Page"
|
||||
},
|
||||
"tables": {
|
||||
"users": "用戶",
|
||||
@@ -2186,7 +2216,8 @@
|
||||
"agents": "應用運營",
|
||||
"ops_overview": "營運總覽",
|
||||
"issue_analysis": "問題分析",
|
||||
"usage_analysis": "使用分析"
|
||||
"usage_analysis": "使用分析",
|
||||
"permission_requests": "權限申請"
|
||||
},
|
||||
"usageIntro": "查看 AI 應用呼叫趨勢、活躍使用者、低使用應用與異常高峰。",
|
||||
"usageTotalSessions": "對話總量",
|
||||
@@ -2376,6 +2407,32 @@
|
||||
"topApp": "優先優化應用",
|
||||
"topAppHint": "需要關注信號占比 {ratio}%"
|
||||
}
|
||||
},
|
||||
"usageRangeLabel": "統計範圍",
|
||||
"usageRanges": {
|
||||
"7d": "近一週",
|
||||
"30d": "近一月",
|
||||
"90d": "近三月",
|
||||
"180d": "近半年",
|
||||
"365d": "近一年"
|
||||
},
|
||||
"feedbackValues": {
|
||||
"types": {
|
||||
"feature_suggestion": "Feature Suggestion",
|
||||
"issue_feedback": "Issue Feedback",
|
||||
"experience_optimization": "Experience Optimization"
|
||||
},
|
||||
"modules": {
|
||||
"knowledge_base": "Knowledge Base",
|
||||
"general": "General",
|
||||
"workflow": "Workflow",
|
||||
"account_permission": "Account & Permissions"
|
||||
},
|
||||
"pages": {
|
||||
"workspace": "Workspace",
|
||||
"chat": "Chat",
|
||||
"unknown": "Unknown"
|
||||
}
|
||||
}
|
||||
},
|
||||
"batchEdit": {
|
||||
@@ -2522,7 +2579,35 @@
|
||||
"voucherCheckNotifyMissing": "缺資料通知",
|
||||
"voucherCheckNotifyMissingHint": "總開關。缺件接收人請到 Chat「立帳憑證 → 通知設定」依檔案類型設定;排程選人只用於技術失敗告警。",
|
||||
"voucherCheckNotifyFailure": "失敗告警",
|
||||
"voucherCheckNotifyFailureHint": "技術失敗會發給下方「選擇通知人員」。"
|
||||
"voucherCheckNotifyFailureHint": "技術失敗會發給下方「選擇通知人員」。",
|
||||
"editTitle": "Edit schedule",
|
||||
"createTitle": "Add schedule",
|
||||
"name": "Schedule name",
|
||||
"namePlaceholder": "e.g. RoHS auto review schedule",
|
||||
"owner": "Schedule owner",
|
||||
"noUsers": "No users available",
|
||||
"selectOwner": "Select an owner",
|
||||
"faqHotAggregate": "FAQ hot aggregate",
|
||||
"querying": "Querying...",
|
||||
"testQuery": "Test query",
|
||||
"expandConfig": "Expand config",
|
||||
"collapseConfig": "Collapse config",
|
||||
"dataSourceSection": "Data source config",
|
||||
"waitSeconds": "Wait time (seconds)",
|
||||
"noAgents": "No agents available",
|
||||
"agentDisabled": "Disabled",
|
||||
"minuteInterval": "Minute interval",
|
||||
"minuteOfHour": "Minute of hour",
|
||||
"weekday": "Weekday",
|
||||
"notifyEnabled": "Enable notifications",
|
||||
"selectNotifyUsers": "Select notification recipients...",
|
||||
"enableOnCreate": "Enable after creation",
|
||||
"cancel": "Cancel",
|
||||
"saving": "Saving...",
|
||||
"saveChanges": "Save changes",
|
||||
"createSchedule": "Create schedule",
|
||||
"dynamicParamsSearchPlaceholder": "搜尋選項(姓名/工號/部門)…",
|
||||
"dynamicParamsSearchNoMatch": "沒有符合的選項"
|
||||
},
|
||||
"status": {
|
||||
"all": "全部狀態",
|
||||
@@ -2559,7 +2644,25 @@
|
||||
"noKbGroupHint": "請先在排程編輯中啟用知識庫同步並選擇分組。",
|
||||
"kbSyncNoStatus": "已請求寫入知識庫,但未返回同步狀態,請檢查排程知識庫配置或後端日誌。",
|
||||
"baseFetchSqlReadonly": "基礎查詢 SQL (base_fetch_sql) — 唯讀",
|
||||
"limitRows": "限制行數 (limit)"
|
||||
"limitRows": "限制行數 (limit)",
|
||||
"title": "Test run — {name}",
|
||||
"subtitle": "Edit WHERE clause, limit rows, run quickly and inspect each step",
|
||||
"close": "Close",
|
||||
"running": "Running...",
|
||||
"start": "Start test run",
|
||||
"waitingHint": "Dify calls may take a while, please wait...",
|
||||
"total": "Total",
|
||||
"success": "Success",
|
||||
"failed": "Failed",
|
||||
"skipped": "Skipped",
|
||||
"limitSummary": "Limit {limit} rows | Dify Agent ID: {agentId}",
|
||||
"noAgent": "None",
|
||||
"stepLogs": "Step logs",
|
||||
"viewSql": "View execution SQL",
|
||||
"errors": "Errors ({count})",
|
||||
"queryResult": "Query result",
|
||||
"resultSummary": "{total} total, showing {showing}",
|
||||
"viewGeneratedSql": "View generated SQL"
|
||||
},
|
||||
"deleteDialogTitle": "刪除排程",
|
||||
"excelExportFailedHint": "庫存來源已成功,但排程 Excel 生成失敗",
|
||||
@@ -2577,8 +2680,19 @@
|
||||
"receiptRawZip": "原始收料",
|
||||
"columns": {
|
||||
"skippedCount": "跳過",
|
||||
"skippedCountReceipt": "無收料/跳過",
|
||||
"skippedCountInventory": "無庫存/跳過"
|
||||
"runNo": "Run ID",
|
||||
"startedAt": "Started at",
|
||||
"finishedAt": "Finished at",
|
||||
"status": "Status",
|
||||
"totalCount": "Processed",
|
||||
"successCount": "Success",
|
||||
"failedCount": "Failed",
|
||||
"excelExportFailedHint": "Inventory sources succeeded, but schedule Excel export failed",
|
||||
"wecomNotified": "WeCom notify",
|
||||
"detail": "Detail",
|
||||
"log": "Log",
|
||||
"skippedCountReceipt": "無收料/跳過",
|
||||
"skippedCountInventory": "無庫存/跳過"
|
||||
},
|
||||
"deleteConfirmMessage": "確認刪除排程「{name}」?",
|
||||
"msg": {
|
||||
@@ -2592,8 +2706,9 @@
|
||||
"runNowWaitTimeout": "等待執行完成逾時(約 15 分鐘),已停止自動重新整理,可手動查詢記錄",
|
||||
"downloadExcelFailed": "下載 Excel 失敗",
|
||||
"downloadInventoryRawZipFailed": "下載原始庫存包失敗",
|
||||
"downloadReceiptRawZipFailed": "下載原始收料包失敗",
|
||||
"deleteFailed": "刪除排程失敗"
|
||||
"deleteFailed": "刪除排程失敗",
|
||||
"testQueryFailed": "Test query failed",
|
||||
"downloadReceiptRawZipFailed": "下載原始收料包失敗"
|
||||
},
|
||||
"difySnapshot": {
|
||||
"title": "Dify 執行快照(審計)",
|
||||
@@ -2605,6 +2720,65 @@
|
||||
"notConfiguredUseDefault": "(未配置,使用 Dify 編排內預設提示詞)",
|
||||
"notEnabledTest": "本次測試未啟用 Dify",
|
||||
"notEnabledRun": "本次執行未啟用 Dify Agent"
|
||||
},
|
||||
"overviewTitle": "Schedule Management Overview",
|
||||
"workbenchTitle": "Schedule Management Workbench",
|
||||
"overviewSubtitle": "Click a schedule card to open the workbench.",
|
||||
"workbenchSubtitle": "Schedule list on the left, run records on the right.",
|
||||
"refresh": "Refresh schedules",
|
||||
"stats": {
|
||||
"total": "Total schedules",
|
||||
"enabled": "Enabled",
|
||||
"disabled": "Disabled",
|
||||
"running": "Running"
|
||||
},
|
||||
"sectionOverview": "Schedule Management Overview",
|
||||
"switchByCard": "Switch by card",
|
||||
"addTitle": "Add schedule",
|
||||
"addHint": "Click the button to fill in schedule fields in a dialog.",
|
||||
"addButton": "Add schedule",
|
||||
"emptyList": "No schedules yet. Create one first.",
|
||||
"loading": "Loading...",
|
||||
"enabled": "Enabled",
|
||||
"disabled": "Disabled",
|
||||
"scheduleNo": "No.",
|
||||
"config": "Config",
|
||||
"owner": "Owner",
|
||||
"lastRun": "Last run",
|
||||
"nextRun": "Next run",
|
||||
"nextRunDisabled": "Disabled",
|
||||
"nextRunPending": "Not computed (save or restart schedule)",
|
||||
"noSelection": "No schedule selected",
|
||||
"selectedHint": "Selected schedule · Last run {time}",
|
||||
"runBatches": "Run batches",
|
||||
"totalProcessed": "Total processed",
|
||||
"totalSuccess": "Total success",
|
||||
"totalFailed": "Total failed",
|
||||
"listTitle": "Schedule list",
|
||||
"recordsTitle": "{name} · Run records",
|
||||
"recordsSubtitle": "Run record details are shown below.",
|
||||
"noSelectionHint": "Select a schedule from the list on the left first.",
|
||||
"filterStart": "Start",
|
||||
"filterEnd": "End",
|
||||
"query": "Search",
|
||||
"reset": "Reset",
|
||||
"queryingRuns": "Loading records...",
|
||||
"noRunRecords": "No run records yet.",
|
||||
"runLogs": "Run logs",
|
||||
"stepsCount": "{count} steps",
|
||||
"viewDetail": "View details",
|
||||
"resizeColumn": "Drag to resize {label} column",
|
||||
"notified": "Notified",
|
||||
"notifyError": "Error",
|
||||
"download": "Download",
|
||||
"log": "Log",
|
||||
"actions": {
|
||||
"edit": "Edit",
|
||||
"start": "Start",
|
||||
"pause": "Pause",
|
||||
"run": "Run",
|
||||
"test": "Test",
|
||||
"delete": "Delete"
|
||||
}
|
||||
},
|
||||
"shippingIdentityRules": {
|
||||
@@ -4251,7 +4425,8 @@
|
||||
"rejected": "已駁回",
|
||||
"needs_review": "待複核"
|
||||
},
|
||||
"confirmRequiresNativePreview": "請先載入原生 PDF 預覽後再確認視覺綁定"
|
||||
"confirmRequiresNativePreview": "請先載入原生 PDF 預覽後再確認視覺綁定",
|
||||
"createBlockersTitle": "创建前阻断项"
|
||||
},
|
||||
"xfaAutoMark": {
|
||||
"title": "自動標記建議",
|
||||
@@ -5293,7 +5468,17 @@
|
||||
"trainingAgentRequired": "未找到員工培訓 Agent,無法建立影片資源",
|
||||
"videoUploaded": "培訓影片已上傳並加入配置資源",
|
||||
"videoUploadFailed": "培訓影片上傳失敗"
|
||||
}
|
||||
},
|
||||
"eyebrow": "培训运营中心",
|
||||
"pageHint": "配置变更将在保存后生效",
|
||||
"footerHint": "所有配置项均支持保存后继续调整",
|
||||
"stats": {
|
||||
"total": "配置总数",
|
||||
"published": "已发布",
|
||||
"resources": "当前资料",
|
||||
"levels": "已配置级别"
|
||||
},
|
||||
"questionBankTitle": "入职培训题库"
|
||||
},
|
||||
"integrationConnector": {
|
||||
"title": "整合連接器",
|
||||
|
||||
@@ -129,7 +129,17 @@
|
||||
"notInScopeAction": "請管理員到企業微信後台,把該成員或其所在部門加入該應用的可見範圍。",
|
||||
"retryLogin": "請重新發起一次企業微信登入。",
|
||||
"contactAdmin": "如需協助,請聯繫管理員。"
|
||||
}
|
||||
},
|
||||
"newPassword": "New Password",
|
||||
"passwordResetSuccess": "Password reset successfully. Please login.",
|
||||
"featuredAgents": "Featured AI Agents",
|
||||
"pleaseLoginFirst": "Please login to access this agent.",
|
||||
"userNotFound": "User not found",
|
||||
"incorrectPassword": "Incorrect password",
|
||||
"accountDisabled": "Account is disabled",
|
||||
"dbConnectionFailed": "Database connection failed. Please check if the database service is running.",
|
||||
"internalError": "Internal server error. Please try again later.",
|
||||
"passwordResetEmailSent": "If the account exists, a reset link has been sent to your email."
|
||||
},
|
||||
"landing": {
|
||||
"hero": {
|
||||
@@ -156,7 +166,8 @@
|
||||
"realName": "真實姓名",
|
||||
"employeeId": "工號",
|
||||
"phone": "手機號"
|
||||
}
|
||||
},
|
||||
"emailRequired": "Email is required"
|
||||
},
|
||||
"resetPassword": {
|
||||
"title": "重設密碼",
|
||||
|
||||
@@ -1188,7 +1188,11 @@
|
||||
"departmentLabel": "部門",
|
||||
"allStatuses": "全部狀態",
|
||||
"allDepartments": "全部部門",
|
||||
"noLimit": "不限"
|
||||
"noLimit": "不限",
|
||||
"typeLabel": "培训类型",
|
||||
"allTypes": "全部培训",
|
||||
"typeOnboarding": "入职培训",
|
||||
"typeSafety": "安全培训"
|
||||
},
|
||||
"columns": {
|
||||
"joinDate": "入職日期",
|
||||
@@ -1543,6 +1547,75 @@
|
||||
"哪些員工還沒有完成培訓?",
|
||||
"我想查看本月培訓成績統計"
|
||||
]
|
||||
},
|
||||
"safety": {
|
||||
"tabs": {
|
||||
"onboarding": "入职培训",
|
||||
"safety": "安全培训"
|
||||
},
|
||||
"progressTitle": "三级安全教育培训进度",
|
||||
"progressHint": "按国家安全生产法要求,新员工须依次完成公司级、部门级、班组级三级安全教育。学完三级的全部资料/视频后,进入1次统一考试,≥90分及格方可结业。",
|
||||
"steps": {
|
||||
"company": "01 · 公司级",
|
||||
"department": "02 · 部门级",
|
||||
"team": "03 · 班组级",
|
||||
"exam": "04 · 统一考试"
|
||||
},
|
||||
"stepStatus": {
|
||||
"watchVideo": "观看视频",
|
||||
"examReq": "≥90 分及格",
|
||||
"completed": "已完成",
|
||||
"inProgress": "进行中",
|
||||
"pending": "待学习",
|
||||
"examPending": "需先学完三级"
|
||||
},
|
||||
"videoPanelTitle": "{level} 第{step}步",
|
||||
"videoPanelSubtitle": "观看安全教育培训视频",
|
||||
"videoPanelPassLine": "及格线:≥ 90分方可进入考试",
|
||||
"videoTitle": "部门安全生产管理制度宣导",
|
||||
"videoDuration": "时长 35 分钟 · 已完成 12%",
|
||||
"materialsTitle": "培训资料清单 (共 3 个文件/视频)",
|
||||
"materials": {
|
||||
"m1": "部门安全生产管理制度宣导.mp4",
|
||||
"m2": "危险化学品安全操作规程.pdf",
|
||||
"m3": "消防应急疏散演练视频.mp4"
|
||||
},
|
||||
"flowTitle": "学习与考试流程",
|
||||
"flowSteps": {
|
||||
"company": "公司级安全教育",
|
||||
"department": "部门级安全教育",
|
||||
"team": "班组级安全教育",
|
||||
"exam": "统一考试 ≥90分"
|
||||
},
|
||||
"summaryTitle": "培训总结",
|
||||
"summaryContent": {
|
||||
"company": [
|
||||
"1公司教育:国家有关安全生产方针、政策、法律、法规和有关规定。",
|
||||
"2公司安全生产特点、有关安全管理标准和制度、安全生产情况及安全生产基本知识。",
|
||||
"3企业安全生产规章制度、安全纪律和劳动纪律。",
|
||||
"4安全生产和职业卫生的基本知识(防机械伤害、安全用电、防火防爆、防尘防毒、急救、危险因素、应急预案等)。",
|
||||
"5作业场所和工作岗位存在的危险因素、防范措施及事故应急措施;",
|
||||
"6安全生产正反方面的经验和教训,及重大事故安全案例教训。",
|
||||
"7从业人员安全生产权利和义务;"
|
||||
],
|
||||
"department": [
|
||||
"1部门概况、生产或作业特点、可能存在的不安全因素及必须遵守的事项。",
|
||||
"2公司、部门安全生产状况、管理制度规定和安全注意事项。",
|
||||
"3所从事工种的安全技术操作规程、安全职责、操作技能及强制性标准。",
|
||||
"4一般的机械设备、电气、触电、中暑、中毒急救安全基础知识",
|
||||
"5作业场所和工作岗位存在的风险、部门危险因素分布、安全通道、职业危害、伤亡事故、应急救缓预案内容。防火、防毒、防尘、防爆知识及紧急情况安全处置、自救互救、急救方法、疏散和现场紧急情况的处理。",
|
||||
"6部门安全设施(工具)、安全警示标志、急救器材、消防器材和个人防护用品的性能、使用方法和维护。",
|
||||
"7部门以往发生的典型安全和职业危害事故教育、岗位预防措施等。",
|
||||
"8有关事故案例。"
|
||||
],
|
||||
"team": [
|
||||
"1本班组(岗位)生产工艺流程、作业特点和注意事项、安全操作规程及细则。",
|
||||
"2本班组安全活动制度及纪律、岗位之间工作衔接配合的安全与职业卫生事项。",
|
||||
"3本班组(岗位)设备、工具的性能和安全装置、安全设施、监控仪器的作用原理、正确使用方法、防护用品及消防器材的使用和保管方法等。",
|
||||
"4危害因素及防范、应急措施,本岗位易发生事故的不安全因素及其防范对策,本工种事故案例剖析。",
|
||||
"5本岗位发现紧急情况应采取的应救措施和报告办法。"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"shippingOrderReview": {
|
||||
@@ -2679,7 +2752,8 @@
|
||||
"inventory_source_unresolved": "庫存源未解析",
|
||||
"effective_reservation_missing": "缺少有效的預約單號",
|
||||
"unknown": "系統發現一項需要人工確認的內容"
|
||||
}
|
||||
},
|
||||
"autoCreateBlocked": "人工建单资格已通过,但自动建单资格未通过;确认后将由人工推进。"
|
||||
},
|
||||
"inventoryCandidates": {
|
||||
"title": "人工選擇庫存源",
|
||||
|
||||
@@ -1,6 +1,21 @@
|
||||
{
|
||||
"generic": "請求失敗。",
|
||||
"codes": {
|
||||
"ORDER_DELIVERY_REPLY.FORBIDDEN": "無訂單交期回覆查看權限,請聯絡管理員開通。",
|
||||
"ORDER_DELIVERY_REPLY.LINE_NOT_FOUND": "訂單行不存在或已不在同步範圍。",
|
||||
"ORDER_DELIVERY_REPLY.ADMIN_REQUIRED": "僅平台管理員可按部門批量發放權限。",
|
||||
"ORDER_DELIVERY_REPLY.GRANT_DEPARTMENT_REQUIRED": "請填寫要發放權限的部門。",
|
||||
"ORDER_DELIVERY_REPLY.GRANT_PERMISSION_INVALID": "權限類型須為 manage 或 access。",
|
||||
"ORDER_DELIVERY_REPLY.BATCH_REPLY_EMPTY": "聯合回覆至少包含一行,且單次不超過 200 行。",
|
||||
"ORDER_DELIVERY_REPLY.NOTIFY_BATCH_EMPTY": "批量通知至少包含一行,且單次不超過 200 行。",
|
||||
"ORDER_DELIVERY_REPLY.SALESPERSON_UNMAPPED": "訂單業務員未關聯系統帳號或未綁定企微,無法發送通知。",
|
||||
"ORDER_DELIVERY_REPLY.NOTIFY_FAILED": "企微通知發送失敗,該行未鎖定,請稍後重試。",
|
||||
"ORDER_DELIVERY_REPLY.LINE_LOCKED": "該訂單行交期已通知鎖定,不能修改批次。",
|
||||
"ORDER_DELIVERY_REPLY.MANAGE_FORBIDDEN": "無訂單交期回覆操作權限,僅生管可儲存或通知。",
|
||||
"ORDER_DELIVERY_REPLY.BATCHES_REQUIRED": "請至少填寫一條交期批次。",
|
||||
"ORDER_DELIVERY_REPLY.BATCH_COUNT_EXCEEDED": "單行批次數量超過上限。",
|
||||
"ORDER_DELIVERY_REPLY.BATCH_INVALID": "批次格式不合法,請檢查交期、數量或備註。",
|
||||
"ORDER_DELIVERY_REPLY.BATCH_QTY_TOTAL_MISMATCH": "各批次數量合計必須等於訂單數量,請調整後重新保存。",
|
||||
"SHIPPING.NOTICE_ODM_CHOICE_INVALID": "所選 ODM ID 不在當前可行候選內,請重新選擇。",
|
||||
"SHIPPING.FULFILLMENT_POLICY_INVALID": "貨代履約策略或欄位能力綁定無效。",
|
||||
"SHIPPING.FULFILLMENT_POLICY_NOT_FOUND": "找不到貨代履約策略。",
|
||||
|
||||
@@ -113,7 +113,8 @@
|
||||
"contractPayment": "合約付款預警",
|
||||
"contractPaymentLedger": "合約台帳",
|
||||
"contractPaymentReview": "待確認合約",
|
||||
"contractPaymentWeeklyBatches": "週彙總批次"
|
||||
"contractPaymentWeeklyBatches": "週彙總批次",
|
||||
"orderDeliveryReply": "訂單交期回覆"
|
||||
},
|
||||
"kb": {
|
||||
"accessDenied": "需要管理員權限才能存取知識庫。"
|
||||
@@ -170,6 +171,20 @@
|
||||
},
|
||||
"msg": {
|
||||
"downloadExcelFailed": "下載 Excel 失敗"
|
||||
},
|
||||
"batch": {
|
||||
"selectAll": "Select all notices on this page",
|
||||
"selected": "{count} selected",
|
||||
"download": "Download Excel",
|
||||
"confirm": "Confirm uploaded",
|
||||
"rpa": "Start RPA upload",
|
||||
"downloadStarted": "Downloading the selected shipping-notice Excel files.",
|
||||
"success": "{action}: {count} notice(s) processed.",
|
||||
"partialResult": "{action}: {accepted} accepted and {blocked} blocked. Refresh to see the latest notice status.",
|
||||
"lines": "Lines",
|
||||
"parts": "Parts",
|
||||
"quantities": "Shipment / available",
|
||||
"uploadStatus": "Freight status"
|
||||
}
|
||||
},
|
||||
"receiptReports": {
|
||||
@@ -968,5 +983,100 @@
|
||||
"notifyExcel": "Excel",
|
||||
"downloadExcel": "下載 Excel",
|
||||
"downloadExcelFailed": "下載 Excel 失敗"
|
||||
},
|
||||
"orderDeliveryReply": {
|
||||
"deepLinkLocated": "已定位到通知對應的訂單行 {order}:{item}",
|
||||
"search": "查詢",
|
||||
"reset": "重置",
|
||||
"saving": "儲存中…",
|
||||
"syncNow": "手動刷新",
|
||||
"syncing": "同步中…",
|
||||
"syncNever": "尚未同步",
|
||||
"syncAt": "最近同步:{time}",
|
||||
"syncRunning": "同步進行中…",
|
||||
"syncFailedAt": "上次同步失敗({time}),列表為上次成功快照",
|
||||
"syncDone": "同步完成,共 {count} 行",
|
||||
"syncSkipped": "已有同步正在進行,請稍後再試",
|
||||
"syncFailedTitle": "同步失敗,已保留上次快照",
|
||||
"filterKeyword": "關鍵詞(訂單 / 產品 / 客戶 / 業務員 / 回覆人員)",
|
||||
"filterKeywordPh": "訂單單號、產品編號、品名、客戶料號、客戶編號、業務員、交期回覆人員均可搜尋",
|
||||
"filterOrderDate": "訂單日期",
|
||||
"filterStatus": "交期回覆狀態",
|
||||
"statusAll": "全部",
|
||||
"statusReplied": "已回覆",
|
||||
"statusNotFully": "未完全回覆",
|
||||
"statusNotReplied": "未回覆",
|
||||
"statusPartial": "部分回覆",
|
||||
"totalCount": "共 {count} 條產品行",
|
||||
"selectAll": "全選(本頁)",
|
||||
"selectedCount": "已勾選 {count} 行",
|
||||
"batchReply": "+ 聯合回覆交期",
|
||||
"batchNotify": "批量通知",
|
||||
"toolbarHint": "聯合回覆只儲存批次;點「批量通知」才發送並鎖定。",
|
||||
"colOrderLine": "訂單單號:項次",
|
||||
"colOrderDate": "訂單日期",
|
||||
"colCustomer": "客戶編號",
|
||||
"colSalesperson": "業務員",
|
||||
"colDept": "部門",
|
||||
"colCustomerPo": "客戶訂單",
|
||||
"colPartNo": "產品編號",
|
||||
"colPartName": "品名",
|
||||
"colSpec": "規格",
|
||||
"colCustomerPartNo": "客戶產品編號",
|
||||
"colAgreedDate": "約定交貨日",
|
||||
"colUnit": "單位",
|
||||
"colQty": "數量",
|
||||
"colDelivered": "已交數量",
|
||||
"colUndelivered": "未交數量",
|
||||
"colStatus": "交期回覆狀態",
|
||||
"colReply": "交期回覆",
|
||||
"colNotify": "通知業務部門",
|
||||
"colReplyPerson": "交期回覆人員",
|
||||
"batchCount": "{count} 批",
|
||||
"repliedOf": "已回覆 {replied}/{remain}",
|
||||
"overTag": "超",
|
||||
"collapse": "收起 ▲",
|
||||
"expand": "+{count} 批 ▾",
|
||||
"lockedTag": "交期已鎖定",
|
||||
"replyAction": "回覆交期",
|
||||
"editReplyAction": "修改回覆",
|
||||
"notifiedTag": "已通知 {name}",
|
||||
"replyFirst": "請先回覆交期",
|
||||
"notifyAction": "發送通知業務部門",
|
||||
"pendingNotify": "待通知後記錄",
|
||||
"empty": "沒有符合條件的訂單行",
|
||||
"pageInfo": "第 {page} / {pages} 頁",
|
||||
"modalTitleSingle": "回覆交期 · {order} / 項次 {item}",
|
||||
"modalTitleBatch": "聯合回覆交期({count} 行)",
|
||||
"quickDate": "快速統一交期",
|
||||
"applyQuickDate": "應用到全部",
|
||||
"modalHint": "可填 1 個交期,或點「增加批次」拆成多個「交期+數量」;各批次數量合計須等於訂單數量。",
|
||||
"itemLabel": "項次 {item}",
|
||||
"qtyPh": "數量",
|
||||
"remarkPh": "備註(可選)",
|
||||
"removeBatch": "刪除本行批次",
|
||||
"addBatch": "+ 增加拆分批次(交期 + 數量 + 備註)",
|
||||
"saveReply": "儲存回覆",
|
||||
"noValidBatches": "請至少為一行填寫交期和數量",
|
||||
"saveSingleDone": "交期批次已儲存(未通知,可繼續修改)",
|
||||
"saveBatchDone": "已儲存 {ok} 行交期批次(未通知)",
|
||||
"saveBatchPartial": "儲存完成:成功 {ok} 行,失敗 {fail} 行:{detail}",
|
||||
"saveFailedTitle": "儲存失敗",
|
||||
"loadFailed": "載入訂單行失敗",
|
||||
"notifyConfirm": "確認向業務員「{salesperson}」發送?\n您有訂單號:項次{order}:{item}的訂單需要填寫/確認/查看交期。\n發送後交期將鎖定。",
|
||||
"notifyDone": "已通知並鎖定:{order}:{item}",
|
||||
"notifyBatchConfirm": "將向 {count} 行對應業務員發送交期通知,發送成功的行將鎖定。繼續?",
|
||||
"notifyPartial": "部分成功:成功 {ok} 行,失敗 {fail} 行,跳過 {skip} 行。失敗:{detail}",
|
||||
"notifyAllFailed": "全部失敗({fail} 行):{detail}",
|
||||
"notifyBatchDone": "已通知並鎖定 {ok} 行,跳過 {skip} 行",
|
||||
"notifyFailedTitle": "通知發送失敗,該行未鎖定",
|
||||
"entryHint": "查單 → 填交期 → 通知業務員",
|
||||
"notNotified": "未通知",
|
||||
"orderQtyLabel": "訂單數量:{qty} {unit}",
|
||||
"batchMissingDate": "第 {batches} 批未填交期",
|
||||
"batchMissingQty": "第 {batches} 批未填數量",
|
||||
"qtyTotalMismatchLine": "各批次合計 {total},須等於訂單數量 {qty}",
|
||||
"saveBlocked": "以下行填寫未完成,無法保存:{detail}",
|
||||
"batchDuplicateDate": "同一訂單單號:項次的不同批次交期時間不能相同(重複:{dates})"
|
||||
}
|
||||
}
|
||||
@@ -122,6 +122,11 @@ export async function requestJson<T>(url: string, init?: RequestInit): Promise<T
|
||||
const headers = new Headers(init?.headers || {});
|
||||
const authHeaders = getAuthHeaders();
|
||||
Object.entries(authHeaders).forEach(([k, v]) => headers.set(k, v as string));
|
||||
// 带 body 的请求若未显式声明类型,统一补 JSON 头:否则 Flask get_json(silent=True)
|
||||
// 会因 Content-Type 非 JSON 解析出 None,把有效载荷当空 body 处理(如订单交期回复保存被误判 400)。
|
||||
if (init?.body && !headers.has('Content-Type')) {
|
||||
headers.set('Content-Type', 'application/json');
|
||||
}
|
||||
const res = await fetch(url, { ...init, headers });
|
||||
|
||||
let data: any = null;
|
||||
|
||||
@@ -6,6 +6,9 @@
|
||||
*/
|
||||
export type FeaturePermissions = {
|
||||
training_hr_manage?: boolean;
|
||||
'contract_payment.access'?: boolean;
|
||||
'order_delivery_reply.manage'?: boolean;
|
||||
'order_delivery_reply.access'?: boolean;
|
||||
[key: string]: boolean | undefined;
|
||||
};
|
||||
|
||||
|
||||
Reference in new issue
Block a user