feat(training): 新增精益培训视频与周任务管理
This commit is contained in:
1 parent
e5ede471fd
commit
a69814c409
32 files changed
+1619
-55
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
|
||||
|
||||
@@ -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, 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,16 @@ 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 (
|
||||
create_or_update_weekly_task,
|
||||
get_current_weekly_task,
|
||||
list_dashboard,
|
||||
save_completion,
|
||||
)
|
||||
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 +60,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。"""
|
||||
@@ -86,6 +105,19 @@ def save_my_training_record():
|
||||
return jsonify(serialize_training_record(record))
|
||||
|
||||
|
||||
@training_user_bp.route("/lean-training/current-task", methods=["GET"])
|
||||
def get_my_lean_training_task():
|
||||
"""返回当前精益周任务,供员工端展示本周两个指定视频与总结门槛。"""
|
||||
return ok(get_current_weekly_task(_require_user()))
|
||||
|
||||
|
||||
@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 +180,39 @@ 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"])
|
||||
return ok(task, status=201)
|
||||
|
||||
|
||||
@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))
|
||||
@@ -530,7 +530,7 @@ class Config:
|
||||
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
|
||||
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset,contract_payment_warning')
|
||||
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')
|
||||
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')
|
||||
|
||||
@@ -192,7 +192,14 @@ from app.models.shipping_inventory_preparation import (
|
||||
ShippingInventoryPreparationSourceAttempt,
|
||||
)
|
||||
from app.models.shipping_inventory_mapping import ShippingInventoryMapping
|
||||
from app.models.training import TrainingRecord, TrainingConfig, TrainingConfigResource
|
||||
from app.models.training import (
|
||||
LeanTrainingCompletion,
|
||||
LeanTrainingReminder,
|
||||
LeanTrainingWeeklyTask,
|
||||
TrainingConfig,
|
||||
TrainingConfigResource,
|
||||
TrainingRecord,
|
||||
)
|
||||
from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig
|
||||
from app.models.voucher_check import VoucherCheckInvoiceState, VoucherCheckRunItem
|
||||
from app.models.contract_payment import (
|
||||
|
||||
@@ -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,78 @@ 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。
|
||||
逻辑:配置页创建或更新任务;员工提交观看与总结时关联本表;提醒服务只扫描已发布周任务。
|
||||
"""
|
||||
|
||||
__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)
|
||||
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])
|
||||
|
||||
|
||||
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)
|
||||
@@ -0,0 +1,180 @@
|
||||
"""
|
||||
backend/app/services/lean_training_reminder_service.py
|
||||
|
||||
用途:执行精益管理周度培训的企微提醒生成与发送。
|
||||
依赖:精益培训任务/完成/提醒模型、User、wecom_notify。
|
||||
逻辑:排程按周日截止、周一/周三/周五催学规则写入幂等提醒,再由统一企微服务发送并落审计。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
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"
|
||||
result = send_wecom_event_message(
|
||||
event_type=event_type,
|
||||
user=recipient,
|
||||
title=title,
|
||||
content=content,
|
||||
jump_path="/workspace",
|
||||
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="targeted",
|
||||
event_type="training_lean_targeted_reminder",
|
||||
title="精益管理培训定向提醒",
|
||||
content="您尚未完成本周精益管理培训,请观看两个指定视频并提交不少于50字的学习感悟。",
|
||||
current=current,
|
||||
)
|
||||
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,30 @@
|
||||
"""
|
||||
backend/app/services/lean_training_schedule_seed.py
|
||||
|
||||
用途:幂等创建精益培训逾期提醒的默认排程。
|
||||
依赖: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 精益培训提醒扫描任务。"""
|
||||
owner = db.session.query(User).filter(User.role == "admin").order_by(User.id.asc()).first()
|
||||
if not owner or db.session.query(ScheduleTask).filter_by(schedule_no="SCH-LEAN-TRAINING-REMINDER").first():
|
||||
return []
|
||||
now = datetime.utcnow()
|
||||
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)
|
||||
if commit:
|
||||
db.session.commit()
|
||||
else:
|
||||
db.session.flush()
|
||||
return [task]
|
||||
@@ -0,0 +1,237 @@
|
||||
"""
|
||||
backend/app/services/lean_training_service.py
|
||||
|
||||
用途:精益管理培训的周任务、员工提交、看板和提醒规则服务。
|
||||
依赖:TrainingConfig/Resource、精益培训模型、User、统一 ValidationError。
|
||||
逻辑:管理端冻结每周两个视频;员工提交观看事实与学习感悟;服务端按 50 字门槛判定完成,管理看板只读取已授权范围。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, time
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import 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.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 _normalize_video_ids(value: Any, config: TrainingConfig) -> list[int]:
|
||||
"""校验周任务必须绑定当前精益配置下恰好两个视频资源。"""
|
||||
if not isinstance(value, list) or len(value) != 2 or len({str(item) for item in value}) != 2:
|
||||
raise ValidationError("Exactly two lean training videos are required", details={"field": "video_resource_ids"})
|
||||
resource_map = {
|
||||
resource.id: 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")
|
||||
}
|
||||
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) -> dict[str, Any]:
|
||||
"""序列化精益周任务,返回视频标题和完成规则供管理端与员工端使用。"""
|
||||
resources = db.session.execute(
|
||||
select(TrainingConfigResource).where(TrainingConfigResource.id.in_(task.video_resource_ids or []))
|
||||
).scalars().all()
|
||||
titles = {resource.id: resource.title or (resource.agent_guide.file_name if resource.agent_guide else "") for resource in resources}
|
||||
return {
|
||||
"id": task.id,
|
||||
"week_key": task.week_key,
|
||||
"due_at": task.due_at.isoformat(),
|
||||
"video_resource_ids": list(task.video_resource_ids or []),
|
||||
"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, "")} for resource_id in task.video_resource_ids or []],
|
||||
"status": task.status,
|
||||
"min_summary_length": MIN_SUMMARY_LENGTH,
|
||||
}
|
||||
|
||||
|
||||
def create_or_update_weekly_task(data: dict[str, Any], user_id: int) -> dict[str, Any]:
|
||||
"""创建或更新指定周的两个视频任务,并由 HR 按角色或用户冻结受训对象。"""
|
||||
config = _get_lean_config()
|
||||
week_key = str(data.get("week_key") or "").strip()
|
||||
try:
|
||||
week_start = date.fromisoformat(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"})
|
||||
try:
|
||||
due_at = to_utc_naive(datetime.fromisoformat(str(data.get("due_at") or "").replace("Z", "+00:00")))
|
||||
except ValueError as exc:
|
||||
raise ValidationError("due_at is invalid", details={"field": "due_at"}) from exc
|
||||
shanghai_tz = resolve_schedule_tzinfo("Asia/Shanghai")
|
||||
minimum_due_at = to_utc_naive(datetime.combine(week_start, time.min, shanghai_tz))
|
||||
if due_at < minimum_due_at:
|
||||
raise ValidationError("due_at must not precede week_key", details={"field": "due_at"})
|
||||
if due_at < utc_now_naive() and not bool(data.get("allow_historical")):
|
||||
raise ValidationError("due_at must be in the future", details={"field": "due_at"})
|
||||
existing = db.session.execute(select(LeanTrainingWeeklyTask).where(LeanTrainingWeeklyTask.week_key == week_key)).scalar_one_or_none()
|
||||
video_ids = _normalize_video_ids(data.get("video_resource_ids"), config) if not existing else list(existing.video_resource_ids or [])
|
||||
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"})
|
||||
task = existing or LeanTrainingWeeklyTask(config_id=config.id, week_key=week_key, created_by_id=user_id)
|
||||
task.due_at = due_at
|
||||
task.video_resource_ids = video_ids
|
||||
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_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) if task else None
|
||||
|
||||
|
||||
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")
|
||||
watched = data.get("watched_at")
|
||||
if not isinstance(watched, dict) or not all(str(resource_id) in watched and watched[str(resource_id)] for resource_id in task.video_resource_ids):
|
||||
raise ValidationError("Both required 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 = 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)
|
||||
completion.watched_at_json = {str(key): str(value) for key, value in watched.items()}
|
||||
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 serialize_completion(completion: LeanTrainingCompletion, task: LeanTrainingWeeklyTask, user: User) -> dict[str, Any]:
|
||||
"""组合看板所需人员、视频观看、总结和完成状态字段。"""
|
||||
return {
|
||||
"id": completion.id,
|
||||
"user_id": user.id,
|
||||
"employee_id": user.employee_id,
|
||||
"name": user.real_name or user.username,
|
||||
"department": user.department,
|
||||
"videos": [
|
||||
{"name": next((resource.title or (resource.agent_guide.file_name if resource.agent_guide else "") for resource in task.config.resources if resource.id == resource_id), ""), "watched_at": (completion.watched_at_json or {}).get(str(resource_id))}
|
||||
for resource_id in task.video_resource_ids
|
||||
],
|
||||
"summary_text": completion.summary_text,
|
||||
"status": completion.status,
|
||||
"completed_at": completion.completed_at.isoformat() if completion.completed_at else None,
|
||||
}
|
||||
|
||||
|
||||
def list_dashboard(task_id: int | None) -> dict[str, Any]:
|
||||
"""返回 HR 可查看的精益看板,仅统计当前周任务已冻结的受训对象。"""
|
||||
task = db.session.get(LeanTrainingWeeklyTask, task_id) if task_id else db.session.execute(select(LeanTrainingWeeklyTask).order_by(LeanTrainingWeeklyTask.week_key.desc())).scalars().first()
|
||||
if not task:
|
||||
return {"task": None, "completed": [], "incomplete": []}
|
||||
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": [], "summary_text": None, "status": "incomplete", "completed_at": None}
|
||||
(completed if row["status"] == "completed" else incomplete).append(row)
|
||||
return {"task": serialize_weekly_task(task), "completed": completed, "incomplete": incomplete}
|
||||
@@ -150,11 +150,16 @@ 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
|
||||
|
||||
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="contract-payment-alert-scan", label="合同付款预警扫描", handler=run_contract_payment_alert_schedule,
|
||||
description="每日扫描四阶段付款节点,只生成待发送预警记录。", category="contract_payment",
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
"""
|
||||
backend/app/services/schedule/lean_training_job.py
|
||||
|
||||
用途:将精益培训逾期提醒接入平台排程契约。
|
||||
依赖:ScheduleTask/ScheduleRun、lean_training_reminder_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.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}]
|
||||
@@ -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")
|
||||
Reference in new issue
Block a user