Merge branch 'dev911' into test
This commit is contained in:
commit
e13838cbb8
71 files changed
+4706
-177
No files matched your search
@@ -0,0 +1,2 @@
|
||||
DEBUG_SERVER_URL=http://127.0.0.1:7778/event
|
||||
DEBUG_SESSION_ID=login-401
|
||||
@@ -0,0 +1,2 @@
|
||||
{"sessionId": "app-open-error", "runId": "pre-fix", "hypothesisId": "A", "location": "src/main.ts:8", "msg": "[DEBUG] Frontend bootstrap started", "data": {"href": "http://192.168.100.192:8910/config"}, "ts": 1788828493927}
|
||||
{"sessionId": "app-open-error", "runId": "pre-fix", "hypothesisId": "C", "location": "src/main.ts:16", "msg": "[DEBUG] Vue app mounted", "data": {"appChildren": 1}, "ts": 1788828493938}
|
||||
@@ -125,7 +125,7 @@ SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL=
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS=10
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS=300
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE=10
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY=3
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY=2
|
||||
SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS=1000000
|
||||
SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES=2000000
|
||||
SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS=3
|
||||
@@ -147,7 +147,7 @@ SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/u
|
||||
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile
|
||||
# AWS 库存列映射(可选 JSON 字符串)
|
||||
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
|
||||
# 本地 RPA(scripts/rpa/inventory/inventory_rpa_worker.py)
|
||||
# 本地 RPA(scripts/rpa/freight_rpa_worker.py)
|
||||
SHIPPING_NOTICE_RPA_WORKER_MOCK=false
|
||||
# 本机无 Redis 时允许进程内存记录心跳;有 Redis 时优先写 Redis
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false
|
||||
|
||||
@@ -70,6 +70,7 @@ 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
|
||||
WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||
|
||||
# --- 5. 数据库与基础设施 ---
|
||||
|
||||
+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
|
||||
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
|
||||
WECOM_FEEDBACK_NOTIFY_ENABLED=true
|
||||
WECOM_FEEDBACK_NOTIFY_BASE_URL=http://ai.well-trust.com:8881
|
||||
# 企业微信群机器人 webhook,按环境写入 .env.<env> 或部署平台变量;不要提交真实 URL。
|
||||
|
||||
@@ -70,6 +70,7 @@ 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
|
||||
WECOM_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||
HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""
|
||||
"""
|
||||
backend/app/__init__.py
|
||||
|
||||
用途:应用工厂:创建 Flask 应用、挂载全局异常与响应处理。
|
||||
@@ -114,6 +114,11 @@ 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.lean_training_schedule_seed import ensure_default_lean_training_schedule
|
||||
ensure_default_lean_training_schedule()
|
||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||
logger.warning('Failed to ensure lean-training schedule: %s', exc)
|
||||
else:
|
||||
logger.info('Skip startup schedule seeding: schedule_tasks table is not ready')
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
"""
|
||||
backend/app/api/contract_payment.py
|
||||
|
||||
用途:采购合同付款预警 Agent 的合同台账、付款计划、待发送摘要和同步 API。
|
||||
用途:采购合同付款预警 Agent 的合同台账、付款计划、待发送摘要、台账汇总卡和同步 API。
|
||||
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、contract_payment 服务和通用 Job 队列。
|
||||
逻辑:页面查询合同、节点与本周待发送摘要;同步和预警操作入队,避免请求线程执行外部系统和企微调用。
|
||||
逻辑:页面查询合同、节点、本周待发送摘要与四张汇总卡;同步和预警操作入队,避免请求线程执行外部系统和企微调用。
|
||||
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍。
|
||||
鉴权:所有接口要求已登录且具备 `contract_payment.access`(admin 默认开,可显式授予普通用户)。
|
||||
鉴权:查询接口要求 `contract_payment.access`(admin 默认开,可显式授予普通用户);
|
||||
同步/扫描/周汇总发送仅 `role=admin`。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -28,6 +29,11 @@ from app.models import (
|
||||
FileAsset,
|
||||
)
|
||||
from app.services.contract_payment.alert_service import build_weekly_alert_summary
|
||||
from app.services.contract_payment.ledger_focus import (
|
||||
LEDGER_FOCUS_VALUES,
|
||||
apply_ledger_focus,
|
||||
ledger_focus_counts,
|
||||
)
|
||||
from app.services.contract_payment.parse_service import unique_parse_issues
|
||||
from app.services.contract_payment.sync_service import build_payment_plan, build_payment_plan_from_bytes
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
@@ -92,6 +98,30 @@ def _require_contract_payment_access():
|
||||
return user
|
||||
|
||||
|
||||
def _require_contract_payment_admin():
|
||||
"""
|
||||
确保当前用户既有合同付款预警访问权,又是平台管理员。
|
||||
|
||||
核心逻辑:普通授权用户可查台账;同步 OA、强制覆盖、批量重解析、扫描预警和发送周汇总
|
||||
会改写外部系统或触发企微,因此仅 `role=admin` 可调用。
|
||||
|
||||
Args:
|
||||
无。当前请求身份由 JWT 上下文提供。
|
||||
Returns:
|
||||
已认证的管理员用户。
|
||||
Raises:
|
||||
UnauthorizedError: 请求没有有效登录身份。
|
||||
ForbiddenError: 无合同付款访问权,或已授权但不是管理员。
|
||||
"""
|
||||
user = _require_contract_payment_access()
|
||||
if getattr(user, "role", None) != "admin":
|
||||
raise ForbiddenError(
|
||||
'Admin privilege required for contract payment jobs',
|
||||
code='CONTRACT_PAYMENT.ADMIN_REQUIRED',
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
def _serialize_contract(row: ContractPaymentContract) -> dict:
|
||||
"""
|
||||
序列化合同台账、付款节点及预警记录,供列表和详情共用。
|
||||
@@ -170,7 +200,7 @@ def list_contracts():
|
||||
"""
|
||||
查询合同台账。
|
||||
|
||||
核心逻辑:支持合同编号、流程编号、采购单号和解析状态筛选,并按 offset 分页返回台账,避免工作台一次加载全部合同。
|
||||
核心逻辑:支持合同编号、流程编号、采购单号、供应商名称、解析状态和汇总卡口径(focus)筛选,并按 offset 分页返回台账。
|
||||
Args:
|
||||
无。筛选条件从 query string 读取。
|
||||
Returns:
|
||||
@@ -185,6 +215,7 @@ def list_contracts():
|
||||
ContractPaymentContract.contract_no.ilike(like)
|
||||
| ContractPaymentContract.workflow_no.ilike(like)
|
||||
| ContractPaymentContract.purchase_order_no.ilike(like)
|
||||
| ContractPaymentContract.supplier_name.ilike(like)
|
||||
)
|
||||
parse_status = str(request.args.get("parse_status") or "").strip()
|
||||
review_only = str(request.args.get("review_only") or "").strip().lower() in {"1", "true", "yes"}
|
||||
@@ -195,6 +226,13 @@ def list_contracts():
|
||||
else:
|
||||
# 自动付款预警台账仅展示关键解析事实完整的合同;待确认合同由独立导航集中处理。
|
||||
query = query.filter_by(parse_status="parsed")
|
||||
focus = str(request.args.get("focus") or "").strip()
|
||||
if focus:
|
||||
if review_only:
|
||||
raise ValidationError("待确认列表不支持汇总卡筛选", details={"focus": focus})
|
||||
if focus not in LEDGER_FOCUS_VALUES:
|
||||
raise ValidationError("不支持的汇总卡筛选", details={"focus": focus})
|
||||
query = apply_ledger_focus(query, focus, session=db.session)
|
||||
page = max(_query_int("page", default=1), 1)
|
||||
page_size = min(max(_query_int("page_size", default=20), 1), 100)
|
||||
total = query.count()
|
||||
@@ -215,6 +253,21 @@ def list_contracts():
|
||||
}, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@contract_payment_bp.route("/contracts/summary", methods=["GET"])
|
||||
def get_ledger_summary():
|
||||
"""
|
||||
查询合同台账四张汇总卡的合同份数。
|
||||
|
||||
核心逻辑:始终统计全部已解析台账,不跟页面 keyword;口径与点卡片过滤列表共用 ledger_focus。
|
||||
Args:
|
||||
无。
|
||||
Returns:
|
||||
标准成功 envelope,含 due、overdue、needs_completion、due_this_month。
|
||||
"""
|
||||
_require_contract_payment_access()
|
||||
return ok(ledger_focus_counts(session=db.session), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
def _query_int(key: str, *, default: int) -> int:
|
||||
"""读取正整数查询参数;非法值回退默认值,防止分页接口返回 500。"""
|
||||
try:
|
||||
@@ -279,12 +332,15 @@ def enqueue_sync():
|
||||
"""
|
||||
将 OA 合同、验收和厂商预付款请款同步任务入队。
|
||||
|
||||
核心逻辑:仅管理员可入队;force / reparse_existing 仍走同一 Job,避免普通授权用户改写 OA 字段。
|
||||
Args:
|
||||
无。操作用户由 JWT 上下文读取。
|
||||
Returns:
|
||||
HTTP 202 与后台 Job ID。
|
||||
Raises:
|
||||
ForbiddenError: 非管理员或无合同付款访问权。
|
||||
"""
|
||||
user = _require_contract_payment_access()
|
||||
user = _require_contract_payment_admin()
|
||||
data = request.get_json(silent=True) or {}
|
||||
force_value = data.get("force", False)
|
||||
if not isinstance(force_value, bool):
|
||||
@@ -303,12 +359,15 @@ def enqueue_alert_scan():
|
||||
"""
|
||||
将四阶段三轮合同付款预警扫描任务入队。
|
||||
|
||||
核心逻辑:仅管理员可手动补扫;日常扫描仍由排程触发。
|
||||
Args:
|
||||
无。操作用户由 JWT 上下文读取。
|
||||
Returns:
|
||||
HTTP 202 与后台 Job ID。
|
||||
Raises:
|
||||
ForbiddenError: 非管理员或无合同付款访问权。
|
||||
"""
|
||||
user = _require_contract_payment_access()
|
||||
user = _require_contract_payment_admin()
|
||||
job_id = enqueue(JobType.CONTRACT_PAYMENT_ALERT, {}, domain="procurement_contract", business_ref="daily-alert", created_by_id=user.id, message="等待计算合同付款预警")
|
||||
return ok({"job_id": job_id}, request_id=getattr(g, "request_id", None), status=202)
|
||||
|
||||
@@ -331,12 +390,15 @@ def get_alert_summary():
|
||||
def enqueue_weekly_alert_send():
|
||||
"""将合同付款预警周汇总发送任务入队。
|
||||
|
||||
核心逻辑:仅管理员可手动补发;周五 18:00 排程不受此限制。
|
||||
Args:
|
||||
无。操作用户由 JWT 上下文读取。
|
||||
Returns:
|
||||
HTTP 202 与后台 Job ID。
|
||||
Raises:
|
||||
ForbiddenError: 非管理员或无合同付款访问权。
|
||||
"""
|
||||
user = _require_contract_payment_access()
|
||||
user = _require_contract_payment_admin()
|
||||
job_id = enqueue(
|
||||
JobType.CONTRACT_PAYMENT_ALERT_WEEKLY,
|
||||
{},
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
"""
|
||||
backend/app/api/kb/common.py
|
||||
|
||||
用途:知识库 API 共享 helper(鉴权、序列化、Markdown 预览)。
|
||||
用途:知识库 API 共享 helper(鉴权、序列化、Markdown 预览、下载头)。
|
||||
依赖:app.core.*、models、services/kb/storage、edkb_system。
|
||||
逻辑:dify/groups/documents/jobs 子模块共用;存储读写见 services/kb/storage。
|
||||
"""
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||
|
||||
@@ -31,6 +34,31 @@ def require_user():
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def build_content_disposition(filename: str, *, as_attachment: bool = True) -> str:
|
||||
"""
|
||||
构造 RFC 5987 Content-Disposition,保证中文源文件名不被浏览器拼成怪名。
|
||||
|
||||
核心逻辑:quoted ASCII 回退名(保留扩展名)+ filename*=UTF-8''百分号编码原名。
|
||||
浏览器优先 filename*;旧客户端才用 ASCII 回退。ASCII 段必须加引号且不含分号。
|
||||
|
||||
Args:
|
||||
filename: 用户可见的原始文件名。禁止路径分隔与换行。
|
||||
as_attachment: True 为下载(attachment),False 为预览(inline)。
|
||||
|
||||
Returns:
|
||||
可直接写入响应头的 Content-Disposition 字符串。
|
||||
"""
|
||||
safe_name = Path(str(filename or '').replace('\\', '/')).name
|
||||
safe_name = safe_name.replace('\r', '').replace('\n', '').replace('"', '').strip() or 'download'
|
||||
suffix = Path(safe_name).suffix
|
||||
stem_ascii = Path(safe_name).stem.encode('ascii', 'ignore').decode('ascii').strip() or 'download'
|
||||
ascii_name = f'{stem_ascii}{suffix}' if suffix else stem_ascii
|
||||
encoded = quote(safe_name, safe='')
|
||||
disposition = 'attachment' if as_attachment else 'inline'
|
||||
return f'{disposition}; filename="{ascii_name}"; filename*=UTF-8\'\'{encoded}'
|
||||
|
||||
|
||||
def run_db_read(label: str, loader):
|
||||
try:
|
||||
return loader()
|
||||
|
||||
@@ -3,13 +3,19 @@ backend/app/api/kb/documents.py
|
||||
|
||||
用途:知识库文档版本、Markdown、上传/清洗/同步 API(薄路由层)。
|
||||
依赖:kb.blueprint、kb.common、services/kb/document_service。
|
||||
逻辑:/documents* 与 /document-versions* 路由;业务见 document_service。
|
||||
逻辑:/documents* 与 /document-versions* 路由;业务见 document_service;源文件下载覆盖 RFC 5987 Content-Disposition。
|
||||
"""
|
||||
from flask import jsonify, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.api.kb.blueprint import knowledge_base_bp
|
||||
from app.api.kb.common import require_user, serialize_document, serialize_sync_record, serialize_version
|
||||
from app.api.kb.common import (
|
||||
build_content_disposition,
|
||||
require_user,
|
||||
serialize_document,
|
||||
serialize_sync_record,
|
||||
serialize_version,
|
||||
)
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.kb import document_service
|
||||
@@ -24,10 +30,18 @@ def list_document_versions(document_id: int):
|
||||
|
||||
@knowledge_base_bp.route('/document-versions/<int:version_id>/source-file', methods=['GET'])
|
||||
def get_document_version_source_file(version_id: int):
|
||||
"""
|
||||
返回知识库版本原始文件。
|
||||
|
||||
用途:工作台源文件信息弹窗下载原件;?download=1 时按附件下发,保存名与上传时一致。
|
||||
核心逻辑:send_file 后再覆盖 Content-Disposition 为 RFC 5987,避免 Werkzeug ASCII 回退名无引号导致浏览器拼名。
|
||||
"""
|
||||
require_user()
|
||||
source_path, filename = document_service.resolve_source_file_path(version_id)
|
||||
as_attachment = str(request.args.get('download') or '').strip() == '1'
|
||||
return send_file(source_path, as_attachment=as_attachment, download_name=filename)
|
||||
response = send_file(source_path, as_attachment=as_attachment, download_name=filename)
|
||||
response.headers['Content-Disposition'] = build_content_disposition(filename, as_attachment=as_attachment)
|
||||
return response
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/document-versions/<int:version_id>/training-preview-file', methods=['GET'])
|
||||
@@ -41,7 +55,9 @@ def get_training_preview_file(version_id: int):
|
||||
require_user()
|
||||
preview_path, filename = document_service.resolve_training_preview_file_path(version_id)
|
||||
as_attachment = str(request.args.get('download') or '').strip() == '1'
|
||||
return send_file(preview_path, as_attachment=as_attachment, download_name=filename)
|
||||
response = send_file(preview_path, as_attachment=as_attachment, download_name=filename)
|
||||
response.headers['Content-Disposition'] = build_content_disposition(filename, as_attachment=as_attachment)
|
||||
return response
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/sync-records', methods=['GET'])
|
||||
|
||||
+130
-3
@@ -13,7 +13,8 @@ from io import BytesIO
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, UnauthorizedError
|
||||
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.services.training_service import (
|
||||
export_training_records_excel,
|
||||
get_user_training_record,
|
||||
@@ -23,6 +24,21 @@ from app.services.training_service import (
|
||||
upsert_user_training_record,
|
||||
)
|
||||
from app.services.training_config_service import get_published_config, list_training_type_codes
|
||||
from app.services.lean_training_service import (
|
||||
LEAN_TRAINING_TYPE,
|
||||
create_or_update_weekly_task,
|
||||
get_current_weekly_task,
|
||||
get_weekly_task_for_admin,
|
||||
list_dashboard,
|
||||
list_my_weekly_tasks,
|
||||
mark_video_watched,
|
||||
save_completion,
|
||||
)
|
||||
from app.services.lean_training_push_service import list_push_logs, push_lean_training_videos
|
||||
from app.services.lean_training_reminder_service import (
|
||||
send_initial_target_notifications,
|
||||
send_targeted_reminders,
|
||||
)
|
||||
|
||||
training_user_bp = Blueprint("training_user", __name__)
|
||||
training_admin_bp = Blueprint("training_admin", __name__)
|
||||
@@ -49,6 +65,14 @@ def _require_training_admin():
|
||||
return user
|
||||
|
||||
|
||||
def _require_lean_training_manager():
|
||||
"""确保当前用户具备 HR 培训管理权限,可维护精益任务、对象、看板和提醒。"""
|
||||
user = _require_user()
|
||||
if not user.can_manage_training():
|
||||
raise ForbiddenError("Lean training manager privilege required")
|
||||
return user
|
||||
|
||||
|
||||
@training_user_bp.route("/training-record", methods=["GET"])
|
||||
def get_my_training_record():
|
||||
"""读取当前用户的培训进度;未创建时返回 null data。"""
|
||||
@@ -66,9 +90,17 @@ def list_my_training_types():
|
||||
用途:为员工动态培训 Tabs 和 HR 类型名称映射提供统一的 code/name 数据源。
|
||||
Returns:
|
||||
已发布培训类型列表;每项包含非空 code 与管理员配置的展示名称。
|
||||
精益管理(lean_management)仅对当前周任务受训对象开放(角色/指定用户并集命中);
|
||||
非受训对象或尚无已发布精益任务时,不返回该类型,员工端据此隐藏"精益管理"模块。
|
||||
"""
|
||||
_require_user()
|
||||
return jsonify(list_training_type_codes())
|
||||
user = _require_user()
|
||||
types = list_training_type_codes()
|
||||
# [STEP 1] 精益管理按受训对象过滤:get_current_weekly_task 已按
|
||||
# is_task_targeted_to_user(角色 ∪ 指定用户)筛选,未命中时剔除该类型
|
||||
if any(item.get("code") == LEAN_TRAINING_TYPE for item in types):
|
||||
if get_current_weekly_task(user) is None:
|
||||
types = [item for item in types if item.get("code") != LEAN_TRAINING_TYPE]
|
||||
return jsonify(types)
|
||||
|
||||
|
||||
@training_user_bp.route("/training-config", methods=["GET"])
|
||||
@@ -86,6 +118,33 @@ def save_my_training_record():
|
||||
return jsonify(serialize_training_record(record))
|
||||
|
||||
|
||||
@training_user_bp.route("/lean-training/my-tasks", methods=["GET"])
|
||||
def list_my_lean_training_tasks():
|
||||
"""
|
||||
返回当前员工被指派的全部精益周任务(周期倒序),供员工端时间树展示。
|
||||
|
||||
每项含学员视角已推送视频(带播放地址)、任务状态(进行中/已延期/已完成)与完成信息。
|
||||
"""
|
||||
return ok(list_my_weekly_tasks(_require_user()))
|
||||
|
||||
|
||||
@training_user_bp.route("/lean-training/my-tasks/watched", methods=["POST"])
|
||||
def mark_my_lean_training_video_watched():
|
||||
"""
|
||||
学员端记录单个精益任务视频完成观看(视频播放到结尾即持久化)。
|
||||
|
||||
请求体需包含 weekly_task_id 与 resource_id;服务端校验视频属于该任务已推送范围。
|
||||
"""
|
||||
return ok(mark_video_watched(_require_user(), request.get_json(silent=True) or {}))
|
||||
|
||||
|
||||
@training_user_bp.route("/lean-training/completions", methods=["PUT"])
|
||||
def save_my_lean_training_completion():
|
||||
"""保存当前员工精益周任务完成事实,服务端强制校验视频和 50 字总结。"""
|
||||
user = _require_user()
|
||||
return ok(save_completion(user, request.get_json(silent=True) or {}))
|
||||
|
||||
|
||||
@training_admin_bp.route("/training-records", methods=["GET"])
|
||||
def list_admin_training_records():
|
||||
"""列出培训记录,支持关键字、部门、状态筛选。"""
|
||||
@@ -148,3 +207,71 @@ def export_admin_training_records():
|
||||
download_name=file_name,
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
|
||||
|
||||
@training_admin_bp.route("/lean-training/weekly-tasks", methods=["POST"])
|
||||
def create_admin_lean_training_weekly_task():
|
||||
"""创建或调整精益周任务(任务周/截止时间支持修改:显式周次按所选周落库,缺省当周);发布后首次自动推送首批视频,员工端即刻可见。"""
|
||||
user = _require_lean_training_manager()
|
||||
task = create_or_update_weekly_task(request.get_json(silent=True) or {}, user.id)
|
||||
send_initial_target_notifications(task["id"])
|
||||
# [STEP] 仅首次发布(游标为 0)时自动推首批;编辑已推过的任务不重复触发
|
||||
if task["pushed_video_count"] == 0:
|
||||
push_lean_training_videos(task["id"], trigger="publish", current_user_id=user.id)
|
||||
task = get_weekly_task_for_admin(task["id"])
|
||||
return ok(task, status=201)
|
||||
|
||||
|
||||
@training_admin_bp.route("/lean-training/weekly-tasks/<int:task_id>", methods=["GET"])
|
||||
def get_admin_lean_training_weekly_task(task_id: int):
|
||||
"""按 ID 读取指定周任务详情(管理端视角,全量视频列表),供发布/补推后刷新所选周任务而非最新周。"""
|
||||
_require_lean_training_manager()
|
||||
task = get_weekly_task_for_admin(task_id)
|
||||
if task is None:
|
||||
raise NotFoundError("weekly task not found")
|
||||
return ok(task)
|
||||
|
||||
|
||||
@training_admin_bp.route("/lean-training/weekly-tasks/<int:task_id>/push", methods=["POST"])
|
||||
def create_admin_lean_training_video_push(task_id: int):
|
||||
"""HR 手动推送下一批精益培训视频,无需等待每周一排程;返回本轮推送日志。"""
|
||||
user = _require_lean_training_manager()
|
||||
try:
|
||||
result = push_lean_training_videos(task_id, trigger="manual", current_user_id=user.id)
|
||||
except ValueError as exc:
|
||||
raise NotFoundError(str(exc)) from exc
|
||||
return ok(result)
|
||||
|
||||
|
||||
@training_admin_bp.route("/lean-training/weekly-tasks/<int:task_id>/push-logs", methods=["GET"])
|
||||
def get_admin_lean_training_push_logs(task_id: int):
|
||||
"""读取指定周任务的分批推送日志(含失败明细),供管理端"推送记录"展示。"""
|
||||
_require_lean_training_manager()
|
||||
return ok(list_push_logs(task_id))
|
||||
|
||||
|
||||
@training_admin_bp.route("/lean-training/weekly-tasks/<int:task_id>/reminders", methods=["POST"])
|
||||
def create_admin_lean_training_targeted_reminders(task_id: int):
|
||||
_require_lean_training_manager()
|
||||
payload = request.get_json(silent=True) or {}
|
||||
raw_user_ids = payload.get("user_ids")
|
||||
if not isinstance(raw_user_ids, list) or not raw_user_ids:
|
||||
raise ValidationError("user_ids must be a non-empty list", details={"field": "user_ids"})
|
||||
try:
|
||||
user_ids = list({int(user_id) for user_id in raw_user_ids})
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError("user_ids contains invalid user", details={"field": "user_ids"}) from exc
|
||||
if any(user_id <= 0 for user_id in user_ids):
|
||||
raise ValidationError("user_ids contains invalid user", details={"field": "user_ids"})
|
||||
try:
|
||||
return ok(send_targeted_reminders(task_id, user_ids))
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc)) from exc
|
||||
|
||||
|
||||
@training_admin_bp.route("/lean-training/dashboard", methods=["GET"])
|
||||
def get_admin_lean_training_dashboard():
|
||||
"""读取 HR 可见的精益培训完成和未完成名单,仅展示任务指定对象。"""
|
||||
_require_lean_training_manager()
|
||||
raw_task_id = request.args.get("task_id", type=int)
|
||||
return ok(list_dashboard(raw_task_id))
|
||||
@@ -552,7 +552,9 @@ 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')
|
||||
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')
|
||||
# 精益培训企微提醒卡片跳转的员工培训聊天页 agent id(前端路由 /chat/<id>,默认 16)。
|
||||
WECOM_LEAN_TRAINING_JUMP_AGENT_ID = int(os.getenv('WECOM_LEAN_TRAINING_JUMP_AGENT_ID', '16'))
|
||||
WECOM_FEEDBACK_NOTIFY_ENABLED = os.getenv('WECOM_FEEDBACK_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_FEEDBACK_NOTIFY_BASE_URL = os.getenv('WECOM_FEEDBACK_NOTIFY_BASE_URL')
|
||||
WECOM_FEEDBACK_BOT_WEBHOOK = os.getenv('WECOM_FEEDBACK_BOT_WEBHOOK')
|
||||
|
||||
@@ -191,6 +191,15 @@ from app.models.shipping_inventory_preparation import (
|
||||
ShippingInventoryPreparationSourceAttempt,
|
||||
)
|
||||
from app.models.shipping_inventory_mapping import ShippingInventoryMapping
|
||||
from app.models.training import (
|
||||
LeanTrainingCompletion,
|
||||
LeanTrainingReminder,
|
||||
LeanTrainingVideoPushLog,
|
||||
LeanTrainingWeeklyTask,
|
||||
TrainingConfig,
|
||||
TrainingConfigResource,
|
||||
TrainingRecord,
|
||||
)
|
||||
from app.models.in_transit_transfer import (
|
||||
TransferArchive,
|
||||
TransferAttempt,
|
||||
|
||||
@@ -11,7 +11,7 @@ from __future__ import annotations
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import Boolean, Date, DateTime, ForeignKey, Integer, JSON, String, UniqueConstraint
|
||||
from sqlalchemy import Boolean, Date, DateTime, ForeignKey, Integer, JSON, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
@@ -94,3 +94,113 @@ class TrainingConfigResource(Base):
|
||||
config: Mapped[TrainingConfig] = relationship("TrainingConfig", back_populates="resources")
|
||||
agent_guide = relationship("AgentGuide", foreign_keys=[agent_guide_id])
|
||||
kb_document_version = relationship("KbDocumentVersion", foreign_keys=[kb_document_version_id])
|
||||
|
||||
|
||||
class LeanTrainingWeeklyTask(Base):
|
||||
"""
|
||||
精益管理周度培训任务。
|
||||
|
||||
用途:冻结每个自然周由 HR 指定的培训视频集合和受训对象,作为员工完成状态、视频推送与提醒扫描的统一事实源。
|
||||
依赖:TrainingConfigResource、TrainingConfig、User。
|
||||
逻辑:配置页创建或更新任务并设定每周推送数量;员工提交观看与总结时关联本表;
|
||||
视频推送服务按 pushed_video_count 游标每周推进 weekly_count 个,提醒服务只扫描已发布周任务。
|
||||
"""
|
||||
|
||||
__tablename__ = "lean_training_weekly_tasks"
|
||||
__table_args__ = (UniqueConstraint("week_key", name="uq_lean_training_week_key"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
config_id: Mapped[int] = mapped_column(ForeignKey("training_configs.id"), nullable=False, index=True)
|
||||
week_key: Mapped[str] = mapped_column(String(10), nullable=False, index=True)
|
||||
due_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, index=True)
|
||||
video_resource_ids: Mapped[list] = mapped_column(JSON, nullable=False)
|
||||
weekly_count: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default="1")
|
||||
pushed_video_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default="0")
|
||||
target_roles: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
|
||||
target_user_ids: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
|
||||
status: Mapped[str] = mapped_column(String(20), nullable=False, default="published", index=True)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
config: Mapped[TrainingConfig] = relationship("TrainingConfig", foreign_keys=[config_id])
|
||||
push_logs: Mapped[list["LeanTrainingVideoPushLog"]] = relationship(
|
||||
"LeanTrainingVideoPushLog", back_populates="task", cascade="all, delete-orphan", order_by="LeanTrainingVideoPushLog.id.desc()"
|
||||
)
|
||||
|
||||
|
||||
class LeanTrainingVideoPushLog(Base):
|
||||
"""
|
||||
精益管理视频推送日志。
|
||||
|
||||
用途:记录每一轮(每周一排程或 HR 手动)按每周任务数量推送视频的执行结果与失败原因,供管理端展示报错日志。
|
||||
依赖:LeanTrainingWeeklyTask、User。
|
||||
逻辑:推送服务每执行一轮写入一行;推送游标推进后天然幂等,重复触发不会重复推送同一批视频;
|
||||
failed_count>0 时 error_message 保存按用户聚合的失败明细。
|
||||
"""
|
||||
|
||||
__tablename__ = "lean_training_video_push_logs"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
weekly_task_id: Mapped[int] = mapped_column(ForeignKey("lean_training_weekly_tasks.id"), nullable=False, index=True)
|
||||
trigger: Mapped[str] = mapped_column(String(20), nullable=False, default="schedule", index=True)
|
||||
pushed_resource_ids: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
|
||||
pushed_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
recipient_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
sent_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
skipped_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
failed_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
status: Mapped[str] = mapped_column(String(20), nullable=False, default="sent", index=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow, index=True)
|
||||
|
||||
task: Mapped[LeanTrainingWeeklyTask] = relationship("LeanTrainingWeeklyTask", back_populates="push_logs")
|
||||
|
||||
|
||||
class LeanTrainingCompletion(Base):
|
||||
"""
|
||||
精益管理周度学习完成事实。
|
||||
|
||||
用途:保存员工对周度已推送视频的观看时间及不少于 50 字的学习感悟。
|
||||
依赖:LeanTrainingWeeklyTask、User。
|
||||
逻辑:员工只能写入本人的记录;服务端依据视频集合和总结长度判定完成,管理看板与提醒任务读取该事实。
|
||||
"""
|
||||
|
||||
__tablename__ = "lean_training_completions"
|
||||
__table_args__ = (UniqueConstraint("weekly_task_id", "user_id", name="uq_lean_training_task_user"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
weekly_task_id: Mapped[int] = mapped_column(ForeignKey("lean_training_weekly_tasks.id"), nullable=False, index=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False, index=True)
|
||||
watched_at_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
summary_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
summary_char_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
status: Mapped[str] = mapped_column(String(20), nullable=False, default="in_progress", index=True)
|
||||
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
|
||||
class LeanTrainingReminder(Base):
|
||||
"""
|
||||
精益管理提醒发送审计。
|
||||
|
||||
用途:对指派、逾期轮次和班组长定向提醒去重并保留发送结果。
|
||||
依赖:LeanTrainingWeeklyTask、User、企微通知审计 trace_id。
|
||||
逻辑:扫描服务先写 pending 行,再调用企微服务更新最终状态,数据库唯一约束防止重复排程产生重复消息。
|
||||
"""
|
||||
|
||||
__tablename__ = "lean_training_reminders"
|
||||
__table_args__ = (UniqueConstraint("weekly_task_id", "recipient_user_id", "event_key", name="uq_lean_training_reminder_event"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
weekly_task_id: Mapped[int] = mapped_column(ForeignKey("lean_training_weekly_tasks.id"), nullable=False, index=True)
|
||||
recipient_user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False, index=True)
|
||||
event_key: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(20), nullable=False, default="pending", index=True)
|
||||
trace_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
@@ -280,22 +280,24 @@ def _node_paid_date(node: ContractPaymentNode) -> str | None:
|
||||
|
||||
|
||||
def _build_excel(items) -> tuple[bytes, dict[str, object]]:
|
||||
"""生成收件人专属逐笔付款预警明细 Excel。"""
|
||||
"""生成收件人专属逐笔付款预警明细 Excel。
|
||||
|
||||
核心逻辑:按合同/节点逐行输出;「收件人」列写该批次实际收件人姓名,「状态」列写中文,不再输出岗位名称或 pending 英文码。
|
||||
"""
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "付款预警明细"
|
||||
headers = ["合同编号", "采购编号", "供应商", "合同金额", "付款阶段", "付款金额", "比例", "付款日期", "到期日", "预警轮次", "收件岗位", "状态"]
|
||||
headers = ["合同编号", "采购编号", "供应商", "合同金额", "付款阶段", "付款金额", "比例", "付款日期", "到期日", "预警轮次", "收件人", "状态"]
|
||||
ws.append(headers)
|
||||
for cell in ws[1]:
|
||||
cell.font = Font(bold=True)
|
||||
counts = Counter()
|
||||
for alert, contract, node, _user in items:
|
||||
role = _ALERT_RULES[node.node_type][alert.alert_round - 1][1]
|
||||
for alert, contract, node, user in items:
|
||||
ws.append([
|
||||
contract.contract_no or "待解析", contract.purchase_order_no or "—", contract.supplier_name or "—",
|
||||
str(contract.total_amount or ""), _node_label(node.node_type), str(node.amount or ""),
|
||||
str(node.percentage or ""), _node_paid_date(node) or "—", (node.due_date or node.anchor_date).isoformat() if (node.due_date or node.anchor_date) else "—",
|
||||
f"第{alert.alert_round}次", _role_label(role), alert.status,
|
||||
f"第{alert.alert_round}次", _recipient_display_name(user), _alert_status_label(alert.status),
|
||||
])
|
||||
counts[node.node_type] += 1
|
||||
ws.freeze_panes = "A2"
|
||||
@@ -305,6 +307,25 @@ def _build_excel(items) -> tuple[bytes, dict[str, object]]:
|
||||
return output.getvalue(), {"total": len(items), "stages": {_node_label(k): v for k, v in counts.items()}}
|
||||
|
||||
|
||||
def _recipient_display_name(user: User | None) -> str:
|
||||
"""
|
||||
返回 Excel「收件人」列展示的人名。
|
||||
|
||||
核心逻辑:优先真实姓名;姓名为空时回退用户名,避免再写出岗位名称。
|
||||
Args:
|
||||
user: 本行预警对应的系统用户;缺失时写「—」。
|
||||
Returns:
|
||||
去空白后的姓名或用户名;都没有时为「—」。
|
||||
"""
|
||||
if user is None:
|
||||
return "—"
|
||||
name = str(getattr(user, "real_name", None) or "").strip()
|
||||
if name:
|
||||
return name
|
||||
username = str(getattr(user, "username", None) or "").strip()
|
||||
return username or "—"
|
||||
|
||||
|
||||
def _build_summary_message(summary: dict[str, object]) -> str:
|
||||
stages = summary.get("stages") or {}
|
||||
detail = "、".join(f"{key}{value}笔" for key, value in stages.items()) or "无"
|
||||
@@ -464,6 +485,22 @@ def _node_label(node_type: str) -> str:
|
||||
return {"prepayment": "预付款", "shipment": "出货款", "acceptance": "验收款", "warranty": "质保款"}.get(node_type, node_type)
|
||||
|
||||
|
||||
def _role_label(role: str) -> str:
|
||||
"""返回提醒岗位中文名称。"""
|
||||
return {"owner": "采购负责人", "department_head": "采购部负责人", "procurement_leader": "采购分管领导"}.get(role, role)
|
||||
def _alert_status_label(status: str | None) -> str:
|
||||
"""返回预警状态的中文名称,供企微 Excel「状态」列使用。
|
||||
|
||||
核心逻辑:与工作台 alertStatus 口径一致;未知编码原样回写,避免掩盖新增状态。
|
||||
Args:
|
||||
status: 预警记录内部状态码。
|
||||
Returns:
|
||||
中文状态;空值写「—」。
|
||||
"""
|
||||
code = str(status or "").strip().lower()
|
||||
if not code:
|
||||
return "—"
|
||||
return {
|
||||
"pending": "待发送",
|
||||
"sent": "已发送",
|
||||
"failed": "发送失败",
|
||||
"resolved": "已关闭",
|
||||
"sending": "发送中",
|
||||
}.get(code, str(status).strip())
|
||||
@@ -0,0 +1,220 @@
|
||||
"""
|
||||
backend/app/services/contract_payment/ledger_focus.py
|
||||
|
||||
用途:合同台账汇总卡口径——即将到期、逾期未付、待补充、本月应付,均按合同计数。
|
||||
依赖:ContractPaymentContract、ContractPaymentNode、业务时区 Asia/Shanghai。
|
||||
逻辑:由 list/summary API 调用;分类规则与台账行状态标签对齐,本月应付可与前两项重叠。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from datetime import date, datetime
|
||||
from typing import Any, Iterable
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from sqlalchemy.orm import Query, Session
|
||||
from sqlalchemy.sql.expression import false
|
||||
|
||||
from app.models import ContractPaymentContract, ContractPaymentNode
|
||||
|
||||
LEDGER_FOCUS_DUE = "due"
|
||||
LEDGER_FOCUS_OVERDUE = "overdue"
|
||||
LEDGER_FOCUS_NEEDS_COMPLETION = "needs_completion"
|
||||
LEDGER_FOCUS_DUE_THIS_MONTH = "due_this_month"
|
||||
LEDGER_FOCUS_VALUES = {
|
||||
LEDGER_FOCUS_DUE,
|
||||
LEDGER_FOCUS_OVERDUE,
|
||||
LEDGER_FOCUS_NEEDS_COMPLETION,
|
||||
LEDGER_FOCUS_DUE_THIS_MONTH,
|
||||
}
|
||||
_NEAR_DUE_DAYS = 7
|
||||
_SHANGHAI = ZoneInfo("Asia/Shanghai")
|
||||
|
||||
|
||||
def business_today(*, today: date | None = None) -> date:
|
||||
"""
|
||||
返回汇总卡使用的业务日(上海日历)。
|
||||
|
||||
Args:
|
||||
today: 测试注入的业务日;缺省为 Asia/Shanghai 当天。
|
||||
Returns:
|
||||
用于 7 日内到期、逾期和本月判断的日期。
|
||||
"""
|
||||
return today or datetime.now(_SHANGHAI).date()
|
||||
|
||||
|
||||
def node_due_reference(due_date: date | None, anchor_date: date | None) -> date | None:
|
||||
"""
|
||||
付款节点到期判断基准日。
|
||||
|
||||
核心逻辑:与前台 paymentStatus.nodeDueReference 一致,优先 due_date,否则回退 anchor_date。
|
||||
Args:
|
||||
due_date: 节点到期日。
|
||||
anchor_date: 节点锚点日。
|
||||
Returns:
|
||||
可用于比较的日期;两者皆空时为 None。
|
||||
"""
|
||||
return due_date or anchor_date
|
||||
|
||||
|
||||
def classify_ledger_status(
|
||||
*,
|
||||
contract_status: str | None,
|
||||
parse_status: str | None,
|
||||
nodes: Iterable[dict[str, Any]],
|
||||
today: date,
|
||||
) -> str:
|
||||
"""
|
||||
按合同聚合出台账状态,与列表「状态」列一致。
|
||||
|
||||
核心逻辑:非激活或待确认 → 待补充;无进行中节点则按是否已付分为已完成/待补充;
|
||||
进行中节点若已过到期日 → 逾期,若在今天起 7 天内 → 即将到期,否则进行中。
|
||||
Args:
|
||||
contract_status: 合同主状态。
|
||||
parse_status: 解析状态。
|
||||
nodes: 轻量节点 dict,含 status / due_date / anchor_date / paid_at。
|
||||
today: 业务日。
|
||||
Returns:
|
||||
overdue / due / active / completed / needs_completion。
|
||||
"""
|
||||
node_list = list(nodes)
|
||||
if str(contract_status or "").strip() != "active" or str(parse_status or "").strip() == "needs_review":
|
||||
return LEDGER_FOCUS_NEEDS_COMPLETION
|
||||
if not node_list:
|
||||
return LEDGER_FOCUS_NEEDS_COMPLETION
|
||||
active = [node for node in node_list if str(node.get("status") or "").strip().lower() == "active"]
|
||||
if not active:
|
||||
has_paid = any(
|
||||
str(node.get("status") or "").strip().lower() == "paid" or bool(node.get("paid_at"))
|
||||
for node in node_list
|
||||
)
|
||||
return "completed" if has_paid else LEDGER_FOCUS_NEEDS_COMPLETION
|
||||
refs = [
|
||||
ref
|
||||
for node in active
|
||||
if (ref := node_due_reference(node.get("due_date"), node.get("anchor_date")))
|
||||
]
|
||||
if any((ref - today).days < 0 for ref in refs):
|
||||
return LEDGER_FOCUS_OVERDUE
|
||||
if any(0 <= (ref - today).days <= _NEAR_DUE_DAYS for ref in refs):
|
||||
return LEDGER_FOCUS_DUE
|
||||
return "active"
|
||||
|
||||
|
||||
def has_unpaid_due_this_month(nodes: Iterable[dict[str, Any]], today: date) -> bool:
|
||||
"""
|
||||
合同是否有未付节点的到期日落在本自然月。
|
||||
|
||||
核心逻辑:只看 status=active 的节点;月份按 today 所在自然月(含 today 所在月的逾期节点)。
|
||||
Args:
|
||||
nodes: 轻量节点 dict。
|
||||
today: 业务日,用于确定自然月。
|
||||
Returns:
|
||||
存在本月未付到期节点时为 True。
|
||||
"""
|
||||
month_start = today.replace(day=1)
|
||||
month_end = date(today.year + 1, 1, 1) if today.month == 12 else date(today.year, today.month + 1, 1)
|
||||
for node in nodes:
|
||||
if str(node.get("status") or "").strip().lower() != "active":
|
||||
continue
|
||||
ref = node_due_reference(node.get("due_date"), node.get("anchor_date"))
|
||||
if ref and month_start <= ref < month_end:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _node_payload(node: ContractPaymentNode) -> dict[str, Any]:
|
||||
"""把 ORM 节点收成分类所需的轻量字段。"""
|
||||
return {
|
||||
"status": node.status,
|
||||
"due_date": node.due_date,
|
||||
"anchor_date": node.anchor_date,
|
||||
"paid_at": (node.evidence_json or {}).get("paid_at"),
|
||||
}
|
||||
|
||||
|
||||
def collect_ledger_focus(*, session: Session, today: date | None = None) -> dict[str, set[int]]:
|
||||
"""
|
||||
扫描全部已解析台账合同,按汇总卡口径收集合同 ID。
|
||||
|
||||
核心逻辑:不应用页面 keyword;待确认合同不进入台账汇总。本月应付可与即将到期/逾期重叠。
|
||||
Args:
|
||||
session: 当前请求的 SQLAlchemy 会话。
|
||||
today: 可选业务日。
|
||||
Returns:
|
||||
四个 focus 键到合同 ID 集合的映射。
|
||||
"""
|
||||
as_of = business_today(today=today)
|
||||
contracts = (
|
||||
session.query(ContractPaymentContract.id, ContractPaymentContract.status, ContractPaymentContract.parse_status)
|
||||
.filter(ContractPaymentContract.parse_status == "parsed")
|
||||
.all()
|
||||
)
|
||||
buckets: dict[str, set[int]] = {
|
||||
LEDGER_FOCUS_DUE: set(),
|
||||
LEDGER_FOCUS_OVERDUE: set(),
|
||||
LEDGER_FOCUS_NEEDS_COMPLETION: set(),
|
||||
LEDGER_FOCUS_DUE_THIS_MONTH: set(),
|
||||
}
|
||||
if not contracts:
|
||||
return buckets
|
||||
contract_ids = [row.id for row in contracts]
|
||||
nodes_by_contract: dict[int, list[dict[str, Any]]] = defaultdict(list)
|
||||
node_rows = (
|
||||
session.query(ContractPaymentNode)
|
||||
.filter(ContractPaymentNode.contract_id.in_(contract_ids))
|
||||
.all()
|
||||
)
|
||||
for node in node_rows:
|
||||
nodes_by_contract[node.contract_id].append(_node_payload(node))
|
||||
for row in contracts:
|
||||
nodes = nodes_by_contract.get(row.id, [])
|
||||
status = classify_ledger_status(
|
||||
contract_status=row.status,
|
||||
parse_status=row.parse_status,
|
||||
nodes=nodes,
|
||||
today=as_of,
|
||||
)
|
||||
if status == LEDGER_FOCUS_DUE:
|
||||
buckets[LEDGER_FOCUS_DUE].add(row.id)
|
||||
elif status == LEDGER_FOCUS_OVERDUE:
|
||||
buckets[LEDGER_FOCUS_OVERDUE].add(row.id)
|
||||
elif status == LEDGER_FOCUS_NEEDS_COMPLETION:
|
||||
buckets[LEDGER_FOCUS_NEEDS_COMPLETION].add(row.id)
|
||||
if has_unpaid_due_this_month(nodes, as_of):
|
||||
buckets[LEDGER_FOCUS_DUE_THIS_MONTH].add(row.id)
|
||||
return buckets
|
||||
|
||||
|
||||
def ledger_focus_counts(*, session: Session, today: date | None = None) -> dict[str, int]:
|
||||
"""
|
||||
返回四张汇总卡的合同份数。
|
||||
|
||||
Args:
|
||||
session: 当前请求的 SQLAlchemy 会话。
|
||||
today: 可选业务日。
|
||||
Returns:
|
||||
due / overdue / needs_completion / due_this_month 的计数。
|
||||
"""
|
||||
buckets = collect_ledger_focus(session=session, today=today)
|
||||
return {key: len(ids) for key, ids in buckets.items()}
|
||||
|
||||
|
||||
def apply_ledger_focus(query: Query, focus: str, *, session: Session, today: date | None = None) -> Query:
|
||||
"""
|
||||
按汇总卡口径把台账查询限制到对应合同 ID。
|
||||
|
||||
核心逻辑:空集合时强制无结果,避免 SQL IN () 退化成不过滤。
|
||||
Args:
|
||||
query: 已按解析状态/关键词过滤的合同查询。
|
||||
focus: 四个合法口径之一。
|
||||
session: 当前请求的 SQLAlchemy 会话。
|
||||
today: 可选业务日。
|
||||
Returns:
|
||||
叠加 ID 过滤后的查询。
|
||||
"""
|
||||
ids = collect_ledger_focus(session=session, today=today).get(focus) or set()
|
||||
if not ids:
|
||||
return query.filter(false())
|
||||
return query.filter(ContractPaymentContract.id.in_(ids))
|
||||
@@ -0,0 +1,213 @@
|
||||
"""
|
||||
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 便于管理端查看失败明细;
|
||||
排程入口每周一 09:00 先自动滚动创建当周任务(复制最近一期配置,无需人工维护),再对各任务推进一批推送。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import LeanTrainingVideoPushLog, LeanTrainingWeeklyTask, User
|
||||
from app.services.lean_training_reminder_service import (
|
||||
_send_reminder,
|
||||
notify_overdue_users_after_push,
|
||||
send_initial_target_notifications,
|
||||
)
|
||||
from app.services.lean_training_service import _current_week_bounds, target_user_ids_for_task
|
||||
from app.services.schedule.timezone_util import utc_now_naive
|
||||
|
||||
VIDEO_PUSH_EVENT_TYPE = "training_lean_video_push"
|
||||
|
||||
|
||||
def ensure_current_week_task(*, now: datetime | None = None) -> LeanTrainingWeeklyTask | None:
|
||||
"""
|
||||
每周自动滚动:当周任务不存在时,以最近一期已发布任务为模板自动创建当周任务(无需人工维护)。
|
||||
|
||||
Args:
|
||||
now: 覆盖当前时间(UTC naive,测试用)。
|
||||
Returns:
|
||||
当周任务(已存在或新建);系统内尚无任何历史任务模板时返回 None,等待管理员手动发布。
|
||||
业务约束:
|
||||
- 任务周=当周周一、截止时间=当周周日 23:59:59(服务端计算,每周自动更新);
|
||||
- 模板仅从"严格早于当周"的最近一期已发布任务选取:任务周已支持管理员指定任意自然周,
|
||||
必须排除未来周任务,避免其(更大游标/不同配置)污染当周滚动进度;
|
||||
- 模板复制视频冻结列表、每周推送数量与受训对象;推送游标继承模板进度,
|
||||
保证"推过的视频不重复推",跨周按视频列表顺序连续推进直至全部推完。
|
||||
"""
|
||||
week_start, due_at = _current_week_bounds(now)
|
||||
week_key = week_start.isoformat()
|
||||
existing = db.session.execute(select(LeanTrainingWeeklyTask).where(LeanTrainingWeeklyTask.week_key == week_key)).scalar_one_or_none()
|
||||
if existing:
|
||||
return existing
|
||||
template = db.session.execute(
|
||||
select(LeanTrainingWeeklyTask)
|
||||
.where(LeanTrainingWeeklyTask.status == "published", LeanTrainingWeeklyTask.week_key < week_key)
|
||||
.order_by(LeanTrainingWeeklyTask.week_key.desc())
|
||||
).scalars().first()
|
||||
if not template:
|
||||
return None
|
||||
# [STEP 1] 复制最近一期配置滚动创建当周任务(视频列表沿用冻结顺序,游标继承已推送进度避免重复推送)
|
||||
task = LeanTrainingWeeklyTask(
|
||||
config_id=template.config_id,
|
||||
week_key=week_key,
|
||||
created_by_id=template.created_by_id,
|
||||
weekly_count=template.weekly_count,
|
||||
pushed_video_count=template.pushed_video_count,
|
||||
due_at=due_at,
|
||||
video_resource_ids=list(template.video_resource_ids or []),
|
||||
target_roles=list(template.target_roles or []),
|
||||
target_user_ids=list(template.target_user_ids or []),
|
||||
status="published",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
# [STEP 2] 同步发送任务发布通知(幂等),受训员工发布后立即可学
|
||||
send_initial_target_notifications(task.id, now=now)
|
||||
return task
|
||||
|
||||
|
||||
def pending_video_ids(task: LeanTrainingWeeklyTask) -> list[int]:
|
||||
"""返回当前任务尚未推送的视频 ID 列表(保持选择顺序,供游标推进与耗尽判断使用)。"""
|
||||
return list(task.video_resource_ids or [])[task.pushed_video_count:]
|
||||
|
||||
|
||||
def serialize_push_log(log: LeanTrainingVideoPushLog) -> dict[str, object]:
|
||||
"""序列化推送日志,供管理端展示每轮推送的批次、数量与失败原因。"""
|
||||
return {
|
||||
"id": log.id,
|
||||
"weekly_task_id": log.weekly_task_id,
|
||||
"trigger": log.trigger,
|
||||
"pushed_resource_ids": list(log.pushed_resource_ids or []),
|
||||
"pushed_count": log.pushed_count,
|
||||
"recipient_count": log.recipient_count,
|
||||
"sent_count": log.sent_count,
|
||||
"skipped_count": log.skipped_count,
|
||||
"failed_count": log.failed_count,
|
||||
"status": log.status,
|
||||
"error_message": log.error_message,
|
||||
"created_by_id": log.created_by_id,
|
||||
"created_at": log.created_at.isoformat() if log.created_at else None,
|
||||
}
|
||||
|
||||
|
||||
def list_push_logs(task_id: int, *, limit: int = 50) -> list[dict[str, object]]:
|
||||
"""按时间倒序返回指定周任务的推送日志,供管理端"推送记录"区块展示。"""
|
||||
logs = db.session.execute(
|
||||
select(LeanTrainingVideoPushLog)
|
||||
.where(LeanTrainingVideoPushLog.weekly_task_id == task_id)
|
||||
.order_by(LeanTrainingVideoPushLog.id.desc())
|
||||
.limit(limit)
|
||||
).scalars().all()
|
||||
return [serialize_push_log(log) for log in logs]
|
||||
|
||||
|
||||
def push_lean_training_videos(
|
||||
task_id: int,
|
||||
*,
|
||||
trigger: str = "schedule",
|
||||
current_user_id: int | None = None,
|
||||
now: datetime | None = None,
|
||||
) -> dict[str, object]:
|
||||
"""
|
||||
推送下一批精益培训视频(数量=weekly_count)并写推送日志。
|
||||
|
||||
Args:
|
||||
task_id: 精益周任务 ID,必须为已发布状态。
|
||||
trigger: 推送来源,publish=发布任务立即推首批 / schedule=每周一排程 / manual=管理端手动推送。
|
||||
current_user_id: 手动推送时的操作人,写入日志审计。
|
||||
now: 覆盖当前时间(测试用)。
|
||||
|
||||
Returns:
|
||||
含 status(completed=无待推视频/partial/failed/sent)、batch、counts 与日志字段的 dict。
|
||||
业务约束:企微发送失败不影响游标前进(员工端已可见视频),失败明细仅记录在日志中。
|
||||
"""
|
||||
task = db.session.get(LeanTrainingWeeklyTask, task_id)
|
||||
if not task or task.status != "published":
|
||||
raise ValueError("Lean training weekly task not found")
|
||||
current = now or utc_now_naive()
|
||||
# [STEP 1] 计算本批视频:按选择顺序从游标起取 weekly_count 个;无待推视频时视为全部推送完
|
||||
batch = pending_video_ids(task)[: task.weekly_count]
|
||||
if not batch:
|
||||
return {"status": "completed", "message": "all videos pushed", "pushed_count": 0}
|
||||
start_index = task.pushed_video_count
|
||||
event_key = f"video-push-{start_index}-{start_index + len(batch)}"
|
||||
# [STEP 2] 面向全体在职受训对象发送企微通知;event_key 按批次区间幂等,同批重推不重复打扰
|
||||
recipients = db.session.execute(
|
||||
select(User).where(User.id.in_(target_user_ids_for_task(task)), User.status == "active")
|
||||
).scalars().all()
|
||||
counts = {"sent": 0, "skipped": 0, "failed": 0}
|
||||
failure_details: list[str] = []
|
||||
for recipient in recipients:
|
||||
result = _send_reminder(
|
||||
task=task,
|
||||
recipient=recipient,
|
||||
event_key=event_key,
|
||||
event_type=VIDEO_PUSH_EVENT_TYPE,
|
||||
title="精益管理培训视频推送",
|
||||
content=f"本周精益管理培训已更新,请观看 {len(batch)} 个新视频并提交不少于50字的学习感悟。",
|
||||
current=current,
|
||||
)
|
||||
counts[result] = counts.get(result, 0) + 1
|
||||
if result == "failed" and recipient.id not in {line.split(":")[0] for line in failure_details}:
|
||||
failure_details.append(f"{recipient.id}:{recipient.real_name or recipient.username}")
|
||||
# [STEP 3] 游标前进(企微失败不回退,员工端已可见该批视频),并落盘本轮推送日志
|
||||
task.pushed_video_count = start_index + len(batch)
|
||||
status = "sent" if counts["failed"] == 0 else ("failed" if counts["sent"] == 0 and counts["skipped"] == 0 else "partial")
|
||||
log = LeanTrainingVideoPushLog(
|
||||
weekly_task_id=task.id,
|
||||
trigger=trigger,
|
||||
pushed_resource_ids=batch,
|
||||
pushed_count=len(batch),
|
||||
recipient_count=len(recipients),
|
||||
sent_count=counts["sent"],
|
||||
skipped_count=counts["skipped"],
|
||||
failed_count=counts["failed"],
|
||||
status=status,
|
||||
error_message=";".join(failure_details)[:2000] if failure_details else None,
|
||||
created_by_id=current_user_id,
|
||||
)
|
||||
db.session.add(log)
|
||||
db.session.commit()
|
||||
# [STEP 4] 消息推送规则:本批推送成功后立马对任务中"已延期"(过截止未提交)的受训人员发送企微提醒
|
||||
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)
|
||||
|
||||
|
||||
def run_lean_training_video_push(*, now: datetime | None = None) -> dict[str, object]:
|
||||
"""
|
||||
排程入口(每周一 09:00):先自动滚动创建当周任务(无需人工维护),再对当周任务推进一批视频推送。
|
||||
|
||||
业务约束:
|
||||
- 仅推进当周任务,保证"视频列表顺序分批、跨周连续、不重复推"的单一进度线;
|
||||
- 历史任务不再由排程推进,其补推由管理端手动触发(立即新增任务补推);
|
||||
- 系统内尚无任务模板时无事可做,返回 completed 汇总。
|
||||
"""
|
||||
current = now or utc_now_naive()
|
||||
week_task = ensure_current_week_task(now=current)
|
||||
if week_task is None:
|
||||
return {"tasks": 0, "pushed": 0, "sent": 0, "skipped": 0, "failed": 0, "completed": 1, "task_results": []}
|
||||
result = push_lean_training_videos(week_task.id, trigger="schedule", now=current)
|
||||
if result.get("status") == "completed":
|
||||
return {"tasks": 1, "pushed": 0, "sent": 0, "skipped": 0, "failed": 0, "completed": 1, "task_results": []}
|
||||
return {
|
||||
"tasks": 1,
|
||||
"pushed": int(result.get("pushed_count") or 0),
|
||||
"sent": int(result.get("sent_count") or 0),
|
||||
"skipped": int(result.get("skipped_count") or 0),
|
||||
"failed": int(result.get("failed_count") or 0),
|
||||
"completed": 0,
|
||||
"task_results": [result],
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
"""
|
||||
backend/app/services/lean_training_reminder_service.py
|
||||
|
||||
用途:执行精益管理周度培训的企微提醒生成与发送。
|
||||
依赖:精益培训任务/完成/提醒模型、User、wecom_notify。
|
||||
逻辑:排程按周日截止、周一/周三/周五催学规则写入幂等提醒,再由统一企微服务发送并落审计。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import LeanTrainingCompletion, LeanTrainingReminder, LeanTrainingWeeklyTask, User
|
||||
from app.services.lean_training_service import target_user_ids_for_task
|
||||
from app.services.wecom_notify import send_wecom_event_message
|
||||
from app.services.schedule.timezone_util import resolve_schedule_tzinfo, utc_now_naive
|
||||
|
||||
|
||||
def _send_reminder(
|
||||
*,
|
||||
task: LeanTrainingWeeklyTask,
|
||||
recipient: User,
|
||||
event_key: str,
|
||||
event_type: str,
|
||||
title: str,
|
||||
content: str,
|
||||
current: datetime,
|
||||
) -> str:
|
||||
reminder = db.session.execute(
|
||||
select(LeanTrainingReminder).where(
|
||||
LeanTrainingReminder.weekly_task_id == task.id,
|
||||
LeanTrainingReminder.recipient_user_id == recipient.id,
|
||||
LeanTrainingReminder.event_key == event_key,
|
||||
)
|
||||
).scalar_one_or_none()
|
||||
if reminder:
|
||||
return "skipped"
|
||||
reminder = LeanTrainingReminder(
|
||||
weekly_task_id=task.id,
|
||||
recipient_user_id=recipient.id,
|
||||
event_key=event_key,
|
||||
)
|
||||
try:
|
||||
with db.session.begin_nested():
|
||||
db.session.add(reminder)
|
||||
db.session.flush()
|
||||
except IntegrityError:
|
||||
return "skipped"
|
||||
# [STEP] 企微卡片跳转地址:指向员工培训聊天页(agent 16),由前端消费 training_type=lean_management
|
||||
# 自动展开精益页签;agent id 走配置,便于多环境调整,避免硬编码。
|
||||
jump_agent_id = int(current_app.config.get("WECOM_LEAN_TRAINING_JUMP_AGENT_ID") or 16)
|
||||
result = send_wecom_event_message(
|
||||
event_type=event_type,
|
||||
user=recipient,
|
||||
title=title,
|
||||
content=content,
|
||||
jump_path=f"/chat/{jump_agent_id}",
|
||||
jump_params={"training_type": "lean_management", "weekly_task_id": task.id},
|
||||
)
|
||||
reminder.trace_id = result.get("trace_id")
|
||||
if result.get("ok"):
|
||||
reminder.status = "sent"
|
||||
reminder.sent_at = current
|
||||
return "sent"
|
||||
reminder.status = "skipped" if result.get("reason") in {"event_disabled", "notify_disabled", "user_unbound"} else "failed"
|
||||
reminder.error_message = str(result.get("reason") or "send_failed")[:255]
|
||||
return reminder.status
|
||||
|
||||
|
||||
def send_initial_target_notifications(task_id: int, *, now: datetime | None = None) -> dict[str, int]:
|
||||
"""向 HR 指定的在职受训对象发送任务发布提醒,审计唯一键保证重复发布不重复推送。"""
|
||||
task = db.session.get(LeanTrainingWeeklyTask, task_id)
|
||||
if not task or task.status != "published":
|
||||
return {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
|
||||
current = now or utc_now_naive()
|
||||
totals = {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
|
||||
recipients = db.session.execute(select(User).where(User.id.in_(target_user_ids_for_task(task)))).scalars().all()
|
||||
for recipient in recipients:
|
||||
result = _send_reminder(
|
||||
task=task,
|
||||
recipient=recipient,
|
||||
event_key="task-initial",
|
||||
event_type="training_lean_task_initial",
|
||||
title="精益管理培训任务已发布",
|
||||
content="您已被指定参加本周精益管理培训,请观看指定视频并提交不少于50字的学习感悟。",
|
||||
current=current,
|
||||
)
|
||||
totals["created"] += result != "skipped"
|
||||
totals[result] += 1
|
||||
db.session.commit()
|
||||
return totals
|
||||
|
||||
|
||||
def send_targeted_reminders(task_id: int, user_ids: list[int], *, now: datetime | None = None) -> dict[str, int]:
|
||||
"""由 HR 对本周指定且尚未完成的员工发起定向提醒,不允许跨任务对象发送。"""
|
||||
task = db.session.get(LeanTrainingWeeklyTask, task_id)
|
||||
if not task or task.status != "published":
|
||||
raise ValueError("Lean training weekly task not found")
|
||||
current = now or utc_now_naive()
|
||||
completed_user_ids = set(
|
||||
db.session.execute(
|
||||
select(LeanTrainingCompletion.user_id).where(
|
||||
LeanTrainingCompletion.weekly_task_id == task.id,
|
||||
LeanTrainingCompletion.status == "completed",
|
||||
)
|
||||
).scalars()
|
||||
)
|
||||
recipients = db.session.execute(
|
||||
select(User).where(User.id.in_(user_ids), User.status == "active")
|
||||
).scalars().all()
|
||||
recipients_by_id = {recipient.id: recipient for recipient in recipients}
|
||||
unavailable_ids = sorted(set(user_ids) - set(recipients_by_id))
|
||||
if unavailable_ids:
|
||||
raise ValueError("Some reminder recipients are unavailable")
|
||||
forbidden_ids = sorted(set(user_ids) - target_user_ids_for_task(task))
|
||||
if forbidden_ids:
|
||||
raise ValueError("Some reminder recipients are outside the task target")
|
||||
totals = {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
|
||||
for recipient in recipients:
|
||||
if recipient.id in completed_user_ids:
|
||||
totals["skipped"] += 1
|
||||
continue
|
||||
result = _send_reminder(
|
||||
task=task,
|
||||
recipient=recipient,
|
||||
event_key=f"targeted-{uuid.uuid4().hex}",
|
||||
event_type="training_lean_targeted_reminder",
|
||||
title="精益管理培训定向提醒",
|
||||
content="您尚未完成本周精益管理培训,请观看指定视频并提交不少于50字的学习感悟。",
|
||||
current=current,
|
||||
)
|
||||
totals["created"] += result != "skipped"
|
||||
totals[result] += 1
|
||||
db.session.commit()
|
||||
return totals
|
||||
|
||||
|
||||
def notify_overdue_users_after_push(
|
||||
task: LeanTrainingWeeklyTask,
|
||||
*,
|
||||
event_key: str,
|
||||
current: datetime | None = None,
|
||||
) -> dict[str, int]:
|
||||
"""
|
||||
视频批次推送成功后,立即对该任务中"已延期"(已过截止时间且未提交感悟)的受训人员发送企微提醒。
|
||||
|
||||
对应周任务消息推送规则:每次推送周任务成功后立马推送延期提醒(与批次 event_key 绑定幂等,同批重推不重复打扰)。
|
||||
|
||||
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:
|
||||
return totals
|
||||
completed_user_ids = set(
|
||||
db.session.execute(
|
||||
select(LeanTrainingCompletion.user_id).where(
|
||||
LeanTrainingCompletion.weekly_task_id == task.id,
|
||||
LeanTrainingCompletion.status == "completed",
|
||||
)
|
||||
).scalars()
|
||||
)
|
||||
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 []
|
||||
for user in users:
|
||||
result = _send_reminder(
|
||||
task=task,
|
||||
recipient=user,
|
||||
event_key=event_key,
|
||||
event_type="training_lean_overdue",
|
||||
title="精益管理培训延期提醒",
|
||||
content="您本周精益管理培训已延期,尚未完成视频观看与学习感悟提交,请尽快完成。",
|
||||
current=now,
|
||||
)
|
||||
totals["created"] += result != "skipped"
|
||||
totals[result] += 1
|
||||
db.session.commit()
|
||||
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]:
|
||||
"""扫描未完成人员并发送本轮提醒,重复运行由唯一约束确保不重复推送。"""
|
||||
current = now or utc_now_naive()
|
||||
tasks = db.session.execute(select(LeanTrainingWeeklyTask).where(LeanTrainingWeeklyTask.status == "published")).scalars().all()
|
||||
created = sent = skipped = failed = 0
|
||||
for task in tasks:
|
||||
event_key = _event_key(task, current)
|
||||
if not event_key:
|
||||
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
|
||||
db.session.commit()
|
||||
return {"created": created, "sent": sent, "skipped": skipped, "failed": failed}
|
||||
@@ -0,0 +1,41 @@
|
||||
"""
|
||||
backend/app/services/lean_training_schedule_seed.py
|
||||
|
||||
用途:幂等创建精益培训默认排程(每日逾期提醒扫描 + 每周一 09:00 视频推送)。
|
||||
依赖:ScheduleTask、User、上海时区 next_run 计算。
|
||||
逻辑:应用启动时在存在管理员和排程表后创建两个默认任务,管理员可在排程中心停用或调整。
|
||||
"""
|
||||
|
||||
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
|
||||
|
||||
|
||||
def ensure_default_lean_training_schedule(*, commit: bool = True) -> list[ScheduleTask]:
|
||||
"""幂等创建精益培训默认排程:每日 09:00 提醒扫描 + 每周一 09:00 视频推送。"""
|
||||
owner = db.session.query(User).filter(User.role == "admin").order_by(User.id.asc()).first()
|
||||
if not owner:
|
||||
return []
|
||||
now = datetime.utcnow()
|
||||
created: list[ScheduleTask] = []
|
||||
# [STEP 1] 每日逾期提醒扫描(既有)
|
||||
if not db.session.query(ScheduleTask).filter_by(schedule_no="SCH-LEAN-TRAINING-REMINDER").first():
|
||||
task = ScheduleTask(schedule_no="SCH-LEAN-TRAINING-REMINDER", name="精益管理培训逾期提醒", schedule_type="platform_job", owner_user_id=owner.id, cron_expr="0 9 * * *", schedule_timezone="Asia/Shanghai", platform_api_path="lean-training-reminder", job_params={}, kb_sync_enabled=False, notify_user_ids_json=[], notify_enabled=False, enabled=True, next_run_at=compute_next_run_at("0 9 * * *", 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)
|
||||
# [STEP 2] 每周一 09:00 按"每周任务数量"推送精益培训视频(新增)
|
||||
if not db.session.query(ScheduleTask).filter_by(schedule_no="SCH-LEAN-TRAINING-VIDEO-PUSH").first():
|
||||
task = ScheduleTask(schedule_no="SCH-LEAN-TRAINING-VIDEO-PUSH", name="精益管理培训视频推送", schedule_type="platform_job", owner_user_id=owner.id, cron_expr="0 9 * * 1", schedule_timezone="Asia/Shanghai", platform_api_path="lean-training-video-push", job_params={}, kb_sync_enabled=False, notify_user_ids_json=[], notify_enabled=False, enabled=True, next_run_at=compute_next_run_at("0 9 * * 1", 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 not created:
|
||||
return []
|
||||
if commit:
|
||||
db.session.commit()
|
||||
else:
|
||||
db.session.flush()
|
||||
return created
|
||||
@@ -0,0 +1,443 @@
|
||||
"""
|
||||
backend/app/services/lean_training_service.py
|
||||
|
||||
用途:精益管理培训的周任务、员工提交、看板和提醒规则服务。
|
||||
依赖:TrainingConfig/Resource、精益培训模型、User、统一 ValidationError。
|
||||
逻辑:管理端冻结每周视频列表、每周推送数量与受训对象;员工仅对已推送批次提交观看事实与学习感悟;
|
||||
服务端按 50 字门槛判定完成,管理看板只读取已授权范围。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, time, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func, or_, select
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
LeanTrainingCompletion,
|
||||
LeanTrainingWeeklyTask,
|
||||
TrainingConfig,
|
||||
TrainingConfigResource,
|
||||
User,
|
||||
)
|
||||
from app.services.minio_service import minio_service
|
||||
from app.services.schedule.timezone_util import resolve_schedule_tzinfo, to_utc_naive, utc_now_naive
|
||||
|
||||
LEAN_TRAINING_TYPE = "lean_management"
|
||||
MIN_SUMMARY_LENGTH = 50
|
||||
|
||||
|
||||
def _get_lean_config() -> TrainingConfig:
|
||||
"""读取已发布精益培训配置,未配置时阻止创建周任务。"""
|
||||
config = db.session.execute(
|
||||
select(TrainingConfig).where(
|
||||
TrainingConfig.training_type == LEAN_TRAINING_TYPE,
|
||||
TrainingConfig.status == "published",
|
||||
).order_by(TrainingConfig.id.desc())
|
||||
).scalars().first()
|
||||
if not config:
|
||||
raise ValidationError("Lean training published config is required")
|
||||
return config
|
||||
|
||||
|
||||
def _current_week_bounds(now: datetime | None = None) -> tuple[date, datetime]:
|
||||
"""
|
||||
计算当周任务边界(Asia/Shanghai):任务周=当周周一,截止时间=当周周日 23:59:59。
|
||||
|
||||
Args:
|
||||
now: 覆盖当前时间(UTC naive,测试用);缺省取当前 UTC 时间。
|
||||
Returns:
|
||||
(week_start, due_at_utc):week_start 为周一日期(ISO week_key),due_at_utc 为转 UTC 后的 naive 截止时间。
|
||||
业务约束:任务周与截止时间由服务端强制计算,客户端只读不可修改,每周自动滚动更新。
|
||||
"""
|
||||
shanghai_tz = resolve_schedule_tzinfo("Asia/Shanghai")
|
||||
current = now or utc_now_naive()
|
||||
local_now = current.replace(tzinfo=timezone.utc).astimezone(shanghai_tz)
|
||||
week_start = local_now.date() - timedelta(days=local_now.weekday())
|
||||
due_local = datetime.combine(week_start + timedelta(days=6), time(23, 59, 59), tzinfo=shanghai_tz)
|
||||
return week_start, to_utc_naive(due_local)
|
||||
|
||||
|
||||
def week_index_for_task(task: LeanTrainingWeeklyTask) -> int:
|
||||
"""返回任务期号:按 week_key 升序编号,最早一周为第 1 期(供前端展示"第N周")。"""
|
||||
earlier_count = db.session.execute(
|
||||
select(func.count(LeanTrainingWeeklyTask.id)).where(LeanTrainingWeeklyTask.week_key < task.week_key)
|
||||
).scalar() or 0
|
||||
return int(earlier_count) + 1
|
||||
|
||||
|
||||
def _normalize_video_ids(value: Any, config: TrainingConfig) -> list[int]:
|
||||
"""
|
||||
校验周任务绑定的视频资源并返回冻结顺序列表。
|
||||
|
||||
Args:
|
||||
value: 管理端提交的 video_resource_ids;为 None/空列表时按新规则自动填充。
|
||||
config: 已发布的精益培训配置,仅其下视频类型资源可选。
|
||||
Returns:
|
||||
去重后的视频资源 ID 顺序列表(即每周分批推送顺序)。
|
||||
业务约束:
|
||||
- 显式选择时按选择顺序冻结(每周按此顺序分批推送);
|
||||
- 未选择时自动按资源上传时间倒序冻结全部视频(对应"发布周任务按上传时间倒序推送"规则);
|
||||
- 推过的视频不能重复推:由推送游标(pushed_video_count)保证,直至全部视频推完。
|
||||
"""
|
||||
video_resources = [
|
||||
resource for resource in config.resources
|
||||
if resource.resource_type == "agent_guide" and resource.agent_guide and str(resource.agent_guide.file_type or "").lower().startswith("video")
|
||||
]
|
||||
# [RULE] 管理端未显式勾选视频时,按上传时间倒序自动冻结全部视频,满足"直至全部上传视频推送完"
|
||||
if not isinstance(value, list) or len(value) == 0:
|
||||
if value is not None and not isinstance(value, list):
|
||||
raise ValidationError("video_resource_ids must be a list", details={"field": "video_resource_ids"})
|
||||
ordered = sorted(video_resources, key=lambda resource: resource.created_at or datetime.min, reverse=True)
|
||||
if not ordered:
|
||||
raise ValidationError("At least one lean training video is required", details={"field": "video_resource_ids"})
|
||||
return [resource.id for resource in ordered]
|
||||
if len({str(item) for item in value}) != len(value):
|
||||
raise ValidationError("video_resource_ids contains duplicate items", details={"field": "video_resource_ids"})
|
||||
resource_map = {resource.id: resource for resource in video_resources}
|
||||
ids: list[int] = []
|
||||
for item in value:
|
||||
try:
|
||||
resource_id = int(item)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError("video_resource_ids contains invalid resource", details={"field": "video_resource_ids"}) from exc
|
||||
if resource_id not in resource_map:
|
||||
raise ValidationError("Selected resource is not a lean training video")
|
||||
ids.append(resource_id)
|
||||
return ids
|
||||
|
||||
|
||||
def _normalize_target_roles(value: Any) -> list[str]:
|
||||
"""校验 HR 按角色指定的精益周任务对象,角色值必须为非空且去重的系统角色。"""
|
||||
if value is None:
|
||||
return []
|
||||
if not isinstance(value, list):
|
||||
raise ValidationError("target_roles must be a list", details={"field": "target_roles"})
|
||||
roles = sorted({str(item).strip() for item in value if str(item).strip()})
|
||||
if len(roles) != len({str(item).strip() for item in value}):
|
||||
raise ValidationError("target_roles contains invalid role", details={"field": "target_roles"})
|
||||
return roles
|
||||
|
||||
|
||||
def _normalize_target_user_ids(value: Any) -> list[int]:
|
||||
"""校验 HR 指定的精益周任务对象,所有用户必须为在职系统用户。"""
|
||||
if value is None:
|
||||
return []
|
||||
if not isinstance(value, list):
|
||||
raise ValidationError("target_user_ids must be a list", details={"field": "target_user_ids"})
|
||||
try:
|
||||
user_ids = sorted({int(item) for item in value})
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError("target_user_ids contains invalid user", details={"field": "target_user_ids"}) from exc
|
||||
if any(user_id <= 0 for user_id in user_ids):
|
||||
raise ValidationError("target_user_ids contains invalid user", details={"field": "target_user_ids"})
|
||||
found_ids = set(db.session.execute(select(User.id).where(User.id.in_(user_ids), User.status == "active")).scalars()) if user_ids else set()
|
||||
if found_ids != set(user_ids):
|
||||
raise ValidationError("target_user_ids contains unavailable user", details={"field": "target_user_ids"})
|
||||
return user_ids
|
||||
|
||||
|
||||
def target_user_ids_for_task(task: LeanTrainingWeeklyTask) -> set[int]:
|
||||
"""返回周任务的在职受训对象,角色和用户指定对象按并集处理。"""
|
||||
predicates = []
|
||||
if task.target_user_ids:
|
||||
predicates.append(User.id.in_(list(task.target_user_ids)))
|
||||
if task.target_roles:
|
||||
predicates.append(User.role.in_(list(task.target_roles)))
|
||||
if not predicates:
|
||||
return set()
|
||||
return set(db.session.execute(select(User.id).where(User.status == "active", or_(*predicates))).scalars())
|
||||
|
||||
|
||||
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]:
|
||||
"""序列化精益周任务;员工端视图仅含已推送视频前缀(游标内),管理端返回全量选择列表。
|
||||
|
||||
videos 每项附带 file_url(MinIO 公开地址),供学员端视频缩略图与点击播放使用。
|
||||
附带 week_index(第 N 期)与 week_end(周日),供前后端拼装"第N周 MM-DD至MM-DD"周次标签。
|
||||
"""
|
||||
visible_ids = list(task.video_resource_ids or [])
|
||||
if learner_view:
|
||||
visible_ids = visible_ids[: task.pushed_video_count]
|
||||
resources = db.session.execute(
|
||||
select(TrainingConfigResource).where(TrainingConfigResource.id.in_(visible_ids))
|
||||
).scalars().all()
|
||||
titles = {resource.id: resource.title or (resource.agent_guide.file_name if resource.agent_guide else "") for resource in resources}
|
||||
file_urls = {
|
||||
resource.id: (minio_service.get_public_url(resource.agent_guide.file_path) if resource.agent_guide and resource.agent_guide.file_path else "")
|
||||
for resource in resources
|
||||
}
|
||||
try:
|
||||
week_start = date.fromisoformat(task.week_key)
|
||||
except ValueError:
|
||||
week_start = None
|
||||
return {
|
||||
"id": task.id,
|
||||
"week_key": task.week_key,
|
||||
"week_end": (week_start + timedelta(days=6)).isoformat() if week_start else None,
|
||||
"week_index": week_index_for_task(task),
|
||||
"due_at": task.due_at.isoformat(),
|
||||
"video_resource_ids": visible_ids,
|
||||
"target_roles": list(task.target_roles or []),
|
||||
"target_user_ids": list(task.target_user_ids or []),
|
||||
"videos": [{"id": resource_id, "name": titles.get(resource_id, ""), "file_url": file_urls.get(resource_id, "")} for resource_id in visible_ids],
|
||||
"status": task.status,
|
||||
"min_summary_length": MIN_SUMMARY_LENGTH,
|
||||
"weekly_count": task.weekly_count,
|
||||
"pushed_video_count": task.pushed_video_count,
|
||||
}
|
||||
|
||||
|
||||
def create_or_update_weekly_task(data: dict[str, Any], user_id: int) -> dict[str, Any]:
|
||||
"""
|
||||
创建或更新精益视频周任务,并由 HR 冻结视频列表、每周推送数量与受训对象。
|
||||
|
||||
业务约束(周任务规则):
|
||||
- 任务周支持修改:显式传 week_key(必须为该周周一)即按所选自然周创建/更新,缺省回落当周周一;
|
||||
- 截止时间支持修改:显式传 due_at 按所选时刻落库,缺省为所选周周日 23:59:59;
|
||||
不得早于所选周周一 00:00(Asia/Shanghai),避免任务创建即处于"已延期"的明显配置错误;
|
||||
- 修改后【发布周任务】/【立即新增任务补推】均作用于所选周任务(发布仅首次自动推首批);
|
||||
- 同周重复提交为更新(游标不回退),新周提交为新建。
|
||||
"""
|
||||
config = _get_lean_config()
|
||||
shanghai_tz = resolve_schedule_tzinfo("Asia/Shanghai")
|
||||
# [STEP 1] 任务周与截止时间:优先取表单显式指定(支持修改为任意自然周),未指定时回落当周(周一 ~ 周日 23:59:59)
|
||||
week_start, due_at = _current_week_bounds()
|
||||
explicit_week_key = str(data.get("week_key") or "").strip()
|
||||
if explicit_week_key:
|
||||
try:
|
||||
week_start = date.fromisoformat(explicit_week_key)
|
||||
except ValueError as exc:
|
||||
raise ValidationError("week_key must be YYYY-MM-DD", details={"field": "week_key"}) from exc
|
||||
if week_start.weekday() != 0:
|
||||
raise ValidationError("week_key must be the Monday of its week", details={"field": "week_key"})
|
||||
explicit_due_at = str(data.get("due_at") or "").strip()
|
||||
if explicit_due_at:
|
||||
try:
|
||||
due_at = to_utc_naive(datetime.fromisoformat(explicit_due_at.replace("Z", "+00:00")))
|
||||
except ValueError as exc:
|
||||
raise ValidationError("due_at is invalid", details={"field": "due_at"}) from exc
|
||||
else:
|
||||
due_at = to_utc_naive(datetime.combine(week_start + timedelta(days=6), time(23, 59, 59), tzinfo=shanghai_tz))
|
||||
# 截止时间下限校验:早于所选周周一 00:00 意味着任务一经创建即整周过期,视为配置错误
|
||||
week_floor = to_utc_naive(datetime.combine(week_start, time(0, 0, 0), tzinfo=shanghai_tz))
|
||||
if due_at < week_floor:
|
||||
raise ValidationError("due_at must not be earlier than the Monday of the selected week", details={"field": "due_at"})
|
||||
existing = db.session.execute(select(LeanTrainingWeeklyTask).where(LeanTrainingWeeklyTask.week_key == week_start.isoformat())).scalar_one_or_none()
|
||||
video_ids = _normalize_video_ids(data.get("video_resource_ids"), config)
|
||||
target_roles = _normalize_target_roles(data.get("target_roles"))
|
||||
target_user_ids = _normalize_target_user_ids(data.get("target_user_ids"))
|
||||
if not target_roles and not target_user_ids:
|
||||
raise ValidationError("At least one target role or user is required", details={"field": "target_roles"})
|
||||
weekly_count = data.get("weekly_count", 1)
|
||||
try:
|
||||
weekly_count = int(weekly_count)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError("weekly_count must be a positive integer", details={"field": "weekly_count"}) from exc
|
||||
if weekly_count < 1 or weekly_count > 50:
|
||||
raise ValidationError("weekly_count must be between 1 and 50", details={"field": "weekly_count"})
|
||||
# 新实例必须显式给游标初值:列 default 仅在 INSERT 时生效,Python 侧构造后为 None,直接参与 min() 会抛 TypeError
|
||||
task = existing or LeanTrainingWeeklyTask(config_id=config.id, week_key=week_start.isoformat(), created_by_id=user_id, weekly_count=1, pushed_video_count=0)
|
||||
task.due_at = due_at
|
||||
task.video_resource_ids = video_ids
|
||||
# [STEP] 视频列表可能被追加,推送游标不能超出列表长度,否则下一轮无视频可推
|
||||
task.pushed_video_count = min(task.pushed_video_count, len(video_ids))
|
||||
task.weekly_count = weekly_count
|
||||
task.target_roles = target_roles
|
||||
task.target_user_ids = target_user_ids
|
||||
task.status = "published"
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
return serialize_weekly_task(task)
|
||||
|
||||
|
||||
def get_weekly_task_for_admin(task_id: int) -> dict[str, Any] | None:
|
||||
"""按 ID 返回管理端视图的周任务(全量视频列表),任务不存在时返回 None。"""
|
||||
task = db.session.get(LeanTrainingWeeklyTask, task_id)
|
||||
return serialize_weekly_task(task) if task else None
|
||||
|
||||
|
||||
def get_current_weekly_task(user: User) -> dict[str, Any] | None:
|
||||
"""返回当前员工被指定的最新已发布周任务,未被指定时不暴露任务内容。"""
|
||||
tasks = db.session.execute(
|
||||
select(LeanTrainingWeeklyTask).where(LeanTrainingWeeklyTask.status == "published").order_by(LeanTrainingWeeklyTask.week_key.desc())
|
||||
).scalars().all()
|
||||
task = next((item for item in tasks if is_task_targeted_to_user(item, user)), None)
|
||||
return serialize_weekly_task(task, learner_view=True) if task else None
|
||||
|
||||
|
||||
def list_my_weekly_tasks(user: User) -> list[dict[str, Any]]:
|
||||
"""
|
||||
返回当前员工被指派的全部已发布精益周任务(按周期倒序,最新在最上),供员工端时间树展示。
|
||||
|
||||
每项为学员视角序列化(仅已推送视频前缀),并附加:
|
||||
- task_status: completed=已完成感悟提交(completed_at 非空);overdue=未完成且已过截止时间;in_progress=未完成且未到截止;
|
||||
- completion: 观看草稿(仅记录了视频观看、感悟未提交)或完成记录的总结/观看时间/完成时间摘要,两者均无时为 None。
|
||||
"""
|
||||
tasks = db.session.execute(
|
||||
select(LeanTrainingWeeklyTask).where(LeanTrainingWeeklyTask.status == "published").order_by(LeanTrainingWeeklyTask.week_key.desc())
|
||||
).scalars().all()
|
||||
targeted = [item for item in tasks if is_task_targeted_to_user(item, user)]
|
||||
if not targeted:
|
||||
return []
|
||||
completions = {
|
||||
item.weekly_task_id: item
|
||||
for item in db.session.execute(
|
||||
select(LeanTrainingCompletion).where(
|
||||
LeanTrainingCompletion.user_id == user.id,
|
||||
LeanTrainingCompletion.weekly_task_id.in_([task.id for task in targeted]),
|
||||
)
|
||||
).scalars().all()
|
||||
}
|
||||
now = utc_now_naive()
|
||||
items: list[dict[str, Any]] = []
|
||||
for task in targeted:
|
||||
completion = completions.get(task.id)
|
||||
item = serialize_weekly_task(task, learner_view=True)
|
||||
# 只有感悟提交完成(completed_at 非空)才算"已完成";仅有观看草稿时仍按截止时间判定进行中/已延期
|
||||
item["task_status"] = "completed" if completion and completion.completed_at else ("overdue" if now > task.due_at else "in_progress")
|
||||
item["completion"] = {
|
||||
"summary_text": completion.summary_text,
|
||||
"watched_at": dict(completion.watched_at_json or {}),
|
||||
"completed_at": completion.completed_at.isoformat() if completion.completed_at else None,
|
||||
} if completion else None
|
||||
items.append(item)
|
||||
return items
|
||||
|
||||
|
||||
def mark_video_watched(user: User, data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
学员端持久化"单个任务视频已完成观看"记录:视频播放到结尾即保存,无需等待感悟提交。
|
||||
|
||||
Args:
|
||||
user: 当前登录员工。
|
||||
data: 需包含 weekly_task_id 与 resource_id;resource_id 必须属于该任务已推送的前缀视频。
|
||||
Returns:
|
||||
{"watched_at": {resource_id: 观看时间iso字符串}},该任务当前的全部观看记录。
|
||||
Raises:
|
||||
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]:
|
||||
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)
|
||||
).scalar_one_or_none() or LeanTrainingCompletion(weekly_task_id=task.id, user_id=user.id)
|
||||
watched = dict(completion.watched_at_json or {})
|
||||
if not watched.get(str(resource_id)):
|
||||
watched[str(resource_id)] = utc_now_naive().isoformat()
|
||||
completion.watched_at_json = watched
|
||||
# 观看草稿:保持 completed_at 为空,任务仍为进行中/已延期,直至感悟提交完成
|
||||
db.session.add(completion)
|
||||
db.session.commit()
|
||||
return {"watched_at": watched}
|
||||
|
||||
|
||||
def save_completion(user: User, data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""保存员工精益学习事实,并强制校验当前已推送视频全部看完且总结不少于 50 字。"""
|
||||
task_id = int(data.get("weekly_task_id") or 0)
|
||||
task = db.session.get(LeanTrainingWeeklyTask, task_id)
|
||||
if not task or task.status != "published":
|
||||
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]
|
||||
# 观看记录以服务端持久化为准(mark_video_watched 已逐个保存),客户端仅作回显兜底,防止伪造观看
|
||||
watched = {str(key): str(value) for key, value in (data.get("watched_at") or {}).items()}
|
||||
completion = db.session.execute(
|
||||
select(LeanTrainingCompletion).where(LeanTrainingCompletion.weekly_task_id == task.id, LeanTrainingCompletion.user_id == user.id)
|
||||
).scalar_one_or_none() or LeanTrainingCompletion(weekly_task_id=task.id, user_id=user.id)
|
||||
watched.update({str(key): str(value) for key, value in (completion.watched_at_json or {}).items()})
|
||||
if not required_ids or not all(str(resource_id) in watched and watched[str(resource_id)] for resource_id in required_ids):
|
||||
raise ValidationError("All pushed videos must be watched", details={"field": "watched_at"})
|
||||
summary = str(data.get("summary_text") or "").strip()
|
||||
char_count = len(summary)
|
||||
if char_count < MIN_SUMMARY_LENGTH:
|
||||
raise ValidationError("Learning summary must contain at least 50 characters", details={"field": "summary_text", "min_length": MIN_SUMMARY_LENGTH, "actual_length": char_count})
|
||||
completion.watched_at_json = watched
|
||||
completion.summary_text = summary
|
||||
completion.summary_char_count = char_count
|
||||
completion.status = "completed"
|
||||
completion.completed_at = completion.completed_at or utc_now_naive()
|
||||
db.session.add(completion)
|
||||
db.session.commit()
|
||||
return serialize_completion(completion, task, user)
|
||||
|
||||
|
||||
def _task_video_rows(task: LeanTrainingWeeklyTask, completion: LeanTrainingCompletion | None) -> list[dict[str, Any]]:
|
||||
"""
|
||||
生成看板行的视频明细:仅展示本周期内已推送、要求员工学习的视频(推送游标前缀),与学员端可见范围一致。
|
||||
|
||||
Args:
|
||||
task: 当前周任务,视频顺序按管理端冻结时的选择顺序展示(截断到推送游标)。
|
||||
completion: 该员工的完成记录;从未观看(无完成记录)时传 None,仅返回视频名称清单(观看时间为 None)。
|
||||
Returns:
|
||||
[{"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]
|
||||
return [
|
||||
{"name": titles.get(resource_id, ""), "watched_at": watched.get(str(resource_id))}
|
||||
for resource_id in visible_ids
|
||||
]
|
||||
|
||||
|
||||
def serialize_completion(completion: LeanTrainingCompletion, task: LeanTrainingWeeklyTask, user: User) -> dict[str, Any]:
|
||||
"""组合看板所需人员、视频观看、总结和完成状态字段。"""
|
||||
# 状态三态归一:已提交感悟为 completed;未完成时按截止时间区分进行中/已延期,管理端状态列直接展示中文
|
||||
if completion.status == "completed":
|
||||
status = "completed"
|
||||
else:
|
||||
status = "overdue" if utc_now_naive() > task.due_at else (completion.status or "in_progress")
|
||||
return {
|
||||
"id": completion.id,
|
||||
"user_id": user.id,
|
||||
"employee_id": user.employee_id,
|
||||
"name": user.real_name or user.username,
|
||||
"department": user.department,
|
||||
"videos": _task_video_rows(task, completion),
|
||||
"summary_text": completion.summary_text,
|
||||
"status": status,
|
||||
"completed_at": completion.completed_at.isoformat() if completion.completed_at else None,
|
||||
}
|
||||
|
||||
|
||||
def list_dashboard(task_id: int | None) -> dict[str, Any]:
|
||||
"""返回 HR 可查看的精益看板,仅统计当前周任务已冻结的受训对象。
|
||||
|
||||
Args:
|
||||
task_id: 指定期次任务 ID;为空时返回最新一期。periods 字段返回全部期次摘要,
|
||||
供管理端下拉区分/切换第几期任务(期号按周次升序,最早为第 1 期)。
|
||||
"""
|
||||
all_tasks = db.session.execute(select(LeanTrainingWeeklyTask).order_by(LeanTrainingWeeklyTask.week_key.desc())).scalars().all()
|
||||
# [STEP 1] 期次摘要列表:无论是否指定期次都返回,期号按周次升序编号(最早的为第 1 期)。
|
||||
periods = [{"id": t.id, "week_key": t.week_key, "index": i + 1} for i, t in enumerate(reversed(all_tasks))]
|
||||
task = db.session.get(LeanTrainingWeeklyTask, task_id) if task_id else (all_tasks[0] if all_tasks else None)
|
||||
if not task:
|
||||
return {"task": None, "completed": [], "incomplete": [], "periods": periods}
|
||||
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()}
|
||||
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}
|
||||
(completed if row["status"] == "completed" else incomplete).append(row)
|
||||
return {"task": serialize_weekly_task(task), "completed": completed, "incomplete": incomplete, "periods": periods}
|
||||
@@ -150,11 +150,20 @@ def _register_builtin_platform_jobs() -> None:
|
||||
run_contract_payment_sync_schedule,
|
||||
run_contract_payment_weekly_alert_schedule,
|
||||
)
|
||||
from app.services.schedule.lean_training_job import run_lean_training_reminder_schedule, run_lean_training_video_push_schedule
|
||||
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="contract-payment-sync", label="合同付款 OA 同步", handler=run_contract_payment_sync_schedule,
|
||||
description="同步 OA 合同归档、验收归档和厂商预付款请款作业。", category="contract_payment",
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="lean-training-reminder", label="精益管理培训逾期提醒", handler=run_lean_training_reminder_schedule,
|
||||
description="周日截止后,于周一、周三、周五向未完成员工推送精益培训提醒。", category="training",
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="lean-training-video-push", label="精益培训视频推送", handler=run_lean_training_video_push_schedule,
|
||||
description="每周一 09:00 按每周任务数量依次推送精益培训视频给受训对象并发送企微通知。", category="training",
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="contract-payment-alert-scan", label="合同付款预警扫描", handler=run_contract_payment_alert_schedule,
|
||||
description="每日扫描四阶段付款节点,只生成待发送预警记录。", category="contract_payment",
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
"""
|
||||
backend/app/services/schedule/lean_training_job.py
|
||||
|
||||
用途:将精益培训逾期提醒与每周视频推送接入平台排程契约。
|
||||
依赖:ScheduleTask/ScheduleRun、lean_training_reminder_service、lean_training_push_service。
|
||||
逻辑:平台调度器调用本入口;各入口执行对应扫描并返回标准七元组执行结果。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.lean_training_reminder_service import run_lean_training_reminders
|
||||
from app.services.lean_training_push_service import run_lean_training_video_push
|
||||
from app.services.schedule.job_registry import ScheduleExecuteResult
|
||||
|
||||
|
||||
def run_lean_training_reminder_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""执行精益培训提醒扫描并返回发送统计,供排程运行记录和运维页面展示。"""
|
||||
_ = task, run
|
||||
result = run_lean_training_reminders()
|
||||
total = result["created"] + result["skipped"]
|
||||
failed = result["failed"]
|
||||
return total, result["sent"], failed, result["skipped"], [result], [], [{"step": "lean_training_reminder", "status": "success" if not failed else "partial", "detail": result}]
|
||||
|
||||
|
||||
def run_lean_training_video_push_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""执行每周一视频推送扫描(每任务按每周任务数量推进一批)并返回推送统计。"""
|
||||
_ = task, run
|
||||
result = run_lean_training_video_push()
|
||||
failed = result["failed"]
|
||||
return result["tasks"], result["sent"], failed, result["skipped"], [result], [], [{"step": "lean_training_video_push", "status": "success" if not failed else "partial", "detail": result}]
|
||||
@@ -0,0 +1,24 @@
|
||||
"""merge lean training and voucher heads
|
||||
|
||||
Revision ID: 951f5631e6c9
|
||||
Revises: p1a2b3c4d5e6, vc3d4e5f6a7b
|
||||
Create Date: 2026-09-08 18:23:29.714737
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '951f5631e6c9'
|
||||
down_revision = ('p1a2b3c4d5e6', 'vc3d4e5f6a7b')
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
pass
|
||||
|
||||
|
||||
def downgrade():
|
||||
pass
|
||||
@@ -0,0 +1,58 @@
|
||||
"""lean training weekly push count and push logs
|
||||
|
||||
Revision ID: fb26bc033d27
|
||||
Revises: 951f5631e6c9
|
||||
Create Date: 2026-09-09 10:00:00.000000
|
||||
|
||||
用途:精益周任务新增"每周任务数量"与视频推送游标,并新增视频推送日志表。
|
||||
依赖:lean_training_weekly_tasks 表已存在。
|
||||
逻辑:weekly_count 默认 1、pushed_video_count 默认 0 均带 server_default 兼容存量行;
|
||||
推送日志表记录每轮推送的触发方式、推送视频、成败计数与失败明细。
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'fb26bc033d27'
|
||||
down_revision = '951f5631e6c9'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column(
|
||||
'lean_training_weekly_tasks',
|
||||
sa.Column('weekly_count', sa.Integer(), nullable=False, server_default='1'),
|
||||
)
|
||||
op.add_column(
|
||||
'lean_training_weekly_tasks',
|
||||
sa.Column('pushed_video_count', sa.Integer(), nullable=False, server_default='0'),
|
||||
)
|
||||
# 存量已发布任务视为"全部已推送",员工端保持旧行为(可见全部视频);新任务从 0 起按每周数量分批推进
|
||||
op.execute(
|
||||
"UPDATE lean_training_weekly_tasks SET pushed_video_count = jsonb_array_length(video_resource_ids::jsonb) "
|
||||
"WHERE status = 'published' AND video_resource_ids IS NOT NULL"
|
||||
)
|
||||
op.create_table(
|
||||
'lean_training_video_push_logs',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('weekly_task_id', sa.Integer(), sa.ForeignKey('lean_training_weekly_tasks.id'), nullable=False, index=True),
|
||||
sa.Column('trigger', sa.String(length=20), nullable=False, server_default='schedule', index=True),
|
||||
sa.Column('pushed_resource_ids', sa.JSON(), nullable=False, server_default='[]'),
|
||||
sa.Column('pushed_count', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.Column('recipient_count', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.Column('sent_count', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.Column('skipped_count', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.Column('failed_count', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.Column('status', sa.String(length=20), nullable=False, server_default='sent', index=True),
|
||||
sa.Column('error_message', sa.Text(), nullable=True),
|
||||
sa.Column('created_by_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False, index=True),
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_table('lean_training_video_push_logs')
|
||||
op.drop_column('lean_training_weekly_tasks', 'pushed_video_count')
|
||||
op.drop_column('lean_training_weekly_tasks', 'weekly_count')
|
||||
@@ -0,0 +1,88 @@
|
||||
"""新增精益管理培训周任务、完成事实和提醒审计。"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "p1a2b3c4d5e6"
|
||||
down_revision = "n8f9a0b1c2d3"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""创建精益培训业务表。"""
|
||||
op.create_table(
|
||||
"lean_training_weekly_tasks",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("config_id", sa.Integer(), nullable=False),
|
||||
sa.Column("week_key", sa.String(length=10), nullable=False),
|
||||
sa.Column("due_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("video_resource_ids", sa.JSON(), nullable=False),
|
||||
sa.Column("target_roles", sa.JSON(), nullable=False),
|
||||
sa.Column("target_user_ids", sa.JSON(), nullable=False),
|
||||
sa.Column("status", sa.String(length=20), nullable=False),
|
||||
sa.Column("created_by_id", sa.Integer(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(["config_id"], ["training_configs.id"]),
|
||||
sa.ForeignKeyConstraint(["created_by_id"], ["users.id"]),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("week_key", name="uq_lean_training_week_key"),
|
||||
)
|
||||
op.create_index("ix_lean_training_weekly_tasks_config_id", "lean_training_weekly_tasks", ["config_id"])
|
||||
op.create_index("ix_lean_training_weekly_tasks_week_key", "lean_training_weekly_tasks", ["week_key"])
|
||||
op.create_index("ix_lean_training_weekly_tasks_due_at", "lean_training_weekly_tasks", ["due_at"])
|
||||
op.create_index("ix_lean_training_weekly_tasks_status", "lean_training_weekly_tasks", ["status"])
|
||||
|
||||
op.create_table(
|
||||
"lean_training_completions",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("weekly_task_id", sa.Integer(), nullable=False),
|
||||
sa.Column("user_id", sa.Integer(), nullable=False),
|
||||
sa.Column("watched_at_json", sa.JSON(), nullable=True),
|
||||
sa.Column("summary_text", sa.Text(), nullable=True),
|
||||
sa.Column("summary_char_count", sa.Integer(), nullable=False),
|
||||
sa.Column("status", sa.String(length=20), nullable=False),
|
||||
sa.Column("completed_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(["weekly_task_id"], ["lean_training_weekly_tasks.id"]),
|
||||
sa.ForeignKeyConstraint(["user_id"], ["users.id"]),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("weekly_task_id", "user_id", name="uq_lean_training_task_user"),
|
||||
)
|
||||
op.create_index("ix_lean_training_completions_weekly_task_id", "lean_training_completions", ["weekly_task_id"])
|
||||
op.create_index("ix_lean_training_completions_user_id", "lean_training_completions", ["user_id"])
|
||||
op.create_index("ix_lean_training_completions_status", "lean_training_completions", ["status"])
|
||||
op.create_index("ix_lean_training_completions_completed_at", "lean_training_completions", ["completed_at"])
|
||||
|
||||
op.create_table(
|
||||
"lean_training_reminders",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("weekly_task_id", sa.Integer(), nullable=False),
|
||||
sa.Column("recipient_user_id", sa.Integer(), nullable=False),
|
||||
sa.Column("event_key", sa.String(length=64), nullable=False),
|
||||
sa.Column("status", sa.String(length=20), nullable=False),
|
||||
sa.Column("trace_id", sa.String(length=64), nullable=True),
|
||||
sa.Column("error_message", sa.String(length=255), nullable=True),
|
||||
sa.Column("sent_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(["weekly_task_id"], ["lean_training_weekly_tasks.id"]),
|
||||
sa.ForeignKeyConstraint(["recipient_user_id"], ["users.id"]),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("weekly_task_id", "recipient_user_id", "event_key", name="uq_lean_training_reminder_event"),
|
||||
)
|
||||
op.create_index("ix_lean_training_reminders_weekly_task_id", "lean_training_reminders", ["weekly_task_id"])
|
||||
op.create_index("ix_lean_training_reminders_recipient_user_id", "lean_training_reminders", ["recipient_user_id"])
|
||||
op.create_index("ix_lean_training_reminders_event_key", "lean_training_reminders", ["event_key"])
|
||||
op.create_index("ix_lean_training_reminders_status", "lean_training_reminders", ["status"])
|
||||
op.create_index("ix_lean_training_reminders_trace_id", "lean_training_reminders", ["trace_id"])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""删除精益培训新增表。"""
|
||||
op.drop_table("lean_training_reminders")
|
||||
op.drop_table("lean_training_completions")
|
||||
op.drop_table("lean_training_weekly_tasks")
|
||||
@@ -0,0 +1,117 @@
|
||||
"""
|
||||
backend/tests/test_contract_payment_ledger_focus.py
|
||||
|
||||
用途:验收合同台账汇总卡按合同计数,以及点卡片过滤列表。
|
||||
依赖:Flask test client、ContractPaymentContract、ContractPaymentNode、ledger_focus。
|
||||
逻辑:固定业务日 2026-09-10,分别构造即将到期、逾期、待补充、本月应付合同后核对计数与 focus 筛选。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
|
||||
from app import db
|
||||
from app.models import ContractPaymentContract, ContractPaymentNode, User
|
||||
from app.services.contract_payment.ledger_focus import ledger_focus_counts
|
||||
|
||||
|
||||
def _create_user(*, username: str) -> 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({'contract_payment.access': True})
|
||||
user.set_password('password123')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
db.session.expunge(user)
|
||||
return user
|
||||
|
||||
|
||||
def _auth_headers(user: User) -> dict[str, str]:
|
||||
"""生成测试鉴权头。"""
|
||||
return {
|
||||
'X-User-Id': str(user.id),
|
||||
'X-Username': user.username,
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
|
||||
def _add_contract(*, contract_no: str, status: str = 'active') -> ContractPaymentContract:
|
||||
"""写入一份已进入台账的合同。"""
|
||||
contract = ContractPaymentContract(
|
||||
contract_no=contract_no,
|
||||
parse_status='parsed',
|
||||
status=status,
|
||||
)
|
||||
db.session.add(contract)
|
||||
db.session.flush()
|
||||
return contract
|
||||
|
||||
|
||||
def _add_node(contract: ContractPaymentContract, *, due: date | None, node_status: str = 'active') -> None:
|
||||
"""写入一个付款节点,供汇总卡按到期日分类。"""
|
||||
db.session.add(ContractPaymentNode(
|
||||
contract_id=contract.id,
|
||||
node_code=f'prepayment-{contract.id}',
|
||||
node_type='prepayment',
|
||||
status=node_status,
|
||||
due_date=due,
|
||||
offset_days=0,
|
||||
reminder_days=14,
|
||||
))
|
||||
|
||||
|
||||
def _seed_focus_contracts() -> None:
|
||||
"""构造四张汇总卡各自至少命中一份的台账合同。"""
|
||||
today = date(2026, 9, 10)
|
||||
due = _add_contract(contract_no='HT-FOCUS-DUE')
|
||||
_add_node(due, due=today.replace(day=14))
|
||||
overdue = _add_contract(contract_no='HT-FOCUS-OVERDUE')
|
||||
_add_node(overdue, due=date(2026, 8, 20))
|
||||
_add_contract(contract_no='HT-FOCUS-NEEDS')
|
||||
month = _add_contract(contract_no='HT-FOCUS-MONTH')
|
||||
_add_node(month, due=date(2026, 9, 28))
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def test_ledger_focus_counts_by_contract(app):
|
||||
"""四张汇总卡均按合同计数;本月应付只含本自然月未付合同。"""
|
||||
with app.app_context():
|
||||
_seed_focus_contracts()
|
||||
counts = ledger_focus_counts(session=db.session, today=date(2026, 9, 10))
|
||||
# 关键断言:即将到期 1、逾期 1、待补充 1、本月应付为 9/14 与 9/28 两份。
|
||||
assert counts['due'] == 1
|
||||
assert counts['overdue'] == 1
|
||||
assert counts['needs_completion'] == 1
|
||||
assert counts['due_this_month'] == 2
|
||||
|
||||
|
||||
def test_list_contracts_focus_filters_ledger(client, app, monkeypatch):
|
||||
"""点汇总卡后列表只返回对应合同;汇总接口不跟 keyword。"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.contract_payment.ledger_focus.business_today',
|
||||
lambda today=None: today or date(2026, 9, 10),
|
||||
)
|
||||
with app.app_context():
|
||||
user = _create_user(username='cp_focus_list')
|
||||
_seed_focus_contracts()
|
||||
|
||||
headers = _auth_headers(user)
|
||||
overdue = client.get('/api/contract-payment/contracts?focus=overdue', headers=headers)
|
||||
summary = client.get('/api/contract-payment/contracts/summary', headers=headers)
|
||||
empty = client.get('/api/contract-payment/contracts?focus=overdue&keyword=NO-SUCH', headers=headers)
|
||||
# 关键断言:逾期卡只筛出逾期合同;汇总仍看全量台账。
|
||||
assert overdue.status_code == 200
|
||||
data = overdue.get_json()['data']
|
||||
assert data['total'] == 1
|
||||
assert data['items'][0]['contract_no'] == 'HT-FOCUS-OVERDUE'
|
||||
assert summary.get_json()['data']['overdue'] == 1
|
||||
assert empty.get_json()['data']['total'] == 0
|
||||
@@ -0,0 +1,98 @@
|
||||
"""
|
||||
backend/tests/test_contract_payment_list.py
|
||||
|
||||
用途:验收合同付款台账列表的 keyword 筛选,尤其是按供应商名称模糊匹配。
|
||||
依赖:Flask test client、ContractPaymentContract、用户功能权限。
|
||||
逻辑:构造两份已解析合同,确认供应商片段只命中对应行,且合同号/采购单号检索仍可用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import ContractPaymentContract, User
|
||||
|
||||
|
||||
def _create_user(*, username: str) -> User:
|
||||
"""创建具备合同付款预警访问权的落库用户,供列表接口走 legacy header 认证。"""
|
||||
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({'contract_payment.access': True})
|
||||
user.set_password('password123')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
db.session.expunge(user)
|
||||
return user
|
||||
|
||||
|
||||
def _auth_headers(user: User) -> dict[str, str]:
|
||||
"""生成测试鉴权头。"""
|
||||
return {
|
||||
'X-User-Id': str(user.id),
|
||||
'X-Username': user.username,
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
|
||||
def _seed_parsed_contracts() -> None:
|
||||
"""写入两份已进入台账的合同,供应商名称可区分。"""
|
||||
db.session.add_all(
|
||||
[
|
||||
ContractPaymentContract(
|
||||
contract_no='HT-20260903-30622-0',
|
||||
workflow_no='5203-2609020001',
|
||||
purchase_order_no='5203-2609020001',
|
||||
supplier_name='诺亘(上海)工业自动化有限公司',
|
||||
parse_status='parsed',
|
||||
status='active',
|
||||
),
|
||||
ContractPaymentContract(
|
||||
contract_no='HT-20260903-30612-0',
|
||||
workflow_no='5203-2608270005',
|
||||
purchase_order_no='5203-2608270005',
|
||||
supplier_name='无锡市质谨机电科技有限公司',
|
||||
parse_status='parsed',
|
||||
status='active',
|
||||
),
|
||||
]
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def test_list_contracts_filters_by_supplier_name(client, app):
|
||||
"""关键词命中供应商名称时只返回对应合同,不误伤其他供应商。"""
|
||||
with app.app_context():
|
||||
user = _create_user(username='cp_list_supplier')
|
||||
_seed_parsed_contracts()
|
||||
|
||||
headers = _auth_headers(user)
|
||||
res = client.get('/api/contract-payment/contracts?keyword=诺亘', headers=headers)
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()['data']
|
||||
# 关键断言:供应商模糊匹配生效,且仍走 parsed 台账口径。
|
||||
assert data['total'] == 1
|
||||
assert data['items'][0]['supplier_name'] == '诺亘(上海)工业自动化有限公司'
|
||||
assert data['items'][0]['contract_no'] == 'HT-20260903-30622-0'
|
||||
|
||||
|
||||
def test_list_contracts_keyword_still_matches_contract_and_po(client, app):
|
||||
"""合同号、采购单号原有检索不能被供应商筛选挤掉。"""
|
||||
with app.app_context():
|
||||
user = _create_user(username='cp_list_keyword')
|
||||
_seed_parsed_contracts()
|
||||
|
||||
headers = _auth_headers(user)
|
||||
by_po = client.get('/api/contract-payment/contracts?keyword=5203-2608270005', headers=headers)
|
||||
by_contract = client.get('/api/contract-payment/contracts?keyword=HT-20260903-30622-0', headers=headers)
|
||||
# 关键断言:原合同号/采购单号路径仍精确命中。
|
||||
assert by_po.get_json()['data']['total'] == 1
|
||||
assert by_po.get_json()['data']['items'][0]['purchase_order_no'] == '5203-2608270005'
|
||||
assert by_contract.get_json()['data']['total'] == 1
|
||||
assert by_contract.get_json()['data']['items'][0]['contract_no'] == 'HT-20260903-30622-0'
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/tests/test_contract_payment_parse.py
|
||||
|
||||
用途:验证合同付款预警解析器、三轮预警升级、ERP 金额匹配及周汇总摘要。
|
||||
依赖:contract_payment.parse_service、alert_service、erp_payment_service、supervisor_oa_service(三轮测试 mock)。
|
||||
逻辑:覆盖确定性解析边界、pending 计数与下一次周五 18:00;三轮升级 mock OA 矩阵,不调用外部 OA、文档库或企业微信。
|
||||
用途:验证合同付款预警解析器、三轮预警升级、ERP 金额匹配、周汇总摘要及企微 Excel 收件人列。
|
||||
依赖:contract_payment.parse_service、alert_service、erp_payment_service、supervisor_oa_service(三轮测试 mock)、openpyxl。
|
||||
逻辑:覆盖确定性解析边界、pending 计数与下一次周五 18:00;三轮升级 mock OA 矩阵,不调用外部 OA、文档库或企业微信;Excel 用例只断言「收件人」列为真实姓名。
|
||||
"""
|
||||
|
||||
from datetime import date, datetime
|
||||
@@ -17,10 +17,17 @@ from app.models import (
|
||||
ContractPaymentNode,
|
||||
User,
|
||||
)
|
||||
from io import BytesIO
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from app.services.contract_payment.alert_service import (
|
||||
bind_contract_owner_from_applicant,
|
||||
build_weekly_alert_summary,
|
||||
generate_alerts,
|
||||
_alert_status_label,
|
||||
_build_excel,
|
||||
_recipient_display_name,
|
||||
)
|
||||
from app.services.contract_payment import parse_service
|
||||
from app.services.contract_payment.parse_service import parse_contract_bytes, parse_contract_text
|
||||
@@ -549,6 +556,81 @@ def test_weekly_alert_summary_counts_pending_and_next_friday(app):
|
||||
assert at_send_time["next_send_at"] == "2026-09-11T10:00:00Z"
|
||||
|
||||
|
||||
def test_weekly_excel_writes_recipient_real_name_not_role(app):
|
||||
"""关键断言:企微 Excel 列名为「收件人」,单元格写系统用户真实姓名,不再写岗位名称。"""
|
||||
with app.app_context():
|
||||
owner = User(
|
||||
username="excel-owner",
|
||||
email="excel-owner@example.com",
|
||||
status="active",
|
||||
real_name="张三",
|
||||
)
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
contract = ContractPaymentContract(
|
||||
contract_no="HT-EXCEL-1",
|
||||
purchase_order_no="PO-1",
|
||||
supplier_name="苏州供应商",
|
||||
owner_user_id=owner.id,
|
||||
status="active",
|
||||
)
|
||||
db.session.add(contract)
|
||||
db.session.flush()
|
||||
node = ContractPaymentNode(
|
||||
contract_id=contract.id,
|
||||
node_code="shipment",
|
||||
node_type="shipment",
|
||||
status="active",
|
||||
due_date=date(2026, 9, 1),
|
||||
)
|
||||
db.session.add(node)
|
||||
db.session.flush()
|
||||
alert = ContractPaymentAlert(
|
||||
contract_id=contract.id,
|
||||
node_id=node.id,
|
||||
trigger_key="round:1:date:2026-09-01",
|
||||
recipient_user_id=owner.id,
|
||||
alert_round=1,
|
||||
status="pending",
|
||||
)
|
||||
db.session.add(alert)
|
||||
db.session.commit()
|
||||
|
||||
data, summary = _build_excel([(alert, contract, node, owner)])
|
||||
wb = load_workbook(BytesIO(data))
|
||||
headers = [cell.value for cell in wb.active[1]]
|
||||
row = [cell.value for cell in wb.active[2]]
|
||||
|
||||
assert "收件岗位" not in headers
|
||||
assert headers[10] == "收件人"
|
||||
assert row[10] == "张三"
|
||||
assert row[11] == "待发送"
|
||||
assert "pending" not in row
|
||||
assert "采购负责人" not in row
|
||||
assert summary["total"] == 1
|
||||
|
||||
|
||||
def test_recipient_display_name_falls_back_to_username(app):
|
||||
"""关键断言:真实姓名为空时 Excel 收件人回退用户名,而不是岗位标签。"""
|
||||
with app.app_context():
|
||||
named = User(username="buyer", email="named@example.com", status="active", real_name="李采购")
|
||||
unnamed = User(username="buyer02", email="unnamed@example.com", status="active", real_name=" ")
|
||||
|
||||
assert _recipient_display_name(named) == "李采购"
|
||||
assert _recipient_display_name(unnamed) == "buyer02"
|
||||
assert _recipient_display_name(None) == "—"
|
||||
|
||||
|
||||
def test_alert_status_label_uses_chinese():
|
||||
"""关键断言:Excel 状态列把 pending/sent/failed 写成中文,未知码保留原文。"""
|
||||
assert _alert_status_label("pending") == "待发送"
|
||||
assert _alert_status_label("sent") == "已发送"
|
||||
assert _alert_status_label("failed") == "发送失败"
|
||||
assert _alert_status_label("resolved") == "已关闭"
|
||||
assert _alert_status_label("unknown-code") == "unknown-code"
|
||||
assert _alert_status_label(None) == "—"
|
||||
|
||||
|
||||
def test_erp_payment_amount_matches_the_corresponding_stage():
|
||||
"""关键断言:不同金额的 ERP 付款必须分别匹配同金额付款阶段。"""
|
||||
paid_node_ids = resolve_paid_node_ids(
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/tests/test_contract_payment_permissions.py
|
||||
|
||||
用途:验收合同付款预警专项权限 `contract_payment.access` 的角色默认值、显式覆盖与 API 拦截。
|
||||
依赖:User 功能权限、Flask test client、contract_payment 蓝图。
|
||||
逻辑:admin 默认可访问;普通用户默认 403;显式授予后可查询台账;关闭 admin 覆盖后同样 403。
|
||||
逻辑:admin 默认可访问;普通用户默认 403;显式授予后可查询台账,但不能触发同步/扫描/发送;关闭 admin 覆盖后同样 403。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -128,3 +128,23 @@ def test_contract_payment_api_allows_granted_user(client, app):
|
||||
body = list_res.get_json()
|
||||
assert body.get('success') is True
|
||||
assert 'items' in (body.get('data') or {})
|
||||
|
||||
|
||||
def test_contract_payment_jobs_require_admin(client, app):
|
||||
"""已授权的普通用户可查台账,但不能触发同步、扫描或周汇总发送。"""
|
||||
with app.app_context():
|
||||
granted = _create_user(
|
||||
username='cp_api_jobs_denied',
|
||||
feature_permissions={'contract_payment.access': True},
|
||||
)
|
||||
|
||||
headers = _auth_headers(granted)
|
||||
# 关键断言:访问权不等于操作权,手动任务仅管理员。
|
||||
for path in (
|
||||
'/api/contract-payment/sync',
|
||||
'/api/contract-payment/alerts/run',
|
||||
'/api/contract-payment/alerts/weekly-run',
|
||||
):
|
||||
res = client.post(path, headers=headers, json={})
|
||||
assert res.status_code == 403, path
|
||||
assert _json_error(res)['code'] == 'CONTRACT_PAYMENT.ADMIN_REQUIRED'
|
||||
@@ -0,0 +1,80 @@
|
||||
"""
|
||||
tests/test_kb_source_file_download.py
|
||||
|
||||
用途:知识库源文件下载的 Content-Disposition 与中文文件名。
|
||||
依赖:kb.common.build_content_disposition、documents 路由、kb 模型。
|
||||
逻辑:纯函数校验 RFC 5987 头;API 用例确认 ?download=1 返回原名且正文为原件。
|
||||
"""
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
from app import db
|
||||
from app.api.kb.common import build_content_disposition
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.models import KbDocument, KbDocumentVersion, KbGroup, User
|
||||
|
||||
|
||||
def test_build_content_disposition_quotes_ascii_and_keeps_utf8_filename():
|
||||
"""
|
||||
ASCII 回退名必须加引号,真实中文名在 filename* 段。
|
||||
|
||||
关键断言:不得出现无引号的 `filename=docx; filename*=...`,否则浏览器会把两段拼成怪名。
|
||||
"""
|
||||
filename = '企业文化.docx'
|
||||
header = build_content_disposition(filename, as_attachment=True)
|
||||
assert header.startswith('attachment; filename="download.docx"; filename*=UTF-8\'\'')
|
||||
assert quote(filename, safe='') in header
|
||||
assert 'filename=docx;' not in header
|
||||
|
||||
|
||||
def test_source_file_download_uses_original_filename(app, client, tmp_path):
|
||||
"""
|
||||
工作台源文件下载应以下载附件返回,且 Content-Disposition 含原始中文文件名。
|
||||
|
||||
关键断言:响应体是原件字节;filename* 为 企业文化.docx;ASCII 回退名带引号。
|
||||
"""
|
||||
storage_root = tmp_path / 'kb-storage'
|
||||
storage_root.mkdir()
|
||||
source_name = '企业文化.docx'
|
||||
source_path = storage_root / 'corp-culture.docx'
|
||||
source_bytes = b'PK\x03\x04fake-docx'
|
||||
source_path.write_bytes(source_bytes)
|
||||
|
||||
app.config['KB_STORAGE_ROOT'] = str(storage_root)
|
||||
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username='kb-download-admin',
|
||||
email='kb-download-admin@example.com',
|
||||
role='admin',
|
||||
status='active',
|
||||
)
|
||||
user.set_password('password123')
|
||||
group = KbGroup(name='源文件下载分组')
|
||||
document = KbDocument(group=group, title='企业文化', status='uploaded')
|
||||
version = KbDocumentVersion(
|
||||
document=document,
|
||||
version_no=1,
|
||||
status='uploaded',
|
||||
is_current=True,
|
||||
source_file_name=source_name,
|
||||
source_file_path=str(source_path),
|
||||
source_file_ext='docx',
|
||||
source_file_size=len(source_bytes),
|
||||
)
|
||||
db.session.add_all([user, group, document, version])
|
||||
db.session.commit()
|
||||
version_id = version.id
|
||||
token = issue_local_access_token(user)
|
||||
|
||||
res = client.get(
|
||||
f'/api/kb/document-versions/{version_id}/source-file?download=1',
|
||||
headers={'Authorization': f'Bearer {token}'},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
assert res.data == source_bytes
|
||||
disposition = res.headers.get('Content-Disposition', '')
|
||||
assert 'attachment' in disposition
|
||||
assert f'filename*=UTF-8\'\'{quote(source_name, safe="")}' in disposition
|
||||
assert 'filename="download.docx"' in disposition
|
||||
assert 'filename=docx;' not in disposition
|
||||
+6
-1
@@ -5,7 +5,7 @@
|
||||
- 覆盖预付款、出货款、验收款、质保款四阶段:预付款为合同申请单归档后第 7/14/21 天;出货款为交货期限前 7 天、当天、后 14 天;验收款为验收归档后第 30/40/60 天;质保款为质保到期前 7 天、当天、后 14 天。
|
||||
- 三轮收件人依次为采购负责人、采购部负责人、采购分管领导。预付款及出货款以 ERP `apa_file` 付款事实判定;匹配付款后仅关闭尚未发送的轮次,保留已发送审计。
|
||||
- 每日定时扫描仅生成待发送预警;每周五 18:00 按收件人归并发送一条企业微信汇总。消息仅展示总笔数及阶段数量;每位收件人附件一份 Excel,列明需付款合同及付款明细。
|
||||
- 工作台左侧“合同付款预警”提供二级入口:“合同台账”仅展示采购单号非空、合同号/金额/交期等关键事实和四阶段付款比例完整且合计 100% 的合同;不再以设备采购合同(项目型 V4)或其他固定模板作为准入条件。“待确认合同”集中展示采购单号缺失、付款比例缺失/重复/合计不为 100%,或合同金额、交货期限等关键事实缺失/与 OA 字段冲突的合同,这些合同不得进入自动付款预警;“周汇总批次”独立查看按收件人生成的批次、Excel 附件和发送审计。点击合同可查看详情、解析原因和原文附件。
|
||||
- 工作台左侧“合同付款预警”提供二级入口:“合同台账”仅展示采购单号非空、合同号/金额/交期等关键事实和四阶段付款比例完整且合计 100% 的合同;不再以设备采购合同(项目型 V4)或其他固定模板作为准入条件。“待确认合同”集中展示采购单号缺失、付款比例缺失/重复/合计不为 100%,或合同金额、交货期限等关键事实缺失/与 OA 字段冲突的合同,这些合同不得进入自动付款预警;“周汇总批次”独立查看按收件人生成的批次、Excel 附件和发送审计。台账与待确认列表均支持按合同编号、流程编号、采购单号或供应商名称模糊检索。台账顶部四张汇总卡按合同统计即将到期(7日内)、逾期未付、待补充、本月应付(全量台账),点击过滤列表。同步 OA、强制覆盖、批量重解析、扫描预警和发送预警仅管理员可见。点击合同可查看详情、解析原因和原文附件。
|
||||
- OA 合同申请单同时存在“合同附件”和“盖章完成合同上传”时,必须优先下载并解析后者;普通合同附件仅在盖章完成合同缺失或下载失败时作为备用。
|
||||
- OA 下载的扫描版 PDF 先通过 MinerU 转为保留标题、表格和阅读顺序的 Markdown,再运行合同付款条款规则;MinerU 失败或无结果时回退原 PDF 文字层/OCR,仍无法确认的合同保留在“待确认合同”。
|
||||
|
||||
@@ -170,6 +170,11 @@
|
||||
- 学员侧仅在后台返回有效 `progress_items` 时渲染培训进度模块;若未配置任何进度项,则整个进度模块隐藏,不显示默认占位内容。
|
||||
- 入职培训、安全培训等存量培训类型需自动补齐预设进度说明与步骤引导文案,保证改造前后的学员体验一致。
|
||||
|
||||
### 3.x 精益培训班组通知
|
||||
|
||||
- 精益周任务由具备培训 HR 管理权限的人员按系统角色或指定用户发布,角色对象与用户对象取并集;员工仅能看到被指定的任务。
|
||||
- 精益周任务首次发布时,向全部在职指定对象发送任务初始通知;HR 可向指定对象中的未完成员工发起定向提醒。通知发送须复用企微事件通道与精益培训提醒审计,防止重复推送。
|
||||
|
||||
### 3.x.1 Excel/CSV 知识库分段补充需求
|
||||
|
||||
- Excel/CSV 清洗以完整原始数据行为不可拆分单元,按表格字符上限组合,避免在字段中间截断。
|
||||
|
||||
+9
-8
@@ -339,8 +339,8 @@
|
||||
</div>
|
||||
<section class="excel-preview">
|
||||
<h2>附件预览:合同付款预警明细.xlsx</h2>
|
||||
<p>仅展示当前收件岗位本周需跟进的事项,按逾期优先、计划预警日升序排列。</p>
|
||||
<table><thead><tr><th>序号</th><th>合同编号</th><th>采购单号</th><th>供应商</th><th>付款阶段</th><th>金额 / 比例</th><th>日期锚点</th><th>计划预警日</th><th>待处理天数</th><th>预警轮次</th><th>收件岗位</th><th>状态</th></tr></thead><tbody id="excelPreviewRows"></tbody></table>
|
||||
<p>仅展示当前收件人本周需跟进的事项,按逾期优先、计划预警日升序排列。</p>
|
||||
<table><thead><tr><th>序号</th><th>合同编号</th><th>采购单号</th><th>供应商</th><th>付款阶段</th><th>金额 / 比例</th><th>日期锚点</th><th>计划预警日</th><th>待处理天数</th><th>预警轮次</th><th>收件人</th><th>状态</th></tr></thead><tbody id="excelPreviewRows"></tbody></table>
|
||||
</section>
|
||||
</div>
|
||||
</section>
|
||||
@@ -422,9 +422,10 @@
|
||||
dates = baseDate ? [baseDate] : [];
|
||||
}
|
||||
return dates.map((plannedDate, index) => {
|
||||
const recipientRole = WARNING_ROLE[index + 1] || "采购负责人";
|
||||
const recipientName = recipientRole === "采购负责人" ? plan.owner : `${recipientRole}(岗位映射)`;
|
||||
return { key: `${milestone.id}:${index + 1}`, round: index + 1, plannedDate, recipientRole, recipientName };
|
||||
const round = index + 1;
|
||||
const recipientRole = WARNING_ROLE[round] || "采购负责人";
|
||||
const recipientName = round === 1 ? (plan.owner || "—") : (round === 2 ? "王主管" : "赵分管");
|
||||
return { key: `${milestone.id}:${round}`, round, plannedDate, recipientRole, recipientName };
|
||||
});
|
||||
}
|
||||
function warningRuleText(milestone) {
|
||||
@@ -531,7 +532,7 @@
|
||||
],
|
||||
claimFacts: {}, sentWarningKeys: ["o1:1"],
|
||||
reminderLogs: [
|
||||
{ id: "or1", at: "2026-07-17 18:00", text: "周五付款预警汇总已发送 · 预付款第 1 次 · 收件岗位:采购负责人 · 详见 Excel 附件" },
|
||||
{ id: "or1", at: "2026-07-17 18:00", text: "周五付款预警汇总已发送 · 预付款第 1 次 · 收件人:李采购 · 详见 Excel 附件" },
|
||||
],
|
||||
},
|
||||
],
|
||||
@@ -738,7 +739,7 @@
|
||||
const plan = getPlan(state.wecomPlanId) || getPlan(state.currentPlanId) || state.plans[0];
|
||||
const queue = weeklyQueue();
|
||||
const preferred = queue.find((item) => item.plan.id === plan.id) || queue[0];
|
||||
const recipientName = state.wecomRecipientName || (preferred && preferred.recipientName) || "采购负责人(岗位映射)";
|
||||
const recipientName = state.wecomRecipientName || (preferred && preferred.recipientName) || (plan && plan.owner) || "—";
|
||||
const items = queue.filter((item) => item.recipientName === recipientName);
|
||||
const byType = items.reduce((result, item) => ({ ...result, [item.milestone.type]: (result[item.milestone.type] || 0) + 1 }), {});
|
||||
const summary = Object.entries(byType).map(([type, count]) => `${TYPE_LABEL[type]} ${count} 笔`).join(";") || "暂无待跟进事项";
|
||||
@@ -752,7 +753,7 @@
|
||||
"详细合同、金额、预警日期请查看附件《合同付款预警明细.xlsx》。",
|
||||
].join("\n");
|
||||
document.getElementById("excelPreviewRows").innerHTML = items.length
|
||||
? items.map(({ plan: item, milestone, plannedDate, round, recipientRole }, index) => `<tr><td>${index + 1}</td><td class="mono">${item.contractNo}</td><td class="mono">${item.purchaseOrderNo || "—"}</td><td>${item.supplier}</td><td>${TYPE_LABEL[milestone.type]}</td><td>${money(milestone.amount)} / ${milestone.percent}%</td><td>${milestone.type === "prepayment" ? (item.events.contract_archive || "待合同归档") : milestone.type === "acceptance" ? (item.events.acceptance_archive || "待验收归档") : milestone.dueDate}</td><td>${plannedDate}</td><td>${Math.max(0, -daysUntil(plannedDate))} 天</td><td>第 ${round} 次</td><td>${recipientRole}</td><td>${statusPill(planBucket(item))}</td></tr>`).join("")
|
||||
? items.map(({ plan: item, milestone, plannedDate, round, recipientName }, index) => `<tr><td>${index + 1}</td><td class="mono">${item.contractNo}</td><td class="mono">${item.purchaseOrderNo || "—"}</td><td>${item.supplier}</td><td>${TYPE_LABEL[milestone.type]}</td><td>${money(milestone.amount)} / ${milestone.percent}%</td><td>${milestone.type === "prepayment" ? (item.events.contract_archive || "待合同归档") : milestone.type === "acceptance" ? (item.events.acceptance_archive || "待验收归档") : milestone.dueDate}</td><td>${plannedDate}</td><td>${Math.max(0, -daysUntil(plannedDate))} 天</td><td>第 ${round} 次</td><td>${recipientName}</td><td>${statusPill(planBucket(item))}</td></tr>`).join("")
|
||||
: '<tr><td colspan="12" class="muted">本周无待发送事项</td></tr>';
|
||||
state.currentPlanId = plan.id;
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
## 1. 目标
|
||||
|
||||
从 OA 归档合同中自动生成付款节点。系统每日扫描到期轮次,仅在每周五 18:00 按收件岗位发送企业微信汇总及 Excel 明细。预付款、出货款是否已经付款,以 ERP `apa_file` 为准。
|
||||
从 OA 归档合同中自动生成付款节点。系统每日扫描到期轮次,仅在每周五 18:00 按收件人发送企业微信汇总及 Excel 明细。预付款、出货款是否已经付款,以 ERP `apa_file` 为准。
|
||||
|
||||
## 2. 总体流程
|
||||
|
||||
@@ -115,7 +115,7 @@ erDiagram
|
||||
- 每日扫描:仅生成到期的待发送记录,不发送企业微信。
|
||||
- 每周五 18:00:以收件人为单位汇总待发送记录;无待处理事项时不发送空消息。
|
||||
- 企业微信正文仅展示总笔数、按阶段汇总、Excel 附件和工作台入口,不逐笔展示详细信息。
|
||||
- Excel 一行对应一笔待跟进的付款节点,至少列合同编号、采购单号、供应商、付款阶段、金额、日期锚点、计划预警日、待处理天数、预警轮次和当前状态;按逾期优先、计划预警日升序排列。
|
||||
- Excel 一行对应一笔待跟进的付款节点,至少列合同编号、采购单号、供应商、付款阶段、金额、日期锚点、计划预警日、待处理天数、预警轮次、收件人(实际姓名)和当前状态;按逾期优先、计划预警日升序排列。
|
||||
|
||||
## 7. 边界与待确认项
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# 合同付款预警 Agent 需求说明
|
||||
|
||||
> **版本**:V1.6(第二、三轮上级改查 OA 矩阵)
|
||||
> **更新日期**:2026-09-02
|
||||
> **版本**:V1.10(企微 Excel 收件人列写实际姓名)
|
||||
> **更新日期**:2026-09-10
|
||||
> **状态**:待业务确认后进入开发/联调
|
||||
> **适用范围**:采购合同付款预警工作台、OA 同步、企业微信通知
|
||||
|
||||
@@ -154,7 +154,9 @@ OA“厂商预付款请款作业”的流程状态不作为付款完成依据;
|
||||
|
||||
- 企业微信正文应包含:本周需跟进付款总笔数、按预付款/出货款/验收款/质保款的笔数汇总、Excel 附件说明及工作台入口。
|
||||
- Excel 一行对应一笔需要付款/请款跟进的付款节点,不应输出无关合同或已停止预警的节点。
|
||||
- Excel 至少包含:序号、合同编号、采购单号、供应商、付款阶段、付款金额、付款比例、日期锚点、计划预警日、逾期/待处理天数、预警轮次、对应收件岗位、当前状态。
|
||||
- Excel 至少包含:合同编号、采购单号、供应商、付款阶段、付款金额、付款比例、日期锚点、计划预警日、逾期/待处理天数、预警轮次、收件人、当前状态。
|
||||
- Excel「收件人」列须写该批次实际收件人姓名(系统用户 `real_name`,为空时回退用户名),不得再写「采购负责人」等岗位名称。
|
||||
- Excel「状态」列须写中文(待发送 / 已发送 / 发送失败 / 已关闭),不得输出 `pending` 等内部英文码。
|
||||
- Excel 按紧急程度排序:逾期在前,其次按计划预警日升序;同一收件人只收到其应处理的明细。
|
||||
- Excel 文件应作为本次汇总发送的审计附件保存,可在工作台下载查看。
|
||||
|
||||
@@ -163,6 +165,9 @@ OA“厂商预付款请款作业”的流程状态不作为付款完成依据;
|
||||
- 工作台应展示各付款阶段的规则说明、合同付款节点、日期依据和当前状态。
|
||||
- 合同详情应展示每条预警的付款阶段、轮次、计划日期、实际汇总发送时间、收件人、汇总批次和发送状态。
|
||||
- 工作台应展示下一次汇总发送时间(每周五 18:00)及本周待发送笔数。
|
||||
- 合同台账与待确认列表应支持按合同编号、流程编号、采购单号或供应商名称模糊检索。
|
||||
- 合同台账应展示四张汇总卡(即将到期 7 日内、逾期未付、待补充、本月应付),均按合同计数、统计全部已解析台账;点击卡片过滤下方列表,再次点击取消过滤。
|
||||
- 同步 OA、强制覆盖 OA 字段、批量重解析存量合同、扫描生成预警和发送预警仅管理员可见;普通授权用户只可查询台账、详情和周汇总批次。
|
||||
- 管理员可手动触发 OA 同步和预警扫描;执行应后台异步化,不阻塞页面请求。
|
||||
|
||||
### FR-06 权限与数据安全
|
||||
@@ -190,7 +195,7 @@ OA“厂商预付款请款作业”的流程状态不作为付款完成依据;
|
||||
### 8.3 企业微信汇总消息与附件
|
||||
|
||||
- 本周需要跟进的付款总笔数及阶段汇总;
|
||||
- 当前收件岗位和汇总周期;
|
||||
- 当前收件人和汇总周期;
|
||||
- Excel 明细附件及工作台入口;
|
||||
- 不在企业微信正文逐笔列出合同、供应商、金额等详细信息。
|
||||
|
||||
@@ -226,6 +231,10 @@ OA“厂商预付款请款作业”的流程状态不作为付款完成依据;
|
||||
|
||||
| 日期 | 版本 | 变更内容 |
|
||||
| --- | --- | --- |
|
||||
| 2026-09-10 | V1.10 | 企微周汇总 Excel「收件岗位」列改为「收件人」,单元格写系统用户真实姓名(为空回退用户名);「状态」列改写中文(待发送/已发送/发送失败/已关闭),不再输出 pending 等英文码;三轮升级规则表仍按岗位定义。 |
|
||||
| 2026-09-10 | V1.9 | 合同台账增加四张汇总卡:即将到期(7日内)、逾期未付、待补充、本月应付;均按合同计数、统计全量台账,点击过滤列表。 |
|
||||
| 2026-09-10 | V1.8 | 同步 OA、强制覆盖、批量重解析、扫描预警和发送预警仅平台管理员可见并可调用。 |
|
||||
| 2026-09-10 | V1.7 | 合同台账与待确认列表的 keyword 增加供应商名称模糊匹配。 |
|
||||
| 2026-09-02 | V1.6 | 第二、三轮上级改查 OA:`HrmResource.lastname` 取部门,`Matrixtable_3.zz`/`jfl` 作为企微收件人;不再使用全局岗位用户 ID。 |
|
||||
| 2026-09-01 | V1.4 | 第一次预警收件人明确为台账申请人,按系统用户真实姓名唯一匹配;第二、三次为其上级主管,组织关系来源待 Q-04。 |
|
||||
| 2026-08-26 | V1.3 | 改为以 ERP apa_file 的合格付款记录判断预付款、出货款已付款;不再使用 OA 请款状态停止预警。 |
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
# 精益管理周任务规则手册
|
||||
|
||||
> 适用模块:后台「培训管理 → 精益管理」(管理端)与员工工作台「精益管理培训」(学员端)。
|
||||
> 本手册固化 2026-09 轮周任务规则改造:任务周自动滚动、视频分批推送、推送游标不重复、企微消息推送与定时排程。
|
||||
> 关联代码:`backend/app/services/lean_training_service.py`、`lean_training_push_service.py`、`lean_training_reminder_service.py`、`lean_training_schedule_seed.py`;管理端 `frontend/src/features/admin/modules/training-config/TrainingConfigPage.vue`;学员端 `frontend/src/features/chat/components/TrainingWorkspacePanel.vue`。
|
||||
|
||||
---
|
||||
|
||||
## 1. 规则总览(后台设置 ↔ 系统行为)
|
||||
|
||||
| # | 后台设置 / 规则 | 系统行为 |
|
||||
| --- | --- | --- |
|
||||
| 1 | 培训视频列表分页展示,一页最多 4 条 | 管理端「指定培训视频」按 4 条/页分页,超出 4 条出现上一页/下一页控件 |
|
||||
| 2 | 任务周(周一):默认展示当周周一,**支持修改** | 默认当周周一(Asia/Shanghai);可改为任意自然周(必须为该周周一),【发布周任务】/【立即新增任务补推】作用于所选周 |
|
||||
| 3 | 截止时间:默认当周周日,**支持修改** | 默认所选周周日 23:59:59(转 UTC 落库);可自由指定,但不得早于所选周周一 00:00 |
|
||||
| 4 | 每周任务数量 N | 每次推送向受训用户推送 N 个视频(游标分批,1 ≤ N ≤ 50) |
|
||||
| 5 | 指定培训视频:按计划分批推送并标注周次 | 视频按冻结顺序每周推 N 个;已推送视频带「第X周 MM-DD至MM-DD」标签;推过的视频不重复推,直至全部视频推完 |
|
||||
| 6 | 推送过的视频默认勾选且不能取消勾选 | 已推送前缀(游标内)视频 checkbox 禁用,取消勾选请求被忽略 |
|
||||
| 7 | 【发布周任务】仅对当周任务推送 | 首次发布按上传时间倒序取 N 个视频推送当周任务;失败可用【立即新增任务补推】补发/增推 |
|
||||
| 8 | 定时脚本自动更新推送 | 平台排程每周一 09:00(Asia/Shanghai)自动滚动创建当周任务并推送下一批,无需人工维护 |
|
||||
| 9 | 消息推送规则(企微) | 任务发布即通知;每批推送成功立即通知;已延期(过截止未提交)人员在每批推送成功后立即收到延期提醒 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 核心概念
|
||||
|
||||
### 2.1 视频冻结顺序
|
||||
|
||||
- 管理端显式勾选视频时,**按勾选顺序冻结**为推送顺序。
|
||||
- 管理端未勾选(或清空)时,**自动按资源上传时间倒序**冻结全部视频(对应"第一次发布随机按上传视频时间倒序找 N 个视频")。
|
||||
- 冻结列表保存在 `LeanTrainingWeeklyTask.video_resource_ids`,后续每周按此顺序推进,顺序一旦落库不再变化。
|
||||
|
||||
实现:`_normalize_video_ids()`([lean_training_service.py](../../../backend/app/services/lean_training_service.py))。
|
||||
|
||||
### 2.2 推送游标(不重复推送)
|
||||
|
||||
- `LeanTrainingWeeklyTask.pushed_video_count` 为游标:`video_resource_ids[0:pushed_video_count]` 是已推送前缀,`[pushed_video_count:]` 是待推送队列。
|
||||
- 每次推送从游标处取 `weekly_count` 个视频,推送成功后游标前进(企微发送失败不影响游标,员工端已可见视频,失败明细记录在推送日志)。
|
||||
- 已推送前缀中的视频即"推送过的视频":管理端默认勾选且不可取消;跨周滚动创建新任务时游标继承最近一期进度,保证全局不重复推。
|
||||
|
||||
实现:`pending_video_ids()` / `push_lean_training_videos()`([lean_training_push_service.py](../../../backend/app/services/lean_training_push_service.py))。
|
||||
|
||||
### 2.3 当周边界与期号
|
||||
|
||||
- 任务周 = 所选自然周的周一(`week_key`,ISO 日期),**默认当周周一、支持修改**;截止时间默认所选周周日 23:59:59(Asia/Shanghai,转 UTC naive 落库),**支持修改**,下限为所选周周一 00:00。
|
||||
- 表单不填 `week_key` 时服务端回落当周;显式指定即按所选周创建/更新(历史补周与未来周均允许),【发布周任务】与【立即新增任务补推】均作用于所选周任务。
|
||||
- 期号 `week_index` 按 `week_key` 升序编号(最早一周为第 1 期),序列化层随任务返回,管理端与学员端共用同一口径。
|
||||
- 客户端校验:任务周必须为周一(前端 date input 拦截 + 后端兜底);截止时间早于所选周周一由后端拒绝。
|
||||
|
||||
实现:`_current_week_bounds()` / `week_index_for_task()` / `create_or_update_weekly_task()`([lean_training_service.py](../../../backend/app/services/lean_training_service.py))。
|
||||
|
||||
### 2.4 单进度线
|
||||
|
||||
- 排程只推进**当周任务**:每周一 09:00 先自动滚动创建当周任务,再对当周任务推一批。
|
||||
- 历史任务不由排程推进,其补推仅由管理端【立即新增任务补推】手动触发,避免多任务并行推进造成乱序。
|
||||
|
||||
---
|
||||
|
||||
## 3. 定时任务(排程)
|
||||
|
||||
| 排程编号 | 名称 | Cron | 时区 | 入口 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| SCH-LEAN-TRAINING-VIDEO-PUSH | 精益管理培训视频推送 | `0 9 * * 1`(每周一 09:00) | Asia/Shanghai | `run_lean_training_video_push` |
|
||||
| SCH-LEAN-TRAINING-REMINDER | 精益管理培训逾期提醒(既有) | `0 9 * * *`(每日 09:00) | Asia/Shanghai | `run_lean_training_reminders` |
|
||||
|
||||
- 两个默认排程由 `ensure_default_lean_training_schedule()` 应用启动时幂等创建([lean_training_schedule_seed.py](../../../backend/app/services/lean_training_schedule_seed.py)),管理员可在排程中心停用或调整。
|
||||
- 每周一 09:00 执行流程(`run_lean_training_video_push`):
|
||||
1. `ensure_current_week_task`:当周任务不存在时,以"严格早于当周"的最近一期已发布任务为模板自动创建(复制视频冻结列表、每周数量、受训对象,**游标继承**最近一期进度),状态直接为已发布,并立即发送任务发布通知;
|
||||
2. `push_lean_training_videos(trigger="schedule")`:按游标推下一批 N 个视频并发企微通知,写推送日志;
|
||||
3. 批次推送成功后立即对"已延期"人员发送延期提醒(见 §4)。
|
||||
- 系统内尚无任何已发布任务模板时排程无事可做,等待管理员首次手动发布。
|
||||
|
||||
---
|
||||
|
||||
## 4. 企微消息推送规则
|
||||
|
||||
| 事件 | 触发时机 | 事件类型 / 幂等键 |
|
||||
| --- | --- | --- |
|
||||
| 任务发布通知 | 周任务发布(手动发布或排程滚动创建)后立即发送 | `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-<日期>` |
|
||||
| 定向提醒(既有) | HR 在管理端对指定未完成员工手动发送 | `training_lean_targeted_reminder` / `targeted-<uuid>`(每次点击唯一) |
|
||||
|
||||
- 所有提醒经 `LeanTrainingReminder`(`weekly_task_id + recipient_user_id + event_key` 唯一约束)幂等,同批重推/补发不会重复打扰。
|
||||
- **例外**:定向提醒由 HR 手动触发,每次点击都应真实触达员工,因此 `event_key` 每次唯一化(`targeted-<uuid>`),不参与幂等去重;其余事件键保持稳定,保证重推/补发不重复打扰。
|
||||
- 全部提醒卡片消息发送至企微「和信AI智能工作台」应用会话,点击卡片跳转员工培训聊天页并自动展开精益管理页签:跳转路径 `/chat/<agentId>?training_type=lean_management&weekly_task_id=<id>`,agent id 由配置 `WECOM_LEAN_TRAINING_JUMP_AGENT_ID`(默认 16)控制;前端由 [TrainingWorkspacePanel.vue](../../../frontend/src/features/chat/components/TrainingWorkspacePanel.vue) 消费 query 参数自动展开(管理员进管理端精益看板、学员进学员侧精益学习页)。
|
||||
- "已延期"判定:当前时间 > 任务 `due_at` 且该用户未提交(`LeanTrainingCompletion.status != 'completed'`)的在职受训人员,与管理端看板"已延期"状态口径一致。
|
||||
|
||||
实现:`_send_reminder()` / `notify_overdue_users_after_push()`([lean_training_reminder_service.py](../../../backend/app/services/lean_training_reminder_service.py))。
|
||||
|
||||
---
|
||||
|
||||
## 5. 管理端(后台「培训管理 → 精益管理」)
|
||||
|
||||
- **培训视频分页**:视频列表 4 条/页(`LEAN_VIDEO_PAGE_SIZE = 4`),分页控件含上一页/下一页与页码概览;保存后回到第 1 页。
|
||||
- **任务周 / 截止时间可修改**:表单默认展示当周周一与当周周日,可改为任意自然周(必须为该周周一)与任意截止时刻(不得早于所选周周一 00:00),保存后按所选周创建/更新任务;【发布周任务】/【立即新增任务补推】均作用于所选周。
|
||||
- **每周任务数量**:设置 N,提示文案展示"每周一 09:00 按该数量从视频列表顺序推送下一批(已推送 {pushed}/{total})"。
|
||||
- **视频勾选锁定**:已推送前缀视频 checkbox 禁用并带绿色「第X周 MM-DD至MM-DD」标签;未推送视频可自由勾选/取消(未全选时保存走"自动倒序冻结"或按所选冻结)。
|
||||
- **完成名单看板**(学员工作区「培训管理 → 精益管理」页签,`GET /lean-training/dashboard`):
|
||||
- 视频名称列仅展示**本周期已推送、要求学习的视频**(`video_resource_ids[:pushed_video_count]` 游标前缀),与学员端可见范围一致;未推送视频不出现,游标为 0 时显示 `--`;
|
||||
- 总结列最多预览 15 个字,超出截断显示省略号,点击弹框查看完整文案(无总结显示 `--`);
|
||||
- 名单合为单一明细表(状态列区分已完成/已延期/进行中),表头铺满容器宽度。
|
||||
- **【发布周任务】**:保存并发布**所选周**任务;首次发布(游标为 0)立即推送首批 N 个视频,编辑已推过的任务不重复触发。
|
||||
- **【立即新增任务补推】**(原"立即推送下一批"):按现有游标逻辑对**所选周**任务增推一批(数量 = 每周任务数量),无需等待每周一排程;可用于发布失败后的补发。若当前无待推视频则返回"全部视频已推送完毕"。发布/补推后按任务 ID 刷新所选周上下文(不跳回最新周)。
|
||||
- **推送记录**:展示每轮推送的触发来源(发布推送/每周排程/手动推送)、批次数量、企微发送/失败统计与失败明细。
|
||||
|
||||
管理端接口:`POST /api/admin/lean-training/weekly-tasks`(创建/更新并发布所选周任务)、`GET /api/admin/lean-training/weekly-tasks/<id>`(按 ID 读取指定周任务)、`POST /api/admin/lean-training/weekly-tasks/<id>/push`(补推)、`GET /api/admin/lean-training/weekly-tasks/<id>/push-logs`、`POST /api/admin/lean-training/weekly-tasks/<id>/reminders`、`GET /api/admin/lean-training/dashboard`([backend/app/api/training.py](../../../backend/app/api/training.py))。
|
||||
|
||||
---
|
||||
|
||||
## 6. 学员端(员工工作台「精益管理培训」)
|
||||
|
||||
- 时间树按发布周期倒序展示各期任务,**期号采用后端 `week_index`**(第 1 期最早),与管理端口径一致。
|
||||
- 每期任务展示:周次区间(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`)。
|
||||
|
||||
---
|
||||
|
||||
## 7. 数据模型与迁移
|
||||
|
||||
- 核心表:`lean_training_weekly_tasks`(周任务,含 `week_key`、`due_at`、`weekly_count`、`pushed_video_count`、`video_resource_ids`、`target_roles/target_user_ids`、`status`)、`lean_training_video_push_logs`(推送日志)、`lean_training_reminders`(企微提醒幂等)、`lean_training_completions`(完成记录)。
|
||||
- 本轮改造**未变更表结构**(复用既有列),无新增 Alembic 迁移;如后续调整上述表结构,必须按仓库红线配套生成迁移。
|
||||
|
||||
---
|
||||
|
||||
## 8. 边界与注意事项
|
||||
|
||||
1. **同周重复提交为更新**:同一 `week_key` 再次发布会更新任务(游标只前进不回退,且会被钳制在视频列表长度内)。
|
||||
2. **游标继承与模板选取**:跨周滚动复制模板时继承 `pushed_video_count`;模板仅从"严格早于当周"的最近一期已发布任务选取——管理员指定未来周发布的任务不会被当作滚动模板,避免污染当周进度。若管理员中途更换视频冻结列表,请确保列表包含已推送前缀,否则游标会被钳制导致重复推(`min(游标, len(视频列表))` 保护)。
|
||||
3. **企微失败不阻塞**:发送失败不影响游标前进,员工端视频照常可见;失败明细在管理端"推送记录"可查,可用【立即新增任务补推】对失败批次外的下批视频继续推进。
|
||||
4. **任意周发布**:任务周/截止时间支持修改后,历史补周与未来周均可通过表单发布;排程只自动推进当周任务,历史/未来周任务的推送仍由管理端手动触发;未来周任务发布后即出现在学员端时间树(按期号排序)。
|
||||
5. **i18n**:本轮新增文案(`pushNow`、`weekRangeLabel`、`weekMustBeMonday`、`videoPagePrev/Next/Info` 等)已同步 zh-CN / zh-TW / en / th 四语言,新增键请继续遵循四语言约束。
|
||||
+9
-6
@@ -6,12 +6,12 @@
|
||||
| ------------------------ | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| OA 合同与请款同步 | 已实现 | 合同申请单走 HTTP 待办/已办;验收归档查 OA SQL(`formtable_main_324.cgdh` × `workflow_requestbase.currentnodetype=3`)按采购单号落事件;普通同步只补空字段,管理员可强制覆盖 OA 非空字段并保留变更审计。 |
|
||||
| 四阶段三轮预警扫描 | 已实现 | 每日扫描只生成 pending 预警;第一轮按台账申请人真实姓名匹配系统用户,第二、三轮按申请人部门查 OA `HrmResource` + `Matrixtable_3`(`zz`/`jfl` 即企微 userid)。 |
|
||||
| 企业微信周汇总 | 已实现 | 每周五 18:00 按收件人发一条汇总卡片及逐笔 Excel 附件,并在“周汇总批次”独立入口保留批次审计。 |
|
||||
| 合同付款台账与详情 | 已实现 | “合同付款预警 > 合同台账”服务端分页展示合同、流程、采购、供应商、四阶段金额比例日期、申请人和简洁状态标签;点击合同查看概览、原文附件、付款计划和预警记录。 |
|
||||
| 企业微信周汇总 | 已实现 | 每周五 18:00 按收件人发一条汇总卡片及逐笔 Excel 附件;Excel「收件人」列为系统用户真实姓名;并在“周汇总批次”独立入口保留批次审计。 |
|
||||
| 合同付款台账与详情 | 已实现 | “合同付款预警 > 合同台账”服务端分页展示合同、流程、采购、供应商、四阶段金额比例日期、申请人和简洁状态标签;关键词同时匹配合同号、流程号、采购单号和供应商;四张汇总卡按合同统计即将到期(7日内)、逾期未付、待补充、本月应付(全量台账),点击过滤列表;点击合同查看概览、原文附件、付款计划和预警记录。 |
|
||||
| 通用合同解析与待确认合同 | 已实现 | 不再校验 V4 或其他固定模板;只校验合同号、金额、交期、采购单号及四阶段付款比例完整、无重复、合计 100%。关键事实或比例校验失败合同归入“待确认合同”,不得触发自动预警。 |
|
||||
| 扫描版合同 MinerU 解析 | 已实现 | OA PDF 附件优先经 MinerU 生成 Markdown 后再解析合同号、金额、交期与四阶段付款比例;服务未配置、失败或空结果时安全回退既有文字层/OCR,历史合同可用“批量重新解析存量合同”刷新。 |
|
||||
| 存量合同批量重解析 | 已实现 | 管理员可直接用已归档附件批量刷新历史解析结果,不拉取 OA、不覆盖 OA 字段,用于规则升级后的待确认合同恢复。 |
|
||||
| 合同付款专项权限 | 已实现 | 功能权限 `contract_payment.access`:admin 默认开启,普通用户需在用户管理勾选;无权限不展示侧栏,直链会提示并回应用管理,API 返回 403。 |
|
||||
| 合同付款专项权限 | 已实现 | 功能权限 `contract_payment.access`:admin 默认开启,普通用户需在用户管理勾选;无权限不展示侧栏,直链会提示并回应用管理,API 返回 403。同步 OA、强制覆盖、批量重解析、扫描预警和发送预警仅平台管理员可见并可调用。 |
|
||||
| OA 盖章合同优先 | 已实现 | 合同申请单存在“盖章完成合同上传”时固定优先下载和解析该附件;“合同附件”仅作为失败降级来源。 |
|
||||
|
||||
## 知识库同步状态校验
|
||||
@@ -28,6 +28,7 @@
|
||||
- Dify 返回 `error/failed` 或 60 秒内未完成索引时,同步任务、同步记录和文档卡片会显示失败原因;再次同步会重新提交失败文档。
|
||||
- 管理端“知识库配置 → Dify 设置”支持配置新建 Dataset 的默认检索模型(检索方式、重排序、Top K、相似度阈值开关及阈值),以及文档同步的自定义分段参数(最大 Token 数、重叠 Token 数);保存仅更新 HXOPS 运行时配置,不自动回写已创建的 Dify Dataset。
|
||||
- Excel/CSV 分段使用独立配置 `KB_DIFY_SEGMENT_MAX_TOKENS_EXCEL`(默认 1200)和表格行组段上限 `table_segment_max_chars`(默认 1000);普通文档仍使用 `KB_DIFY_SEGMENT_MAX_TOKENS`(默认 600)。
|
||||
- 工作台知识库源文件下载保存名为上传时的原始文件名;一次点击只触发一次下载。
|
||||
|
||||
## 设备维保助手
|
||||
|
||||
@@ -55,7 +56,7 @@
|
||||
| 功能项 | 状态 | 说明 |
|
||||
| -------------------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Chat 内培训工作区 | 前端已实现 | 在培训 Agent 聊天页顶部提供视频学习、知识点复盘、逐题考试、成绩结算的一体化工作区 |
|
||||
| Chat 内 HR 管理面板 | 已实现 | 仅具备培训 HR 管理权限的用户可在同一聊天页查看真实培训统计、筛选记录并导出 Excel;权限支持角色默认值与前端用户配置共同控制 |
|
||||
| Chat 内 HR 管理面板 | 已实现 | 仅具备培训 HR 管理权限的用户可在同一聊天页查看真实培训统计、筛选记录并导出 Excel;管理端顶部提供【全部培训】/【精益管理】页签,统计卡片随页签按各自实际数据切换(全部培训=考试通过统计;精益管理=按看板三态计数的完成率统计);精益页签展示单表格明细(已完成+未完成合并为一张表,仅靠状态列区分已完成/已延期/进行中),并提供期次下拉可区分/切换第几期任务(期号按周次升序,最早为第 1 期),切换后重拉对应期看板与精益统计;状态列统一中文显示;权限支持角色默认值与前端用户配置共同控制 |
|
||||
| Chat 附件发送前预览 | 已实现 | 附件列表显示在输入框上方,展示文件类型、名称、真实大小和逐文件处理状态;支持右上角删除,上传中保护删除,发货通知保留解析重试与重复处理入口 |
|
||||
| 培训题库后台配置 | 已实现 | Agent 管理表单支持维护及格线、复盘要点、考前清单与题库;员工培训页优先读取 `extra_config.training_config`,未配置时才回退前端默认题库 |
|
||||
| 培训聊天常见问题分角色配置 | 已实现 | Agent 管理表单支持分别维护普通员工与 HR 管理员进入“员工培训”聊天页时看到的常见问题;聊天欢迎区会按 `training_hr_manage` 权限自动切换对应问题集 |
|
||||
@@ -64,6 +65,8 @@
|
||||
| 首页培训推荐入口 | 前端已实现 | 当 Agent 开启培训模式后,工作台首页会在应用列表上方展示培训强入口卡片 |
|
||||
| 培训记录后端落库 | 已实现 | 已新增培训记录模型、迁移与用户/管理端 API,考试进度、结果、统计与导出均可走后端数据源 |
|
||||
| 培训配置管理 | 已实现 | `TrainingConfigResource` 增加 `training_level`;管理端按公司级、部门级、班组级卡片独立增删资料;知识库候选仅允许“员工培训”分组内未删除文档的当前版本;员工端按 `safetyStage` 动态展示当前级别资料 |
|
||||
| 精益培训对象化任务与提醒 | 已实现 | HR 按系统角色或指定用户(并集)发布精益周任务;任务、看板和提醒只处理冻结对象,首次发布与定向催学均复用企微提醒审计幂等去重。学员端“精益管理”按时间树展示全部已发布任务(按任务周期倒序、最新在上),每期任务带状态徽章(进行中/已延期/已完成,由服务端按截止时间与完成记录判定)、任务周期区间与视频缩略图(点击弹窗播放,须播放到结尾才判定观看完成并由服务端持久化,提前关闭或拖拽跳过不计);提交学习感悟前校验:未观看全部已推送视频或感悟字数不达标时拦截并友好提示;任务"已完成"仅在感悟提交后落定。 |
|
||||
| 精益周任务规则化推送 | 已实现 | 任务周(周一)与截止时间默认按当周计算且**支持修改**(可指定任意自然周与截止时刻,须为周一且截止不早于所选周周一;修改后【发布周任务】/【立即新增任务补推】均作用于所选周任务);培训视频列表分页展示(4 条/页),已推送视频默认勾选、不可取消并带"第X周 MM-DD至MM-DD"周次标签,推过的视频不重复推直至全部推完;【发布周任务】对所选周任务发布并首次自动推首批,【立即新增任务补推】按游标对所选周任务增推;平台排程每周一 09:00(Asia/Shanghai)自动滚动创建当周任务(模板取严格早于当周的最近一期,游标继承进度)并推送下一批,无需人工维护;每批推送成功后立即向受训人员发送企微通知,并对"已延期"(过截止未提交)人员立即发送延期提醒(event_key 幂等防重);学员端任务期号统一采用后端 week_index 口径。规则手册见 [docs/features/training/精益管理周任务规则手册.md](features/training/精益管理周任务规则手册.md) |
|
||||
| 培训主链推荐架构 | 已文档化 | 推荐采用“受控考试主链 + Dify 辅助问答/ChatBI”的混合方案;培训 Agent 对接 Dify 时会额外透传后台账号 `role`,便于区分学员/HR 问答分支,见 [docs/新人入职培训Agent_推荐落地方案.md](新人入职培训Agent_推荐落地方案.md) |
|
||||
| 培训业务闭环整改清单 | 已文档化 | 见[docs/新人入职培训Agent_闭环整改清单.md](新人入职培训Agent_闭环整改清单.md) |
|
||||
|
||||
@@ -700,9 +703,9 @@
|
||||
| 四阶段付款节点 | 已实现 | 解析预付款、出货款、验收款、质保款;不完整合同进入待复核,不伪造节点。 |
|
||||
| 三轮分级预警 | 已实现 | 首次为台账申请人(系统用户真实姓名唯一匹配);第二、三次按申请人部门查 OA 矩阵 `zz`/`jfl`,该 ID 同时用于企业微信。 |
|
||||
| OA 厂商请款判定 | 已实现 | 同步「厂商预付款请款作业」,预付款/出货款存在对应请款事实即停止后续升级。 |
|
||||
| 每日扫描与周五汇总 | 已实现 | 每日生成到期轮次待发送记录;仅周五 18:00 按收件人发送一条企业微信汇总及 Excel 明细附件。 |
|
||||
| 每日扫描与周五汇总 | 已实现 | 每日生成到期轮次待发送记录;仅周五 18:00 按收件人发送一条企业微信汇总及 Excel 明细附件(「收件人」列为实际姓名)。 |
|
||||
| OA 增量同步 | 已实现 | 合同 HTTP 列表以 `oa-contract-archive` 为游标;验收 SQL 以 `oa-acceptance-archive` 独立游标。首次全量,增量按时间窗口 + 采购单号回补;触顶不推进合同断点;重复运行不重复入库。 |
|
||||
| 工作台与审计 | 已实现 | “合同付款预警”左侧二级菜单分为合同台账与周汇总批次;台账展示本周待发送笔数和下一次周五 18:00;周汇总页可查看批次并下载 Excel 附件。具备 `contract_payment.access` 的用户可见菜单并调用 API,不要求平台 admin 角色。 |
|
||||
| 工作台与审计 | 已实现 | “合同付款预警”左侧二级菜单分为合同台账与周汇总批次;台账/待确认支持按合同号、流程号、采购单号或供应商模糊检索;台账展示本周待发送笔数和下一次周五 18:00;周汇总页可查看批次并下载 Excel 附件。具备 `contract_payment.access` 的用户可见菜单并查询,不要求平台 admin 角色;同步/扫描/发送仅管理员。 |
|
||||
|
||||
- [X] Admin 模板比对区域配置、V4 默认恢复与识别预览
|
||||
- [X] 默认启用模板区域规则自动应用于 Chat 双文件比对
|
||||
|
||||
@@ -207,6 +207,7 @@
|
||||
|
||||
<br />
|
||||
|
||||
|
||||
二、前端页面说明
|
||||
|
||||

|
||||
|
||||
- 使用 Flask + SQLAlchemy 合同付款域模型,OA 同步、每日预警扫描与周汇总均注册为平台排程任务;默认时区 `Asia/Shanghai`,周汇总 Cron 为 `0 18 * * 5`。合同付款 Job 运行超时由 `CONTRACT_PAYMENT_JOB_TIMEOUT_SECONDS`(默认 1800 秒)回收:未超过最大重试次数的任务重新排队,耗尽后标记失败,避免 Worker 异常退出导致任务永久停在 `running`。
|
||||
- `contract_payment_alerts` 保存逐笔、逐轮、逐收件人的幂等记录;`contract_payment_alert_batches` 对 `(week_key, recipient_user_id)` 唯一,保存汇总统计、Excel 二进制附件及企微发送审计。
|
||||
- `contract_payment_alerts` 保存逐笔、逐轮、逐收件人的幂等记录;`contract_payment_alert_batches` 对 `(week_key, recipient_user_id)` 唯一,保存汇总统计、Excel 二进制附件及企微发送审计。Excel「收件人」列写入系统用户真实姓名(为空回退用户名),不再写岗位名称。
|
||||
- 企业微信正文只发送汇总数字,附件通过现有临时媒体上传能力发送;OA、DMS 地址和凭据仅通过环境变量配置。
|
||||
- 合同台账接口采用 offset 服务端分页,最大每页 100 条;前端复用 `PaginationBar`,避免同步量增长后一次查询加载全部合同。付款解析不依赖设备采购合同(项目型 V4)或其他固定模板,只根据可识别的合同号、金额、交期及预付款、出货款、验收款、质保款四阶段比例生成计划;比例须完整、无重复且合计为 100%,并要求采购单号非空,作为 ERP `apa_file` 回查预付款/出货款完成事实的业务键。比例校验失败、采购单号缺失、关键事实缺失或合同正文与 OA 字段冲突时写入 `needs_review`,从正常台账排除并由“待确认合同”二级路由通过 `review_only=1` 集中查询。合同详情复用 `/contracts/{id}` 返回合同、附件、节点与解析问题,附件下载必须校验附件归属该合同,批次页面独立调用审计批次接口。
|
||||
- 合同台账接口采用 offset 服务端分页,最大每页 100 条;`keyword` 同时模糊匹配合同编号、流程编号、采购单号和供应商名称。`GET /contracts/summary` 按合同统计即将到期(7 日内)、逾期未付、待补充、本月应付,始终看全部已解析台账;列表 `focus` 与 keyword 叠加过滤。前端复用 `PaginationBar`,避免同步量增长后一次查询加载全部合同。付款解析不依赖设备采购合同(项目型 V4)或其他固定模板,只根据可识别的合同号、金额、交期及预付款、出货款、验收款、质保款四阶段比例生成计划;比例须完整、无重复且合计为 100%,并要求采购单号非空,作为 ERP `apa_file` 回查预付款/出货款完成事实的业务键。比例校验失败、采购单号缺失、关键事实缺失或合同正文与 OA 字段冲突时写入 `needs_review`,从正常台账排除并由“待确认合同”二级路由通过 `review_only=1` 集中查询。合同详情复用 `/contracts/{id}` 返回合同、附件、节点与解析问题,附件下载必须校验附件归属该合同,批次页面独立调用审计批次接口。
|
||||
- OA 附件排序以字段语义为第一优先级:`盖章完成合同上传` 固定优先于 `合同附件`,不得被文件名中的“合同”等关键词逆转;同一字段内部再按文件名对正文和辅助文件排序。
|
||||
- 普通 OA 同步仅补充本地空字段;管理员显式提交 `POST /api/contract-payment/sync` 的 `{ "force": true }` 时,才以 OA 本次非空字段覆盖合同主表。覆盖操作人、时间和 `before/after` 字段差异保存在既有 JSON 列 `source_payload_json.force_sync_audit`(最近 20 次),不新增数据库结构;附件下载及付款计划解析链路保持不变。
|
||||
- 同一同步 Job 支持 `{ "reparse_existing": true }` 存量恢复模式:不依赖 OA 增量通知,遍历已有合同的已归档附件并按盖章完成合同上传优先级重跑解析,刷新 `parse_result_json`、解析状态和节点;单次最多 1000 份,没有附件或文件资产的记录安全跳过。
|
||||
- OA 通知同步采用增量断点:`contract_payment_sync_states` 以 `state_key='oa-contract-archive'` 单行游标记录上次成功同步时间,下次用 `last_successful_sync_at - CONTRACT_PAYMENT_OA_SYNC_OVERLAP_SECONDS` 作为归档时间下限(overlap 兜住迟到/越序记录)。翻页使用 `CONTRACT_PAYMENT_OA_SYNC_PAGE_SIZE` / `..._PAGE_PARAM`;`CONTRACT_PAYMENT_OA_SYNC_MAX_PAGES` 默认 `0`(翻到短页为止),仅约束增量窗口,首次全量忽略此上限。触顶且末页仍满页时标记截断,已入库记录保留但**不推进断点**。重复项由 `(event_type, source_event_id)` 幂等去重;仅当 OA 配置、列表接口可用且本轮未截断时才推进断点。增量窗口只拉"归档时间在窗口内"的合同,窗口外旧合同的字段修正由管理员显式触发:`{ force: true }` 同步绕过时间窗口全量重扫,`{ reparse_existing: true }` 存量重解析遍历全部已归档附件,都会覆盖窗口外记录。
|
||||
- 工作台与 `/api/contract-payment/*` 统一校验功能权限 `contract_payment.access`:`admin` 角色默认开启,其他角色默认关闭,可在用户管理中显式授予或关闭。前端侧栏与路由守卫只负责展示,后端仍做 403 强校验(`CONTRACT_PAYMENT.FORBIDDEN`)。企业微信收件人与该访问权解耦。
|
||||
- 工作台与 `/api/contract-payment/*` 统一校验功能权限 `contract_payment.access`:`admin` 角色默认开启,其他角色默认关闭,可在用户管理中显式授予或关闭。前端侧栏与路由守卫只负责展示,后端仍做 403 强校验(`CONTRACT_PAYMENT.FORBIDDEN`)。`POST /sync`、`POST /alerts/run`、`POST /alerts/weekly-run` 额外要求 `role=admin`(`CONTRACT_PAYMENT.ADMIN_REQUIRED`),企业微信收件人与该访问权解耦。
|
||||
- 验收单归档不走合同申请单 HTTP 列表,而查 OA SQL Server(凭据复用 `OA_SQLSERVER_*`):`formtable_main_324.cgdh` 为采购单号,`requestId` 关联 `workflow_requestbase`,`currentnodetype='3'` 为已归档(0 创建 / 1 批准 / 2 提交 / 3 归档)。归档日取 `lastoperatedate`/`lastoperatetime`。事件幂等键 `oa-acceptance:{requestId}:c{contractId}`,按采购单号匹配台账;独立断点 `oa-acceptance-archive`。查询失败 fail-safe 跳过且不推进该断点。节点后于事件生成时,`_persist_payment_plan` 回放已有验收事件计算验收款/质保款日期。表名/字段可由 `CONTRACT_PAYMENT_OA_ACCEPTANCE_*` 覆盖。
|
||||
- 第二、三轮收件人查同一 OA SQL:`HrmResource.lastname` 唯一匹配台账申请人,取其 `departmentid`;`Matrixtable_3.bm` 关联部门,`zz` 为第二轮、`jfl` 为第三轮。该 ID 即 `HrmResource.id` 与企业微信 userid。优先按 `users.wecom_userid` 映射系统用户,未绑定再用主管 `lastname` 唯一匹配 `real_name`;查不到不向第一轮兜底。表名/字段可由 `CONTRACT_PAYMENT_OA_HRM_*`、`CONTRACT_PAYMENT_OA_MATRIX_*` 覆盖。
|
||||
|
||||
@@ -1303,6 +1303,8 @@ Dify
|
||||
- 管理后台用户编辑表单可对单个用户显式授予或关闭该权限
|
||||
- 前端只根据登录态里的 `feature_permissions.training_hr_manage` 决定是否展示 `HR 管理` 标签;后端仍做强校验,避免仅靠前端隐藏导致越权。
|
||||
|
||||
- 精益周任务不依赖用户的 `team`、`job_title`、`is_team_leader` 字段,也不使用精益专属权限;任务模型冻结 `target_roles` 与 `target_user_ids`,受训对象按角色或用户并集计算,看板和提醒均只处理冻结对象。
|
||||
|
||||
### 19.5 培训资料维护
|
||||
|
||||
- 后台继续复用 `AgentGuide` 资料模型承载培训素材,不单独新建一套上传体系。
|
||||
@@ -1333,6 +1335,8 @@ Dify
|
||||
2. 若未命中发布配置,再兼容读取 `extra_config.training_config`
|
||||
3. 对入职培训、安全培训的存量配置,后端序列化阶段自动补默认进度说明和步骤引导文案,避免旧数据出现空白
|
||||
- 学员侧通用培训进度模块只根据 `progress_items` 动态渲染;当该数组为空时,整个进度模块隐藏,避免显示静态默认流程。
|
||||
- 精益管理培训使用 `lean_management` 独立任务模型:HR 每周发布视频列表、每周推送数量、截止时间及角色/用户对象,员工仅对当前已推送批次提交观看事实及不少于 50 字学习感悟;`LeanTrainingWeeklyTask`、`LeanTrainingCompletion`、`LeanTrainingReminder` 分别承载任务、完成事实和通知幂等审计。
|
||||
- 精益任务、看板与定向提醒统一使用 `training_hr_manage` 强校验;首次发布向在职指定对象发送初始企微通知,逾期提醒按上海时区周一、周三、周五执行。
|
||||
- 题库题量改为后台可配后,前端分数计算改为“按当前题量折算百分制”,不再硬编码每题 5 分。
|
||||
- 管理端支持从已上传并标记为 `training_exam_pdf` 的指南 PDF 解析题库:
|
||||
1. 后端按 `guide_id` 读取 PDF 文本
|
||||
@@ -1475,7 +1479,7 @@ RecoveryPlan → Gate Attempt → Job → Worker/RPA → 幂等回调 → `run_t
|
||||
- 付款计划统一生成 `prepayment`、`shipment`、`acceptance`、`warranty` 节点;预付款以合同申请单归档日、出货款以交货期限、验收款以验收单归档日、质保款以质保到期日作为提醒锚点。
|
||||
- 合同付款预警通过 ERP Oracle `apa_file` 查询付款完成事实:以 `apaud03` 关联采购单号,筛选 `apa41='Y'` 且 `apa63=1`,按 `apa34f` 汇总付款金额;累计金额覆盖节点金额时停止预付款/出货款后续提醒。ERP 未配置或查询失败时 fail-safe 按未付款处理。历史 `contract_payment_vendor_requests` 表保留兼容性,但不再作为付款完成停止条件。
|
||||
- `contract_payment_alerts` 以 `(node_id, trigger_key, recipient_user_id)` 幂等,并保存 `alert_round`。第一轮收件人按台账申请人 `users.real_name` 唯一匹配,匹配失败或重名则不发送、不回退默认管理员。第二、三轮查 OA `HrmResource.lastname` → `departmentid` → `Matrixtable_3.bm`,分别取 `zz`/`jfl` 作为企微 userid;未命中不向第一轮兜底。历史环境变量 `CONTRACT_PAYMENT_DEPARTMENT_HEAD_USER_IDS` / `CONTRACT_PAYMENT_PROCUREMENT_LEADER_USER_IDS` 已不再参与解析。
|
||||
- 预警任务拆分为“每日扫描”和“周五 18:00 汇总发送”:每日仅产生待发送预警,周汇总按收件人聚合并生成 Excel 明细附件,再发送一条企业微信消息;无待发送事项不得发送空消息。汇总批次、Excel 文件和单笔预警的关联须可审计,且同一节点轮次在同一收件人下保持幂等。
|
||||
- 预警任务拆分为“每日扫描”和“周五 18:00 汇总发送”:每日仅产生待发送预警,周汇总按收件人聚合并生成 Excel 明细附件(「收件人」列为系统用户真实姓名,为空回退用户名),再发送一条企业微信消息;无待发送事项不得发送空消息。汇总批次、Excel 文件和单笔预警的关联须可审计,且同一节点轮次在同一收件人下保持幂等。
|
||||
- 合同付款 OA 附件中的 PDF 与采购合同审核固定共用 `PROCUREMENT_CONTRACT_MINERU_*` 配置,并优先调用 MinerU 同步 `/file_parse`:请求携带 `lang_list=ch`、`backend`、`parse_method` 和 `formula_enable=false`,仅接受 `status=completed` 且结果含 `md_content` 的响应。付款条款规则直接消费 Markdown,以保留扫描版合同的表格与阅读顺序;MinerU 故障或空结果则回退附件文字层及历史 OCR,保证同步任务可继续完成。
|
||||
- 验收归档读取 OA SQL Server(`OA_SQLSERVER_*`):`formtable_main_324.cgdh` 匹配采购单号,`workflow_requestbase.currentnodetype='3'`(归档);归档日取 `lastoperatedate`。事件先于付款节点时,解析落库后回放已有 `acceptance_archive` 计算验收款与质保款日期。
|
||||
- `contract_templates.comparison_region_config` 使用 JSON 保存唯一默认启用模板的区域规则,由 Admin API 统一校验。
|
||||
|
||||
@@ -18,7 +18,15 @@ import type {
|
||||
UsageReport,
|
||||
UsageRangeKey,
|
||||
} from '../types/report.types';
|
||||
import type { TrainingConfig, TrainingConfigPayload, TrainingResourceCandidates } from '../types/training-config.types';
|
||||
import type {
|
||||
LeanTrainingWeeklyTask,
|
||||
LeanTrainingWeeklyTaskPayload,
|
||||
LeanTrainingDashboard,
|
||||
LeanTrainingPushLog,
|
||||
TrainingConfig,
|
||||
TrainingConfigPayload,
|
||||
TrainingResourceCandidates,
|
||||
} from '../types/training-config.types';
|
||||
|
||||
const auth = () => ({ headers: getAuthHeaders() });
|
||||
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
|
||||
@@ -454,6 +462,31 @@ export const deleteAdminTrainingConfig = (id: number) =>
|
||||
...auth(),
|
||||
});
|
||||
|
||||
export const createOrUpdateAdminLeanTrainingWeeklyTask = (payload: LeanTrainingWeeklyTaskPayload) =>
|
||||
requestJson<LeanTrainingWeeklyTask>('/api/admin/lean-training/weekly-tasks', {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
export const getAdminLeanTrainingDashboard = () =>
|
||||
requestJson<LeanTrainingDashboard>('/api/admin/lean-training/dashboard', auth());
|
||||
|
||||
/** 按 ID 读取指定周任务详情:发布/补推后刷新所选周任务上下文(dashboard 永远返回最新周,会跳走所选历史周)。 */
|
||||
export const getAdminLeanTrainingWeeklyTask = (taskId: number) =>
|
||||
requestJson<LeanTrainingWeeklyTask>(`/api/admin/lean-training/weekly-tasks/${taskId}`, auth());
|
||||
|
||||
/** HR 手动推送下一批精益培训视频(无需等待每周一排程),返回本轮推送日志。 */
|
||||
export const pushAdminLeanTrainingWeeklyTask = (taskId: number) =>
|
||||
requestJson<LeanTrainingPushLog>(`/api/admin/lean-training/weekly-tasks/${taskId}/push`, {
|
||||
method: 'POST',
|
||||
...auth(),
|
||||
});
|
||||
|
||||
/** 读取指定周任务的分批推送日志(含失败明细),供"推送记录"区块展示。 */
|
||||
export const getAdminLeanTrainingPushLogs = (taskId: number) =>
|
||||
requestJson<LeanTrainingPushLog[]>(`/api/admin/lean-training/weekly-tasks/${taskId}/push-logs`, auth());
|
||||
|
||||
// Users
|
||||
export const listAdminUsers = () => requestJson<AdminUserRow[]>('/api/admin/users', auth());
|
||||
|
||||
|
||||
@@ -20,23 +20,36 @@ import {
|
||||
ListChecks,
|
||||
Plus,
|
||||
Save,
|
||||
Send,
|
||||
Settings2,
|
||||
ShieldCheck,
|
||||
Trash2,
|
||||
Video,
|
||||
X,
|
||||
} from 'lucide-vue-next';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import {
|
||||
createAdminTrainingConfig,
|
||||
createAdminAgentGuide,
|
||||
createOrUpdateAdminLeanTrainingWeeklyTask,
|
||||
deleteAdminTrainingConfig,
|
||||
getAdminLeanTrainingDashboard,
|
||||
getAdminLeanTrainingPushLogs,
|
||||
getAdminLeanTrainingWeeklyTask,
|
||||
listAdminTrainingConfigs,
|
||||
listAdminAgents,
|
||||
listAdminTrainingResourceCandidates,
|
||||
listAdminUsers,
|
||||
parseAdminTrainingQuestionBank,
|
||||
pushAdminLeanTrainingWeeklyTask,
|
||||
updateAdminTrainingConfig,
|
||||
uploadAdminAgentGuideFile,
|
||||
} from '../../api/admin.api';
|
||||
import type {
|
||||
GenericTrainingStage,
|
||||
LeanTrainingPushLog,
|
||||
LeanTrainingWeeklyTask,
|
||||
SafetyTrainingStage,
|
||||
TrainingConfig,
|
||||
TrainingConfigPayload,
|
||||
@@ -44,7 +57,9 @@ import type {
|
||||
TrainingLevel,
|
||||
TrainingProgressItem,
|
||||
} from '../../types/training-config.types';
|
||||
import type { AdminUserRow } from '../../types/admin.types';
|
||||
import TrainingTypeFormModal from './components/TrainingTypeFormModal.vue';
|
||||
import LeanTargetModal from './components/LeanTargetModal.vue';
|
||||
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
@@ -61,9 +76,35 @@ const questionSourceVersionId = ref<number | null>(null);
|
||||
const isParsingQuestions = ref(false);
|
||||
const questionParseMeta = ref<{ mode: string; fileName: string; skipped: number[] } | null>(null);
|
||||
const candidates = ref({ guides: [], documents: [], training_exam_documents: [] } as Awaited<ReturnType<typeof listAdminTrainingResourceCandidates>>);
|
||||
const leanTask = ref<LeanTrainingWeeklyTask | null>(null);
|
||||
const leanWeekKey = ref('');
|
||||
const leanDueAt = ref('');
|
||||
const leanWeeklyCount = ref(1);
|
||||
const leanVideoResourceIds = ref<number[]>([]);
|
||||
const leanTargetRoles = ref<string[]>([]);
|
||||
const leanTargetUserIds = ref<number[]>([]);
|
||||
const leanTargetUsers = ref<AdminUserRow[]>([]);
|
||||
const isSavingLeanTask = ref(false);
|
||||
const isPushingLeanTask = ref(false);
|
||||
const leanPushLogs = ref<LeanTrainingPushLog[]>([]);
|
||||
const isUploadingVideo = ref(false);
|
||||
const videoInput = ref<HTMLInputElement | null>(null);
|
||||
// 培训视频列表分页:一页最多 4 条记录(周任务规则)
|
||||
const LEAN_VIDEO_PAGE_SIZE = 4;
|
||||
const leanVideoPage = ref(1);
|
||||
|
||||
const selected = computed(() => configs.value.find((item) => item.id === selectedId.value) || null);
|
||||
const form = ref<TrainingConfigPayload>(emptyForm());
|
||||
const isSafetyConfig = computed(() => form.value.training_type === 'safety');
|
||||
const supportsDirectVideoUpload = computed(() => (
|
||||
['lean_management', 'overseas_regulations', 'overseas_regulations_training', 'overseas_training'].includes(form.value.training_type)
|
||||
|| form.value.name.includes('出国规章')
|
||||
));
|
||||
const videoGuideCandidates = computed(() => candidates.value.guides.filter((guide) => guide.file_type.toLowerCase() === 'video'));
|
||||
const directVideoResources = computed(() => contentResources.value.filter((resource) => (
|
||||
resource.resource_type === 'agent_guide'
|
||||
&& videoGuideCandidates.value.some((guide) => guide.id === resource.agent_guide_id)
|
||||
)));
|
||||
const contentResources = computed(() => form.value.resources.filter((resource) => resource.resource_type !== 'inline_questions'));
|
||||
const trainingLevels: TrainingLevel[] = ['company', 'department', 'team'];
|
||||
const guideGroups = computed(() => {
|
||||
@@ -97,7 +138,8 @@ const sectionItems = computed(() => [
|
||||
{ id: 'resources', label: t('admin.trainingConfig.sections.resourcesTitle'), icon: Library },
|
||||
{ id: 'exam', label: t('admin.trainingConfig.sections.examTitle'), icon: FileQuestion },
|
||||
{ id: 'review', label: t('admin.trainingConfig.sections.reviewTitle'), icon: ClipboardCheck },
|
||||
]);
|
||||
{ id: 'lean', label: t('admin.trainingConfig.sections.leanTitle'), icon: Video },
|
||||
].filter((item) => item.id !== 'lean' || form.value.training_type === 'lean_management'));
|
||||
const publishedCount = computed(() => configs.value.filter((config) => config.status === 'published').length);
|
||||
const resourceCount = computed(() => contentResources.value.length);
|
||||
const configuredLevelCount = computed(() => trainingLevels.filter((level) => resourcesByLevel(level).length > 0).length);
|
||||
@@ -120,6 +162,197 @@ const progressItems = computed(() => {
|
||||
const settings = form.value.settings as TrainingConfigSettings;
|
||||
return Array.isArray(settings.progress_items) ? settings.progress_items : [];
|
||||
});
|
||||
const leanVideoResources = computed(() => form.value.resources.filter((resource) => {
|
||||
if (resource.resource_type !== 'agent_guide' || !resource.id || !resource.agent_guide_id) return false;
|
||||
const guide = candidates.value.guides.find((item) => item.id === resource.agent_guide_id);
|
||||
return Boolean(guide?.file_type?.toLowerCase().startsWith('video'));
|
||||
}));
|
||||
const leanTaskVideoNames = computed(() => new Map(leanVideoResources.value.map((resource) => [
|
||||
resource.id as number,
|
||||
resource.title || candidates.value.guides.find((guide) => guide.id === resource.agent_guide_id)?.file_name || t('admin.trainingConfig.lean.unnamedVideo'),
|
||||
])));
|
||||
// 培训视频分页展示:一页最多 4 条(周任务规则 1)
|
||||
const leanVideoTotalPages = computed(() => Math.max(1, Math.ceil(leanVideoResources.value.length / LEAN_VIDEO_PAGE_SIZE)));
|
||||
const leanVideoResourcesPaged = computed(() => (
|
||||
leanVideoResources.value.slice((leanVideoPage.value - 1) * LEAN_VIDEO_PAGE_SIZE, leanVideoPage.value * LEAN_VIDEO_PAGE_SIZE)
|
||||
));
|
||||
const leanRoleOptions = computed(() => [...new Set(leanTargetUsers.value.map((user) => user.role).filter(Boolean))].sort());
|
||||
// 已选用户 ID → 用户行映射,用于受训对象列表展示真实姓名/用户名
|
||||
const leanTargetUserMap = computed(() => new Map(leanTargetUsers.value.map((user) => [user.id, user])));
|
||||
const showLeanTargetModal = ref(false);
|
||||
|
||||
/** 已选用户展示名:优先真实姓名,缺失时回退用户名,与弹窗选择列表口径一致。 */
|
||||
const leanTargetUserName = (userId: number): string => {
|
||||
const user = leanTargetUserMap.value.get(userId);
|
||||
if (!user) return `#${userId}`;
|
||||
return user.real_name || user.username;
|
||||
};
|
||||
|
||||
/** 移除单个已选角色(弹窗外快捷操作,未保存前仅影响草稿状态)。 */
|
||||
const removeLeanRole = (role: string) => {
|
||||
leanTargetRoles.value = leanTargetRoles.value.filter((item) => item !== role);
|
||||
};
|
||||
|
||||
/** 移除单个已选员工。 */
|
||||
const removeLeanUser = (userId: number) => {
|
||||
leanTargetUserIds.value = leanTargetUserIds.value.filter((item) => item !== userId);
|
||||
};
|
||||
|
||||
/** 接收受训弹窗确认结果,写回角色与用户 ID 草稿,等待"保存任务"统一提交。 */
|
||||
const handleLeanTargetSave = (payload: { roles: string[]; userIds: number[] }) => {
|
||||
leanTargetRoles.value = payload.roles;
|
||||
leanTargetUserIds.value = payload.userIds;
|
||||
showLeanTargetModal.value = false;
|
||||
};
|
||||
|
||||
function mondayOfCurrentWeek(): string {
|
||||
const today = new Date();
|
||||
const monday = new Date(today);
|
||||
monday.setDate(today.getDate() - ((today.getDay() + 6) % 7));
|
||||
return monday.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function defaultLeanDueAt(weekKey: string): string {
|
||||
const due = new Date(`${weekKey}T23:59:00`);
|
||||
due.setDate(due.getDate() + 6);
|
||||
const local = new Date(due.getTime() - due.getTimezoneOffset() * 60000);
|
||||
return local.toISOString().slice(0, 16);
|
||||
}
|
||||
|
||||
/** 将后端 UTC ISO 时间转换为 datetime-local 输入框本地值(YYYY-MM-DDTHH:mm),非法值返回空串。 */
|
||||
const toLocalDateTimeInput = (iso: string | null | undefined): string => {
|
||||
if (!iso) return '';
|
||||
const parsed = new Date(iso);
|
||||
if (Number.isNaN(parsed.getTime())) return '';
|
||||
const local = new Date(parsed.getTime() - parsed.getTimezoneOffset() * 60000);
|
||||
return local.toISOString().slice(0, 16);
|
||||
};
|
||||
|
||||
const loadLeanTask = async () => {
|
||||
if (form.value.training_type !== 'lean_management') return;
|
||||
try {
|
||||
const dashboard = await getAdminLeanTrainingDashboard();
|
||||
leanTask.value = dashboard.task;
|
||||
} catch {
|
||||
leanTask.value = null;
|
||||
}
|
||||
// [RULE] 任务周与截止时间支持修改:已有任务回填其周次与截止(本地时区展示),新任务默认当周(周一 ~ 周日 23:59);保存后按所选周创建/更新
|
||||
leanWeekKey.value = leanTask.value?.week_key || mondayOfCurrentWeek();
|
||||
leanDueAt.value = leanTask.value?.due_at ? toLocalDateTimeInput(leanTask.value.due_at) : defaultLeanDueAt(leanWeekKey.value);
|
||||
leanWeeklyCount.value = leanTask.value?.weekly_count ?? 1;
|
||||
leanVideoResourceIds.value = leanTask.value?.video_resource_ids ? [...leanTask.value.video_resource_ids] : [];
|
||||
leanTargetRoles.value = leanTask.value?.target_roles ? [...leanTask.value.target_roles] : [];
|
||||
leanTargetUserIds.value = leanTask.value?.target_user_ids ? [...leanTask.value.target_user_ids] : [];
|
||||
leanTargetUsers.value = await listAdminUsers();
|
||||
leanVideoPage.value = 1;
|
||||
if (leanTask.value) await loadLeanPushLogs();
|
||||
};
|
||||
|
||||
/** 拉取当前周任务的分批推送日志(含失败明细),供"推送记录"区块展示。 */
|
||||
const loadLeanPushLogs = async () => {
|
||||
if (!leanTask.value) return;
|
||||
try {
|
||||
leanPushLogs.value = await getAdminLeanTrainingPushLogs(leanTask.value.id);
|
||||
} catch {
|
||||
leanPushLogs.value = [];
|
||||
}
|
||||
};
|
||||
|
||||
/** 立即新增任务补推:按现有游标逻辑对新增任务视频增推一批(数量=每周任务数量),无需等待每周一排程;成功后刷新任务与日志。 */
|
||||
const pushLeanTaskNow = async () => {
|
||||
if (!leanTask.value || isPushingLeanTask.value) return;
|
||||
isPushingLeanTask.value = true;
|
||||
try {
|
||||
const log = await pushAdminLeanTrainingWeeklyTask(leanTask.value.id);
|
||||
if (log.status === 'completed') {
|
||||
msg.warning(t('admin.trainingConfig.lean.pushCompleted'));
|
||||
} else {
|
||||
msg.success(t('admin.trainingConfig.lean.pushSuccess', { count: log.pushed_count }));
|
||||
}
|
||||
// [STEP] 补推后按所选周任务刷新(而非 dashboard 最新周),保持表单周次/截止/游标上下文一致
|
||||
try {
|
||||
leanTask.value = await getAdminLeanTrainingWeeklyTask(leanTask.value.id);
|
||||
leanVideoResourceIds.value = leanTask.value?.video_resource_ids ? [...leanTask.value.video_resource_ids] : [];
|
||||
} catch {
|
||||
// 刷新失败不吞掉推送成功结果,游标以推送日志为准
|
||||
}
|
||||
await loadLeanPushLogs();
|
||||
} catch (error) {
|
||||
msg.error(error instanceof Error ? error.message : t('admin.trainingConfig.lean.pushFailed'));
|
||||
} finally {
|
||||
isPushingLeanTask.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 判断视频是否为已推送(锁定)状态:任务游标前缀内的视频已推送给受训员工。
|
||||
* 业务约束:推送过的视频默认勾选且不能取消勾选(周任务规则 5)。
|
||||
*/
|
||||
const isLeanVideoLocked = (resourceId: number): boolean => {
|
||||
const pushedCount = leanTask.value?.pushed_video_count ?? 0;
|
||||
return (leanTask.value?.video_resource_ids || []).slice(0, pushedCount).includes(resourceId);
|
||||
};
|
||||
|
||||
/**
|
||||
* 已推送视频的周次标签:"第N周 MM-DD至MM-DD"(N=任务期号,范围为该任务周)。
|
||||
* 仅已推送视频展示(周任务规则 4),未推送视频返回空字符串。
|
||||
*/
|
||||
const leanVideoWeekLabel = (resourceId: number): string => {
|
||||
if (!isLeanVideoLocked(resourceId) || !leanTask.value) return '';
|
||||
const weekKey = leanTask.value.week_key || '';
|
||||
const weekEnd = leanTask.value.week_end || '';
|
||||
const range = weekKey && weekEnd ? `${weekKey.slice(5)}至${weekEnd.slice(5)}` : weekKey;
|
||||
return t('admin.trainingConfig.lean.weekRangeLabel', { index: leanTask.value.week_index ?? 1, range });
|
||||
};
|
||||
|
||||
/** 培训视频翻页:目标页越界时收敛到有效范围。 */
|
||||
const goLeanVideoPage = (page: number) => {
|
||||
leanVideoPage.value = Math.min(Math.max(1, page), leanVideoTotalPages.value);
|
||||
};
|
||||
|
||||
/** 切换视频选择:已推送(锁定)视频禁止取消勾选;新视频可自由追加/移除,保存后按选择顺序继续分批推送。 */
|
||||
const toggleLeanVideo = (resourceId: number) => {
|
||||
if (isLeanVideoLocked(resourceId)) return;
|
||||
leanVideoResourceIds.value = leanVideoResourceIds.value.includes(resourceId)
|
||||
? leanVideoResourceIds.value.filter((id) => id !== resourceId)
|
||||
: [...leanVideoResourceIds.value, resourceId];
|
||||
};
|
||||
|
||||
const saveLeanTask = async () => {
|
||||
// 任务周必须为周一:date input 允许选任意日期,前端先行拦截,后端同规则兜底校验
|
||||
if (!leanWeekKey.value || new Date(`${leanWeekKey.value}T00:00:00`).getDay() !== 1) {
|
||||
msg.warning(t('admin.trainingConfig.lean.weekMustBeMonday'));
|
||||
return;
|
||||
}
|
||||
isSavingLeanTask.value = true;
|
||||
try {
|
||||
leanTask.value = await createOrUpdateAdminLeanTrainingWeeklyTask({
|
||||
// 任务周/截止时间支持修改:按表单所选周创建或更新,发布/补推均作用于所选周任务(周任务规则 7)
|
||||
week_key: leanWeekKey.value,
|
||||
due_at: new Date(leanDueAt.value).toISOString(),
|
||||
// 未勾选任何视频时传空数组,服务端自动按上传时间倒序冻结全部视频(周任务规则 6)
|
||||
video_resource_ids: leanVideoResourceIds.value,
|
||||
target_roles: leanTargetRoles.value,
|
||||
target_user_ids: leanTargetUserIds.value,
|
||||
weekly_count: leanWeeklyCount.value,
|
||||
});
|
||||
// 保存后回填勾选状态(空选择时服务端可能已自动填充全部视频)
|
||||
leanVideoResourceIds.value = leanTask.value?.video_resource_ids ? [...leanTask.value.video_resource_ids] : [];
|
||||
await loadLeanPushLogs();
|
||||
msg.success(t('admin.trainingConfig.messages.leanTaskSaved'));
|
||||
} catch (error) {
|
||||
msg.error(error instanceof Error ? error.message : t('admin.trainingConfig.messages.saveFailed'));
|
||||
} finally {
|
||||
isSavingLeanTask.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 推送批次展示名:视频序号(从 1 起)+ 资源标题。 */
|
||||
const leanPushedVideoLabel = (resourceId: number): string => {
|
||||
const index = leanTask.value?.video_resource_ids.indexOf(resourceId) ?? -1;
|
||||
const name = leanTaskVideoNames.value.get(resourceId) || `#${resourceId}`;
|
||||
return index >= 0 ? `${String(index + 1).padStart(2, '0')} ${name}` : name;
|
||||
};
|
||||
|
||||
/** 创建新增培训类型所需的完整默认配置,确保沿用后端既有字段契约。 */
|
||||
function emptyForm(): TrainingConfigPayload {
|
||||
@@ -181,6 +414,7 @@ const selectConfig = (config: TrainingConfig) => {
|
||||
questionJsonText.value = JSON.stringify(questions, null, 2);
|
||||
questionSourceVersionId.value = null;
|
||||
questionParseMeta.value = null;
|
||||
void loadLeanTask();
|
||||
};
|
||||
|
||||
/** 从已选择的员工培训知识库当前 PDF 解析题库,并将结果回填到可继续手工编辑的 JSON。 */
|
||||
@@ -428,6 +662,54 @@ const updateResourceType = (resource: TrainingConfigPayload['resources'][number]
|
||||
resource.kb_document_version_id = undefined;
|
||||
};
|
||||
|
||||
const openVideoUpload = () => videoInput.value?.click();
|
||||
|
||||
const uploadTrainingVideo = async (event: Event) => {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
input.value = '';
|
||||
if (!file) return;
|
||||
if (!file.type.startsWith('video/')) {
|
||||
msg.warning(t('admin.trainingConfig.messages.videoFileRequired'));
|
||||
return;
|
||||
}
|
||||
isUploadingVideo.value = true;
|
||||
try {
|
||||
const trainingAgent = (await listAdminAgents()).find((agent) => (
|
||||
agent.handler_config?.content_profile === 'training'
|
||||
|| agent.extra_config?.training_workspace_enabled === true
|
||||
|| agent.extra_config?.training_mode === true
|
||||
|| agent.extra_config?.training_agent === true
|
||||
));
|
||||
if (!trainingAgent) throw new Error(t('admin.trainingConfig.messages.trainingAgentRequired'));
|
||||
const uploaded = await uploadAdminAgentGuideFile(file);
|
||||
const created = await createAdminAgentGuide({
|
||||
agent_id: trainingAgent.id,
|
||||
file_name: uploaded.file_name,
|
||||
file_path: uploaded.file_path,
|
||||
file_type: uploaded.file_type,
|
||||
file_size: uploaded.file_size,
|
||||
guide_usage: 'training_video',
|
||||
sort_order: candidates.value.guides.length,
|
||||
status: 1,
|
||||
}) as { id: number };
|
||||
candidates.value = await listAdminTrainingResourceCandidates();
|
||||
form.value.resources.push({
|
||||
resource_type: 'agent_guide',
|
||||
agent_guide_id: created.id,
|
||||
training_level: 'company',
|
||||
title: uploaded.file_name,
|
||||
required_duration: 0,
|
||||
sort_order: form.value.resources.length,
|
||||
});
|
||||
msg.success(t('admin.trainingConfig.messages.videoUploaded'));
|
||||
} catch (error) {
|
||||
msg.error(error instanceof Error ? error.message : t('admin.trainingConfig.messages.videoUploadFailed'));
|
||||
} finally {
|
||||
isUploadingVideo.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const scrollToSection = (sectionId: string) => {
|
||||
activeSection.value = sectionId;
|
||||
document.getElementById(`training-section-${sectionId}`)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
@@ -614,7 +896,26 @@ onMounted(() => void load());
|
||||
<p class="mt-1 text-xs text-muted">{{ t('admin.trainingConfig.resourcesEmptyHint') }}</p>
|
||||
</div>
|
||||
<div class="flex flex-col gap-5">
|
||||
<article v-if="supportsDirectVideoUpload" class="w-full overflow-hidden rounded-2xl border border-violet-200 bg-surface shadow-sm">
|
||||
<div class="flex flex-col gap-3 border-b border-violet-200 bg-violet-50/80 px-5 py-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h4 class="text-base font-bold text-primary">{{ t('admin.trainingConfig.directVideo.title') }}</h4>
|
||||
<p class="mt-1 text-xs text-muted">{{ t('admin.trainingConfig.directVideo.hint') }}</p>
|
||||
</div>
|
||||
<button class="btn-secondary btn-sm" type="button" :disabled="isUploadingVideo" @click="openVideoUpload"><Plus class="h-4 w-4" />{{ isUploadingVideo ? t('admin.trainingConfig.directVideo.uploading') : t('admin.trainingConfig.directVideo.upload') }}</button>
|
||||
<input ref="videoInput" type="file" accept="video/*" class="hidden" @change="uploadTrainingVideo" />
|
||||
</div>
|
||||
<div class="space-y-3 p-4 md:p-5">
|
||||
<div v-if="!directVideoResources.length" class="rounded-xl border border-dashed border-default bg-surface-soft/50 px-3 py-8 text-center text-xs text-muted">{{ t('admin.trainingConfig.directVideo.empty') }}</div>
|
||||
<div v-for="(resource, index) in directVideoResources" v-else :key="resource.id || `direct-video-${index}`" class="grid gap-3 rounded-xl border border-default bg-white p-4 md:grid-cols-[minmax(0,1fr)_180px_auto] md:items-end">
|
||||
<div class="flex min-w-0 items-center gap-2 text-sm font-medium text-primary"><Video class="h-4 w-4 shrink-0 text-violet-500" /><span class="truncate">{{ resource.title || videoGuideCandidates.find((guide) => guide.id === resource.agent_guide_id)?.file_name || t('admin.trainingConfig.directVideo.unnamed') }}</span></div>
|
||||
<label class="label-field">{{ t('admin.trainingConfig.fields.requiredDuration') }}<input v-model.number="resource.required_duration" type="number" min="0" class="input-field mt-2" /></label>
|
||||
<button class="btn-danger btn-sm" type="button" @click="removeResource(resource)"><Trash2 class="h-4 w-4" />{{ t('admin.delete') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
<article
|
||||
v-if="isSafetyConfig"
|
||||
v-for="(level, levelIndex) in trainingLevels"
|
||||
:key="level"
|
||||
class="w-full overflow-hidden rounded-2xl border bg-surface shadow-sm"
|
||||
@@ -667,6 +968,108 @@ onMounted(() => void load());
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section v-if="form.training_type === 'lean_management'" id="training-section-lean" class="surface-panel scroll-mt-20 p-5 md:p-7">
|
||||
<div class="mb-6 flex items-start gap-3">
|
||||
<span class="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-emerald-50 text-emerald-600"><Video class="h-5 w-5" /></span>
|
||||
<div><h3 class="text-base font-bold text-primary">{{ t('admin.trainingConfig.sections.leanTitle') }}</h3><p class="mt-1 text-sm text-muted">{{ t('admin.trainingConfig.sections.leanDesc') }}</p></div>
|
||||
</div>
|
||||
<div v-if="form.status !== 'published'" class="rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800">{{ t('admin.trainingConfig.lean.publishRequired') }}</div>
|
||||
<div v-else class="space-y-5">
|
||||
<div class="grid gap-5 md:grid-cols-3">
|
||||
<!-- 任务周/截止时间支持修改:按所选自然周创建或更新任务,【发布周任务】/【立即新增任务补推】均作用于所选周 -->
|
||||
<label class="label-field">{{ t('admin.trainingConfig.lean.weekKey') }}<input v-model="leanWeekKey" type="date" class="input-field mt-2" /></label>
|
||||
<label class="label-field">{{ t('admin.trainingConfig.lean.dueAt') }}<input v-model="leanDueAt" type="datetime-local" class="input-field mt-2" /></label>
|
||||
<!-- 每周任务数量:每周一 09:00 按该数量从视频列表顺序推送下一批给受训对象 -->
|
||||
<label class="label-field">{{ t('admin.trainingConfig.lean.weeklyCount') }}<input v-model.number="leanWeeklyCount" type="number" min="1" max="50" class="input-field mt-2" /></label>
|
||||
</div>
|
||||
<p class="-mt-2 text-xs text-muted">{{ t('admin.trainingConfig.lean.weeklyCountHint', { pushed: leanTask?.pushed_video_count ?? 0, total: leanVideoResourceIds.length }) }}</p>
|
||||
<div class="rounded-xl border border-default bg-surface-soft/40 p-4">
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<div><h4 class="text-sm font-semibold text-primary">{{ t('admin.trainingConfig.lean.videosTitle') }}</h4><p class="mt-1 text-xs text-muted">{{ t('admin.trainingConfig.lean.videosHint', { count: leanVideoResourceIds.length }) }}</p></div>
|
||||
<span v-if="leanTask" class="rounded-full bg-emerald-50 px-3 py-1 text-xs font-medium text-emerald-700">{{ t('admin.trainingConfig.lean.pushProgress', { pushed: leanTask.pushed_video_count, total: leanTask.video_resource_ids.length }) }}</span>
|
||||
</div>
|
||||
<div v-if="!leanVideoResources.length" class="mt-4 rounded-lg border border-dashed border-default bg-white px-4 py-5 text-sm text-muted">{{ t('admin.trainingConfig.lean.noVideoResources') }}</div>
|
||||
<template v-else>
|
||||
<!-- 培训视频分页展示:一页最多 4 条(周任务规则 1);已推送视频锁定勾选并展示周次标签 -->
|
||||
<div class="mt-4 grid gap-3 md:grid-cols-2">
|
||||
<label v-for="resource in leanVideoResourcesPaged" :key="resource.id" class="flex items-center gap-3 rounded-xl border bg-white p-4 transition" :class="leanVideoResourceIds.includes(resource.id as number) ? 'border-emerald-400 ring-1 ring-emerald-200' : 'border-default'" :style="isLeanVideoLocked(resource.id as number) ? 'cursor:not-allowed' : 'cursor:pointer'">
|
||||
<input :checked="leanVideoResourceIds.includes(resource.id as number)" type="checkbox" :disabled="isLeanVideoLocked(resource.id as number)" class="h-4 w-4 rounded border-default text-emerald-600 focus:ring-emerald-500 disabled:opacity-70" @change="toggleLeanVideo(resource.id as number)" />
|
||||
<span class="min-w-0 flex-1 truncate text-sm text-primary">{{ leanTaskVideoNames.get(resource.id as number) }}</span>
|
||||
<!-- 已推送视频展示所属周次:"第N周 MM-DD至MM-DD"(不可取消勾选) -->
|
||||
<span v-if="leanVideoWeekLabel(resource.id as number)" class="shrink-0 rounded-full bg-emerald-50 px-2.5 py-0.5 text-xs font-medium text-emerald-700">{{ leanVideoWeekLabel(resource.id as number) }}</span>
|
||||
</label>
|
||||
</div>
|
||||
<!-- 分页控件:超过一页时展示上一页/下一页与页码概览 -->
|
||||
<div v-if="leanVideoTotalPages > 1" class="mt-3 flex items-center justify-end gap-2 text-xs text-muted">
|
||||
<button class="btn-secondary btn-sm" type="button" :disabled="leanVideoPage <= 1" @click="goLeanVideoPage(leanVideoPage - 1)">{{ t('admin.trainingConfig.lean.videoPagePrev') }}</button>
|
||||
<span>{{ t('admin.trainingConfig.lean.videoPageInfo', { page: leanVideoPage, total: leanVideoTotalPages }) }}</span>
|
||||
<button class="btn-secondary btn-sm" type="button" :disabled="leanVideoPage >= leanVideoTotalPages" @click="goLeanVideoPage(leanVideoPage + 1)">{{ t('admin.trainingConfig.lean.videoPageNext') }}</button>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
<div class="rounded-xl border border-default bg-surface-soft/40 p-4">
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<div><h4 class="text-sm font-semibold text-primary">{{ t('admin.trainingConfig.lean.targetsTitle') }}</h4><p class="mt-1 text-xs text-muted">{{ t('admin.trainingConfig.lean.targetsHint') }}</p></div>
|
||||
<button class="btn-secondary btn-sm" type="button" @click="showLeanTargetModal = true"><Plus class="h-4 w-4" />{{ t('admin.trainingConfig.lean.addTarget') }}</button>
|
||||
</div>
|
||||
<!-- 已选受训对象列表:角色与员工以 chip 展示,支持快捷移除 -->
|
||||
<div v-if="!leanTargetRoles.length && !leanTargetUserIds.length" class="mt-4 rounded-lg border border-dashed border-default bg-white px-4 py-5 text-sm text-muted">{{ t('admin.trainingConfig.lean.targetEmpty') }}</div>
|
||||
<div v-else class="mt-4 space-y-3">
|
||||
<div v-if="leanTargetRoles.length" class="flex flex-wrap items-center gap-2">
|
||||
<span class="shrink-0 text-xs font-medium text-muted">{{ t('admin.trainingConfig.lean.targetRoles') }}</span>
|
||||
<span v-for="role in leanTargetRoles" :key="role" class="inline-flex items-center gap-1 rounded-full bg-emerald-50 px-3 py-1 text-xs font-medium text-emerald-700">
|
||||
{{ role }}
|
||||
<button type="button" class="rounded-full transition hover:text-emerald-900" :title="t('admin.trainingConfig.lean.removeTarget')" @click="removeLeanRole(role)"><X class="h-3 w-3" /></button>
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="leanTargetUserIds.length" class="flex flex-wrap items-center gap-2">
|
||||
<span class="shrink-0 text-xs font-medium text-muted">{{ t('admin.trainingConfig.lean.targetUsersCount', { count: leanTargetUserIds.length }) }}</span>
|
||||
<span v-for="userId in leanTargetUserIds" :key="userId" class="inline-flex items-center gap-1 rounded-full bg-sky-50 px-3 py-1 text-xs font-medium text-sky-700">
|
||||
{{ leanTargetUserName(userId) }}
|
||||
<button type="button" class="rounded-full transition hover:text-sky-900" :title="t('admin.trainingConfig.lean.removeTarget')" @click="removeLeanUser(userId)"><X class="h-3 w-3" /></button>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 添加受训弹窗:按角色 / 按员工多选 -->
|
||||
<LeanTargetModal
|
||||
:visible="showLeanTargetModal"
|
||||
:roles="leanTargetRoles"
|
||||
:user-ids="leanTargetUserIds"
|
||||
:users="leanTargetUsers"
|
||||
:role-options="leanRoleOptions"
|
||||
@close="showLeanTargetModal = false"
|
||||
@save="handleLeanTargetSave"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-emerald-200 bg-emerald-50/50 p-4">
|
||||
<p class="text-sm text-emerald-800">{{ t('admin.trainingConfig.lean.summaryRule', { count: 50 }) }}</p>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<!-- 手动推送:立即按每周任务数量推送下一批视频,无需等待每周一排程 -->
|
||||
<button class="btn-secondary btn-sm" type="button" :disabled="!leanTask || isPushingLeanTask" @click="pushLeanTaskNow"><Send class="h-4 w-4" />{{ isPushingLeanTask ? t('admin.trainingConfig.lean.pushing') : t('admin.trainingConfig.lean.pushNow') }}</button>
|
||||
<button class="btn-primary btn-sm" type="button" :disabled="isSavingLeanTask || !leanWeekKey || !leanDueAt || leanVideoResourceIds.length < 1 || (!leanTargetRoles.length && !leanTargetUserIds.length)" @click="saveLeanTask"><Save class="h-4 w-4" />{{ isSavingLeanTask ? t('admin.trainingConfig.saving') : t('admin.trainingConfig.lean.saveTask') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 推送记录:每轮发布/排程/手动推送的批次、成败计数与失败明细 -->
|
||||
<div class="rounded-xl border border-default bg-surface-soft/40 p-4">
|
||||
<h4 class="text-sm font-semibold text-primary">{{ t('admin.trainingConfig.lean.pushLogsTitle') }}</h4>
|
||||
<div v-if="!leanPushLogs.length" class="mt-3 rounded-lg border border-dashed border-default bg-white px-4 py-5 text-sm text-muted">{{ t('admin.trainingConfig.lean.pushLogsEmpty') }}</div>
|
||||
<ul v-else class="mt-3 space-y-3">
|
||||
<li v-for="log in leanPushLogs" :key="log.id" class="rounded-lg border bg-white p-3 text-sm" :class="log.status === 'failed' ? 'border-red-200' : 'border-default'">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="rounded-full px-2.5 py-0.5 text-xs font-medium" :class="log.status === 'failed' ? 'bg-red-50 text-red-700' : log.status === 'partial' ? 'bg-amber-50 text-amber-700' : 'bg-emerald-50 text-emerald-700'">{{ t(`admin.trainingConfig.lean.pushStatus.${log.status}`) }}</span>
|
||||
<span class="text-xs text-muted">{{ t(`admin.trainingConfig.lean.pushTrigger.${log.trigger}`) }} · {{ log.created_at ? new Date(log.created_at).toLocaleString() : '' }}</span>
|
||||
</div>
|
||||
<p class="mt-2 text-xs text-muted">{{ t('admin.trainingConfig.lean.pushBatch', { count: log.pushed_count, sent: log.sent_count, failed: log.failed_count, recipients: log.recipient_count }) }}</p>
|
||||
<div v-if="log.pushed_resource_ids?.length" class="mt-2 flex flex-wrap gap-1.5">
|
||||
<span v-for="resourceId in log.pushed_resource_ids" :key="resourceId" class="rounded-full bg-slate-100 px-2.5 py-0.5 text-xs text-slate-600">{{ leanPushedVideoLabel(resourceId) }}</span>
|
||||
</div>
|
||||
<p v-if="log.error_message" class="mt-2 rounded bg-red-50 px-2.5 py-1.5 text-xs text-red-700">{{ log.error_message }}</p>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="training-section-exam" class="surface-panel scroll-mt-20 p-5 md:p-7">
|
||||
<div class="mb-6 flex items-start justify-between gap-4">
|
||||
<div class="flex items-start gap-3">
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/admin/modules/training-config/components/LeanTargetModal.vue
|
||||
* 用途:精益周任务"受训对象"选择弹窗,支持按角色、按员工两个维度多选(两个范围取并集生效)。
|
||||
* 依赖:vue-i18n、lucide 图标与父级培训配置页面传入的目标状态(角色/用户 ID/用户列表)。
|
||||
* 逻辑:弹窗打开时从 props 快照到本地草稿(取消不污染外部状态);员工支持关键字搜索;
|
||||
* 确认后 emit save({ roles, userIds }),由父级写回表单并随"保存任务"统一落库。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Search } from 'lucide-vue-next';
|
||||
import type { AdminUserRow } from '../../../types/admin.types';
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean;
|
||||
roles: string[];
|
||||
userIds: number[];
|
||||
users: AdminUserRow[];
|
||||
roleOptions: string[];
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{ close: []; save: [payload: { roles: string[]; userIds: number[] }] }>();
|
||||
const { t } = useI18n();
|
||||
|
||||
const draftRoles = ref<string[]>([]);
|
||||
const draftUserIds = ref<number[]>([]);
|
||||
const keyword = ref('');
|
||||
|
||||
// [STEP 1] 打开时同步父级当前选择,避免用户在弹窗内取消后残留草稿
|
||||
watch(() => props.visible, (visible) => {
|
||||
if (visible) {
|
||||
draftRoles.value = [...props.roles];
|
||||
draftUserIds.value = [...props.userIds];
|
||||
keyword.value = '';
|
||||
}
|
||||
});
|
||||
|
||||
// [STEP 2] 员工列表按姓名/用户名/部门模糊过滤,便于在大量员工中快速定位
|
||||
const filteredUsers = computed(() => {
|
||||
const query = keyword.value.trim().toLowerCase();
|
||||
if (!query) return props.users;
|
||||
return props.users.filter((user) => [user.real_name, user.username, user.department]
|
||||
.some((field) => field && field.toLowerCase().includes(query)));
|
||||
});
|
||||
|
||||
const summaryLabel = computed(() => t('admin.trainingConfig.lean.targetSelectedCount', {
|
||||
roles: draftRoles.value.length,
|
||||
users: draftUserIds.value.length,
|
||||
}));
|
||||
|
||||
const toggleRole = (role: string) => {
|
||||
draftRoles.value = draftRoles.value.includes(role)
|
||||
? draftRoles.value.filter((item) => item !== role)
|
||||
: [...draftRoles.value, role];
|
||||
};
|
||||
|
||||
const toggleUser = (userId: number) => {
|
||||
draftUserIds.value = draftUserIds.value.includes(userId)
|
||||
? draftUserIds.value.filter((item) => item !== userId)
|
||||
: [...draftUserIds.value, userId];
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
emit('save', { roles: [...draftRoles.value], userIds: [...draftUserIds.value] });
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="props.visible" class="admin-modal-overlay animate-fade-in items-center" @click.self="emit('close')">
|
||||
<div class="admin-modal-panel max-w-2xl max-h-[92vh] scale-100">
|
||||
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
|
||||
<h3 class="section-title">{{ t('admin.trainingConfig.lean.targetModalTitle') }}</h3>
|
||||
<p class="mt-1 text-xs text-muted">{{ t('admin.trainingConfig.lean.targetsHint') }}</p>
|
||||
</div>
|
||||
<div class="px-5 sm:px-8 py-5 overflow-y-auto">
|
||||
<div class="grid gap-5 md:grid-cols-2">
|
||||
<!-- 按角色选择 -->
|
||||
<div class="space-y-2">
|
||||
<label class="label-field">{{ t('admin.trainingConfig.lean.targetRoles') }}</label>
|
||||
<div class="space-y-2 rounded-xl border border-default bg-surface p-3">
|
||||
<label
|
||||
v-for="role in props.roleOptions"
|
||||
:key="role"
|
||||
class="flex cursor-pointer items-center gap-3 rounded-lg px-2 py-2 text-sm transition hover:bg-surface-soft"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
class="h-4 w-4 rounded border-default text-emerald-600 focus:ring-emerald-500"
|
||||
:checked="draftRoles.includes(role)"
|
||||
@change="toggleRole(role)"
|
||||
/>
|
||||
<span class="text-primary">{{ role }}</span>
|
||||
</label>
|
||||
<p v-if="!props.roleOptions.length" class="px-2 py-3 text-xs text-muted">{{ t('admin.trainingConfig.lean.targetRolesEmpty') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 按员工选择 -->
|
||||
<div class="space-y-2">
|
||||
<label class="label-field">{{ t('admin.trainingConfig.lean.targetUsers') }}</label>
|
||||
<div class="relative">
|
||||
<Search class="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted" />
|
||||
<input
|
||||
v-model="keyword"
|
||||
type="text"
|
||||
class="input-field pl-9 text-sm"
|
||||
:placeholder="t('admin.trainingConfig.lean.targetSearchPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="max-h-64 space-y-1 overflow-y-auto rounded-xl border border-default bg-surface p-2">
|
||||
<label
|
||||
v-for="user in filteredUsers"
|
||||
:key="user.id"
|
||||
class="flex cursor-pointer items-center gap-3 rounded-lg px-2 py-2 text-sm transition hover:bg-surface-soft"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
class="h-4 w-4 rounded border-default text-emerald-600 focus:ring-emerald-500"
|
||||
:checked="draftUserIds.includes(user.id)"
|
||||
@change="toggleUser(user.id)"
|
||||
/>
|
||||
<span class="min-w-0 flex-1 truncate text-primary">{{ user.real_name || user.username }}</span>
|
||||
<span class="shrink-0 text-xs text-muted">{{ user.username }}</span>
|
||||
</label>
|
||||
<p v-if="!filteredUsers.length" class="px-2 py-3 text-xs text-muted">{{ t('admin.trainingConfig.lean.targetUsersEmpty') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="admin-modal-footer">
|
||||
<p class="mr-auto text-xs text-muted">{{ summaryLabel }}</p>
|
||||
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
|
||||
<button type="button" class="btn-primary" @click="handleSave">
|
||||
{{ t('admin.trainingConfig.lean.targetConfirm') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -58,6 +58,54 @@ export interface TrainingConfigPayload {
|
||||
resources: TrainingConfigResource[];
|
||||
}
|
||||
|
||||
/** 精益推送日志:记录每轮(发布/排程/手动)分批推送视频的执行结果与失败明细。 */
|
||||
export interface LeanTrainingPushLog {
|
||||
id: number;
|
||||
weekly_task_id: number;
|
||||
trigger: 'publish' | 'schedule' | 'manual' | string;
|
||||
pushed_resource_ids: number[];
|
||||
pushed_count: number;
|
||||
recipient_count: number;
|
||||
sent_count: number;
|
||||
skipped_count: number;
|
||||
failed_count: number;
|
||||
status: 'sent' | 'partial' | 'failed' | 'completed' | string;
|
||||
error_message: string | null;
|
||||
created_by_id: number | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface LeanTrainingWeeklyTask {
|
||||
id: number;
|
||||
week_key: string;
|
||||
/** 任务周周日(ISO 日期),与 week_key 拼装"第N周 MM-DD至MM-DD"周次标签。 */
|
||||
week_end: string | null;
|
||||
/** 期号:按周次升序编号,最早一周为第 1 期。 */
|
||||
week_index: number;
|
||||
due_at: string;
|
||||
video_resource_ids: number[];
|
||||
target_roles: string[];
|
||||
target_user_ids: number[];
|
||||
videos: Array<{ id: number; name: string }>;
|
||||
status: string;
|
||||
min_summary_length: number;
|
||||
weekly_count: number;
|
||||
pushed_video_count: number;
|
||||
}
|
||||
|
||||
export interface LeanTrainingWeeklyTaskPayload {
|
||||
week_key: string;
|
||||
due_at: string;
|
||||
video_resource_ids: number[];
|
||||
target_roles: string[];
|
||||
target_user_ids: number[];
|
||||
weekly_count: number;
|
||||
}
|
||||
|
||||
export interface LeanTrainingDashboard {
|
||||
task: LeanTrainingWeeklyTask | null;
|
||||
}
|
||||
|
||||
export interface TrainingResourceCandidates {
|
||||
guides: Array<{
|
||||
id: number;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* features/chat/api/training.api.ts
|
||||
* 用途:培训工作区专用 HTTP API,负责员工进度读取/保存、HR 记录查询、统计和导出。
|
||||
* 用途:培训工作区专用 HTTP API,负责员工进度读取/保存、HR 记录查询、统计导出和精益任务提醒。
|
||||
* 依赖:shared/api/client、auth headers、training.types。
|
||||
* 逻辑:把后端 training 领域的 snake_case 返回值统一映射成前端工作区需要的 camelCase 结构。
|
||||
* 逻辑:把后端 training 领域的 snake_case 返回值统一映射成前端工作区需要的 camelCase 结构,并提交精益未完成人员提醒请求。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
@@ -15,10 +15,60 @@ import type {
|
||||
TrainingRecord,
|
||||
TrainingStage,
|
||||
TrainingStats,
|
||||
LeanTrainingDashboard,
|
||||
LeanTrainingDashboardRow,
|
||||
LeanTrainingMyTask,
|
||||
LeanTrainingTaskStatus,
|
||||
LeanTrainingWeeklyTask,
|
||||
TrainingType,
|
||||
TrainingTypeOption,
|
||||
} from '../training/training.types';
|
||||
|
||||
type LeanTrainingTaskApi = {
|
||||
id: number; week_key: string; due_at: string; video_resource_ids: number[];
|
||||
target_roles: string[]; target_user_ids: number[];
|
||||
videos: Array<{ id: number; name: string; file_url?: string | null }>; status: string; min_summary_length: number;
|
||||
weekly_count?: number; pushed_video_count?: number;
|
||||
week_end?: string | null; week_index?: number;
|
||||
};
|
||||
|
||||
type LeanTrainingMyTaskApi = LeanTrainingTaskApi & {
|
||||
task_status: LeanTrainingTaskStatus;
|
||||
completion: { summary_text: string; watched_at: Record<string, string>; completed_at?: string | null } | null;
|
||||
};
|
||||
|
||||
type LeanTrainingDashboardRowApi = {
|
||||
id?: number; user_id: number; employee_id?: string | null; name: string; department?: string | null;
|
||||
videos: Array<{ name: string; watched_at?: string | null }>;
|
||||
// 后端序列化层三态归一:completed=已提交感悟;overdue=过截止未完成;in_progress=进行中
|
||||
summary_text?: string | null; status: 'completed' | 'in_progress' | 'overdue'; completed_at?: string | null;
|
||||
};
|
||||
|
||||
const mapLeanTask = (data: LeanTrainingTaskApi): LeanTrainingWeeklyTask => ({
|
||||
id: data.id, weekKey: data.week_key, dueAt: data.due_at, videoResourceIds: data.video_resource_ids || [],
|
||||
targetRoles: data.target_roles || [], targetUserIds: data.target_user_ids || [],
|
||||
videos: (data.videos || []).map((video) => ({ id: video.id, name: video.name, fileUrl: video.file_url || null })),
|
||||
status: data.status, minSummaryLength: data.min_summary_length,
|
||||
weeklyCount: data.weekly_count, pushedVideoCount: data.pushed_video_count,
|
||||
weekEnd: data.week_end ?? null, weekIndex: data.week_index,
|
||||
});
|
||||
|
||||
const mapLeanMyTask = (data: LeanTrainingMyTaskApi): LeanTrainingMyTask => ({
|
||||
...mapLeanTask(data),
|
||||
taskStatus: data.task_status,
|
||||
completion: data.completion ? {
|
||||
summaryText: data.completion.summary_text,
|
||||
watchedAt: data.completion.watched_at || {},
|
||||
completedAt: data.completion.completed_at || null,
|
||||
} : null,
|
||||
});
|
||||
|
||||
const mapLeanDashboardRow = (data: LeanTrainingDashboardRowApi): LeanTrainingDashboardRow => ({
|
||||
id: data.id, userId: data.user_id, employeeId: data.employee_id, name: data.name, department: data.department,
|
||||
videos: (data.videos || []).map((item) => ({ name: item.name, watchedAt: item.watched_at })),
|
||||
summaryText: data.summary_text, status: data.status, completedAt: data.completed_at,
|
||||
});
|
||||
|
||||
type TrainingRecordApi = {
|
||||
id: number;
|
||||
user_id?: number;
|
||||
@@ -229,6 +279,47 @@ export async function getMyTrainingTypes(): Promise<TrainingTypeOption[]> {
|
||||
return requestJson<TrainingTypeOption[]>('/api/user/training-types', authHeaders());
|
||||
}
|
||||
|
||||
export async function getMyLeanTrainingTasks(): Promise<LeanTrainingMyTask[]> {
|
||||
const response = await requestJson<LeanTrainingMyTaskApi[]>('/api/user/lean-training/my-tasks', authHeaders());
|
||||
return (response || []).map(mapLeanMyTask);
|
||||
}
|
||||
|
||||
export async function markMyLeanVideoWatched(weeklyTaskId: number, resourceId: number): Promise<void> {
|
||||
await requestJson<{ watched_at: Record<string, string> }>('/api/user/lean-training/my-tasks/watched', {
|
||||
method: 'POST',
|
||||
...jsonAuthHeaders(),
|
||||
body: JSON.stringify({ weekly_task_id: weeklyTaskId, resource_id: resourceId }),
|
||||
});
|
||||
}
|
||||
|
||||
export async function saveMyLeanTrainingCompletion(payload: { weeklyTaskId: number; watchedAt: Record<string, string>; summaryText: string }): Promise<LeanTrainingDashboardRow> {
|
||||
const response = await requestJson<LeanTrainingDashboardRowApi>('/api/user/lean-training/completions', {
|
||||
method: 'PUT', ...jsonAuthHeaders(), body: JSON.stringify({ weekly_task_id: payload.weeklyTaskId, watched_at: payload.watchedAt, summary_text: payload.summaryText }),
|
||||
});
|
||||
return mapLeanDashboardRow(response);
|
||||
}
|
||||
|
||||
export async function getLeanTrainingDashboard(taskId?: number): Promise<LeanTrainingDashboard> {
|
||||
// task_id 为空时后端返回最新一期;periods 为全部期次摘要(期号按周次升序),供管理端下拉切换第几期。
|
||||
const query = taskId ? `?task_id=${taskId}` : '';
|
||||
const response = await requestJson<{ task: LeanTrainingTaskApi | null; completed: LeanTrainingDashboardRowApi[]; incomplete: LeanTrainingDashboardRowApi[]; periods?: Array<{ id: number; week_key: string; index: number }> }>(`/api/admin/lean-training/dashboard${query}`, authHeaders());
|
||||
return {
|
||||
task: response.task ? mapLeanTask(response.task) : null,
|
||||
completed: (response.completed || []).map(mapLeanDashboardRow),
|
||||
incomplete: (response.incomplete || []).map(mapLeanDashboardRow),
|
||||
periods: (response.periods || []).map((period) => ({ id: period.id, weekKey: period.week_key, index: period.index })),
|
||||
};
|
||||
}
|
||||
|
||||
/** HR 对指定成员发起精益培训定向提醒;返回后端实发统计(sent/failed 才是真实送达情况,created 含发送失败)。 */
|
||||
export async function sendLeanTrainingReminders(weeklyTaskId: number, userIds: number[]): Promise<{ created: number; sent: number; skipped: number; failed: number }> {
|
||||
return requestJson<{ created: number; sent: number; skipped: number; failed: number }>(`/api/admin/lean-training/weekly-tasks/${weeklyTaskId}/reminders`, {
|
||||
method: 'POST',
|
||||
...jsonAuthHeaders(),
|
||||
body: JSON.stringify({ user_ids: userIds }),
|
||||
});
|
||||
}
|
||||
|
||||
export async function getMyTrainingProgress(type: string = 'onboarding'): Promise<TrainingProgressRecord | null> {
|
||||
const data = await requestJson<TrainingRecordApi | null>(`/api/user/training-record?type=${encodeURIComponent(type)}`, authHeaders());
|
||||
return data ? mapTrainingProgressRecord(data) : null;
|
||||
|
||||
@@ -9,8 +9,10 @@
|
||||
*/
|
||||
import { computed, reactive, ref, watch, type ShallowUnwrapRef } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import {
|
||||
BookOpen,
|
||||
Bell,
|
||||
CheckCircle2,
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
@@ -31,11 +33,11 @@ import FilePreviewModal from '@/shared/components/FilePreviewModal.vue';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { resolveTrainingExamPdfGuide, type TrainingGuideLike } from '@/features/chat/training/trainingWorkspace.utils';
|
||||
import { getMyTrainingConfig } from '@/features/chat/api/training.api';
|
||||
import type { TrainingAnswerRecord, TrainingRecord, TrainingQuestion } from '@/features/chat/training/training.types';
|
||||
import type { TrainingAnswerRecord, TrainingRecord, TrainingQuestion, LeanTrainingMyTask, LeanTrainingTaskStatus, LeanTrainingVideo } from '@/features/chat/training/training.types';
|
||||
import html2pdf from 'html2pdf.js';
|
||||
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
|
||||
|
||||
const props = defineProps<{
|
||||
currentAgent: Record<string, unknown> | null;
|
||||
currentUser: Record<string, unknown> | null;
|
||||
@@ -72,7 +74,8 @@ const learnerStageIconMap = {
|
||||
result: ShieldCheck,
|
||||
} as const;
|
||||
const currentLearnerStageIndex = computed(() => learnerStageOrder.indexOf(workspace.stage));
|
||||
const showLearnerProgressModule = computed(() => workspace.learnerProgressItems.length > 0);
|
||||
// 进度模块仅在配置了多阶段流程时展示;单阶段培训(如出国规章培训仅视频学习)无进度追踪意义,主区域卡片与右侧栏面板同步隐藏。
|
||||
const showLearnerProgressModule = computed(() => workspace.learnerProgressItems.length > 1);
|
||||
const learnerProgressItems = computed(() => workspace.learnerProgressItems.map((item, index) => {
|
||||
const stageIndex = learnerStageOrder.indexOf(item.stage as typeof learnerStageOrder[number]);
|
||||
const status = stageIndex >= 0 && currentLearnerStageIndex.value >= 0
|
||||
@@ -117,6 +120,12 @@ const handleVideoSeeking = (e: Event) => {
|
||||
};
|
||||
|
||||
const handleVideoEnded = () => {
|
||||
// 精益任务视频:仅当播放到结尾才记录观看完成(配合防拖拽保证按时长完整观看)
|
||||
if (activeLeanVideo.value) {
|
||||
workspace.markLeanVideoWatched(activeLeanVideo.value.taskId, activeLeanVideo.value.resourceId);
|
||||
msg.success(t('chat.training.lean.videoWatchedToast'));
|
||||
activeLeanVideo.value = null;
|
||||
}
|
||||
workspace.showVideoModal = false;
|
||||
workspace.stopMaterialTimer();
|
||||
};
|
||||
@@ -284,6 +293,33 @@ const openWorkspaceView = (view: typeof workspace.activeView) => {
|
||||
setWorkspaceExpanded(true, true);
|
||||
};
|
||||
|
||||
// [STEP] 企微提醒卡片深链支持:/chat/<agentId>?training_type=lean_management&weekly_task_id=<id>
|
||||
// AI 触发时机:员工/HR 从企微“和信AI智能工作台”精益提醒卡片点入时,自动展开精益培训对应页签
|
||||
// (管理员进管理端看板、学员进学员侧学习页),无需手动点页签,保证卡片“点击直达”体验。
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
let leanJumpConsumed = false;
|
||||
watch(
|
||||
() => [workspace.isTrainingAgent, Boolean(props.currentUser), workspace.canManageTrainingWorkspace] as const,
|
||||
([isTraining, loggedIn]) => {
|
||||
// 仅在培训 Agent 且登录态就绪后消费一次,避免身份权限异步未加载时误判视图归属
|
||||
if (!isTraining || !loggedIn || leanJumpConsumed) return;
|
||||
leanJumpConsumed = true;
|
||||
if (route.query.training_type !== 'lean_management') return;
|
||||
if (workspace.canManageTrainingWorkspace) {
|
||||
workspace.activeView = 'admin';
|
||||
workspace.hrTrainingTab = 'lean';
|
||||
} else {
|
||||
workspace.activeView = 'learner';
|
||||
workspace.learnerTab = 'lean_management';
|
||||
}
|
||||
setWorkspaceExpanded(true, true);
|
||||
// 消费后清理深链参数,避免刷新或分享链接时重复自动展开
|
||||
void router.replace({ query: { ...route.query, training_type: undefined, weekly_task_id: undefined } });
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
/**
|
||||
* 收起培训工作区并回到纯聊天页面。
|
||||
* AI 触发时机:点击“收起工作区”时,必须立即恢复聊天消息区与输入栏,而不是仅折叠局部内容。
|
||||
@@ -326,7 +362,7 @@ const applyDefaultExpandedState = () => {
|
||||
|
||||
// 监听 Agent/角色切换,重置本地展开态:培训角色首次进入默认展开工作区。
|
||||
watch(
|
||||
() => [props.currentAgent?.id, workspace.isAdminViewer],
|
||||
() => [props.currentAgent?.id, workspace.canManageTrainingWorkspace],
|
||||
() => {
|
||||
userExpandedOverride.value = null;
|
||||
applyDefaultExpandedState();
|
||||
@@ -414,6 +450,40 @@ const isMaterialCompleted = (material: any) => {
|
||||
};
|
||||
|
||||
const currentPreviewVideoUrl = ref('');
|
||||
const activeNonSafetyVideoId = ref<number | null>(null);
|
||||
const nonSafetyVideoMaterials = computed(() => workspace.publishedTrainingMaterials.filter((material) => (
|
||||
material.resource?.fileType === 'video' && Boolean(material.resource.fileUrl)
|
||||
)));
|
||||
const activeNonSafetyVideo = computed(() => (
|
||||
nonSafetyVideoMaterials.value.find((material) => material.id === activeNonSafetyVideoId.value)
|
||||
|| nonSafetyVideoMaterials.value[0]
|
||||
|| null
|
||||
));
|
||||
|
||||
const selectNonSafetyVideo = (material: { id?: number | null; resource?: { fileUrl?: string } | null }) => {
|
||||
if (!material.resource?.fileUrl) return;
|
||||
if (workspace.currentViewingMaterialId !== material.id) {
|
||||
workspace.stopMaterialTimer();
|
||||
}
|
||||
activeNonSafetyVideoId.value = material.id ?? null;
|
||||
workspace.currentViewingMaterialId = material.id ?? null;
|
||||
};
|
||||
|
||||
const startNonSafetyVideoTimer = () => {
|
||||
if (activeNonSafetyVideo.value?.id != null) {
|
||||
workspace.startMaterialTimer(activeNonSafetyVideo.value.id);
|
||||
}
|
||||
};
|
||||
|
||||
const stopNonSafetyVideoTimer = () => {
|
||||
workspace.stopMaterialTimer();
|
||||
};
|
||||
|
||||
watch([() => workspace.learnerTab, nonSafetyVideoMaterials], () => {
|
||||
if (!nonSafetyVideoMaterials.value.some((material) => material.id === activeNonSafetyVideoId.value)) {
|
||||
activeNonSafetyVideoId.value = nonSafetyVideoMaterials.value[0]?.id ?? null;
|
||||
}
|
||||
}, { immediate: true });
|
||||
|
||||
const videoCountdownSeconds = ref(0);
|
||||
let videoCountdownTimer: ReturnType<typeof setInterval> | null = null;
|
||||
@@ -477,11 +547,69 @@ const handlePreviewClose = (val: boolean) => {
|
||||
};
|
||||
|
||||
const handleVideoModalClose = () => {
|
||||
// 提前关闭弹窗视为未完成观看:清空精益视频定位,不记录观看
|
||||
activeLeanVideo.value = null;
|
||||
workspace.showVideoModal = false;
|
||||
currentPreviewVideoUrl.value = '';
|
||||
stopVideoCountdown();
|
||||
workspace.stopMaterialTimer();
|
||||
};
|
||||
|
||||
/** 当前弹窗正在播放的精益任务视频定位(非精益视频播放时为 null),用于播放到结尾时记录对应任务与视频。 */
|
||||
const activeLeanVideo = ref<{ taskId: number; resourceId: number } | null>(null);
|
||||
|
||||
/** 精益任务状态徽章样式与文案键映射:进行中 / 已延期 / 已完成。 */
|
||||
const leanStatusMeta: Record<LeanTrainingTaskStatus, { badgeClass: string; labelKey: string }> = {
|
||||
in_progress: { badgeClass: 'border-blue-200 bg-blue-50 text-blue-700', labelKey: 'chat.training.lean.taskStatus.in_progress' },
|
||||
overdue: { badgeClass: 'border-red-200 bg-red-50 text-red-600', labelKey: 'chat.training.lean.taskStatus.overdue' },
|
||||
completed: { badgeClass: 'border-emerald-200 bg-emerald-50 text-emerald-700', labelKey: 'chat.training.lean.taskStatus.completed' },
|
||||
};
|
||||
|
||||
/** 看板总结弹框上下文:员工姓名 + 完整总结文案;为 null 时弹框关闭。 */
|
||||
const summaryModal = ref<{ name: string; text: string } | null>(null);
|
||||
|
||||
/** 总结列预览截断:最多显示 15 个字,超出部分以省略号收尾,点击可弹框查看全文。 */
|
||||
const truncateSummary = (text: string) => (text.length > 15 ? `${text.slice(0, 15)}…` : text);
|
||||
|
||||
/** 打开总结详情弹框:仅当该行有总结文案时可点击(无总结的行显示 "--" 不可点)。 */
|
||||
const openSummaryModal = (name: string, text: string) => {
|
||||
summaryModal.value = { name, text };
|
||||
};
|
||||
|
||||
/** 视频缩略图取首帧地址:追加 #t=0.1 让浏览器在 preload=metadata 下渲染首帧画面。 */
|
||||
const leanThumbSrc = (url?: string | null) => (url ? (url.includes('#') ? url : `${url}#t=0.1`) : '');
|
||||
|
||||
/**
|
||||
* 打开精益任务视频弹窗播放。
|
||||
* AI 触发时机:学员在精益管理时间树上点击任务视频缩略图时调用;无播放地址时给出提示且不打开弹窗。
|
||||
* 注意:此处不记录观看,观看完成仅在视频播放到结尾(handleVideoEnded)时记录。
|
||||
*/
|
||||
const openLeanVideo = (task: LeanTrainingMyTask, video: LeanTrainingVideo) => {
|
||||
if (!video.fileUrl) {
|
||||
msg.warning(t('chat.training.lean.videoUnavailable'));
|
||||
return;
|
||||
}
|
||||
activeLeanVideo.value = { taskId: task.id, resourceId: video.id };
|
||||
workspace.showVideoModal = true;
|
||||
currentPreviewVideoUrl.value = video.fileUrl;
|
||||
};
|
||||
|
||||
/**
|
||||
* 提交精益学习感悟前的友好校验:未看完全部已推送视频或感悟字数不足时仅提示,不发请求。
|
||||
* AI 触发时机:学员点击某期任务的"提交学习感悟"按钮时调用。
|
||||
*/
|
||||
const handleLeanSubmit = (task: LeanTrainingMyTask) => {
|
||||
const watchedCount = Object.keys(workspace.leanWatchedByTask[task.id] || {}).length;
|
||||
if (watchedCount < task.videos.length) {
|
||||
msg.warning(t('chat.training.lean.completeVideosFirst'));
|
||||
return;
|
||||
}
|
||||
if ((workspace.leanSummaryByTask[task.id] || '').trim().length < task.minSummaryLength) {
|
||||
msg.warning(t('chat.training.lean.summaryTooShort', { minSummaryLength: task.minSummaryLength }));
|
||||
return;
|
||||
}
|
||||
void workspace.submitLeanTrainingCompletion(task.id);
|
||||
};
|
||||
const jumpToExamQuestion = (index: number) => {
|
||||
if (!canNavigateExamQuestions.value) return;
|
||||
workspace.syncExamQuestionIndex(index);
|
||||
@@ -533,7 +661,7 @@ const currentSafetyStageText = computed(() => {
|
||||
{{ $t('chat.training.tabs.learner') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="workspace.isAdminViewer"
|
||||
v-if="workspace.canManageTrainingWorkspace"
|
||||
type="button"
|
||||
class="rounded-full px-3 py-1.5 text-xs font-medium transition"
|
||||
:class="workspace.activeView === 'admin' ? 'bg-brand-600 text-white' : 'bg-surface-soft text-secondary hover:bg-slate-100'"
|
||||
@@ -546,7 +674,7 @@ const currentSafetyStageText = computed(() => {
|
||||
|
||||
<div class="flex flex-wrap items-center justify-end gap-2">
|
||||
<button
|
||||
v-if="trainingExamPdfGuide"
|
||||
v-if="trainingExamPdfGuide && workspace.learnerTab === 'safety'"
|
||||
type="button"
|
||||
class="inline-flex h-9 items-center gap-2 rounded-xl border border-default bg-white px-3.5 text-xs font-medium leading-none text-secondary transition hover:bg-surface-soft"
|
||||
@click="emit('open-guide', Number(trainingExamPdfGuide.id))"
|
||||
@@ -555,7 +683,7 @@ const currentSafetyStageText = computed(() => {
|
||||
<span class="leading-none">{{ $t('chat.training.actions.viewExamPdf') }}</span>
|
||||
</button>
|
||||
<button
|
||||
v-if="workspace.stage === 'video'"
|
||||
v-if="workspace.learnerTab === 'safety' && workspace.safetyViewStage !== 'exam' && workspace.safetyViewStage !== 'result'"
|
||||
type="button"
|
||||
class="inline-flex min-h-9 items-center gap-2 rounded-xl border border-brand-200 bg-brand-50 px-3 py-2 text-xs font-medium text-brand-700 transition hover:bg-brand-100"
|
||||
@click="showVideoModal = true"
|
||||
@@ -619,7 +747,7 @@ const currentSafetyStageText = computed(() => {
|
||||
{{ $t('chat.training.tabs.learner') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="workspace.isAdminViewer"
|
||||
v-if="workspace.canManageTrainingWorkspace"
|
||||
type="button"
|
||||
class="rounded-full px-3 py-1.5 text-xs font-medium transition"
|
||||
:class="workspace.activeView === 'admin' ? 'bg-brand-600 text-white' : 'bg-surface-soft text-secondary hover:bg-slate-100'"
|
||||
@@ -632,7 +760,7 @@ const currentSafetyStageText = computed(() => {
|
||||
|
||||
<div class="flex flex-wrap items-center justify-end gap-2">
|
||||
<button
|
||||
v-if="trainingExamPdfGuide"
|
||||
v-if="trainingExamPdfGuide && workspace.learnerTab === 'safety'"
|
||||
type="button"
|
||||
class="inline-flex h-9 items-center gap-2 rounded-xl border border-default bg-white px-3.5 text-xs font-medium leading-none text-secondary transition hover:bg-surface-soft"
|
||||
@click="emit('open-guide', Number(trainingExamPdfGuide.id))"
|
||||
@@ -708,7 +836,68 @@ const currentSafetyStageText = computed(() => {
|
||||
<div class="mt-3 text-base font-semibold text-primary">{{ $t('chat.training.noContent.title') }}</div>
|
||||
<div class="mt-1 text-sm">{{ $t('chat.training.noContent.description') }}</div>
|
||||
</div>
|
||||
<template v-else-if="workspace.learnerTab !== 'safety'">
|
||||
<div v-if="workspace.learnerTab === 'lean_management'" class="col-span-full">
|
||||
<div v-if="!workspace.leanMyTasks.length" class="rounded-2xl border border-dashed border-default bg-white px-6 py-12 text-center text-sm text-secondary">
|
||||
{{ $t('chat.training.lean.learner.empty') }}
|
||||
</div>
|
||||
<!-- 时间树:后端按发布周期倒序返回,最新任务在最上方 -->
|
||||
<div v-else class="rounded-2xl border border-emerald-200 bg-emerald-50/40 p-4">
|
||||
<div class="text-base font-semibold text-primary">{{ $t('chat.training.lean.learner.title') }}</div>
|
||||
<div class="relative mt-4">
|
||||
<div class="absolute bottom-3 left-[7px] top-3 w-px bg-emerald-200" aria-hidden="true"></div>
|
||||
<div v-for="(task, index) in workspace.leanMyTasks" :key="task.id" class="relative pl-7" :class="index > 0 ? 'pt-4' : ''">
|
||||
<span class="absolute left-0 top-7 h-[15px] w-[15px] rounded-full border-[3px] bg-white" :class="task.taskStatus === 'completed' ? 'border-emerald-500' : task.taskStatus === 'overdue' ? 'border-red-400' : 'border-blue-500'" aria-hidden="true"></span>
|
||||
<article class="rounded-2xl border border-default bg-white p-4">
|
||||
<div class="flex flex-wrap items-start justify-between gap-2">
|
||||
<div>
|
||||
<!-- 期号优先用后端 weekIndex(按周次升序,最早为第 1 期),与管理端口径一致;旧数据兜底按返回顺序倒推编号 -->
|
||||
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.lean.learner.taskTitle', { index: task.weekIndex ?? workspace.leanMyTasks.length - index }) }}</div>
|
||||
<div class="mt-1 text-xs text-secondary">{{ $t('chat.training.lean.learner.description', { count: task.videos.length, minSummaryLength: task.minSummaryLength }) }}</div>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="rounded-full border px-3 py-1 text-xs font-medium" :class="leanStatusMeta[task.taskStatus].badgeClass">{{ $t(leanStatusMeta[task.taskStatus].labelKey) }}</span>
|
||||
<span class="rounded-full bg-surface-soft px-3 py-1 text-xs text-secondary">{{ $t('chat.training.lean.learner.taskPeriod', { start: task.weekKey, end: task.dueAt.slice(0, 10) }) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 任务视频缩略图:点击弹出播放器完成学习并记录观看 -->
|
||||
<div class="mt-3 grid gap-3 md:grid-cols-2">
|
||||
<div v-for="video in task.videos" :key="video.id" class="overflow-hidden rounded-xl border border-default bg-surface-soft">
|
||||
<button type="button" class="group relative block h-32 w-full" @click="openLeanVideo(task, video)">
|
||||
<video v-if="video.fileUrl" :src="leanThumbSrc(video.fileUrl)" preload="metadata" muted playsinline class="h-full w-full object-cover"></video>
|
||||
<div v-else class="flex h-full w-full items-center justify-center text-secondary"><Video class="h-8 w-8" /></div>
|
||||
<span class="absolute inset-0 flex items-center justify-center transition group-hover:bg-slate-900/20">
|
||||
<PlayCircle class="h-9 w-9 text-white drop-shadow" />
|
||||
</span>
|
||||
<!-- 观看完成标记:服务端持久化,刷新后仍显示 -->
|
||||
<span v-if="(workspace.leanWatchedByTask[task.id] || {})[String(video.id)]" class="absolute top-2 right-2 rounded-full bg-emerald-500 px-2 py-0.5 text-xs font-medium text-white shadow">{{ $t('chat.training.lean.videoWatchedBadge') }}</span>
|
||||
</button>
|
||||
<div class="p-3">
|
||||
<div class="flex items-center gap-2 text-sm font-medium text-primary"><Video class="h-4 w-4 shrink-0 text-emerald-600" /><span class="truncate">{{ video.name }}</span></div>
|
||||
<div class="mt-1 text-xs" :class="(workspace.leanWatchedByTask[task.id] || {})[String(video.id)] ? 'text-emerald-600' : 'text-secondary'">
|
||||
{{ (workspace.leanWatchedByTask[task.id] || {})[String(video.id)] ? $t('chat.training.lean.watchedAt', { time: ((workspace.leanWatchedByTask[task.id] || {})[String(video.id)] || '').slice(0, 16).replace('T', ' ') }) : $t('chat.training.lean.markVideoWatched') }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 已完成:只读展示已提交感悟与完成时间;进行中/已延期:可继续编辑并提交 -->
|
||||
<div v-if="task.taskStatus === 'completed' && task.completion" class="mt-3 rounded-xl bg-emerald-50/60 p-3">
|
||||
<div class="text-xs font-medium text-emerald-700">{{ $t('chat.training.lean.learner.completedSummary') }}<template v-if="task.completion.completedAt"> · {{ $t('chat.training.lean.learner.completedAt', { time: task.completion.completedAt.slice(0, 16).replace('T', ' ') }) }}</template></div>
|
||||
<p class="mt-1 whitespace-pre-wrap text-sm text-primary">{{ task.completion.summaryText }}</p>
|
||||
</div>
|
||||
<template v-else>
|
||||
<textarea v-model="workspace.leanSummaryByTask[task.id]" rows="4" class="mt-3 w-full rounded-xl border border-default bg-white p-3 text-sm" :placeholder="$t('chat.training.lean.summaryPlaceholder', { minSummaryLength: task.minSummaryLength })" />
|
||||
<div class="mt-2 flex items-center justify-between gap-3">
|
||||
<span class="text-xs" :class="(workspace.leanSummaryByTask[task.id] || '').length >= task.minSummaryLength ? 'text-emerald-600' : 'text-amber-600'">{{ $t('chat.training.lean.summaryLength', { current: (workspace.leanSummaryByTask[task.id] || '').length, minSummaryLength: task.minSummaryLength }) }}</span>
|
||||
<!-- 未看完视频/字数不足时不静默禁用,点击由 handleLeanSubmit 给出友好提示 -->
|
||||
<button type="button" class="rounded-xl bg-emerald-600 px-4 py-2 text-sm font-medium text-white" @click="handleLeanSubmit(task)">{{ $t('chat.training.lean.submitSummary') }}</button>
|
||||
</div>
|
||||
</template>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<template v-if="workspace.learnerTab !== 'safety' && workspace.learnerTab !== 'lean_management'">
|
||||
<div :class="learnerWorkspaceMainClass">
|
||||
<div v-if="showLearnerProgressModule" :class="progressCardClass">
|
||||
<div class="flex flex-col gap-1.5 lg:flex-row lg:items-start lg:justify-between">
|
||||
@@ -762,31 +951,34 @@ const currentSafetyStageText = computed(() => {
|
||||
<p v-if="learnerStepIntroDescription" class="mt-1 whitespace-pre-line text-sm leading-6 text-secondary">{{ learnerStepIntroDescription }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-3">
|
||||
<ul v-if="workspace.publishedTrainingMaterials.length" class="space-y-2">
|
||||
<li
|
||||
v-for="material in workspace.publishedTrainingMaterials"
|
||||
:key="material.id || `${material.resourceType}-${material.sortOrder}`"
|
||||
class="flex items-center justify-between gap-3 rounded-xl border border-slate-100 bg-slate-50 px-3 py-2.5 cursor-pointer transition hover:bg-slate-100"
|
||||
@click="handleMaterialClick(material)"
|
||||
>
|
||||
<div class="flex min-w-0 items-center gap-2 text-sm font-medium text-primary hover:text-brand-600">
|
||||
<Video v-if="material.resource?.fileType === 'video'" class="h-4 w-4 text-brand-500" />
|
||||
<FileText v-else class="h-4 w-4 text-slate-400" />
|
||||
<span class="truncate">{{ material.title || material.resource?.fileName || $t('chat.training.video.playerTitle') }}</span>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
<div v-if="activeNonSafetyVideo" class="mt-3 overflow-hidden rounded-2xl border border-default bg-black shadow-lg">
|
||||
<video
|
||||
:key="activeNonSafetyVideo.id ?? activeNonSafetyVideo.resource?.fileUrl"
|
||||
controls
|
||||
playsinline
|
||||
preload="metadata"
|
||||
class="aspect-video w-full"
|
||||
:src="activeNonSafetyVideo.resource?.fileUrl"
|
||||
@play="startNonSafetyVideoTimer"
|
||||
@pause="stopNonSafetyVideoTimer"
|
||||
@ended="stopNonSafetyVideoTimer"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 relative group cursor-pointer overflow-hidden rounded-2xl border border-default bg-slate-900 shadow-lg aspect-video flex items-center justify-center" @click="showVideoModal = true">
|
||||
<img src="https://coresg-normal.trae.ai/api/ide/v1/text_to_image?prompt=Professional%20corporate%20training%20video%20cover%2C%20high-quality%2C%20modern%20office%20background%2C%20play%20button%20overlay&image_size=landscape_16_9" class="absolute inset-0 w-full h-full object-cover opacity-60 group-hover:scale-105 transition-transform duration-500" />
|
||||
<div class="relative z-10 flex flex-col items-center gap-3">
|
||||
<div class="h-16 w-16 flex items-center justify-center rounded-full bg-white/20 backdrop-blur-md border border-white/30 group-hover:bg-brand-600 group-hover:border-brand-500 transition-all duration-300">
|
||||
<PlayCircle class="h-8 w-8 text-white fill-white/20" />
|
||||
</div>
|
||||
<span class="text-white font-medium drop-shadow-md">{{ $t('chat.training.video.playerTitle') }}</span>
|
||||
</div>
|
||||
<div v-else class="mt-3 rounded-2xl border border-dashed border-default bg-surface-soft px-4 py-10 text-center text-sm text-muted">
|
||||
{{ $t('chat.training.video.empty') }}
|
||||
</div>
|
||||
<div v-if="nonSafetyVideoMaterials.length > 1" class="mt-3 grid gap-2 sm:grid-cols-2">
|
||||
<button
|
||||
v-for="(material, index) in nonSafetyVideoMaterials"
|
||||
:key="material.id || `${material.resourceType}-${material.sortOrder}`"
|
||||
type="button"
|
||||
class="flex min-w-0 items-center gap-2 rounded-xl border px-3 py-2.5 text-left text-sm transition"
|
||||
:class="activeNonSafetyVideo?.id === material.id ? 'border-brand-300 bg-brand-50 text-brand-700' : 'border-default bg-white text-primary hover:border-brand-200'"
|
||||
@click="selectNonSafetyVideo(material)"
|
||||
>
|
||||
<Video class="h-4 w-4 shrink-0" />
|
||||
<span class="min-w-0 flex-1 truncate">{{ material.title || material.resource?.fileName || `${$t('chat.training.video.playerTitle')} ${index + 1}` }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1034,8 +1226,8 @@ const currentSafetyStageText = computed(() => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 考试题目面板 (在考试或结果阶段展示) -->
|
||||
<div v-else :class="questionNavPanelClass">
|
||||
<!-- 考试题目面板 (在考试或结果阶段展示;单阶段培训无考试流程,不渲染任何侧栏面板) -->
|
||||
<div v-else-if="showLearnerProgressModule" :class="questionNavPanelClass">
|
||||
<div class="flex items-center gap-2">
|
||||
<ClipboardCheck class="h-4 w-4 text-brand-600" />
|
||||
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.examQuestionCard.title') }}</div>
|
||||
@@ -1079,8 +1271,8 @@ const currentSafetyStageText = computed(() => {
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 安全培训视图 -->
|
||||
<template v-else>
|
||||
<!-- 安全培训视图(仅安全培训进入该分支;精益管理走独立精益任务卡片,避免误渲染三级安全教育内容) -->
|
||||
<template v-else-if="workspace.learnerTab === 'safety'">
|
||||
<div :class="learnerWorkspaceMainClass">
|
||||
<!-- 进度卡片 -->
|
||||
<div :class="progressCardClass">
|
||||
@@ -1428,40 +1620,55 @@ const currentSafetyStageText = computed(() => {
|
||||
</div>
|
||||
|
||||
<div v-else-if="!isCompactMode" class="space-y-4 p-4 md:p-5">
|
||||
<!-- 管理端内容页签:全部培训=现有统计/筛选/主表;精益管理=精益看板(单任务,状态列区分三态)。 -->
|
||||
<div>
|
||||
<div class="inline-flex flex-wrap rounded-xl border border-default bg-surface-soft p-1">
|
||||
<button
|
||||
v-for="tab in [{ key: 'all', label: 'chat.training.hr.tabs.allTraining' }, { key: 'lean', label: 'chat.training.hr.tabs.leanManagement' }]"
|
||||
:key="tab.key"
|
||||
class="flex items-center gap-2 rounded-lg px-6 py-2 text-sm font-medium transition"
|
||||
:class="workspace.hrTrainingTab === tab.key ? 'bg-white text-brand-700 shadow-sm border border-brand-200' : 'text-secondary hover:text-primary'"
|
||||
@click="workspace.hrTrainingTab = tab.key as 'all' | 'lean'"
|
||||
>
|
||||
{{ $t(tab.label) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-3 sm:grid-cols-2 xl:grid-cols-5">
|
||||
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
|
||||
<div class="flex items-center justify-center gap-2 text-center">
|
||||
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.total') }}</div>
|
||||
<div class="text-2xl font-semibold text-primary">{{ workspace.stats.total }}</div>
|
||||
<div class="text-2xl font-semibold text-primary">{{ workspace.hrTrainingTab === 'lean' ? workspace.leanStats.total : workspace.stats.total }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
|
||||
<div class="flex items-center justify-center gap-2 text-center">
|
||||
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.passed') }}</div>
|
||||
<div class="text-2xl font-semibold text-emerald-600">{{ workspace.stats.passed }}</div>
|
||||
<div class="text-sm text-muted">{{ $t(workspace.hrTrainingTab === 'lean' ? 'chat.training.lean.status.completed' : 'chat.training.hr.stats.passed') }}</div>
|
||||
<div class="text-2xl font-semibold text-emerald-600">{{ workspace.hrTrainingTab === 'lean' ? workspace.leanStats.passed : workspace.stats.passed }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
|
||||
<div class="flex items-center justify-center gap-2 text-center">
|
||||
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.failed') }}</div>
|
||||
<div class="text-2xl font-semibold text-amber-600">{{ workspace.stats.failed }}</div>
|
||||
<div class="text-sm text-muted">{{ $t(workspace.hrTrainingTab === 'lean' ? 'chat.training.lean.status.overdue' : 'chat.training.hr.stats.failed') }}</div>
|
||||
<div class="text-2xl font-semibold text-amber-600">{{ workspace.hrTrainingTab === 'lean' ? workspace.leanStats.failed : workspace.stats.failed }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
|
||||
<div class="flex items-center justify-center gap-2 text-center">
|
||||
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.inProgress') }}</div>
|
||||
<div class="text-2xl font-semibold text-blue-600">{{ workspace.stats.inProgress }}</div>
|
||||
<div class="text-2xl font-semibold text-blue-600">{{ workspace.hrTrainingTab === 'lean' ? workspace.leanStats.inProgress : workspace.stats.inProgress }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
|
||||
<div class="flex items-center justify-center gap-2 text-center">
|
||||
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.passRate') }}</div>
|
||||
<div class="text-2xl font-semibold text-primary">{{ workspace.stats.passRate }}%</div>
|
||||
<div class="text-sm text-muted">{{ $t(workspace.hrTrainingTab === 'lean' ? 'chat.training.lean.dashboard.passRate' : 'chat.training.hr.stats.passRate') }}</div>
|
||||
<div class="text-2xl font-semibold text-primary">{{ workspace.hrTrainingTab === 'lean' ? workspace.leanStats.passRate : workspace.stats.passRate }}%</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="rounded-2xl border border-default bg-white p-4 shadow-sm">
|
||||
<div v-if="workspace.hrTrainingTab === 'all'" class="rounded-2xl border border-default bg-white p-4 shadow-sm">
|
||||
<div class="flex flex-col gap-3">
|
||||
<div class="grid gap-3 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)_auto] xl:items-center">
|
||||
<label>
|
||||
@@ -1572,6 +1779,87 @@ const currentSafetyStageText = computed(() => {
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 精益管理页签内容:仅当页签切到 lean 且当前用户可见时展示;看板保持单期任务,状态列区分已完成/已延期/进行中。 -->
|
||||
<div v-if="workspace.hrTrainingTab === 'lean' && workspace.canViewLeanDashboard && workspace.leanDashboard.task" class="rounded-2xl border border-emerald-200 bg-emerald-50/40 p-4 shadow-sm">
|
||||
<div class="flex flex-wrap items-start justify-between gap-3">
|
||||
<div>
|
||||
<div class="flex items-center gap-2 text-base font-semibold text-primary">
|
||||
<BookOpen class="h-4 w-4 text-emerald-600" />
|
||||
{{ $t('chat.training.lean.dashboard.title') }}
|
||||
</div>
|
||||
<div class="mt-1 flex flex-wrap items-center gap-2 text-xs text-secondary">
|
||||
<span>{{ $t('chat.training.lean.dashboard.week', { week: workspace.leanDashboard.task.weekKey }) }}</span>
|
||||
<span class="rounded-full bg-white px-2.5 py-1 font-medium text-emerald-700">{{ $t('chat.training.lean.dashboard.count', { count: workspace.leanRows.length }) }}</span>
|
||||
<!-- 期次下拉:期号按周次升序区分第几期任务,切换后重拉对应期看板与精益统计。 -->
|
||||
<select
|
||||
v-if="workspace.leanDashboard.periods.length"
|
||||
class="rounded-lg border border-default bg-white px-2 py-1 text-xs font-medium text-primary"
|
||||
:value="workspace.leanDashboardTaskId ?? workspace.leanDashboard.task.id"
|
||||
@change="workspace.selectLeanDashboardPeriod(Number(($event.target as HTMLSelectElement).value))"
|
||||
>
|
||||
<option v-for="period in workspace.leanDashboard.periods" :key="period.id" :value="period.id">{{ $t('chat.training.lean.dashboard.periodLabel', { index: period.index }) }}({{ period.weekKey }})</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-full bg-white px-3 py-1 text-xs font-medium text-emerald-700">{{ $t('chat.training.lean.dueAt', { time: workspace.leanDashboard.task.dueAt.slice(0, 16).replace('T', ' ') }) }}</div>
|
||||
</div>
|
||||
|
||||
<!-- 用户复测要求:不再分"已完成/未完成"双列,合为单一明细表,仅通过状态列区分已完成/已延期/进行中。 -->
|
||||
<div class="mt-4 overflow-hidden rounded-2xl border border-default bg-white">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full min-w-[900px] border-collapse text-sm">
|
||||
<thead class="bg-surface-soft">
|
||||
<tr>
|
||||
<th class="border-b border-default px-3 py-2.5 text-left font-semibold text-primary">{{ $t('chat.training.lean.columns.employeeId') }}</th>
|
||||
<th class="border-b border-default px-3 py-2.5 text-left font-semibold text-primary">{{ $t('chat.training.lean.columns.name') }}</th>
|
||||
<th class="border-b border-default px-3 py-2.5 text-left font-semibold text-primary">{{ $t('chat.training.lean.columns.department') }}</th>
|
||||
<th class="border-b border-default px-3 py-2.5 text-left font-semibold text-primary">{{ $t('chat.training.lean.columns.videoName') }}</th>
|
||||
<th class="border-b border-default px-3 py-2.5 text-left font-semibold text-primary">{{ $t('chat.training.lean.columns.watchedAt') }}</th>
|
||||
<th class="border-b border-default px-3 py-2.5 text-left font-semibold text-primary">{{ $t('chat.training.lean.columns.status') }}</th>
|
||||
<th class="border-b border-default px-3 py-2.5 text-left font-semibold text-primary">{{ $t('chat.training.lean.columns.summary') }}</th>
|
||||
<th class="border-b border-default px-3 py-2.5 text-left font-semibold text-primary">{{ $t('chat.training.lean.columns.action') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="row in workspace.leanRows" :key="row.userId" class="odd:bg-white even:bg-surface-soft/30">
|
||||
<td class="whitespace-nowrap border-b border-default px-3 py-2.5 text-secondary">{{ row.employeeId || '--' }}</td>
|
||||
<td class="whitespace-nowrap border-b border-default px-3 py-2.5 font-medium text-primary">{{ row.name }}</td>
|
||||
<td class="whitespace-nowrap border-b border-default px-3 py-2.5 text-secondary">{{ row.department || '--' }}</td>
|
||||
<td class="border-b border-default px-3 py-2.5 text-secondary"><div v-for="video in row.videos" :key="video.name" class="whitespace-nowrap">{{ video.name }}</div><span v-if="!row.videos.length">--</span></td>
|
||||
<!-- [RULE] 观看时间仅展示到分钟(slice(0,16) 去掉秒),与产品要求一致。 -->
|
||||
<td class="border-b border-default px-3 py-2.5 text-secondary"><div v-for="video in row.videos" :key="`${video.name}-${video.watchedAt}`" class="whitespace-nowrap">{{ video.watchedAt ? video.watchedAt.slice(0, 16).replace('T', ' ') : '--' }}</div><span v-if="!row.videos.length">--</span></td>
|
||||
<!-- 状态徽章三态:已完成(绿)/已延期(红)/进行中(蓝),文案统一中文(含其余三语言),禁止回显原始键。 -->
|
||||
<td class="border-b border-default px-3 py-2.5"><span class="inline-flex rounded-full px-2.5 py-1 text-xs font-semibold" :class="row.status === 'completed' ? 'bg-emerald-50 text-emerald-700' : row.status === 'overdue' ? 'bg-red-50 text-red-700' : 'bg-blue-50 text-blue-700'">{{ $t(`chat.training.lean.status.${row.status}`) }}</span></td>
|
||||
<!-- [RULE] 总结列最多显示 15 个字:超出截断并显示省略号,点击弹框查看全部文案;无总结显示 "--"。
|
||||
常显虚线下划线提示可点击(用户复测反馈点击无效,实为部署版本差异,此处强化可点性视觉)。 -->
|
||||
<td class="border-b border-default px-3 py-2.5 text-secondary">
|
||||
<button v-if="row.summaryText" type="button" class="max-w-56 cursor-pointer text-left whitespace-pre-wrap break-words underline decoration-dotted decoration-secondary/60 underline-offset-2 transition hover:decoration-solid hover:text-primary" :title="$t('chat.training.lean.summaryModal.viewHint')" @click="openSummaryModal(row.name, row.summaryText)">{{ truncateSummary(row.summaryText) }}</button>
|
||||
<span v-else>--</span>
|
||||
</td>
|
||||
<!-- 仅未完成(进行中/已延期)提供提醒操作,已完成无需催办。 -->
|
||||
<td class="border-b border-default px-3 py-2.5">
|
||||
<button
|
||||
v-if="row.status !== 'completed'"
|
||||
type="button"
|
||||
class="inline-flex whitespace-nowrap items-center gap-1.5 rounded-lg bg-amber-500 px-2.5 py-1.5 text-xs font-medium text-white transition hover:bg-amber-600 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
:disabled="workspace.leanReminderLoading[row.userId]"
|
||||
@click="workspace.remindLeanTrainingMember(row.userId)"
|
||||
>
|
||||
<Bell class="h-3.5 w-3.5" />
|
||||
{{ workspace.leanReminderLoading[row.userId] ? $t('chat.training.lean.reminder.sending') : $t('chat.training.lean.reminder.action') }}
|
||||
</button>
|
||||
<span v-else class="text-secondary">--</span>
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-if="!workspace.leanRows.length">
|
||||
<td colspan="8" class="px-4 py-6 text-center text-sm text-muted">{{ $t('chat.training.lean.dashboard.empty') }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -1724,10 +2012,35 @@ const currentSafetyStageText = computed(() => {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 总结详情弹框:看板总结列最多预览 15 字,点击后在此查看完整文案(点击遮罩或关闭按钮关闭)。 -->
|
||||
<div v-if="summaryModal" class="fixed inset-0 z-[110] flex items-center justify-center bg-slate-950/80 p-4 backdrop-blur-sm" @click.self="summaryModal = null">
|
||||
<div class="w-full max-w-lg rounded-2xl bg-white p-5 shadow-2xl">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<h3 class="text-base font-semibold text-primary">{{ $t('chat.training.lean.summaryModal.title') }}</h3>
|
||||
<p class="mt-0.5 text-xs text-secondary">{{ summaryModal.name }}</p>
|
||||
</div>
|
||||
<button type="button" class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-secondary transition hover:bg-surface-soft hover:text-primary" :aria-label="$t('chat.training.lean.summaryModal.close')" @click="summaryModal = null">
|
||||
<XCircle class="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
<div class="mt-4 max-h-96 overflow-y-auto whitespace-pre-wrap break-words rounded-xl bg-surface-soft/60 p-4 text-sm leading-relaxed text-secondary">{{ summaryModal.text }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 期次下拉自绘右置箭头:与全局 .select-field 同思路但尺寸紧凑(text-xs 头部场景)。
|
||||
[FIX] 用户复测反馈箭头压住日期数字:appearance-none 移除原生箭头,箭头整体右移贴边
|
||||
(距右缘 0.3rem),配合 pr-8 预留 2rem 空间,确保与文案完全无重叠。 */
|
||||
.lean-period-select {
|
||||
background-image: linear-gradient(45deg, transparent 50%, currentColor 50%), linear-gradient(135deg, currentColor 50%, transparent 50%);
|
||||
background-position: calc(100% - 0.55rem) 50%, calc(100% - 0.3rem) 50%;
|
||||
background-repeat: no-repeat;
|
||||
background-size: 0.3rem 0.3rem, 0.3rem 0.3rem;
|
||||
}
|
||||
|
||||
.report-pdf-page {
|
||||
width: 100%;
|
||||
max-width: 794px;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
/**
|
||||
* features/chat/composables/useTrainingWorkspace.ts
|
||||
* 用途:封装员工培训 Agent 的工作区状态,包括学员考试流、进度持久化与 HR 真实统计导出。
|
||||
* 用途:封装员工培训 Agent 的工作区状态,包括学员考试流、进度持久化、HR 真实统计导出与精益定向提醒。
|
||||
* 依赖:Vue reactivity、vue-i18n、training.api,以及 training.types。
|
||||
* 逻辑:仅在培训 Agent 下启用;学员端按“视频 -> 知识点 -> 一题一答 -> 结算”推进,并把进度同步到后端;
|
||||
* 非安全培训页额外按后台配置动态渲染进度项与步骤说明文案。
|
||||
* 非安全培训页额外按后台配置动态渲染进度项与步骤说明文案;精益管理面板通过独立状态提交未完成人员提醒。
|
||||
*/
|
||||
import { computed, ref, watch, type ComputedRef } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
@@ -15,8 +15,13 @@ import {
|
||||
getMyTrainingProgress,
|
||||
getMyTrainingTypes,
|
||||
getTrainingStats,
|
||||
getMyLeanTrainingTasks,
|
||||
getLeanTrainingDashboard,
|
||||
sendLeanTrainingReminders,
|
||||
listTrainingRecords,
|
||||
markMyLeanVideoWatched,
|
||||
saveMyTrainingProgress,
|
||||
saveMyLeanTrainingCompletion,
|
||||
} from '@/features/chat/api/training.api';
|
||||
import type {
|
||||
SafetyProgressState,
|
||||
@@ -36,6 +41,9 @@ import type {
|
||||
TrainingType,
|
||||
TrainingTypeOption,
|
||||
TrainingWorkspaceView,
|
||||
LeanTrainingDashboard,
|
||||
LeanTrainingDashboardRow,
|
||||
LeanTrainingMyTask,
|
||||
} from '@/features/chat/training/training.types';
|
||||
import {
|
||||
SAFETY_STAGE_GUIDE_USAGE_MAP,
|
||||
@@ -107,7 +115,21 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
});
|
||||
const hasAuthenticatedUser = computed(() => Boolean(String(currentUser.value?.username || '').trim()));
|
||||
const isAdminViewer = computed(() => Boolean(currentUser.value?.feature_permissions?.training_hr_manage));
|
||||
const defaultActiveView = computed<TrainingWorkspaceView>(() => (isAdminViewer.value ? 'admin' : 'learner'));
|
||||
const canViewLeanDashboard = computed(() => isAdminViewer.value);
|
||||
const canManageTrainingWorkspace = computed(() => isAdminViewer.value);
|
||||
/** 学员端精益周任务列表(后端按发布周期倒序,最新在前),并附每期任务状态与完成信息。 */
|
||||
const leanMyTasks = ref<LeanTrainingMyTask[]>([]);
|
||||
const leanDashboard = ref<LeanTrainingDashboard>({ task: null, completed: [], incomplete: [], periods: [] });
|
||||
/** 管理端内容页签:all=全部培训(现有统计/筛选/主表);lean=精益管理(精益看板单任务,按状态列区分三态)。 */
|
||||
const hrTrainingTab = ref<'all' | 'lean'>('all');
|
||||
/** 管理端精益看板当前选中的期次任务 ID;为空表示最新一期,切换后重新拉取对应期看板。 */
|
||||
const leanDashboardTaskId = ref<number | null>(null);
|
||||
const leanReminderLoading = ref<Record<number, boolean>>({});
|
||||
/** 按任务 ID 分组的感悟草稿,支持时间树上多期任务并行编辑。 */
|
||||
const leanSummaryByTask = ref<Record<number, string>>({});
|
||||
/** 按任务 ID 分组的观看记录(资源 ID -> 观看时间),提交时随感悟一并交由服务端校验。 */
|
||||
const leanWatchedByTask = ref<Record<number, Record<string, string>>>({});
|
||||
const defaultActiveView = computed<TrainingWorkspaceView>(() => (canManageTrainingWorkspace.value ? 'admin' : 'learner'));
|
||||
const activeView = ref<TrainingWorkspaceView>('learner');
|
||||
const learnerTab = ref<TrainingType>('onboarding');
|
||||
const trainingTypes = ref<TrainingTypeOption[]>([
|
||||
@@ -162,6 +184,28 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
passRate: 0,
|
||||
averageScore: 0,
|
||||
});
|
||||
/** 精益看板合并行:已完成+未完成名单合为单表遍历,状态列区分已完成/已延期/进行中三态。 */
|
||||
const leanRows = computed<LeanTrainingDashboardRow[]>(() => [...leanDashboard.value.completed, ...leanDashboard.value.incomplete]);
|
||||
/**
|
||||
* 精益管理页签统计:按看板行三态(completed/in_progress/overdue)实际计数,供统计卡片随页签切换数据源。
|
||||
* total=参训人数(已完成+未完成名单行数);passed=已完成;failed=已延期;inProgress=进行中;passRate=完成率。
|
||||
*/
|
||||
const leanStats = computed<TrainingStats>(() => {
|
||||
// [STEP 1] 合并已完成/未完成两组行后按后端归一的三态计数,避免只扫 incomplete 组漏算已延期。
|
||||
const rows = [...leanDashboard.value.completed, ...leanDashboard.value.incomplete];
|
||||
const total = rows.length;
|
||||
const completedCount = rows.filter((row) => row.status === 'completed').length;
|
||||
const overdueCount = rows.filter((row) => row.status === 'overdue').length;
|
||||
const inProgressCount = rows.filter((row) => row.status === 'in_progress').length;
|
||||
return {
|
||||
total,
|
||||
passed: completedCount,
|
||||
failed: overdueCount,
|
||||
inProgress: inProgressCount,
|
||||
passRate: total > 0 ? Math.round((completedCount / total) * 100) : 0,
|
||||
averageScore: 0,
|
||||
};
|
||||
});
|
||||
let persistQueue: Promise<void> = Promise.resolve();
|
||||
|
||||
watch(isTrainingAgent, (enabled) => {
|
||||
@@ -172,7 +216,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
});
|
||||
|
||||
watch(
|
||||
[isTrainingAgent, isAdminViewer],
|
||||
[isTrainingAgent, canManageTrainingWorkspace],
|
||||
([enabled]) => {
|
||||
if (!enabled) return;
|
||||
activeView.value = defaultActiveView.value;
|
||||
@@ -780,6 +824,92 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
}
|
||||
};
|
||||
|
||||
/** 拉取管理端精益看板(按 leanDashboardTaskId 指定期次,空则最新一期),失败时清空兜底。 */
|
||||
const loadLeanDashboard = async () => {
|
||||
if (!canViewLeanDashboard.value) return;
|
||||
try {
|
||||
leanDashboard.value = await getLeanTrainingDashboard(leanDashboardTaskId.value ?? undefined);
|
||||
} catch {
|
||||
leanDashboard.value = { task: null, completed: [], incomplete: [], periods: [] };
|
||||
}
|
||||
};
|
||||
|
||||
/** 切换精益看板期次:记录任务 ID 后仅重拉看板与精益统计,不动学员任务列表。 */
|
||||
const selectLeanDashboardPeriod = async (taskId: number) => {
|
||||
if (leanDashboardTaskId.value === taskId) return;
|
||||
leanDashboardTaskId.value = taskId;
|
||||
await loadLeanDashboard();
|
||||
};
|
||||
|
||||
/** 读取学员端全部已发布精益周任务(含状态与播放地址),并以服务端完成记录回填各任务的感悟/观看草稿。 */
|
||||
const loadLeanTraining = async () => {
|
||||
if (!isTrainingAgent.value || !hasAuthenticatedUser.value) return;
|
||||
try {
|
||||
leanMyTasks.value = await getMyLeanTrainingTasks();
|
||||
// [STEP 1] 回填草稿:已完成任务还原当时提交的感悟与观看时间;进行中/已延期任务保留已有观看记录,避免刷新后丢失。
|
||||
const summaries: Record<number, string> = {};
|
||||
const watched: Record<number, Record<string, string>> = {};
|
||||
leanMyTasks.value.forEach((task) => {
|
||||
summaries[task.id] = task.completion?.summaryText || '';
|
||||
watched[task.id] = { ...(task.completion?.watchedAt || {}) };
|
||||
});
|
||||
leanSummaryByTask.value = summaries;
|
||||
leanWatchedByTask.value = watched;
|
||||
await loadLeanDashboard();
|
||||
} catch {
|
||||
leanMyTasks.value = [];
|
||||
leanDashboard.value = { task: null, completed: [], incomplete: [], periods: [] };
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 记录某期任务的指定视频已完成观看:本地即时生效,并异步持久化到服务端(刷新后仍保留)。
|
||||
* AI 触发时机:学员在精益管理时间树上点击任务视频并完整播放到结尾时调用;已有观看记录的资源保留首次时间不覆盖。
|
||||
*/
|
||||
const markLeanVideoWatched = (taskId: number, resourceId: number) => {
|
||||
const taskWatched = leanWatchedByTask.value[taskId] || {};
|
||||
if (taskWatched[String(resourceId)]) return;
|
||||
leanWatchedByTask.value = { ...leanWatchedByTask.value, [taskId]: { ...taskWatched, [String(resourceId)]: new Date().toISOString() } };
|
||||
// 持久化失败不阻塞本地状态;下次刷新列表会以服务端记录为准,未持久化的视频需重新完整观看
|
||||
void markMyLeanVideoWatched(taskId, resourceId).catch(() => {});
|
||||
};
|
||||
|
||||
/**
|
||||
* 提交指定周任务的学习感悟;服务端校验该任务已推送视频全部完成且达到最少字数,成功后刷新任务列表与看板。
|
||||
*/
|
||||
const submitLeanTrainingCompletion = async (taskId: number) => {
|
||||
await saveMyLeanTrainingCompletion({ weeklyTaskId: taskId, watchedAt: leanWatchedByTask.value[taskId] || {}, summaryText: leanSummaryByTask.value[taskId] || '' });
|
||||
await loadLeanTraining();
|
||||
};
|
||||
|
||||
/**
|
||||
* HR 对看板中未完成成员发起定向提醒,并按服务端实发统计如实提示。
|
||||
* AI 触发时机:HR 在精益培训完成名单点击行内【提醒】按钮时调用。
|
||||
* 核心逻辑:后端 created 计数包含"企微发送失败"的提醒(仅代表已尝试),
|
||||
* 成功提示必须以 sent(企微受理成功)为准,failed>0 时明确告知失败,避免误报已送达。
|
||||
*/
|
||||
const remindLeanTrainingMember = async (userId: number) => {
|
||||
if (!leanDashboard.value.task || leanReminderLoading.value[userId]) return;
|
||||
leanReminderLoading.value[userId] = true;
|
||||
try {
|
||||
const result = await sendLeanTrainingReminders(leanDashboard.value.task.id, [userId]);
|
||||
if (result.sent > 0 && result.failed > 0) {
|
||||
msg.warning(t('chat.training.lean.reminder.partial', { sent: result.sent, failed: result.failed }));
|
||||
} else if (result.sent > 0) {
|
||||
msg.success(t('chat.training.lean.reminder.success', { count: result.sent }));
|
||||
} else if (result.failed > 0) {
|
||||
msg.error(t('chat.training.lean.reminder.sendFailed', { count: result.failed }));
|
||||
} else {
|
||||
msg.warning(t('chat.training.lean.reminder.notSent'));
|
||||
}
|
||||
await loadLeanTraining();
|
||||
} catch (error) {
|
||||
msg.error(error instanceof BusinessError ? error.message : t('chat.training.lean.reminder.failed'));
|
||||
} finally {
|
||||
leanReminderLoading.value[userId] = false;
|
||||
}
|
||||
};
|
||||
|
||||
watch(
|
||||
[
|
||||
currentAgent,
|
||||
@@ -812,6 +942,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
void loadTrainingTypes();
|
||||
void loadTrainingConfig();
|
||||
void loadTrainingProgress();
|
||||
void loadLeanTraining();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
@@ -1160,6 +1291,13 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
return {
|
||||
isTrainingAgent,
|
||||
isAdminViewer,
|
||||
canViewLeanDashboard,
|
||||
canManageTrainingWorkspace,
|
||||
leanDashboard,
|
||||
leanReminderLoading,
|
||||
leanSummaryByTask,
|
||||
leanWatchedByTask,
|
||||
leanMyTasks,
|
||||
isHydrated,
|
||||
trainingConfigLoading,
|
||||
hasPublishedTrainingConfig,
|
||||
@@ -1215,6 +1353,11 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
departmentOptions,
|
||||
filteredRecords,
|
||||
stats,
|
||||
hrTrainingTab,
|
||||
leanStats,
|
||||
leanRows,
|
||||
leanDashboardTaskId,
|
||||
selectLeanDashboardPeriod,
|
||||
learnerChatPrompt,
|
||||
newSessionReminderMessage,
|
||||
shouldShowNewSessionReminder,
|
||||
@@ -1230,6 +1373,10 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
restartExam,
|
||||
setSafetyStage,
|
||||
exportRecords,
|
||||
loadLeanTraining,
|
||||
markLeanVideoWatched,
|
||||
submitLeanTrainingCompletion,
|
||||
remindLeanTrainingMember,
|
||||
showVideoModal,
|
||||
videoUrl,
|
||||
startMaterialTimer,
|
||||
|
||||
@@ -139,3 +139,70 @@ export interface TrainingStats {
|
||||
passRate: number;
|
||||
averageScore: number;
|
||||
}
|
||||
|
||||
export interface LeanTrainingVideo {
|
||||
id: number;
|
||||
name: string;
|
||||
/** MinIO 公开播放地址,供缩略图首帧与弹窗播放使用 */
|
||||
fileUrl?: string | null;
|
||||
}
|
||||
|
||||
/** 学员视角任务状态:in_progress=进行中;overdue=已延期(过截止未完成);completed=已完成 */
|
||||
export type LeanTrainingTaskStatus = 'in_progress' | 'overdue' | 'completed';
|
||||
|
||||
export interface LeanTrainingCompletionBrief {
|
||||
summaryText: string;
|
||||
watchedAt: Record<string, string>;
|
||||
completedAt: string | null;
|
||||
}
|
||||
|
||||
export interface LeanTrainingWeeklyTask {
|
||||
id: number;
|
||||
weekKey: string;
|
||||
dueAt: string;
|
||||
videoResourceIds: number[];
|
||||
targetRoles: string[];
|
||||
targetUserIds: number[];
|
||||
videos: LeanTrainingVideo[];
|
||||
status: string;
|
||||
minSummaryLength: number;
|
||||
weeklyCount?: number;
|
||||
pushedVideoCount?: number;
|
||||
/** 任务周周日(ISO 日期),供前端拼装"第N周 MM-DD至MM-DD"周次区间标签。 */
|
||||
weekEnd?: string | null;
|
||||
/** 期号:按周次升序编号,最早一周为第 1 期,与管理端口径一致。 */
|
||||
weekIndex?: number;
|
||||
}
|
||||
|
||||
/** 学员端时间树任务项:周任务 + 任务状态 + 完成信息 */
|
||||
export interface LeanTrainingMyTask extends LeanTrainingWeeklyTask {
|
||||
taskStatus: LeanTrainingTaskStatus;
|
||||
completion: LeanTrainingCompletionBrief | null;
|
||||
}
|
||||
|
||||
export interface LeanTrainingDashboardRow {
|
||||
id?: number;
|
||||
userId: number;
|
||||
employeeId?: string | null;
|
||||
name: string;
|
||||
department?: string | null;
|
||||
videos: Array<{ name: string; watchedAt?: string | null }>;
|
||||
summaryText?: string | null;
|
||||
/** 管理端三态:completed=已完成(感悟已提交);in_progress=进行中;overdue=已延期(过截止未完成),由后端序列化层归一 */
|
||||
status: 'completed' | 'in_progress' | 'overdue';
|
||||
completedAt?: string | null;
|
||||
}
|
||||
|
||||
/** 精益看板期次摘要:index 为期号(按周次升序,最早为第 1 期),供管理端下拉区分第几期任务。 */
|
||||
export interface LeanTrainingPeriod {
|
||||
id: number;
|
||||
weekKey: string;
|
||||
index: number;
|
||||
}
|
||||
|
||||
export interface LeanTrainingDashboard {
|
||||
task: LeanTrainingWeeklyTask | null;
|
||||
completed: LeanTrainingDashboardRow[];
|
||||
incomplete: LeanTrainingDashboardRow[];
|
||||
periods: LeanTrainingPeriod[];
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* 合同付款预警 API 类型与请求封装。
|
||||
* 依赖:统一 requestJson;后端 /api/contract-payment。
|
||||
* 逻辑:台账/合同详情查询、待发送摘要、每日扫描入队、周五汇总入队及批次附件下载。
|
||||
* 逻辑:台账/合同详情查询、汇总卡统计、待发送摘要、每日扫描入队、周五汇总入队及批次附件下载。
|
||||
*/
|
||||
import { requestBlob, requestJson } from '@/shared/api/client';
|
||||
|
||||
@@ -21,11 +21,27 @@ export interface ContractPaymentContract {
|
||||
status: string; parse_status: string; plan_status: string; parse_issues?: string[]; nodes: PaymentNode[]; alerts?: PaymentAlert[]; attachments?: ContractAttachment[];
|
||||
}
|
||||
export interface ContractListResponse { total: number; page: number; page_size: number; pages: number; items: ContractPaymentContract[]; }
|
||||
export type LedgerFocus = 'due' | 'overdue' | 'needs_completion' | 'due_this_month';
|
||||
export interface LedgerSummary {
|
||||
due: number;
|
||||
overdue: number;
|
||||
needs_completion: number;
|
||||
due_this_month: number;
|
||||
}
|
||||
export interface AlertBatch { id: number; batch_no: string; week_key: string; status: string; summary?: { total?: number; stages?: Record<string, number> }; excel_file_name?: string | null; excel_file_size?: number | null; sent_at?: string | null; }
|
||||
export interface AlertSummary { pending_count: number; next_send_at?: string | null; timezone?: string | null; }
|
||||
|
||||
export const listContractPaymentContracts = (params?: { keyword?: string; parse_status?: string; reviewOnly?: boolean; page?: number; pageSize?: number }) => {
|
||||
const query = new URLSearchParams(); if (params?.keyword) query.set('keyword', params.keyword); if (params?.parse_status) query.set('parse_status', params.parse_status); if (params?.reviewOnly) query.set('review_only', '1'); if (params?.page) query.set('page', String(params.page)); if (params?.pageSize) query.set('page_size', String(params.pageSize));
|
||||
/**
|
||||
* 分页查询合同付款台账或待确认合同。
|
||||
* 核心逻辑:keyword 同时匹配合同号、流程号、采购单号和供应商;reviewOnly 走待确认列表。
|
||||
* @param params.keyword - 模糊检索词,可为空。
|
||||
* @param params.parse_status - 解析状态精确筛选。
|
||||
* @param params.reviewOnly - 为 true 时只查 needs_review。
|
||||
* @param params.focus - 汇总卡口径:即将到期 / 逾期未付 / 待补充 / 本月应付。
|
||||
* @returns 分页后的合同列表。
|
||||
*/
|
||||
export const listContractPaymentContracts = (params?: { keyword?: string; parse_status?: string; reviewOnly?: boolean; focus?: LedgerFocus; page?: number; pageSize?: number }) => {
|
||||
const query = new URLSearchParams(); if (params?.keyword) query.set('keyword', params.keyword); if (params?.parse_status) query.set('parse_status', params.parse_status); if (params?.reviewOnly) query.set('review_only', '1'); if (params?.focus) query.set('focus', params.focus); if (params?.page) query.set('page', String(params.page)); if (params?.pageSize) query.set('page_size', String(params.pageSize));
|
||||
const suffix = query.toString() ? `?${query.toString()}` : ''; return requestJson<ContractListResponse>(`/api/contract-payment/contracts${suffix}`);
|
||||
};
|
||||
/** 获取单份合同的概览、原文附件、付款计划与预警审计详情。 */
|
||||
@@ -42,6 +58,12 @@ export const enqueueContractPaymentAlertScan = () => requestJson<{ job_id: strin
|
||||
export const enqueueContractPaymentWeeklyAlert = () => requestJson<{ job_id: string }>('/api/contract-payment/alerts/weekly-run', { method: 'POST' });
|
||||
/** 查询本周待发送笔数和下一次周五汇总发送时间。 */
|
||||
export const getContractPaymentAlertSummary = () => requestJson<AlertSummary>('/api/contract-payment/alerts/summary');
|
||||
/**
|
||||
* 查询合同台账四张汇总卡的合同份数。
|
||||
* 核心逻辑:始终统计全部已解析台账,不跟当前 keyword;与点卡片过滤共用 focus 口径。
|
||||
* @returns due / overdue / needs_completion / due_this_month。
|
||||
*/
|
||||
export const getContractPaymentLedgerSummary = () => requestJson<LedgerSummary>('/api/contract-payment/contracts/summary');
|
||||
export const listContractPaymentAlertBatches = () => requestJson<{ items: AlertBatch[] }>('/api/contract-payment/alert-batches');
|
||||
/** 下载已归档的合同付款预警周汇总 Excel 明细。 */
|
||||
export const downloadContractPaymentAlertBatchExcel = (batchId: number) => requestBlob(`/api/contract-payment/alert-batches/${batchId}/excel`);
|
||||
@@ -1,6 +1,6 @@
|
||||
<!--
|
||||
合同付款预警工作台:展示合同台账、付款阶段字段、本周待发送摘要,并提供预警任务入口。
|
||||
依赖:contract-payment.api、PaginationBar、统一消息提示;周汇总批次由独立页面展示。
|
||||
合同付款预警工作台:展示汇总卡、合同台账、付款阶段字段、本周待发送摘要;同步/扫描/发送仅管理员可见。
|
||||
依赖:contract-payment.api、PaginationBar、useAuthStore、统一消息提示;周汇总批次由独立页面展示。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
@@ -11,6 +11,7 @@ import { BusinessError } from '@/shared/api/client';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
||||
import { WORKSPACE_PATHS } from '@/features/workspace/constants/routes';
|
||||
import {
|
||||
enqueueContractPaymentAlertScan,
|
||||
@@ -18,21 +19,34 @@ import {
|
||||
enqueueContractPaymentSync,
|
||||
enqueueContractPaymentWeeklyAlert,
|
||||
getContractPaymentAlertSummary,
|
||||
getContractPaymentLedgerSummary,
|
||||
listContractPaymentContracts,
|
||||
type AlertSummary,
|
||||
type ContractPaymentContract,
|
||||
type LedgerFocus,
|
||||
type LedgerSummary,
|
||||
} from '../api/contract-payment.api';
|
||||
import { displayCurrency } from '../utils/currency';
|
||||
import { aggregateContractNodeStatus, type ContractNodeStatusCode } from '../utils/paymentStatus';
|
||||
|
||||
const { t } = useI18n();
|
||||
const router = useRouter();
|
||||
const auth = useAuthStore();
|
||||
const isAdmin = computed(() => auth.isAdmin);
|
||||
const msg = useMessage(); const keyword = ref(''); const loading = ref(false); const actionLoading = ref(false);
|
||||
const showForceSyncConfirm = ref(false);
|
||||
const showReparseExistingConfirm = ref(false);
|
||||
const contracts = ref<ContractPaymentContract[]>([]);
|
||||
const alertSummary = ref<AlertSummary | null>(null);
|
||||
const ledgerSummary = ref<LedgerSummary>({ due: 0, overdue: 0, needs_completion: 0, due_this_month: 0 });
|
||||
const ledgerFocus = ref<LedgerFocus | ''>('');
|
||||
const page = ref(1); const pageSize = ref(20); const total = ref(0); const pages = ref(1);
|
||||
const ledgerFocusCards = computed(() => ([
|
||||
{ key: 'due' as const, label: t('admin.contractPayment.ledgerFocus.due'), hint: t('admin.contractPayment.ledgerFocus.dueHint'), value: ledgerSummary.value.due, tone: 'due' },
|
||||
{ key: 'overdue' as const, label: t('admin.contractPayment.ledgerFocus.overdue'), hint: '', value: ledgerSummary.value.overdue, tone: 'overdue' },
|
||||
{ key: 'needs_completion' as const, label: t('admin.contractPayment.ledgerFocus.needsCompletion'), hint: '', value: ledgerSummary.value.needs_completion, tone: 'needs' },
|
||||
{ key: 'due_this_month' as const, label: t('admin.contractPayment.ledgerFocus.dueThisMonth'), hint: t('admin.contractPayment.ledgerFocus.dueThisMonthHint'), value: ledgerSummary.value.due_this_month, tone: 'month' },
|
||||
]));
|
||||
const stage = (item: ContractPaymentContract, name: string) => item.nodes.find((node) => node.node_type === name);
|
||||
/**
|
||||
* 以整数格式展示付款比例,不改变接口返回的精确比例值。
|
||||
@@ -123,19 +137,37 @@ async function refreshSummary(): Promise<void> {
|
||||
if (!alertSummary.value) alertSummary.value = { pending_count: 0, next_send_at: null, timezone: 'Asia/Shanghai' };
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 刷新四张汇总卡的合同份数。
|
||||
* 核心逻辑:始终统计全部已解析台账,失败时保留上次数字,不阻断列表。
|
||||
*/
|
||||
async function refreshLedgerSummary(): Promise<void> {
|
||||
try {
|
||||
ledgerSummary.value = await getContractPaymentLedgerSummary();
|
||||
} catch {
|
||||
/* 汇总失败不影响台账列表 */
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 加载当前页合同台账。
|
||||
* 核心逻辑:合同列表使用服务端分页;搜索和每页条数变化均从第一页开始,并并行刷新待发送摘要。
|
||||
* @param resetPage - 为 true 时重置为第一页,用于关键词查询。
|
||||
* @returns 完成后更新当前列表、分页元数据和待发送摘要。
|
||||
* 核心逻辑:合同列表使用服务端分页;关键词同时匹配合同号、流程号、采购单号和供应商;
|
||||
* 汇总卡 focus 与关键词叠加;搜索、点卡片和每页条数变化均从第一页开始,并并行刷新待发送摘要与汇总卡。
|
||||
* @param resetPage - 为 true 时重置为第一页,用于关键词查询或切换汇总卡。
|
||||
* @returns 完成后更新当前列表、分页元数据、待发送摘要和汇总卡。
|
||||
*/
|
||||
async function load(resetPage = false): Promise<void> {
|
||||
if (resetPage) page.value = 1;
|
||||
loading.value = true;
|
||||
try {
|
||||
const [result] = await Promise.all([
|
||||
listContractPaymentContracts({ keyword: keyword.value.trim(), page: page.value, pageSize: pageSize.value }),
|
||||
listContractPaymentContracts({
|
||||
keyword: keyword.value.trim(),
|
||||
focus: ledgerFocus.value || undefined,
|
||||
page: page.value,
|
||||
pageSize: pageSize.value,
|
||||
}),
|
||||
refreshSummary(),
|
||||
refreshLedgerSummary(),
|
||||
]);
|
||||
contracts.value = result.items || [];
|
||||
total.value = result.total || 0;
|
||||
@@ -147,13 +179,23 @@ async function load(resetPage = false): Promise<void> {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 点击汇总卡过滤台账;再次点击同一张卡则取消过滤。
|
||||
* 核心逻辑:focus 写入列表查询;汇总数字本身仍看全部台账。
|
||||
* @param key - 汇总卡口径。
|
||||
*/
|
||||
function toggleLedgerFocus(key: LedgerFocus): void {
|
||||
ledgerFocus.value = ledgerFocus.value === key ? '' : key;
|
||||
void load(true);
|
||||
}
|
||||
/**
|
||||
* 提交合同付款预警后台任务。
|
||||
* 核心逻辑:按操作类型调用相应的异步接口,任务入队成功后仅展示任务编号,不等待长耗时同步或发送完成。
|
||||
* 核心逻辑:仅管理员可提交;按操作类型调用相应的异步接口,任务入队成功后仅展示任务编号,不等待长耗时同步或发送完成。
|
||||
* @param action - sync 同步 OA、force-sync 强制覆盖、reparse-existing 刷新存量解析、scan 扫描预警、weekly 周汇总。
|
||||
* @returns 任务提交完成后显示成功或失败提示。
|
||||
*/
|
||||
async function submitAction(action: 'sync' | 'force-sync' | 'reparse-existing' | 'scan' | 'weekly'): Promise<void> {
|
||||
if (!isAdmin.value) return;
|
||||
actionLoading.value = true;
|
||||
try {
|
||||
if (action === 'sync' || action === 'force-sync') {
|
||||
@@ -181,6 +223,7 @@ async function submitAction(action: 'sync' | 'force-sync' | 'reparse-existing' |
|
||||
* @param action - 待提交的预警任务类型。
|
||||
*/
|
||||
function run(action: 'sync' | 'force-sync' | 'reparse-existing' | 'scan' | 'weekly'): void {
|
||||
if (!isAdmin.value) return;
|
||||
if (action === 'force-sync') {
|
||||
showForceSyncConfirm.value = true;
|
||||
return;
|
||||
@@ -212,8 +255,33 @@ onMounted(() => void load());
|
||||
</script>
|
||||
<template>
|
||||
<section class="section-gap animate-fade-in-up">
|
||||
<div class="flex flex-wrap items-start justify-between gap-4"><div><h2 class="text-2xl font-bold text-primary">{{ t('admin.contractPayment.title') }}</h2><p class="text-sm text-muted mt-1">{{ t('admin.contractPayment.subtitle') }}</p></div><div class="flex gap-2"><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('sync')"><RefreshCw class="w-4 h-4" />{{ t('admin.contractPayment.sync') }}</button><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('force-sync')"><RefreshCw class="w-4 h-4" />{{ t('admin.contractPayment.forceSync') }}</button><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('reparse-existing')"><RefreshCw class="w-4 h-4" />{{ t('admin.contractPayment.reparseExisting') }}</button><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('scan')"><CalendarClock class="w-4 h-4" />{{ t('admin.contractPayment.scanAlerts') }}</button><button class="btn-primary" :disabled="actionLoading" @click="run('weekly')"><Send class="w-4 h-4" />{{ t('admin.contractPayment.weeklySend') }}</button></div></div>
|
||||
<div class="surface-panel rounded-2xl p-4 mt-5"><div class="flex flex-wrap gap-3 items-center"><div class="relative w-full md:w-[360px]"><Search class="absolute left-3 top-2.5 w-4 h-4 text-muted" /><input v-model="keyword" class="input-field pl-9" :placeholder="t('admin.contractPayment.searchPlaceholder')" @keyup.enter="load(true)" /></div><button class="btn-secondary-ds" @click="load(true)">{{ t('admin.contractPayment.search') }}</button><span v-if="weeklyPendingText" class="text-xs text-muted">{{ weeklyPendingText }}</span></div></div>
|
||||
<div class="flex flex-wrap items-start justify-between gap-4"><div><h2 class="text-2xl font-bold text-primary">{{ t('admin.contractPayment.title') }}</h2><p class="text-sm text-muted mt-1">{{ t('admin.contractPayment.subtitle') }}</p></div><div v-if="isAdmin" class="flex flex-wrap gap-2"><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('sync')"><RefreshCw class="w-4 h-4" />{{ t('admin.contractPayment.sync') }}</button><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('force-sync')"><RefreshCw class="w-4 h-4" />{{ t('admin.contractPayment.forceSync') }}</button><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('reparse-existing')"><RefreshCw class="w-4 h-4" />{{ t('admin.contractPayment.reparseExisting') }}</button><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('scan')"><CalendarClock class="w-4 h-4" />{{ t('admin.contractPayment.scanAlerts') }}</button><button class="btn-primary" :disabled="actionLoading" @click="run('weekly')"><Send class="w-4 h-4" />{{ t('admin.contractPayment.weeklySend') }}</button></div></div>
|
||||
<div class="contract-stat-grid">
|
||||
<button
|
||||
v-for="card in ledgerFocusCards"
|
||||
:key="card.key"
|
||||
type="button"
|
||||
class="contract-stat-card"
|
||||
:class="[card.tone, { active: ledgerFocus === card.key }]"
|
||||
@click="toggleLedgerFocus(card.key)"
|
||||
>
|
||||
<span class="contract-stat-label">{{ card.label }}<small v-if="card.hint">({{ card.hint }})</small></span>
|
||||
<strong class="contract-stat-value">{{ card.value }}</strong>
|
||||
</button>
|
||||
</div>
|
||||
<div class="contract-filter-bar">
|
||||
<div class="contract-filter-search">
|
||||
<Search class="contract-filter-icon" />
|
||||
<input
|
||||
v-model="keyword"
|
||||
class="contract-filter-input"
|
||||
:placeholder="t('admin.contractPayment.searchPlaceholder')"
|
||||
@keyup.enter="load(true)"
|
||||
/>
|
||||
</div>
|
||||
<button type="button" class="contract-filter-submit" @click="load(true)">{{ t('admin.contractPayment.search') }}</button>
|
||||
<span v-if="weeklyPendingText" class="contract-filter-meta">{{ weeklyPendingText }}</span>
|
||||
</div>
|
||||
<div class="surface-panel contract-ledger-panel mt-4 overflow-x-auto">
|
||||
<table class="contract-ledger-table text-sm">
|
||||
<thead><tr>
|
||||
@@ -233,8 +301,9 @@ onMounted(() => void load());
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<PaginationBar v-model:page="page" v-model:page-size="pageSize" :total="total" :pages="pages" :visible="total > 0 || !!keyword.trim()" @update:page="() => load()" @update:page-size="() => load()" />
|
||||
<PaginationBar v-model:page="page" v-model:page-size="pageSize" :total="total" :pages="pages" :visible="total > 0 || !!keyword.trim() || !!ledgerFocus" @update:page="() => load()" @update:page-size="() => load()" />
|
||||
<DeleteConfirmDialog
|
||||
v-if="isAdmin"
|
||||
v-model="showForceSyncConfirm"
|
||||
:title="t('admin.contractPayment.forceSync')"
|
||||
:message="t('admin.contractPayment.forceSyncConfirm')"
|
||||
@@ -242,6 +311,7 @@ onMounted(() => void load());
|
||||
@confirm="confirmForceSync"
|
||||
/>
|
||||
<DeleteConfirmDialog
|
||||
v-if="isAdmin"
|
||||
v-model="showReparseExistingConfirm"
|
||||
:title="t('admin.contractPayment.reparseExisting')"
|
||||
:message="t('admin.contractPayment.reparseExistingConfirm')"
|
||||
@@ -251,6 +321,83 @@ onMounted(() => void load());
|
||||
</section>
|
||||
</template>
|
||||
<style scoped>
|
||||
.contract-stat-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
.contract-stat-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
min-height: 88px;
|
||||
padding: 14px 16px 12px;
|
||||
border: 1px solid #d7e1ef;
|
||||
border-radius: 14px;
|
||||
background: #fff;
|
||||
box-shadow: 0 6px 20px rgba(33, 65, 111, .05);
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.contract-stat-card.active { border-color: #93c5fd; box-shadow: 0 0 0 2px rgba(59, 130, 246, .16); }
|
||||
.contract-stat-label { color: #8aa0bd; font-size: 12px; font-weight: 600; line-height: 1.35; }
|
||||
.contract-stat-label small { margin-left: 2px; font-size: 12px; font-weight: 600; }
|
||||
.contract-stat-value { margin-top: 8px; font-size: 28px; font-weight: 800; line-height: 1; }
|
||||
.contract-stat-card.due .contract-stat-value { color: #d97706; }
|
||||
.contract-stat-card.overdue .contract-stat-value { color: #dc2626; }
|
||||
.contract-stat-card.needs .contract-stat-value { color: #0f172a; }
|
||||
.contract-stat-card.month .contract-stat-value { color: #16a34a; }
|
||||
@media (max-width: 900px) { .contract-stat-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
.contract-filter-bar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 16px;
|
||||
padding: 10px 14px;
|
||||
border: 1px solid #d7e1ef;
|
||||
border-radius: 12px;
|
||||
background: #fff;
|
||||
}
|
||||
.contract-filter-search { position: relative; width: min(100%, 320px); }
|
||||
.contract-filter-icon {
|
||||
position: absolute;
|
||||
left: 10px;
|
||||
top: 50%;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
color: #8aa0bd;
|
||||
transform: translateY(-50%);
|
||||
pointer-events: none;
|
||||
}
|
||||
.contract-filter-input {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
height: 36px;
|
||||
padding: 0 12px 0 30px;
|
||||
border: 1px solid #d7e1ef;
|
||||
border-radius: 8px;
|
||||
background: #f7faff;
|
||||
color: #183c72;
|
||||
font-size: 14px;
|
||||
line-height: 36px;
|
||||
outline: none;
|
||||
}
|
||||
.contract-filter-input::placeholder { color: #8aa0bd; font-size: 14px; }
|
||||
.contract-filter-input:focus { border-color: #93c5fd; box-shadow: 0 0 0 2px rgba(59, 130, 246, .12); }
|
||||
.contract-filter-submit {
|
||||
height: 36px;
|
||||
padding: 0 14px;
|
||||
border: 1px solid #d7e1ef;
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
color: #426493;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.contract-filter-submit:hover { background: #f7faff; color: #183c72; }
|
||||
.contract-filter-meta { color: #8aa0bd; font-size: 13px; line-height: 1.4; }
|
||||
.contract-ledger-panel { border: 1px solid #d7e1ef; border-radius: 14px; background: #fff; box-shadow: 0 6px 20px rgba(33, 65, 111, .05); }
|
||||
.contract-ledger-table { width: 100%; min-width: 1260px; border-collapse: collapse; color: #183c72; }
|
||||
.contract-ledger-table th { height: 59px; padding: 11px 12px; background: #f7faff; border-bottom: 1px solid #d7e1ef; color: #426493; font-size: 13px; font-weight: 700; line-height: 1.35; text-align: left; vertical-align: top; white-space: nowrap; }
|
||||
|
||||
@@ -28,7 +28,7 @@ const pages = ref(1);
|
||||
|
||||
/**
|
||||
* 读取需要人工确认的合同列表。
|
||||
* 核心逻辑:明确传入 reviewOnly,避免前端仅按显示状态过滤而遗漏后端新产生的待确认合同。
|
||||
* 核心逻辑:明确传入 reviewOnly,避免前端仅按显示状态过滤而遗漏后端新产生的待确认合同;关键词同样匹配供应商。
|
||||
* @param resetPage - 为 true 时重置到第一页,供关键词查询使用。
|
||||
* @returns 请求完成后更新分页数据;失败时保留已有列表并提示原因。
|
||||
*/
|
||||
@@ -66,7 +66,18 @@ onMounted(() => void load());
|
||||
<template>
|
||||
<section class="section-gap animate-fade-in-up">
|
||||
<div><h2 class="text-2xl font-bold text-primary">{{ t('admin.contractPaymentReview.title') }}</h2><p class="mt-1 text-sm text-muted">{{ t('admin.contractPaymentReview.subtitle') }}</p></div>
|
||||
<div class="surface-panel mt-5 rounded-2xl p-4"><div class="flex flex-wrap items-center gap-3"><div class="relative w-full md:w-[360px]"><Search class="absolute left-3 top-2.5 h-4 w-4 text-muted" /><input v-model="keyword" class="input-field pl-9" :placeholder="t('admin.contractPaymentReview.searchPlaceholder')" @keyup.enter="load(true)" /></div><button class="btn-secondary-ds" @click="load(true)">{{ t('admin.contractPayment.search') }}</button></div></div>
|
||||
<div class="contract-filter-bar">
|
||||
<div class="contract-filter-search">
|
||||
<Search class="contract-filter-icon" />
|
||||
<input
|
||||
v-model="keyword"
|
||||
class="contract-filter-input"
|
||||
:placeholder="t('admin.contractPaymentReview.searchPlaceholder')"
|
||||
@keyup.enter="load(true)"
|
||||
/>
|
||||
</div>
|
||||
<button type="button" class="contract-filter-submit" @click="load(true)">{{ t('admin.contractPayment.search') }}</button>
|
||||
</div>
|
||||
<div class="surface-panel mt-4 overflow-x-auto rounded-2xl">
|
||||
<table class="review-table text-sm"><thead><tr><th>{{ t('admin.contractPaymentReview.contractWorkflow') }}</th><th>{{ t('admin.contractPayment.purchaseOrder') }}</th><th>{{ t('admin.contractPayment.supplier') }}</th><th>{{ t('admin.contractPayment.amount') }}</th><th>{{ t('admin.contractPaymentReview.reason') }}</th></tr></thead>
|
||||
<tbody><tr v-for="item in contracts" :key="item.id" class="cursor-pointer hover:bg-surface-soft" @click="openContractDetail(item.id)"><td><strong>{{ item.contract_no || t('admin.contractPayment.contractNoPending') }}</strong><span>{{ item.workflow_no || '—' }}</span></td><td>{{ item.purchase_order_no || '—' }}</td><td>{{ item.supplier_name || '—' }}</td><td>{{ item.total_amount || '—' }}</td><td><ul><li v-for="issue in item.parse_issues || [t('admin.contractPaymentReview.fallbackIssue')]" :key="issue">{{ issue }}</li></ul></td></tr><tr v-if="!loading && !contracts.length"><td colspan="5" class="py-9 text-center text-muted">{{ t('admin.contractPaymentReview.empty') }}</td></tr></tbody>
|
||||
@@ -77,5 +88,53 @@ onMounted(() => void load());
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.contract-filter-bar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 16px;
|
||||
padding: 10px 14px;
|
||||
border: 1px solid #d7e1ef;
|
||||
border-radius: 12px;
|
||||
background: #fff;
|
||||
}
|
||||
.contract-filter-search { position: relative; width: min(100%, 320px); }
|
||||
.contract-filter-icon {
|
||||
position: absolute;
|
||||
left: 10px;
|
||||
top: 50%;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
color: #8aa0bd;
|
||||
transform: translateY(-50%);
|
||||
pointer-events: none;
|
||||
}
|
||||
.contract-filter-input {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
height: 36px;
|
||||
padding: 0 12px 0 30px;
|
||||
border: 1px solid #d7e1ef;
|
||||
border-radius: 8px;
|
||||
background: #f7faff;
|
||||
color: #183c72;
|
||||
font-size: 14px;
|
||||
line-height: 36px;
|
||||
outline: none;
|
||||
}
|
||||
.contract-filter-input::placeholder { color: #8aa0bd; font-size: 14px; }
|
||||
.contract-filter-input:focus { border-color: #93c5fd; box-shadow: 0 0 0 2px rgba(59, 130, 246, .12); }
|
||||
.contract-filter-submit {
|
||||
height: 36px;
|
||||
padding: 0 14px;
|
||||
border: 1px solid #d7e1ef;
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
color: #426493;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.contract-filter-submit:hover { background: #f7faff; color: #183c72; }
|
||||
.review-table { width: 100%; min-width: 980px; border-collapse: collapse; color: #183c72; }.review-table th { padding: 13px 14px; border-bottom: 1px solid #d7e1ef; background: #f7faff; color: #426493; text-align: left; }.review-table td { padding: 13px 14px; border-bottom: 1px solid #d7e1ef; vertical-align: top; }.review-table tbody tr:last-child td { border-bottom: 0; }.review-table strong, .review-table span { display: block; }.review-table strong { color: #102d59; }.review-table span, .review-table li { color: #9a3412; }.review-table ul { margin: 0; padding-left: 18px; }.review-table li + li { margin-top: 3px; }
|
||||
</style>
|
||||
@@ -1,16 +1,17 @@
|
||||
<!--
|
||||
features/contract-payment/views/ContractPaymentWeeklyBatchesPage.vue
|
||||
用途:独立展示合同付款预警的周汇总批次及其企业微信发送审计摘要,并下载 Excel 明细。
|
||||
依赖:contract-payment.api、统一消息提示;由工作台“合同付款预警 > 周汇总批次”路由加载。
|
||||
逻辑:后端扫描产生的批次在此集中查看;Excel 经受控接口下载,手动发送仅提交异步任务。
|
||||
依赖:contract-payment.api、useAuthStore、统一消息提示;由工作台“合同付款预警 > 周汇总批次”路由加载。
|
||||
逻辑:后端扫描产生的批次在此集中查看;Excel 经受控接口下载;手动发送仅管理员可见并提交异步任务。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { CalendarClock, Download, RefreshCw, Send } from 'lucide-vue-next';
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import { CalendarClock, Download, Send } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { formatLocalDateTime } from '@/shared/utils/dateTime';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
||||
import {
|
||||
downloadContractPaymentAlertBatchExcel,
|
||||
enqueueContractPaymentWeeklyAlert,
|
||||
@@ -19,6 +20,8 @@ import {
|
||||
} from '../api/contract-payment.api';
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const auth = useAuthStore();
|
||||
const isAdmin = computed(() => auth.isAdmin);
|
||||
const msg = useMessage();
|
||||
const batches = ref<AlertBatch[]>([]);
|
||||
const loading = ref(false);
|
||||
@@ -44,10 +47,11 @@ async function load(): Promise<void> {
|
||||
|
||||
/**
|
||||
* 手动提交本周汇总发送任务。
|
||||
* 核心逻辑:调用异步入队接口,避免浏览器等待企业微信发送和 Excel 文件生成完成。
|
||||
* 核心逻辑:仅管理员可调用异步入队接口,避免浏览器等待企业微信发送和 Excel 文件生成完成。
|
||||
* @returns 提交结果通过统一消息提示反馈,成功后刷新批次列表。
|
||||
*/
|
||||
async function runWeeklyAlert(): Promise<void> {
|
||||
if (!isAdmin.value) return;
|
||||
actionLoading.value = true;
|
||||
try {
|
||||
await enqueueContractPaymentWeeklyAlert();
|
||||
@@ -128,10 +132,7 @@ onMounted(() => void load());
|
||||
<h2 class="text-2xl font-bold text-primary">{{ t('admin.contractPayment.weeklyBatchesTitle') }}</h2>
|
||||
<p class="mt-1 text-sm text-muted">{{ t('admin.contractPayment.weeklyBatchesSubtitle') }}</p>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<button class="btn-secondary-ds" :disabled="loading" @click="() => load()">
|
||||
<RefreshCw class="h-4 w-4" />{{ t('admin.contractPayment.refresh') }}
|
||||
</button>
|
||||
<div v-if="isAdmin" class="flex gap-2">
|
||||
<button class="btn-primary" :disabled="actionLoading" @click="runWeeklyAlert">
|
||||
<Send class="h-4 w-4" />{{ t('admin.contractPayment.weeklySend') }}
|
||||
</button>
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
/**
|
||||
* features/kb/api/kb.api.ts
|
||||
* 用途:知识库 HTTP API 封装。
|
||||
* 依赖:auth、requestJson/BusinessError、vue-i18n(错误 fallback 文案)。
|
||||
* 依赖:auth、requestJson/BusinessError、vue-i18n(错误 fallback 文案)、shared/utils/download。
|
||||
* 逻辑:KbWorkspace / composables 调用;失败时优先保留 BusinessError.message,否则回退本地化 fallback。
|
||||
* 源文件下载走 ?download=1,文件名由 Content-Disposition filename* 或调用方 source_file_name 决定。
|
||||
*/
|
||||
import i18n from '@/i18n';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { BusinessError, requestJson } from '@/shared/api/client';
|
||||
import { parseContentDispositionFilename } from '@/shared/utils/download';
|
||||
|
||||
const kbT = (key: string) => String(i18n.global.t(key));
|
||||
const kbErrorMessage = (e: unknown, fallbackKey: string) =>
|
||||
@@ -300,11 +302,17 @@ export const getKbDocumentVersions = async (
|
||||
return getJson<KbDocumentVersionItem[]>(`/api/kb/documents/${documentId}/versions`, []);
|
||||
};
|
||||
|
||||
/**
|
||||
* 拉取知识库版本原始文件,供作业面触发本地下载。
|
||||
* 核心逻辑:带 download=1 走附件响应;文件名优先 RFC 5987 filename*,失败由调用方回退 source_file_name。
|
||||
* @param versionId - 文档版本 ID
|
||||
* @returns 成功时含 blob 与解析出的文件名;失败时 ok=false
|
||||
*/
|
||||
export const getKbDocumentVersionSourceFile = async (
|
||||
versionId: number
|
||||
): Promise<{ ok: boolean; error?: string; blob?: Blob; filename?: string; contentType?: string }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/document-versions/${versionId}/source-file`, {
|
||||
const res = await fetch(`/api/kb/document-versions/${versionId}/source-file?download=1`, {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
if (!res.ok) {
|
||||
@@ -318,13 +326,10 @@ export const getKbDocumentVersionSourceFile = async (
|
||||
}
|
||||
return { ok: false, error: message };
|
||||
}
|
||||
const disposition = res.headers.get('content-disposition') || '';
|
||||
const filenameMatch = disposition.match(/filename\*=UTF-8''([^;]+)|filename="?([^"]+)"?/i);
|
||||
const filename = decodeURIComponent(filenameMatch?.[1] || filenameMatch?.[2] || '');
|
||||
return {
|
||||
ok: true,
|
||||
blob: await res.blob(),
|
||||
filename: filename || undefined,
|
||||
filename: parseContentDispositionFilename(res.headers.get('content-disposition')),
|
||||
contentType: res.headers.get('content-type') || undefined,
|
||||
};
|
||||
} catch {
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
/**
|
||||
* features/kb/composables/kb-workspace/useKbWorkspaceModals.ts
|
||||
* 记录/来源/Markdown/失败弹窗与原始文件预览。
|
||||
* 用途:记录/来源/Markdown/失败弹窗与原始文件下载。
|
||||
* 依赖:kb.api、kb-workspace state/computed/data、shared/utils/download。
|
||||
* 逻辑:KbWorkspaceOverlays 调用;源文件点击只触发一次 a[download],保存名与上传时一致。
|
||||
*/
|
||||
import { triggerBlobDownload } from '@/shared/utils/download';
|
||||
import type { KbDocumentItem, KbDocumentMarkdown, KbDocumentVersionItem } from '../../api/kb.api';
|
||||
import {
|
||||
getKbDocumentMarkdown,
|
||||
@@ -74,6 +77,11 @@ export function useKbWorkspaceModals(
|
||||
showSourceInfoModal.value = false;
|
||||
};
|
||||
|
||||
/**
|
||||
* 下载当前版本的原始文件,保存名与上传时的源文件名一致。
|
||||
* 核心逻辑:拉 blob 后只触发一次 a[download];不用 window.open blob URL,避免再下一份 UUID 名文件。
|
||||
* @param version - 源文件信息弹窗中的版本项
|
||||
*/
|
||||
const openOriginalSourceFile = async (version: KbDocumentVersionItem) => {
|
||||
openingSourceVersionId.value = version.id;
|
||||
const result = await getKbDocumentVersionSourceFile(version.id);
|
||||
@@ -84,15 +92,8 @@ export function useKbWorkspaceModals(
|
||||
return;
|
||||
}
|
||||
|
||||
const objectUrl = window.URL.createObjectURL(result.blob);
|
||||
const opened = window.open(objectUrl, '_blank', 'noopener,noreferrer');
|
||||
if (!opened) {
|
||||
const link = window.document.createElement('a');
|
||||
link.href = objectUrl;
|
||||
link.download = result.filename || version.source_file_name || `source-${version.id}`;
|
||||
link.click();
|
||||
}
|
||||
window.setTimeout(() => window.URL.revokeObjectURL(objectUrl), 60_000);
|
||||
const filename = version.source_file_name || result.filename || `source-${version.id}`;
|
||||
triggerBlobDownload(result.blob, filename);
|
||||
};
|
||||
|
||||
const openFailureModal = (type: 'upload' | 'clean' | 'sync') => {
|
||||
|
||||
@@ -1186,12 +1186,17 @@
|
||||
"username": "Username",
|
||||
"email": "Email",
|
||||
"department": "Department",
|
||||
"team": "Team",
|
||||
"jobTitle": "Job title",
|
||||
"isTeamLeader": "Team leader",
|
||||
"role": "Role",
|
||||
"featurePermissions": "Feature Permissions",
|
||||
"trainingHrManage": "Training HR Admin",
|
||||
"trainingHrManageHint": "Allows this user to open the employee training agent HR Management view for stats, filtering, and Excel export.",
|
||||
"trainingLeanManage": "Lean training full management",
|
||||
"trainingLeanTeamManage": "Lean training team management",
|
||||
"contractPaymentAccess": "Contract payment alert access",
|
||||
"contractPaymentAccessHint": "Allows this user to open the contract payment workbench (ledger, review, weekly batches) and trigger sync or scans.",
|
||||
"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.",
|
||||
"password": "Password",
|
||||
"passwordHint": "(leave blank to keep)",
|
||||
"noAgents": "No agents available."
|
||||
@@ -4758,7 +4763,7 @@
|
||||
}
|
||||
},
|
||||
"contractPayment": {
|
||||
"title": "Contract Payment Alerts", "subtitle": "Sync OA contract, acceptance, and vendor prepayment requests; notify procurement roles through three escalation rounds.", "sync": "Sync OA data", "forceSync": "Force overwrite OA fields", "forceSyncConfirm": "This will overwrite existing OA data with non-empty fields returned this time and record an audit trail. Continue?", "reparseExisting": "Reparse existing contracts", "reparseExistingConfirm": "This will refresh all existing contract parsing results from archived attachments using the current rules. OA fields will not be synced or overwritten. Continue?", "scanAlerts": "Scan to generate alerts", "jobSubmitted": "Job submitted", "actionFailed": "Action failed", "loadFailed": "Failed to load contracts", "searchPlaceholder": "Search contract or purchase order number", "allStatus": "All", "search": "Search", "ledger": "Contract ledger", "items": "items", "empty": "No contract data", "purchaseOrder": "Purchase order", "supplier": "Supplier", "amount": "Contract amount", "deliveryDate": "Delivery due date", "timeline": "Payment plan timeline", "notAvailable": "—", "stats": {"contracts": "Contracts", "pendingParse": "Pending contracts", "readyPlans": "Plans ready", "alerts": "Alert nodes"}, "status": {"completed": "Completed", "needs_review": "Needs review", "pending": "Pending parse"}, "stateLabel": {"parsed": "Parsed", "needs_review": "Needs review", "pending": "Pending parse", "active": "Active"}, "nodeType": {"prepayment": "Prepayment", "shipment": "Shipment payment", "acceptance": "Acceptance payment", "warranty": "Warranty payment"}, "ruleConfirmed": "Confirmed", "prepaymentRule": "Alerts at 7/14/21 days after contract archival; request status comes from OA vendor prepayment requests.", "shipmentRule": "Alerts 7 days before delivery, on the due date, and 14 days after; request status comes from OA vendor prepayment requests.", "acceptanceRule": "Alerts at 30/40/60 days after acceptance archival; warranty alerts are 7 days before, on, and 14 days after maturity.", "pendingAlerts": "Pending alerts", "processing": "Payment initiated", "dataPending": "Data pending", "paid": "Paid", "amountRatioDate": "Amount / ratio · date", "applicant": "Applicant", "statusLabel": "Status", "contractPrefix": "Contract", "datePending": "Date pending", "statusNormal": "Normal", "statusNeedsCompletion": "Needs completion", "statusOverdue": "Overdue", "statusUpcoming": "Due soon", "statusActive": "In progress", "statusCompleted": "Completed", "totalPrefix": "Total", "contractSupplier": "Contract / supplier", "nextAlert": "Next alert", "triggerBasis": "Trigger basis", "alertDate": "Alert date", "alertFirstRound": "Round 1", "payDate": "Payment date", "processStatus": "Status", "owner": "Procurement owner", "oaData": "OA data", "contractRule": "Contract rule", "ownerDefault": "Procurement owner", "workflowNo": "Workflow number", "contractNoPending": "Contract number pending attachment parsing", "synced": "Synced", "detailSubtitle": "OA data, payment nodes, and WeCom alert records", "backToOverview": "Back to overview", "contractInfo": "OA contract details", "alertHistory": "Alert history", "alertRound": "Alert round {round}", "alertAudit": "Alert delivery record", "alertAuditEmpty": "No alert records", "alertNode": "Payment stage", "alertScheduledAt": "Scheduled date", "alertSentAt": "Sent at", "alertStatus": {"pending": "Pending", "sent": "Sent", "failed": "Failed"}, "roundValue": "Round {round}", "weeklyBatchesTitle": "Weekly Summary Batches", "weeklyBatchesSubtitle": "Review recipient-level payment-alert summaries, Excel attachments, and delivery records.", "refresh": "Refresh", "weeklySend": "Send alerts", "weeklyBatchSubmitted": "Send alert job submitted", "weeklyBatchesLoadFailed": "Failed to load weekly summary batches", "batchNo": "Batch no.", "weekKey": "Week", "batchStatusLabel": "Delivery status", "batchTotal": "Summary count", "batchExcel": "Excel attachment", "batchSentAt": "Sent at", "weeklyBatchesEmpty": "No weekly summary batches", "weeklyPendingSummary": "{count} pending this week · next send {datetime}", "weeklyPendingCountOnly": "{count} pending this week", "downloadExcel": "Download Excel", "excelDownloadFailed": "Failed to download the alert attachment", "batchStatus": {"pending": "Pending", "sent": "Sent", "failed": "Failed", "processing": "Processing", "resolved": "Alerts stopped"}, "backToLedger": "Back", "detailLoadFailed": "Failed to load contract details", "detailLoading": "Loading contract details…", "detailOverview": "Contract Overview", "detailAttachments": "Original Attachments", "detailPaymentPlan": "Payment Plan", "detailAlertHistory": "Alert History", "archiveDate": "Contract archive date", "archiveDateHint": "This date is when the contract application form was archived", "parseStatus": "Parsing status", "parseIssueTitle": "Parse issues", "planStatus": "Plan status", "attachmentsEmpty": "No archived original contract attachments", "downlLine truncated
|
||||
"title": "Contract Payment Alerts", "subtitle": "Sync OA contract, acceptance, and vendor prepayment requests; notify procurement roles through three escalation rounds.", "sync": "Sync OA data", "forceSync": "Force overwrite OA fields", "forceSyncConfirm": "This will overwrite existing OA data with non-empty fields returned this time and record an audit trail. Continue?", "reparseExisting": "Reparse existing contracts", "reparseExistingConfirm": "This will refresh all existing contract parsing results from archived attachments using the current rules. OA fields will not be synced or overwritten. Continue?", "scanAlerts": "Scan to generate alerts", "jobSubmitted": "Job submitted", "actionFailed": "Action failed", "loadFailed": "Failed to load contracts", "searchPlaceholder": "Search contract number, purchase order, or supplier", "allStatus": "All", "search": "Search", "ledger": "Contract ledger", "items": "items", "empty": "No contract data", "purchaseOrder": "Purchase order", "supplier": "Supplier", "amount": "Contract amount", "deliveryDate": "Delivery due date", "timeline": "Payment plan timeline", "notAvailable": "—", "stats": {"contracts": "Contracts", "pendingParse": "Pending contracts", "readyPlans": "Plans ready", "alerts": "Alert nodes"}, "ledgerFocus": {"due": "Due soon", "dueHint": "within 7 days", "overdue": "Overdue unpaid", "needsCompletion": "Needs completion", "dueThisMonth": "Due this month", "dueThisMonthHint": "this calendar month"}, "status": {"completed": "Completed", "needs_review": "Needs review", "pending": "Pending parse"}, "stateLabel": {"parsed": "Parsed", "needs_review": "Needs review", "pending": "Pending parse", "active": "Active"}, "nodeType": {"prepayment": "Prepayment", "shipment": "Shipment payment", "acceptance": "Acceptance payment", "warranty": "Warranty payment"}, "ruleConfirmed": "Confirmed", "prepaymentRule": "Alerts at 7/14/21 days after contract archival; request status comes from OA vendor prepayment requests.", "shipmentRule": "Alerts 7 days before delivery, on the due date, and 14 days after; request status comes from OA vendor prepayment requests.", "acceptanceRule": "Alerts at 30/40/60 days after acceptance archival; warranty alerts are 7 days before, on, and 14 days after maturity.", "pendingAlerts": "Pending alerts", "processing": "Payment initiated", "dataPending": "Data pending", "paid": "Paid", "amountRatioDate": "Amount / ratio · date", "applicant": "Applicant", "statusLabel": "Status", "contractPrefix": "Contract", "datePending": "Date pending", "statusNormal": "Normal", "statusNeedsCompletion": "Needs completion", "statusOverdue": "Overdue", "statusUpcoming": "Due soon", "statusActive": "In progress", "statusCompleted": "Completed", "totalPrefix": "Total", "contractSupplier": "Contract / supplier", "nextAlert": "Next alert", "triggerBasis": "Trigger basis", "alertDate": "Alert date", "alertFirstRound": "Round 1", "payDate": "Payment date", "processStatus": "Status", "owner": "Procurement owner", "oaData": "OA data", "contractRule": "Contract rule", "ownerDefault": "Procurement owner", "workflowNo": "Workflow number", "contractNoPending": "Contract number pending attachment parsing", "synced": "Synced", "detailSubtitle": "OA data, payment nodes, and WeCom alert records", "backToOverview": "Back to overview", "contractInfo": "OA contract details", "alertHistory": "Alert history", "alertRound": "Alert round {round}", "alertAudit": "Alert delivery record", "alertAuditEmpty": "No alert records", "alertNode": "Payment stage", "alertScheduledAt": "Scheduled date", "alertSentAt": "Sent at", "alertStatus": {"pending": "Pending", "sent": "Sent", "failed": "Failed"}, "roundValue": "Round {round}", "weeklyBatchesTitle": "Weekly Summary Batches", "weeklyBatchesSubtitle": "Review recipient-level payment-alert summaries, Excel attachments, and delivery records.", "weeklySend": "Send alerts", "weeklyBatchSubmitted": "Send alert job submitted", "weeklyBatchesLoadFailed": "Failed to load weekly summary batches", "batchNo": "Batch no.", "weekKey": "Week", "batchStatusLabel": "Delivery status", "batchTotal": "Summary count", "batchExcel": "Excel attachment", "batchSentAt": "Sent at", "weeklyBatchesEmpty": "No weekly summary batches", "weeklyPendingSummary": "{count} pending this week · next send {datetime}", "weeklyPendingCountOnly": "{count} pending this week", "downloadExcel": "Download Excel", "excelDownloadFailed": "Failed to download the alert attachment", "batchStatus": {"pending": "Pending", "sent": "Sent", "failed": "Failed", "processing": "Processing", "resolved": "Alerts stopped"}, "backToLedger": "Back", "detailLoadFailed": "Failed to load contract details", "detailLoading": "Loading contract details…", "detailOverview": "Contract Overview", "detailAttachments": "Original Attachments", "detailPaymentPlan": "Payment Plan", "detailAlertHistory": "Alert History", "archiveDate": "Contract archive date", "archiveDateHint": "This date is when the contract apLine truncated
|
||||
},
|
||||
"contractPaymentReview": {"title": "Contracts for Confirmation", "subtitle": "Contracts that do not match the equipment procurement synonym title groups, fail payment-ratio validation, or conflict with OA fields are excluded from payment alerts. Download the original contract to verify it.", "searchPlaceholder": "Contract number, purchase order, or supplier", "loadFailed": "Failed to load contracts for confirmation", "contractWorkflow": "Contract / workflow number", "reason": "Reason for confirmation", "fallbackIssue": "Parsing result requires manual confirmation", "empty": "No contracts need confirmation"},
|
||||
"contractPaymentReparse": {"action": "Reparse contract original", "success": "Reparsed with attachment “{attachment}”", "failed": "Failed to reparse contract"},
|
||||
@@ -4957,7 +4962,9 @@
|
||||
"examTitle": "Question Bank",
|
||||
"examDesc": "Maintain structured question data for controlled examinations",
|
||||
"reviewTitle": "Review & Checklist",
|
||||
"reviewDesc": "Configure review points, pre-exam checklists, and guided chat questions"
|
||||
"reviewDesc": "Configure review points, pre-exam checklists, and guided chat questions",
|
||||
"leanTitle": "Lean Weekly Task",
|
||||
"leanDesc": "Choose the weekly video list, set videos per week, and configure the deadline for that week"
|
||||
},
|
||||
"guideGroups": {
|
||||
"company": "Company-level Safety Training",
|
||||
@@ -4984,6 +4991,7 @@
|
||||
"progressItemLabel": "Progress item label",
|
||||
"progressHintText": "Training progress note",
|
||||
"stepIntroText": "Training step guide copy",
|
||||
"requiredDuration": "Required time (minutes)",
|
||||
"summaryPoints": "Review points",
|
||||
"summaryChecklist": "Pre-exam checklist",
|
||||
"employeeQuestions": "Employee FAQs",
|
||||
@@ -5012,6 +5020,66 @@
|
||||
"guide": "Guide resource",
|
||||
"document": "Knowledge document"
|
||||
},
|
||||
"directVideo": {
|
||||
"title": "Training Videos",
|
||||
"hint": "Upload videos directly. Uploaded videos are automatically added to this training configuration.",
|
||||
"upload": "Upload Video",
|
||||
"uploading": "Uploading...",
|
||||
"empty": "No training videos uploaded",
|
||||
"unnamed": "Unnamed video"
|
||||
},
|
||||
"lean": {
|
||||
"weekKey": "Task week (Monday)",
|
||||
"dueAt": "Due time",
|
||||
"weekMustBeMonday": "The task week must be a Monday",
|
||||
"weeklyCount": "Videos per week",
|
||||
"weeklyCountHint": "Every Monday 09:00, the next batch of this many videos is pushed in selection order ({pushed}/{total} pushed); trainees get access immediately after publishing",
|
||||
"videosTitle": "Required training videos",
|
||||
"videosHint": "{count} videos selected (pushed weekly in batches by selection order)",
|
||||
"targetsTitle": "Training targets",
|
||||
"targetsHint": "Select roles or users; both scopes are combined.",
|
||||
"targetRoles": "Target roles",
|
||||
"targetUsers": "Target users",
|
||||
"addTarget": "Add trainees",
|
||||
"targetEmpty": "No training targets selected yet. Click \"Add trainees\" to configure by role or employee.",
|
||||
"targetModalTitle": "Add training targets",
|
||||
"targetSearchPlaceholder": "Search name / username / department",
|
||||
"targetSelectedCount": "{roles} roles · {users} employees selected",
|
||||
"targetUsersCount": "Target users ({count})",
|
||||
"targetRolesEmpty": "No roles available",
|
||||
"targetUsersEmpty": "No matching employees found",
|
||||
"removeTarget": "Remove",
|
||||
"targetConfirm": "Confirm",
|
||||
"noVideoResources": "Save at least one video resource in Training Materials first",
|
||||
"summaryRule": "Employees must watch the assigned videos and submit a learning reflection of at least {count} characters",
|
||||
"pushNow": "Push new-task supplement now",
|
||||
"pushing": "Pushing…",
|
||||
"weekRangeLabel": "Week {index} · {range}",
|
||||
"videoPagePrev": "Previous",
|
||||
"videoPageNext": "Next",
|
||||
"videoPageInfo": "Page {page} / {total}",
|
||||
"pushCompleted": "All videos have been pushed",
|
||||
"pushSuccess": "Pushed {count} videos and notified trainees",
|
||||
"pushFailed": "Video push failed, please retry later",
|
||||
"pushLogsTitle": "Push logs",
|
||||
"pushLogsEmpty": "No push logs yet",
|
||||
"pushProgress": "{pushed}/{total} videos pushed",
|
||||
"pushBatch": "Pushed {count} videos · sent {sent} · failed {failed} · {recipients} recipients",
|
||||
"pushStatus": {
|
||||
"sent": "All sent",
|
||||
"partial": "Partially failed",
|
||||
"failed": "Push failed",
|
||||
"completed": "Fully pushed"
|
||||
},
|
||||
"pushTrigger": {
|
||||
"publish": "On publish",
|
||||
"schedule": "Weekly schedule",
|
||||
"manual": "Manual push"
|
||||
},
|
||||
"saveTask": "Publish weekly task",
|
||||
"publishRequired": "Save and publish the Lean Management configuration before creating a weekly task",
|
||||
"unnamedVideo": "Unnamed video"
|
||||
},
|
||||
"messages": {
|
||||
"loadFailed": "Failed to load training configurations",
|
||||
"saveFailed": "Failed to save training configuration",
|
||||
@@ -5026,7 +5094,13 @@
|
||||
"parseSuccess": "Parsed {count} questions. Review before saving.",
|
||||
"parseFailed": "Question bank parsing failed",
|
||||
"saved": "Training configuration saved",
|
||||
"deleted": "Training configuration deleted"
|
||||
"deleted": "Training configuration deleted",
|
||||
"leanVideoCount": "Select at least one training video",
|
||||
"leanTaskSaved": "Lean weekly task published",
|
||||
"videoFileRequired": "Please select a video file",
|
||||
"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"
|
||||
}
|
||||
},
|
||||
"integrationConnector": {
|
||||
|
||||
@@ -1014,11 +1014,81 @@
|
||||
"description": "The administrator has not published the current training configuration yet."
|
||||
},
|
||||
"unknownDepartment": "Department pending",
|
||||
"lean": {
|
||||
"learner": {
|
||||
"title": "Lean Management Weekly Training",
|
||||
"taskTitle": "Session {index}",
|
||||
"description": "Complete {count} required videos and submit a learning reflection of at least {minSummaryLength} characters for this session.",
|
||||
"taskPeriod": "Task period: {start} to {end}",
|
||||
"completedSummary": "Learning Reflection",
|
||||
"completedAt": "Completed at: {time}",
|
||||
"empty": "No lean training tasks yet"
|
||||
},
|
||||
"taskStatus": {
|
||||
"in_progress": "In Progress",
|
||||
"overdue": "Overdue",
|
||||
"completed": "Completed"
|
||||
},
|
||||
"videoUnavailable": "This video has no playable URL yet",
|
||||
"dueAt": "Due {time}",
|
||||
"watchedAt": "Watched: {time}",
|
||||
"markVideoWatched": "Click to record video completion",
|
||||
"videoWatchedToast": "Video watching completed",
|
||||
"videoWatchedBadge": "Completed",
|
||||
"completeVideosFirst": "Please watch all required videos of this session in full before submitting your reflection",
|
||||
"summaryTooShort": "The learning reflection must be at least {minSummaryLength} characters. Please keep writing",
|
||||
"summaryPlaceholder": "Enter this week's learning reflection (at least {minSummaryLength} characters)",
|
||||
"summaryLength": "{current}/{minSummaryLength} characters",
|
||||
"submitSummary": "Submit Learning Reflection",
|
||||
"dashboard": {
|
||||
"title": "Lean Training Completion Lists",
|
||||
"week": "Training week: {week}",
|
||||
"completed": "Completed",
|
||||
"incomplete": "Incomplete",
|
||||
"count": "{count} people",
|
||||
"empty": "No personnel data",
|
||||
"passRate": "Completion Rate",
|
||||
"periodLabel": "Period {index}"
|
||||
},
|
||||
"columns": {
|
||||
"employeeId": "Employee ID",
|
||||
"name": "Name",
|
||||
"department": "Department",
|
||||
"team": "Team",
|
||||
"jobTitle": "Job Title",
|
||||
"videoName": "Video Name",
|
||||
"watchedAt": "Watch Time",
|
||||
"status": "Status",
|
||||
"summary": "Summary",
|
||||
"action": "Action"
|
||||
},
|
||||
"status": {
|
||||
"completed": "Completed",
|
||||
"in_progress": "In Progress",
|
||||
"overdue": "Overdue",
|
||||
"incomplete": "Incomplete"
|
||||
},
|
||||
"reminder": {
|
||||
"action": "Remind",
|
||||
"sending": "Sending...",
|
||||
"success": "Reminder sent ({count} people)",
|
||||
"partial": "Reminder sent ({sent} people), {failed} failed. See the WeCom notify audit in the admin console for details.",
|
||||
"sendFailed": "Failed to send reminder ({count} people). Check the WeCom notification settings, or see the notify audit in the admin console.",
|
||||
"notSent": "No reminder sent: the member may have completed the training or is not bound to WeCom.",
|
||||
"failed": "Failed to send reminder. Please try again later."
|
||||
},
|
||||
"summaryModal": {
|
||||
"title": "Summary Details",
|
||||
"viewHint": "Click to view the full summary",
|
||||
"close": "Close"
|
||||
}
|
||||
},
|
||||
"video": {
|
||||
"title": "Step 1: Watch the training video",
|
||||
"description": "Employees first complete the onboarding video, then move on to the knowledge review and exam.",
|
||||
"completeAction": "I finished watching the video",
|
||||
"playerTitle": "Video player slot",
|
||||
"empty": "No playable training video is configured yet",
|
||||
"playerHint": "This area can later connect to an enterprise video URL or internal player. The frontend container and completion action are already prepared."
|
||||
},
|
||||
"summary": {
|
||||
@@ -1078,6 +1148,10 @@
|
||||
"rule4": "HR can view statistics and export Excel from the same chat page."
|
||||
},
|
||||
"hr": {
|
||||
"tabs": {
|
||||
"allTraining": "All Training",
|
||||
"leanManagement": "Lean Management"
|
||||
},
|
||||
"stats": {
|
||||
"total": "Participants",
|
||||
"passed": "Passed",
|
||||
|
||||
@@ -129,6 +129,7 @@
|
||||
"AUTH_SSO_ASSERTION_ISSUE_FAILED": "The peer-service login assertion could not be issued. Please retry.",
|
||||
"AUTH_FORBIDDEN": "You do not have permission to perform this action.",
|
||||
"CONTRACT_PAYMENT_FORBIDDEN": "You do not have access to contract payment alerts.",
|
||||
"CONTRACT_PAYMENT_ADMIN_REQUIRED": "Only administrators can sync, scan, or send contract payment alerts.",
|
||||
"SHIPPING_TASK_SELECTION_INVALID": "Select between 1 and 100 shipping tasks.",
|
||||
"SHIPPING_TASK_DELETE_REASON_REQUIRED": "A reason is required to delete or void tasks.",
|
||||
"SHIPPING_TASK_EXTERNAL_VOID_BLOCKED": "The task is uploading externally or has been uploaded. It can only be archived.",
|
||||
|
||||
@@ -284,7 +284,7 @@
|
||||
"loading": "Loading source file info...",
|
||||
"empty": "No source file info. Upload a version to see it here.",
|
||||
"currentVersion": "Current version",
|
||||
"opening": "Opening...",
|
||||
"opening": "Downloading...",
|
||||
"fileName": "File: {name}",
|
||||
"fileSize": "Size: {size}",
|
||||
"fileType": "Type: {ext}"
|
||||
|
||||
@@ -1186,12 +1186,17 @@
|
||||
"username": "ชื่อผู้ใช้",
|
||||
"email": "อีเมล",
|
||||
"department": "แผนก",
|
||||
"team": "ทีม",
|
||||
"jobTitle": "ตำแหน่งงาน",
|
||||
"isTeamLeader": "หัวหน้าทีม",
|
||||
"role": "บทบาท",
|
||||
"featurePermissions": "สิทธิ์ฟีเจอร์",
|
||||
"trainingHrManage": "จัดการ HR การฝึกอบรม",
|
||||
"trainingHrManageHint": "เมื่อเปิดแล้ว ผู้ใช้นี้จะเข้าใช้มุมมอง HR 管理 ใน employee training agent เพื่อดูสถิติ คัดกรองข้อมูล และส่งออก Excel ได้",
|
||||
"trainingLeanManage": "จัดการการฝึกอบรม Lean ทั้งหมด",
|
||||
"trainingLeanTeamManage": "จัดการการฝึกอบรม Lean ระดับทีม",
|
||||
"contractPaymentAccess": "สิทธิ์แจ้งเตือนการชำระเงินตามสัญญา",
|
||||
"contractPaymentAccessHint": "เมื่อเปิดแล้ว ผู้ใช้นี้จะเข้าโต๊ะทำงานแจ้งเตือนการชำระเงินตามสัญญา (บัญชีสัญญา รายการรอยืนยัน และชุดสรุปรายสัปดาห์) และสั่งซิงค์หรือสแกนได้",
|
||||
"contractPaymentAccessHint": "เมื่อเปิดแล้ว ผู้ใช้นี้จะเข้าโต๊ะทำงานแจ้งเตือนการชำระเงินตามสัญญา (บัญชีสัญญา รายการรอยืนยัน และชุดสรุปรายสัปดาห์) ได้ การซิงก์ OA สแกนแจ้งเตือน และส่งสรุปรายสัปดาห์ใช้ได้เฉพาะผู้ดูแลระบบ",
|
||||
"password": "รหัสผ่าน",
|
||||
"passwordHint": "(เว้นว่างไว้หากไม่ต้องการเปลี่ยน)",
|
||||
"noAgents": "ไม่มีตัวแทนที่ใช้ได้"
|
||||
@@ -4627,7 +4632,7 @@
|
||||
}
|
||||
},
|
||||
"contractPayment": {
|
||||
"title": "แจ้งเตือนการชำระเงินตามสัญญา", "subtitle": "ซิงก์สัญญา OA การรับมอบ และคำขอเบิกเงินล่วงหน้าของผู้ขาย พร้อมแจ้งเตือน 3 ระดับ", "sync": "ซิงก์ข้อมูล OA", "forceSync": "เขียนทับฟิลด์ OA แบบบังคับ", "forceSyncConfirm": "ระบบจะเขียนทับข้อมูล OA เดิมด้วยฟิลด์ที่ไม่ว่างจาก OA ครั้งนี้และบันทึกการตรวจสอบ ต้องการดำเนินการต่อหรือไม่?", "reparseExisting": "แยกวิเคราะห์สัญญาเดิมทั้งหมดใหม่", "reparseExistingConfirm": "ระบบจะรีเฟรชผลการแยกข้อมูลของสัญญาเดิมทั้งหมดจากไฟล์แนบที่จัดเก็บตามกฎปัจจุบัน โดยจะไม่ซิงก์หรือเขียนทับฟิลด์ OA ต้องการดำเนินการต่อหรือไม่?", "scanAlerts": "สแกนเพื่อสร้างแจ้งเตือน", "jobSubmitted": "ส่งงานแล้ว", "actionFailed": "ดำเนินการไม่สำเร็จ", "loadFailed": "โหลดสัญญาไม่สำเร็จ", "searchPlaceholder": "ค้นหาเลขที่สัญญาหรือใบสั่งซื้อ", "allStatus": "ทั้งหมด", "search": "ค้นหา", "ledger": "ทะเบียนสัญญา", "items": "รายการ", "empty": "ไม่มีข้อมูลสัญญา", "purchaseOrder": "ใบสั่งซื้อ", "supplier": "ผู้ขาย", "amount": "มูลค่าสัญญา", "deliveryDate": "กำหนดส่งมอบ", "timeline": "ไทม์ไลน์แผนการชำระเงิน", "notAvailable": "—", "stats": {"contracts": "สัญญา", "pendingParse": "สัญญาที่รอดำเนินการ", "readyPlans": "แผนพร้อมใช้", "alerts": "จุดแจ้งเตือน"}, "status": {"completed": "เสร็จสิ้น", "needs_review": "ต้องตรวจสอบ", "pending": "รอแยกข้อมูล"}, "stateLabel": {"parsed": "แยกข้อมูลแล้ว", "needs_review": "ต้องตรวจสอบ", "pending": "รอแยกข้อมูล", "active": "ใช้งานอยู่"}, "nodeType": {"prepayment": "เงินล่วงหน้า", "shipment": "เงินก่อนส่ง", "acceptance": "เงินรับมอบ", "warranty": "เงินประกัน"}, "ruleConfirmed": "ยืนยันแล้ว", "prepaymentRule": "แจ้งเตือนวันที่ 7/14/21 หลังจัดเก็บสัญญา; สถานะคำขออ้างอิง OA.", "shipmentRule": "แจ้งเตือนก่อนกำหนดส่ง 7 วัน วันครบกำหนด และหลังครบกำหนด 14 วัน; สถานะคำขออ้างอิง OA.", "acceptanceRule": "แจ้งเตือนวันที่ 30/40/60 หลังจัดเก็บใบรับมอบ; เงินประกันแจ้งก่อนครบกำหนด 7 วัน วันครบกำหนด และหลังครบกำหนด 14 วัน.", "pendingAlerts": "แจ้งเตือนที่รอดำเนินการ", "processing": "เริ่มชำระแล้ว", "dataPending": "รอข้อมูล", "paid": "ชำระแล้ว", "amountRatioDate": "จำนวนเงิน / สัดส่วน · วันที่", "applicant": "ผู้ขอ", "statusLabel": "สถานะ", "contractPrefix": "สัญญา", "datePending": "รอระบุวันที่", "statusNormal": "ปกติ", "statusNeedsCompletion": "ต้องเติมข้อมูล", "statusOverdue": "เกินกำหนดชำระ", "statusUpcoming": "ใกล้ถึงกำหนด", "statusActive": "กำลังดำเนินการ", "statusCompleted": "เสร็จสิ้น", "totalPrefix": "รวม", "contractSupplier": "สัญญา / ผู้ขาย", "nextAlert": "แจ้งเตือนถัดไป", "triggerBasis": "เกณฑ์เริ่ม", "alertDate": "วันที่แจ้งเตือน", "alertFirstRound": "รอบ 1", "payDate": "วันที่ชำระLine truncated
|
||||
"title": "แจ้งเตือนการชำระเงินตามสัญญา", "subtitle": "ซิงก์สัญญา OA การรับมอบ และคำขอเบิกเงินล่วงหน้าของผู้ขาย พร้อมแจ้งเตือน 3 ระดับ", "sync": "ซิงก์ข้อมูล OA", "forceSync": "เขียนทับฟิลด์ OA แบบบังคับ", "forceSyncConfirm": "ระบบจะเขียนทับข้อมูล OA เดิมด้วยฟิลด์ที่ไม่ว่างจาก OA ครั้งนี้และบันทึกการตรวจสอบ ต้องการดำเนินการต่อหรือไม่?", "reparseExisting": "แยกวิเคราะห์สัญญาเดิมทั้งหมดใหม่", "reparseExistingConfirm": "ระบบจะรีเฟรชผลการแยกข้อมูลของสัญญาเดิมทั้งหมดจากไฟล์แนบที่จัดเก็บตามกฎปัจจุบัน โดยจะไม่ซิงก์หรือเขียนทับฟิลด์ OA ต้องการดำเนินการต่อหรือไม่?", "scanAlerts": "สแกนเพื่อสร้างแจ้งเตือน", "jobSubmitted": "ส่งงานแล้ว", "actionFailed": "ดำเนินการไม่สำเร็จ", "loadFailed": "โหลดสัญญาไม่สำเร็จ", "searchPlaceholder": "ค้นหาเลขที่สัญญา ใบสั่งซื้อ หรือผู้ขาย", "allStatus": "ทั้งหมด", "search": "ค้นหา", "ledger": "ทะเบียนสัญญา", "items": "รายการ", "empty": "ไม่มีข้อมูลสัญญา", "purchaseOrder": "ใบสั่งซื้อ", "supplier": "ผู้ขาย", "amount": "มูลค่าสัญญา", "deliveryDate": "กำหนดส่งมอบ", "timeline": "ไทม์ไลน์แผนการชำระเงิน", "notAvailable": "—", "stats": {"contracts": "สัญญา", "pendingParse": "สัญญาที่รอดำเนินการ", "readyPlans": "แผนพร้อมใช้", "alerts": "จุดแจ้งเตือน"}, "ledgerFocus": {"due": "ใกล้ครบกำหนด", "dueHint": "ใน 7 วัน", "overdue": "ค้างชำระเกินกำหนด", "needsCompletion": "รอข้อมูลเพิ่ม", "dueThisMonth": "ถึงกำหนดเดือนนี้", "dueThisMonthHint": "เดือนปฏิทินนี้"}, "status": {"completed": "เสร็จสิ้น", "needs_review": "ต้องตรวจสอบ", "pending": "รอแยกข้อมูล"}, "stateLabel": {"parsed": "แยกข้อมูลแล้ว", "needs_review": "ต้องตรวจสอบ", "pending": "รอแยกข้อมูล", "active": "ใช้งานอยู่"}, "nodeType": {"prepayment": "เงินล่วงหน้า", "shipment": "เงินก่อนส่ง", "acceptance": "เงินรับมอบ", "warranty": "เงินประกัน"}, "ruleConfirmed": "ยืนยันแล้ว", "prepaymentRule": "แจ้งเตือนวันที่ 7/14/21 หลังจัดเก็บสัญญา; สถานะคำขออ้างอิง OA.", "shipmentRule": "แจ้งเตือนก่อนกำหนดส่ง 7 วัน วันครบกำหนด และหลังครบกำหนด 14 วัน; สถานะคำขออ้างอิง OA.", "acceptanceRule": "แจ้งเตือนวันที่ 30/40/60 หลังจัดเก็บใบรับมอบ; เงินประกันแจ้งก่อนครบกำหนด 7 วัน วันครบกำหนด และหลังครบกำหนด 14 วัน.", "pendingAlerts": "แจ้งเตือนที่รอดำเนินการ", "processing": "เริ่มชำระแล้ว", "dataPending": "รอข้อมูล", "paid": "ชำระแล้ว", "amountRatioDate": "จำนวนเงิน / สัดส่วน · วันที่", "applicant": "ผู้ขอ", "statusLabel": "สถานะ", "contractPrefix": "สัญญา", "datePending": "รอระบุวันที่", "statusNormal": "ปกติ", "statusNeedsCompletion": "ต้องเติมข้อมูล", "statusOverdue": "เกินกำหนดชำระ", "statusUpcoming": "ใกล้ถึงกำหนด", "statusActive": "กำลังดำเนินการ", "statusLine truncated
|
||||
},
|
||||
"contractPaymentReview": {"title": "สัญญาที่รอยืนยัน", "subtitle": "สัญญาที่ไม่ตรงกับกลุ่มหัวข้อคำพ้องของสัญญาจัดซื้ออุปกรณ์ ตรวจสอบสัดส่วนการชำระเงินไม่ผ่าน หรือขัดแย้งกับฟิลด์ OA จะไม่เข้าสู่การแจ้งเตือนการชำระเงิน โปรดดาวน์โหลดต้นฉบับเพื่อตรวจสอบ", "searchPlaceholder": "เลขที่สัญญา ใบสั่งซื้อ หรือผู้ขาย", "loadFailed": "โหลดสัญญาที่รอยืนยันไม่สำเร็จ", "contractWorkflow": "เลขที่สัญญา / เวิร์กโฟลว์", "reason": "เหตุผลที่ต้องยืนยัน", "fallbackIssue": "ผลการแยกข้อมูลต้องยืนยันโดยผู้ใช้", "empty": "ไม่มีสัญญาที่รอยืนยัน"},
|
||||
"contractPaymentReparse": {"action": "แยกข้อมูลจากต้นฉบับอีกครั้ง", "success": "แยกข้อมูลใหม่ด้วยไฟล์แนบ “{attachment}” แล้ว", "failed": "แยกข้อมูลสัญญาใหม่ไม่สำเร็จ"},
|
||||
@@ -4826,7 +4831,9 @@
|
||||
"examTitle": "คลังข้อสอบ",
|
||||
"examDesc": "ดูแลข้อมูลคำถามแบบมีโครงสร้างสำหรับการสอบที่ควบคุม",
|
||||
"reviewTitle": "ทบทวนและรายการตรวจสอบ",
|
||||
"reviewDesc": "กำหนดประเด็นทบทวน รายการก่อนสอบ และคำถามแนะนำในการสนทนา"
|
||||
"reviewDesc": "กำหนดประเด็นทบทวน รายการก่อนสอบ และคำถามแนะนำในการสนทนา",
|
||||
"leanTitle": "ภารกิจ Lean รายสัปดาห์",
|
||||
"leanDesc": "เลือกรายการวิดีโอประจำสัปดาห์ กำหนดจำนวนวิดีโอต่อสัปดาห์ และตั้งเส้นตายของสัปดาห์นั้น"
|
||||
},
|
||||
"guideGroups": {
|
||||
"company": "การฝึกอบรมความปลอดภัยระดับบริษัท",
|
||||
@@ -4853,6 +4860,7 @@
|
||||
"progressItemLabel": "ชื่อรายการความคืบหน้า",
|
||||
"progressHintText": "คำอธิบายความคืบหน้าการฝึกอบรม",
|
||||
"stepIntroText": "ข้อความแนะนำขั้นตอนการฝึกอบรม",
|
||||
"requiredDuration": "เวลาที่ต้องใช้ (นาที)",
|
||||
"summaryPoints": "ประเด็นทบทวน",
|
||||
"summaryChecklist": "รายการก่อนสอบ",
|
||||
"employeeQuestions": "คำถามที่พบบ่อยของพนักงาน",
|
||||
@@ -4881,6 +4889,66 @@
|
||||
"guide": "ทรัพยากรคู่มือ",
|
||||
"document": "เอกสารคลังความรู้"
|
||||
},
|
||||
"directVideo": {
|
||||
"title": "วิดีโอการฝึกอบรม",
|
||||
"hint": "อัปโหลดวิดีโอโดยตรง และวิดีโอจะถูกเพิ่มในทรัพยากรการกำหนดค่านี้โดยอัตโนมัติ",
|
||||
"upload": "อัปโหลดวิดีโอ",
|
||||
"uploading": "กำลังอัปโหลด...",
|
||||
"empty": "ยังไม่มีวิดีโอการฝึกอบรม",
|
||||
"unnamed": "วิดีโอไม่มีชื่อ"
|
||||
},
|
||||
"lean": {
|
||||
"weekKey": "สัปดาห์ภารกิจ (วันจันทร์)",
|
||||
"dueAt": "เวลาครบกำหนด",
|
||||
"weekMustBeMonday": "สัปดาห์ของงานต้องเป็นวันจันทร์",
|
||||
"weeklyCount": "จำนวนวิดีโอต่อสัปดาห์",
|
||||
"weeklyCountHint": "ทุกวันจันทร์ 09:00 ระบบจะส่งวิดีโอชุดถัดไปตามจำนวนนี้ตามลำดับที่เลือก (ส่งแล้ว {pushed}/{total}) ผู้เข้าอบรมเริ่มเรียนได้ทันทีหลังเผยแพร่",
|
||||
"videosTitle": "วิดีโอการฝึกอบรมที่กำหนด",
|
||||
"videosHint": "เลือกแล้ว {count} วิดีโอ (ส่งเป็นชุดรายสัปดาห์ตามลำดับที่เลือก)",
|
||||
"targetsTitle": "กลุ่มผู้เข้ารับการฝึกอบรม",
|
||||
"targetsHint": "เลือกตามบทบาทหรือผู้ใช้ที่ระบุ โดยรวมทั้งสองขอบเขต",
|
||||
"targetRoles": "บทบาทที่ระบุ",
|
||||
"targetUsers": "ผู้ใช้ที่ระบุ",
|
||||
"addTarget": "เพิ่มผู้เข้ารับการฝึกอบรม",
|
||||
"targetEmpty": "ยังไม่ได้เลือกกลุ่มผู้เข้ารับการฝึกอบรม โปรดคลิก \"เพิ่มผู้เข้ารับการฝึกอบรม\" เพื่อกำหนดตามบทบาทหรือพนักงาน",
|
||||
"targetModalTitle": "เพิ่มกลุ่มผู้เข้ารับการฝึกอบรม",
|
||||
"targetSearchPlaceholder": "ค้นหาชื่อ / ชื่อผู้ใช้ / แผนก",
|
||||
"targetSelectedCount": "เลือกแล้ว {roles} บทบาท · {users} พนักงาน",
|
||||
"targetUsersCount": "ผู้ใช้ที่ระบุ ({count})",
|
||||
"targetRolesEmpty": "ไม่มีบทบาทให้เลือก",
|
||||
"targetUsersEmpty": "ไม่พบพนักงานที่ตรงกัน",
|
||||
"removeTarget": "นำออก",
|
||||
"targetConfirm": "ยืนยัน",
|
||||
"noVideoResources": "โปรดบันทึกทรัพยากรวิดีโออย่างน้อยหนึ่งรายการในเอกสารฝึกอบรมก่อน",
|
||||
"summaryRule": "พนักงานต้องดูวิดีโอที่กำหนดและส่งความเห็นการเรียนรู้อย่างน้อย {count} อักขระ",
|
||||
"pushNow": "เพิ่มงานใหม่และส่งเพิ่มทันที",
|
||||
"pushing": "กำลังส่ง…",
|
||||
"weekRangeLabel": "สัปดาห์ที่ {index} {range}",
|
||||
"videoPagePrev": "ก่อนหน้า",
|
||||
"videoPageNext": "ถัดไป",
|
||||
"videoPageInfo": "หน้า {page} / {total}",
|
||||
"pushCompleted": "ส่งวิดีโอครบทุกรายการแล้ว",
|
||||
"pushSuccess": "ส่งวิดีโอ {count} รายการและแจ้งผู้เข้าอบรมแล้ว",
|
||||
"pushFailed": "การส่งวิดีโอล้มเหลว โปรดลองอีกครั้งภายหลัง",
|
||||
"pushLogsTitle": "บันทึกการส่ง",
|
||||
"pushLogsEmpty": "ยังไม่มีบันทึกการส่ง",
|
||||
"pushProgress": "ส่งแล้ว {pushed}/{total} วิดีโอ",
|
||||
"pushBatch": "ส่ง {count} วิดีโอ · สำเร็จ {sent} · ล้มเหลว {failed} · ผู้รับ {recipients} คน",
|
||||
"pushStatus": {
|
||||
"sent": "สำเร็จทั้งหมด",
|
||||
"partial": "ล้มเหลวบางส่วน",
|
||||
"failed": "การส่งล้มเหลว",
|
||||
"completed": "ส่งครบแล้ว"
|
||||
},
|
||||
"pushTrigger": {
|
||||
"publish": "ส่งเมื่อเผยแพร่",
|
||||
"schedule": "ตารางรายสัปดาห์",
|
||||
"manual": "ส่งด้วยตนเอง"
|
||||
},
|
||||
"saveTask": "เผยแพร่ภารกิจรายสัปดาห์",
|
||||
"publishRequired": "โปรดบันทึกและเผยแพร่การกำหนดค่า Lean Management ก่อนสร้างภารกิจรายสัปดาห์",
|
||||
"unnamedVideo": "วิดีโอไม่มีชื่อ"
|
||||
},
|
||||
"messages": {
|
||||
"loadFailed": "โหลดการกำหนดค่าไม่สำเร็จ",
|
||||
"saveFailed": "บันทึกการกำหนดค่าไม่สำเร็จ",
|
||||
@@ -4895,7 +4963,13 @@
|
||||
"parseSuccess": "วิเคราะห์ได้ {count} ข้อ โปรดตรวจสอบก่อนบันทึก",
|
||||
"parseFailed": "วิเคราะห์คลังข้อสอบไม่สำเร็จ",
|
||||
"saved": "บันทึกการกำหนดค่าแล้ว",
|
||||
"deleted": "ลบการกำหนดค่าแล้ว"
|
||||
"deleted": "ลบการกำหนดค่าแล้ว",
|
||||
"leanVideoCount": "โปรดเลือกวิดีโอการฝึกอบรมอย่างน้อยหนึ่งรายการ",
|
||||
"leanTaskSaved": "เผยแพร่ภารกิจ Lean รายสัปดาห์แล้ว",
|
||||
"videoFileRequired": "โปรดเลือกไฟล์วิดีโอ",
|
||||
"trainingAgentRequired": "ไม่พบ Agent การฝึกอบรมพนักงาน จึงไม่สามารถสร้างทรัพยากรวิดีโอได้",
|
||||
"videoUploaded": "อัปโหลดวิดีโอการฝึกอบรมและเพิ่มในทรัพยากรการกำหนดค่าแล้ว",
|
||||
"videoUploadFailed": "อัปโหลดวิดีโอการฝึกอบรมไม่สำเร็จ"
|
||||
}
|
||||
},
|
||||
"integrationConnector": {
|
||||
|
||||
@@ -1014,11 +1014,81 @@
|
||||
"description": "ผู้ดูแลระบบยังไม่ได้เผยแพร่การกำหนดค่าการฝึกอบรมปัจจุบัน"
|
||||
},
|
||||
"unknownDepartment": "ยังไม่ได้ระบุแผนก",
|
||||
"lean": {
|
||||
"learner": {
|
||||
"title": "การอบรมการจัดการแบบลีนประจำสัปดาห์",
|
||||
"taskTitle": "รอบที่ {index}",
|
||||
"description": "รอบนี้ต้องดูวิดีโอที่กำหนด {count} รายการและส่งสรุปการเรียนรู้อย่างน้อย {minSummaryLength} ตัวอักษร",
|
||||
"taskPeriod": "รอบงาน: {start} ถึง {end}",
|
||||
"completedSummary": "สรุปการเรียนรู้",
|
||||
"completedAt": "เสร็จสิ้นเมื่อ: {time}",
|
||||
"empty": "ยังไม่มีงานอบรมลีน"
|
||||
},
|
||||
"taskStatus": {
|
||||
"in_progress": "กำลังดำเนินการ",
|
||||
"overdue": "เกินกำหนด",
|
||||
"completed": "เสร็จสิ้น"
|
||||
},
|
||||
"videoUnavailable": "วิดีโอนี้ยังไม่มีลิงก์สำหรับเล่น",
|
||||
"dueAt": "กำหนดส่ง {time}",
|
||||
"watchedAt": "ดูแล้ว: {time}",
|
||||
"markVideoWatched": "คลิกเพื่อบันทึกว่าดูวิดีโอเสร็จแล้ว",
|
||||
"videoWatchedToast": "ดูวิดีโอครบแล้ว",
|
||||
"videoWatchedBadge": "เสร็จสิ้น",
|
||||
"completeVideosFirst": "กรุณาดูวิดีโอที่กำหนดของรอบนี้ให้ครบก่อนส่งสรุปการเรียนรู้",
|
||||
"summaryTooShort": "สรุปการเรียนรู้ต้องมีอย่างน้อย {minSummaryLength} ตัวอักษร กรุณาเขียนต่อ",
|
||||
"summaryPlaceholder": "กรอกสรุปการเรียนรู้ประจำสัปดาห์ (อย่างน้อย {minSummaryLength} ตัวอักษร)",
|
||||
"summaryLength": "{current}/{minSummaryLength} ตัวอักษร",
|
||||
"submitSummary": "ส่งสรุปการเรียนรู้",
|
||||
"dashboard": {
|
||||
"title": "รายชื่อผลการอบรมลีน",
|
||||
"week": "สัปดาห์อบรม: {week}",
|
||||
"completed": "รายชื่อผู้เสร็จสิ้น",
|
||||
"incomplete": "รายชื่อผู้ยังไม่เสร็จ",
|
||||
"count": "{count} คน",
|
||||
"empty": "ไม่มีข้อมูลบุคลากร",
|
||||
"passRate": "อัตราความสำเร็จ",
|
||||
"periodLabel": "รอบที่ {index}"
|
||||
},
|
||||
"columns": {
|
||||
"employeeId": "รหัสพนักงาน",
|
||||
"name": "ชื่อ",
|
||||
"department": "แผนก",
|
||||
"team": "ทีม",
|
||||
"jobTitle": "ตำแหน่ง",
|
||||
"videoName": "ชื่อวิดีโอ",
|
||||
"watchedAt": "เวลาที่รับชม",
|
||||
"status": "สถานะ",
|
||||
"summary": "สรุป",
|
||||
"action": "การดำเนินการ"
|
||||
},
|
||||
"status": {
|
||||
"completed": "เสร็จสิ้น",
|
||||
"in_progress": "กำลังดำเนินการ",
|
||||
"overdue": "เกินกำหนด",
|
||||
"incomplete": "ยังไม่เสร็จ"
|
||||
},
|
||||
"reminder": {
|
||||
"action": "เตือน",
|
||||
"sending": "กำลังส่ง...",
|
||||
"success": "ส่งการเตือนแล้ว ({count} คน)",
|
||||
"partial": "ส่งการเตือนแล้ว ({sent} คน) แต่ {failed} คนส่งไม่สำเร็จ โปรดตรวจสอบบันทึกการแจ้งเตือน WeCom ในหน้าผู้ดูแลระบบ",
|
||||
"sendFailed": "ส่งการเตือนไม่สำเร็จ ({count} คน) โปรดตรวจสอบการตั้งค่าการแจ้งเตือน WeCom หรือดูบันทึกการแจ้งเตือนในหน้าผู้ดูแลระบบ",
|
||||
"notSent": "ยังไม่ได้ส่งการเตือน: สมาชิกอาจเรียนเสร็จแล้วหรือยังไม่ได้ผูกบัญชี WeCom",
|
||||
"failed": "ส่งการเตือนไม่สำเร็จ โปรดลองอีกครั้งภายหลัง"
|
||||
},
|
||||
"summaryModal": {
|
||||
"title": "รายละเอียดสรุป",
|
||||
"viewHint": "คลิกเพื่อดูสรุปทั้งหมด",
|
||||
"close": "ปิด"
|
||||
}
|
||||
},
|
||||
"video": {
|
||||
"title": "ขั้นตอน 1: ดูวิดีโออบรม",
|
||||
"description": "พนักงานใหม่ต้องดูวิดีโออบรมก่อน แล้วจึงเข้าสู่การทบทวนความรู้และการสอบ",
|
||||
"completeAction": "ฉันดูวิดีโอเสร็จแล้ว",
|
||||
"playerTitle": "ตำแหน่งตัวเล่นวิดีโอ",
|
||||
"empty": "ยังไม่ได้กำหนดวิดีโอการฝึกอบรมที่เล่นได้",
|
||||
"playerHint": "ส่วนนี้สามารถเชื่อมต่อกับลิงก์วิดีโอภายในบริษัทหรือเครื่องเล่นภายในได้ในภายหลัง"
|
||||
},
|
||||
"summary": {
|
||||
@@ -1078,6 +1148,10 @@
|
||||
"rule4": "HR สามารถดูสถิติและส่งออก Excel ได้จากหน้าแชตเดียวกัน"
|
||||
},
|
||||
"hr": {
|
||||
"tabs": {
|
||||
"allTraining": "การอบรมทั้งหมด",
|
||||
"leanManagement": "การจัดการแบบลีน"
|
||||
},
|
||||
"stats": {
|
||||
"total": "จำนวนผู้เข้าอบรม",
|
||||
"passed": "ผ่านแล้ว",
|
||||
|
||||
@@ -129,6 +129,7 @@
|
||||
"AUTH_SSO_ASSERTION_ISSUE_FAILED": "ไม่สามารถออกข้อมูลยืนยันการเข้าสู่ระบบสำหรับบริการในผลิตภัณฑ์ได้ โปรดลองใหม่",
|
||||
"AUTH_FORBIDDEN": "คุณไม่มีสิทธิ์ดำเนินการนี้",
|
||||
"CONTRACT_PAYMENT_FORBIDDEN": "คุณไม่มีสิทธิ์เข้าถึงการแจ้งเตือนการชำระเงินตามสัญญา",
|
||||
"CONTRACT_PAYMENT_ADMIN_REQUIRED": "เฉพาะผู้ดูแลระบบเท่านั้นที่ซิงก์ สแกน หรือส่งการแจ้งเตือนการชำระเงินตามสัญญาได้",
|
||||
"SHIPPING_TASK_SELECTION_INVALID": "เลือกงานจัดส่งได้ 1 ถึง 100 งาน",
|
||||
"SHIPPING_TASK_DELETE_REASON_REQUIRED": "ต้องระบุเหตุผลในการลบหรือยกเลิกงาน",
|
||||
"SHIPPING_TASK_EXTERNAL_VOID_BLOCKED": "งานกำลังอัปโหลดภายนอกหรืออัปโหลดแล้ว จึงทำได้เพียงเก็บถาวร",
|
||||
|
||||
@@ -284,7 +284,7 @@
|
||||
"loading": "กำลังโหลดข้อมูลไฟล์ต้นฉบับ...",
|
||||
"empty": "ยังไม่มีข้อมูลไฟล์ต้นฉบับ อัปโหลดเวอร์ชันเพื่อดูที่นี่",
|
||||
"currentVersion": "เวอร์ชันปัจจุบัน",
|
||||
"opening": "กำลังเปิด...",
|
||||
"opening": "กำลังดาวน์โหลด...",
|
||||
"fileName": "ไฟล์: {name}",
|
||||
"fileSize": "ขนาด: {size}",
|
||||
"fileType": "ประเภท: {ext}"
|
||||
|
||||
@@ -1320,12 +1320,17 @@
|
||||
"username": "用户名",
|
||||
"email": "邮箱",
|
||||
"department": "部门",
|
||||
"team": "班组",
|
||||
"jobTitle": "职务",
|
||||
"isTeamLeader": "班组长",
|
||||
"role": "角色",
|
||||
"featurePermissions": "功能权限",
|
||||
"trainingHrManage": "培训 HR 管理",
|
||||
"trainingHrManageHint": "勾选后可进入员工培训 Agent 的【HR 管理】视图,查看统计、筛选记录并导出 Excel。",
|
||||
"trainingLeanManage": "精益培训全量管理",
|
||||
"trainingLeanTeamManage": "精益培训班组管理",
|
||||
"contractPaymentAccess": "合同付款预警访问",
|
||||
"contractPaymentAccessHint": "勾选后可进入工作台合同付款预警(台账、待确认、周汇总),并触发同步与扫描。",
|
||||
"contractPaymentAccessHint": "勾选后可进入工作台合同付款预警(台账、待确认、周汇总)。同步 OA、扫描预警和发送预警仅管理员可用。",
|
||||
"password": "密码",
|
||||
"passwordHint": "(留空表示不修改)",
|
||||
"noAgents": "暂无可用应用"
|
||||
@@ -4754,7 +4759,7 @@
|
||||
"jobSubmitted": "任务已提交",
|
||||
"actionFailed": "操作失败",
|
||||
"loadFailed": "加载合同失败",
|
||||
"searchPlaceholder": "搜索合同编号或采购单号",
|
||||
"searchPlaceholder": "搜索合同编号、采购单号或供应商",
|
||||
"allStatus": "全部",
|
||||
"search": "查询",
|
||||
"ledger": "合同台账",
|
||||
@@ -4767,6 +4772,7 @@
|
||||
"timeline": "付款计划时间线",
|
||||
"notAvailable": "—",
|
||||
"stats": {"contracts": "合同总数", "pendingParse": "待处理合同", "readyPlans": "计划已生成", "alerts": "待预警节点"},
|
||||
"ledgerFocus": {"due": "即将到期", "dueHint": "7日内", "overdue": "逾期未付", "needsCompletion": "待补充", "dueThisMonth": "本月应付", "dueThisMonthHint": "本自然月"},
|
||||
"status": {"completed": "已完成", "needs_review": "待复核", "pending": "待解析"}, "stateLabel": {"parsed": "已解析", "needs_review": "待复核", "pending": "待解析", "active": "已生效"},
|
||||
"nodeType": {"prepayment": "预付款", "shipment": "出货款", "acceptance": "验收款", "warranty": "质保款"},
|
||||
"ruleConfirmed": "已确定",
|
||||
@@ -4774,7 +4780,7 @@
|
||||
"shipmentRule": "交货期限前 7 天、到期日、到期后 14 天预警;请款以 OA 厂商预付款请款作业为准。",
|
||||
"acceptanceRule": "验收归档后第 30/40/60 天预警;质保款在质保到期前 7 天、到期日、到期后 14 天预警。",
|
||||
"pendingAlerts": "待处理预警", "processing": "已发起付款", "dataPending": "数据待确认", "paid": "已付款", "amountRatioDate": "金额 / 比例 · 日期", "applicant": "申请人", "statusLabel": "状态", "contractPrefix": "合同", "datePending": "待补充日期", "statusNormal": "正常", "statusNeedsCompletion": "待补充", "statusOverdue": "已逾期", "statusUpcoming": "即将到期", "statusActive": "进行中", "statusCompleted": "已完成",
|
||||
"totalPrefix": "共", "contractSupplier": "合同号 / 供应商", "nextAlert": "下一预警", "triggerBasis": "触发依据", "alertDate": "预警日期", "alertFirstRound": "首轮", "payDate": "付款日期", "processStatus": "处理状态", "owner": "采购负责人", "oaData": "OA 数据", "contractRule": "合同规则", "ownerDefault": "采购负责人", "workflowNo": "流程编号", "contractNoPending": "合同号待从附件解析", "synced": "已同步", "detailSubtitle": "OA 数据、付款节点与企业微信提醒记录", "backToOverview": "返回总览", "contractInfo": "OA 合同信息", "alertHistory": "预警记录", "alertRound": "第 {round} 次预警", "alertAudit": "预警发送记录", "alertAuditEmpty": "暂无预警记录", "alertNode": "付款节点", "alertScheduledAt": "计划日期", "alertSentAt": "发送时间", "alertStatus": {"pending": "待发送", "sent": "已发送", "failed": "发送失败"}, "roundValue": "第 {round} 次", "weeklyBatchesTitle": "周汇总批次", "weeklyBatchesSubtitle": "查看按收件人生成的付款预警周汇总、Excel 附件及发送记录。", "refresh": "刷新", "weeklySend": "发送预警", "weeklyBatchSubmitted": "发送预警任务已提交", "weeklyBatchesLoadFailed": "加载周汇总批次失败", "batchNo": "批次号", "weekKey": "周次", "batchStatusLabel": "发送状态", "batchTotal": "汇总笔数", "batchExcel": "Excel 附件", "batchSentAt": "发送时间", "weeklyBatchesEmpty": "暂无周汇总批次", "weeklyPendingSummary": "本周待发送 {count} 笔 · 下次发送 {datetime}", "weeklyPendingCountOnly": "本周待发送 {count} 笔", "downloadExcel": "下载 Excel", "excelDownloadFailed": "下载预警附件失败", "batchStatus": {"pending": "待发送", "sent": "已发送", "failed": "发送失败", "processing": "处理中", "resolved": "已停止提醒"}, "backToLedger": "返回", "detailLoadFailed": "加载合同详情失败", "detailLoading": "正在加载合同详情…", "detailOverview": "合同概览", "detailAttachments": "原文附件", "detailPaymentPlan": "付款计划", "detailAlertHistory": "预警记录", "archiveDate": "合同归档日期", "archiveDateHint": "该日期为合同申请单的归档日期", "parseStatus": "解析状态", "parseIssueTitle": "解析提示", "planStatus": "计划状态", "attachmentsEmpty": "暂无已归档的合同原文附件", "downloadAttachment": "下载附件", "attachmentDownloadFailed": "下载合同附件失败", "paymentPlanEmpty": "暂无可展示的付款计划", "anchorDate": "日期依据", "nodeStatus": {"pending": "待处理", "active": "进行中", "paid": "已付", "processing": "处理中", "resolved": "已停止提醒", "upcoming": "即将到期", "notStarted": "待起算", "overdue": "已逾期", "review": "待复核"}, "reparse": "重新解析合同原文", "reparseSuccess": "已使用附件“{attachment}”重新解析", "reparseFailed": "重新解析合同失败", "reviewTitle": "待确认合同", "reviewSubtitle": "未匹配设备采购合同同义标题组、付款比例校验失败或关键字段冲突的合同不会进入付款预警,请下载原文核对。", "reviewSearchPlaceholder": "合同编号、采购编号或供应商", "reviewLoadFailed": "待确认合同加载失败", "reviewContractWorkflow": "合同号 / 流程编号", "reviewReason": "待确认原因", "reviewFallbackIssue": "解析结果待人工确认", "reviewEmpty": "暂无待确认合同"
|
||||
"totalPrefix": "共", "contractSupplier": "合同号 / 供应商", "nextAlert": "下一预警", "triggerBasis": "触发依据", "alertDate": "预警日期", "alertFirstRound": "首轮", "payDate": "付款日期", "processStatus": "处理状态", "owner": "采购负责人", "oaData": "OA 数据", "contractRule": "合同规则", "ownerDefault": "采购负责人", "workflowNo": "流程编号", "contractNoPending": "合同号待从附件解析", "synced": "已同步", "detailSubtitle": "OA 数据、付款节点与企业微信提醒记录", "backToOverview": "返回总览", "contractInfo": "OA 合同信息", "alertHistory": "预警记录", "alertRound": "第 {round} 次预警", "alertAudit": "预警发送记录", "alertAuditEmpty": "暂无预警记录", "alertNode": "付款节点", "alertScheduledAt": "计划日期", "alertSentAt": "发送时间", "alertStatus": {"pending": "待发送", "sent": "已发送", "failed": "发送失败"}, "roundValue": "第 {round} 次", "weeklyBatchesTitle": "周汇总批次", "weeklyBatchesSubtitle": "查看按收件人生成的付款预警周汇总、Excel 附件及发送记录。", "weeklySend": "发送预警", "weeklyBatchSubmitted": "发送预警任务已提交", "weeklyBatchesLoadFailed": "加载周汇总批次失败", "batchNo": "批次号", "weekKey": "周次", "batchStatusLabel": "发送状态", "batchTotal": "汇总笔数", "batchExcel": "Excel 附件", "batchSentAt": "发送时间", "weeklyBatchesEmpty": "暂无周汇总批次", "weeklyPendingSummary": "本周待发送 {count} 笔 · 下次发送 {datetime}", "weeklyPendingCountOnly": "本周待发送 {count} 笔", "downloadExcel": "下载 Excel", "excelDownloadFailed": "下载预警附件失败", "batchStatus": {"pending": "待发送", "sent": "已发送", "failed": "发送失败", "processing": "处理中", "resolved": "已停止提醒"}, "backToLedger": "返回", "detailLoadFailed": "加载合同详情失败", "detailLoading": "正在加载合同详情…", "detailOverview": "合同概览", "detailAttachments": "原文附件", "detailPaymentPlan": "付款计划", "detailAlertHistory": "预警记录", "archiveDate": "合同归档日期", "archiveDateHint": "该日期为合同申请单的归档日期", "parseStatus": "解析状态", "parseIssueTitle": "解析提示", "planStatus": "计划状态", "attachmentsEmpty": "暂无已归档的合同原文附件", "downloadAttachment": "下载附件", "attachmentDownloadFailed": "下载合同附件失败", "paymentPlanEmpty": "暂无可展示的付款计划", "anchorDate": "日期依据", "nodeStatus": {"pending": "待处理", "active": "进行中", "paid": "已付", "processing": "处理中", "resolved": "已停止提醒", "upcoming": "即将到期", "notStarted": "待起算", "overdue": "已逾期", "review": "待复核"}, "reparse": "重新解析合同原文", "reparseSuccess": "已使用附件“{attachment}”重新解析", "reparseFailed": "重新解析合同失败", "reviewTitle": "待确认合同", "reviewSubtitle": "未匹配设备采购合同同义标题组、付款比例校验失败或关键字段冲突的合同不会进入付款预警,请下载原文核对。", "reviewSearchPlaceholder": "合同编号、采购编号或供应商", "reviewLoadFailed": "待确认合同加载失败", "reviewContractWorkflow": "合同号 / 流程编号", "reviewReason": "待确认原因", "reviewFallbackIssue": "解析结果待人工确认", "reviewEmpty": "暂无待确认合同"
|
||||
},
|
||||
"contractPaymentReview": {"title": "待确认合同", "subtitle": "未匹配设备采购合同同义标题组、付款比例校验失败或关键字段冲突的合同不会进入付款预警,请下载原文核对。", "searchPlaceholder": "合同编号、采购编号或供应商", "loadFailed": "待确认合同加载失败", "contractWorkflow": "合同号 / 流程编号", "reason": "待确认原因", "fallbackIssue": "解析结果待人工确认", "empty": "暂无待确认合同"},
|
||||
"contractPaymentReparse": {"action": "重新解析合同原文", "success": "已使用附件“{attachment}”重新解析", "failed": "重新解析合同失败"},
|
||||
@@ -4982,7 +4988,9 @@
|
||||
"examTitle": "考试题库",
|
||||
"examDesc": "维护受控考试使用的结构化题目数据",
|
||||
"reviewTitle": "复盘与清单",
|
||||
"reviewDesc": "配置培训完成后的复盘重点、考前清单与聊天引导问题"
|
||||
"reviewDesc": "配置培训完成后的复盘重点、考前清单与聊天引导问题",
|
||||
"leanTitle": "精益周任务",
|
||||
"leanDesc": "为指定自然周选择视频列表、设置每周推送数量并配置周截止时间"
|
||||
},
|
||||
"guideGroups": {
|
||||
"company": "公司级安全培训",
|
||||
@@ -5009,6 +5017,7 @@
|
||||
"progressItemLabel": "进度项名称",
|
||||
"progressHintText": "培训进度说明",
|
||||
"stepIntroText": "培训步骤引导文案",
|
||||
"requiredDuration": "所需时间(分钟)",
|
||||
"summaryPoints": "复盘要点",
|
||||
"summaryChecklist": "考前清单",
|
||||
"employeeQuestions": "员工常见问题",
|
||||
@@ -5037,6 +5046,66 @@
|
||||
"guide": "指南资源",
|
||||
"document": "知识库文档"
|
||||
},
|
||||
"directVideo": {
|
||||
"title": "培训视频",
|
||||
"hint": "可直接上传视频,上传后自动加入当前培训配置资源。",
|
||||
"upload": "上传视频",
|
||||
"uploading": "上传中...",
|
||||
"empty": "暂未上传培训视频",
|
||||
"unnamed": "未命名视频"
|
||||
},
|
||||
"lean": {
|
||||
"weekKey": "任务周(周一)",
|
||||
"dueAt": "截止时间",
|
||||
"weekMustBeMonday": "任务周必须选择周一",
|
||||
"weeklyCount": "每周任务数量",
|
||||
"weeklyCountHint": "每周一 09:00 按该数量从视频列表顺序推送下一批(已推送 {pushed}/{total}),受训员工发布后立即可学",
|
||||
"videosTitle": "指定培训视频",
|
||||
"videosHint": "已选择 {count} 个视频(按选择顺序每周分批推送)",
|
||||
"targetsTitle": "受训对象",
|
||||
"targetsHint": "按角色或指定用户选择,两个范围取并集",
|
||||
"targetRoles": "指定角色",
|
||||
"targetUsers": "指定用户",
|
||||
"addTarget": "添加受训",
|
||||
"targetEmpty": "尚未选择受训对象,请点击\"添加受训\"按角色或员工配置",
|
||||
"targetModalTitle": "添加受训对象",
|
||||
"targetSearchPlaceholder": "搜索姓名 / 用户名 / 部门",
|
||||
"targetSelectedCount": "已选 {roles} 个角色 · {users} 名员工",
|
||||
"targetUsersCount": "指定用户({count})",
|
||||
"targetRolesEmpty": "暂无可选角色",
|
||||
"targetUsersEmpty": "未找到匹配员工",
|
||||
"removeTarget": "移除",
|
||||
"targetConfirm": "确认添加",
|
||||
"noVideoResources": "请先在培训资料中保存至少一个视频资源",
|
||||
"summaryRule": "员工需完成指定视频观看并提交不少于 {count} 字的学习感悟",
|
||||
"pushNow": "立即新增任务补推",
|
||||
"pushing": "推送中…",
|
||||
"weekRangeLabel": "第{index}周 {range}",
|
||||
"videoPagePrev": "上一页",
|
||||
"videoPageNext": "下一页",
|
||||
"videoPageInfo": "第 {page} / {total} 页",
|
||||
"pushCompleted": "全部视频已推送完毕",
|
||||
"pushSuccess": "已推送 {count} 个视频并通知受训员工",
|
||||
"pushFailed": "视频推送失败,请稍后重试",
|
||||
"pushLogsTitle": "推送记录",
|
||||
"pushLogsEmpty": "暂无推送记录",
|
||||
"pushProgress": "已推送 {pushed}/{total} 个视频",
|
||||
"pushBatch": "推送 {count} 个视频 · 发送 {sent} · 失败 {failed} · 接收 {recipients} 人",
|
||||
"pushStatus": {
|
||||
"sent": "全部成功",
|
||||
"partial": "部分失败",
|
||||
"failed": "推送失败",
|
||||
"completed": "已全部推送"
|
||||
},
|
||||
"pushTrigger": {
|
||||
"publish": "发布推送",
|
||||
"schedule": "每周排程",
|
||||
"manual": "手动推送"
|
||||
},
|
||||
"saveTask": "发布周任务",
|
||||
"publishRequired": "请先保存并发布精益管理培训配置,再创建周任务",
|
||||
"unnamedVideo": "未命名视频"
|
||||
},
|
||||
"messages": {
|
||||
"loadFailed": "加载培训配置失败",
|
||||
"saveFailed": "保存培训配置失败",
|
||||
@@ -5051,7 +5120,13 @@
|
||||
"parseSuccess": "已解析 {count} 道题目,请复核后保存",
|
||||
"parseFailed": "题库解析失败",
|
||||
"saved": "培训配置已保存",
|
||||
"deleted": "培训配置已删除"
|
||||
"deleted": "培训配置已删除",
|
||||
"leanVideoCount": "请至少选择一个培训视频",
|
||||
"leanTaskSaved": "精益周任务已发布",
|
||||
"videoFileRequired": "请选择视频文件",
|
||||
"trainingAgentRequired": "未找到员工培训 Agent,无法创建视频资源",
|
||||
"videoUploaded": "培训视频已上传并加入配置资源",
|
||||
"videoUploadFailed": "培训视频上传失败"
|
||||
}
|
||||
},
|
||||
"integrationConnector": {
|
||||
|
||||
@@ -1048,11 +1048,81 @@
|
||||
"description": "管理员尚未发布当前培训配置,请稍后再试。"
|
||||
},
|
||||
"unknownDepartment": "待补充部门",
|
||||
"lean": {
|
||||
"learner": {
|
||||
"title": "精益管理周度培训",
|
||||
"taskTitle": "第 {index} 期",
|
||||
"description": "本期需完成 {count} 个指定视频,并提交不少于 {minSummaryLength} 字的学习感悟。",
|
||||
"taskPeriod": "任务周期:{start} 至 {end}",
|
||||
"completedSummary": "学习感悟",
|
||||
"completedAt": "完成时间:{time}",
|
||||
"empty": "暂无精益培训任务"
|
||||
},
|
||||
"taskStatus": {
|
||||
"in_progress": "进行中",
|
||||
"overdue": "已延期",
|
||||
"completed": "已完成"
|
||||
},
|
||||
"videoUnavailable": "该视频暂无可播放地址",
|
||||
"dueAt": "截止 {time}",
|
||||
"watchedAt": "已观看:{time}",
|
||||
"markVideoWatched": "点击记录观看完成",
|
||||
"videoWatchedToast": "视频观看完成",
|
||||
"videoWatchedBadge": "已完成",
|
||||
"completeVideosFirst": "请先完整观看本期全部任务视频,再提交学习感悟",
|
||||
"summaryTooShort": "学习感悟不少于 {minSummaryLength} 字,请继续补充",
|
||||
"summaryPlaceholder": "请填写本周学习感悟(不少于 {minSummaryLength} 字)",
|
||||
"summaryLength": "{current}/{minSummaryLength} 字",
|
||||
"submitSummary": "提交学习感悟",
|
||||
"dashboard": {
|
||||
"title": "精益培训完成名单",
|
||||
"week": "培训周次:{week}",
|
||||
"completed": "已完成名单",
|
||||
"incomplete": "未完成名单",
|
||||
"count": "共 {count} 人",
|
||||
"empty": "暂无人员数据",
|
||||
"passRate": "完成率",
|
||||
"periodLabel": "第 {index} 期"
|
||||
},
|
||||
"columns": {
|
||||
"employeeId": "工号",
|
||||
"name": "姓名",
|
||||
"department": "部门",
|
||||
"team": "班组",
|
||||
"jobTitle": "职务",
|
||||
"videoName": "视频名称",
|
||||
"watchedAt": "观看时间",
|
||||
"status": "状态",
|
||||
"summary": "总结",
|
||||
"action": "操作"
|
||||
},
|
||||
"status": {
|
||||
"completed": "已完成",
|
||||
"in_progress": "进行中",
|
||||
"overdue": "已延期",
|
||||
"incomplete": "未完成"
|
||||
},
|
||||
"reminder": {
|
||||
"action": "提醒",
|
||||
"sending": "发送中...",
|
||||
"success": "已发送提醒({count} 人)",
|
||||
"partial": "已发送提醒({sent} 人),{failed} 人发送失败,请在管理端企微通知审计中查看原因",
|
||||
"sendFailed": "提醒发送失败({count} 人),请检查企业微信通知配置,或在管理端企微通知审计中查看原因",
|
||||
"notSent": "未发送提醒:对方可能已完成培训或未绑定企业微信",
|
||||
"failed": "提醒发送失败,请稍后重试"
|
||||
},
|
||||
"summaryModal": {
|
||||
"title": "总结详情",
|
||||
"viewHint": "点击查看全部总结",
|
||||
"close": "关闭"
|
||||
}
|
||||
},
|
||||
"video": {
|
||||
"title": "第一步:观看培训视频",
|
||||
"description": "员工先完成入职培训视频学习,再进入知识点复盘和考试环节。",
|
||||
"completeAction": "我已完成视频学习",
|
||||
"playerTitle": "视频播放位",
|
||||
"empty": "暂未配置可播放的培训视频",
|
||||
"playerHint": "这里可接入企业视频链接或内部播放器。当前前端已预留完整容器与学习完成按钮。"
|
||||
},
|
||||
"summary": {
|
||||
@@ -1181,6 +1251,10 @@
|
||||
}
|
||||
},
|
||||
"hr": {
|
||||
"tabs": {
|
||||
"allTraining": "全部培训",
|
||||
"leanManagement": "精益管理"
|
||||
},
|
||||
"stats": {
|
||||
"total": "参训人数",
|
||||
"passed": "已通过",
|
||||
|
||||
@@ -129,6 +129,7 @@
|
||||
"AUTH_SSO_ASSERTION_ISSUE_FAILED": "平级服务登录声明签发失败,请重试。",
|
||||
"AUTH_FORBIDDEN": "你没有权限执行该操作。",
|
||||
"CONTRACT_PAYMENT_FORBIDDEN": "你没有合同付款预警的访问权限。",
|
||||
"CONTRACT_PAYMENT_ADMIN_REQUIRED": "仅管理员可执行合同付款预警的同步、扫描或发送操作。",
|
||||
"SHIPPING_TASK_SELECTION_INVALID": "请选择 1 到 100 个发货任务。",
|
||||
"SHIPPING_TASK_DELETE_REASON_REQUIRED": "删除或作废任务必须填写原因。",
|
||||
"SHIPPING_TASK_EXTERNAL_VOID_BLOCKED": "任务正在外部上传或已上传,只能归档,不能作废或删除。",
|
||||
|
||||
@@ -284,7 +284,7 @@
|
||||
"loading": "正在加载源文件信息...",
|
||||
"empty": "暂无源文件信息,上传版本后会显示在这里。",
|
||||
"currentVersion": "当前版本",
|
||||
"opening": "正在打开...",
|
||||
"opening": "正在下载...",
|
||||
"fileName": "文件名:{name}",
|
||||
"fileSize": "大小:{size}",
|
||||
"fileType": "类型:{ext}"
|
||||
|
||||
@@ -1191,12 +1191,17 @@
|
||||
"username": "用戶名",
|
||||
"email": "郵箱",
|
||||
"department": "部門",
|
||||
"team": "班組",
|
||||
"jobTitle": "職務",
|
||||
"isTeamLeader": "班組長",
|
||||
"role": "角色",
|
||||
"featurePermissions": "功能權限",
|
||||
"trainingHrManage": "培訓 HR 管理",
|
||||
"trainingHrManageHint": "勾選後可進入員工培訓 Agent 的【HR 管理】視圖,查看統計、篩選記錄並匯出 Excel。",
|
||||
"trainingLeanManage": "精益培訓全量管理",
|
||||
"trainingLeanTeamManage": "精益培訓班組管理",
|
||||
"contractPaymentAccess": "合約付款預警存取",
|
||||
"contractPaymentAccessHint": "勾選後可進入工作臺合約付款預警(臺帳、待確認、週彙總),並觸發同步與掃描。",
|
||||
"contractPaymentAccessHint": "勾選後可進入工作臺合約付款預警(臺帳、待確認、週彙總)。同步 OA、掃描預警與發送預警僅管理員可用。",
|
||||
"password": "密碼",
|
||||
"passwordHint": "(留空表示不修改)",
|
||||
"noAgents": "暫無可用應用"
|
||||
@@ -4632,7 +4637,7 @@
|
||||
}
|
||||
},
|
||||
"contractPayment": {
|
||||
"title": "合約付款預警", "subtitle": "同步 OA 合約、驗收和廠商預付款請款作業,按三輪規則通知採購職位", "sync": "同步 OA 資料", "forceSync": "強制覆蓋 OA 欄位", "forceSyncConfirm": "將以本次 OA 回傳的非空欄位覆蓋既有 OA 資料,並記錄變更稽核。是否繼續?", "reparseExisting": "批量重新解析既有合約", "reparseExistingConfirm": "將使用已歸檔的合約附件依目前規則更新所有既有合約的解析結果,不會同步或覆蓋 OA 欄位。是否繼續?", "scanAlerts": "掃描產生預警", "jobSubmitted": "工作已提交", "actionFailed": "操作失敗", "loadFailed": "載入合約失敗", "searchPlaceholder": "搜尋合約編號或採購單號", "allStatus": "全部", "search": "查詢", "ledger": "合約台帳", "items": "筆", "empty": "暫無合約資料", "purchaseOrder": "採購單號", "supplier": "供應商", "amount": "合約金額", "deliveryDate": "交貨期限", "timeline": "付款計畫時間線", "notAvailable": "—", "stats": {"contracts": "合約總數", "pendingParse": "待處理合約", "readyPlans": "計畫已產生", "alerts": "待預警節點"}, "status": {"completed": "已完成", "needs_review": "待覆核", "pending": "待解析"}, "stateLabel": {"parsed": "已解析", "needs_review": "待複核", "pending": "待解析", "active": "已生效"}, "nodeType": {"prepayment": "預付款", "shipment": "出貨款", "acceptance": "驗收款", "warranty": "質保款"}, "ruleConfirmed": "已確定", "prepaymentRule": "合約歸檔後第 7/14/21 天預警;請款以 OA 廠商預付款請款作業為準。", "shipmentRule": "交貨期限前 7 天、到期日、到期後 14 天預警;請款以 OA 廠商預付款請款作業為準。", "acceptanceRule": "驗收歸檔後第 30/40/60 天預警;質保款在質保到期前 7 天、到期日、到期後 14 天預警。", "pendingAlerts": "待處理預警", "processing": "已發起付款", "dataPending": "資料待確認", "paid": "已付款", "amountRatioDate": "金額 / 比例 · 日期", "applicant": "申請人", "statusLabel": "狀態", "contractPrefix": "合約", "datePending": "待補充日期", "statusNormal": "正常", "statusNeedsCompletion": "待補充", "statusOverdue": "已逾期", "statusUpcoming": "即將到期", "statusActive": "進行中", "statusCompleted": "已完成", "totalPrefix": "共", "contractSupplier": "合約號 / 供應商", "nextAlert": "下一預警", "triggerBasis": "觸發依據", "alertDate": "預警日期", "alertFirstRound": "首輪", "payDate": "付款日期", "processStatus": "處理狀態", "owner": "採購負責人", "oaData": "OA 資料", "contractRule": "合約規則", "ownerDefault": "採購負責人", "workflowNo": "流程編號", "contractNoPending": "合約號待從附件解析", "synced": "已同步", "detailSubtitle": "OA 資料、付款節點與企業微信提醒記錄", "backToOverview": "返回總覽", "contractInfo": "OA 合約資訊", "alertHistory": "預警記錄", "alertRound": "第 {round} 次預警", "alertAudit": "預警發送記錄", "alertAuditEmpty": "暫無預警記錄", "alertNode": "付款節點", "alertScheduledAt": "計畫日期", "alertSentAt": "發送時間", "alertStatus": {"pending": "待發送", "sent": "已發送", "failed": "發送失敗"}, "roundValue": "第 {round} 次", "weeklyBatchesTitle": "週彙總批次", "weeklyBatchesSubtitle": "查看依收件人產生的付款預警週彙總、Excel 附件與發送記錄。", "refresh": "重新整理", "weeklySend": "傳送預警", "weeklyBatchSubmitted": "發送預警任務已提交", "weeklyBatchesLoadFailed": "載入週彙總批次失敗", "batchNo": "批次號", "weekKey": "週次", "batchStatusLabel": "發送狀態", "batchTotal": "彙總筆數", "batchExcel": "Excel 附件", "batchSentAt": "發送時間", "weeklyBatchesEmpty": "暫無週彙總批次", "weeklyPendingSummary": "本週待發送 {count} 筆 · 下次發送 {datetime}", "weeklyPendingCountOnly": "本週待發送 {count} 筆", "downloadExcel": "下載 Excel", "excelDownloadFailed": "下載預警附件失敗", "batchStatus": {"pending": "待發送", "sent": "已發送", "failed": "發送失敗", "processing": "處理中", "resolved": "已停止提醒"}, "backToLedger": "返回", "detailLoadFailed": "載入合約詳情失敗", "detailLoading": "正在載入合約詳情…", "detailOverview": "合約概覽", "detailAttachments": "原文附件", "detailPaymentPlan": "付款計畫", "detailAlertHistory": "預警記錄", "archiveDate": "合約歸檔日期", "archiveDateHint": "該日期為合約申請單的歸檔日期", "parseStatus": "解析狀態", "parseIssueTitle": "解析提示", "planStatus": "計畫狀態", "attachmentsEmpty": "暫無已歸檔的合約原文附件", "downloadAttachment": "下載附件", "attachmentDownloadFailed": "下載合約附件失敗", "paymentPlanEmpty": "暫無可展示的付款計畫", "anchorDate": "日期依據", "nodeStatus": {"pending":Line truncated
|
||||
"title": "合約付款預警", "subtitle": "同步 OA 合約、驗收和廠商預付款請款作業,按三輪規則通知採購職位", "sync": "同步 OA 資料", "forceSync": "強制覆蓋 OA 欄位", "forceSyncConfirm": "將以本次 OA 回傳的非空欄位覆蓋既有 OA 資料,並記錄變更稽核。是否繼續?", "reparseExisting": "批量重新解析既有合約", "reparseExistingConfirm": "將使用已歸檔的合約附件依目前規則更新所有既有合約的解析結果,不會同步或覆蓋 OA 欄位。是否繼續?", "scanAlerts": "掃描產生預警", "jobSubmitted": "工作已提交", "actionFailed": "操作失敗", "loadFailed": "載入合約失敗", "searchPlaceholder": "搜尋合約編號、採購單號或供應商", "allStatus": "全部", "search": "查詢", "ledger": "合約台帳", "items": "筆", "empty": "暫無合約資料", "purchaseOrder": "採購單號", "supplier": "供應商", "amount": "合約金額", "deliveryDate": "交貨期限", "timeline": "付款計畫時間線", "notAvailable": "—", "stats": {"contracts": "合約總數", "pendingParse": "待處理合約", "readyPlans": "計畫已產生", "alerts": "待預警節點"}, "ledgerFocus": {"due": "即將到期", "dueHint": "7日內", "overdue": "逾期未付", "needsCompletion": "待補充", "dueThisMonth": "本月應付", "dueThisMonthHint": "本自然月"}, "status": {"completed": "已完成", "needs_review": "待覆核", "pending": "待解析"}, "stateLabel": {"parsed": "已解析", "needs_review": "待複核", "pending": "待解析", "active": "已生效"}, "nodeType": {"prepayment": "預付款", "shipment": "出貨款", "acceptance": "驗收款", "warranty": "質保款"}, "ruleConfirmed": "已確定", "prepaymentRule": "合約歸檔後第 7/14/21 天預警;請款以 OA 廠商預付款請款作業為準。", "shipmentRule": "交貨期限前 7 天、到期日、到期後 14 天預警;請款以 OA 廠商預付款請款作業為準。", "acceptanceRule": "驗收歸檔後第 30/40/60 天預警;質保款在質保到期前 7 天、到期日、到期後 14 天預警。", "pendingAlerts": "待處理預警", "processing": "已發起付款", "dataPending": "資料待確認", "paid": "已付款", "amountRatioDate": "金額 / 比例 · 日期", "applicant": "申請人", "statusLabel": "狀態", "contractPrefix": "合約", "datePending": "待補充日期", "statusNormal": "正常", "statusNeedsCompletion": "待補充", "statusOverdue": "已逾期", "statusUpcoming": "即將到期", "statusActive": "進行中", "statusCompleted": "已完成", "totalPrefix": "共", "contractSupplier": "合約號 / 供應商", "nextAlert": "下一預警", "triggerBasis": "觸發依據", "alertDate": "預警日期", "alertFirstRound": "首輪", "payDate": "付款日期", "processStatus": "處理狀態", "owner": "採購負責人", "oaData": "OA 資料", "contractRule": "合約規則", "ownerDefault": "採購負責人", "workflowNo": "流程編號", "contractNoPending": "合約號待從附件解析", "synced": "已同步", "detailSubtitle": "OA 資料、付款節點與企業微信提醒記錄", "backToOverview": "返回總覽", "contractInfo": "OA 合約資訊", "alertHistory": "預警記錄", "alertRound": "第 {round} 次預警", "alertAudit": "預警發送記錄", "alertAuditEmpty": "暫無預警記錄", "alertNode": "付款節點", "alertScheduledAt": "計畫日期", "alertSentAt": "發送時間", "alertStatus": {"pending": "待發送", "sent": "已發送", "failed": "發送失敗"}, "roundValue": "第 {round} 次", "weeklyBatchesTitle": "週彙總批次", "weeklyBatchesSubtitle": "查看依收件人產生的付款預警週彙總、Excel 附件與發送記錄。", "weeklySend": "傳送預警", "weeklyBatchSubmitted": "發送預警任務已提交", "weeklyBatchesLoadFailed": "載入週彙總批次失敗", "batchNo": "批次號", "weekKey": "週次", "batchStatusLabel": "發送狀態", "batchTotal": "彙總筆數", "batchExcel": "Excel 附件", "batchSentAt": "發送時間", "weeklyBatchesEmpty": "暫無週彙總批次", "weeklyPendingSummary": "本週待發送 {count} 筆 · 下次發送 {datetime}", "weeklyPendingCountOnly": "本週待發送 {count} 筆", "downloadExcel": "下載 Excel", "excelDownloadFailed": "下載預警附件失敗", "batchStatus": {"pending": "待發送", "sent": "已發送", "failed": "發送失敗", "processing": "處理中", "resolved": "已停止提醒"}, "backToLedger": "返回", "detailLoadFailed": "載入合約詳情失敗", "detailLoading": "正在載入合約詳情…", "detailOverview": "合約概覽", "detailAttachments": "原文附件", "detailPaymentPlan": "付款計畫", "detailAlertHistory": "預警記錄", "archiveDate": "合約歸檔日期", "archiveDateHint": "該日期為合約申請單的歸檔日期", "parseStatus": "解析狀態", "parseIssueTitle": "解析提示", "planStatus": "計畫狀態", "attachmentsEmpty": "暫無已歸檔的合約原文附件", "downloadAttachment": "下載Line truncated
|
||||
},
|
||||
"contractPaymentReview": {"title": "待確認合約", "subtitle": "未符合設備採購合約同義標題組、付款比例驗證失敗或關鍵欄位衝突的合約,不會進入付款預警,請下載原文核對。", "searchPlaceholder": "合約編號、採購單號或供應商", "loadFailed": "待確認合約載入失敗", "contractWorkflow": "合約號 / 流程編號", "reason": "待確認原因", "fallbackIssue": "解析結果待人工確認", "empty": "暫無待確認合約"},
|
||||
"contractPaymentReparse": {"action": "重新解析合約原文", "success": "已使用附件“{attachment}”重新解析", "failed": "重新解析合約失敗"},
|
||||
@@ -4831,7 +4836,9 @@
|
||||
"examTitle": "考試題庫",
|
||||
"examDesc": "維護受控考試使用的結構化題目資料",
|
||||
"reviewTitle": "複盤與清單",
|
||||
"reviewDesc": "配置培訓完成後的複盤重點、考前清單與聊天引導問題"
|
||||
"reviewDesc": "配置培訓完成後的複盤重點、考前清單與聊天引導問題",
|
||||
"leanTitle": "精益每週任務",
|
||||
"leanDesc": "為指定自然週選擇影片清單、設定每週推送數量並配置週截止時間"
|
||||
},
|
||||
"guideGroups": {
|
||||
"company": "公司級安全培訓",
|
||||
@@ -4858,6 +4865,7 @@
|
||||
"progressItemLabel": "進度項名稱",
|
||||
"progressHintText": "培訓進度說明",
|
||||
"stepIntroText": "培訓步驟引導文案",
|
||||
"requiredDuration": "所需時間(分鐘)",
|
||||
"summaryPoints": "複盤要點",
|
||||
"summaryChecklist": "考前清單",
|
||||
"employeeQuestions": "員工常見問題",
|
||||
@@ -4886,6 +4894,66 @@
|
||||
"guide": "指南資源",
|
||||
"document": "知識庫文件"
|
||||
},
|
||||
"directVideo": {
|
||||
"title": "培訓影片",
|
||||
"hint": "可直接上傳影片;上傳後會自動加入目前培訓配置資源。",
|
||||
"upload": "上傳影片",
|
||||
"uploading": "上傳中...",
|
||||
"empty": "尚未上傳培訓影片",
|
||||
"unnamed": "未命名影片"
|
||||
},
|
||||
"lean": {
|
||||
"weekKey": "任務週(週一)",
|
||||
"dueAt": "截止時間",
|
||||
"weekMustBeMonday": "任務週必須選擇週一",
|
||||
"weeklyCount": "每週任務數量",
|
||||
"weeklyCountHint": "每週一 09:00 按該數量從影片清單順序推送下一批(已推送 {pushed}/{total}),受訓員工發布後立即可學",
|
||||
"videosTitle": "指定培訓影片",
|
||||
"videosHint": "已選擇 {count} 部影片(按選擇順序每週分批推送)",
|
||||
"targetsTitle": "受訓對象",
|
||||
"targetsHint": "依角色或指定使用者選擇,兩個範圍取聯集",
|
||||
"targetRoles": "指定角色",
|
||||
"targetUsers": "指定使用者",
|
||||
"addTarget": "新增受訓",
|
||||
"targetEmpty": "尚未選擇受訓對象,請點擊「新增受訓」按角色或員工配置",
|
||||
"targetModalTitle": "新增受訓對象",
|
||||
"targetSearchPlaceholder": "搜尋姓名 / 使用者名稱 / 部門",
|
||||
"targetSelectedCount": "已選 {roles} 個角色 · {users} 位員工",
|
||||
"targetUsersCount": "指定使用者({count})",
|
||||
"targetRolesEmpty": "暫無可選角色",
|
||||
"targetUsersEmpty": "未找到符合的員工",
|
||||
"removeTarget": "移除",
|
||||
"targetConfirm": "確認新增",
|
||||
"noVideoResources": "請先在培訓資料中儲存至少一部影片資源",
|
||||
"summaryRule": "員工須完成指定影片觀看並提交不少於 {count} 字的學習感悟",
|
||||
"pushNow": "立即新增任務補推",
|
||||
"pushing": "推送中…",
|
||||
"weekRangeLabel": "第{index}週 {range}",
|
||||
"videoPagePrev": "上一頁",
|
||||
"videoPageNext": "下一頁",
|
||||
"videoPageInfo": "第 {page} / {total} 頁",
|
||||
"pushCompleted": "全部影片已推送完畢",
|
||||
"pushSuccess": "已推送 {count} 部影片並通知受訓員工",
|
||||
"pushFailed": "影片推送失敗,請稍後重試",
|
||||
"pushLogsTitle": "推送記錄",
|
||||
"pushLogsEmpty": "暫無推送記錄",
|
||||
"pushProgress": "已推送 {pushed}/{total} 部影片",
|
||||
"pushBatch": "推送 {count} 部影片 · 發送 {sent} · 失敗 {failed} · 接收 {recipients} 人",
|
||||
"pushStatus": {
|
||||
"sent": "全部成功",
|
||||
"partial": "部分失敗",
|
||||
"failed": "推送失敗",
|
||||
"completed": "已全部推送"
|
||||
},
|
||||
"pushTrigger": {
|
||||
"publish": "發布推送",
|
||||
"schedule": "每週排程",
|
||||
"manual": "手動推送"
|
||||
},
|
||||
"saveTask": "發佈每週任務",
|
||||
"publishRequired": "請先儲存並發佈精益管理培訓配置,再建立每週任務",
|
||||
"unnamedVideo": "未命名影片"
|
||||
},
|
||||
"messages": {
|
||||
"loadFailed": "載入培訓配置失敗",
|
||||
"saveFailed": "儲存培訓配置失敗",
|
||||
@@ -4900,7 +4968,13 @@
|
||||
"parseSuccess": "已解析 {count} 道題目,請複核後儲存",
|
||||
"parseFailed": "題庫解析失敗",
|
||||
"saved": "培訓配置已儲存",
|
||||
"deleted": "培訓配置已刪除"
|
||||
"deleted": "培訓配置已刪除",
|
||||
"leanVideoCount": "請至少選擇一部培訓影片",
|
||||
"leanTaskSaved": "精益每週任務已發佈",
|
||||
"videoFileRequired": "請選擇影片檔案",
|
||||
"trainingAgentRequired": "未找到員工培訓 Agent,無法建立影片資源",
|
||||
"videoUploaded": "培訓影片已上傳並加入配置資源",
|
||||
"videoUploadFailed": "培訓影片上傳失敗"
|
||||
}
|
||||
},
|
||||
"integrationConnector": {
|
||||
|
||||
@@ -1014,11 +1014,81 @@
|
||||
"description": "管理員尚未發布當前培訓配置,請稍後再試。"
|
||||
},
|
||||
"unknownDepartment": "待補充部門",
|
||||
"lean": {
|
||||
"learner": {
|
||||
"title": "精益管理週度培訓",
|
||||
"taskTitle": "第 {index} 期",
|
||||
"description": "本期需完成 {count} 個指定影片,並提交不少於 {minSummaryLength} 字的學習心得。",
|
||||
"taskPeriod": "任務週期:{start} 至 {end}",
|
||||
"completedSummary": "學習心得",
|
||||
"completedAt": "完成時間:{time}",
|
||||
"empty": "暫無精益培訓任務"
|
||||
},
|
||||
"taskStatus": {
|
||||
"in_progress": "進行中",
|
||||
"overdue": "已延期",
|
||||
"completed": "已完成"
|
||||
},
|
||||
"videoUnavailable": "該影片暫無可播放地址",
|
||||
"dueAt": "截止 {time}",
|
||||
"watchedAt": "已觀看:{time}",
|
||||
"markVideoWatched": "點擊記錄完成觀看",
|
||||
"videoWatchedToast": "影片觀看完成",
|
||||
"videoWatchedBadge": "已完成",
|
||||
"completeVideosFirst": "請先完整觀看本期全部任務影片,再提交學習心得",
|
||||
"summaryTooShort": "學習心得不少於 {minSummaryLength} 字,請繼續補充",
|
||||
"summaryPlaceholder": "請填寫本週學習心得(不少於 {minSummaryLength} 字)",
|
||||
"summaryLength": "{current}/{minSummaryLength} 字",
|
||||
"submitSummary": "提交學習心得",
|
||||
"dashboard": {
|
||||
"title": "精益培訓完成名單",
|
||||
"week": "培訓週次:{week}",
|
||||
"completed": "已完成名單",
|
||||
"incomplete": "未完成名單",
|
||||
"count": "共 {count} 人",
|
||||
"empty": "暫無人員資料",
|
||||
"passRate": "完成率",
|
||||
"periodLabel": "第 {index} 期"
|
||||
},
|
||||
"columns": {
|
||||
"employeeId": "工號",
|
||||
"name": "姓名",
|
||||
"department": "部門",
|
||||
"team": "班組",
|
||||
"jobTitle": "職務",
|
||||
"videoName": "影片名稱",
|
||||
"watchedAt": "觀看時間",
|
||||
"status": "狀態",
|
||||
"summary": "總結",
|
||||
"action": "操作"
|
||||
},
|
||||
"status": {
|
||||
"completed": "已完成",
|
||||
"in_progress": "進行中",
|
||||
"overdue": "已延期",
|
||||
"incomplete": "未完成"
|
||||
},
|
||||
"reminder": {
|
||||
"action": "提醒",
|
||||
"sending": "發送中...",
|
||||
"success": "已發送提醒({count} 人)",
|
||||
"partial": "已發送提醒({sent} 人),{failed} 人發送失敗,請在管理端企微通知審計中查看原因",
|
||||
"sendFailed": "提醒發送失敗({count} 人),請檢查企業微信通知配置,或在管理端企微通知審計中查看原因",
|
||||
"notSent": "未發送提醒:對方可能已完成培訓或未綁定企業微信",
|
||||
"failed": "提醒發送失敗,請稍後重試"
|
||||
},
|
||||
"summaryModal": {
|
||||
"title": "總結詳情",
|
||||
"viewHint": "點擊查看全部總結",
|
||||
"close": "關閉"
|
||||
}
|
||||
},
|
||||
"video": {
|
||||
"title": "第一步:觀看培訓影片",
|
||||
"description": "員工先完成入職培訓影片學習,再進入知識點複盤與考試環節。",
|
||||
"completeAction": "我已完成影片學習",
|
||||
"playerTitle": "影片播放區",
|
||||
"empty": "尚未配置可播放的培訓影片",
|
||||
"playerHint": "此處可接入企業影片連結或內部播放器。當前前端已預留完整容器與完成按鈕。"
|
||||
},
|
||||
"summary": {
|
||||
@@ -1078,6 +1148,10 @@
|
||||
"rule4": "HR 管理端可在同一聊天頁查看統計並匯出 Excel。"
|
||||
},
|
||||
"hr": {
|
||||
"tabs": {
|
||||
"allTraining": "全部培訓",
|
||||
"leanManagement": "精益管理"
|
||||
},
|
||||
"stats": {
|
||||
"total": "參訓人數",
|
||||
"passed": "已通過",
|
||||
|
||||
@@ -129,6 +129,7 @@
|
||||
"AUTH_SSO_ASSERTION_ISSUE_FAILED": "平級服務登入聲明簽發失敗,請重試。",
|
||||
"AUTH_FORBIDDEN": "你沒有權限執行此操作。",
|
||||
"CONTRACT_PAYMENT_FORBIDDEN": "你沒有合約付款預警的存取權限。",
|
||||
"CONTRACT_PAYMENT_ADMIN_REQUIRED": "僅管理員可執行合約付款預警的同步、掃描或發送操作。",
|
||||
"SHIPPING_TASK_SELECTION_INVALID": "請選擇 1 到 100 個發貨任務。",
|
||||
"SHIPPING_TASK_DELETE_REASON_REQUIRED": "刪除或作廢任務必須填寫原因。",
|
||||
"SHIPPING_TASK_EXTERNAL_VOID_BLOCKED": "任務正在外部上傳或已上傳,只能歸檔,不能作廢或刪除。",
|
||||
|
||||
@@ -284,7 +284,7 @@
|
||||
"loading": "正在載入源文件信息...",
|
||||
"empty": "暫無源文件信息,上傳版本後會顯示在這裡。",
|
||||
"currentVersion": "當前版本",
|
||||
"opening": "正在打開...",
|
||||
"opening": "正在下載...",
|
||||
"fileName": "文件名:{name}",
|
||||
"fileSize": "大小:{size}",
|
||||
"fileType": "類型:{ext}"
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
/**
|
||||
* shared/api/client.ts
|
||||
* 跨域 HTTP 客户端:envelope 解析、BusinessError、requestJson、requestBlob。
|
||||
* 依赖:auth、vue-i18n、shared/utils/download(Content-Disposition 文件名)。
|
||||
* 所有 feature API 层应通过此模块发起请求;二进制下载走 requestBlob,失败仍为 BusinessError。
|
||||
*/
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { parseContentDispositionFilename } from '@/shared/utils/download';
|
||||
import i18n from '@/i18n';
|
||||
|
||||
export interface ApiSuccessEnvelope<T> {
|
||||
@@ -217,11 +219,9 @@ export async function requestBlob(url: string, init?: RequestInit): Promise<Blob
|
||||
}
|
||||
|
||||
const blob = await res.blob();
|
||||
const disposition = res.headers.get('Content-Disposition') || '';
|
||||
const filename = disposition.match(/filename\*?=(?:UTF-8''|")?([^";]+)"?/i)?.[1];
|
||||
return {
|
||||
blob,
|
||||
filename: filename ? decodeURIComponent(filename) : undefined,
|
||||
filename: parseContentDispositionFilename(res.headers.get('Content-Disposition')),
|
||||
requestId: requestIdHeader,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* shared/utils/download.test.ts
|
||||
* 用途:校验 Content-Disposition 解析与单次 blob 下载不会拼出怪名。
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
parseContentDispositionFilename,
|
||||
sanitizeDownloadFilename,
|
||||
triggerBlobDownload,
|
||||
} from './download';
|
||||
|
||||
describe('parseContentDispositionFilename', () => {
|
||||
it('prefers RFC 5987 filename* over ASCII fallback', () => {
|
||||
// 断言:Werkzeug/Flask 中文名会留下 ASCII 回退段,必须取 filename*。
|
||||
const encoded = encodeURIComponent('企业文化.docx');
|
||||
const disposition = `attachment; filename="download.docx"; filename*=UTF-8''${encoded}`;
|
||||
expect(parseContentDispositionFilename(disposition)).toBe('企业文化.docx');
|
||||
});
|
||||
|
||||
it('does not concatenate unquoted ASCII fallback with filename*', () => {
|
||||
// 断言:旧实现会得到 `docx; filename_=UTF-8''企业文化.docx`。
|
||||
const encoded = encodeURIComponent('企业文化.docx');
|
||||
const disposition = `inline; filename=docx; filename*=UTF-8''${encoded}`;
|
||||
expect(parseContentDispositionFilename(disposition)).toBe('企业文化.docx');
|
||||
});
|
||||
|
||||
it('reads quoted filename when filename* is absent', () => {
|
||||
expect(parseContentDispositionFilename('attachment; filename="report.pdf"')).toBe('report.pdf');
|
||||
});
|
||||
|
||||
it('returns undefined for empty header', () => {
|
||||
expect(parseContentDispositionFilename('')).toBeUndefined();
|
||||
expect(parseContentDispositionFilename(null)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizeDownloadFilename', () => {
|
||||
it('keeps only the last path segment', () => {
|
||||
expect(sanitizeDownloadFilename('dir/企业文化.docx')).toBe('企业文化.docx');
|
||||
});
|
||||
});
|
||||
|
||||
describe('triggerBlobDownload', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('clicks a single anchor with the original filename', () => {
|
||||
// 断言:一次下载只产生一个 a[download],文件名与源文件一致。
|
||||
const clicks: string[] = [];
|
||||
const createObjectURL = vi.fn(() => 'blob:http://localhost/fake');
|
||||
const revokeObjectURL = vi.fn();
|
||||
vi.stubGlobal('URL', { createObjectURL, revokeObjectURL });
|
||||
|
||||
const originalCreateElement = document.createElement.bind(document);
|
||||
vi.spyOn(document, 'createElement').mockImplementation((tagName: string) => {
|
||||
const el = originalCreateElement(tagName);
|
||||
if (tagName === 'a') {
|
||||
vi.spyOn(el, 'click').mockImplementation(() => {
|
||||
clicks.push(el.download);
|
||||
});
|
||||
}
|
||||
return el;
|
||||
});
|
||||
|
||||
triggerBlobDownload(new Blob(['hello']), '企业文化.docx');
|
||||
|
||||
expect(createObjectURL).toHaveBeenCalledTimes(1);
|
||||
expect(clicks).toEqual(['企业文化.docx']);
|
||||
expect(document.body.querySelectorAll('a')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* shared/utils/download.ts
|
||||
* 用途:浏览器受控下载的文件名解析与单次触发,避免 blob URL 被 window.open 再下一份。
|
||||
* 依赖:无业务模块;仅使用 DOM URL / a[download]。
|
||||
* 逻辑:requestBlob、知识库源文件等调用;Content-Disposition 优先 RFC 5987 filename*。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 去掉路径与非法换行,得到可写入 a[download] 的纯文件名。
|
||||
* 核心逻辑:只保留最后一段路径分量,避免把目录或响应头片段写进保存名。
|
||||
* @param filename - 原始或解析得到的文件名
|
||||
* @param fallback - 清洗后为空时的回退名
|
||||
* @returns 可安全用作下载名的字符串
|
||||
*/
|
||||
export function sanitizeDownloadFilename(filename: string, fallback = 'download'): string {
|
||||
const name = String(filename || '').replace(/\\/g, '/').split('/').pop()?.trim() || '';
|
||||
const cleaned = name.replace(/[\r\n"]/g, '');
|
||||
return cleaned || fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Content-Disposition 解析下载文件名,优先 RFC 5987 的 filename*。
|
||||
* 核心逻辑:先取 filename*=UTF-8'',再取带引号或到分号为止的 filename=。
|
||||
* 不能用贪婪的 filename="?([^"]+)"?,否则会把 `filename=docx; filename*=UTF-8''原名.docx` 整段当成文件名。
|
||||
* @param disposition - 响应头原文
|
||||
* @returns 解码后的文件名;无法解析时返回 undefined
|
||||
*/
|
||||
export function parseContentDispositionFilename(
|
||||
disposition: string | null | undefined,
|
||||
): string | undefined {
|
||||
const value = String(disposition || '');
|
||||
if (!value) return undefined;
|
||||
|
||||
const utf8Match = value.match(/filename\*\s*=\s*UTF-8''([^;]+)/i);
|
||||
const quotedMatch = value.match(/filename\s*=\s*"([^"]+)"/i);
|
||||
const unquotedMatch = value.match(/filename\s*=\s*([^;]+)/i);
|
||||
const raw = (utf8Match?.[1] || quotedMatch?.[1] || unquotedMatch?.[1] || '').trim();
|
||||
if (!raw) return undefined;
|
||||
|
||||
let decoded = raw;
|
||||
try {
|
||||
decoded = decodeURIComponent(raw);
|
||||
} catch {
|
||||
decoded = raw;
|
||||
}
|
||||
const name = sanitizeDownloadFilename(decoded, '');
|
||||
return name || undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用 blob 触发一次浏览器下载,保存名使用给定文件名。
|
||||
* 核心逻辑:只创建一条 a[download] 并 click;禁止 window.open blob URL,
|
||||
* 因为 docx 等无法预览的类型会再下一份 UUID 名文件,且 noopener 使 open 返回 null 导致双下载。
|
||||
* @param blob - 文件内容
|
||||
* @param filename - 保存文件名,应与源文件名一致
|
||||
*/
|
||||
export function triggerBlobDownload(blob: Blob, filename: string): void {
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = objectUrl;
|
||||
link.download = sanitizeDownloadFilename(filename);
|
||||
link.rel = 'noopener';
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
window.setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
|
||||
}
|
||||
Reference in new issue
Block a user