180 lines
8.3 KiB
Python
180 lines
8.3 KiB
Python
"""员工花名册批量导入:自动发号、重复导入、脏数据的可见性。
|
||
|
||
线上事故复盘:清空数据后先导部门(成功)、再导人事档案,整单报
|
||
「数据已存在或被其它记录引用,无法保存」。根因是自动发号只看已提交数据,
|
||
同一批次里每一行都拿到同一个工号 EMP00001,最后一起 commit 时撞 work_no
|
||
唯一约束,被全局 IntegrityError 处理器翻译成了那句看不懂的话。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import io
|
||
from datetime import date
|
||
|
||
from openpyxl import Workbook
|
||
|
||
API = "/api/v1"
|
||
XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||
HEADERS = ["姓名", "性别", "部门", "职位", "职级", "手机号", "邮箱", "身份证号", "学历",
|
||
"入职日期", "用工形式", "试用期月数", "民族", "婚姻状况", "籍贯"]
|
||
|
||
|
||
def _xlsx(headers: list[str], rows: list[list]) -> bytes:
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
ws.append(headers)
|
||
for row in rows:
|
||
ws.append(row)
|
||
buffer = io.BytesIO()
|
||
wb.save(buffer)
|
||
return buffer.getvalue()
|
||
|
||
|
||
def _import(client, headers: dict, rows: list[list], cols: list[str] | None = None):
|
||
return client.post(
|
||
f"{API}/employees/import", headers=headers,
|
||
files={"file": ("roster.xlsx", _xlsx(cols or HEADERS, rows), XLSX)},
|
||
)
|
||
|
||
|
||
def _contracts(client, admin, employee_id: int) -> list[dict]:
|
||
resp = client.get(f"{API}/employee-contracts", headers=admin,
|
||
params={"employee_id": employee_id, "page_size": 20})
|
||
assert resp.status_code == 200, resp.text
|
||
return resp.json()["items"]
|
||
|
||
|
||
def _row(name: str, phone: str, id_card: str, **over) -> list:
|
||
"""按 HEADERS 顺序造一行;未指定的列留空(部门/职位/职级故意留空,由用例覆盖)。"""
|
||
base = {
|
||
"姓名": name, "性别": "男", "部门": None, "职位": None, "职级": None,
|
||
"手机号": phone, "邮箱": None, "身份证号": id_card, "学历": "本科",
|
||
"入职日期": "2026-01-05", "用工形式": "正式", "试用期月数": None,
|
||
"民族": "汉族", "婚姻状况": "已婚", "籍贯": "江苏南京",
|
||
}
|
||
base.update(over)
|
||
return [base[key] for key in HEADERS]
|
||
|
||
|
||
def test_bulk_import_assigns_unique_work_nos(client, admin):
|
||
"""一批没填工号的人必须各自拿到不同工号,且真正落库(事故回归)。"""
|
||
rows = [_row(f"导入甲{i}", f"1390000{i:04d}", f"3201021990010{i:04d}0{i % 10}X")
|
||
for i in range(12)]
|
||
resp = _import(client, admin, rows)
|
||
assert resp.status_code == 200, resp.text
|
||
body = resp.json()
|
||
assert body["created"] == 12, body
|
||
assert body["failed"] == 0, body["errors"]
|
||
|
||
listed = client.get(f"{API}/employees", headers=admin,
|
||
params={"keyword": "导入甲", "page_size": 50}).json()
|
||
work_nos = [e["work_no"] for e in listed["items"]]
|
||
assert len(work_nos) == 12, listed["total"]
|
||
assert len(set(work_nos)) == 12, work_nos
|
||
|
||
|
||
def test_reimport_updates_instead_of_duplicating(client, admin):
|
||
"""同一份表导两次:第二次必须是更新(工号留空时靠身份证号/手机号认领)。"""
|
||
rows = [_row("重复导入", "13911110001", "320102199001010011")]
|
||
first = _import(client, admin, rows).json()
|
||
assert first["created"] == 1, first
|
||
again = _import(client, admin, rows).json()
|
||
assert again == {**again, "created": 0, "updated": 1, "failed": 0}, again
|
||
|
||
listed = client.get(f"{API}/employees", headers=admin, params={"keyword": "重复导入"}).json()
|
||
assert listed["total"] == 1, listed
|
||
|
||
|
||
def test_missing_department_is_warning_not_silent(client, admin):
|
||
"""部门/职位在系统里不存在 → 档案照样建,但必须回到 warnings 里。"""
|
||
rows = [_row("查无此部门", "13922220002", "320102199001020022", 部门="火星事业部")]
|
||
body = _import(client, admin, rows).json()
|
||
assert body["created"] == 1, body
|
||
hits = [w for w in body["warnings"] if "火星事业部" in w["message"]]
|
||
assert hits and "不存在" in hits[0]["message"], body["warnings"]
|
||
assert hits[0]["row"] == 2, hits
|
||
|
||
|
||
def test_bad_rows_are_isolated(client, admin):
|
||
"""坏行只影响自己:好行照常入库,失败行给出可读原因。"""
|
||
rows = [
|
||
_row("正常员工", "13933330003", "320102199001030033"),
|
||
["", "男", None, None, None, "13933330004", None, None, None, None,
|
||
None, None, None, None, None], # 姓名为空
|
||
]
|
||
body = _import(client, admin, rows).json()
|
||
assert body["created"] == 1 and body["failed"] == 1, body
|
||
assert body["errors"][0]["row"] == 3 and "姓名" in body["errors"][0]["message"], body["errors"]
|
||
|
||
|
||
def test_duplicate_id_card_inside_file_fails(client, admin):
|
||
"""同文件里两个人填了同一身份证号:判失败,不能让后一行覆盖前一行。"""
|
||
rows = [
|
||
_row("身份证号重复甲", "13944440004", "320102199001040044"),
|
||
_row("身份证号重复乙", "13944440005", "320102199001040044"),
|
||
]
|
||
body = _import(client, admin, rows).json()
|
||
assert body["created"] == 1 and body["failed"] == 1, body
|
||
assert "身份证号" in body["errors"][0]["message"], body["errors"]
|
||
|
||
|
||
def test_dirty_degree_and_marital_are_reported(client, admin):
|
||
"""学历写法不统一、婚姻状况填错列:原样保存但必须提示。"""
|
||
cols = HEADERS
|
||
rows = [
|
||
["非标学历", "男", None, None, None, "13955550006", None, "320102199001050055",
|
||
"全日制本科", "2026-01-05", None, None, "汉族", "否", "江苏"],
|
||
]
|
||
body = _import(client, admin, rows, cols).json()
|
||
assert body["created"] == 1, body
|
||
messages = " ".join(w["message"] for w in body["warnings"])
|
||
assert "学历" in messages and "婚姻状况" in messages, body["warnings"]
|
||
|
||
|
||
def test_import_completes_onboarding_and_status(client, admin):
|
||
"""导入必须与「新增员工」同链路补入职三件套,并按入职日期判断在职/试用。
|
||
|
||
少这一步的后果:批量导入的人没有生效合同、进不了算薪取人名单,
|
||
而且看板「在职 / 试用」会把十多年前入职的老员工全部算成试用期。
|
||
"""
|
||
rows = [
|
||
_row("老员工导入", "13977770008", "320102199001070077", 入职日期="2019-06-01"),
|
||
_row("新员工导入", "13977770009", "320102199001080088", 入职日期="2026-09-01"),
|
||
]
|
||
body = _import(client, admin, rows).json()
|
||
assert body["created"] == 2, body
|
||
|
||
by_name = {}
|
||
for name in ("老员工导入", "新员工导入"):
|
||
listed = client.get(f"{API}/employees", headers=admin, params={"keyword": name}).json()
|
||
row = listed["items"][0]
|
||
by_name[name] = row
|
||
contracts = _contracts(client, admin, row["id"])
|
||
active = [c for c in contracts if c["status"] == "active"]
|
||
assert active, (name, contracts)
|
||
assert active[0]["end_date"] >= date.today().isoformat(), (name, active)
|
||
|
||
assert by_name["老员工导入"]["status"] == "active", by_name
|
||
assert by_name["新员工导入"]["status"] == "probation", by_name
|
||
|
||
# 重复导入不能补出第二份生效合同
|
||
_import(client, admin, rows)
|
||
listed = client.get(f"{API}/employees", headers=admin, params={"keyword": "老员工导入"}).json()
|
||
row = listed["items"][0]
|
||
contracts = _contracts(client, admin, row["id"])
|
||
assert len([c for c in contracts if c["status"] == "active"]) == 1, contracts
|
||
|
||
|
||
def test_template_and_extra_columns_are_accepted(client, admin):
|
||
"""模板新增列(出生日期/政治面貌/地址…)要能认下来,别再让 HR 手工搬表。"""
|
||
cols = ["工号", *HEADERS, "出生日期", "政治面貌", "现居住地址", "紧急联系人", "紧急联系电话"]
|
||
rows = [["", "模板新列", "女", None, None, None, "13966660007", None,
|
||
"320102199001060066", "本科", "2026-01-05", None, None, "汉族", "未婚", "南京",
|
||
"1995-03-08", "群众", "南京市鼓楼区人民路 1 号", "李四", "13900000000"]]
|
||
body = _import(client, admin, rows, cols).json()
|
||
assert body["created"] == 1 and body["failed"] == 0, body
|
||
|
||
listed = client.get(f"{API}/employees", headers=admin, params={"keyword": "模板新列"}).json()
|
||
row = listed["items"][0]
|
||
assert row["birthday"] == "1995-03-08" and row["political_status"] == "群众", row
|