Merge branch 'dev911' into test
This commit is contained in:
commit
e13838cbb8
71 files changed
+4706
-177
No files matched your search
@@ -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}]
|
||||
Reference in new issue
Block a user