unis_hrms/app/api/v1/dashboard.py

261 lines
13 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""工作台 / 数据看板:HR 总览、趋势、招聘与薪资摘要、最近动态."""
from __future__ import annotations
from datetime import date, timedelta
from typing import Annotated, Any
from fastapi import APIRouter, Depends, Query
from sqlalchemy import func, or_, select
from ...core.constants import RENEW_WINDOW_DAYS
from ...core.deps import (
AuthContext,
AuthCtx,
Session,
apply_employee_scope,
ensure,
require_perm,
)
from ...models.benefits import BenefitRecord, Enrollment, LeaveRequest
from ...models.employee import Employee, EmployeeChange, EmployeeContract
from ...models.org import Department
from ...models.payroll import PayrollBatch, Payslip
from ...models.rbac import Announcement, Notification, OperationLog
from ...models.recruitment import Application, Candidate, Interview, JobPosting, Offer
from ...models.selfservice import ProfileRequest, TaskReminder
from ..helpers import label_map
router = APIRouter(prefix="/dashboard", tags=["工作台"])
ACTIVE = ("probation", "active", "leave")
def _month_keys(count: int = 12) -> list[str]:
today = date.today()
keys = []
year, month = today.year, today.month
for _ in range(count):
keys.append(f"{year}-{month:02d}")
month -= 1
if month == 0:
month, year = 12, year - 1
return list(reversed(keys))
@router.get("/overview", summary="HR 工作台总览")
async def overview(session: Session,
auth: Annotated[AuthContext, Depends(require_perm("employee:employee:read"))]):
today = date.today()
month_start = today.replace(day=1)
employees = list((await session.execute(
await apply_employee_scope(session, select(Employee), auth, Employee.id))).scalars().all())
active = [e for e in employees if e.status in ACTIVE]
depts = await label_map(session, Department)
hired_month = [e for e in active if e.hire_date and e.hire_date >= month_start]
leaving_month = [e for e in employees if e.leave_date and e.leave_date >= month_start]
probation_due = [e for e in active if e.status == "probation" and e.regular_date
and e.regular_date <= today + timedelta(days=30)]
week_end = today + timedelta(days=7)
birthdays = [e for e in active if e.birthday and
((e.birthday.month, e.birthday.day) >= (today.month, today.day)) and
((e.birthday.month, e.birthday.day) <= (week_end.month, week_end.day))]
async def pending(model):
return int((await session.execute(
select(func.count()).select_from(model).where(model.status == "pending"))).scalar() or 0)
expiring = list((await session.execute(
select(EmployeeContract).where(EmployeeContract.status == "active",
EmployeeContract.end_date.is_not(None),
EmployeeContract.end_date <= today + timedelta(days=RENEW_WINDOW_DAYS))
.order_by(EmployeeContract.end_date))).scalars().all())
dept_counts: dict[str, int] = {}
for e in active:
key = depts.get(e.department_id, "未分配")
dept_counts[key] = dept_counts.get(key, 0) + 1
gender: dict[str, int] = {}
for e in active:
gender[e.gender or "未知"] = gender.get(e.gender or "未知", 0) + 1
latest_batch = (await session.execute(
select(PayrollBatch).order_by(PayrollBatch.year.desc(), PayrollBatch.month.desc())
)).scalars().first()
open_jobs = int((await session.execute(
select(func.count()).select_from(JobPosting).where(JobPosting.status == "open"))).scalar() or 0)
active_apps = int((await session.execute(
select(func.count()).select_from(Application).where(Application.stage != "rejected")
)).scalar() or 0)
return {
"cards": [
{"key": "headcount", "label": "在职人数", "value": len(active), "unit": "人",
"trend": f"本月入职 +{len(hired_month)}", "color": "#2f6bff", "icon": "TeamOutlined",
"link": "/employees"},
{"key": "probation", "label": "试用期", "value": sum(1 for e in active if e.status == "probation"),
"unit": "人", "trend": f"30 天内转正 {len(probation_due)} 人", "color": "#13c2c2",
"icon": "ExperimentOutlined", "link": "/employees?status=probation"},
{"key": "recruiting", "label": "在招职位", "value": open_jobs, "unit": "个",
"trend": f"流程中候选人 {active_apps} 人", "color": "#722ed1",
"icon": "UserSwitchOutlined", "link": "/recruitment/pipeline"},
{"key": "payroll", "label": "最近计薪", "value": float(latest_batch.net_total or 0)
if latest_batch else 0, "unit": "元", "money": True,
"trend": (f"{latest_batch.year}-{latest_batch.month:02d} · {latest_batch.employee_count} 人"
if latest_batch else "尚未生成工资表"), "color": "#fa8c16",
"icon": "PayCircleOutlined", "link": "/payroll/batches"},
],
"todos": [
{"key": "leave", "label": "请假待审批", "count": await pending(LeaveRequest),
"link": "/benefits/leaves", "color": "#2f6bff"},
{"key": "profile", "label": "信息变更待审核", "count": await pending(ProfileRequest),
"link": "/employees/changes", "color": "#13c2c2"},
{"key": "change", "label": "异动待审批", "count": await pending(EmployeeChange),
"link": "/employees/changes", "color": "#722ed1"},
{"key": "contract", "label": f"合同 {RENEW_WINDOW_DAYS} 天内到期", "count": len(expiring),
"link": "/employees/contracts", "color": "#fa8c16"},
],
"distribution": {
"department": [{"name": k, "value": v} for k, v in
sorted(dept_counts.items(), key=lambda kv: -kv[1])[:10]],
"gender": [{"name": k, "value": v} for k, v in gender.items()],
},
"attention": {
"probation_due": [{"employee_id": e.id, "name": e.name, "work_no": e.work_no,
"regular_date": e.regular_date,
"department_name": depts.get(e.department_id)} for e in probation_due[:8]],
"contracts": [{"contract_id": c.id, "employee_id": c.employee_id,
"end_date": c.end_date, "days_left": (c.end_date - today).days,
"contract_no": c.contract_no} for c in expiring[:8]],
"birthdays": [{"employee_id": e.id, "name": e.name, "birthday": e.birthday,
"department_name": depts.get(e.department_id)} for e in birthdays[:8]],
},
"summary": {"total_records": len(employees), "hired_this_month": len(hired_month),
"leaving_this_month": len(leaving_month), "resigned": sum(
1 for e in employees if e.status == "resigned")},
}
@router.get("/trends", summary="人员趋势")
async def trends(
session: Session,
auth: Annotated[AuthContext, Depends(require_perm("employee:employee:read"))],
months: int = Query(12, ge=3, le=36),
):
employees = list((await session.execute(
await apply_employee_scope(session, select(Employee), auth, Employee.id))).scalars().all())
keys = _month_keys(months)
hired = {k: 0 for k in keys}
left = {k: 0 for k in keys}
for e in employees:
if e.hire_date:
key = f"{e.hire_date.year}-{e.hire_date.month:02d}"
if key in hired:
hired[key] += 1
if e.leave_date:
key = f"{e.leave_date.year}-{e.leave_date.month:02d}"
if key in left:
left[key] += 1
headcount = []
running = sum(1 for e in employees if e.status in ACTIVE) - sum(hired.values()) + sum(left.values())
for key in keys:
running += hired[key] - left[key]
headcount.append({"period": key, "count": max(0, running)})
return {"periods": keys, "hired": [{"period": k, "count": v} for k, v in hired.items()],
"resigned": [{"period": k, "count": v} for k, v in left.items()],
"headcount": headcount}
@router.get("/recruitment", summary="招聘摘要")
async def recruitment_summary(session: Session,
auth: Annotated[AuthContext, Depends(require_perm("recruitment:report:read"))]):
jobs = list((await session.execute(select(JobPosting))).scalars().all())
apps = list((await session.execute(select(Application))).scalars().all())
candidates = list((await session.execute(select(Candidate))).scalars().all())
offers = list((await session.execute(select(Offer))).scalars().all())
interviews = list((await session.execute(select(Interview))).scalars().all())
today = date.today()
upcoming = [{"interview_id": i.id, "scheduled_at": i.scheduled_at, "round": i.round,
"interview_type": i.interview_type, "application_id": i.application_id}
for i in interviews if i.status == "scheduled" and i.scheduled_at
and i.scheduled_at.date() <= today + timedelta(days=7)]
by_stage: dict[str, int] = {}
for a in apps:
by_stage[a.stage] = by_stage.get(a.stage, 0) + 1
source: dict[str, int] = {}
for c in candidates:
source[c.source or "其他"] = source.get(c.source or "其他", 0) + 1
return {
"jobs_total": len(jobs), "jobs_open": sum(1 for j in jobs if j.status == "open"),
"candidates": len(candidates), "applications": len(apps),
"offers_pending": sum(1 for o in offers if o.status in ("draft", "pending")),
"hired": sum(1 for a in apps if a.stage == "hired"),
"by_stage": [{"stage": k, "count": v} for k, v in by_stage.items()],
"by_source": [{"source": k, "count": v} for k, v in sorted(source.items(), key=lambda kv: -kv[1])],
"upcoming_interviews": sorted(upcoming, key=lambda r: r["scheduled_at"])[:8],
"headcount_gap": sum(max(0, (j.headcount or 0) - (j.hired_count or 0)) for j in jobs
if j.status == "open"),
}
@router.get("/payroll", summary="人力成本摘要")
async def payroll_summary(
session: Session,
auth: Annotated[AuthContext, Depends(require_perm("payroll:report:read"))],
months: int = Query(6, ge=2, le=24),
):
batches = list((await session.execute(
select(PayrollBatch).order_by(PayrollBatch.year.desc(), PayrollBatch.month.desc())
.limit(months))).scalars().all())
depts = await label_map(session, Department)
slips = list((await session.execute(
select(Payslip).where(Payslip.year == date.today().year))).scalars().all())
emp_map = {e.id: e for e in (await session.execute(
select(Employee).where(Employee.id.in_({s.employee_id for s in slips} or [-1])))).scalars().all()}
dept_cost: dict[str, float] = {}
for s in slips:
emp = emp_map.get(s.employee_id)
key = depts.get(emp.department_id, "未分配") if emp else "未分配"
dept_cost[key] = round(dept_cost.get(key, 0.0) + float(s.gross or 0), 2)
enrollments = list((await session.execute(
select(Enrollment).where(Enrollment.status == "active"))).scalars().all())
benefit_total = float((await session.execute(
select(func.coalesce(func.sum(BenefitRecord.amount), 0)).where(
BenefitRecord.year == date.today().year))).scalar() or 0)
return {
"batches": [{"id": b.id, "period": f"{b.year}-{b.month:02d}", "status": b.status,
"gross": float(b.gross_total or 0), "net": float(b.net_total or 0),
"tax": float(b.tax_total or 0), "insurance": float(b.insurance_total or 0),
"count": b.employee_count}
for b in sorted(batches, key=lambda b: (b.year, b.month))],
"department_cost": [{"name": k, "value": v} for k, v in
sorted(dept_cost.items(), key=lambda kv: -kv[1])[:12]],
"enrolled": len(enrollments),
"benefit_year_total": round(benefit_total, 2),
}
@router.get("/activities", summary="最近动态")
async def activities(
session: Session,
auth: Annotated[AuthContext, Depends(require_perm("system:log:read"))],
limit: int = Query(20, le=60),
):
logs = list((await session.execute(
select(OperationLog).order_by(OperationLog.id.desc()).limit(limit))).scalars().all())
return [{"id": l.id, "username": l.username, "module": l.module, "action": l.action,
"path": l.path, "status_code": l.status_code, "duration_ms": l.duration_ms,
"created_at": l.created_at, "detail": l.detail} for l in logs]
@router.get("/announcements", summary="工作台公告")
async def dashboard_announcements(session: Session, auth: AuthCtx):
rows = list((await session.execute(
select(Announcement).where(Announcement.is_published.is_(True))
.order_by(Announcement.published_at.desc()).limit(10))).scalars().all())
return [{"id": a.id, "title": a.title, "content": a.content, "category": a.category,
"level": a.level, "publisher": a.publisher, "published_at": a.published_at}
for a in rows]