343 lines
20 KiB
Python
343 lines
20 KiB
Python
"""员工全生命周期端到端测试(objective 2)。
|
||
|
||
一条链按真实业务顺序跑完:
|
||
|
||
招聘漏斗 → Offer 审批发放接受 → 入职三件套(合同/薪资标准/参保)→ 登记人事信息
|
||
→ 开通 H5 自助账号 → 首次发薪 → 试用期转正定薪 → 调部门(走审批)→ 晋升调薪
|
||
→ 二次发薪 → H5 请假与审批 → 离职收尾(合同终止 / 停保 / 标准失效 / 账号禁用)。
|
||
|
||
刻意写在同一个测试函数里:这条链本身有状态,后一步的断言依赖前一步的落库结果,
|
||
拆成多个用例反而要靠 fixture 复制状态,掩盖真正的联动缺陷。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
API = "/api/v1"
|
||
YEAR = 2031
|
||
HIRE = f"{YEAR}-01-06"
|
||
PWD = "E2e#Life2031"
|
||
|
||
|
||
def _items(client, headers, path, **params):
|
||
resp = client.get(API + path, headers=headers, params={"page_size": 200, **params})
|
||
assert resp.status_code == 200, f"GET {path}: {resp.text}"
|
||
return resp.json()["items"]
|
||
|
||
|
||
def _post(client, headers, path, payload=None, msg=""):
|
||
resp = client.post(API + path, headers=headers, json=payload if payload is not None else {})
|
||
assert resp.status_code < 300, f"POST {msg or path} -> {resp.status_code} {resp.text}"
|
||
return resp.json()
|
||
|
||
|
||
def _patch(client, headers, path, payload, msg=""):
|
||
resp = client.patch(API + path, headers=headers, json=payload)
|
||
assert resp.status_code < 300, f"PATCH {msg or path} -> {resp.status_code} {resp.text}"
|
||
return resp.json()
|
||
|
||
|
||
def _std_package(client, headers, emp_id) -> tuple[float, dict]:
|
||
"""从薪资标准读「基本 + 绩效」薪酬包(含明细),供发薪断言复用。"""
|
||
rows = _items(client, headers, "/payroll/standards", employee_id=emp_id)
|
||
assert rows, "员工应有生效薪资标准"
|
||
items = {k: float(v) for k, v in (rows[0]["item_values"] or {}).items()}
|
||
package = sum(v for k, v in items.items() if k in ("base_salary", "perf_salary"))
|
||
return round(package, 2), items
|
||
|
||
|
||
# ======================================================================================
|
||
def test_full_employee_lifecycle(client, admin, hr, payroll, login):
|
||
recruiter = login("recruiter")
|
||
|
||
# ---------------------------------------------------------------- 0. 组织参照物
|
||
depts = _items(client, hr, "/org/departments")
|
||
assert len(depts) >= 2, "种子数据至少要有两个部门,才能验证调部门"
|
||
jobs = _items(client, recruiter, "/recruitment/jobs", status="open")
|
||
assert jobs, "种子数据应包含在招职位"
|
||
job = jobs[0]
|
||
dept_a = next((d for d in depts if d["id"] == job.get("department_id")), depts[0])
|
||
dept_b = next(d for d in depts if d["id"] != dept_a["id"])
|
||
level = _items(client, hr, "/org/job-levels")[0]
|
||
position = _items(client, hr, "/org/positions")[0]
|
||
|
||
# ---------------------------------------------------------------- 1. 招聘漏斗
|
||
cand = _post(client, recruiter, "/recruitment/candidates", {
|
||
"name": "链路测试-林牧", "gender": "男", "phone": "13900002031",
|
||
"email": "linmu@example.com", "degree": "硕士", "school": "华中科技大学",
|
||
"major": "计算机科学与技术", "work_years": 7, "source": "猎头",
|
||
"expect_salary_min": 28000, "expect_salary_max": 35000,
|
||
}, "候选人建档")
|
||
app = _post(client, recruiter, "/recruitment/applications", {
|
||
"candidate_id": cand["id"], "job_id": job["id"], "stage": "resume",
|
||
}, "创建应聘")
|
||
_post(client, recruiter, f"/recruitment/applications/{app['id']}/move",
|
||
{"stage": "screen", "rating": 4, "remark": "简历初筛通过"}, "简历初筛")
|
||
itv = _post(client, recruiter, "/recruitment/interviews", {
|
||
"application_id": app["id"], "round": 1, "interview_type": "field",
|
||
"scheduled_at": f"{YEAR}-01-02T10:00:00", "duration_minutes": 60,
|
||
"interviewer_names": ["王志强", "张丽丽"],
|
||
}, "安排面试")
|
||
_post(client, recruiter, f"/recruitment/interviews/{itv['id']}/feedback",
|
||
{"result": "pass", "score": 88, "feedback": "技术匹配度高"}, "面试评价")
|
||
cols = client.get(API + "/recruitment/board", headers=recruiter).json()
|
||
stages = {c["stage"]: c for c in cols}
|
||
assert stages["interview"]["count"] >= 1, "面试通过的候选人应进入面试列"
|
||
|
||
offer = _post(client, recruiter, "/recruitment/offers", {
|
||
"application_id": app["id"], "candidate_id": cand["id"], "job_id": job["id"],
|
||
"department_id": dept_a["id"], "position_id": position["id"],
|
||
"job_level_id": level["id"], "monthly_salary": 30000,
|
||
"probation_months": 3, "contract_years": 3, "expected_hire_date": HIRE,
|
||
}, "创建 Offer")
|
||
for step in ("approved", "sent", "accepted"):
|
||
_post(client, recruiter, f"/recruitment/offers/{offer['id']}/decide",
|
||
{"status": step, "comment": f"链路-{step}"}, f"Offer {step}")
|
||
onboard = _post(client, recruiter, f"/recruitment/offers/{offer['id']}/onboard",
|
||
{"hire_date": HIRE, "engage_form": "正式", "probation_months": 3},
|
||
"Offer 转档案")
|
||
emp_id = onboard["employee_id"]
|
||
|
||
# ------------------------------------------------- 2. 入职三件套自动落地(幂等)
|
||
emp = client.get(f"{API}/employees/{emp_id}", headers=hr).json()
|
||
assert emp["status"] == "probation" and emp["is_active"] is True
|
||
assert emp["hire_date"] == HIRE and emp["department_id"] == dept_a["id"]
|
||
assert emp["work_no"] and emp["probation_months"] == 3
|
||
|
||
doss = client.get(f"{API}/employees/{emp_id}/dossier", headers=hr).json()
|
||
contracts = doss["contracts"]
|
||
assert len(contracts) == 1, f"入职应自动生成 1 份劳动合同,实际 {len(contracts)}"
|
||
contract = contracts[0]
|
||
assert contract["status"] == "active"
|
||
assert contract["start_date"] == HIRE
|
||
assert contract["end_date"] == f"{YEAR + 3}-01-06", "合同年限应取自 Offer.contract_years"
|
||
assert contract["probation_end"] == f"{YEAR}-04-06", "试用期到期日 = 入职日 + 3 个月"
|
||
assert contract["contract_no"].startswith("HT")
|
||
|
||
package, items = _std_package(client, hr, emp_id)
|
||
assert package == 30000.0, f"薪资标准薪酬包应等于 Offer 月薪,实际 {package}"
|
||
assert items.get("base_salary") and items.get("perf_salary")
|
||
|
||
enrolls = _items(client, hr, "/benefits/enrollments", employee_id=emp_id)
|
||
assert len(enrolls) == 1 and enrolls[0]["status"] == "active"
|
||
assert enrolls[0]["include_in_payroll"] is True
|
||
assert float(enrolls[0]["social_base"]) > 0 and float(enrolls[0]["fund_base"]) > 0
|
||
|
||
# 幂等:再次触发入职动作不应重复建档
|
||
_patch(client, hr, f"/employees/{emp_id}", {"phone": "13900002032"}, "更新联系方式")
|
||
doss = client.get(f"{API}/employees/{emp_id}/dossier", headers=hr).json()
|
||
assert len(doss["contracts"]) == 1
|
||
assert len(_items(client, hr, "/payroll/standards", employee_id=emp_id)) == 1
|
||
assert len(_items(client, hr, "/benefits/enrollments", employee_id=emp_id)) == 1
|
||
|
||
# ---------------------------------------------------------------- 3. 登记人事信息
|
||
_patch(client, hr, f"/employees/{emp_id}", {
|
||
"id_card": "420101199005064321", "native_place": "湖北 武汉",
|
||
"marital_status": "已婚", "address": "武汉市东湖高新区光谷大道 1 号",
|
||
"emergency_contact": "苏晚", "emergency_phone": "13800002031",
|
||
"bank_name": "招商银行", "bank_account": "6225880123456789",
|
||
}, "补充基本信息")
|
||
_post(client, hr, "/employee-educations", {
|
||
"employee_id": emp_id, "degree": "硕士", "school": "华中科技大学",
|
||
"major": "计算机科学与技术", "start_date": "2011-09-01", "end_date": "2014-06-30",
|
||
"is_highest": True,
|
||
}, "登记教育经历")
|
||
_post(client, hr, "/employee-work-histories", {
|
||
"employee_id": emp_id, "company": "某科技有限公司", "position": "高级后端工程师",
|
||
"department": "平台架构部", "start_date": "2014-07-01", "end_date": HIRE,
|
||
"description": "负责订单中台与结算系统,团队 8 人",
|
||
}, "登记工作经历")
|
||
_post(client, hr, "/employee-families", {
|
||
"employee_id": emp_id, "name": "苏晚", "relation": "配偶",
|
||
"phone": "13800002031", "employer": "武汉市第一小学", "is_emergency": True,
|
||
}, "登记家庭成员")
|
||
_post(client, hr, "/employee-certificates", {
|
||
"employee_id": emp_id, "name": "系统架构设计师",
|
||
"certificate_no": "软考-2023-0001", "issue_date": "2023-11-15",
|
||
"expire_date": "2028-11-14", "issuer": "工业和信息化部",
|
||
}, "登记证书")
|
||
doss = client.get(f"{API}/employees/{emp_id}/dossier", headers=hr).json()
|
||
assert doss["employee"]["emergency_contact"] == "苏晚"
|
||
for key in ("educations", "work_histories", "families", "certificates"):
|
||
assert len(doss[key]) == 1, f"{key} 应登记 1 条"
|
||
|
||
# ---------------------------------------------------------- 4. 开通 H5 自助账号
|
||
roles = _items(client, admin, "/system/roles", code="employee")
|
||
emp_role = next(r for r in roles if r["code"] == "employee")
|
||
user = _post(client, admin, "/system/users", {
|
||
"username": "e2e_linmu", "password": PWD, "name": "林牧",
|
||
"email": "linmu@example.com", "phone": "13900002032", "employee_id": emp_id,
|
||
}, "创建自助账号")
|
||
_post(client, admin, f"/system/users/{user['id']}/roles", {"role_ids": [emp_role["id"]]},
|
||
"绑定普通员工角色")
|
||
self_h = login("e2e_linmu", PWD)
|
||
|
||
home = client.get(API + "/self/home", headers=self_h)
|
||
assert home.status_code == 200, home.text
|
||
home_body = home.json()
|
||
assert home_body["employee"]["employee_id"] == emp_id
|
||
assert home_body["employee"]["work_no"] == emp["work_no"]
|
||
assert home_body["contract"]["end_date"] == f"{YEAR + 3}-01-06"
|
||
|
||
ins = client.get(API + "/self/insurance", headers=self_h).json()
|
||
assert ins["enrolled"] is True and ins["plan_name"], "H5 应能看到自己的参保信息"
|
||
assert ins["social_base"] > 0 and ins["fund_base"] > 0 and ins["monthly_personal"] > 0
|
||
standard = client.get(API + "/self/salary-standard", headers=self_h).json()
|
||
assert standard["configured"] is True
|
||
assert standard["total"] > 0
|
||
|
||
# 越权自检:普通员工不能看别人的工资条,也不能读全量花名册
|
||
assert client.get(API + "/payroll/payslips", headers=self_h).status_code == 403
|
||
assert client.get(API + "/employees", headers=self_h).status_code == 403
|
||
|
||
# ---------------------------------------------------------------- 5. 首次发薪
|
||
_post(client, payroll, "/payroll/periods/init", {"year": YEAR}, "初始化计薪期间")
|
||
periods = {p["month"]: p for p in _items(client, payroll, "/payroll/periods", year=YEAR)}
|
||
assert len(periods) == 12
|
||
|
||
def run_batch(month: int, name: str) -> dict:
|
||
batch = _post(client, payroll, "/payroll/batches", {
|
||
"name": name, "period_id": periods[month]["id"], "scope": {"employee_ids": [emp_id]},
|
||
}, f"创建 {month} 月工资表")
|
||
preview = client.get(f"{API}/payroll/batches/{batch['id']}/preview", headers=payroll).json()
|
||
rows = [r for r in preview["items"] if r["employee_id"] == emp_id]
|
||
assert len(rows) == 1, "计薪名单应只包含链路员工"
|
||
assert rows[0]["standard_total"] > 0
|
||
_post(client, payroll, f"/payroll/batches/{batch['id']}/manual", {
|
||
"manual": {str(emp_id): {"items": {"overtime": 1000}, "remark": "链路测试加班费"}},
|
||
}, "录入变动项")
|
||
calc = _post(client, payroll, f"/payroll/batches/{batch['id']}/calculate", {}, "算薪")
|
||
assert calc["employee_count"] == 1
|
||
assert abs(calc["net_total"] - (calc["gross_total"] - calc["deduction_total"])) < 0.5
|
||
assert calc["insurance_personal_total"] > 0
|
||
_post(client, payroll, f"/payroll/batches/{batch['id']}/approve",
|
||
{"comment": "链路审核"}, "审核工资表")
|
||
_post(client, payroll, f"/payroll/batches/{batch['id']}/publish", None, "发布工资条")
|
||
_post(client, payroll, f"/payroll/batches/{batch['id']}/pay", None, "发放工资")
|
||
detail = client.get(f"{API}/payroll/batches/{batch['id']}", headers=payroll).json()
|
||
assert detail["status"] == "paid"
|
||
return {"batch": detail, "calc": calc, "row": rows[0]}
|
||
|
||
first = run_batch(1, f"{YEAR} 年 1 月链路工资表")
|
||
expected_gross = round(first["row"]["standard_total"] + 1000, 2)
|
||
assert abs(first["calc"]["gross_total"] - expected_gross) < 1, (
|
||
f"应发工资 = 薪资标准 {first['row']['standard_total']} + 加班费 1000,"
|
||
f"实际 {first['calc']['gross_total']}")
|
||
|
||
slips = _items(client, self_h, "/self/payslips", year=YEAR)
|
||
assert len(slips) == 1 and slips[0]["month"] == 1
|
||
slip_detail = client.get(f"{API}/self/payslips/{slips[0]['id']}", headers=self_h).json()
|
||
assert abs(slip_detail["net"] - first["calc"]["net_total"]) < 0.5
|
||
assert slip_detail["status"] == "published"
|
||
|
||
# ------------------------------------------------------------ 6. 试用期转正定薪
|
||
_post(client, hr, f"/employees/{emp_id}/regular", {
|
||
"effective_date": f"{YEAR}-04-01", "regular_salary": 36000,
|
||
"reason": "试用期考核优秀", "direct": True,
|
||
}, "转正")
|
||
emp = client.get(f"{API}/employees/{emp_id}", headers=hr).json()
|
||
assert emp["status"] == "active" and emp["regular_date"] == f"{YEAR}-04-01"
|
||
doss = client.get(f"{API}/employees/{emp_id}/dossier", headers=hr).json()
|
||
assert doss["contracts"][0]["probation_end"] is None
|
||
reg_adjs = [a for a in doss["adjustments"] if a["adjust_type"] == "regular"]
|
||
assert reg_adjs and reg_adjs[0]["status"] == "approved"
|
||
assert float(reg_adjs[0]["before_amount"]) == 30000
|
||
assert float(reg_adjs[0]["after_amount"]) == 36000
|
||
package, _ = _std_package(client, hr, emp_id)
|
||
assert package == 36000.0, "转正定薪应同步生效到薪资标准"
|
||
|
||
# ------------------------------------------------- 7. 调部门(走审批 + 账套切换)
|
||
change = _post(client, hr, f"/employees/{emp_id}/transfer", {
|
||
"department_id": dept_b["id"], "position_id": position["id"],
|
||
"effective_date": f"{YEAR}-04-15", "reason": "组织架构调整", "direct": False,
|
||
}, "提交调部门")
|
||
assert client.get(f"{API}/employees/{emp_id}", headers=hr).json()["department_id"] == dept_a["id"], \
|
||
"审批通过前不应改变部门"
|
||
_post(client, hr, f"/employee-changes/{change['id']}/approve",
|
||
{"status": "approved", "comment": "同意调岗"}, "审批调部门")
|
||
emp = client.get(f"{API}/employees/{emp_id}", headers=hr).json()
|
||
assert emp["department_id"] == dept_b["id"]
|
||
std_after_move = _items(client, hr, "/payroll/standards", employee_id=emp_id)[0]
|
||
plan_new = client.get(f"{API}/payroll/plans/{std_after_move['plan_id']}", headers=payroll).json()
|
||
assert std_after_move["plan_name"] == plan_new["name"], "薪资账套应随部门切换"
|
||
package, _ = _std_package(client, hr, emp_id)
|
||
assert package == 36000.0, "调部门不应改变薪酬包金额"
|
||
|
||
# ------------------------------------------------------------ 8. 晋升调薪(走审批)
|
||
adj = _post(client, payroll, "/salary-adjustments", {
|
||
"employee_id": emp_id, "effective_date": f"{YEAR}-05-01",
|
||
"after_amount": 40000, "adjust_type": "promotion",
|
||
"reason": "晋升为架构师", "status": "pending",
|
||
}, "提交调薪")
|
||
assert client.get(f"{API}/employees/{emp_id}", headers=hr).json() is not None
|
||
_post(client, payroll, f"/salary-adjustments/{adj['id']}/approve",
|
||
{"status": "approved", "comment": "同意晋升"}, "审批调薪")
|
||
package, _ = _std_package(client, hr, emp_id)
|
||
assert package == 40000.0, "调薪审批通过后应写入薪资标准"
|
||
|
||
second = run_batch(5, f"{YEAR} 年 5 月链路工资表")
|
||
assert second["calc"]["gross_total"] > first["calc"]["gross_total"], "调薪后应发工资需上涨"
|
||
|
||
# ------------------------------------------------------ 9. H5 请假 + 审批闭环
|
||
types = _items(client, hr, "/benefits/leave-types")
|
||
plain = [t for t in types if not t.get("requires_balance") and not t.get("requires_certificate")]
|
||
if plain:
|
||
leave_type = plain[0]
|
||
else: # 兜底:新生成员工额度后使用需额度的假期类型
|
||
leave_type = next(t for t in types if not t.get("requires_certificate"))
|
||
_post(client, hr, "/benefits/leave-balances/generate",
|
||
{"year": YEAR, "employee_ids": [emp_id]}, "生成假期额度")
|
||
req = _post(client, self_h, "/self/leave", {
|
||
"leave_type_id": leave_type["id"], "start_date": f"{YEAR}-05-12",
|
||
"end_date": f"{YEAR}-05-13", "reason": "家中有事", "phone": "13900002032",
|
||
}, "H5 提交请假")
|
||
assert req["days"] == 2
|
||
# 员工不能自批;HR 在数据范围内审批通过
|
||
assert client.post(API + f"/self/approvals/leave/{req['id']}/decide",
|
||
headers=self_h, json={"status": "approved"}).status_code == 403
|
||
approvals = client.get(API + "/self/approvals", headers=hr, params={"kind": "leave"})
|
||
assert approvals.status_code == 200, approvals.text
|
||
pending_ids = [i["id"] for i in approvals.json()["items"]]
|
||
assert req["id"] in pending_ids, "HR 审批中心应看到该请假"
|
||
_post(client, hr, f"/self/approvals/leave/{req['id']}/decide",
|
||
{"status": "approved", "comment": "准假"}, "审批请假")
|
||
mine = _items(client, self_h, "/self/leave", page_size=50)
|
||
mine = [m for m in mine if m["id"] == req["id"]]
|
||
assert mine and mine[0]["status"] == "approved"
|
||
|
||
# ---------------------------------------------------------------- 10. 离职收尾
|
||
_post(client, hr, f"/employees/{emp_id}/resign", {
|
||
"leave_date": f"{YEAR}-06-30", "leave_reason": "个人职业发展",
|
||
"remark": "链路测试离职", "direct": True,
|
||
}, "办理离职")
|
||
emp = client.get(f"{API}/employees/{emp_id}", headers=hr).json()
|
||
assert emp["status"] == "resigned" and emp["is_active"] is False
|
||
assert emp["leave_date"] == f"{YEAR}-06-30"
|
||
|
||
doss = client.get(f"{API}/employees/{emp_id}/dossier", headers=hr).json()
|
||
assert doss["contracts"][0]["status"] == "terminated"
|
||
assert doss["contracts"][0]["end_date"] == f"{YEAR}-06-30"
|
||
enrolls = _items(client, hr, "/benefits/enrollments", employee_id=emp_id)
|
||
assert enrolls[0]["status"] == "stopped" and enrolls[0]["include_in_payroll"] is False
|
||
assert _items(client, hr, "/payroll/standards", employee_id=emp_id, is_active=True) == []
|
||
|
||
# 离职后 H5 账号必须失效
|
||
assert client.post(API + "/auth/login",
|
||
json={"username": "e2e_linmu", "password": PWD}).status_code in (401, 403)
|
||
# 不再进入新的计薪名单
|
||
june = _post(client, payroll, "/payroll/batches", {
|
||
"name": f"{YEAR} 年 6 月链路工资表", "period_id": periods[6]["id"],
|
||
"scope": {"employee_ids": [emp_id]},
|
||
}, "创建 6 月工资表")
|
||
preview = client.get(f"{API}/payroll/batches/{june['id']}/preview", headers=payroll).json()
|
||
assert preview["count"] == 0, "离职员工不应出现在计薪名单"
|
||
assert client.post(f"{API}/payroll/batches/{june['id']}/calculate",
|
||
headers=payroll, json={}).status_code == 400
|
||
|
||
# ------------------------------------------------------- 11. 统计口径随之更新
|
||
stats = client.get(API + "/employees/stats", headers=hr).json()
|
||
assert stats["resigned"] >= 1 and stats["total"] >= 1
|
||
dash = client.get(API + "/dashboard/overview", headers=hr)
|
||
assert dash.status_code == 200, dash.text
|
||
cards = {c["key"]: c for c in dash.json()["cards"]}
|
||
assert cards["headcount"]["value"] >= 1 and "payroll" in cards
|