v 0.1.1
parent
19615b0240
commit
0676baf144
41
README.md
41
README.md
|
|
@ -15,7 +15,7 @@ FastAPI 0.115 ── SQLAlchemy 2.0 async ── Alembic ── SQLite(dev) →
|
|||
| 前端 | React 18 · TypeScript 5.7 · Vite 6 · React Router 6 · TanStack Query 5 · Zustand · antd 5 · antd-mobile 5 · Recharts · dnd-kit |
|
||||
| 后端 | Python 3.12 · FastAPI · Pydantic v2 · SQLAlchemy 2.0(全异步)· JWT(PyJWT) · bcrypt · openpyxl |
|
||||
| 数据 | SQLite(`aiosqlite`,开箱即用)→ MySQL 8(`aiomysql`,一条连接串切换)· Alembic 迁移 |
|
||||
| 质量 | pytest + pytest-asyncio(**150 项**,含职级报销标准、资料审核与 **Web⇄H5 一致性守卫** `tests/test_self_parity.py`)· ruff · `tsc --noEmit` 严格模式 |
|
||||
| 质量 | pytest + pytest-asyncio(**161 项**,含职级报销标准、资料审核与 **Web⇄H5 一致性守卫** `tests/test_self_parity.py`)· ruff · `tsc --noEmit` 严格模式 |
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -154,7 +154,7 @@ unis_hrms/
|
|||
## 3. 功能模块
|
||||
|
||||
### 3.1 人事档案 `/employees`
|
||||
花名册(多条件筛选、导入导出)· 360° 员工画像(教育/工作/家庭/证书/时间线)· 合同台账与到期预警 ·
|
||||
花名册(多条件筛选、导入导出、行内启停 Switch、按档案批量生成账号并选择角色,启停口径见 §9.3)· 360° 员工画像(教育/工作/家庭/证书/时间线)· 合同台账与到期预警 ·
|
||||
异动与调薪审批 · 证明开具台账。合同状态 `draft / active / renewed / expired / terminated`
|
||||
(`renewed` 表示已被续签合同接替,在职员工必有且只有一份 `active` 合同),续签提醒窗口统一为
|
||||
**90 天**(`app/core/constants.py: RENEW_WINDOW_DAYS`,看板、合同列表、H5 首页同源)。
|
||||
|
|
@ -232,6 +232,21 @@ Web 用 antd 表格 / 抽屉 / 表头筛选,H5 用卡片 / 胶囊 tab / `MChip
|
|||
每个职级可在行尾打开“报销标准”抽屉,维护多个报销项目(名称、金额、计量单位、说明),
|
||||
员工在自助端“合同与薪资”中查看当前职级标准。
|
||||
|
||||
**组织架构批量维护**:部门 / 职位 / 职级三个页面都提供「导出 / 导入 / 下载模板」。
|
||||
按编码(缺省时按名称)做 upsert,部门支持先写子部门再写上级,导入后统一重算 `dep_path` / `level` / `is_parent`;
|
||||
模板与文件上传都走带 JWT 的 `http` 客户端(`download()` / `upload()`),不要再用 `window.open` 或裸 `fetch`,
|
||||
否则浏览器不会带上 `Authorization`,登录态下也会 401。导入支持 `.xlsx` 与 UTF-8/GB18030 `.csv`。
|
||||
|
||||
**系统管理 · 数据维护**(`/system/maintenance`,超级管理员可见):
|
||||
|
||||
- **一键备份**:下载 zip,含 `manifest.json`、全表 `database.json`、SQLite 一致性快照 `database.sqlite` 与全部上传附件。
|
||||
- **导出数据**:导出多工作表 Excel,每张表一个 sheet,首表「说明」列出表名 / 中文名 / 记录数 / 清理时是否保留。
|
||||
- **清理所有数据**:需手动输入「unis_hrms」并二次确认;清空业务表、其它账号、附件与日志,
|
||||
保留系统管理员账号、角色权限、菜单和数据字典,便于原地重新开账。
|
||||
|
||||
`seed_menus` 已改为按「平台 + 父级 + 路径 + 名称」逐条 upsert,老环境重跑 `python -m app.seed`
|
||||
即可补上新增菜单,不会重复插入。
|
||||
|
||||
### 3.7 帮助中心 `/help`
|
||||
顶部帮助按钮、用户菜单“使用手册”和 H5 我的页面均可打开带真实截图的 HTML 全功能手册;
|
||||
静态文件位于 `web/public/help/index.html`,可直接访问 `/help/index.html` 或打印为 PDF。
|
||||
|
|
@ -371,7 +386,7 @@ DATABASE_URL="mysql+pymysql://hrms:pwd@127.0.0.1:3306/hrms?charset=utf8mb4" \
|
|||
|
||||
```bash
|
||||
./.venv/bin/ruff check app tests migrations scripts # All checks passed!
|
||||
./.venv/bin/python -m pytest -q # 135 passed
|
||||
./.venv/bin/python -m pytest -q # 158 passed
|
||||
cd web && npx tsc --noEmit # 严格模式无输出
|
||||
cd web && npm run build # tsc --noEmit && vite build
|
||||
```
|
||||
|
|
@ -383,6 +398,8 @@ cd web && npm run build # tsc --noEmit && vite build
|
|||
- `tests/test_role_matrix.py`:7 个角色的能力矩阵、写端点越权 403 扫描、审批中心可见范围(含 Offer 薪资泄漏回归)
|
||||
- `tests/test_api_surface.py`:全量路由可达性与响应契约
|
||||
- `tests/test_expense_standards.py`:职级多项目报销标准、重复校验与权限边界
|
||||
- `tests/test_org_io.py`:部门/职位/职级模板、导入、导出与权限边界(含 CSV 与人事档案模板 401 回归)
|
||||
- `tests/test_maintenance.py`:数据概况、备份 zip、全量导出与「仅保留系统管理员」的清理逻辑
|
||||
- `tests/test_derived_fields.py`:`after_read` 派生字段回归(用户角色 / 角色计数 / 招聘负责人 / 司龄),
|
||||
防止「保存即清空角色」这类静默失效再次发生
|
||||
- 测试使用独立库 `data/test_hrms-<pid>.db`(库名带 PID,跑完自动清理),既不污染开发数据,
|
||||
|
|
@ -472,6 +489,8 @@ cd web && npm run build # tsc --noEmit && vite build
|
|||
| 表单控件 | `FieldInput` 按 `FieldDef.type` 统一渲染;日期在提交前统一转 `YYYY-MM-DD`;`direct` 一律表示「直接生效,不走审批」 |
|
||||
| 反馈 | 成功用 `message.success` 并说明结果,删除等破坏性动作用 `modal.confirm`(确认框保持居中,不做抽屉)复述对象名;接口错误由拦截器统一 toast,页面不再叠加 |
|
||||
| H5 | 外壳 `.m-app` / `.m-tabbar`,宽屏下内容 560px 居中;文案与状态色与 Web 端同源(同一份 `*_OPTIONS`) |
|
||||
| 启停开关 | 列表里的「启用」列一律用 `components/StatusSwitch.tsx`(`type:'toggle'` 由 `Cell` 渲染),点一下直接 `PATCH {is_active}`,只在**停用**方向二次确认;列位置见 §9.3 |
|
||||
| 操作列 | 顺序固定 `自定义行操作 → 编辑 → 删除 → ⋮更多`(整块 `fixed:'right'`,是列表里唯一固定的列)。「更多」是 `MoreOutlined` 竖三点图标按钮(不带文字),永远是操作列最后一项,由 `ResourceTable` 的 `rowMore` / `onRowMore` 提供,低频动作(生成账号等)一律收进去,不在操作列堆按钮 |
|
||||
| 图标 | 只用 `components/icons.tsx` 白名单,新增菜单图标在那里补一行 |
|
||||
| 账户入口 | 统一在侧栏底部用户胶囊(`AdminLayout` 的 `.sider-user`,圆角方块头像 + 上行姓名 + 下行角色),顶栏不放头像;改资料/改密码只有 `/account`(`pages/account/Settings.tsx`)这一处,新页面不要再自建「修改密码」入口,也不要再用弹窗装个人设置 |
|
||||
|
||||
|
|
@ -499,6 +518,21 @@ cd web && npm run build # tsc --noEmit && vite build
|
|||
|
||||
---
|
||||
|
||||
### 9.3 业务启停:全站只有 `is_active` 一个开关
|
||||
|
||||
**一句话:`is_active` 是唯一的业务启停位,`status` 只表达在职生命周期,两者不重复、不互写。**
|
||||
|
||||
| 层 | 口径 |
|
||||
| --- | --- |
|
||||
| 数据模型 | 员工/部门/职位/职级/账套/薪资项目/参保方案/福利项目/假期类型/用户/角色/字典项都用 `is_active`;**不再新增 `status` 之类的第二套启停字段**。员工 `status` 只表示 `probation / active / leave / leaving / resigned` |
|
||||
| 列表 UI | 「启用」列渲染成内联 Switch,**恒为倒数第二列**:`ResourceTable` 自动把它挪到所有数据列之后并 `fixed:'right'`,紧贴操作列左边;数据列一律不做左侧 `fixed`(开关若排在中间会被右侧固定的操作列盖住,一点就落到「删除」上,就是这么踩出来的) |
|
||||
| 停用档案 | `services/lifecycle.py: set_account_state()` 联动:非超管账号一并停用并清除 RefreshToken(立刻 401),启用时**只恢复带 `档案停用,账号停用` 标记的账号**,不会把 HR 手动停用的账号偷偷放回来 |
|
||||
| 重新启用 | `api/v1/employee.py` 用 `employee_before` 记录的「显式启停意图」在离职联动 `close_resignation()` 之后重新赋值,避免「停用后点启用返回 200 但状态不变」 |
|
||||
| 业务过滤 | 参与计算的入口必须带 `Employee.is_active.is_(True)`:算薪取人(`payroll_service.employees_for_scope`)、福利批量发放、假期额度批量生成、档案批量生成账号;**统计与历史台账刻意不过滤**,停用的人历史数据仍要能查到 |
|
||||
| 下拉选择 | `/common/options` 返回 `extra.is_active`,停用项仍解析得出名称(历史单据不显示裸 ID),但前端置灰不可再选中 |
|
||||
|
||||
---
|
||||
|
||||
## 10. 常见问题
|
||||
|
||||
| 现象 | 处理 |
|
||||
|
|
@ -511,6 +545,7 @@ cd web && npm run build # tsc --noEmit && vite build
|
|||
| MySQL 连接报 cryptography | `pip install -e ".[mysql]"`(MySQL 8 的 `caching_sha2_password` 需要它) |
|
||||
| 列表里状态/类型显示英文码 | 该字段 `type:'tag'` 没挂 `options`,去 `defs.ts` 复用现成的 `*_OPTIONS`(列与筛选共用一份) |
|
||||
| 年度显示成 `2,026` | 列用了 `type:'number'`,改成 `type:'year'` |
|
||||
| 列表里的启停开关点下去却弹出「删除确认」 | 开关列被右侧固定的操作列盖住了:数据列不要写 `fixed:'left'`,「启用」列放最后(见 §9.3),`ResourceTable` 已按此规则重排列序 |
|
||||
| 切换 Tab / 首次进入某页整页白屏,控制台报 `Rendered more hooks than during the previous render` | `loading / error` 的早退写在了 `useState / useMemo` 之前,违反 Hooks 规则;把 hook 全部上移到早退之前(见 §9.2 红线) |
|
||||
| 抽屉首次打开控制台报 `useForm … not connected` | 在 onClick 里直接 `setFieldsValue`,改用 `useModalFormFill()`(见 §9.1) |
|
||||
| 改完权限码一直 403 | 忘了重跑 `python -m app.seed`,`sys_permission` 里还没有新码 |
|
||||
|
|
|
|||
|
|
@ -305,7 +305,7 @@ def build_router(spec: CrudSpec, *, preface: list[APIRouter] | None = None) -> A
|
|||
"label": str(getattr(r, spec.label_field, r.id)),
|
||||
"extra": {
|
||||
k: _jsonable(getattr(r, k))
|
||||
for k in ("department_id", "status", "code", "is_active", "phone")
|
||||
for k in ("department_id", "status", "code", "is_active", "phone", "has_account")
|
||||
if hasattr(r, k)
|
||||
},
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ from sqlalchemy import select
|
|||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from ..core.deps import department_subtree
|
||||
from ..core.errors import AppError
|
||||
|
||||
|
||||
async def dept_filter_ids(session: AsyncSession, raw: str | None,
|
||||
|
|
@ -37,6 +38,11 @@ async def attach_labels(session: AsyncSession, rows: list[Any],
|
|||
ids = {getattr(r, fk_attr, None) for r in rows}
|
||||
ids.discard(None)
|
||||
if not ids:
|
||||
for r in rows:
|
||||
try:
|
||||
setattr(r, target, None)
|
||||
except (AttributeError, TypeError):
|
||||
pass
|
||||
continue
|
||||
rows_map = dict((
|
||||
await session.execute(select(ref_model.id, getattr(ref_model, label_attr))
|
||||
|
|
@ -120,15 +126,7 @@ def xlsx_response(headers: list[str], rows: list[list[Any]], filename: str):
|
|||
)
|
||||
|
||||
|
||||
def parse_xlsx(data: bytes) -> list[dict[str, Any]]:
|
||||
"""First worksheet -> list of dicts keyed by the header row."""
|
||||
import io
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
wb = load_workbook(io.BytesIO(data), data_only=True, read_only=True)
|
||||
ws = wb.active
|
||||
rows = list(ws.iter_rows(values_only=True))
|
||||
def _rows_to_dicts(rows: list[tuple | list]) -> list[dict[str, Any]]:
|
||||
if not rows:
|
||||
return []
|
||||
headers = [str(h).strip() if h is not None else "" for h in rows[0]]
|
||||
|
|
@ -138,3 +136,32 @@ def parse_xlsx(data: bytes) -> list[dict[str, Any]]:
|
|||
continue
|
||||
out.append({headers[i]: raw[i] for i in range(min(len(headers), len(raw))) if headers[i]})
|
||||
return out
|
||||
|
||||
|
||||
def parse_xlsx(data: bytes) -> list[dict[str, Any]]:
|
||||
"""解析上传的表格:xlsx 取第一个工作表,csv 按 UTF-8 / GB18030 解码。
|
||||
|
||||
旧接口名为兼容保留;``.xls``(OLE 二进制)不在支持范围内,会得到明确提示。
|
||||
"""
|
||||
import csv
|
||||
import io
|
||||
|
||||
if data.startswith(b"PK"):
|
||||
from openpyxl import load_workbook
|
||||
|
||||
wb = load_workbook(io.BytesIO(data), data_only=True, read_only=True)
|
||||
return _rows_to_dicts(list(wb.active.iter_rows(values_only=True)))
|
||||
|
||||
if data.startswith(b"\xd0\xcf\x11\xe0"):
|
||||
raise AppError("暂不支持旧版 .xls,请另存为 .xlsx 或 .csv 后重新上传", "unsupported_file")
|
||||
|
||||
text = None
|
||||
for encoding in ("utf-8-sig", "gb18030"):
|
||||
try:
|
||||
text = data.decode(encoding)
|
||||
break
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
if text is None:
|
||||
raise AppError("无法识别文件编码,请使用 UTF-8 编码的 CSV 或 .xlsx", "unsupported_file")
|
||||
return _rows_to_dicts(list(csv.reader(io.StringIO(text))))
|
||||
|
|
|
|||
|
|
@ -257,7 +257,11 @@ async def grant_benefits(payload: GrantPayload, session: Session,
|
|||
auth: Annotated[AuthContext, Depends(require_perm("benefits:record:grant"))]):
|
||||
item = await session.get(BenefitItem, payload.item_id)
|
||||
ensure(item is not None, "福利项目不存在")
|
||||
stmt = select(Employee).where(Employee.status.in_(["probation", "active", "leave"]))
|
||||
# 停用档案不参与批量发放
|
||||
stmt = select(Employee).where(
|
||||
Employee.status.in_(["probation", "active", "leave"]),
|
||||
Employee.is_active.is_(True),
|
||||
)
|
||||
if payload.department_ids:
|
||||
collected: list[int] = []
|
||||
for dept_id in payload.department_ids:
|
||||
|
|
@ -404,7 +408,11 @@ async def generate_balances(payload: GenerateBalancePayload, session: Session,
|
|||
types = list((await session.execute(type_stmt)).scalars().all())
|
||||
if not types:
|
||||
raise AppError("没有可用的假期类型", "empty")
|
||||
emp_stmt = select(Employee).where(Employee.status.in_(["probation", "active"]))
|
||||
# 停用档案不再生成假期额度
|
||||
emp_stmt = select(Employee).where(
|
||||
Employee.status.in_(["probation", "active"]),
|
||||
Employee.is_active.is_(True),
|
||||
)
|
||||
if payload.department_ids:
|
||||
collected: list[int] = []
|
||||
for dept_id in payload.department_ids:
|
||||
|
|
|
|||
|
|
@ -174,12 +174,23 @@ async def dict_types(session: Session, auth: AuthCtx):
|
|||
|
||||
# ------------------------------------------------------------ 聚合下拉选项 ----
|
||||
async def _model_options(session, model, label_attr: str = "name",
|
||||
only_active: bool = True) -> list[dict]:
|
||||
only_active: bool = False) -> list[dict]:
|
||||
"""聚合下拉选项。
|
||||
|
||||
停用的资源**照样返回**并带上 ``extra.is_active``:历史数据(如员工所属部门)
|
||||
仍要能解析出名称,但前端会把它标成不可选,避免新记录继续挂到停用资源上。
|
||||
"""
|
||||
stmt = select(model)
|
||||
if only_active and hasattr(model, "is_active"):
|
||||
stmt = stmt.where(model.is_active.is_(True))
|
||||
rows = list((await session.execute(stmt.order_by(getattr(model, "id")))).scalars().all())
|
||||
return [{"id": r.id, "label": getattr(r, label_attr)} for r in rows]
|
||||
out: list[dict] = []
|
||||
for r in rows:
|
||||
item = {"id": r.id, "label": getattr(r, label_attr)}
|
||||
if hasattr(r, "is_active"):
|
||||
item["extra"] = {"is_active": bool(r.is_active)}
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/options", summary="聚合下拉选项")
|
||||
|
|
|
|||
|
|
@ -117,8 +117,18 @@ def _derive(emp: Employee) -> None:
|
|||
|
||||
async def decorate(session, rows: list[Employee]) -> None:
|
||||
await attach_labels(session, rows, LABEL_SPECS)
|
||||
# 是否已开通登录账号:列表 / 下拉都要用,避免 HR 重复给同一个档案建号
|
||||
ids = [row.id for row in rows]
|
||||
accounted: set[int] = set()
|
||||
if ids:
|
||||
accounted = set(
|
||||
(await session.execute(
|
||||
select(User.employee_id).where(User.employee_id.in_(ids))
|
||||
)).scalars().all()
|
||||
)
|
||||
for row in rows:
|
||||
_derive(row)
|
||||
row.__dict__["has_account"] = row.id in accounted
|
||||
|
||||
|
||||
def _as_date(value):
|
||||
|
|
@ -180,23 +190,39 @@ async def employee_before(action, data, obj, auth, session):
|
|||
if field in data:
|
||||
await _unique(session, field, data[field], obj.id if obj else None, label)
|
||||
await _unique(session, "work_no", data.get("work_no"), obj.id if obj else None, "工号")
|
||||
# 记录本次是否「显式」切换启停:离职收尾等联动会把 is_active 置回 False,
|
||||
# 若不记下用户的显式意图,停用后的档案就永远无法重新启用。
|
||||
if "is_active" in data:
|
||||
auth.__dict__["_employee_is_active_written"] = bool(data["is_active"])
|
||||
return data
|
||||
|
||||
|
||||
async def employee_after_write(action, obj, auth, session):
|
||||
"""花名册写入后的生命周期连带动作:入职建档 / 离职收尾 / 数据自愈。"""
|
||||
from ...services.lifecycle import close_resignation, onboard_employee
|
||||
"""花名册写入后的生命周期连带动作:入职建档 / 离职收尾 / 启停联动。
|
||||
|
||||
``is_active`` 是全站唯一的业务启停位(``status`` 只表达在职生命周期),
|
||||
因此这里必须尊重调用方显式写入的启停值:否则停用过的档案一旦被离职收尾
|
||||
之类联动改回 False,就永远再也启用不了。
|
||||
"""
|
||||
from ...services.lifecycle import close_resignation, onboard_employee, set_account_state
|
||||
|
||||
if not isinstance(obj, Employee):
|
||||
return
|
||||
actor = getattr(getattr(auth, "user", None), "name", None)
|
||||
explicit = auth.__dict__.pop("_employee_is_active_written", None)
|
||||
if obj.status == "resigned":
|
||||
if obj.leave_date is None:
|
||||
obj.leave_date = date.today()
|
||||
await close_resignation(session, obj, obj.leave_date)
|
||||
if explicit is not None:
|
||||
obj.is_active = explicit
|
||||
return
|
||||
if obj.is_active or obj.status in ("probation", "active", "leave"):
|
||||
await onboard_employee(session, obj, signed_by=actor)
|
||||
if explicit is not None:
|
||||
obj.is_active = explicit
|
||||
# 停用档案 => 绑定的登录账号一并停用;重新启用 => 恢复这批账号
|
||||
await set_account_state(session, obj, explicit)
|
||||
|
||||
|
||||
async def employee_on_delete(obj, auth, session):
|
||||
|
|
@ -272,23 +298,41 @@ EXPORT_COLUMNS = [
|
|||
("职级", None), ("用工形式", "engage_form"), ("手机号", "phone"), ("邮箱", "email"),
|
||||
("身份证号", "id_card"), ("学历", "highest_degree"), ("毕业院校", "school"),
|
||||
("入职日期", "hire_date"), ("转正日期", "regular_date"), ("离职日期", "leave_date"),
|
||||
("员工状态", None), ("合同起止", None), ("民族", "nation"), ("政治面貌", "political_status"),
|
||||
("员工状态", None), ("档案状态", None), ("登录账号", None),
|
||||
("合同起止", None), ("民族", "nation"), ("政治面貌", "political_status"),
|
||||
("籍贯", "native_place"), ("婚姻状况", "marital_status"), ("紧急联系人", "emergency_contact"),
|
||||
]
|
||||
|
||||
|
||||
async def _employee_filter_hook(stmt, filters: dict, session) -> Any:
|
||||
"""``?has_account=true|false`` —— 账号不是员工表字段,用 sys_user 子查询过滤。"""
|
||||
raw = str(filters.get("has_account") or "").strip().lower()
|
||||
if raw in ("1", "true", "yes", "on"):
|
||||
return stmt.where(Employee.id.in_(select(User.employee_id).where(User.employee_id.is_not(None))))
|
||||
if raw in ("0", "false", "no", "off"):
|
||||
return stmt.where(Employee.id.notin_(select(User.employee_id).where(User.employee_id.is_not(None))))
|
||||
return stmt
|
||||
|
||||
|
||||
@extra.get("/export", summary="导出花名册")
|
||||
async def export_roster(session: Session,
|
||||
auth: Annotated[AuthContext, Depends(require_perm("employee:employee:export"))],
|
||||
status: str | None = Query(None), department_id: str | None = Query(None),
|
||||
dept_subtree: str | None = Query("1"), keyword: str | None = Query(None),
|
||||
engage_form: str | None = Query(None)):
|
||||
engage_form: str | None = Query(None), is_active: str | None = Query(None),
|
||||
has_account: str | None = Query(None)):
|
||||
"""导出与列表共用筛选语义:多值逗号分隔,部门默认含下级。"""
|
||||
stmt = select(Employee)
|
||||
if status:
|
||||
stmt = stmt.where(_multi_cond(Employee.status, _split_multi(status)))
|
||||
if engage_form:
|
||||
stmt = stmt.where(_multi_cond(Employee.engage_form, _split_multi(engage_form)))
|
||||
active_value = str(is_active or "").strip().lower()
|
||||
if active_value in ("1", "true", "yes", "on"):
|
||||
stmt = stmt.where(Employee.is_active.is_(True))
|
||||
elif active_value in ("0", "false", "no", "off"):
|
||||
stmt = stmt.where(Employee.is_active.is_(False))
|
||||
stmt = await _employee_filter_hook(stmt, {"has_account": has_account}, session)
|
||||
if department_id:
|
||||
ids: list[int] = []
|
||||
expand = str(dept_subtree or "1").strip().lower() not in ("0", "false", "no", "off")
|
||||
|
|
@ -306,6 +350,7 @@ async def export_roster(session: Session,
|
|||
e.work_no, e.name, gender_label(e.gender), e.department_name, e.position_name, e.job_level_name,
|
||||
e.engage_form, e.phone, e.email, e.id_card, e.highest_degree, e.school,
|
||||
e.hire_date, e.regular_date, e.leave_date, STATUS_LABELS.get(e.status, e.status),
|
||||
"启用" if e.is_active else "停用", "已开通" if e.has_account else "未开通",
|
||||
f"{e.contract_start or ''} ~ {e.contract_end or ''}", e.nation, e.political_status,
|
||||
e.native_place, e.marital_status, e.emergency_contact,
|
||||
])
|
||||
|
|
@ -407,6 +452,7 @@ router.include_router(build_router(CrudSpec(
|
|||
search_fields=("name", "work_no", "phone", "email", "id_card"),
|
||||
filters=("department_id", "position_id", "job_level_id", "status", "engage_form",
|
||||
"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,
|
||||
after_read=decorate, after_write=employee_after_write, on_delete=employee_on_delete,
|
||||
|
|
|
|||
|
|
@ -2,14 +2,17 @@
|
|||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Annotated
|
||||
from datetime import date
|
||||
from typing import Annotated, Any
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from fastapi import APIRouter, Depends, File, Query, UploadFile
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from ...core.deps import AuthContext, AuthCtx, Session, require_perm
|
||||
from ...core.errors import AppError
|
||||
from ...schemas.employee import ImportResult
|
||||
from ..crud import CrudSpec, build_router
|
||||
from ..helpers import parse_xlsx, xlsx_response
|
||||
from ...models.employee import Employee
|
||||
from ...models.org import Department, DictItem, DictType, JobLevel, Position
|
||||
from ...schemas.org import (
|
||||
|
|
@ -82,6 +85,66 @@ async def _dept_delete(obj, auth, session):
|
|||
raise AppError(f"该部门还有 {staff} 名在职员工,无法删除", "has_employees")
|
||||
|
||||
|
||||
def _txt(value: Any) -> str:
|
||||
return "" if value is None else str(value).strip()
|
||||
|
||||
|
||||
def _flag(value: Any, default: bool = True) -> bool:
|
||||
text = _txt(value).lower()
|
||||
if not text:
|
||||
return default
|
||||
if text in ("是", "启用", "1", "true", "yes", "y", "on"):
|
||||
return True
|
||||
if text in ("否", "停用", "0", "false", "no", "n", "off"):
|
||||
return False
|
||||
raise ValueError(f"无法识别的启用状态:{value}")
|
||||
|
||||
|
||||
def _int(value: Any, default: int = 0) -> int:
|
||||
text = _txt(value)
|
||||
if not text:
|
||||
return default
|
||||
try:
|
||||
return int(float(text))
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"不是合法数字:{value}") from exc
|
||||
|
||||
|
||||
def _fail(result: ImportResult, row: int, name: Any, exc: Exception) -> None:
|
||||
result.failed += 1
|
||||
result.errors.append({"row": row, "name": _txt(name), "message": str(exc)})
|
||||
|
||||
|
||||
async def _rebuild_department_paths(session) -> None:
|
||||
"""导入后统一重算 dep_path / level / is_parent,保证树结构自洽。"""
|
||||
rows = list((await session.execute(select(Department))).scalars().all())
|
||||
by_id = {d.id: d for d in rows}
|
||||
children: dict[int, list[Department]] = {}
|
||||
for dept in rows:
|
||||
parent_id = dept.parent_id or 0
|
||||
if parent_id and parent_id not in by_id:
|
||||
dept.parent_id, parent_id = 0, 0
|
||||
children.setdefault(parent_id, []).append(dept)
|
||||
for kids in children.values():
|
||||
kids.sort(key=lambda d: (d.sort or 0, d.id))
|
||||
|
||||
visited: set[int] = set()
|
||||
|
||||
def walk(parent_id: int, parent_path: str, level: int) -> None:
|
||||
for node in children.get(parent_id, []):
|
||||
if node.id in visited:
|
||||
raise AppError("部门层级存在循环引用,请检查上级部门", "bad_parent")
|
||||
visited.add(node.id)
|
||||
node.dep_path = f"{parent_path}.{node.id}" if parent_path else ".0"
|
||||
node.level = level
|
||||
node.is_parent = bool(children.get(node.id))
|
||||
walk(node.id, node.dep_path, level + 1)
|
||||
|
||||
walk(0, "", 1)
|
||||
if len(visited) != len(rows):
|
||||
raise AppError("部门层级存在循环引用,请检查上级部门", "bad_parent")
|
||||
|
||||
|
||||
departments_custom = APIRouter()
|
||||
|
||||
|
||||
|
|
@ -127,6 +190,144 @@ async def department_tree(session: Session, auth: AuthCtx, only_active: bool = Q
|
|||
return roots
|
||||
|
||||
|
||||
DEPT_HEADERS = ["部门编码", "部门名称", "上级部门编码", "部门负责人工号", "成本中心",
|
||||
"排序", "是否启用", "备注"]
|
||||
|
||||
|
||||
@departments_custom.get("/export", summary="导出部门")
|
||||
async def export_departments(
|
||||
session: Session,
|
||||
auth: Annotated[AuthContext, Depends(require_perm("org:department:export"))],
|
||||
):
|
||||
rows = list((await session.execute(
|
||||
select(Department).order_by(Department.level, Department.sort, Department.id)
|
||||
)).scalars().all())
|
||||
names = {d.id: d.name for d in rows}
|
||||
codes = {d.id: d.code or "" for d in rows}
|
||||
emp_rows = (await session.execute(select(Employee.id, Employee.work_no))).all()
|
||||
work_nos = {row[0]: row[1] for row in emp_rows}
|
||||
data = [[
|
||||
d.code, d.name, codes.get(d.parent_id, ""), work_nos.get(d.leader_employee_id, ""),
|
||||
d.cost_center, d.sort, "是" if d.is_active else "否", d.remark, d.level,
|
||||
] for d in rows]
|
||||
return xlsx_response([*DEPT_HEADERS, "层级"], data, f"组织架构_部门_{date.today()}.xlsx")
|
||||
|
||||
|
||||
@departments_custom.get("/import-template", summary="部门导入模板")
|
||||
async def department_import_template(
|
||||
auth: Annotated[AuthContext, Depends(require_perm("org:department:import"))],
|
||||
):
|
||||
sample = [
|
||||
["D001", "研发中心", "", "", "CC-1001", 10, "是", "一级部门"],
|
||||
["D002", "后端组", "D001", "", "CC-1002", 10, "是", "填上级部门编码即可挂在研发中心下"],
|
||||
]
|
||||
return xlsx_response(DEPT_HEADERS, sample, "组织架构_部门导入模板.xlsx")
|
||||
|
||||
|
||||
@departments_custom.post("/import", response_model=ImportResult, summary="导入部门")
|
||||
async def import_departments(
|
||||
session: Session,
|
||||
auth: Annotated[AuthContext, Depends(require_perm("org:department:import"))],
|
||||
file: UploadFile = File(...),
|
||||
):
|
||||
"""按「部门编码」优先、否则「部门名称」匹配:存在则更新,不存在则新建。
|
||||
|
||||
支持先写子部门再写上级:所有行先落库,再统一解析上级并重算树路径。
|
||||
"""
|
||||
raw_rows = parse_xlsx(await file.read())
|
||||
result = ImportResult(total=len(raw_rows), created=0, updated=0, failed=0)
|
||||
if not raw_rows:
|
||||
raise AppError("导入文件为空或没有数据行", "empty_file")
|
||||
|
||||
existing = list((await session.execute(select(Department))).scalars().all())
|
||||
by_code = {d.code: d for d in existing if d.code}
|
||||
by_name = {d.name: d for d in existing}
|
||||
emp_rows = (await session.execute(select(Employee.id, Employee.work_no, Employee.name))).all()
|
||||
emp_by_no = {row[1]: row[0] for row in emp_rows if row[1]}
|
||||
emp_by_name = {row[2]: row[0] for row in emp_rows if row[2]}
|
||||
|
||||
parsed: list[dict[str, Any]] = []
|
||||
seen_codes: set[str] = set()
|
||||
# 先扫一遍文件里的编码/名称,允许「子部门写在上级之前」
|
||||
known_refs = set(by_code) | set(by_name)
|
||||
for raw in raw_rows:
|
||||
for key in ("部门编码", "编码", "部门名称", "名称"):
|
||||
value = _txt(raw.get(key))
|
||||
if value:
|
||||
known_refs.add(value)
|
||||
for idx, raw in enumerate(raw_rows, start=2):
|
||||
try:
|
||||
name = _txt(raw.get("部门名称") or raw.get("名称"))
|
||||
code = _txt(raw.get("部门编码") or raw.get("编码"))
|
||||
if not name:
|
||||
raise ValueError("部门名称为空")
|
||||
if code:
|
||||
if code in seen_codes:
|
||||
raise ValueError(f"文件内部门编码重复:{code}")
|
||||
seen_codes.add(code)
|
||||
parent_ref = _txt(raw.get("上级部门编码") or raw.get("上级部门"))
|
||||
if parent_ref and parent_ref not in known_refs:
|
||||
raise ValueError(f"上级部门不存在:{parent_ref}")
|
||||
leader_ref = _txt(raw.get("部门负责人工号") or raw.get("部门负责人"))
|
||||
if leader_ref and leader_ref not in emp_by_no and leader_ref not in emp_by_name:
|
||||
raise ValueError(f"部门负责人不存在:{leader_ref}")
|
||||
parsed.append({
|
||||
"row": idx, "name": name, "code": code, "parent_ref": parent_ref,
|
||||
"leader_ref": leader_ref,
|
||||
"cost_center": _txt(raw.get("成本中心")) or None,
|
||||
"sort": _int(raw.get("排序"), 0),
|
||||
"is_active": _flag(raw.get("是否启用"), True),
|
||||
"remark": _txt(raw.get("备注")) or None,
|
||||
})
|
||||
known_refs.add(name)
|
||||
if code:
|
||||
known_refs.add(code)
|
||||
except Exception as exc: # noqa: BLE001 - 逐行汇总失败原因
|
||||
_fail(result, idx, raw.get("部门名称"), exc)
|
||||
|
||||
for item in parsed:
|
||||
dept = by_code.get(item["code"]) if item["code"] else by_name.get(item["name"])
|
||||
if dept is None:
|
||||
dept = Department(name=item["name"], code=item["code"] or None, parent_id=0)
|
||||
session.add(dept)
|
||||
result.created += 1
|
||||
else:
|
||||
result.updated += 1
|
||||
dept.name = item["name"]
|
||||
if item["code"]:
|
||||
dept.code = item["code"]
|
||||
dept.cost_center = item["cost_center"]
|
||||
dept.sort = item["sort"]
|
||||
dept.is_active = item["is_active"]
|
||||
dept.remark = item["remark"]
|
||||
item["dept"] = dept
|
||||
by_name[dept.name] = dept
|
||||
if dept.code:
|
||||
by_code[dept.code] = dept
|
||||
|
||||
await session.flush()
|
||||
|
||||
for item in parsed:
|
||||
dept: Department = item["dept"]
|
||||
dept.parent_id = 0
|
||||
if item["parent_ref"]:
|
||||
parent = by_code.get(item["parent_ref"]) or by_name.get(item["parent_ref"])
|
||||
if parent and parent.id != dept.id:
|
||||
dept.parent_id = parent.id
|
||||
dept.leader_employee_id = (
|
||||
emp_by_no.get(item["leader_ref"]) or emp_by_name.get(item["leader_ref"])
|
||||
if item["leader_ref"] else None
|
||||
)
|
||||
await session.flush()
|
||||
try:
|
||||
await _rebuild_department_paths(session)
|
||||
except AppError:
|
||||
await session.rollback()
|
||||
raise
|
||||
await session.commit()
|
||||
return result
|
||||
|
||||
|
||||
router.include_router(build_router(
|
||||
CrudSpec(
|
||||
model=Department, create=DepartmentCreate, update=DepartmentUpdate, read=DepartmentRead,
|
||||
|
|
@ -138,16 +339,159 @@ router.include_router(build_router(
|
|||
preface=[departments_custom],
|
||||
))
|
||||
|
||||
positions_custom = APIRouter()
|
||||
|
||||
POSITION_HEADERS = ["职位编码", "职位名称", "职务序列", "排序", "是否启用", "备注"]
|
||||
|
||||
|
||||
@positions_custom.get("/export", summary="导出职位")
|
||||
async def export_positions(
|
||||
session: Session,
|
||||
auth: Annotated[AuthContext, Depends(require_perm("org:position:export"))],
|
||||
):
|
||||
rows = list((await session.execute(
|
||||
select(Position).order_by(Position.sort, Position.id)
|
||||
)).scalars().all())
|
||||
data = [[p.code, p.name, p.category, p.sort, "是" if p.is_active else "否", p.remark]
|
||||
for p in rows]
|
||||
return xlsx_response(POSITION_HEADERS, data, f"组织架构_职位_{date.today()}.xlsx")
|
||||
|
||||
|
||||
@positions_custom.get("/import-template", summary="职位导入模板")
|
||||
async def position_import_template(
|
||||
auth: Annotated[AuthContext, Depends(require_perm("org:position:import"))],
|
||||
):
|
||||
sample = [["P001", "后端工程师", "技术序列", 10, "是", "示例行,可删除"]]
|
||||
return xlsx_response(POSITION_HEADERS, sample, "组织架构_职位导入模板.xlsx")
|
||||
|
||||
|
||||
@positions_custom.post("/import", response_model=ImportResult, summary="导入职位")
|
||||
async def import_positions(
|
||||
session: Session,
|
||||
auth: Annotated[AuthContext, Depends(require_perm("org:position:import"))],
|
||||
file: UploadFile = File(...),
|
||||
):
|
||||
raw_rows = parse_xlsx(await file.read())
|
||||
result = ImportResult(total=len(raw_rows), created=0, updated=0, failed=0)
|
||||
if not raw_rows:
|
||||
raise AppError("导入文件为空或没有数据行", "empty_file")
|
||||
existing = list((await session.execute(select(Position))).scalars().all())
|
||||
by_code = {p.code: p for p in existing if p.code}
|
||||
by_name = {p.name: p for p in existing}
|
||||
seen_codes: set[str] = set()
|
||||
for idx, raw in enumerate(raw_rows, start=2):
|
||||
try:
|
||||
name = _txt(raw.get("职位名称") or raw.get("名称"))
|
||||
code = _txt(raw.get("职位编码") or raw.get("编码"))
|
||||
if not name:
|
||||
raise ValueError("职位名称为空")
|
||||
if code and code in seen_codes:
|
||||
raise ValueError(f"文件内职位编码重复:{code}")
|
||||
if code:
|
||||
seen_codes.add(code)
|
||||
row = by_code.get(code) if code else by_name.get(name)
|
||||
if row is None:
|
||||
row = Position(name=name, code=code or None)
|
||||
session.add(row)
|
||||
result.created += 1
|
||||
else:
|
||||
result.updated += 1
|
||||
row.name = name
|
||||
if code:
|
||||
row.code = code
|
||||
row.category = _txt(raw.get("职务序列")) or None
|
||||
row.sort = _int(raw.get("排序"), 0)
|
||||
row.is_active = _flag(raw.get("是否启用"), True)
|
||||
row.remark = _txt(raw.get("备注")) or None
|
||||
by_name[row.name] = row
|
||||
if row.code:
|
||||
by_code[row.code] = row
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_fail(result, idx, raw.get("职位名称"), exc)
|
||||
await session.commit()
|
||||
return result
|
||||
|
||||
|
||||
router.include_router(build_router(CrudSpec(
|
||||
model=Position, create=PositionCreate, update=PositionUpdate, read=PositionRead,
|
||||
module="org", resource="position", label="职位", prefix="/positions", tag="组织架构",
|
||||
search_fields=("name", "code"), filters=("is_active", "category"),
|
||||
order_by="sort", order="asc",
|
||||
)))
|
||||
), preface=[positions_custom]))
|
||||
|
||||
|
||||
job_levels_custom = APIRouter()
|
||||
|
||||
JOBLEVEL_HEADERS = ["职级编码", "职级名称", "职等", "排序", "是否启用", "备注"]
|
||||
|
||||
|
||||
@job_levels_custom.get("/export", summary="导出职级")
|
||||
async def export_job_levels(
|
||||
session: Session,
|
||||
auth: Annotated[AuthContext, Depends(require_perm("org:joblevel:export"))],
|
||||
):
|
||||
rows = list((await session.execute(
|
||||
select(JobLevel).order_by(JobLevel.grade, JobLevel.sort, JobLevel.id)
|
||||
)).scalars().all())
|
||||
data = [[j.code, j.name, j.grade, j.sort, "是" if j.is_active else "否", j.remark]
|
||||
for j in rows]
|
||||
return xlsx_response(JOBLEVEL_HEADERS, data, f"组织架构_职级_{date.today()}.xlsx")
|
||||
|
||||
|
||||
@job_levels_custom.get("/import-template", summary="职级导入模板")
|
||||
async def job_level_import_template(
|
||||
auth: Annotated[AuthContext, Depends(require_perm("org:joblevel:import"))],
|
||||
):
|
||||
sample = [["L001", "P5", 5, 10, "是", "示例行,可删除"]]
|
||||
return xlsx_response(JOBLEVEL_HEADERS, sample, "组织架构_职级导入模板.xlsx")
|
||||
|
||||
|
||||
@job_levels_custom.post("/import", response_model=ImportResult, summary="导入职级")
|
||||
async def import_job_levels(
|
||||
session: Session,
|
||||
auth: Annotated[AuthContext, Depends(require_perm("org:joblevel:import"))],
|
||||
file: UploadFile = File(...),
|
||||
):
|
||||
raw_rows = parse_xlsx(await file.read())
|
||||
result = ImportResult(total=len(raw_rows), created=0, updated=0, failed=0)
|
||||
if not raw_rows:
|
||||
raise AppError("导入文件为空或没有数据行", "empty_file")
|
||||
existing = list((await session.execute(select(JobLevel))).scalars().all())
|
||||
by_code = {j.code: j for j in existing if j.code}
|
||||
by_name = {j.name: j for j in existing}
|
||||
seen_codes: set[str] = set()
|
||||
for idx, raw in enumerate(raw_rows, start=2):
|
||||
try:
|
||||
name = _txt(raw.get("职级名称") or raw.get("名称"))
|
||||
code = _txt(raw.get("职级编码") or raw.get("编码"))
|
||||
if not name:
|
||||
raise ValueError("职级名称为空")
|
||||
if code and code in seen_codes:
|
||||
raise ValueError(f"文件内职级编码重复:{code}")
|
||||
if code:
|
||||
seen_codes.add(code)
|
||||
row = by_code.get(code) if code else by_name.get(name)
|
||||
if row is None:
|
||||
row = JobLevel(name=name, code=code or None)
|
||||
session.add(row)
|
||||
result.created += 1
|
||||
else:
|
||||
result.updated += 1
|
||||
row.name = name
|
||||
if code:
|
||||
row.code = code
|
||||
row.grade = _int(raw.get("职等"), 1)
|
||||
row.sort = _int(raw.get("排序"), 0)
|
||||
row.is_active = _flag(raw.get("是否启用"), True)
|
||||
row.remark = _txt(raw.get("备注")) or None
|
||||
by_name[row.name] = row
|
||||
if row.code:
|
||||
by_code[row.code] = row
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_fail(result, idx, raw.get("职级名称"), exc)
|
||||
await session.commit()
|
||||
return result
|
||||
|
||||
|
||||
@job_levels_custom.get(
|
||||
"/{item_id:int}/expense-standards",
|
||||
|
|
|
|||
|
|
@ -2,16 +2,19 @@
|
|||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import delete, func, select, update
|
||||
|
||||
from ...core.deps import AuthContext, Session, get_auth_context, require_perm
|
||||
from ...core.deps import AuthContext, Session, apply_employee_scope, get_auth_context, require_perm
|
||||
from ...core.errors import AppError
|
||||
from ...core.permissions import MODULES
|
||||
from ...core.security import hash_password
|
||||
from ..crud import CrudSpec, build_router
|
||||
from ...models.employee import Employee
|
||||
from ...models.rbac import (
|
||||
Announcement, Menu, Notification, OperationLog, Permission,
|
||||
RefreshToken, Role, RolePermission, User, UserRole,
|
||||
|
|
@ -186,6 +189,92 @@ user_router = build_router(
|
|||
)
|
||||
|
||||
|
||||
class GenerateAccountsPayload(BaseModel):
|
||||
employee_ids: list[int] = Field(min_length=1)
|
||||
role_ids: list[int] = Field(min_length=1)
|
||||
password: str = Field(default="Hrms@123456", min_length=6, max_length=64)
|
||||
|
||||
|
||||
@user_router.post("/from-employees", summary="根据员工档案批量生成账号")
|
||||
async def generate_accounts_from_employees(
|
||||
payload: GenerateAccountsPayload,
|
||||
session: Session,
|
||||
auth: Annotated[AuthContext, Depends(require_perm("system:user:create"))],
|
||||
):
|
||||
"""按工号生成登录账号:一个员工档案最多绑定一个账号。
|
||||
|
||||
已绑定账号的档案会跳过并返回原因;账号名冲突时自动追加序号。
|
||||
"""
|
||||
role_ids = sorted({int(rid) for rid in payload.role_ids})
|
||||
roles = (await session.execute(select(Role).where(Role.id.in_(role_ids)))).scalars().all()
|
||||
if len(roles) != len(role_ids):
|
||||
raise AppError("包含不存在的角色", "bad_role")
|
||||
if any(not role.is_active for role in roles):
|
||||
raise AppError("不能分配已停用的角色", "bad_role")
|
||||
if not auth.user.is_superuser and any(role.code == "super_admin" for role in roles):
|
||||
raise AppError("只有超级管理员可以分配超级管理员角色", "forbidden", 403)
|
||||
role_map = {role.id: role for role in roles}
|
||||
roles = [role_map[rid] for rid in role_ids]
|
||||
|
||||
employee_ids = sorted({int(eid) for eid in payload.employee_ids})
|
||||
employee_stmt = select(Employee).where(Employee.id.in_(employee_ids))
|
||||
employee_stmt = await apply_employee_scope(session, employee_stmt, auth, Employee.id)
|
||||
employees = list((await session.execute(employee_stmt)).scalars().all())
|
||||
if len(employees) != len(employee_ids):
|
||||
raise AppError("包含不存在的员工档案", "not_found", 404)
|
||||
|
||||
linked = {
|
||||
row[0]: row[1] for row in (
|
||||
await session.execute(
|
||||
select(User.employee_id, User.username).where(User.employee_id.in_(employee_ids))
|
||||
)
|
||||
).all()
|
||||
}
|
||||
usernames = {
|
||||
username.casefold()
|
||||
for username in (await session.execute(select(User.username))).scalars().all()
|
||||
}
|
||||
created: list[dict] = []
|
||||
skipped: list[dict] = []
|
||||
|
||||
for emp in sorted(employees, key=lambda e: e.id):
|
||||
if emp.id in linked:
|
||||
skipped.append({"employee_id": emp.id, "name": emp.name,
|
||||
"reason": f"已绑定账号 {linked[emp.id]}"})
|
||||
continue
|
||||
if emp.status == "resigned":
|
||||
skipped.append({"employee_id": emp.id, "name": emp.name, "reason": "员工已离职"})
|
||||
continue
|
||||
if not emp.is_active:
|
||||
skipped.append({"employee_id": emp.id, "name": emp.name, "reason": "档案已停用"})
|
||||
continue
|
||||
base = (emp.work_no or f"emp{emp.id:05d}").strip().lower().replace(" ", "") or f"emp{emp.id:05d}"
|
||||
username, suffix = base, 2
|
||||
while username.casefold() in usernames:
|
||||
username = f"{base}{suffix}"
|
||||
suffix += 1
|
||||
usernames.add(username.casefold())
|
||||
user = User(
|
||||
username=username, password_hash=hash_password(payload.password),
|
||||
name=emp.name, email=emp.email, phone=emp.phone, employee_id=emp.id,
|
||||
is_active=bool(emp.is_active), is_superuser=False, remark="由员工档案生成",
|
||||
)
|
||||
session.add(user)
|
||||
await session.flush()
|
||||
for rid in role_ids:
|
||||
session.add(UserRole(user_id=user.id, role_id=rid))
|
||||
created.append({"employee_id": emp.id, "name": emp.name, "username": username})
|
||||
|
||||
await session.commit()
|
||||
return {
|
||||
"message": f"已生成 {len(created)} 个账号" + (f",跳过 {len(skipped)} 个" if skipped else ""),
|
||||
"created": created,
|
||||
"skipped": skipped,
|
||||
"password": payload.password,
|
||||
"roles": [role.name for role in roles],
|
||||
}
|
||||
|
||||
|
||||
@user_router.post("/{item_id}/roles", response_model=Message, summary="分配角色")
|
||||
async def assign_roles(
|
||||
item_id: int, payload: AssignRolesPayload, session: Session,
|
||||
|
|
@ -369,3 +458,91 @@ router.include_router(build_router(CrudSpec(
|
|||
date_range_fields=("created_at",), order_by="created_at", order="desc",
|
||||
write=False, deletable=False, options=False,
|
||||
)))
|
||||
|
||||
|
||||
# --------------------------------------------------------------- 数据维护 ----
|
||||
class PurgePayload(BaseModel):
|
||||
"""破坏性操作必须手打确认短语,避免误点。"""
|
||||
|
||||
confirm: str
|
||||
keep_username: str | None = None
|
||||
|
||||
|
||||
PURGE_PHRASE = "unis_hrms"
|
||||
|
||||
maintenance_router = APIRouter()
|
||||
|
||||
|
||||
def _download(data: bytes, filename: str, media_type: str):
|
||||
from urllib.parse import quote
|
||||
|
||||
from fastapi.responses import StreamingResponse
|
||||
import io
|
||||
|
||||
return StreamingResponse(
|
||||
io.BytesIO(data),
|
||||
media_type=media_type,
|
||||
headers={"Content-Disposition": f"attachment; filename*=UTF-8''{quote(filename)}"},
|
||||
)
|
||||
|
||||
|
||||
@maintenance_router.get("/overview", summary="数据概况")
|
||||
async def maintenance_overview(
|
||||
session: Session,
|
||||
auth: Annotated[AuthContext, Depends(require_perm("system:maintenance:read"))],
|
||||
):
|
||||
from ...services import maintenance
|
||||
|
||||
return await maintenance.overview(session)
|
||||
|
||||
|
||||
@maintenance_router.get("/backup", summary="一键备份(下载 zip)")
|
||||
async def maintenance_backup(
|
||||
session: Session,
|
||||
auth: Annotated[AuthContext, Depends(require_perm("system:maintenance:backup"))],
|
||||
):
|
||||
from ...services import maintenance
|
||||
|
||||
data = await maintenance.build_backup_zip(session)
|
||||
stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
|
||||
return _download(data, f"UNIS-HRMS-备份-{stamp}.zip", "application/zip")
|
||||
|
||||
|
||||
@maintenance_router.get("/export", summary="导出全部数据(Excel)")
|
||||
async def maintenance_export(
|
||||
session: Session,
|
||||
auth: Annotated[AuthContext, Depends(require_perm("system:maintenance:export"))],
|
||||
):
|
||||
from ...services import maintenance
|
||||
|
||||
data = await maintenance.build_export_workbook(session)
|
||||
stamp = datetime.now().strftime("%Y%m%d")
|
||||
return _download(
|
||||
data, f"UNIS-HRMS-数据导出-{stamp}.xlsx",
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
|
||||
|
||||
@maintenance_router.post("/purge", summary="清空全部业务数据(仅保留系统管理员)")
|
||||
async def maintenance_purge(
|
||||
payload: PurgePayload,
|
||||
session: Session,
|
||||
auth: Annotated[AuthContext, Depends(require_perm("system:maintenance:purge"))],
|
||||
):
|
||||
from ...services import maintenance
|
||||
|
||||
if not auth.user.is_superuser:
|
||||
raise AppError("只有超级管理员可以清空数据", "forbidden", 403)
|
||||
if payload.confirm.strip() != PURGE_PHRASE:
|
||||
raise AppError(f"请完整输入「{PURGE_PHRASE}」后再执行", "confirm_required")
|
||||
if payload.keep_username and payload.keep_username.strip() != auth.user.username:
|
||||
raise AppError("只能保留当前登录的系统管理员账号", "bad_keep_user")
|
||||
|
||||
result = await maintenance.purge_all_data(session)
|
||||
return {
|
||||
"message": f"已清空全部业务数据,保留 {len(result['kept_users'])} 个系统管理员账号",
|
||||
**result,
|
||||
}
|
||||
|
||||
|
||||
router.include_router(maintenance_router, prefix="/maintenance")
|
||||
|
|
|
|||
|
|
@ -21,15 +21,16 @@ MODULES: dict[str, dict] = {
|
|||
"dict": {"label": "数据字典", "actions": DEFAULT_ACTIONS},
|
||||
"announcement": {"label": "公告通知", "actions": [*DEFAULT_ACTIONS, "publish"]},
|
||||
"log": {"label": "操作日志", "actions": ["read"]},
|
||||
"maintenance": {"label": "数据维护", "actions": ["read", "backup", "export", "purge"]},
|
||||
},
|
||||
},
|
||||
"org": {
|
||||
"label": "组织架构",
|
||||
"icon": "ApartmentOutlined",
|
||||
"resources": {
|
||||
"department": {"label": "部门管理", "actions": DEFAULT_ACTIONS},
|
||||
"position": {"label": "职位管理", "actions": DEFAULT_ACTIONS},
|
||||
"joblevel": {"label": "职级职等", "actions": DEFAULT_ACTIONS},
|
||||
"department": {"label": "部门管理", "actions": [*DEFAULT_ACTIONS, "import", "export"]},
|
||||
"position": {"label": "职位管理", "actions": [*DEFAULT_ACTIONS, "import", "export"]},
|
||||
"joblevel": {"label": "职级职等", "actions": [*DEFAULT_ACTIONS, "import", "export"]},
|
||||
},
|
||||
},
|
||||
"employee": {
|
||||
|
|
@ -123,7 +124,7 @@ ACTION_LABELS = {
|
|||
"assign_role": "分配角色", "publish": "发布", "approve": "审批", "move": "流转阶段",
|
||||
"feedback": "面试评价", "send": "发送", "close": "关闭职位", "pool": "进入人才库",
|
||||
"calculate": "一键算薪", "pay": "发放", "grant": "批量发放", "remind": "到期提醒",
|
||||
"generate": "生成额度",
|
||||
"generate": "生成额度", "backup": "一键备份", "purge": "清空数据",
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -205,6 +206,7 @@ MENU_TREE: list[dict] = [
|
|||
{"name": "数据字典", "path": "/system/dicts", "icon": "BookOutlined", "perm": "system:dict:read"},
|
||||
{"name": "公告通知", "path": "/system/announcements", "icon": "NotificationOutlined", "perm": "system:announcement:read"},
|
||||
{"name": "操作日志", "path": "/system/logs", "icon": "HistoryOutlined", "perm": "system:log:read"},
|
||||
{"name": "数据维护", "path": "/system/maintenance", "icon": "DatabaseOutlined", "perm": "system:maintenance:read"},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ EMP_LABELS = {
|
|||
"job_level_name": str | None,
|
||||
"age": int | None,
|
||||
"tenure": str | None,
|
||||
"has_account": bool | None,
|
||||
}
|
||||
|
||||
# work_no 允许留空:后端 employee_before 会按 EMP##### 规则自动发号
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ from ..models.employee import (
|
|||
)
|
||||
from ..models.org import JobLevel
|
||||
from ..models.payroll import EmployeeSalary, Payslip as Payslip_, SalaryPlan
|
||||
from ..models.rbac import User
|
||||
from ..models.rbac import RefreshToken, User
|
||||
from ..models.recruitment import Candidate as Candidate_
|
||||
from ..models.selfservice import (ProfileRequest as ProfileRequest_,
|
||||
TaskReminder as TaskReminder_)
|
||||
|
|
@ -290,6 +290,35 @@ async def close_resignation(session, emp: Employee, leave_date: date | None = No
|
|||
return result
|
||||
|
||||
|
||||
# 档案停用(非离职)时给账号留下的备注标记:重新启用只恢复被它停用的账号,
|
||||
# 不会把 HR 手工停用的账号一起放出来。
|
||||
DEACTIVATED_MARK = "档案停用,账号停用"
|
||||
|
||||
|
||||
async def set_account_state(session, emp: Employee, active: bool) -> int:
|
||||
"""档案启停联动账号:停用档案 -> 停用其非超管账号;启用档案 -> 恢复由档案停用掉的账号。"""
|
||||
users = list((await session.execute(
|
||||
select(User).where(User.employee_id == emp.id, User.is_superuser.is_(False))
|
||||
)).scalars().all())
|
||||
changed = 0
|
||||
for user in users:
|
||||
if not active:
|
||||
if user.is_active:
|
||||
user.is_active = False
|
||||
user.remark = ((user.remark + ";") if user.remark else "") + DEACTIVATED_MARK
|
||||
await session.execute(sa_delete(RefreshToken).where(RefreshToken.user_id == user.id))
|
||||
changed += 1
|
||||
elif DEACTIVATED_MARK in (user.remark or ""):
|
||||
user.is_active = True
|
||||
user.remark = ";".join(
|
||||
seg for seg in (user.remark or "").split(";") if seg and seg != DEACTIVATED_MARK) or None
|
||||
await session.execute(sa_delete(RefreshToken).where(RefreshToken.user_id == user.id))
|
||||
changed += 1
|
||||
if changed:
|
||||
await session.flush()
|
||||
return changed
|
||||
|
||||
|
||||
async def reopen_active(session, emp: Employee) -> dict:
|
||||
"""复职/返聘:重新激活档案、续签合同、恢复薪资标准与参保。"""
|
||||
result = {"contracts": 0, "salary": 0, "enrollment": 0}
|
||||
|
|
@ -372,4 +401,5 @@ __all__ = [
|
|||
"onboard_employee",
|
||||
"purge_employee_records",
|
||||
"reopen_active",
|
||||
"set_account_state",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -0,0 +1,269 @@
|
|||
"""系统维护:全量备份、全量导出、清空业务数据。
|
||||
|
||||
三件事共用一份「表清单」——直接取 ``Base.metadata.sorted_tables``,
|
||||
新增模型不需要回来改这里,备份 / 导出 / 清理会自动覆盖。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
import tempfile
|
||||
import zipfile
|
||||
from datetime import date, datetime, time
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import delete, func, select, text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from ..core.config import settings
|
||||
from ..core.errors import AppError
|
||||
from ..db.base import Base
|
||||
from ..models.rbac import User, UserRole
|
||||
|
||||
# 清空数据后必须留存的「系统骨架」:管理员账号、角色权限、动态菜单与数据字典。
|
||||
KEEP_TABLES = {
|
||||
"sys_user",
|
||||
"sys_user_role",
|
||||
"sys_role",
|
||||
"sys_role_permission",
|
||||
"sys_permission",
|
||||
"sys_menu",
|
||||
"org_dict_type",
|
||||
"org_dict_item",
|
||||
}
|
||||
|
||||
TABLE_LABELS: dict[str, str] = {
|
||||
"sys_user": "用户账号", "sys_role": "角色", "sys_permission": "权限点",
|
||||
"sys_role_permission": "角色权限", "sys_user_role": "用户角色", "sys_menu": "菜单",
|
||||
"sys_announcement": "公告", "sys_notification": "站内消息", "sys_operation_log": "操作日志",
|
||||
"sys_attachment": "附件", "sys_refresh_token": "刷新令牌",
|
||||
"org_department": "部门", "org_position": "职位", "org_job_level": "职级",
|
||||
"org_dict_type": "字典类型", "org_dict_item": "字典项",
|
||||
"hr_employee": "员工档案", "hr_employee_contract": "劳动合同",
|
||||
"hr_employee_change": "人事异动", "hr_employee_education": "教育经历",
|
||||
"hr_employee_work_history": "工作经历", "hr_employee_family": "家庭成员",
|
||||
"hr_employee_certificate": "证书", "hr_salary_adjustment": "调薪记录",
|
||||
"hr_employee_document": "证明开具",
|
||||
"sal_salary_item": "薪资项目", "sal_salary_plan": "薪资账套", "sal_employee_salary": "员工薪资",
|
||||
"sal_payroll_period": "计薪期间", "sal_payroll_batch": "算薪批次", "sal_payslip": "工资条",
|
||||
"ben_insurance_plan": "参保方案", "ben_enrollment": "参保登记", "ben_benefit_item": "福利项目",
|
||||
"ben_benefit_record": "福利发放", "ben_leave_type": "假期类型", "ben_leave_balance": "假期额度",
|
||||
"ben_leave_request": "请假申请",
|
||||
"rec_job": "招聘职位", "rec_candidate": "候选人", "rec_application": "应聘流程",
|
||||
"rec_interview": "面试", "rec_offer": "Offer",
|
||||
"self_approval_log": "审批记录", "self_profile_request": "信息变更申请",
|
||||
"self_task_reminder": "待办提醒",
|
||||
}
|
||||
|
||||
|
||||
def table_label(name: str) -> str:
|
||||
return TABLE_LABELS.get(name, name)
|
||||
|
||||
|
||||
def _jsonable(value: Any) -> Any:
|
||||
if isinstance(value, (datetime, date, time)):
|
||||
return value.isoformat()
|
||||
if isinstance(value, Decimal):
|
||||
return float(value)
|
||||
if isinstance(value, bytes):
|
||||
return base64.b64encode(value).decode("ascii")
|
||||
return value
|
||||
|
||||
|
||||
def _excelable(value: Any) -> Any:
|
||||
value = _jsonable(value)
|
||||
if isinstance(value, (dict, list)):
|
||||
return json.dumps(value, ensure_ascii=False)
|
||||
return value
|
||||
|
||||
|
||||
def _sheet_name(name: str, used: set[str]) -> str:
|
||||
clean = "".join(ch for ch in name if ch not in "[]:*?/\\")[:31] or "sheet"
|
||||
candidate, index = clean, 2
|
||||
while candidate in used:
|
||||
suffix = f"_{index}"
|
||||
candidate = clean[: 31 - len(suffix)] + suffix
|
||||
index += 1
|
||||
used.add(candidate)
|
||||
return candidate
|
||||
|
||||
|
||||
async def table_stats(session: AsyncSession) -> list[dict]:
|
||||
"""每张表的行数;``kept`` 标记清理数据时会保留的系统骨架表。"""
|
||||
out: list[dict] = []
|
||||
for table in Base.metadata.sorted_tables:
|
||||
rows = int((await session.execute(select(func.count()).select_from(table))).scalar() or 0)
|
||||
out.append({"name": table.name, "label": table_label(table.name),
|
||||
"rows": rows, "kept": table.name in KEEP_TABLES})
|
||||
return out
|
||||
|
||||
|
||||
def _dir_size(path: Path) -> tuple[int, int]:
|
||||
if not path.exists():
|
||||
return 0, 0
|
||||
size = files = 0
|
||||
for item in path.rglob("*"):
|
||||
if item.is_file():
|
||||
size += item.stat().st_size
|
||||
files += 1
|
||||
return size, files
|
||||
|
||||
|
||||
async def overview(session: AsyncSession) -> dict:
|
||||
tables = await table_stats(session)
|
||||
db_file = None
|
||||
db_size = 0
|
||||
if settings.is_sqlite:
|
||||
db_file = Path(settings.database_url.split("///")[-1]).expanduser()
|
||||
db_size = db_file.stat().st_size if db_file.exists() else 0
|
||||
upload_size, upload_files = _dir_size(Path(settings.upload_dir))
|
||||
return {
|
||||
"database": "sqlite" if settings.is_sqlite else "mysql",
|
||||
"database_size": db_size,
|
||||
"upload_size": upload_size,
|
||||
"upload_files": upload_files,
|
||||
"tables": tables,
|
||||
"table_count": len(tables),
|
||||
"total_rows": sum(t["rows"] for t in tables),
|
||||
"keep_tables": sorted(KEEP_TABLES),
|
||||
}
|
||||
|
||||
|
||||
def _sqlite_snapshot() -> bytes | None:
|
||||
"""用 ``VACUUM INTO`` 拿一份一致的 SQLite 快照(运行中也能安全拷贝)。"""
|
||||
if not settings.is_sqlite:
|
||||
return None
|
||||
import sqlite3
|
||||
|
||||
source = Path(settings.database_url.split("///")[-1]).expanduser()
|
||||
if not source.exists():
|
||||
return None
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
target = Path(tmp) / "snapshot.db"
|
||||
conn = sqlite3.connect(str(source))
|
||||
try:
|
||||
conn.execute("VACUUM INTO ?", (str(target),))
|
||||
finally:
|
||||
conn.close()
|
||||
return target.read_bytes() if target.exists() else None
|
||||
|
||||
|
||||
async def build_backup_zip(session: AsyncSession) -> bytes:
|
||||
"""完整备份:JSON 数据 + 上传附件 + SQLite 原始快照。"""
|
||||
tables: dict[str, list[dict]] = {}
|
||||
for table in Base.metadata.sorted_tables:
|
||||
rows = (await session.execute(select(table))).mappings().all()
|
||||
tables[table.name] = [{k: _jsonable(v) for k, v in row.items()} for row in rows]
|
||||
|
||||
manifest = {
|
||||
"app": settings.app_name,
|
||||
"version": settings.version,
|
||||
"created_at": datetime.now().isoformat(timespec="seconds"),
|
||||
"database": "sqlite" if settings.is_sqlite else "mysql",
|
||||
"tables": {name: len(rows) for name, rows in tables.items()},
|
||||
}
|
||||
|
||||
buffer = io.BytesIO()
|
||||
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
zf.writestr("manifest.json", json.dumps(manifest, ensure_ascii=False, indent=2))
|
||||
zf.writestr("database.json",
|
||||
json.dumps({"tables": tables}, ensure_ascii=False, indent=1))
|
||||
snapshot = _sqlite_snapshot()
|
||||
if snapshot:
|
||||
zf.writestr("database.sqlite", snapshot)
|
||||
upload_root = Path(settings.upload_dir)
|
||||
if upload_root.exists():
|
||||
for item in sorted(upload_root.rglob("*")):
|
||||
if item.is_file():
|
||||
zf.write(item, f"uploads/{item.relative_to(upload_root).as_posix()}")
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
async def build_export_workbook(session: AsyncSession) -> bytes:
|
||||
"""全量导出为 Excel:每张表一个工作表,首表说明表名与行数。"""
|
||||
from openpyxl import Workbook
|
||||
|
||||
wb = Workbook(write_only=True)
|
||||
info = wb.create_sheet("说明")
|
||||
info.append(["表名", "中文名", "记录数", "清理数据时保留"])
|
||||
counts: dict[str, int] = {}
|
||||
payload: dict[str, list[tuple]] = {}
|
||||
|
||||
for table in Base.metadata.sorted_tables:
|
||||
rows = (await session.execute(select(table))).all()
|
||||
counts[table.name] = len(rows)
|
||||
payload[table.name] = rows
|
||||
info.append([table.name, table_label(table.name), len(rows),
|
||||
"是" if table.name in KEEP_TABLES else "否"])
|
||||
|
||||
used: set[str] = {"说明"}
|
||||
for table in Base.metadata.sorted_tables:
|
||||
ws = wb.create_sheet(_sheet_name(table.name, used))
|
||||
ws.append([column.name for column in table.columns])
|
||||
for row in payload[table.name]:
|
||||
ws.append([_excelable(value) for value in row])
|
||||
|
||||
buffer = io.BytesIO()
|
||||
wb.save(buffer)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
async def purge_all_data(session: AsyncSession) -> dict:
|
||||
"""清空全部业务数据,只保留系统管理员账号与系统骨架表。"""
|
||||
kept_ids = set(
|
||||
(await session.execute(select(User.id).where(User.is_superuser.is_(True)))).scalars().all()
|
||||
)
|
||||
if not kept_ids:
|
||||
raise AppError("未找到系统管理员账号,已取消清理", "no_superuser", 409)
|
||||
|
||||
# 先解除管理员账号对员工档案的引用,避免外键约束挡住后面的清表
|
||||
await session.execute(User.__table__.update().where(User.id.in_(kept_ids)).values(employee_id=None))
|
||||
# 非管理员的用户角色关系先删,保留账号本身留到最后处理
|
||||
await session.execute(delete(UserRole).where(UserRole.user_id.notin_(kept_ids)))
|
||||
|
||||
deleted: dict[str, int] = {}
|
||||
# 依赖关系按 sorted_tables 的逆序删,先清子表再清主表
|
||||
for table in reversed(Base.metadata.sorted_tables):
|
||||
if table.name in KEEP_TABLES:
|
||||
continue
|
||||
result = await session.execute(delete(table))
|
||||
deleted[table.name] = max(int(result.rowcount or 0), 0)
|
||||
|
||||
users = await session.execute(delete(User).where(User.id.notin_(kept_ids)))
|
||||
deleted["sys_user"] = max(int(users.rowcount or 0), 0)
|
||||
await session.commit()
|
||||
|
||||
if settings.is_sqlite:
|
||||
try: # 仅自增表才有 sqlite_sequence,缺表时忽略
|
||||
names = ",".join(f"'{name}'" for name in KEEP_TABLES)
|
||||
await session.execute(text(f"DELETE FROM sqlite_sequence WHERE name NOT IN ({names})"))
|
||||
await session.commit()
|
||||
except Exception: # noqa: BLE001 - 重置序号失败不影响清理结果
|
||||
await session.rollback()
|
||||
|
||||
upload_root = Path(settings.upload_dir)
|
||||
removed_files = 0
|
||||
if upload_root.exists():
|
||||
for item in upload_root.rglob("*"):
|
||||
if item.is_file():
|
||||
try:
|
||||
item.unlink()
|
||||
removed_files += 1
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
kept_users = (
|
||||
await session.execute(
|
||||
select(User.id, User.username, User.name).where(User.id.in_(kept_ids)).order_by(User.id)
|
||||
)
|
||||
).all()
|
||||
return {
|
||||
"deleted": deleted,
|
||||
"deleted_rows": sum(deleted.values()),
|
||||
"removed_files": removed_files,
|
||||
"kept_users": [{"id": r[0], "username": r[1], "name": r[2]} for r in kept_users],
|
||||
}
|
||||
|
|
@ -109,7 +109,11 @@ async def resolve_items(session: AsyncSession) -> dict[str, dict[str, Any]]:
|
|||
|
||||
|
||||
async def employees_for_scope(session: AsyncSession, scope: dict | None) -> list[Employee]:
|
||||
stmt = select(Employee).where(Employee.status.in_(["probation", "active", "leave"]))
|
||||
# 停用的档案与离职一样不参与算薪:``is_active`` 是全站唯一的业务启停位
|
||||
stmt = select(Employee).where(
|
||||
Employee.status.in_(["probation", "active", "leave"]),
|
||||
Employee.is_active.is_(True),
|
||||
)
|
||||
scope = scope or {}
|
||||
dept_ids = list(scope.get("department_ids") or [])
|
||||
emp_ids = list(scope.get("employee_ids") or [])
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ from ..core.permissions import (MENU_TREE, MOBILE_MENU_TREE, MODULES,
|
|||
from ..core.security import hash_password
|
||||
from ..models.employee import Employee
|
||||
from ..models.rbac import Menu, Permission, Role, RolePermission, User, UserRole
|
||||
from .seed import ACCOUNTS, RNG, add, already, count, log, mk
|
||||
from .seed import ACCOUNTS, RNG, add, count, log, mk
|
||||
|
||||
|
||||
async def seed_permissions(session) -> int:
|
||||
|
|
@ -52,28 +52,43 @@ async def seed_roles(session) -> int:
|
|||
|
||||
|
||||
async def seed_menus(session) -> int:
|
||||
"""按 MENU_TREE / MOBILE_MENU_TREE 生成两级菜单。"""
|
||||
if await already(session, Menu):
|
||||
return 0
|
||||
total = 0
|
||||
"""按 MENU_TREE / MOBILE_MENU_TREE 同步两级菜单。
|
||||
|
||||
以往只要库里已有菜单就整段跳过,导致新增页面永远进不了老环境的导航;
|
||||
这里改成按「平台 + 父级 + 路径 + 名称」逐条 upsert,只补缺(并用事实来源
|
||||
刷新图标/权限码/排序),不会重复插入。
|
||||
"""
|
||||
rows = list((await session.execute(select(Menu))).scalars().all())
|
||||
by_key = {(m.platform, m.parent_id or 0, m.path or "", m.name): m for m in rows}
|
||||
created = 0
|
||||
|
||||
async def walk_async(nodes, platform, parent_id, depth):
|
||||
nonlocal total
|
||||
nonlocal created
|
||||
for index, node in enumerate(nodes):
|
||||
sort = node.get("sort") or (index + 1) * 10 + depth * 100
|
||||
menu = mk(Menu, parent_id=parent_id, name=node["name"], path=node.get("path"),
|
||||
icon=node.get("icon"), perm_code=node.get("perm"), sort=sort,
|
||||
visible=True, platform=platform)
|
||||
session.add(menu)
|
||||
await session.flush()
|
||||
total += 1
|
||||
path = node.get("path")
|
||||
key = (platform, parent_id or 0, path or "", node["name"])
|
||||
menu = by_key.get(key)
|
||||
if menu is None:
|
||||
menu = mk(Menu, parent_id=parent_id, name=node["name"], path=path,
|
||||
icon=node.get("icon"), perm_code=node.get("perm"), sort=sort,
|
||||
visible=True, platform=platform)
|
||||
session.add(menu)
|
||||
await session.flush()
|
||||
by_key[key] = menu
|
||||
created += 1
|
||||
else:
|
||||
menu.icon = node.get("icon")
|
||||
menu.perm_code = node.get("perm")
|
||||
menu.sort = sort
|
||||
menu.visible = True
|
||||
if node.get("children"):
|
||||
await walk_async(node["children"], platform, menu.id, depth + 1)
|
||||
|
||||
await walk_async(MENU_TREE, "web", None, 0)
|
||||
await walk_async(MOBILE_MENU_TREE, "mobile", None, 0)
|
||||
await session.flush()
|
||||
return total
|
||||
return created
|
||||
|
||||
|
||||
async def run(session, *, force: bool = False) -> dict:
|
||||
|
|
|
|||
|
|
@ -0,0 +1,214 @@
|
|||
"""员工档案与系统账号联动:已开通状态筛选、按档案建号。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
API = "/api/v1"
|
||||
|
||||
|
||||
def _employee_options(client, admin) -> dict[str, dict]:
|
||||
rows = client.get(f"{API}/employees/options", headers=admin, params={"limit": 5000}).json()
|
||||
return {row["id"]: row for row in rows}
|
||||
|
||||
|
||||
def _create_employee(client, admin, *, name: str, work_no: str, status: str = "probation") -> dict:
|
||||
departments = client.get(f"{API}/org/departments/options", headers=admin).json()
|
||||
department_id = departments[0]["id"]
|
||||
resp = client.post(f"{API}/employees", headers=admin, json={
|
||||
"name": name,
|
||||
"work_no": work_no,
|
||||
"department_id": department_id,
|
||||
"status": status,
|
||||
"engage_form": "外包",
|
||||
})
|
||||
assert resp.status_code == 200, resp.text
|
||||
return resp.json()
|
||||
|
||||
|
||||
def test_generate_accounts_from_employees(client, admin, hr, employee):
|
||||
roles = client.get(f"{API}/system/roles", headers=admin, params={"page_size": 100}).json()["items"]
|
||||
role = next(row for row in roles if row["code"] == "employee")
|
||||
active = _create_employee(client, admin, name="建号测试员工", work_no="ACCT-TEST-01")
|
||||
resigned = _create_employee(
|
||||
client, admin, name="建号测试离职员工", work_no="ACCT-TEST-02", status="resigned",
|
||||
)
|
||||
user_id = None
|
||||
|
||||
payload = {
|
||||
"employee_ids": [active["id"], resigned["id"]],
|
||||
"role_ids": [role["id"]],
|
||||
"password": "Acct#Test2026",
|
||||
}
|
||||
try:
|
||||
# HR 和普通员工都不能代替系统管理员创建账号
|
||||
assert client.post(f"{API}/system/users/from-employees", headers=hr, json=payload).status_code == 403
|
||||
assert client.post(
|
||||
f"{API}/system/users/from-employees", headers=employee, json=payload,
|
||||
).status_code == 403
|
||||
|
||||
resp = client.post(f"{API}/system/users/from-employees", headers=admin, json=payload)
|
||||
assert resp.status_code == 200, resp.text
|
||||
result = resp.json()
|
||||
assert len(result["created"]) == 1
|
||||
assert result["created"][0]["employee_id"] == active["id"]
|
||||
assert result["created"][0]["username"] == "acct-test-01"
|
||||
assert result["skipped"] == [
|
||||
{"employee_id": resigned["id"], "name": "建号测试离职员工", "reason": "员工已离职"},
|
||||
]
|
||||
|
||||
users = client.get(f"{API}/system/users", headers=admin, params={
|
||||
"employee_id": active["id"], "page_size": 20,
|
||||
}).json()["items"]
|
||||
assert len(users) == 1
|
||||
user_id = users[0]["id"]
|
||||
assert users[0]["role_ids"] == [role["id"]]
|
||||
|
||||
# 档案列表和账号下拉同步展示已开通状态
|
||||
employee_rows = client.get(f"{API}/employees", headers=admin, params={
|
||||
"keyword": "ACCT-TEST-01", "page_size": 20,
|
||||
}).json()["items"]
|
||||
assert employee_rows[0]["has_account"] is True
|
||||
assert _employee_options(client, admin)[active["id"]]["extra"]["has_account"] is True
|
||||
unopened = client.get(f"{API}/employees", headers=admin, params={
|
||||
"has_account": "false", "keyword": "ACCT-TEST-01", "page_size": 20,
|
||||
}).json()
|
||||
assert unopened["total"] == 0
|
||||
exported = client.get(f"{API}/employees/export", headers=admin, params={
|
||||
"keyword": "ACCT-TEST", "has_account": "false",
|
||||
})
|
||||
assert exported.status_code == 200, exported.text
|
||||
sheet = load_workbook(io.BytesIO(exported.content), read_only=True).active
|
||||
headers = next(sheet.iter_rows(max_row=1, values_only=True))
|
||||
rows = list(sheet.iter_rows(min_row=2, values_only=True))
|
||||
assert "档案状态" in headers and "登录账号" in headers
|
||||
assert len(rows) == 1
|
||||
assert rows[0][headers.index("工号")] == resigned["work_no"]
|
||||
assert rows[0][headers.index("登录账号")] == "未开通"
|
||||
|
||||
# 同一档案再次选择会被跳过,不生成重复账号
|
||||
repeated = client.post(f"{API}/system/users/from-employees", headers=admin, json={
|
||||
**payload, "employee_ids": [active["id"]],
|
||||
})
|
||||
assert repeated.status_code == 200, repeated.text
|
||||
assert repeated.json()["created"] == []
|
||||
assert repeated.json()["skipped"][0]["employee_id"] == active["id"]
|
||||
|
||||
bad_role = client.post(f"{API}/system/users/from-employees", headers=admin, json={
|
||||
**payload, "employee_ids": [active["id"]], "role_ids": [99999999],
|
||||
})
|
||||
assert bad_role.status_code == 400
|
||||
assert bad_role.json()["code"] == "bad_role"
|
||||
finally:
|
||||
if user_id:
|
||||
client.delete(f"{API}/system/users/{user_id}", headers=admin)
|
||||
client.delete(f"{API}/employees/{active['id']}", headers=admin)
|
||||
client.delete(f"{API}/employees/{resigned['id']}", headers=admin)
|
||||
|
||||
|
||||
def _account_of(client, admin, employee_id: int) -> dict | None:
|
||||
items = client.get(f"{API}/system/users", headers=admin,
|
||||
params={"employee_id": employee_id, "page_size": 5}).json()["items"]
|
||||
return items[0] if items else None
|
||||
|
||||
|
||||
def test_deactivate_then_reactivate_employee_round_trip(client, admin, login):
|
||||
"""档案停用必须可逆:此前离职收尾会把 is_active 强行改回 False,导致再也启用不了。
|
||||
|
||||
同时校验启停与登录账号的联动 —— 停用档案 = 账号立即失效,重新启用 = 账号恢复。
|
||||
"""
|
||||
roles = client.get(f"{API}/system/roles", headers=admin, params={"page_size": 100}).json()["items"]
|
||||
role = next(row for row in roles if row["code"] == "employee")
|
||||
emp = _create_employee(client, admin, name="启停回归员工", work_no="TOGGLE-01")
|
||||
password = "Toggle#2026"
|
||||
created = client.post(f"{API}/system/users/from-employees", headers=admin, json={
|
||||
"employee_ids": [emp["id"]], "role_ids": [role["id"]], "password": password,
|
||||
})
|
||||
assert created.status_code == 200, created.text
|
||||
account = _account_of(client, admin, emp["id"])
|
||||
assert account, "生成账号后应能查到绑定账号"
|
||||
user_id = account["id"]
|
||||
try:
|
||||
assert login("toggle-01", password)["Authorization"]
|
||||
|
||||
# 停用:档案与账号一起停用,已登录会话立刻失效
|
||||
headers = login("toggle-01", password)
|
||||
off = client.patch(f"{API}/employees/{emp['id']}", headers=admin, json={"is_active": False})
|
||||
assert off.status_code == 200, off.text
|
||||
assert off.json()["is_active"] is False
|
||||
assert _account_of(client, admin, emp["id"])["is_active"] is False
|
||||
assert client.get(f"{API}/auth/me", headers=headers).status_code in (401, 403)
|
||||
|
||||
# 已绑定账号的档案不会被重复建号
|
||||
again = client.post(f"{API}/system/users/from-employees", headers=admin, json={
|
||||
"employee_ids": [emp["id"]], "role_ids": [role["id"]], "password": password,
|
||||
})
|
||||
assert again.status_code == 200
|
||||
assert again.json()["created"] == []
|
||||
assert "已绑定账号" in again.json()["skipped"][0]["reason"]
|
||||
|
||||
# 未开号的停用档案同样不能生成账号
|
||||
quiet = _create_employee(client, admin, name="停用未开号员工", work_no="TOGGLE-03")
|
||||
try:
|
||||
client.patch(f"{API}/employees/{quiet['id']}", headers=admin, json={"is_active": False})
|
||||
blocked = client.post(f"{API}/system/users/from-employees", headers=admin, json={
|
||||
"employee_ids": [quiet["id"]], "role_ids": [role["id"]], "password": password,
|
||||
})
|
||||
assert blocked.json()["created"] == []
|
||||
assert "停用" in blocked.json()["skipped"][0]["reason"]
|
||||
finally:
|
||||
client.delete(f"{API}/employees/{quiet['id']}", headers=admin)
|
||||
|
||||
# 重新启用:档案与账号都回到可用状态(这一步曾经静默失败)
|
||||
on = client.patch(f"{API}/employees/{emp['id']}", headers=admin, json={"is_active": True})
|
||||
assert on.status_code == 200, on.text
|
||||
assert on.json()["is_active"] is True, "显式启用被生命周期联动覆盖回去了"
|
||||
assert _account_of(client, admin, emp["id"])["is_active"] is True
|
||||
assert login("toggle-01", password)["Authorization"]
|
||||
assert client.get(f"{API}/auth/me", headers=login("toggle-01", password)).status_code == 200
|
||||
|
||||
# 列表筛选同步跟上
|
||||
assert client.get(f"{API}/employees", headers=admin,
|
||||
params={"is_active": "false", "keyword": "TOGGLE-01"}).json()["total"] == 0
|
||||
assert client.get(f"{API}/employees", headers=admin,
|
||||
params={"is_active": "true", "keyword": "TOGGLE-01"}).json()["total"] == 1
|
||||
finally:
|
||||
client.patch(f"{API}/system/users/{user_id}", headers=admin, json={"is_active": True})
|
||||
client.delete(f"{API}/system/users/{user_id}", headers=admin)
|
||||
client.delete(f"{API}/employees/{emp['id']}", headers=admin)
|
||||
|
||||
|
||||
def test_resigned_profile_can_be_reactivated(client, admin):
|
||||
"""已离职档案的启停只动启停位,不再被离职收尾反复压制。"""
|
||||
emp = _create_employee(client, admin, name="离职复职探针", work_no="TOGGLE-02", status="resigned")
|
||||
try:
|
||||
off = client.patch(f"{API}/employees/{emp['id']}", headers=admin, json={"is_active": False})
|
||||
assert off.json()["is_active"] is False
|
||||
on = client.patch(f"{API}/employees/{emp['id']}", headers=admin, json={"is_active": True})
|
||||
assert on.json()["is_active"] is True
|
||||
finally:
|
||||
client.delete(f"{API}/employees/{emp['id']}", headers=admin)
|
||||
|
||||
|
||||
def test_disabled_master_data_cannot_be_reselected(client, admin):
|
||||
"""停用的部门/职位仍要能解析名称(历史数据),但不能被新记录选中。"""
|
||||
depts = client.get(f"{API}/org/departments/options", headers=admin).json()
|
||||
target = depts[-1]
|
||||
back = client.patch(f"{API}/org/departments/{target['id']}", headers=admin,
|
||||
json={"is_active": False})
|
||||
assert back.status_code == 200, back.text
|
||||
try:
|
||||
options = {o["id"]: o for o in client.get(f"{API}/org/departments/options", headers=admin).json()}
|
||||
assert options[target["id"]]["extra"]["is_active"] is False
|
||||
emp = client.post(f"{API}/employees", headers=admin, json={
|
||||
"name": "停用部门探针", "work_no": "DPT-01", "department_id": target["id"],
|
||||
"engage_form": "外包",
|
||||
})
|
||||
assert emp.status_code == 200, emp.text
|
||||
emp_id = emp.json()["id"]
|
||||
client.delete(f"{API}/employees/{emp_id}", headers=admin)
|
||||
finally:
|
||||
assert client.patch(f"{API}/org/departments/{target['id']}", headers=admin,
|
||||
json={"is_active": True}).json()["is_active"] is True
|
||||
|
|
@ -0,0 +1,125 @@
|
|||
"""系统数据维护:概况、备份、导出、清空数据。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import io
|
||||
import json
|
||||
import zipfile
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
API = "/api/v1"
|
||||
|
||||
|
||||
def test_maintenance_is_admin_only(client, admin, hr):
|
||||
assert client.get(f"{API}/system/maintenance/overview", headers=hr).status_code == 403
|
||||
resp = client.get(f"{API}/system/maintenance/overview", headers=admin)
|
||||
assert resp.status_code == 200, resp.text
|
||||
body = resp.json()
|
||||
assert body["tables"] and body["table_count"] == len(body["tables"])
|
||||
assert any(t["kept"] for t in body["tables"])
|
||||
|
||||
|
||||
def test_backup_and_export_payloads(client, admin):
|
||||
backup = client.get(f"{API}/system/maintenance/backup", headers=admin)
|
||||
assert backup.status_code == 200, backup.text
|
||||
assert backup.headers["content-type"] == "application/zip"
|
||||
archive = zipfile.ZipFile(io.BytesIO(backup.content))
|
||||
names = set(archive.namelist())
|
||||
assert {"manifest.json", "database.json"} <= names
|
||||
assert "database.sqlite" in names
|
||||
manifest = json.loads(archive.read("manifest.json"))
|
||||
assert manifest["tables"]["sys_user"] > 0
|
||||
database = json.loads(archive.read("database.json"))
|
||||
assert database["tables"]["hr_employee"]
|
||||
|
||||
exported = client.get(f"{API}/system/maintenance/export", headers=admin)
|
||||
assert exported.status_code == 200, exported.text
|
||||
workbook = load_workbook(io.BytesIO(exported.content), read_only=True)
|
||||
assert "说明" in workbook.sheetnames
|
||||
assert "sys_user" in workbook.sheetnames
|
||||
assert "hr_employee" in workbook.sheetnames
|
||||
|
||||
|
||||
def test_purge_requires_exact_confirm_phrase_and_leaves_data_intact(client, admin):
|
||||
resp = client.post(
|
||||
f"{API}/system/maintenance/purge",
|
||||
headers=admin,
|
||||
json={"confirm": "清空全部数据"},
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
assert resp.json()["code"] == "confirm_required"
|
||||
total = client.get(f"{API}/employees", headers=admin, params={"page_size": 1}).json()["total"]
|
||||
assert total > 0
|
||||
|
||||
|
||||
def test_purge_accepts_unis_hrms_phrase(client, admin, monkeypatch):
|
||||
"""确认短语放行逻辑单独验证,替换破坏性清理函数,避免影响共享测试库。"""
|
||||
from app.services import maintenance
|
||||
|
||||
called = False
|
||||
|
||||
async def fake_purge(_session):
|
||||
nonlocal called
|
||||
called = True
|
||||
return {"kept_users": ["admin"], "deleted_rows": 0}
|
||||
|
||||
monkeypatch.setattr(maintenance, "purge_all_data", fake_purge)
|
||||
resp = client.post(
|
||||
f"{API}/system/maintenance/purge",
|
||||
headers=admin,
|
||||
json={"confirm": "unis_hrms"},
|
||||
)
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["deleted_rows"] == 0
|
||||
assert called
|
||||
|
||||
|
||||
def test_purge_keeps_only_superuser(tmp_path, monkeypatch):
|
||||
"""用独立临时库验证清理逻辑,避免破坏测试会话共享的数据库。"""
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
|
||||
from app.db.base import Base
|
||||
from app.models.employee import Employee
|
||||
from app.models.rbac import Announcement, Role, User, UserRole
|
||||
from app.services import maintenance
|
||||
|
||||
monkeypatch.setattr(maintenance.settings, "upload_dir", tmp_path / "uploads")
|
||||
|
||||
async def scenario():
|
||||
engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'purge.db'}")
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
session_factory = async_sessionmaker(engine, expire_on_commit=False)
|
||||
|
||||
async with session_factory() as session:
|
||||
admin = User(username="admin", password_hash="x", name="管理员", is_superuser=True)
|
||||
other = User(username="hr", password_hash="x", name="人事", is_superuser=False)
|
||||
role = Role(code="super_admin", name="超级管理员", data_scope="all",
|
||||
is_builtin=True, is_active=True, sort=1)
|
||||
session.add_all([admin, other, role])
|
||||
await session.flush()
|
||||
session.add_all([
|
||||
UserRole(user_id=admin.id, role_id=role.id),
|
||||
UserRole(user_id=other.id, role_id=role.id),
|
||||
Employee(name="张三", work_no="E9001", status="active"),
|
||||
Announcement(title="公告", content="内容"),
|
||||
])
|
||||
await session.commit()
|
||||
|
||||
result = await maintenance.purge_all_data(session)
|
||||
assert result["deleted_rows"] > 0
|
||||
|
||||
async with session_factory() as session:
|
||||
users = (await session.execute(select(User))).scalars().all()
|
||||
assert [u.username for u in users] == ["admin"]
|
||||
assert (await session.execute(select(func.count()).select_from(Employee))).scalar() == 0
|
||||
assert (await session.execute(select(func.count()).select_from(Announcement))).scalar() == 0
|
||||
assert (await session.execute(select(func.count()).select_from(UserRole))).scalar() == 1
|
||||
assert (await session.execute(select(func.count()).select_from(Role))).scalar() == 1
|
||||
|
||||
await engine.dispose()
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
|
@ -0,0 +1,137 @@
|
|||
"""组织架构导入 / 导出 / 模板,以及人事档案模板下载的鉴权回归。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
|
||||
from openpyxl import Workbook, load_workbook
|
||||
|
||||
API = "/api/v1"
|
||||
XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
|
||||
|
||||
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 _upload(client, path: str, headers: dict, file_headers: list[str], rows: list[list]):
|
||||
return client.post(
|
||||
f"{API}{path}", headers=headers,
|
||||
files={"file": ("import.xlsx", _xlsx(file_headers, rows), XLSX)},
|
||||
)
|
||||
|
||||
|
||||
def test_employee_import_template_downloads_with_auth(client, admin):
|
||||
"""回归:模板以前用 window.open,带不上 token,登录态下反而 401。"""
|
||||
resp = client.get(f"{API}/employees/import-template", headers=admin)
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.headers["content-type"].startswith(XLSX)
|
||||
sheet = load_workbook(io.BytesIO(resp.content)).active
|
||||
assert "姓名" in [cell.value for cell in sheet[1]]
|
||||
|
||||
|
||||
def test_org_io_endpoints_are_permission_gated(client, admin, hr):
|
||||
paths = [
|
||||
"/org/departments/export", "/org/departments/import-template",
|
||||
"/org/positions/export", "/org/positions/import-template",
|
||||
"/org/job-levels/export", "/org/job-levels/import-template",
|
||||
]
|
||||
for path in paths:
|
||||
assert client.get(f"{API}{path}", headers=hr).status_code == 403, path
|
||||
assert client.get(f"{API}{path}", headers=admin).status_code == 200, path
|
||||
|
||||
|
||||
def _dept_nodes(nodes: list[dict]) -> list[dict]:
|
||||
out: list[dict] = []
|
||||
for node in nodes:
|
||||
out.append(node)
|
||||
out.extend(_dept_nodes(node.get("children") or []))
|
||||
return out
|
||||
|
||||
|
||||
def test_department_import_export_roundtrip(client, admin):
|
||||
headers = ["部门编码", "部门名称", "上级部门编码", "部门负责人工号", "成本中心", "排序", "是否启用", "备注"]
|
||||
# 子部门写在上级前面,验证导入后仍能正确挂接并重算层级
|
||||
rows = [
|
||||
["T-IO-002", "测试子部门", "T-IO-001", "EMP00001", "CC-T2", 20, "是", "子部门"],
|
||||
["T-IO-001", "测试一级部门", "", "", "CC-T1", 10, "是", "一级部门"],
|
||||
]
|
||||
try:
|
||||
resp = _upload(client, "/org/departments/import", admin, headers, rows)
|
||||
assert resp.status_code == 200, resp.text
|
||||
body = resp.json()
|
||||
assert body["created"] == 2 and body["failed"] == 0, body
|
||||
|
||||
nodes = _dept_nodes(client.get(f"{API}/org/departments/tree", headers=admin).json())
|
||||
parent = next(n for n in nodes if n["code"] == "T-IO-001")
|
||||
child = next(n for n in nodes if n["code"] == "T-IO-002")
|
||||
assert child["parent_id"] == parent["id"]
|
||||
assert child["level"] == parent["level"] + 1
|
||||
assert parent["is_parent"] is True
|
||||
|
||||
exported = client.get(f"{API}/org/departments/export", headers=admin)
|
||||
assert exported.status_code == 200
|
||||
sheet = load_workbook(io.BytesIO(exported.content)).active
|
||||
codes = {row[0] for row in sheet.iter_rows(min_row=2, values_only=True)}
|
||||
assert {"T-IO-001", "T-IO-002"} <= codes
|
||||
|
||||
# 再次导入:同一批数据应全部走更新,不重复建部门
|
||||
again = _upload(client, "/org/departments/import", admin, headers, rows)
|
||||
assert again.status_code == 200
|
||||
assert again.json()["updated"] == 2 and again.json()["created"] == 0
|
||||
finally:
|
||||
remaining = _dept_nodes(client.get(f"{API}/org/departments/tree", headers=admin).json())
|
||||
for code in ("T-IO-002", "T-IO-001"):
|
||||
node = next((n for n in remaining if n["code"] == code), None)
|
||||
if node:
|
||||
client.delete(f"{API}/org/departments/{node['id']}", headers=admin)
|
||||
|
||||
|
||||
def test_position_and_job_level_import(client, admin):
|
||||
position_headers = ["职位编码", "职位名称", "职务序列", "排序", "是否启用", "备注"]
|
||||
level_headers = ["职级编码", "职级名称", "职等", "排序", "是否启用", "备注"]
|
||||
try:
|
||||
created = _upload(client, "/org/positions/import", admin, position_headers,
|
||||
[["T-POS-01", "测试职位", "技术序列", 10, "是", ""]])
|
||||
assert created.status_code == 200 and created.json()["created"] == 1, created.text
|
||||
updated = _upload(client, "/org/positions/import", admin, position_headers,
|
||||
[["T-POS-01", "测试职位改名", "技术序列", 20, "否", ""]])
|
||||
assert updated.json()["updated"] == 1, updated.text
|
||||
rows = client.get(f"{API}/org/positions", headers=admin,
|
||||
params={"keyword": "T-POS-01"}).json()["items"]
|
||||
assert rows and rows[0]["name"] == "测试职位改名" and rows[0]["is_active"] is False
|
||||
|
||||
created = _upload(client, "/org/job-levels/import", admin, level_headers,
|
||||
[["T-JL-01", "T5", 5, 10, "是", ""]])
|
||||
assert created.status_code == 200 and created.json()["created"] == 1, created.text
|
||||
levels = client.get(f"{API}/org/job-levels", headers=admin,
|
||||
params={"keyword": "T-JL-01"}).json()["items"]
|
||||
assert levels and levels[0]["grade"] == 5
|
||||
finally:
|
||||
for path, code in (("/org/positions", "T-POS-01"), ("/org/job-levels", "T-JL-01")):
|
||||
items = client.get(f"{API}{path}", headers=admin, params={"keyword": code}).json()["items"]
|
||||
for item in items:
|
||||
client.delete(f"{API}{path}/{item['id']}", headers=admin)
|
||||
|
||||
|
||||
def test_csv_import_is_supported(client, admin):
|
||||
content = "职位编码,职位名称,职务序列,排序,是否启用,备注\nT-CSV-01,CSV职位,技术序列,10,是,\n".encode("utf-8-sig")
|
||||
try:
|
||||
resp = client.post(
|
||||
f"{API}/org/positions/import", headers=admin,
|
||||
files={"file": ("positions.csv", content, "text/csv")},
|
||||
)
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["created"] == 1, resp.text
|
||||
finally:
|
||||
items = client.get(f"{API}/org/positions", headers=admin,
|
||||
params={"keyword": "T-CSV-01"}).json()["items"]
|
||||
for item in items:
|
||||
client.delete(f"{API}/org/positions/{item['id']}", headers=admin)
|
||||
|
|
@ -432,12 +432,13 @@ MENU_TO_PERM = {
|
|||
"/system/dicts": "system:dict",
|
||||
"/system/announcements": "system:announcement",
|
||||
"/system/logs": "system:log",
|
||||
"/system/maintenance": "system:maintenance",
|
||||
}
|
||||
|
||||
WEB_MENUS = {
|
||||
"admin": set(MENU_TO_PERM) | {"/dashboard"},
|
||||
"hr": (set(MENU_TO_PERM) | {"/dashboard"})
|
||||
- {"/system/users", "/system/roles", "/system/dicts"},
|
||||
- {"/system/users", "/system/roles", "/system/dicts", "/system/maintenance"},
|
||||
"payroll": {"/dashboard", "/employees", "/payroll/batches", "/payroll/payslips", "/payroll/plans",
|
||||
"/payroll/standards", "/payroll/items", "/payroll/reports",
|
||||
"/benefits/enrollments", "/benefits/plans", "/benefits/items",
|
||||
|
|
|
|||
|
|
@ -46,6 +46,7 @@ const Roles = lazy(() => import('./pages/system/Roles'))
|
|||
const Dicts = lazy(() => import('./pages/system/Dicts'))
|
||||
const Announcements = lazy(() => import('./pages/system/Announcements'))
|
||||
const Logs = lazy(() => import('./pages/system/Logs'))
|
||||
const Maintenance = lazy(() => import('./pages/system/Maintenance'))
|
||||
|
||||
const MHome = lazy(() => import('./pages/mobile/MHome'))
|
||||
const MApprovals = lazy(() => import('./pages/mobile/MApprovals'))
|
||||
|
|
@ -159,6 +160,7 @@ export default function App() {
|
|||
<Route path="system/dicts" element={<Dicts />} />
|
||||
<Route path="system/announcements" element={<Announcements />} />
|
||||
<Route path="system/logs" element={<Logs />} />
|
||||
<Route path="system/maintenance" element={<Maintenance />} />
|
||||
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Route>
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@ export type FieldType =
|
|||
| 'year'
|
||||
| 'dateRange'
|
||||
| 'switch'
|
||||
/** 列表内联启停开关:点一下直接 PATCH,不再跳进编辑抽屉 */
|
||||
| 'toggle'
|
||||
| 'tag'
|
||||
| 'tags'
|
||||
| 'select'
|
||||
|
|
@ -60,6 +62,19 @@ export interface FieldDef {
|
|||
/** 表头筛选:是否允许多选,默认 true */
|
||||
filterMultiple?: boolean
|
||||
render?: (value: any, row: any) => ReactNode
|
||||
/** type='toggle' 时生效:内联启停开关的落库与刷新配置 */
|
||||
toggle?: {
|
||||
/** PATCH 地址(由行数据算出),请求体固定为 { is_active: true|false } */
|
||||
path: (row: any) => string
|
||||
/** 需要的权限码,缺省=任何登录用户都可点(后端仍会再校验) */
|
||||
perm?: string
|
||||
/** 所属列表的 ResourceDef.key,保存成功后刷新该列表 */
|
||||
listKey: string
|
||||
/** 停用方向的二次确认文案 */
|
||||
confirm?: (row: any) => string
|
||||
/** 保存成功后额外失效的 queryKey */
|
||||
invalidate?: (row: any) => readonly (readonly unknown[])[]
|
||||
}
|
||||
/** 表单里显示但提交前转换(例如 dayjs -> 字符串) */
|
||||
toForm?: (v: any, row: any) => any
|
||||
toPayload?: (v: any, row: any) => any
|
||||
|
|
|
|||
|
|
@ -29,6 +29,12 @@ export const employeeDef: ResourceDef = {
|
|||
{ label: '休假中', value: 'leave' },
|
||||
] }),
|
||||
col('engage_form', '用工形式', { type: 'dict', dict: 'engage_form' }),
|
||||
col('is_active', '档案状态', { type: 'select', options: [
|
||||
{ label: '启用', value: 'true' }, { label: '停用', value: 'false' },
|
||||
], filterMultiple: false }),
|
||||
col('has_account', '账号状态', { type: 'select', options: [
|
||||
{ label: '已开通', value: 'true' }, { label: '未开通', value: 'false' },
|
||||
], filterMultiple: false }),
|
||||
col('gender', '性别', { type: 'tag', options: GENDER_OPTIONS, filterMultiple: false }),
|
||||
col('highest_degree', '最高学历', { type: 'dict', dict: 'degree' }),
|
||||
col('position_id', '职位', { type: 'options', source: '/org/positions/options', filterOn: 'position_name' }),
|
||||
|
|
@ -36,13 +42,21 @@ export const employeeDef: ResourceDef = {
|
|||
col('hire_date', '入职日期', { type: 'dateRange' }),
|
||||
],
|
||||
columns: [
|
||||
col('work_no', '工号', { width: 106, fixed: 'left' }),
|
||||
col('name', '姓名', { width: 96, fixed: 'left', required: true }),
|
||||
col('work_no', '工号', { width: 106 }),
|
||||
col('name', '姓名', { width: 96, required: true }),
|
||||
col('is_active', '启用', { type: 'toggle', width: 96, toggle: {
|
||||
path: (r: any) => `/employees/${r.id}`,
|
||||
perm: 'employee:employee:update',
|
||||
listKey: 'employee',
|
||||
confirm: (r: any) => `停用「${r.name}」的员工档案?停用后不能再被新业务选中,也不能生成登录账号。`,
|
||||
invalidate: () => [['options', '/employees/options'], ['employee-stats'], ['boot-options']],
|
||||
} }),
|
||||
col('gender', '性别', { type: 'tag', width: 68, options: GENDER_OPTIONS }),
|
||||
col('department_name', '部门', { width: 120 }),
|
||||
col('position_name', '职位', { width: 130 }),
|
||||
col('job_level_name', '职级', { width: 90 }),
|
||||
col('status', '状态', { type: 'tag', width: 90, options: EMP_STATUS_OPTIONS }),
|
||||
col('has_account', '登录账号', { width: 96, render: (v: boolean) => (v ? '已开通' : '未开通') }),
|
||||
col('hire_date', '入职日期', { type: 'date', width: 116 }),
|
||||
col('tenure', '司龄', { width: 90 }),
|
||||
col('phone', '手机号', { width: 124 }),
|
||||
|
|
@ -50,8 +64,7 @@ export const employeeDef: ResourceDef = {
|
|||
col('highest_degree', '学历', { width: 84 }),
|
||||
col('engage_form', '用工形式', { type: 'dict', dict: 'engage_form', width: 100 }),
|
||||
col('tags', '标签', { type: 'tags', width: 160 }),
|
||||
col('leave_date', '离职日期', { type: 'date', width: 116 }),
|
||||
],
|
||||
col('leave_date', '离职日期', { type: 'date', width: 116 })],
|
||||
form: [
|
||||
fld('name', '姓名', { required: true }),
|
||||
fld('work_no', '工号', { tip: '留空由系统自动发号 EMPxxxxx' }),
|
||||
|
|
@ -68,6 +81,7 @@ export const employeeDef: ResourceDef = {
|
|||
fld('position_id', '职位', { type: 'options', source: '/org/positions/options' }),
|
||||
fld('job_level_id', '职级', { type: 'options', source: '/org/job-levels/options' }),
|
||||
fld('engage_form', '用工形式', { type: 'dict', dict: 'engage_form', default: '正式' }),
|
||||
fld('is_active', '档案启用', { type: 'switch', default: true, tip: '停用后档案仍会保留,可随时重新启用' }),
|
||||
fld('status', '在职状态', { type: 'select', default: 'probation', options: [
|
||||
{ label: '试用期', value: 'probation' },
|
||||
{ label: '在职', value: 'active' },
|
||||
|
|
@ -295,15 +309,20 @@ export const departmentDef: ResourceDef = {
|
|||
filters: [col('is_active', '启用', { type: 'switch' })],
|
||||
columns: [
|
||||
col('name', '部门名称', { width: 180, required: true }),
|
||||
col('is_active', '启用', { type: 'toggle', width: 100, toggle: {
|
||||
path: (r: any) => `/org/departments/${r.id}`,
|
||||
perm: 'org:department:update',
|
||||
listKey: 'department',
|
||||
confirm: (r: any) => `停用后该部门(含下级)不再出现在新的业务选择中,已有人员与数据不受影响。`,
|
||||
invalidate: () => [['boot-options']],
|
||||
} }),
|
||||
col('code', '编码', { width: 120 }),
|
||||
col('dep_path', '全路径', { width: 240 }),
|
||||
col('level', '层级', { type: 'number', width: 80 }),
|
||||
col('leader_employee_id', '负责人', { type: 'options', source: '/employees/options', width: 110 }),
|
||||
col('employee_count', '在编人数', { type: 'number', width: 100, align: 'right' }),
|
||||
col('cost_center', '成本中心', { width: 120 }),
|
||||
col('is_parent', '虚拟节点', { type: 'switch', width: 100 }),
|
||||
col('is_active', '启用', { type: 'switch', width: 80 }),
|
||||
],
|
||||
col('is_parent', '虚拟节点', { type: 'switch', width: 100 })],
|
||||
form: [
|
||||
fld('name', '部门名称', { required: true }),
|
||||
fld('code', '部门编码'),
|
||||
|
|
@ -322,17 +341,23 @@ export const positionDef: ResourceDef = {
|
|||
path: '/org/positions',
|
||||
label: '职位',
|
||||
perm: 'org:position',
|
||||
exportPath: '/org/positions/export',
|
||||
orderBy: 'sort',
|
||||
order: 'asc',
|
||||
filters: [col('is_active', '启用', { type: 'switch' })],
|
||||
columns: [
|
||||
col('name', '职位名称', { width: 200, required: true }),
|
||||
col('is_active', '启用', { type: 'toggle', width: 110, toggle: {
|
||||
path: (r: any) => `/org/positions/${r.id}`,
|
||||
perm: 'org:position:update',
|
||||
listKey: 'position',
|
||||
confirm: (r: any) => `停用后该职位不能再被新的员工/职位任命选中,已有人员不受影响。`,
|
||||
invalidate: () => [['boot-options']],
|
||||
} }),
|
||||
col('code', '编码', { width: 140 }),
|
||||
col('category', '职务序列', { width: 140 }),
|
||||
col('sort', '排序', { type: 'number', width: 90 }),
|
||||
col('is_active', '启用', { type: 'switch', width: 90 }),
|
||||
col('remark', '备注', { width: 220 }),
|
||||
],
|
||||
col('remark', '备注', { width: 220 })],
|
||||
form: [
|
||||
fld('name', '职位名称', { required: true }),
|
||||
fld('code', '职位编码'),
|
||||
|
|
@ -348,11 +373,19 @@ export const jobLevelDef: ResourceDef = {
|
|||
path: '/org/job-levels',
|
||||
label: '职级职等',
|
||||
perm: 'org:joblevel',
|
||||
exportPath: '/org/job-levels/export',
|
||||
orderBy: 'sort',
|
||||
order: 'asc',
|
||||
filters: [col('is_active', '启用', { type: 'switch' })],
|
||||
columns: [
|
||||
col('name', '职级', { width: 160, required: true }),
|
||||
col('is_active', '启用', { type: 'toggle', width: 110, toggle: {
|
||||
path: (r: any) => `/org/job-levels/${r.id}`,
|
||||
perm: 'org:joblevel:update',
|
||||
listKey: 'joblevel',
|
||||
confirm: (r: any) => `停用后该职级不能再被新的员工/职位选中,已有人员不受影响。`,
|
||||
invalidate: () => [['boot-options']],
|
||||
} }),
|
||||
col('code', '编码', { width: 140 }),
|
||||
col('grade', '职等', { type: 'number', width: 100 }),
|
||||
col('expense_standard_count', '报销项目', {
|
||||
|
|
@ -360,9 +393,7 @@ export const jobLevelDef: ResourceDef = {
|
|||
render: (v: number) => `${v ?? 0} 项`,
|
||||
}),
|
||||
col('sort', '排序', { type: 'number', width: 90 }),
|
||||
col('is_active', '启用', { type: 'switch', width: 90 }),
|
||||
col('remark', '备注', { width: 240 }),
|
||||
],
|
||||
col('remark', '备注', { width: 240 })],
|
||||
form: [
|
||||
fld('name', '职级名称', { required: true, placeholder: '如 P5 / M2' }),
|
||||
fld('code', '编码'),
|
||||
|
|
@ -478,7 +509,7 @@ export const jobDef: ResourceDef = {
|
|||
col('publish_date', '发布日期', { type: 'dateRange' }),
|
||||
],
|
||||
columns: [
|
||||
col('title', '职位名称', { width: 190, fixed: 'left', required: true }),
|
||||
col('title', '职位名称', { width: 190, required: true }),
|
||||
col('department_name', '部门', { width: 120 }),
|
||||
col('position_name', '职位', { width: 130 }),
|
||||
col('job_level_name', '职级', { width: 90 }),
|
||||
|
|
@ -533,7 +564,7 @@ export const candidateDef: ResourceDef = {
|
|||
col('degree', '学历', { type: 'dict', dict: 'degree' }),
|
||||
],
|
||||
columns: [
|
||||
col('name', '姓名', { width: 100, fixed: 'left', required: true }),
|
||||
col('name', '姓名', { width: 100, required: true }),
|
||||
col('phone', '手机号', { width: 128 }),
|
||||
col('gender', '性别', { type: 'tag', width: 70, options: GENDER_OPTIONS }),
|
||||
col('age', '年龄', { type: 'number', width: 76 }),
|
||||
|
|
@ -581,7 +612,7 @@ export const applicationDef: ResourceDef = {
|
|||
col('owner_user_id', '负责人', { type: 'options', source: '/system/users/options', filterOn: 'owner_name' }),
|
||||
],
|
||||
columns: [
|
||||
col('candidate_name', '候选人', { width: 110, fixed: 'left' }),
|
||||
col('candidate_name', '候选人', { width: 110 }),
|
||||
col('candidate_phone', '手机号', { width: 128 }),
|
||||
col('job_title', '应聘职位', { width: 180 }),
|
||||
col('department_name', '部门', { width: 120 }),
|
||||
|
|
@ -617,7 +648,7 @@ export const interviewDef: ResourceDef = {
|
|||
col('scheduled_at', '面试时间', { type: 'dateRange' }),
|
||||
],
|
||||
columns: [
|
||||
col('candidate_name', '候选人', { width: 110, fixed: 'left' }),
|
||||
col('candidate_name', '候选人', { width: 110 }),
|
||||
col('job_title', '应聘职位', { width: 170 }),
|
||||
col('round_label', '轮次', { width: 90 }),
|
||||
col('interview_type', '形式', { type: 'dict', dict: 'interview_type', width: 100 }),
|
||||
|
|
@ -654,7 +685,7 @@ export const offerDef: ResourceDef = {
|
|||
{ label: '已接受', value: 'accepted' }, { label: '已拒绝', value: 'declined' }, { label: '已入职', value: 'onboarded' },
|
||||
] }), col('job_id', '应聘职位', { type: 'options', source: '/recruitment/jobs/options', filterOn: 'job_title' })],
|
||||
columns: [
|
||||
col('candidate_name', '候选人', { width: 110, fixed: 'left' }),
|
||||
col('candidate_name', '候选人', { width: 110 }),
|
||||
col('job_title', '职位', { width: 180 }),
|
||||
col('department_name', '部门', { width: 120 }),
|
||||
col('monthly_salary', '月薪', { type: 'money', width: 120 }),
|
||||
|
|
@ -721,6 +752,13 @@ export const salaryItemDef: ResourceDef = {
|
|||
col('is_active', '启用', { type: 'switch' })],
|
||||
columns: [
|
||||
col('code', '编码', { width: 130, required: true }),
|
||||
col('is_active', '启用', { type: 'toggle', width: 100, toggle: {
|
||||
path: (r: any) => `/payroll/items/${r.id}`,
|
||||
perm: 'payroll:item:update',
|
||||
listKey: 'salaryitem',
|
||||
confirm: (r: any) => `停用后算薪不再计入该薪资项目,历史工资条不受影响。`,
|
||||
invalidate: () => [['boot-options']],
|
||||
} }),
|
||||
col('name', '项目名称', { width: 150, required: true }),
|
||||
col('category', '类别', { type: 'tag', width: 100, options: SALARY_ITEM_CATEGORY_OPTIONS }),
|
||||
col('calc_type', '计算方式', { type: 'tag', width: 110, options: CALC_TYPE_OPTIONS }),
|
||||
|
|
@ -728,9 +766,7 @@ export const salaryItemDef: ResourceDef = {
|
|||
col('include_in_gross', '计入应发', { type: 'switch', width: 100 }),
|
||||
col('taxable', '计税', { type: 'switch', width: 80 }),
|
||||
col('is_system', '系统内置', { type: 'switch', width: 100 }),
|
||||
col('sort', '排序', { type: 'number', width: 80 }),
|
||||
col('is_active', '启用', { type: 'switch', width: 80 }),
|
||||
],
|
||||
col('sort', '排序', { type: 'number', width: 80 })],
|
||||
form: [
|
||||
fld('code', '项目编码', { required: true, placeholder: '如 BASIC / PERF' }),
|
||||
fld('name', '项目名称', { required: true }),
|
||||
|
|
@ -755,15 +791,20 @@ export const salaryPlanDef: ResourceDef = {
|
|||
filters: [col('is_active', '启用', { type: 'switch' })],
|
||||
columns: [
|
||||
col('name', '账套名称', { width: 190, required: true }),
|
||||
col('is_active', '启用', { type: 'toggle', width: 100, toggle: {
|
||||
path: (r: any) => `/payroll/plans/${r.id}`,
|
||||
perm: 'payroll:plan:update',
|
||||
listKey: 'salaryplan',
|
||||
confirm: (r: any) => `停用后新建薪资标准不会再选用该账套,已生效标准不受影响。`,
|
||||
invalidate: () => [['boot-options']],
|
||||
} }),
|
||||
col('code', '编码', { width: 120 }),
|
||||
col('department_name', '适用部门', { width: 130 }),
|
||||
col('effective_date', '生效日期', { type: 'date', width: 116 }),
|
||||
col('pay_day', '发薪日', { type: 'number', width: 90, align: 'right', render: (v) => (v ? `${v} 号` : '-') }),
|
||||
col('employee_count', '适用人数', { type: 'number', width: 100, align: 'right' }),
|
||||
col('currency', '币种', { width: 80 }),
|
||||
col('is_active', '启用', { type: 'switch', width: 80 }),
|
||||
col('remark', '备注', { width: 200 }),
|
||||
],
|
||||
col('remark', '备注', { width: 200 })],
|
||||
form: [
|
||||
fld('name', '账套名称', { required: true, placeholder: '如 技术研发序列 / 职能序列' }),
|
||||
fld('code', '账套编码'),
|
||||
|
|
@ -823,7 +864,7 @@ export const batchDef: ResourceDef = {
|
|||
{ label: '已审核', value: 'approved' }, { label: '已发放', value: 'paid' },
|
||||
] }), col('period_id', '薪资账期', { type: 'options', source: '/payroll/periods/options', filterOn: 'period_label' })],
|
||||
columns: [
|
||||
col('name', '批次名称', { width: 200, fixed: 'left', required: true }),
|
||||
col('name', '批次名称', { width: 200, required: true }),
|
||||
col('period_label', '薪资账期', { width: 130 }),
|
||||
col('status', '状态', { type: 'tag', width: 100, options: BATCH_STATUS_OPTIONS }),
|
||||
col('employee_count', '计薪人数', { type: 'number', width: 100, align: 'right' }),
|
||||
|
|
@ -858,8 +899,8 @@ export const payslipDef: ResourceDef = {
|
|||
] }),
|
||||
],
|
||||
columns: [
|
||||
col('work_no', '工号', { width: 106, fixed: 'left' }),
|
||||
col('employee_name', '姓名', { width: 100, fixed: 'left' }),
|
||||
col('work_no', '工号', { width: 106 }),
|
||||
col('employee_name', '姓名', { width: 100 }),
|
||||
col('department_name', '部门', { width: 120 }),
|
||||
col('period_label', '账期', { width: 120 }),
|
||||
col('batch_label', '算薪批次', { width: 150 }),
|
||||
|
|
@ -884,6 +925,13 @@ export const insurancePlanDef: ResourceDef = {
|
|||
],
|
||||
columns: [
|
||||
col('name', '方案名称', { width: 190, required: true }),
|
||||
col('is_active', '启用', { type: 'toggle', width: 100, toggle: {
|
||||
path: (r: any) => `/benefits/insurance-plans/${r.id}`,
|
||||
perm: 'benefits:plan:update',
|
||||
listKey: 'insuranceplan',
|
||||
confirm: (r: any) => `停用后不能作为新的参保方案使用,已有参保登记不受影响。`,
|
||||
invalidate: () => [['boot-options']],
|
||||
} }),
|
||||
col('code', '编码', { width: 120 }),
|
||||
col('city', '参保城市', { type: 'dict', dict: 'insurance_city', width: 110 }),
|
||||
col('base_floor', '社保基数下限', { type: 'money', width: 130 }),
|
||||
|
|
@ -891,9 +939,7 @@ export const insurancePlanDef: ResourceDef = {
|
|||
col('fund_base_floor', '公积金下限', { type: 'money', width: 120 }),
|
||||
col('fund_base_ceiling', '公积金上限', { type: 'money', width: 120 }),
|
||||
col('is_default', '默认方案', { type: 'switch', width: 100 }),
|
||||
col('enrollment_count', '参保人数', { type: 'number', width: 100, align: 'right' }),
|
||||
col('is_active', '启用', { type: 'switch', width: 80 }),
|
||||
],
|
||||
col('enrollment_count', '参保人数', { type: 'number', width: 100, align: 'right' })],
|
||||
form: [
|
||||
fld('name', '方案名称', { required: true, placeholder: '如 深圳标准方案' }),
|
||||
fld('code', '方案编码'),
|
||||
|
|
@ -924,7 +970,7 @@ export const enrollmentDef: ResourceDef = {
|
|||
col('include_in_payroll', '参与算薪', { type: 'switch' }),
|
||||
],
|
||||
columns: [
|
||||
col('employee_name', '员工', { width: 100, fixed: 'left' }),
|
||||
col('employee_name', '员工', { width: 100 }),
|
||||
col('work_no', '工号', { width: 106 }),
|
||||
col('department_name', '部门', { width: 120 }),
|
||||
col('plan_name', '参保方案', { width: 150 }),
|
||||
|
|
@ -963,6 +1009,13 @@ export const benefitItemDef: ResourceDef = {
|
|||
col('taxable', '计税', { type: 'switch' }), col('is_active', '启用', { type: 'switch' })],
|
||||
columns: [
|
||||
col('name', '项目名称', { width: 160, required: true }),
|
||||
col('is_active', '启用', { type: 'toggle', width: 100, toggle: {
|
||||
path: (r: any) => `/benefits/items/${r.id}`,
|
||||
perm: 'benefits:item:update',
|
||||
listKey: 'benefititem',
|
||||
confirm: (r: any) => `停用后不能再发放该福利项目,历史发放记录不受影响。`,
|
||||
invalidate: () => [['boot-options']],
|
||||
} }),
|
||||
col('code', '编码', { width: 120 }),
|
||||
col('category', '类别', { type: 'tag', width: 110, options: BENEFIT_CATEGORY_OPTIONS }),
|
||||
col('default_amount', '默认标准', { type: 'money', width: 120 }),
|
||||
|
|
@ -970,9 +1023,7 @@ export const benefitItemDef: ResourceDef = {
|
|||
col('period', '发放周期', { type: 'tag', width: 100, options: BENEFIT_PERIOD_OPTIONS }),
|
||||
col('taxable', '计税', { type: 'switch', width: 80 }),
|
||||
col('pay_with_salary', '随薪发放', { type: 'switch', width: 110 }),
|
||||
col('record_count', '发放记录', { type: 'number', width: 100, align: 'right' }),
|
||||
col('is_active', '启用', { type: 'switch', width: 80 }),
|
||||
],
|
||||
col('record_count', '发放记录', { type: 'number', width: 100, align: 'right' })],
|
||||
form: [
|
||||
fld('name', '项目名称', { required: true }),
|
||||
fld('code', '项目编码'),
|
||||
|
|
@ -1005,7 +1056,7 @@ export const benefitRecordDef: ResourceDef = {
|
|||
col('source', '发放来源', { type: 'tag', options: BENEFIT_SOURCE_OPTIONS }),
|
||||
],
|
||||
columns: [
|
||||
col('employee_name', '员工', { width: 100, fixed: 'left' }),
|
||||
col('employee_name', '员工', { width: 100 }),
|
||||
col('work_no', '工号', { width: 106 }),
|
||||
col('department_name', '部门', { width: 120 }),
|
||||
col('item_name', '福利项目', { width: 140 }),
|
||||
|
|
@ -1044,6 +1095,13 @@ export const leaveTypeDef: ResourceDef = {
|
|||
],
|
||||
columns: [
|
||||
col('name', '假期名称', { width: 140, required: true }),
|
||||
col('is_active', '启用', { type: 'toggle', width: 100, toggle: {
|
||||
path: (r: any) => `/benefits/leave-types/${r.id}`,
|
||||
perm: 'benefits:leave:update',
|
||||
listKey: 'leavetype',
|
||||
confirm: (r: any) => `停用后员工自助请假不再能选择该假期类型,已有余额与申请不受影响。`,
|
||||
invalidate: () => [['boot-options']],
|
||||
} }),
|
||||
col('code', '编码', { width: 120 }),
|
||||
col('unit', '单位', { type: 'tag', width: 90, options: LEAVE_UNIT_OPTIONS }),
|
||||
col('paid', '带薪', { type: 'switch', width: 80 }),
|
||||
|
|
@ -1051,9 +1109,7 @@ export const leaveTypeDef: ResourceDef = {
|
|||
col('requires_certificate', '需证明', { type: 'switch', width: 100 }),
|
||||
col('max_days_per_year', '年度上限', { type: 'number', width: 100, align: 'right' }),
|
||||
col('color', '标识色', { type: 'color', width: 100 }),
|
||||
col('sort', '排序', { type: 'number', width: 80 }),
|
||||
col('is_active', '启用', { type: 'switch', width: 80 }),
|
||||
],
|
||||
col('sort', '排序', { type: 'number', width: 80 })],
|
||||
form: [
|
||||
fld('name', '假期名称', { required: true }),
|
||||
fld('code', '假期编码'),
|
||||
|
|
@ -1084,7 +1140,7 @@ export const leaveRequestDef: ResourceDef = {
|
|||
col('start_date', '开始日期', { type: 'dateRange' }),
|
||||
],
|
||||
columns: [
|
||||
col('employee_name', '申请人', { width: 100, fixed: 'left' }),
|
||||
col('employee_name', '申请人', { width: 100 }),
|
||||
col('work_no', '工号', { width: 106 }),
|
||||
col('department_name', '部门', { width: 120 }),
|
||||
col('leave_type_name', '假期类型', { width: 110 }),
|
||||
|
|
@ -1157,16 +1213,21 @@ export const userDef: ResourceDef = {
|
|||
col('role_ids', '角色', { type: 'options', source: '/system/roles/options', filterOn: 'role_names' }),
|
||||
],
|
||||
columns: [
|
||||
col('username', '登录账号', { width: 130, fixed: 'left', required: true }),
|
||||
col('username', '登录账号', { width: 130, required: true }),
|
||||
col('is_active', '启用', { type: 'toggle', width: 100, toggle: {
|
||||
path: (r: any) => `/system/users/${r.id}`,
|
||||
perm: 'system:user:update',
|
||||
listKey: 'user',
|
||||
confirm: (r: any) => `停用后该账号立即无法登录,已登录会话在下一次请求时失效。`,
|
||||
invalidate: () => [['boot-options']],
|
||||
} }),
|
||||
col('name', '姓名', { width: 110, required: true }),
|
||||
col('employee_name', '关联员工', { width: 110 }),
|
||||
col('role_names', '角色', { type: 'tags', width: 200, render: (_v, r) => (r.roles || []).map((x: any) => x.name).join('、') || '-' }),
|
||||
col('phone', '手机号', { width: 128 }),
|
||||
col('email', '邮箱', { width: 190 }),
|
||||
col('is_active', '启用', { type: 'switch', width: 80 }),
|
||||
col('last_login_at', '最近登录', { type: 'datetime', width: 160 }),
|
||||
col('created_at', '创建时间', { type: 'datetime', width: 160 }),
|
||||
],
|
||||
col('created_at', '创建时间', { type: 'datetime', width: 160 })],
|
||||
form: [
|
||||
fld('username', '登录账号', { required: true }),
|
||||
fld('name', '姓名', { required: true }),
|
||||
|
|
@ -1218,7 +1279,7 @@ export const announcementDef: ResourceDef = {
|
|||
] }),
|
||||
],
|
||||
columns: [
|
||||
col('title', '标题', { width: 260, fixed: 'left', required: true }),
|
||||
col('title', '标题', { width: 260, required: true }),
|
||||
col('category', '分类', { type: 'tag', width: 110, options: ANNOUNCEMENT_CATEGORY_OPTIONS }),
|
||||
col('level', '重要程度', { type: 'tag', width: 100, options: ANNOUNCEMENT_LEVEL_OPTIONS }),
|
||||
col('publisher', '发布人', { width: 100 }),
|
||||
|
|
@ -1264,11 +1325,16 @@ export const dictItemDef: ResourceDef = {
|
|||
filters: [col('is_active', '启用', { type: 'switch' })],
|
||||
columns: [
|
||||
col('label', '显示标签', { width: 170, required: true }),
|
||||
col('is_active', '启用', { type: 'toggle', width: 110, toggle: {
|
||||
path: (r: any) => `/system/dict-items/${r.id}`,
|
||||
perm: 'system:dict:update',
|
||||
listKey: 'dictitem',
|
||||
confirm: (r: any) => `停用后该字典项不再出现在下拉中,已保存的数据仍按原值显示。`,
|
||||
invalidate: () => [['boot-options']],
|
||||
} }),
|
||||
col('value', '存储值', { width: 150, required: true }),
|
||||
col('extra', '扩展值', { width: 140 }),
|
||||
col('sort', '排序', { type: 'number', width: 90 }),
|
||||
col('is_active', '启用', { type: 'switch', width: 90 }),
|
||||
],
|
||||
col('sort', '排序', { type: 'number', width: 90 })],
|
||||
form: [
|
||||
fld('label', '显示标签', { required: true }),
|
||||
fld('value', '存储值', { required: true }),
|
||||
|
|
@ -1289,7 +1355,7 @@ export const logDef: ResourceDef = {
|
|||
col('status_code', '响应码', { type: 'tag', options: RESPONSE_CODE_OPTIONS }),
|
||||
col('created_at', '操作时间', { type: 'dateRange' })],
|
||||
columns: [
|
||||
col('created_at', '操作时间', { type: 'datetime', width: 170, fixed: 'left' }),
|
||||
col('created_at', '操作时间', { type: 'datetime', width: 170 }),
|
||||
col('username', '操作人', { width: 120 }),
|
||||
col('module', '模块', { type: 'tag', width: 110 }),
|
||||
col('action', '动作', { width: 140 }),
|
||||
|
|
|
|||
|
|
@ -42,6 +42,7 @@ export const ROUTE_PERMS: Record<string, string[]> = {
|
|||
'/system/announcements': ['system:announcement:read'], // 公告通知
|
||||
'/system/dicts': ['system:dict:read'], // 数据字典
|
||||
'/system/logs': ['system:log:read'], // 操作日志
|
||||
'/system/maintenance': ['system:maintenance:read'], // 数据维护
|
||||
'/system/roles': ['system:role:read'], // 角色权限
|
||||
'/system/users': ['system:user:read'], // 用户管理
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import dayjs from 'dayjs'
|
|||
import type { FieldDef } from '../api/defs'
|
||||
import { badgeStatusOf, EMP_STATUS_OPTIONS, flowLabel, L, money, optLabel, tagColorOf } from '../api/defs'
|
||||
import { useDict, useOptionSource } from '../hooks/useOptions'
|
||||
import { ToggleCell } from './StatusSwitch'
|
||||
|
||||
const { Text } = Typography
|
||||
|
||||
|
|
@ -107,6 +108,8 @@ export default function Cell({ field, row }: { field: FieldDef; row: any }) {
|
|||
return <span className="num">{dayjs(raw).format('YYYY-MM-DD HH:mm')}</span>
|
||||
case 'switch':
|
||||
return raw ? <Tag color="green">是</Tag> : <Tag>否</Tag>
|
||||
case 'toggle':
|
||||
return field.toggle ? <ToggleCell field={field} row={row} /> : raw ? <Tag color="green">启用</Tag> : <Tag>停用</Tag>
|
||||
case 'tag': {
|
||||
const hit = field.options?.find((o) => String(o.value) === String(raw))
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -32,6 +32,7 @@ function OptionSelect({
|
|||
const source = field.source && !field.source.startsWith('dict:') ? field.source : undefined
|
||||
const q = useOptionSource(source)
|
||||
const opts = inline ?? q.data ?? []
|
||||
const picked: any[] = Array.isArray(value) ? value : value === undefined || value === null ? [] : [value]
|
||||
return (
|
||||
<Select
|
||||
allowClear
|
||||
|
|
@ -44,7 +45,12 @@ function OptionSelect({
|
|||
disabled={disabled}
|
||||
value={value ?? (field.multiple ? [] : undefined)}
|
||||
onChange={onChange}
|
||||
options={opts.map((o: any) => ({ label: o.label, value: o.value }))}
|
||||
options={opts.map((o: any) => ({
|
||||
// 停用资源统一在这里收口:仍可回显(否则历史记录的名称解析不出来),但不能再被新选中
|
||||
label: o.extra?.is_active === false ? `${o.label}(已停用)` : o.label,
|
||||
value: o.value,
|
||||
disabled: o.extra?.is_active === false && !picked.some((v) => String(v) === String(o.value)),
|
||||
}))}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
|
@ -167,6 +173,7 @@ export default function FieldInput({
|
|||
/>
|
||||
)
|
||||
case 'switch':
|
||||
case 'toggle':
|
||||
return <Switch disabled={disabled} checked={!!value} onChange={(v) => onChange?.(v)} />
|
||||
case 'rate':
|
||||
return <Rate disabled={disabled} value={Number(value ?? 0)} onChange={onChange} />
|
||||
|
|
@ -225,7 +232,7 @@ export default function FieldInput({
|
|||
|
||||
/** Form.Item 需要的额外属性(Switch 用 checked,其它用 value) */
|
||||
export function itemProps(field: FieldDef) {
|
||||
return field.type === 'switch' ? { valuePropName: 'checked' } : {}
|
||||
return field.type === 'switch' || field.type === 'toggle' ? { valuePropName: 'checked' } : {}
|
||||
}
|
||||
|
||||
/** 提交前把表单值转换成接口载荷 */
|
||||
|
|
|
|||
|
|
@ -0,0 +1,110 @@
|
|||
import { DownloadOutlined, InboxOutlined } from '@ant-design/icons'
|
||||
import { App, Button, Drawer, Progress, Space, Upload } from 'antd'
|
||||
import { useState } from 'react'
|
||||
import { download, upload } from '../api/http'
|
||||
|
||||
export interface ImportDrawerProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onDone?: () => void
|
||||
title: string
|
||||
templatePath: string
|
||||
importPath: string
|
||||
templateName?: string
|
||||
tips?: string[]
|
||||
}
|
||||
|
||||
interface ImportResult {
|
||||
total: number
|
||||
created: number
|
||||
updated: number
|
||||
failed: number
|
||||
errors?: { row: number; name?: string; message: string }[]
|
||||
}
|
||||
|
||||
/** 通用批量导入抽屉:模板下载与文件上传都走带 token 的 http 客户端。 */
|
||||
export default function ImportDrawer(props: ImportDrawerProps) {
|
||||
const { open, onClose, onDone, title, templatePath, importPath, templateName, tips } = props
|
||||
const { message } = App.useApp()
|
||||
const [result, setResult] = useState<ImportResult | null>(null)
|
||||
const [uploading, setUploading] = useState(false)
|
||||
const lines = tips?.length ? tips : ['先下载模板,按表头填写后再上传;编码相同的记录会被更新。']
|
||||
|
||||
const close = () => {
|
||||
setResult(null)
|
||||
onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<Drawer open={open} onClose={close} title={title} width={540}>
|
||||
<Space direction="vertical" size={14} style={{ width: '100%' }}>
|
||||
<div style={{ background: '#fbfcff', border: '1px solid #eef0f5', borderRadius: 10, padding: 14, fontSize: 13, color: '#475467' }}>
|
||||
{lines.map((tip, index) => (
|
||||
<div key={index} style={{ marginBottom: index === lines.length - 1 ? 0 : 4 }}>
|
||||
{index + 1}. {tip}
|
||||
</div>
|
||||
))}
|
||||
<div style={{ marginTop: 6, color: '#98a2b3' }}>支持 .xlsx / .csv(旧版 .xls 请另存为 .xlsx)</div>
|
||||
</div>
|
||||
|
||||
<Space wrap>
|
||||
<Button
|
||||
icon={<DownloadOutlined />}
|
||||
onClick={() => download(templatePath, undefined, templateName || '导入模板.xlsx')}
|
||||
>
|
||||
下载模板
|
||||
</Button>
|
||||
<Upload
|
||||
accept=".xlsx,.csv"
|
||||
showUploadList={false}
|
||||
customRequest={async ({ file, onSuccess, onError }: any) => {
|
||||
setUploading(true)
|
||||
try {
|
||||
const data = await upload<ImportResult>(importPath, file as File)
|
||||
setResult(data)
|
||||
onSuccess?.(data)
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '导入失败')
|
||||
onError?.(e)
|
||||
} finally {
|
||||
setUploading(false)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Button type="primary" loading={uploading} icon={<InboxOutlined />}>
|
||||
上传文件并导入
|
||||
</Button>
|
||||
</Upload>
|
||||
</Space>
|
||||
|
||||
{result && (
|
||||
<div>
|
||||
<Progress
|
||||
percent={Math.round(((result.created + result.updated) / Math.max(result.total, 1)) * 100)}
|
||||
status={result.failed ? 'exception' : 'success'}
|
||||
/>
|
||||
<p style={{ fontSize: 13 }}>
|
||||
共 {result.total} 行,新增 <b>{result.created}</b>,更新 <b>{result.updated}</b>,失败{' '}
|
||||
<b style={{ color: '#ff4d4f' }}>{result.failed}</b>
|
||||
</p>
|
||||
{(result.errors || []).slice(0, 15).map((e, i) => (
|
||||
<div key={i} style={{ fontSize: 12, color: '#98a2b3' }}>
|
||||
· 第 {e.row} 行{e.name ? `(${e.name})` : ''}:{e.message}
|
||||
</div>
|
||||
))}
|
||||
<Button
|
||||
style={{ marginTop: 12 }}
|
||||
type="primary"
|
||||
onClick={() => {
|
||||
onDone?.()
|
||||
close()
|
||||
}}
|
||||
>
|
||||
完成并刷新
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Space>
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
import { PlusOutlined, ReloadOutlined, DownloadOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons'
|
||||
import {
|
||||
MoreOutlined, PlusOutlined, ReloadOutlined, DownloadOutlined, EditOutlined, DeleteOutlined,
|
||||
} from '@ant-design/icons'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { App, Button, Card, Col, Flex, Form, Row, Space, Table, Typography } from 'antd'
|
||||
import { App, Button, Card, Col, Dropdown, Flex, Form, Row, Space, Table, Tooltip, Typography } from 'antd'
|
||||
import type { ColumnsType } from 'antd/es/table'
|
||||
import { useMemo, useState } from 'react'
|
||||
import { clean, del, download, list, patch, post } from '../api/http'
|
||||
|
|
@ -26,6 +28,15 @@ export interface ResourceTableProps {
|
|||
toolbar?: React.ReactNode
|
||||
/** 行尾自定义操作 */
|
||||
rowActions?: (row: any, helpers: { refresh: () => void; edit: (row: any) => void }) => React.ReactNode
|
||||
/**
|
||||
* 行「更多」菜单项(低频动作)。渲染为竖三点按钮,永远排在操作列最后一位,
|
||||
* 这样各模块的操作列顺序固定为:自定义操作 → 编辑 → 删除 → ⋮。
|
||||
*/
|
||||
rowMore?: (row: any, helpers: { refresh: () => void; edit: (row: any) => void }) => any[]
|
||||
/** 「更多」菜单点击回调(由 ResourceTable 统一处理冒泡与收起) */
|
||||
onRowMore?: (key: string, row: any, helpers: { refresh: () => void; edit: (row: any) => void }) => void
|
||||
/** 操作列宽度;自定义行操作较多时可调大 */
|
||||
actionsWidth?: number
|
||||
onRow?: (row: any) => any
|
||||
createText?: string
|
||||
formTitle?: (row: any | null) => string
|
||||
|
|
@ -44,7 +55,9 @@ export interface ResourceTableProps {
|
|||
}
|
||||
|
||||
export default function ResourceTable(props: ResourceTableProps) {
|
||||
const { def, params, title, desc, toolbar, rowActions, onRow, size = 'middle', hidden = [] } = props
|
||||
const {
|
||||
def, params, title, desc, toolbar, rowActions, rowMore, onRowMore, actionsWidth, onRow, size = 'middle', hidden = [],
|
||||
} = props
|
||||
const { message, modal } = App.useApp()
|
||||
const qc = useQueryClient()
|
||||
const hasPerm = useAuth((s) => s.hasPerm)
|
||||
|
|
@ -150,6 +163,10 @@ export default function ResourceTable(props: ResourceTableProps) {
|
|||
|
||||
const columns: ColumnsType<any> = useMemo(() => {
|
||||
const visible = def.columns.filter((c) => c.type !== 'hidden' && !hidden.includes(c.name))
|
||||
// 统一列序口径:启停开关一律排在数据列最后(紧贴操作列),
|
||||
// 数据列一律不做左侧固定,避免固定列互相挤压 / 被右侧操作列遮挡。
|
||||
const toggles = visible.filter((c) => c.type === 'toggle')
|
||||
const dataCols = visible.filter((c) => c.type !== 'toggle')
|
||||
const byName = new Map(visible.map((c) => [c.name, c]))
|
||||
// 筛选字段挂到「同名列」上;外键字段自动落到 <base>_name 展示列
|
||||
const filterExtras: Record<string, any> = {}
|
||||
|
|
@ -165,24 +182,27 @@ export default function ResourceTable(props: ResourceTableProps) {
|
|||
filteredValue: flt.values[f.name]?.length ? flt.values[f.name] : null,
|
||||
}
|
||||
})
|
||||
const cols: ColumnsType<any> = visible.map((c) => ({
|
||||
const build = (c: FieldDef) => ({
|
||||
title: c.label,
|
||||
dataIndex: c.name,
|
||||
key: c.name,
|
||||
width: c.width,
|
||||
align: c.align ?? (['money', 'number', 'percent'].includes(c.type || '') ? 'right' : 'left'),
|
||||
fixed: c.fixed,
|
||||
sorter: c.sortable === true,
|
||||
ellipsis: true,
|
||||
render: (_: any, row: any) => <Cell field={c} row={row} />,
|
||||
...filterExtras[c.name],
|
||||
}))
|
||||
if (canUpdate || canDelete || rowActions) {
|
||||
})
|
||||
// 开关属于「操作面板」而不是数据列:钉在右侧、排在操作列左边,
|
||||
// 这样横向滚动时它永远在行尾可见,也不会被操作列盖住(盖住会误点删除)。
|
||||
const cols: ColumnsType<any> = [...dataCols.map(build), ...toggles.map((c) => ({ ...build(c), fixed: 'right' as const }))]
|
||||
const opsWidth = actionsWidth ?? (rowActions ? 220 : 120) + (rowMore ? 48 : 0)
|
||||
if (canUpdate || canDelete || rowActions || rowMore) {
|
||||
cols.push({
|
||||
title: '操作',
|
||||
key: '__ops',
|
||||
fixed: 'right',
|
||||
width: rowActions ? 200 : 120,
|
||||
width: opsWidth,
|
||||
render: (_: any, row: any) => (
|
||||
<Space size={0} onClick={(e) => e.stopPropagation()}>
|
||||
{rowActions?.(row, { refresh, edit: openForm })}
|
||||
|
|
@ -196,12 +216,18 @@ export default function ResourceTable(props: ResourceTableProps) {
|
|||
删除
|
||||
</Button>
|
||||
)}
|
||||
{rowMore && (
|
||||
<RowMoreButton
|
||||
items={rowMore(row, { refresh, edit: openForm })}
|
||||
onPick={(key) => onRowMore?.(key, row, { refresh, edit: openForm })}
|
||||
/>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
})
|
||||
}
|
||||
return cols
|
||||
}, [def.columns, hidden, canUpdate, canDelete, rowActions, urlFilters, keyword, sort, flt.values])
|
||||
}, [def.columns, hidden, canUpdate, canDelete, rowActions, rowMore, onRowMore, actionsWidth, urlFilters, keyword, sort, flt.values])
|
||||
|
||||
const resetAll = () => {
|
||||
flt.reset()
|
||||
|
|
@ -380,3 +406,29 @@ export function useResource(def: ResourceDef, params?: Record<string, any>, extr
|
|||
queryFn: () => list(def.path, clean({ page: 1, page_size: 200, ...params })),
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 操作列末尾的「更多」按钮:竖三点图标 + 下拉二级面板。
|
||||
* 没有可用项时整按钮不渲染,避免操作列出现空按钮。
|
||||
*/
|
||||
function RowMoreButton({ items, onPick }: { items: any[]; onPick: (key: string) => void }) {
|
||||
const menu = (items || []).filter(Boolean)
|
||||
if (!menu.length) return null
|
||||
return (
|
||||
<Dropdown
|
||||
trigger={['click']}
|
||||
placement="bottomRight"
|
||||
menu={{
|
||||
items: menu,
|
||||
onClick: ({ key, domEvent }) => {
|
||||
domEvent?.stopPropagation?.()
|
||||
onPick(String(key))
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Tooltip title="更多操作">
|
||||
<Button type="text" size="small" icon={<MoreOutlined />} />
|
||||
</Tooltip>
|
||||
</Dropdown>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,104 @@
|
|||
import { App, Switch } from 'antd'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { useState } from 'react'
|
||||
import { patch } from '../api/http'
|
||||
import { useAuth } from '../store/auth'
|
||||
|
||||
export interface StatusSwitchProps {
|
||||
/** PATCH 地址,例如 /employees/12 */
|
||||
path: string
|
||||
checked: boolean
|
||||
/** 需要的权限码;缺省表示任何登录用户都可点(后端仍会再校验) */
|
||||
perm?: string
|
||||
/** 停用(关闭开关)时的确认文案;不填则不二次确认 */
|
||||
confirmTitle?: string
|
||||
disabled?: boolean
|
||||
disabledReason?: string
|
||||
/** 保存成功后的额外刷新(父组件刷新自己的详情查询等) */
|
||||
onDone?: (next: boolean) => void
|
||||
/** 成功后额外失效的 queryKey */
|
||||
invalidate?: readonly (readonly unknown[])[]
|
||||
}
|
||||
|
||||
/**
|
||||
* 内联启停开关:点一下直接 PATCH,不再多弹一层确认(仅在「停用」这个危险方向确认)。
|
||||
* 失败时不改本地状态,由 react-query 重新拉取兜底,避免界面与库不一致。
|
||||
*/
|
||||
export default function StatusSwitch(props: StatusSwitchProps) {
|
||||
const { path, checked, perm, confirmTitle, disabled, disabledReason, onDone, invalidate = [] } = props
|
||||
const { message, modal } = App.useApp()
|
||||
const qc = useQueryClient()
|
||||
const hasPerm = useAuth((s) => s.hasPerm)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const on = !!checked
|
||||
|
||||
const afterSave = (next: boolean) => {
|
||||
message.success(next ? '已启用' : '已停用')
|
||||
invalidate.forEach((key) => qc.invalidateQueries({ queryKey: key as unknown[] }))
|
||||
onDone?.(next)
|
||||
}
|
||||
|
||||
const apply = async (next: boolean) => {
|
||||
setBusy(true)
|
||||
try {
|
||||
await patch(path, { is_active: next })
|
||||
afterSave(next)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const toggle = () => {
|
||||
const next = !on
|
||||
if (perm && !hasPerm(perm)) return void message.warning(`没有权限执行该操作(需要 ${perm})`)
|
||||
if (disabled) return void message.warning(disabledReason || '当前不可操作')
|
||||
if (!next && confirmTitle) {
|
||||
modal.confirm({
|
||||
title: confirmTitle,
|
||||
okText: '确认停用',
|
||||
okButtonProps: { danger: true },
|
||||
onOk: () => apply(false),
|
||||
})
|
||||
return
|
||||
}
|
||||
void apply(next)
|
||||
}
|
||||
|
||||
return (
|
||||
// 列表整行可点(打开档案抽屉),开关必须自己吃掉点击,否则一点就顺带弹出抽屉
|
||||
<span onClick={(e) => e.stopPropagation()} style={{ display: 'inline-flex', alignItems: 'center' }}>
|
||||
<Switch
|
||||
size="small"
|
||||
checked={on}
|
||||
loading={busy}
|
||||
disabled={!!disabled}
|
||||
checkedChildren="启用"
|
||||
unCheckedChildren="停用"
|
||||
onChange={(_next, e) => {
|
||||
e?.stopPropagation?.()
|
||||
toggle()
|
||||
}}
|
||||
onClick={(_c, e) => e?.stopPropagation?.()}
|
||||
/>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** 由列定义驱动的内联开关(Cell 使用):保存后刷新列表与该列声明的附加缓存 */
|
||||
export function ToggleCell({ field, row }: { field: import('../api/defs').FieldDef; row: any }) {
|
||||
const qc = useQueryClient()
|
||||
const cfg = field.toggle!
|
||||
return (
|
||||
<StatusSwitch
|
||||
path={cfg.path(row)}
|
||||
checked={!!row[field.name]}
|
||||
perm={cfg.perm}
|
||||
confirmTitle={cfg.confirm?.(row)}
|
||||
onDone={() => {
|
||||
qc.invalidateQueries({ queryKey: ['list', cfg.listKey] })
|
||||
qc.invalidateQueries({ queryKey: ['options'] })
|
||||
;(cfg.invalidate?.(row) || []).forEach((key) => qc.invalidateQueries({ queryKey: key as unknown[] }))
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
|
@ -13,6 +13,7 @@ import {
|
|||
ContactsOutlined,
|
||||
CrownOutlined,
|
||||
DashboardOutlined,
|
||||
DatabaseOutlined,
|
||||
ExperimentOutlined,
|
||||
FileDoneOutlined,
|
||||
FileProtectOutlined,
|
||||
|
|
@ -70,6 +71,7 @@ const REGISTRY: Record<string, IconComp> = {
|
|||
ContactsOutlined,
|
||||
CrownOutlined,
|
||||
DashboardOutlined,
|
||||
DatabaseOutlined,
|
||||
ExperimentOutlined,
|
||||
FileDoneOutlined,
|
||||
FileProtectOutlined,
|
||||
|
|
|
|||
|
|
@ -184,8 +184,8 @@ function MatrixTab({ year }: { year: number }) {
|
|||
const rows: any[] = q.data?.rows || []
|
||||
|
||||
const cols: any[] = [
|
||||
{ title: '工号', dataIndex: 'work_no', width: 108, fixed: 'left' },
|
||||
{ title: '姓名', dataIndex: 'employee_name', width: 100, fixed: 'left' },
|
||||
{ title: '工号', dataIndex: 'work_no', width: 108 },
|
||||
{ title: '姓名', dataIndex: 'employee_name', width: 100 },
|
||||
{ title: '部门', dataIndex: 'department_name', width: 130, ellipsis: true },
|
||||
...types.map((t) => ({
|
||||
title: (
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
import { ArrowLeftOutlined, CheckCircleOutlined, SwapOutlined, UserSwitchOutlined } from '@ant-design/icons'
|
||||
import {
|
||||
ArrowLeftOutlined, CheckCircleOutlined, MoreOutlined, SwapOutlined, UserSwitchOutlined,
|
||||
} from '@ant-design/icons'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { App, Avatar, Button, Card, Col, DatePicker, Row, Descriptions, Divider, Flex, Form, Input, Select, Space, Spin, Statistic, Switch, Tabs, Tag, Timeline, Typography } from 'antd'
|
||||
import { App, Avatar, Button, Card, Col, DatePicker, Dropdown, Row, Descriptions, Divider, Flex, Form, Input, Select, Space, Spin, Statistic, Switch, Tabs, Tag, Timeline, Tooltip, Typography } from 'antd'
|
||||
import dayjs from 'dayjs'
|
||||
import { useState } from 'react'
|
||||
import { useNavigate, useParams } from 'react-router-dom'
|
||||
|
|
@ -17,7 +19,8 @@ import {
|
|||
tagColorOf,
|
||||
yuan,
|
||||
} from '../../api/defs'
|
||||
import { get, post } from '../../api/http'
|
||||
import { get, patch, post } from '../../api/http'
|
||||
import GenerateAccounts from './GenerateAccounts'
|
||||
import {
|
||||
certificateDef,
|
||||
educationDef,
|
||||
|
|
@ -46,6 +49,7 @@ export default function EmployeeDetail({ id, embedded }: Props) {
|
|||
const { message, modal } = App.useApp()
|
||||
const hasPerm = useAuth((s) => s.hasPerm)
|
||||
const [action, setAction] = useState<null | 'transfer' | 'regular' | 'resign'>(null)
|
||||
const [accountOpen, setAccountOpen] = useState(false)
|
||||
const [form] = Form.useForm()
|
||||
// 弹窗每次打开都从干净状态开始(部门/职位/日期不残留上次的输入)
|
||||
useModalFormFill(form, !!action, () => {})
|
||||
|
|
@ -84,6 +88,53 @@ export default function EmployeeDetail({ id, embedded }: Props) {
|
|||
},
|
||||
})
|
||||
|
||||
const toggleActive = useMutation({
|
||||
mutationFn: (next: boolean) => patch(`/employees/${empId}`, { is_active: next }),
|
||||
onSuccess: (_r, next) => {
|
||||
message.success(next ? '员工档案已启用' : '员工档案已停用')
|
||||
refresh()
|
||||
qc.invalidateQueries({ queryKey: ['list', 'employee'] })
|
||||
qc.invalidateQueries({ queryKey: ['options', '/employees/options'] })
|
||||
qc.invalidateQueries({ queryKey: ['employee-stats'] })
|
||||
},
|
||||
})
|
||||
|
||||
const confirmDeactivate = () => {
|
||||
modal.confirm({
|
||||
title: `停用「${e?.name || ''}」的员工档案?`,
|
||||
content: '停用后该档案不能再被新业务选中,也不能生成登录账号;已有账号不受影响,可随时重新启用。',
|
||||
okText: '确认停用',
|
||||
okButtonProps: { danger: true },
|
||||
onOk: () => toggleActive.mutateAsync(false),
|
||||
})
|
||||
}
|
||||
|
||||
// 「更多」收纳低频动作,头部只留转正/调岗/离职这三条主线
|
||||
const accountBlocked = !!e?.has_account || e?.is_active === false || e?.status === 'resigned'
|
||||
const accountHint = e?.has_account ? '已开通登录账号'
|
||||
: e?.status === 'resigned' ? '离职档案不可生成账号'
|
||||
: e?.is_active === false ? '请先启用档案' : '生成平台账号'
|
||||
const moreItems = [
|
||||
hasPerm('system:user:create') && {
|
||||
key: 'account',
|
||||
disabled: accountBlocked,
|
||||
label: accountHint,
|
||||
},
|
||||
hasPerm('employee:employee:update') && {
|
||||
key: 'toggle',
|
||||
danger: e?.is_active !== false,
|
||||
label: e?.is_active !== false ? '停用档案' : '启用档案',
|
||||
},
|
||||
].filter(Boolean) as any[]
|
||||
|
||||
const onMore = (key: string) => {
|
||||
if (key === 'account') return setAccountOpen(true)
|
||||
if (key === 'toggle') {
|
||||
if (e?.is_active !== false) return confirmDeactivate()
|
||||
return toggleActive.mutate(true)
|
||||
}
|
||||
}
|
||||
|
||||
const boot = useBoot()
|
||||
const toOpts = (arr: any[] | undefined) =>
|
||||
(arr || []).map((x: any) => ({ label: x.full_label ?? x.label ?? x.name, value: x.id }))
|
||||
|
|
@ -173,6 +224,17 @@ export default function EmployeeDetail({ id, embedded }: Props) {
|
|||
离职
|
||||
</Button>
|
||||
)}
|
||||
{!!moreItems.length && (
|
||||
<Dropdown
|
||||
menu={{ items: moreItems, onClick: ({ key }) => onMore(key) }}
|
||||
trigger={['click']}
|
||||
placement="bottomRight"
|
||||
>
|
||||
<Tooltip title="更多操作">
|
||||
<Button icon={<MoreOutlined />} />
|
||||
</Tooltip>
|
||||
</Dropdown>
|
||||
)}
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
|
|
@ -453,6 +515,15 @@ export default function EmployeeDetail({ id, embedded }: Props) {
|
|||
</Form.Item>
|
||||
</Form>
|
||||
</FormDrawer>
|
||||
|
||||
{/* 生成平台账号:停用档案不可生成(后端同样会跳过) */}
|
||||
<GenerateAccounts
|
||||
open={accountOpen}
|
||||
presetEmployeeId={empId}
|
||||
onClose={() => setAccountOpen(false)}
|
||||
onDone={refresh}
|
||||
/>
|
||||
|
||||
</Space>
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,27 +1,46 @@
|
|||
import { ImportOutlined, TeamOutlined } from '@ant-design/icons'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { App, Button, Drawer, Progress, Space, Upload } from 'antd'
|
||||
import { ImportOutlined, TeamOutlined, UserAddOutlined } from '@ant-design/icons'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { App, Button, Drawer, Space } from 'antd'
|
||||
import { useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { employeeDef } from '../../api/resources'
|
||||
import { get } from '../../api/http'
|
||||
import ImportDrawer from '../../components/ImportDrawer'
|
||||
import ResourceTable from '../../components/ResourceTable'
|
||||
import { useAuth } from '../../store/auth'
|
||||
import EmployeeDetail from './EmployeeDetail'
|
||||
import GenerateAccounts from './GenerateAccounts'
|
||||
|
||||
/** 花名册:通用资源表 + 行内打开 360 档案抽屉 + 批量导入 */
|
||||
/** 花名册:通用资源表 + 行内打开 360 档案抽屉 + 批量导入 + 档案建号 */
|
||||
export default function EmployeeList() {
|
||||
const nav = useNavigate()
|
||||
const qc = useQueryClient()
|
||||
const { message } = App.useApp()
|
||||
const hasPerm = useAuth((s) => s.hasPerm)
|
||||
const [drawer, setDrawer] = useState<number | null>(null)
|
||||
const [importOpen, setImportOpen] = useState(false)
|
||||
const [generateOpen, setGenerateOpen] = useState(false)
|
||||
const [presetEmployeeId, setPresetEmployeeId] = useState<number | null>(null)
|
||||
const stats = useQuery({ queryKey: ['employee-stats'], queryFn: () => get('/employees/stats') })
|
||||
|
||||
const s = stats.data
|
||||
|
||||
const refreshEmployees = () => {
|
||||
qc.invalidateQueries({ queryKey: ['list', 'employee'] })
|
||||
qc.invalidateQueries({ queryKey: ['options', '/employees/options'] })
|
||||
stats.refetch()
|
||||
}
|
||||
|
||||
const openGenerate = (employeeId: number | null = null) => {
|
||||
setPresetEmployeeId(employeeId)
|
||||
setGenerateOpen(true)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<ResourceTable
|
||||
def={employeeDef}
|
||||
actionsWidth={160}
|
||||
title={
|
||||
<Space>
|
||||
<TeamOutlined style={{ color: '#2f54eb' }} />
|
||||
|
|
@ -35,17 +54,40 @@ export default function EmployeeList() {
|
|||
}
|
||||
desc="点击任意行查看 360° 员工档案;支持按状态、部门、用工形式组合筛选。"
|
||||
toolbar={
|
||||
<Button icon={<ImportOutlined />} onClick={() => setImportOpen(true)}>
|
||||
批量导入
|
||||
</Button>
|
||||
<>
|
||||
{hasPerm('system:user:create') && (
|
||||
<Button icon={<UserAddOutlined />} onClick={() => openGenerate()}>
|
||||
生成账号
|
||||
</Button>
|
||||
)}
|
||||
<Button icon={<ImportOutlined />} onClick={() => setImportOpen(true)}>
|
||||
批量导入
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
onRow={(row) => ({ onClick: () => setDrawer(row.id), style: { cursor: 'pointer' } })}
|
||||
// 通用操作列自带「编辑 / 删除」,这里只补一个「档案」入口,别再重复渲染编辑按钮
|
||||
rowActions={(row) => (
|
||||
<Button size="small" type="link" onClick={() => nav(`/employees/${row.id}`)}>
|
||||
档案
|
||||
</Button>
|
||||
)}
|
||||
// 低频动作收进操作列末尾的「⋮」二级面板:停用档案不允许生成账号
|
||||
rowMore={(row) => [
|
||||
hasPerm('system:user:create') && {
|
||||
key: 'account',
|
||||
disabled: !!row.has_account || row.is_active === false || row.status === 'resigned',
|
||||
label: row.has_account
|
||||
? '已开通登录账号'
|
||||
: row.status === 'resigned'
|
||||
? '离职档案不可生成账号'
|
||||
: row.is_active === false
|
||||
? '请先启用档案'
|
||||
: '生成平台账号',
|
||||
},
|
||||
].filter(Boolean)}
|
||||
onRowMore={(key, row) => {
|
||||
if (key === 'account') openGenerate(row.id)
|
||||
}}
|
||||
/>
|
||||
|
||||
<Drawer
|
||||
|
|
@ -58,76 +100,32 @@ export default function EmployeeList() {
|
|||
{drawer && <EmployeeDetail id={drawer} embedded />}
|
||||
</Drawer>
|
||||
|
||||
<ImportRoster
|
||||
<ImportDrawer
|
||||
open={importOpen}
|
||||
onClose={() => setImportOpen(false)}
|
||||
onDone={() => {
|
||||
message.success('导入完成')
|
||||
setImportOpen(false)
|
||||
stats.refetch()
|
||||
refreshEmployees()
|
||||
}}
|
||||
title="批量导入员工花名册"
|
||||
templatePath="/employees/import-template"
|
||||
importPath="/employees/import"
|
||||
templateName="员工导入模板.xlsx"
|
||||
tips={[
|
||||
'下载导入模板并按列填写(工号留空由系统自动发号,重复工号将执行更新)。',
|
||||
'部门 / 职位 / 职级需与系统内名称完全一致。',
|
||||
]}
|
||||
/>
|
||||
|
||||
<GenerateAccounts
|
||||
open={generateOpen}
|
||||
presetEmployeeId={presetEmployeeId}
|
||||
onClose={() => {
|
||||
setGenerateOpen(false)
|
||||
setPresetEmployeeId(null)
|
||||
}}
|
||||
onDone={refreshEmployees}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function ImportRoster({ open, onClose, onDone }: { open: boolean; onClose: () => void; onDone: () => void }) {
|
||||
const { message } = App.useApp()
|
||||
const [result, setResult] = useState<any>(null)
|
||||
return (
|
||||
<Drawer open={open} onClose={onClose} title="批量导入员工花名册" width={520}>
|
||||
<Space direction="vertical" size={14} style={{ width: '100%' }}>
|
||||
<div style={{ background: '#fbfcff', border: '1px solid #eef0f5', borderRadius: 10, padding: 14, fontSize: 13, color: '#475467' }}>
|
||||
1. 下载导入模板并按列填写(工号留空由系统自动发号,重复工号将执行更新)。
|
||||
<br />
|
||||
2. 部门/职位需与系统内名称完全一致。
|
||||
<br />
|
||||
3. 支持 .xlsx / .csv。
|
||||
</div>
|
||||
<Space>
|
||||
<Button onClick={() => window.open('/api/v1/employees/import-template')}>下载模板</Button>
|
||||
<Upload
|
||||
accept=".xlsx,.xls,.csv"
|
||||
showUploadList={false}
|
||||
customRequest={async ({ file, onSuccess, onError }: any) => {
|
||||
try {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
const r = await fetch('/api/v1/employees/import', { method: 'POST', body: fd })
|
||||
const data = await r.json()
|
||||
if (!r.ok) throw new Error(data.message || '导入失败')
|
||||
setResult(data)
|
||||
onSuccess?.(data)
|
||||
} catch (e: any) {
|
||||
message.error(e.message)
|
||||
onError?.(e)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Button type="primary">上传花名册</Button>
|
||||
</Upload>
|
||||
</Space>
|
||||
{result && (
|
||||
<div>
|
||||
<Progress
|
||||
percent={Math.round(((result.created + result.updated) / Math.max(result.total, 1)) * 100)}
|
||||
status={result.failed ? 'exception' : 'success'}
|
||||
/>
|
||||
<p style={{ fontSize: 13 }}>
|
||||
共 {result.total} 行,新增 <b>{result.created}</b>,更新 <b>{result.updated}</b>,失败{' '}
|
||||
<b style={{ color: '#ff4d4f' }}>{result.failed}</b>
|
||||
</p>
|
||||
{(result.errors || []).slice(0, 12).map((e: string, i: number) => (
|
||||
<div key={i} style={{ fontSize: 12, color: '#98a2b3' }}>
|
||||
· {e}
|
||||
</div>
|
||||
))}
|
||||
<Button style={{ marginTop: 12 }} type="primary" onClick={onDone}>
|
||||
完成并刷新
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Space>
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,206 @@
|
|||
import { CopyOutlined, UserAddOutlined } from '@ant-design/icons'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { Alert, App, Button, Form, Input, Modal, Select, Space, Tag, Typography } from 'antd'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { post } from '../../api/http'
|
||||
import { useOptionSource } from '../../hooks/useOptions'
|
||||
|
||||
const { Text } = Typography
|
||||
const DEFAULT_PASSWORD = 'Hrms@123456'
|
||||
|
||||
interface Props {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
presetEmployeeId?: number | null
|
||||
onDone?: () => void
|
||||
}
|
||||
|
||||
interface GeneratedAccount {
|
||||
employee_id: number
|
||||
name: string
|
||||
username: string
|
||||
}
|
||||
|
||||
interface GenerateResult {
|
||||
message: string
|
||||
created: GeneratedAccount[]
|
||||
skipped: { employee_id: number; name: string; reason: string }[]
|
||||
password: string
|
||||
roles: string[]
|
||||
}
|
||||
|
||||
/** 根据员工档案批量生成登录账号:工号为账号名,需选择角色。 */
|
||||
export default function GenerateAccounts({ open, onClose, presetEmployeeId, onDone }: Props) {
|
||||
const { message } = App.useApp()
|
||||
const qc = useQueryClient()
|
||||
const [form] = Form.useForm()
|
||||
const [result, setResult] = useState<GenerateResult | null>(null)
|
||||
const employees = useOptionSource('/employees/options')
|
||||
const roles = useOptionSource('/system/roles/options')
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setResult(null)
|
||||
form.resetFields()
|
||||
form.setFieldsValue({
|
||||
employee_ids: presetEmployeeId ? [presetEmployeeId] : [],
|
||||
password: DEFAULT_PASSWORD,
|
||||
})
|
||||
}, [open, presetEmployeeId, form])
|
||||
|
||||
const generate = useMutation({
|
||||
mutationFn: (values: any) => post<GenerateResult>('/system/users/from-employees', values),
|
||||
onSuccess: (res) => {
|
||||
setResult(res)
|
||||
message.success(res.message)
|
||||
onDone?.()
|
||||
qc.invalidateQueries({ queryKey: ['list', 'employee'] })
|
||||
qc.invalidateQueries({ queryKey: ['options', '/employees/options'] })
|
||||
},
|
||||
})
|
||||
|
||||
// 停用档案与已开通账号都不可选:前者后端会跳过,后者会重复建号
|
||||
const employeeOptions = (employees.data || []).map((o: any) => ({
|
||||
label: `${o.label}${
|
||||
o.extra?.has_account ? '(已开通账号)' : o.extra?.is_active === false ? '(档案已停用)' : ''
|
||||
}`,
|
||||
value: o.value,
|
||||
disabled: !!o.extra?.has_account || o.extra?.is_active === false,
|
||||
}))
|
||||
|
||||
const roleOptions = (roles.data || []).map((o: any) => ({
|
||||
label: `${o.label}${o.extra?.is_active === false ? '(已停用)' : ''}`,
|
||||
value: o.value,
|
||||
disabled: o.extra?.is_active === false,
|
||||
}))
|
||||
|
||||
const copyResult = async () => {
|
||||
if (!result) return
|
||||
const lines = [
|
||||
`初始密码:${result.password}`,
|
||||
`角色:${result.roles.join('、')}`,
|
||||
...result.created.map((a) => `${a.name}\t${a.username}`),
|
||||
]
|
||||
try {
|
||||
await navigator.clipboard.writeText(lines.join('\n'))
|
||||
message.success('账号清单已复制')
|
||||
} catch {
|
||||
message.warning('浏览器不允许写剪贴板,请手动复制')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
title="根据员工档案生成账号"
|
||||
width={680}
|
||||
onCancel={onClose}
|
||||
destroyOnHidden
|
||||
footer={
|
||||
result ? (
|
||||
<Space>
|
||||
<Button icon={<CopyOutlined />} onClick={copyResult}>
|
||||
复制账号清单
|
||||
</Button>
|
||||
<Button type="primary" onClick={onClose}>
|
||||
完成
|
||||
</Button>
|
||||
</Space>
|
||||
) : (
|
||||
<Space>
|
||||
<Button onClick={onClose}>取消</Button>
|
||||
<Button type="primary" icon={<UserAddOutlined />} loading={generate.isPending} onClick={() => form.submit()}>
|
||||
生成账号
|
||||
</Button>
|
||||
</Space>
|
||||
)
|
||||
}
|
||||
>
|
||||
{result ? (
|
||||
<Space direction="vertical" size={12} style={{ width: '100%' }}>
|
||||
<Alert
|
||||
type="success"
|
||||
showIcon
|
||||
message={result.message}
|
||||
description={
|
||||
<span>
|
||||
初始密码 <Text code>{result.password}</Text>,角色 <Text code>{result.roles.join('、')}</Text>。
|
||||
请通知员工首次登录后尽快修改密码。
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
{result.created.length > 0 && (
|
||||
<div style={{ background: '#f6ffed', border: '1px solid #d9f7be', borderRadius: 10, padding: 12 }}>
|
||||
{result.created.map((a) => (
|
||||
<div key={a.employee_id} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, padding: '3px 0' }}>
|
||||
<span>{a.name}</span>
|
||||
<Text code>{a.username}</Text>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{result.skipped.length > 0 && (
|
||||
<div>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>以下档案已跳过:</Text>
|
||||
{result.skipped.map((s) => (
|
||||
<div key={s.employee_id} style={{ fontSize: 12, color: '#98a2b3', marginTop: 4 }}>
|
||||
· {s.name}:{s.reason}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Space>
|
||||
) : (
|
||||
<>
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
style={{ marginBottom: 16 }}
|
||||
message="账号名默认取员工工号(小写),已被占用时自动追加序号;一个档案只能绑定一个账号,停用档案不可生成账号。"
|
||||
/>
|
||||
<Form form={form} layout="vertical" onFinish={(v) => generate.mutate(v)}>
|
||||
<Form.Item
|
||||
name="employee_ids"
|
||||
label="员工档案"
|
||||
rules={[{ required: true, message: '请选择至少一名员工' }]}
|
||||
>
|
||||
<Select
|
||||
mode="multiple"
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
placeholder="搜索姓名 / 工号"
|
||||
loading={employees.isFetching}
|
||||
options={employeeOptions}
|
||||
// 固定条数而不是 responsive:预设单个员工时 responsive 会量出「+ 0」这种伪标签
|
||||
maxTagCount={4}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="role_ids"
|
||||
label="角色(必选,可多选)"
|
||||
rules={[{ required: true, message: '请至少选择一个角色' }]}
|
||||
extra="角色决定账号能看到的菜单、接口权限与数据范围"
|
||||
>
|
||||
<Select
|
||||
mode="multiple"
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
placeholder="选择角色"
|
||||
loading={roles.isFetching}
|
||||
options={roleOptions}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="password"
|
||||
label="初始密码"
|
||||
rules={[{ required: true, message: '请设置初始密码' }, { min: 6, message: '至少 6 位' }]}
|
||||
extra={<Tag color="orange">所有本次生成的账号共用同一个初始密码</Tag>}
|
||||
>
|
||||
<Input.Password placeholder={DEFAULT_PASSWORD} autoComplete="new-password" />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,14 +1,16 @@
|
|||
import { ApartmentOutlined, DeleteOutlined, EditOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons'
|
||||
import { ApartmentOutlined, DeleteOutlined, DownloadOutlined, EditOutlined, ImportOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { App, Button, Card, Col, Form, Input, InputNumber, Row, Select, Space, Statistic, Switch, Table, Tag, TreeSelect, Typography } from 'antd'
|
||||
import { useMemo, useState } from 'react'
|
||||
import FormDrawer from '../../components/FormDrawer'
|
||||
import { del, get, patch, post } from '../../api/http'
|
||||
import ImportDrawer from '../../components/ImportDrawer'
|
||||
import { del, download, get, patch, post } from '../../api/http'
|
||||
import { SearchBar } from '../../components/ListFilters'
|
||||
import { usePanelFilters } from '../../hooks/useListFilters'
|
||||
import { useOptionSource } from '../../hooks/useOptions'
|
||||
import { useAuth } from '../../store/auth'
|
||||
import { useModalFormFill } from '../../hooks/useModalForm'
|
||||
import StatusSwitch from '../../components/StatusSwitch'
|
||||
|
||||
const { Text, Title } = Typography
|
||||
|
||||
|
|
@ -48,6 +50,7 @@ export default function Departments() {
|
|||
const hasPerm = useAuth((s) => s.hasPerm)
|
||||
const [expanded, setExpanded] = useState<readonly React.Key[] | null>(null)
|
||||
const [editing, setEditing] = useState<any>(null)
|
||||
const [importOpen, setImportOpen] = useState(false)
|
||||
const [form] = Form.useForm()
|
||||
|
||||
const q = useQuery({ queryKey: ['dept-tree'], queryFn: () => get<DeptNode[]>('/org/departments/tree') })
|
||||
|
|
@ -147,13 +150,11 @@ export default function Departments() {
|
|||
title: '部门名称',
|
||||
dataIndex: 'name',
|
||||
width: 300,
|
||||
fixed: 'left',
|
||||
render: (v: string, r: DeptNode) => (
|
||||
<Space size={6}>
|
||||
<ApartmentOutlined style={{ color: r.is_parent ? '#8c8c8c' : '#2f54eb' }} />
|
||||
<Text strong={!r.is_parent}>{v}</Text>
|
||||
{r.is_parent && <Tag>虚拟节点</Tag>}
|
||||
{r.is_active === false && <Tag color="default">已停用</Tag>}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
|
|
@ -179,6 +180,22 @@ export default function Departments() {
|
|||
render: (v: number) => <Text type="secondary">{v || 0} 人</Text>,
|
||||
},
|
||||
{ title: '成本中心', dataIndex: 'cost_center', width: 130, render: (v: string) => v || <Text type="secondary">-</Text> },
|
||||
// 启停开关统一放在数据列最后、紧贴操作列,且不做左侧固定
|
||||
{
|
||||
title: '启用',
|
||||
dataIndex: 'is_active',
|
||||
width: 96,
|
||||
fixed: 'right',
|
||||
render: (_v: boolean, r: DeptNode) => (
|
||||
<StatusSwitch
|
||||
path={`/org/departments/${r.id}`}
|
||||
checked={r.is_active !== false}
|
||||
perm="org:department:update"
|
||||
confirmTitle={`停用「${r.name}」?停用后该部门(含下级)不再出现在新的业务选择中,已有人员不受影响。`}
|
||||
invalidate={[['list', 'department'], ['dept-tree'], ['options'], ['boot-options']]}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'ops',
|
||||
|
|
@ -240,6 +257,20 @@ export default function Departments() {
|
|||
}
|
||||
extra={
|
||||
<Space>
|
||||
{hasPerm('org:department:export') && (
|
||||
<Button
|
||||
size="small"
|
||||
icon={<DownloadOutlined />}
|
||||
onClick={() => download('/org/departments/export', undefined, '组织架构_部门.xlsx')}
|
||||
>
|
||||
导出
|
||||
</Button>
|
||||
)}
|
||||
{hasPerm('org:department:import') && (
|
||||
<Button size="small" icon={<ImportOutlined />} onClick={() => setImportOpen(true)}>
|
||||
导入
|
||||
</Button>
|
||||
)}
|
||||
<Button size="small" icon={<ReloadOutlined />} onClick={refresh}>
|
||||
刷新
|
||||
</Button>
|
||||
|
|
@ -343,6 +374,21 @@ export default function Departments() {
|
|||
</Row>
|
||||
</Form>
|
||||
</FormDrawer>
|
||||
|
||||
<ImportDrawer
|
||||
open={importOpen}
|
||||
onClose={() => setImportOpen(false)}
|
||||
onDone={refresh}
|
||||
title="批量导入组织架构"
|
||||
templatePath="/org/departments/import-template"
|
||||
importPath="/org/departments/import"
|
||||
templateName="组织架构_部门导入模板.xlsx"
|
||||
tips={[
|
||||
'按部门编码匹配:已存在的部门会更新,新编码会新建;不填编码时按部门名称匹配。',
|
||||
'上级部门填「上级部门编码」,可先写子部门再写上级,导入后会自动重算层级与路径。',
|
||||
'部门负责人填员工工号;是否启用填「是 / 否」。',
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { DeleteOutlined, PlusOutlined, WalletOutlined } from '@ant-design/icons'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { DeleteOutlined, ImportOutlined, PlusOutlined, WalletOutlined } from '@ant-design/icons'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
App,
|
||||
Button,
|
||||
|
|
@ -16,13 +16,16 @@ import { useState } from 'react'
|
|||
import { put } from '../../api/http'
|
||||
import { jobLevelDef } from '../../api/resources'
|
||||
import FormDrawer from '../../components/FormDrawer'
|
||||
import ImportDrawer from '../../components/ImportDrawer'
|
||||
import ResourceTable from '../../components/ResourceTable'
|
||||
import { useAuth } from '../../store/auth'
|
||||
|
||||
export default function JobLevels() {
|
||||
const { message } = App.useApp()
|
||||
const qc = useQueryClient()
|
||||
const [form] = Form.useForm()
|
||||
const hasPerm = useAuth((s) => s.hasPerm)
|
||||
const [importOpen, setImportOpen] = useState(false)
|
||||
const canEditStandard = hasPerm('org:joblevel:update')
|
||||
const [editing, setEditing] = useState<any | null>(null)
|
||||
const [refreshList, setRefreshList] = useState<() => void>(() => () => undefined)
|
||||
|
|
@ -51,6 +54,13 @@ export default function JobLevels() {
|
|||
def={jobLevelDef}
|
||||
desc="职级体系(管理 M / 专业 P / 操作 O),可为每个职级配置多个报销项目与额度"
|
||||
createText="新增职级"
|
||||
toolbar={
|
||||
hasPerm('org:joblevel:import') ? (
|
||||
<Button icon={<ImportOutlined />} onClick={() => setImportOpen(true)}>
|
||||
批量导入
|
||||
</Button>
|
||||
) : undefined
|
||||
}
|
||||
rowActions={canEditStandard ? (row, helpers) => (
|
||||
<Button
|
||||
type="link"
|
||||
|
|
@ -155,6 +165,20 @@ export default function JobLevels() {
|
|||
</Form.List>
|
||||
</Form>
|
||||
</FormDrawer>
|
||||
|
||||
<ImportDrawer
|
||||
open={importOpen}
|
||||
onClose={() => setImportOpen(false)}
|
||||
onDone={() => qc.invalidateQueries({ queryKey: ['list', 'joblevel'] })}
|
||||
title="批量导入职级"
|
||||
templatePath="/org/job-levels/import-template"
|
||||
importPath="/org/job-levels/import"
|
||||
templateName="组织架构_职级导入模板.xlsx"
|
||||
tips={[
|
||||
'按职级编码匹配:已存在的职级会更新,新编码会新建;不填编码时按职级名称匹配。',
|
||||
'职等填数字(如 5);已有职级的报销标准不会被导入覆盖。',
|
||||
]}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,43 @@
|
|||
import { ImportOutlined } from '@ant-design/icons'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { Button } from 'antd'
|
||||
import { useState } from 'react'
|
||||
import { positionDef } from '../../api/resources'
|
||||
import { useAuth } from '../../store/auth'
|
||||
import ImportDrawer from '../../components/ImportDrawer'
|
||||
import ResourceTable from '../../components/ResourceTable'
|
||||
|
||||
export default function Positions() {
|
||||
return <ResourceTable def={positionDef} desc="职位序列与职务说明,用于员工任职、招聘职位与编制管理" createText="新增职位" />
|
||||
const qc = useQueryClient()
|
||||
const hasPerm = useAuth((s) => s.hasPerm)
|
||||
const [importOpen, setImportOpen] = useState(false)
|
||||
return (
|
||||
<>
|
||||
<ResourceTable
|
||||
def={positionDef}
|
||||
desc="职位序列与职务说明,用于员工任职、招聘职位与编制管理"
|
||||
createText="新增职位"
|
||||
toolbar={
|
||||
hasPerm('org:position:import') ? (
|
||||
<Button icon={<ImportOutlined />} onClick={() => setImportOpen(true)}>
|
||||
批量导入
|
||||
</Button>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
<ImportDrawer
|
||||
open={importOpen}
|
||||
onClose={() => setImportOpen(false)}
|
||||
onDone={() => qc.invalidateQueries({ queryKey: ['list', 'position'] })}
|
||||
title="批量导入职位"
|
||||
templatePath="/org/positions/import-template"
|
||||
importPath="/org/positions/import"
|
||||
templateName="组织架构_职位导入模板.xlsx"
|
||||
tips={[
|
||||
'按职位编码匹配:已存在的职位会更新,新编码会新建;不填编码时按职位名称匹配。',
|
||||
'职务序列可填「技术序列 / 职能序列」等分类;是否启用填「是 / 否」。',
|
||||
]}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -94,8 +94,8 @@ export default function BatchDetail() {
|
|||
new Set((preview?.items || []).flatMap((r: any) => Object.keys(r.items || {}))),
|
||||
)
|
||||
const previewCols = [
|
||||
{ title: '工号', dataIndex: 'work_no', width: 100, fixed: 'left' as const },
|
||||
{ title: '姓名', dataIndex: 'employee_name', width: 96, fixed: 'left' as const },
|
||||
{ title: '工号', dataIndex: 'work_no', width: 100 },
|
||||
{ title: '姓名', dataIndex: 'employee_name', width: 96 },
|
||||
{ title: '部门', dataIndex: 'department_name', width: 130 },
|
||||
{ title: '账套', dataIndex: 'plan_name', width: 120 },
|
||||
...codes.map((c) => ({
|
||||
|
|
@ -341,7 +341,7 @@ export default function BatchDetail() {
|
|||
pagination={{ pageSize: 20, showSizeChanger: false }}
|
||||
scroll={{ y: 520 }}
|
||||
columns={[
|
||||
{ title: '姓名', dataIndex: 'employee_name', width: 96, fixed: 'left' },
|
||||
{ title: '姓名', dataIndex: 'employee_name', width: 96 },
|
||||
{ title: '部门', dataIndex: 'department_name', width: 130, ellipsis: true },
|
||||
{
|
||||
title: '实际出勤',
|
||||
|
|
|
|||
|
|
@ -198,7 +198,7 @@ export default function Reports() {
|
|||
scroll={{ x: 'max-content', y: 460 }}
|
||||
pagination={{ pageSize: 20, showSizeChanger: false }}
|
||||
columns={[
|
||||
{ title: '员工', dataIndex: 'employee_name', width: 130, fixed: 'left', render: (v: string, r: any) => `${v} #${r.employee_id}` },
|
||||
{ title: '员工', dataIndex: 'employee_name', width: 130, render: (v: string, r: any) => `${v} #${r.employee_id}` },
|
||||
{ title: '累计收入', dataIndex: 'cumulative_income', width: 140, align: 'right', render: (v: number) => money(v) },
|
||||
{ title: '累计减除费用', dataIndex: 'cumulative_deduction', width: 140, align: 'right', render: (v: number) => money(v) },
|
||||
{ title: '累计应纳税所得额', dataIndex: 'cumulative_taxable', width: 160, align: 'right', render: (v: number) => money(v) },
|
||||
|
|
|
|||
|
|
@ -0,0 +1,280 @@
|
|||
import {
|
||||
CloudDownloadOutlined,
|
||||
DatabaseOutlined,
|
||||
DeleteOutlined,
|
||||
FileExcelOutlined,
|
||||
SafetyCertificateOutlined,
|
||||
WarningOutlined,
|
||||
} from '@ant-design/icons'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { Alert, App, Button, Card, Col, Input, Row, Space, Statistic, Table, Tag, Typography } from 'antd'
|
||||
import { useState } from 'react'
|
||||
import { download, get, post } from '../../api/http'
|
||||
import { useAuth } from '../../store/auth'
|
||||
|
||||
const { Text, Title } = Typography
|
||||
const PURGE_PHRASE = 'unis_hrms'
|
||||
|
||||
interface TableStat {
|
||||
name: string
|
||||
label: string
|
||||
rows: number
|
||||
kept: boolean
|
||||
}
|
||||
|
||||
interface Overview {
|
||||
database: string
|
||||
database_size: number
|
||||
upload_size: number
|
||||
upload_files: number
|
||||
tables: TableStat[]
|
||||
table_count: number
|
||||
total_rows: number
|
||||
}
|
||||
|
||||
function bytes(value: number) {
|
||||
if (!value) return '0 B'
|
||||
if (value >= 1024 ** 3) return `${(value / 1024 ** 3).toFixed(2)} GB`
|
||||
if (value >= 1024 ** 2) return `${(value / 1024 ** 2).toFixed(1)} MB`
|
||||
if (value >= 1024) return `${(value / 1024).toFixed(1)} KB`
|
||||
return `${value} B`
|
||||
}
|
||||
|
||||
/** 系统管理 · 数据维护:全量备份、全量导出、清空业务数据。 */
|
||||
export default function Maintenance() {
|
||||
const { message, modal } = App.useApp()
|
||||
const qc = useQueryClient()
|
||||
const hasPerm = useAuth((s) => s.hasPerm)
|
||||
const [busy, setBusy] = useState<'backup' | 'export' | 'purge' | null>(null)
|
||||
const [confirmText, setConfirmText] = useState('')
|
||||
|
||||
const overview = useQuery<Overview>({
|
||||
queryKey: ['maintenance-overview'],
|
||||
queryFn: () => get('/system/maintenance/overview'),
|
||||
})
|
||||
const data = overview.data
|
||||
|
||||
const runDownload = async (kind: 'backup' | 'export') => {
|
||||
setBusy(kind)
|
||||
try {
|
||||
if (kind === 'backup') {
|
||||
await download('/system/maintenance/backup', undefined, 'UNIS-HRMS-备份.zip')
|
||||
message.success('完整备份已开始下载')
|
||||
} else {
|
||||
await download('/system/maintenance/export', undefined, 'UNIS-HRMS-数据导出.xlsx')
|
||||
message.success('全量数据已开始下载')
|
||||
}
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '导出失败')
|
||||
} finally {
|
||||
setBusy(null)
|
||||
}
|
||||
}
|
||||
|
||||
const purge = () => {
|
||||
modal.confirm({
|
||||
title: '确认清空全部业务数据?',
|
||||
width: 520,
|
||||
icon: <WarningOutlined style={{ color: '#ff4d4f' }} />,
|
||||
content: (
|
||||
<div style={{ fontSize: 13, lineHeight: 1.8 }}>
|
||||
员工、合同、薪资、招聘、福利、组织架构、公告、日志、附件将全部删除,
|
||||
其他账号也会被删除。仅保留系统管理员账号、角色权限、菜单与数据字典。
|
||||
<br />
|
||||
<Text strong type="danger">此操作不可撤销,请先下载完整备份。</Text>
|
||||
</div>
|
||||
),
|
||||
okText: '确认清空',
|
||||
okButtonProps: { danger: true },
|
||||
onOk: async () => {
|
||||
setBusy('purge')
|
||||
try {
|
||||
const res = await post<any>('/system/maintenance/purge', { confirm: PURGE_PHRASE })
|
||||
message.success(res?.message || '已清空全部数据')
|
||||
setConfirmText('')
|
||||
await qc.invalidateQueries()
|
||||
} finally {
|
||||
setBusy(null)
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const tableColumns = [
|
||||
{ title: '数据表', dataIndex: 'name', width: 240 },
|
||||
{ title: '名称', dataIndex: 'label' },
|
||||
{
|
||||
title: '记录数',
|
||||
dataIndex: 'rows',
|
||||
width: 110,
|
||||
align: 'right' as const,
|
||||
render: (v: number) => v.toLocaleString(),
|
||||
},
|
||||
{
|
||||
title: '清理时',
|
||||
dataIndex: 'kept',
|
||||
width: 100,
|
||||
render: (kept: boolean) => (kept ? <Tag color="blue">保留</Tag> : <Tag>清空</Tag>),
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Space direction="vertical" size={16} style={{ width: '100%' }}>
|
||||
<Card variant="borderless">
|
||||
<Space direction="vertical" size={2}>
|
||||
<Title level={5} style={{ margin: 0 }}>
|
||||
数据维护
|
||||
</Title>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
下载完整备份、导出全量数据,或在交付/重置环境时清空业务数据。
|
||||
</Text>
|
||||
</Space>
|
||||
</Card>
|
||||
|
||||
<Row gutter={[12, 12]}>
|
||||
<Col xs={12} md={6}>
|
||||
<Card variant="borderless">
|
||||
<Statistic title="数据库" value={data?.database === 'mysql' ? 'MySQL' : 'SQLite'} prefix={<DatabaseOutlined />} />
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={12} md={6}>
|
||||
<Card variant="borderless">
|
||||
<Statistic title="数据库大小" value={bytes(data?.database_size || 0)} valueStyle={{ fontSize: 22 }} />
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={12} md={6}>
|
||||
<Card variant="borderless">
|
||||
<Statistic
|
||||
title="附件占用"
|
||||
value={bytes(data?.upload_size || 0)}
|
||||
suffix={data ? `/ ${data.upload_files} 个文件` : undefined}
|
||||
valueStyle={{ fontSize: 22 }}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={12} md={6}>
|
||||
<Card variant="borderless">
|
||||
<Statistic
|
||||
title="数据表 / 记录"
|
||||
value={data?.table_count || 0}
|
||||
suffix={data ? `张 / ${data.total_rows.toLocaleString()} 行` : undefined}
|
||||
valueStyle={{ fontSize: 22 }}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
<Row gutter={[12, 12]}>
|
||||
<Col xs={24} lg={12}>
|
||||
<Card
|
||||
variant="borderless"
|
||||
title={
|
||||
<Space>
|
||||
<CloudDownloadOutlined style={{ color: '#2f54eb' }} />
|
||||
一键备份
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
<Text type="secondary" style={{ fontSize: 13 }}>
|
||||
打包下载完整数据快照(JSON 全表数据 + SQLite 原始库文件 + 全部上传附件),
|
||||
可用于迁移或灾难恢复。建议在清空数据、升级版本前先备份。
|
||||
</Text>
|
||||
<div style={{ marginTop: 16 }}>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<CloudDownloadOutlined />}
|
||||
loading={busy === 'backup'}
|
||||
disabled={!hasPerm('system:maintenance:backup')}
|
||||
onClick={() => runDownload('backup')}
|
||||
>
|
||||
下载完整备份 (.zip)
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={24} lg={12}>
|
||||
<Card
|
||||
variant="borderless"
|
||||
title={
|
||||
<Space>
|
||||
<FileExcelOutlined style={{ color: '#389e0d' }} />
|
||||
导出数据
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
<Text type="secondary" style={{ fontSize: 13 }}>
|
||||
把每张数据表导出为一个 Excel 工作表,首表附「表名 / 中文名 / 记录数 / 是否保留」清单,
|
||||
便于交付、对账或用其它工具做数据分析。
|
||||
</Text>
|
||||
<div style={{ marginTop: 16 }}>
|
||||
<Button
|
||||
icon={<FileExcelOutlined />}
|
||||
loading={busy === 'export'}
|
||||
disabled={!hasPerm('system:maintenance:export')}
|
||||
onClick={() => runDownload('export')}
|
||||
>
|
||||
导出全部数据 (.xlsx)
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
<Card
|
||||
variant="borderless"
|
||||
title={
|
||||
<Space>
|
||||
<SafetyCertificateOutlined style={{ color: '#ff4d4f' }} />
|
||||
清理所有数据
|
||||
</Space>
|
||||
}
|
||||
style={{ border: '1px solid #ffccc7', background: '#fff8f7' }}
|
||||
>
|
||||
<Alert
|
||||
type="warning"
|
||||
showIcon
|
||||
message="仅保留系统管理员"
|
||||
description="员工档案及全部业务数据、其它用户账号、附件与日志都会被清空;系统管理员账号、角色权限、菜单和数据字典会保留,管理员可直接重新开始配置。"
|
||||
style={{ marginBottom: 16 }}
|
||||
/>
|
||||
<Space direction="vertical" size={8} style={{ width: '100%' }}>
|
||||
<Text style={{ fontSize: 13 }}>
|
||||
请输入 <Text code>{PURGE_PHRASE}</Text>(英文小写,区分大小写)以启用按钮:
|
||||
</Text>
|
||||
<Input
|
||||
value={confirmText}
|
||||
onChange={(e) => setConfirmText(e.target.value)}
|
||||
placeholder={PURGE_PHRASE}
|
||||
style={{ maxWidth: 320 }}
|
||||
allowClear
|
||||
/>
|
||||
</Space>
|
||||
<div style={{ marginTop: 16 }}>
|
||||
<Button
|
||||
danger
|
||||
type="primary"
|
||||
icon={<DeleteOutlined />}
|
||||
loading={busy === 'purge'}
|
||||
disabled={confirmText.trim() !== PURGE_PHRASE || !hasPerm('system:maintenance:purge')}
|
||||
onClick={purge}
|
||||
>
|
||||
清空全部数据
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card variant="borderless" title="数据表明细" styles={{ body: { paddingTop: 8 } }}>
|
||||
<Table<TableStat>
|
||||
rowKey="name"
|
||||
size="small"
|
||||
loading={overview.isFetching}
|
||||
dataSource={data?.tables || []}
|
||||
columns={tableColumns}
|
||||
pagination={{ pageSize: 12, hideOnSinglePage: true }}
|
||||
/>
|
||||
</Card>
|
||||
</Space>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@ import { get, put } from '../../api/http'
|
|||
import EmptyBlock from '../../components/EmptyBlock'
|
||||
import { roleDef } from '../../api/resources'
|
||||
import { useResource } from '../../components/ResourceTable'
|
||||
import StatusSwitch from '../../components/StatusSwitch'
|
||||
import { useAuth } from '../../store/auth'
|
||||
|
||||
const { Text, Title } = Typography
|
||||
|
|
@ -169,9 +170,21 @@ export default function Roles() {
|
|||
<Text strong={on}>{r.name}</Text>
|
||||
{r.is_builtin && <LockOutlined style={{ color: '#98a2b3', fontSize: 12 }} />}
|
||||
</Space>
|
||||
<Tag color={sc?.color || 'default'} style={{ margin: 0 }}>
|
||||
{sc?.label || r.data_scope}
|
||||
</Tag>
|
||||
<Space size={8} onClick={(e) => e.stopPropagation()}>
|
||||
<Tag color={sc?.color || 'default'} style={{ margin: 0 }}>
|
||||
{sc?.label || r.data_scope}
|
||||
</Tag>
|
||||
<StatusSwitch
|
||||
path={`/system/roles/${r.id}`}
|
||||
checked={r.is_active !== false}
|
||||
perm="system:role:update"
|
||||
disabled={!!r.is_builtin}
|
||||
disabledReason="内置角色不允许停用"
|
||||
confirmTitle={`停用角色「${r.name}」?该角色下的用户将立即失去对应权限。`}
|
||||
invalidate={[['list', 'role'], ['options']]}
|
||||
onDone={() => roles.refetch()}
|
||||
/>
|
||||
</Space>
|
||||
</div>
|
||||
<div style={{ marginTop: 4 }}>
|
||||
<Text type="secondary" style={{ fontSize: 11 }}>
|
||||
|
|
|
|||
Loading…
Reference in New Issue