diff --git a/app/api/v1/employee.py b/app/api/v1/employee.py index 8cbba26..e3ab4c4 100644 --- a/app/api/v1/employee.py +++ b/app/api/v1/employee.py @@ -34,7 +34,7 @@ from ...models.employee import ( EmployeeSalaryAdjustment, EmployeeWorkHistory, ) -from ...models.org import Department, JobLevel, Position +from ...models.org import Department, DictItem, JobLevel, Position from ...models.payroll import EmployeeSalary as EmployeeSalaryRef from ...models.rbac import Attachment, User from ...models.selfservice import ProfileRequest @@ -152,11 +152,15 @@ async def _unique(session, field, value, exclude_id=None, label="") -> None: raise AppError(f"{label or field} 已存在:{value}", "duplicate", 409) -async def next_work_no(session) -> str: +async def next_work_no(session, taken: set[str] | None = None) -> str: + """发号 EMPxxxxx。``taken`` 用于批量导入:同批次里已发但**还没 flush** 的工号 + 在库里查不到,只看库会把同一号发给多行,最后一起提交时撞唯一约束。""" max_no = (await session.execute(select(func.max(Employee.id)))).scalar() or 0 while True: max_no += 1 code = f"EMP{max_no:05d}" + if code in (taken or set()): + continue if not (await session.execute(select(Employee.id).where(Employee.work_no == code))).first(): return code @@ -359,11 +363,27 @@ async def export_roster(session: Session, @extra.get("/import-template", summary="导入模板") async def import_template(auth: Annotated[AuthContext, Depends(require_perm("employee:employee:import"))]): - headers = ["姓名", "性别", "部门", "职位", "职级", "手机号", "邮箱", "身份证号", "学历", - "入职日期", "用工形式", "试用期月数", "民族", "婚姻状况", "籍贯"] - return xlsx_response(headers, [["张三", "男", "研发中心", "后端工程师", "P5", "13800000000", + headers = ["工号", "姓名", "性别", "部门", "职位", "职级", "手机号", "邮箱", "身份证号", "学历", + "入职日期", "用工形式", "试用期月数", "民族", "婚姻状况", "籍贯", + "出生日期", "政治面貌", "现居住地址", "紧急联系人", "紧急联系电话", "毕业院校", "专业"] + return xlsx_response(headers, [["", "张三", "男", "研发中心", "后端工程师", "P5", "13800000000", "zhangsan@example.com", "", "本科", "2026-01-05", "正式", 3, - "汉族", "未婚", "江苏南京"]], "员工导入模板.xlsx") + "汉族", "未婚", "江苏南京", + "1995-03-08", "群众", "南京市鼓楼区人民路 1 号", "李四", "13900000000", + "东南大学", "软件工程"]], "员工导入模板.xlsx") + + +# 婚姻状况是自由文本列,历史表格里常混进「否 / 单身」甚至误填的姓名 +MARITAL_VALUES = ("未婚", "已婚", "离异", "丧偶") +MARITAL_ALIASES = {"单身": "未婚", "初婚": "已婚", "再婚": "已婚", "离异未再婚": "离异"} + + +def _marital(value: Any) -> str: + """认不出的婚姻状况原样返回,由导入结果提示,不静默丢弃。""" + text = str(value).strip() + if text in MARITAL_VALUES: + return text + return MARITAL_ALIASES.get(text, text) IMPORT_FIELDS = { @@ -371,14 +391,20 @@ IMPORT_FIELDS = { "职级": ("_level", str), "手机号": ("phone", str), "邮箱": ("email", str), "身份证号": ("id_card", str), "学历": ("highest_degree", str), "入职日期": ("hire_date", date), "用工形式": ("engage_form", str), "试用期月数": ("probation_months", int), - "民族": ("nation", str), "婚姻状况": ("marital_status", str), "籍贯": ("native_place", str), + "民族": ("nation", str), "婚姻状况": ("marital_status", _marital), "籍贯": ("native_place", str), "工号": ("work_no", str), + # 模板没有下列列,但真实花名册普遍会带;顺手认下来,省得手工搬表 + "出生日期": ("birthday", date), "政治面貌": ("political_status", str), + "现居住地址": ("address", str), "紧急联系人": ("emergency_contact", str), + "紧急联系电话": ("emergency_phone", str), "毕业院校": ("school", str), "专业": ("specialty", str), } def _coerce(value: Any, kind) -> Any: if value in (None, ""): return None + if callable(kind) and kind not in (date, int, str): + return kind(value) if kind is date: if isinstance(value, datetime): return value.date() @@ -390,57 +416,167 @@ def _coerce(value: Any, kind) -> Any: return str(value).strip() +def _import_error_text(exc: Exception) -> str: + """行级失败原因:唯一约束等技术错误翻译成 HR 看得懂的话。""" + from sqlalchemy.exc import IntegrityError + + if isinstance(exc, IntegrityError): + return "工号 / 身份证号与已有档案冲突,请检查表格是否重复或工号已被占用" + return str(exc) or type(exc).__name__ + + +def _default_status(hire_date: date | None, probation_months: int | None, + engage_form: str | None) -> str: + """按导入表推断在职状态:真实花名册里绝大多数是多年前入职的老员工。 + + 一律写 probation 会让看板「在职 / 试用」失真,也会让转正提醒全是过期数据。 + """ + if engage_form == "试用": + return "probation" + if hire_date and probation_months: + months = probation_months + anniversary = date(hire_date.year + months // 12, + (hire_date.month - 1 + months) % 12 + 1, + min(hire_date.day, 28)) + return "probation" if anniversary > date.today() else "active" + # 没填试用期时:入职日期已过 60 天视为正式在职,否则按试用期处理 + if hire_date and (date.today() - hire_date).days > 60: + return "active" + return "probation" + + +# 学历写法不统一时先归一到字典值,避免列表按学历筛选时漏人 +DEGREE_ALIASES = { + "硕士研究生": "硕士", "学士": "本科", "大学本科": "本科", "大学": "本科", + "博士研究生": "博士", "专科": "大专", "初中": "初中及以下", "高中及以下": "初中及以下", +} + + @extra.post("/import", response_model=ImportResult, summary="批量导入员工") async def import_roster( session: Session, auth: Annotated[AuthContext, Depends(require_perm("employee:employee:import"))], file: UploadFile = File(...), ): + """按「工号优先、其次身份证号」匹配:存在则更新,不存在则新建。 + + 两个硬约束(都是踩过坑的地方): + + 1. **逐行 flush**:工号是自动发号(EMPxxxxx),只看已提交数据的话, + 同一批次里所有行都会拿到同一个号,最后一起提交时撞 work_no 唯一约束, + 整单导入报「数据已存在或被其它记录引用」。这里每行开 savepoint 并 flush, + 坏行只影响自己,其余行照常入库。 + 2. **部门/职位/职级找不到不静默留空**:那是导入最常见的口径事故, + 必须回到 warnings 里让 HR 看得见。 + """ rows = parse_xlsx(await file.read()) + result = ImportResult(total=len(rows), created=0, updated=0, failed=0) + if not rows: + raise AppError("导入文件为空或没有数据行", "empty_file") depts = {d.name: d.id for d in (await session.execute(select(Department))).scalars().all()} positions = {p.name: p.id for p in (await session.execute(select(Position))).scalars().all()} levels = {j.name: j.id for j in (await session.execute(select(JobLevel))).scalars().all()} - result = ImportResult(total=len(rows), created=0, updated=0, failed=0) + ref_labels = {"部门": depts, "职位": positions, "职级": levels} + degree_values = { + item.label for item in (await session.execute( + select(DictItem).where(DictItem.type_code == "degree"))).scalars().all() + } + # 本批次已占用/已出现的工号与身份证号:未 flush 的行在库里查不到,只能自己记账 + taken_work_nos = { + w for (w,) in (await session.execute(select(Employee.work_no))).all() if w + } + seen_id_cards: set[str] = set() + for idx, raw in enumerate(rows, start=2): + name = raw.get("姓名") try: data: dict[str, Any] = {} for header, (field, kind) in IMPORT_FIELDS.items(): value = _coerce(raw.get(header), kind) if value is None: continue - if field == "_dept": - data["department_id"] = depts.get(value) - elif field == "_position": - data["position_id"] = positions.get(value) - elif field == "_level": - data["job_level_id"] = levels.get(value) + if field in ("_dept", "_position", "_level"): + label = {"_dept": "部门", "_position": "职位", "_level": "职级"}[field] + column = {"_dept": "department_id", "_position": "position_id", + "_level": "job_level_id"}[field] + hit = ref_labels[label].get(value) + if hit is None: + result.warnings.append( + {"row": idx, "name": name, + "message": f"{label}「{value}」在系统中不存在,已留空;" + f"请先在组织架构里维护该{label},或修正表格后重新导入"}) + else: + data[column] = hit elif field == "gender": data["gender"] = gender_code(value) + elif field == "marital_status" and value not in MARITAL_VALUES: + result.warnings.append( + {"row": idx, "name": name, + "message": f"婚姻状况「{value}」不是标准取值" + f"({'/'.join(MARITAL_VALUES)}),已原样保存"}) + data[field] = value + elif field == "highest_degree": + data[field] = DEGREE_ALIASES.get(value, value) + if degree_values and data[field] not in degree_values: + result.warnings.append( + {"row": idx, "name": name, + "message": f"学历「{value}」不在数据字典 degree 中," + "已原样保存,按学历筛选/统计时可能漏人"}) else: data[field] = value if not data.get("name"): raise ValueError("姓名为空") - data.setdefault("status", "probation") + + # 同一个文件里两个人填了同一身份证号:直接判失败, + # 否则后一行会「更新」前一行的档案,无声少一个人。 + if data.get("id_card") and data["id_card"] in seen_id_cards: + raise ValueError(f"文件内身份证号重复:{data['id_card']}") + data.setdefault( + "status", _default_status(data.get("hire_date"), data.get("probation_months"), + data.get("engage_form"))) + # 认领已有档案的优先级:工号 → 身份证号 → 手机号。 + # 模板里工号是可以留空由系统发号的,没有前两者时用手机号兜底, + # 否则重复导入会把同一批人再建一遍(花名册凭空翻倍)。 existing = None - if data.get("work_no"): + for field, label in (("work_no", "工号"), ("id_card", "身份证号"), ("phone", "手机号")): + value = data.get(field) + if not value: + continue existing = (await session.execute( - select(Employee).where(Employee.work_no == data["work_no"]))).scalar_one_or_none() - elif data.get("id_card"): - existing = (await session.execute( - select(Employee).where(Employee.id_card == data["id_card"]))).scalar_one_or_none() - if existing: - for key, value in data.items(): - setattr(existing, key, value) - result.updated += 1 - else: - data["work_no"] = data.get("work_no") or await next_work_no(session) - data = await employee_before("create", data, None, auth, session) - session.add(Employee(**data)) - result.created += 1 + select(Employee).where(getattr(Employee, field) == value))).scalar_one_or_none() + if existing is not None: + break + # 工号命中但身份证号对不上:多半是工号填错,绝不能覆盖别人的档案 + if existing and data.get("id_card") and existing.id_card and existing.id_card != data["id_card"]: + raise ValueError( + f"工号 {existing.work_no} 已属于「{existing.name}」(身份证号不一致)," + "请删除本行或修正工号") + + # 每行一个 savepoint:坏行回滚到行首,不会连累已成功的行 + async with session.begin_nested(): + if existing: + for key, value in data.items(): + setattr(existing, key, value) + target, action = existing, "update" + result.updated += 1 + else: + data["work_no"] = data.get("work_no") or await next_work_no(session, taken_work_nos) + data = await employee_before("create", data, None, auth, session) + target = Employee(**data) + session.add(target) + await session.flush() # 让工号/主键立刻可见,下一行才能正确发号 + taken_work_nos.add(data["work_no"]) + action = "create" + result.created += 1 + # 与「新增员工」按钮同一条链路补入职三件套(合同 / 薪资标准 / 参保)。 + # 少这一步的话,批量导入的人没有生效合同、也进不了算薪取人名单。 + await employee_after_write(action, target, auth, session) + if data.get("id_card"): + seen_id_cards.add(data["id_card"]) except Exception as exc: # noqa: BLE001 - collect per-row failures result.failed += 1 - result.errors.append({"row": idx, "name": raw.get("姓名"), "message": str(exc)}) + result.errors.append({"row": idx, "name": name, "message": _import_error_text(exc)}) await session.commit() result.total = len(rows) return result @@ -454,7 +590,7 @@ router.include_router(build_router(CrudSpec( "gender", "highest_degree", "is_active"), extra_query=("has_account",), filter_hook=_employee_filter_hook, date_range_fields=("hire_date", "leave_date", "regular_date"), - order_by="hire_date", employee_scope="id", before_write=employee_before, + order_by="work_no", order="asc", employee_scope="id", before_write=employee_before, after_read=decorate, after_write=employee_after_write, on_delete=employee_on_delete, ), preface=[extra])) diff --git a/app/api/v1/org.py b/app/api/v1/org.py index 5fcd545..501c257 100644 --- a/app/api/v1/org.py +++ b/app/api/v1/org.py @@ -27,16 +27,34 @@ from ...schemas.org import ( router = APIRouter() +async def _parent_chain(session, department_id: int) -> set[int]: + """给定部门的整条上级链(不含自身),沿 parent_id 上溯。 + + 只信 parent_id:dep_path 是展示用的历史字段(播种 / 新增 / 导入三种写法都出现过), + 拿它做前缀判断既会误报环,也会漏判。 + """ + rows = (await session.execute(select(Department.id, Department.parent_id))).all() + parent_of = {row[0]: row[1] or 0 for row in rows} + chain: set[int] = set() + cursor = parent_of.get(department_id, 0) + while cursor and cursor not in chain: + chain.add(cursor) + cursor = parent_of.get(cursor, 0) + return chain + + async def _dept_before(action, data, obj, auth, session): parent_id = int(data.get("parent_id", (getattr(obj, "parent_id", 0) if obj else 0)) or 0) if obj is not None and parent_id: if parent_id == obj.id: raise AppError("不能把部门移动到自身下", "bad_parent") parent = await session.get(Department, parent_id) - node = await session.get(Department, obj.id) if not parent: raise AppError("上级部门不存在", "bad_parent") - if parent.dep_path and node.dep_path and parent.dep_path.startswith(node.dep_path): + # 环检测只能沿 parent_id 往上爬:dep_path 历史上有两套写法,顶层一律是 + # `.0`,用前缀判断会把「把 7 挂到 3 下」误判成「移动到自己的下级」而拒绝。 + chain = await _parent_chain(session, parent_id) + if obj.id in chain: raise AppError("不能把部门移动到自己的下级部门", "bad_parent") data["parent_id"] = parent_id if parent_id: diff --git a/app/core/deps.py b/app/core/deps.py index 4fae3b5..c0c9a8e 100644 --- a/app/core/deps.py +++ b/app/core/deps.py @@ -128,18 +128,29 @@ async def department_subtree(session: AsyncSession, department_id: int | None) - """All department ids inside the given node (self included).""" if not department_id: return [] - dept = await session.get(Department, department_id) - if not dept: + # 必须按 parent_id 逐层展开,**不能**拿 dep_path 做前缀匹配: + # 这张表的 dep_path 历史上有两套写法(播种写 /UNIS/RD,页面新增与导入写 + # .0 / .0.3),顶层部门一律是 .0,`LIKE '.0%'` 会把全公司部门都命中, + # 于是「只选一个部门」实际捞出全部员工,看起来就像筛选完全没生效。 + rows = (await session.execute(select(Department.id, Department.parent_id))).all() + known = {row[0] for row in rows} + if department_id not in known: return [department_id] - path = dept.dep_path or f".{department_id}" - rows = ( - await session.execute( - select(Department.id).where( - (Department.dep_path.like(f"{path}%")) | (Department.id == department_id) - ) - ) - ).all() - return [r[0] for r in rows] + children: dict[int, list[int]] = {} + for dept_id, parent_id in rows: + children.setdefault(parent_id or 0, []).append(dept_id) + + out: list[int] = [department_id] + seen = {department_id} + stack = [department_id] + while stack: + for child in children.get(stack.pop(), []): + if child in seen: # 脏数据里的循环引用不能把这里绕成死循环 + continue + seen.add(child) + out.append(child) + stack.append(child) + return out async def scope_employee_ids(session: AsyncSession, auth: AuthContext) -> list[int] | None: diff --git a/app/schemas/employee.py b/app/schemas/employee.py index 7917c51..b45edd9 100644 --- a/app/schemas/employee.py +++ b/app/schemas/employee.py @@ -133,6 +133,8 @@ class ImportResult(BaseModel): updated: int failed: int errors: list[dict] = [] + # 不算失败、但必须让导入者知道的口径问题(例如部门/职位在系统里找不到,已留空) + warnings: list[dict] = [] class ProfileRequestRead(BaseModel): diff --git a/app/services/lifecycle.py b/app/services/lifecycle.py index 3633f9f..9412488 100644 --- a/app/services/lifecycle.py +++ b/app/services/lifecycle.py @@ -13,7 +13,7 @@ from __future__ import annotations -from datetime import date +from datetime import date, timedelta from decimal import Decimal from typing import Any @@ -94,6 +94,12 @@ async def ensure_contract(session, emp: Employee, *, signed_by: str | None = Non end = _plus_years(start, float(emp.contract_term_years)) if not end and start: end = _plus_years(start, 3) + # 导入历史花名册时,不能把多年前的到期日直接挂到「生效中」合同上。 + # 按合同年限依次续到当前周期,保留一份当前有效合同,避免 H5 出现负数剩余天数。 + term_years = max(int(emp.contract_term_years or 3), 1) + while end and end < date.today(): + start = end + timedelta(days=1) + end = _plus_years(start, term_years) count = (await session.execute( select(func.count()).select_from(EmployeeContract) .where(EmployeeContract.employee_id == emp.id))).scalar() or 0 diff --git a/tests/test_dept_filter.py b/tests/test_dept_filter.py new file mode 100644 index 0000000..807a222 --- /dev/null +++ b/tests/test_dept_filter.py @@ -0,0 +1,158 @@ +"""部门筛选:选中一个部门必须只出这个部门(含下级时含其子树)的人。 + +线上现象:人事档案里勾选某个部门,列表人数没变化,像筛选完全没生效。 +根因是「部门子树」用 dep_path 前缀匹配,而 dep_path 历史上有两套写法 +(播种写 `/UNIS/RD`,页面新增与导入写 `.0` / `.0.3`),顶层部门一律是 `.0`, +`LIKE '.0%'` 直接把全公司部门都命中。现在一律按 parent_id 逐层展开。 +""" + +from __future__ import annotations + +import asyncio + +import pytest +from sqlalchemy import select + +from app.core.deps import department_subtree +from app.db.session import SessionFactory +from app.models.org import Department + +API = "/api/v1" + + +class _Probe: + """记录本文件造出来的部门/员工,模块结束时一律删掉。 + + 部门筛选与「数据范围」类用例共用同一份演示数据:探针留在库里会让后续 + 用例的「部门子树严格小于全公司」「全员都有司龄」等断言漂移。 + """ + + def __init__(self) -> None: + self.employees: list[int] = [] + self.departments: list[int] = [] + + +@pytest.fixture(scope="module") +def probe(client, admin): + made = _Probe() + yield made + # 先删人(连带清掉合同/薪资/参保),再自下而上删部门 + for emp_id in reversed(made.employees): + client.delete(f"{API}/employees/{emp_id}", headers=admin) + for dept_id in reversed(made.departments): + client.delete(f"{API}/org/departments/{dept_id}", headers=admin) + + +def _emp(probe, client, admin, name: str, department_id: int, phone: str) -> int: + resp = client.post( + f"{API}/employees", headers=admin, + json={"name": name, "work_no": phone, "phone": phone, "work_age_years": 2.0, + "department_id": department_id, "status": "active"}, + ) + assert resp.status_code == 200, resp.text + emp_id = resp.json()["id"] + probe.employees.append(emp_id) + return emp_id + + +def _dept(probe, client, admin, name: str, parent_id: int | None = None) -> int: + body = {"name": name} + if parent_id: + body["parent_id"] = parent_id + resp = client.post(f"{API}/org/departments", headers=admin, json=body) + assert resp.status_code == 200, resp.text + dept_id = resp.json()["id"] + probe.departments.append(dept_id) + return dept_id + + +def _total(client, admin, **params) -> int: + resp = client.get(f"{API}/employees", headers=admin, params={"page_size": 100, **params}) + assert resp.status_code == 200, resp.text + return resp.json()["total"] + + +def test_sibling_departments_do_not_leak(client, admin, probe): + """两个平级顶层部门(dep_path 同为 .0):选一个不能带出另一个的人。""" + a = _dept(probe, client, admin, "__筛选甲部") + b = _dept(probe, client, admin, "__筛选乙部") + _emp(probe, client, admin, "__筛选甲员工", a, "19100000001") + _emp(probe, client, admin, "__筛选乙员工", b, "19100000002") + + for subtree in ("1", "0"): + listed = client.get(f"{API}/employees", headers=admin, + params={"department_id": a, "dept_subtree": subtree, + "page_size": 50}).json() + assert listed["total"] == 1, (subtree, listed["total"]) + assert {i["department_name"] for i in listed["items"]} == {"__筛选甲部"} + + assert _total(client, admin, department_id=f"{a},{b}", dept_subtree="1") == 2 + + +def test_subtree_toggle_respected(client, admin, probe): + """含下级=开 → 命中子部门的人;含下级=关 → 只算本部门。""" + parent = _dept(probe, client, admin, "__筛选上级部") + child = _dept(probe, client, admin, "__筛选下级部", parent) + _emp(probe, client, admin, "__筛选下级员工", child, "19100000003") + + assert _total(client, admin, department_id=parent, dept_subtree="1") == 1 + assert _total(client, admin, department_id=parent, dept_subtree="0") == 0 + assert _total(client, admin, department_id=child, dept_subtree="1") == 1 + assert client.get(f"{API}/employees/export", headers=admin, + params={"department_id": parent, "dept_subtree": "1"}).status_code == 200 + + +def test_department_move_between_roots_is_allowed(client, admin, probe): + """平级部门之间改挂上级必须放行:dep_path 都是 .0,前缀判断会误报成环。""" + target = _dept(probe, client, admin, "__筛选新上级") + mover = _dept(probe, client, admin, "__筛选被移动部") + resp = client.patch(f"{API}/org/departments/{mover}", headers=admin, + json={"parent_id": target}) + assert resp.status_code == 200, resp.text + assert resp.json()["level"] == 2 + + # 反向:把上级挂到自己的下级之下,必须仍然被拦住 + back = client.patch(f"{API}/org/departments/{target}", headers=admin, + json={"parent_id": mover}) + assert back.status_code == 400 and back.json()["code"] == "bad_parent", back.text + + +def test_department_subtree_is_cycle_safe(client, admin): + """脏数据里 parent_id 自引用不能让子树展开死循环(会话自回滚,不污染库)。""" + + async def scenario(): + async with SessionFactory() as session: + dept = Department(name="__筛选环部", parent_id=0, dep_path=".0", level=1) + session.add(dept) + await session.flush() + dept.parent_id = dept.id # 制造自引用 + await session.flush() + ids = await department_subtree(session, dept.id) + dept_id = dept.id + await session.rollback() + return ids, dept_id + + ids, dept_id = asyncio.run(scenario()) + assert ids == [dept_id] + + +def test_seeded_tree_subtree_matches_tree_endpoint(client, admin): + """播种的组织树:后端展开的下级集合要和 /org/departments/tree 一致。""" + tree = client.get(f"{API}/org/departments/tree", headers=admin).json() + + def walk(nodes): + for node in nodes: + yield node + yield from walk(node.get("children") or []) + + async def scenario(): + async with SessionFactory() as session: + out = {} + for node in walk(tree): + out[node["id"]] = set(await department_subtree(session, node["id"])) + return out + + expanded = asyncio.run(scenario()) + for node in walk(tree): + child_ids = {c["id"] for c in walk(node.get("children") or [])} + assert expanded[node["id"]] == child_ids | {node["id"]}, node["name"] diff --git a/tests/test_employee_import.py b/tests/test_employee_import.py new file mode 100644 index 0000000..e47829c --- /dev/null +++ b/tests/test_employee_import.py @@ -0,0 +1,179 @@ +"""员工花名册批量导入:自动发号、重复导入、脏数据的可见性。 + +线上事故复盘:清空数据后先导部门(成功)、再导人事档案,整单报 +「数据已存在或被其它记录引用,无法保存」。根因是自动发号只看已提交数据, +同一批次里每一行都拿到同一个工号 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 diff --git a/tests/test_employee_order.py b/tests/test_employee_order.py new file mode 100644 index 0000000..eaf567a --- /dev/null +++ b/tests/test_employee_order.py @@ -0,0 +1,54 @@ +"""员工档案默认按工号升序排列。""" + +from __future__ import annotations + +API = "/api/v1" + + +def test_employees_default_to_work_no_ascending(client, admin): + """列表默认与显式点击工号升序都应按工号从小到大。""" + prefix = "__工号排序" + created: list[int] = [] + try: + for suffix in ("10", "02", "01"): + resp = client.post( + f"{API}/employees", + headers=admin, + json={ + "name": f"{prefix}{suffix}", + "work_no": f"SORT{suffix}", + "status": "active", + }, + ) + assert resp.status_code == 200, resp.text + created.append(resp.json()["id"]) + + default_rows = client.get( + f"{API}/employees", + headers=admin, + params={"keyword": prefix, "page_size": 20}, + ).json() + assert [row["work_no"] for row in default_rows["items"]] == [ + "SORT01", + "SORT02", + "SORT10", + ] + + explicit_rows = client.get( + f"{API}/employees", + headers=admin, + params={ + "keyword": prefix, + "page_size": 20, + "order_by": "work_no", + "order": "asc", + }, + ).json() + assert [row["work_no"] for row in explicit_rows["items"]] == [ + "SORT01", + "SORT02", + "SORT10", + ] + finally: + for employee_id in created: + client.delete(f"{API}/employees/{employee_id}", headers=admin) diff --git a/tests/员工导入模板-AI_已填充_20261022.xlsx b/tests/员工导入模板-AI_已填充_20261022.xlsx new file mode 100644 index 0000000..db7f01e Binary files /dev/null and b/tests/员工导入模板-AI_已填充_20261022.xlsx differ diff --git a/tests/组织架构_部门导入模板.xlsx b/tests/组织架构_部门导入模板.xlsx new file mode 100644 index 0000000..6da6816 Binary files /dev/null and b/tests/组织架构_部门导入模板.xlsx differ diff --git a/web/src/api/resources.ts b/web/src/api/resources.ts index 48aaeed..52a7f2e 100644 --- a/web/src/api/resources.ts +++ b/web/src/api/resources.ts @@ -18,8 +18,8 @@ export const employeeDef: ResourceDef = { perm: 'employee:employee', exportPath: '/employees/export', searchPlaceholder: '姓名 / 工号 / 手机号', - orderBy: 'id', - order: 'desc', + orderBy: 'work_no', + order: 'asc', deptFilter: true, filters: [ col('status', '在职状态', { type: 'tag', options: [ diff --git a/web/src/components/ImportDrawer.tsx b/web/src/components/ImportDrawer.tsx index f744bea..9d34533 100644 --- a/web/src/components/ImportDrawer.tsx +++ b/web/src/components/ImportDrawer.tsx @@ -1,5 +1,5 @@ import { DownloadOutlined, InboxOutlined } from '@ant-design/icons' -import { App, Button, Drawer, Progress, Space, Upload } from 'antd' +import { Alert, App, Button, Drawer, Progress, Space, Upload } from 'antd' import { useState } from 'react' import { download, upload } from '../api/http' @@ -20,6 +20,8 @@ interface ImportResult { updated: number failed: number errors?: { row: number; name?: string; message: string }[] + /** 不算失败但需要 HR 处理的口径问题(部门/职位找不到、学历不在字典等) */ + warnings?: { row: number; name?: string; message: string }[] } /** 通用批量导入抽屉:模板下载与文件上传都走带 token 的 http 客户端。 */ @@ -87,11 +89,32 @@ export default function ImportDrawer(props: ImportDrawerProps) { 共 {result.total} 行,新增 {result.created},更新 {result.updated},失败{' '} {result.failed}
+ {!!(result.warnings || []).length && ( +