unis_hrms/app/api/v1/recruitment.py

476 lines
23 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.

"""招聘管理:职位、候选人、应聘流程看板、面试、Offer、招聘分析."""
from __future__ import annotations
from typing import Annotated, Any
from fastapi import APIRouter, Depends, Query
from sqlalchemy import func, or_, select
from ...core.deps import AuthContext, Session, department_subtree, ensure, require_perm
from ...core.errors import AppError
from ...db.base import utcnow
from ...models.employee import Employee
from ...models.org import Department, JobLevel, Position
from ...models.recruitment import Application, Candidate, Interview, JobPosting, Offer
from ...models.rbac import User
from ...schemas.recruitment import (
ApplicationCreate,
ApplicationRead,
ApplicationUpdate,
BoardColumn,
CandidateCreate,
CandidateRead,
CandidateUpdate,
InterviewCreate,
InterviewFeedbackPayload,
InterviewRead,
InterviewUpdate,
JobCreate,
JobRead,
JobUpdate,
MovePayload,
OfferCreate,
OfferDecisionPayload,
OfferRead,
OfferUpdate,
OnboardPayload,
RecruitmentAnalytics,
)
from ..crud import CrudSpec, build_router
from ..helpers import attach_labels, counts_by, dept_filter_ids, label_map
from .employee import _log
router = APIRouter()
STAGES: list[tuple[str, str]] = [
("resume", "简历投递"), ("screen", "简历筛选"), ("interview", "面试评估"),
("assessment", "测评/加面"), ("offer", "Offer 沟通"), ("hired", "已录用"),
]
STAGE_LABELS = dict(STAGES) | {"rejected": "已淘汰"}
STAGE_ORDER = {code: idx + 1 for idx, (code, _label) in enumerate(STAGES)} | {"rejected": 99}
ACTIVE_STAGES = [code for code, _ in STAGES if code != "hired"]
async def job_after(session, rows):
await attach_labels(session, rows, [
("department_name", Department, "department_id", "name"),
("position_name", Position, "position_id", "name"),
("job_level_name", JobLevel, "job_level_id", "name"),
("owner_name", User, "owner_user_id", "name"),
])
counts = await counts_by(session, Application, "job_id")
for r in rows:
r.application_count = counts.get(r.id, 0)
async def candidate_after(session, rows):
if not rows:
return
apps = list((await session.execute(
select(Application).where(Application.candidate_id.in_([r.id for r in rows]))
.order_by(Application.id))).scalars().all())
latest: dict[int, Application] = {}
for app in apps:
latest[app.candidate_id] = app
job_titles = await label_map(session, JobPosting, "title")
counts: dict[int, int] = {}
for app in apps:
counts[app.candidate_id] = counts.get(app.candidate_id, 0) + 1
for r in rows:
r.application_count = counts.get(r.id, 0)
app = latest.get(r.id)
r.latest_stage = STAGE_LABELS.get(app.stage, app.stage) if app else None
r.latest_job_title = job_titles.get(app.job_id) if app else None
async def application_after(session, rows):
if not rows:
return
await attach_labels(session, rows, [
("candidate_name", Candidate, "candidate_id", "name"),
("candidate_phone", Candidate, "candidate_id", "phone"),
("job_title", JobPosting, "job_id", "title"),
("owner_name", User, "owner_user_id", "name"),
])
jobs = {j.id: j for j in (await session.execute(
select(JobPosting).where(JobPosting.id.in_({r.job_id for r in rows})))).scalars().all()}
depts = await label_map(session, Department)
for r in rows:
job = jobs.get(r.job_id)
r.department_name = depts.get(job.department_id) if job else None
async def interview_after(session, rows):
if not rows:
return
apps = {a.id: a for a in (await session.execute(
select(Application).where(Application.id.in_({r.application_id for r in rows})))).scalars().all()}
cands = await label_map(session, Candidate)
jobs = await label_map(session, JobPosting, "title")
for r in rows:
app = apps.get(r.application_id)
r.candidate_name = cands.get(app.candidate_id) if app else None
r.job_title = jobs.get(app.job_id) if app else None
r.round_label = f"第 {r.round} 轮"
async def offer_after(session, rows):
await attach_labels(session, rows, [
("candidate_name", Candidate, "candidate_id", "name"),
("job_title", JobPosting, "job_id", "title"),
("department_name", Department, "department_id", "name"),
])
router.include_router(build_router(CrudSpec(
model=JobPosting, create=JobCreate, update=JobUpdate, read=JobRead,
module="recruitment", resource="job", label="招聘职位", prefix="/recruitment/jobs", tag="招聘管理",
search_fields=("title", "code"), filters=("department_id", "status", "urgency", "employ_type",
"position_id", "job_level_id"),
date_range_fields=("publish_date",), order_by="id", after_read=job_after,
)))
router.include_router(build_router(CrudSpec(
model=Candidate, create=CandidateCreate, update=CandidateUpdate, read=CandidateRead,
module="recruitment", resource="candidate", label="候选人", prefix="/recruitment/candidates",
tag="招聘管理", search_fields=("name", "phone", "email", "current_company"),
filters=("source", "degree", "is_pool", "gender", "work_years"), order_by="id",
after_read=candidate_after,
before_write=lambda a, d, o, auth, s: _candidate_before(a, d, o, auth, s),
)))
router.include_router(build_router(CrudSpec(
model=Application, create=ApplicationCreate, update=ApplicationUpdate, read=ApplicationRead,
module="recruitment", resource="application", label="应聘流程", prefix="/recruitment/applications",
tag="招聘管理", search_fields=(), filters=("job_id", "candidate_id", "stage", "sub_status",
"owner_user_id", "rating"),
in_fields=("stage",), order_by="last_action_at", after_read=application_after,
)))
router.include_router(build_router(CrudSpec(
model=Interview, create=InterviewCreate, update=InterviewUpdate, read=InterviewRead,
module="recruitment", resource="interview", label="面试", prefix="/recruitment/interviews",
tag="招聘管理", search_fields=("location",), filters=("application_id", "status", "result",
"interview_type"),
in_fields=("status",), date_range_fields=("scheduled_at",), order_by="scheduled_at",
order="asc", after_read=interview_after,
)))
router.include_router(build_router(CrudSpec(
model=Offer, create=OfferCreate, update=OfferUpdate, read=OfferRead,
module="recruitment", resource="offer", label="Offer", prefix="/recruitment/offers", tag="招聘管理",
search_fields=(), filters=("application_id", "candidate_id", "job_id", "status", "department_id"),
in_fields=("status",), order_by="id", after_read=offer_after,
)))
async def _candidate_before(action, data, obj, auth, session):
if action == "create":
data.setdefault("source", "官网")
data.setdefault("is_pool", False)
data["creator_id"] = auth.user.id
if data.get("phone"):
dup = (await session.execute(select(Candidate.id).where(
Candidate.phone == data["phone"]))).scalar_one_or_none()
if dup:
raise AppError(f"手机号已存在于候选人 #{dup}", "duplicate", 409)
return data
# ------------------------------------------------------------- 看板 / 阶段流转
board = APIRouter()
@board.get("/board", summary="招聘看板(按阶段分组)")
async def kanban(session: Session,
auth: Annotated[AuthContext, Depends(require_perm("recruitment:application:read"))],
job_id: int | None = Query(None), keyword: str | None = Query(None),
department_id: str | None = Query(None), dept_subtree: bool = Query(True),
limit: int = Query(200, le=500)):
stmt = select(Application)
if job_id:
stmt = stmt.where(Application.job_id == job_id)
if keyword:
kw = f"%{keyword}%"
ids = list((await session.execute(select(Candidate.id).where(or_(
Candidate.name.like(kw), Candidate.phone.like(kw))))).scalars().all())
stmt = stmt.where(Application.candidate_id.in_(ids or [-1]))
dept_ids = await dept_filter_ids(session, department_id, dept_subtree)
if dept_ids:
stmt = stmt.where(Application.job_id.in_(
select(JobPosting.id).where(JobPosting.department_id.in_(dept_ids))))
rows = list((await session.execute(
stmt.order_by(Application.last_action_at.desc().nullslast(), Application.id.desc())
)).scalars().all())
await application_after(session, rows)
grouped: dict[str, list] = {code: [] for code in STAGE_LABELS}
for row in rows:
grouped.setdefault(row.stage, []).append(ApplicationRead.model_validate(row))
counts = {code: len(grouped.get(code, [])) for code in grouped}
ordered = list(STAGES) + [("rejected", "已淘汰")]
return [BoardColumn(stage=code, label=STAGE_LABELS[code], count=counts.get(code, 0),
items=grouped.get(code, [])[:limit]) for code, _label in ordered]
@board.post("/applications/{item_id}/move", summary="流转应聘阶段")
async def move_application(item_id: int, payload: MovePayload, session: Session,
auth: Annotated[AuthContext, Depends(require_perm("recruitment:application:move"))]):
app = await session.get(Application, item_id)
ensure(app is not None, "应聘记录不存在")
if payload.stage not in STAGE_ORDER:
raise AppError("未知的流程阶段", "bad_stage")
before = app.stage
app.stage = payload.stage
app.stage_order = STAGE_ORDER[payload.stage]
app.sub_status = payload.sub_status
if payload.rating is not None:
app.rating = payload.rating
if payload.reject_reason:
app.reject_reason = payload.reject_reason
app.last_action_at = utcnow()
timeline = list(app.timeline or [])
timeline.append({"at": utcnow().isoformat(timespec="seconds"), "from": before, "to": payload.stage,
"actor": auth.user.name, "remark": payload.remark})
app.timeline = timeline[-60:]
if payload.stage == "hired":
job = await session.get(JobPosting, app.job_id)
if job:
job.hired_count = (job.hired_count or 0) + 1
await _log(session, "rec_application", app.id, f"move:{before}->{payload.stage}", auth, payload.remark)
await session.commit()
return {"message": f"已移动到「{STAGE_LABELS[payload.stage]}」", "stage": payload.stage}
@board.get("/stages", summary="流程阶段选项")
async def stage_options(auth: Annotated[AuthContext, Depends(require_perm("recruitment:application:read"))]):
return [{"value": code, "label": label, "order": STAGE_ORDER[code]} for code, label in STAGE_LABELS.items()
if code in STAGE_ORDER]
@board.post("/candidates/{item_id}/pool", summary="候选人转入人才库")
async def to_pool(item_id: int, session: Session,
auth: Annotated[AuthContext, Depends(require_perm("recruitment:candidate:pool"))],
is_pool: bool = Query(True)):
obj = await session.get(Candidate, item_id)
ensure(obj, "候选人不存在")
obj.is_pool = is_pool
await session.commit()
return {"message": "已加入人才库" if is_pool else "已移出人才库"}
@board.post("/jobs/{item_id}/close", summary="关闭职位")
async def close_job(item_id: int, session: Session,
auth: Annotated[AuthContext, Depends(require_perm("recruitment:job:close"))]):
obj = await session.get(JobPosting, item_id)
ensure(obj, "职位不存在")
obj.status = "closed"
obj.close_date = utcnow().date()
await session.commit()
return {"message": "职位已关闭"}
@board.post("/interviews/{item_id}/feedback", summary="填写面试评价")
async def interview_feedback(item_id: int, payload: InterviewFeedbackPayload, session: Session,
auth: Annotated[AuthContext, Depends(require_perm("recruitment:interview:feedback"))]):
itv = await session.get(Interview, item_id)
ensure(itv, "面试不存在")
itv.status = "finished"
itv.result = payload.result
itv.score = payload.score
itv.feedback = payload.feedback
itv.interviewer_comment = payload.feedback
app = await session.get(Application, itv.application_id)
if payload.result == "fail" and app:
app.stage, app.stage_order = "rejected", STAGE_ORDER["rejected"]
app.reject_reason = app.reject_reason or "面试未通过"
app.last_action_at = utcnow()
elif payload.result == "pass" and app and app.stage in ("resume", "screen", "interview"):
app.stage, app.stage_order, app.last_action_at = "interview", STAGE_ORDER["interview"], utcnow()
if payload.schedule_next:
nxt = Interview(application_id=app.id, round=(itv.round or 1) + 1,
interview_type=payload.next_type, scheduled_at=payload.next_at,
status="scheduled", notified=False)
session.add(nxt)
await _log(session, "rec_interview", itv.id, f"feedback:{payload.result}", auth, payload.feedback)
await session.commit()
return {"message": "评价已保存"}
@board.post("/offers/{item_id}/decide", summary="Offer 审批 / 发送 / 反馈")
async def offer_decide(item_id: int, payload: OfferDecisionPayload, session: Session,
auth: Annotated[AuthContext, Depends(require_perm("recruitment:offer:update"))]):
offer = await session.get(Offer, item_id)
ensure(offer, "Offer 不存在")
offer.status = payload.status
if payload.status in ("approved", "sent", "accepted", "declined", "cancelled"):
offer.decided_at = utcnow()
if payload.status in ("approved", "cancelled"):
offer.approver_id = auth.user.id
offer.comment = payload.comment
if payload.decline_reason:
offer.decline_reason = payload.decline_reason
app = await session.get(Application, offer.application_id)
if payload.status == "accepted" and app:
app.stage, app.stage_order, app.last_action_at = "offer", STAGE_ORDER["offer"], utcnow()
if payload.status == "declined":
if offer.decline_reason is None:
offer.decline_reason = "候选人拒绝"
if app:
app.stage, app.stage_order = "rejected", STAGE_ORDER["rejected"]
app.reject_reason = offer.decline_reason
await _log(session, "rec_offer", offer.id, f"offer:{payload.status}", auth, payload.comment)
await session.commit()
return {"message": "已更新", "status": payload.status}
@board.post("/offers/{item_id}/onboard", summary="Offer 转 employee 档案")
async def offer_onboard(item_id: int, payload: OnboardPayload, session: Session,
auth: Annotated[AuthContext, Depends(require_perm("recruitment:offer:approve"))]):
from datetime import date
from .employee import _as_date, next_work_no
from ...services.lifecycle import onboard_employee
offer = await session.get(Offer, item_id)
ensure(offer, "Offer 不存在")
if offer.employee_id:
raise AppError("该 Offer 已经建立员工档案", "already_onboarded", 409)
cand = await session.get(Candidate, offer.candidate_id)
ensure(cand, "候选人不存在")
hire_date = _as_date(payload.hire_date) or offer.expected_hire_date or date.today()
emp = Employee(
work_no=payload.work_no or await next_work_no(session), name=cand.name, gender=cand.gender,
phone=cand.phone, email=cand.email, highest_degree=cand.degree, school=cand.school,
specialty=cand.major, department_id=offer.department_id, position_id=offer.position_id,
job_level_id=offer.job_level_id, engage_form=payload.engage_form, hire_date=hire_date,
probation_months=offer.probation_months or payload.probation_months, status="probation",
contract_start=hire_date, contract_term_years=offer.contract_years,
application_id=offer.application_id, is_active=True,
custom_fields={"source": "recruitment", "offer_id": offer.id, "expected_salary": cand.expect_salary_min},
)
session.add(emp)
await session.flush()
offer.employee_id = emp.id
if offer.monthly_salary:
from ...models.employee import EmployeeSalaryAdjustment
session.add(EmployeeSalaryAdjustment(
employee_id=emp.id, effective_date=hire_date, after_amount=offer.monthly_salary,
adjust_type="hire", reason="入职定薪", status="approved",
approver_id=auth.user.id, approved_at=utcnow()))
# 入职三件套:劳动合同 + 薪资标准 + 五险一金参保(幂等)
await onboard_employee(session, emp, monthly_salary=offer.monthly_salary,
signed_by=auth.user.name)
app = await session.get(Application, offer.application_id)
if app:
app.stage, app.stage_order, app.last_action_at = "hired", STAGE_ORDER["hired"], utcnow()
cand.employee_id = emp.id
await _log(session, "rec_offer", offer.id, "onboard", auth, f"工号 {emp.work_no}")
await session.commit()
return {"message": f"已入职,工号 {emp.work_no}", "employee_id": emp.id}
@board.get("/analytics", response_model=RecruitmentAnalytics, summary="招聘漏斗分析")
async def analytics(session: Session,
auth: Annotated[AuthContext, Depends(require_perm("recruitment:report:read"))],
year: int | None = Query(None)):
apps = list((await session.execute(select(Application))).scalars().all())
cands = list((await session.execute(select(Candidate))).scalars().all())
jobs = list((await session.execute(select(JobPosting))).scalars().all())
offers = list((await session.execute(select(Offer))).scalars().all())
if year:
apps = [a for a in apps if a.created_at and a.created_at.year == year]
cands = [c for c in cands if c.created_at and c.created_at.year == year]
stage_counts: dict[str, int] = {}
for a in apps:
if a.stage == "rejected":
continue
stage_counts[a.stage] = stage_counts.get(a.stage, 0) + 1
funnel = []
for code, label in STAGES:
reached = sum(1 for a in apps if STAGE_ORDER.get(a.stage, 0) >= STAGE_ORDER[code]
and a.stage != "rejected") + sum(
1 for a in apps if a.stage == "rejected" and (a.timeline or []))
funnel.append({"stage": code, "label": label, "count": stage_counts.get(code, 0),
"reached": reached})
total_apps = len(apps) or 1
by_source: dict[str, int] = {}
for c in cands:
by_source[c.source or "其他"] = by_source.get(c.source or "其他", 0) + 1
job_map = {j.id: j for j in jobs}
per_job: dict[int, dict[str, Any]] = {}
for a in apps:
row = per_job.setdefault(a.job_id, {"job_id": a.job_id,
"title": job_map[a.job_id].title if a.job_id in job_map else "-",
"applications": 0, "interviews": 0, "hired": 0})
row["applications"] += 1
if STAGE_ORDER.get(a.stage, 0) >= STAGE_ORDER["interview"] and a.stage != "rejected":
row["interviews"] += 1
if a.stage == "hired":
row["hired"] += 1
dept_map = await label_map(session, Department)
by_dept: dict[str, dict[str, int]] = {}
for j in jobs:
key = dept_map.get(j.department_id, "未分配")
row = by_dept.setdefault(key, {"department": key, "jobs": 0, "applications": 0, "hired": 0})
row["jobs"] += 1
if j.hired_count:
row["hired"] += j.hired_count
for a in apps:
job = job_map.get(a.job_id)
if not job:
continue
key = dept_map.get(job.department_id, "未分配")
by_dept.setdefault(key, {"department": key, "jobs": 0, "applications": 0, "hired": 0})["applications"] += 1
accepted = sum(1 for o in offers if o.status == "accepted")
hired_days = []
for o in offers:
app = next((a for a in apps if a.id == o.application_id), None)
if o.status == "accepted" and app and app.created_at and o.decided_at:
hired_days.append((o.decided_at - app.created_at).days)
interviews = list((await session.execute(select(Interview))).scalars().all())
finished = [i for i in interviews if i.result in ("pass", "fail")]
return RecruitmentAnalytics(
funnel=funnel, by_job=sorted(per_job.values(), key=lambda r: -r["applications"])[:20],
by_source=[{"source": k, "count": v} for k, v in sorted(by_source.items(), key=lambda kv: -kv[1])],
by_department=sorted(by_dept.values(), key=lambda r: -r["applications"]),
total_jobs=len(jobs), open_jobs=sum(1 for j in jobs if j.status == "open"),
total_candidates=len(cands), total_applications=len(apps),
hired=sum(1 for a in apps if a.stage == "hired"),
offer_accept_rate=round(accepted / len(offers) * 100, 1) if offers else None,
avg_time_to_hire_days=round(sum(hired_days) / len(hired_days), 1) if hired_days else None,
pass_rate=round(sum(1 for i in finished if i.result == "pass") / len(finished) * 100, 1)
if finished else None,
)
router.include_router(board, prefix="/recruitment")
@router.get("/recruitment/todos", summary="招聘待办", tags=["招聘管理"])
async def recruitment_todos(session: Session,
auth: Annotated[AuthContext, Depends(require_perm("recruitment:application:read"))]):
from datetime import date, timedelta
from ...models.rbac import Notification
today = date.today()
soon = (await session.execute(select(Interview, Candidate.name).join(
Application, Interview.application_id == Application.id).join(
Candidate, Application.candidate_id == Candidate.id).where(
Interview.status == "scheduled",
Interview.scheduled_at.is_not(None)).order_by(Interview.scheduled_at))).all()
upcoming = [{"interview_id": i.id, "candidate_name": name, "scheduled_at": i.scheduled_at,
"interview_type": i.interview_type, "location": i.location}
for i, name in soon if i.scheduled_at and i.scheduled_at.date() <= today + timedelta(days=7)]
pending_offers = int((await session.execute(
select(func.count()).select_from(Offer).where(Offer.status.in_(["draft", "pending"])))).scalar() or 0)
stale_apps = int((await session.execute(
select(func.count()).select_from(Application).where(
Application.stage.in_(ACTIVE_STAGES),
Application.last_action_at.is_not(None),
Application.last_action_at < utcnow() - timedelta(days=7)))).scalar() or 0)
return {"upcoming_interviews": upcoming, "pending_offers": pending_offers,
"stale_applications": stale_apps}