v0.1.0-sp1

main
mula.liu 2026-10-21 10:28:25 +08:00
parent 185f467105
commit 19615b0240
65 changed files with 6450 additions and 523 deletions

100
README.md
View File

@ -1,6 +1,6 @@
# UNIS HRMS 2.0
新一代人力资源管理系统:**人事档案 · 招聘 · 薪资 · 福利保险 · 员工自助(H5)**
新一代人力资源管理系统:**人事档案 · 招聘 · 薪资 · 福利保险 · 员工自助(Web / H5)**
配套完整 RBAC(权限码 + 数据范围 + 动态菜单),面向现代浏览器的简洁高交互界面。
```
@ -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(**130 项**,52 个测试函数参数化展开)· ruff · `tsc --noEmit` 严格模式 |
| 质量 | pytest + pytest-asyncio(**150 项**,含职级报销标准、资料审核与 **Web⇄H5 一致性守卫** `tests/test_self_parity.py`)· ruff · `tsc --noEmit` 严格模式 |
---
@ -70,9 +70,10 @@ npm run dev # http://localhost:5173
| `payroll` | `pay123456` | 薪酬福利专员 | 全部 | 算薪、报盘、参保 |
| `recruiter` | `rec123456` | 招聘经理 | 全部 | 职位、看板、Offer |
| `manager` | `mgr123456` | 部门经理 | 部门及以下 | 部门内审批(王志强 / EMP00003) |
| `emp` | `emp123456` | 普通员工 | 仅本人 | 只看 H5 自助(王建国 / EMP00001) |
| `emp` | `emp123456` | 普通员工 | 仅本人 | 桌面浏览器进 Web 自助 5 项导航,手机进 H5(王建国 / EMP00001) |
登录页内置这些账号(点击自动填充),勾选 **「以 H5 自助端进入」** 直接跳转 `/m`。
登录页内置这些账号(点击自动填充);登录后按浏览器自动进入 Web 工作台或 H5,
桌面普通员工进入 `/dashboard`,手机浏览器进入 `/m`,无需手动切换。
### 生产部署(Docker Compose)
@ -137,7 +138,9 @@ unis_hrms/
│ ├── components/ # ResourceTable(核心) FormDrawer(新增/编辑统一右侧抽屉) FieldInput Cell
│ │ # icons(图标白名单) PageFallback EmptyBlock ListFilters
│ ├── layouts/ # AdminLayout(动态菜单 + 固定侧栏/顶栏 + 用户胶囊) MobileLayout(H5 底栏)
│ ├── pages/ # 33 个管理端路由页面 + pages/mobile 6 个 H5 页面
│ ├── pages/ # 33 个管理端路由页面 + pages/self 6 个自助页 + pages/mobile 7 个 H5 页
│ ├── self/manifest.ts # 员工自助 7 模块唯一清单(两端名称/权限/顺序/图标/双端路径)
│ ├── lib/mode.ts # 外壳模式判定(Web / H5)唯一口径 + 偏好持久化
│ │ └── account/Settings.tsx # 个人设置(独立页面 /account,侧栏用户胶囊进入)
│ └── store/ # zustand:auth(token/me/menus/can)
├── Dockerfile # 两段式构建:node 产出 web/dist → python 运行整站
@ -168,22 +171,72 @@ Offer 审批与一键入职(生成员工 + 账号 + 合同)。漏斗/渠道/
五险一金方案(基数上下限、比例)· 参保登记与增减员 · 福利项目与发放记录 ·
假期类型 / 额度矩阵 / 请假审批(含额度校验与扣减)/ 假期分析。
### 3.5 员工自助(H5)`/m`
移动优先,390×844 起设计,antd-mobile 组件 + 自绘卡片体系,与桌面端共用一套 JWT 与 API。
### 3.5 员工自助(Web / H5)
| 路由 | 内容 |
| --- | --- |
| `/m` | 首页:最新工资条、假期额度、九宫格入口、合同到期提醒、**待我审批**、公告、待办 |
| `/m/leave` | 请假申请(类型/日期/事由 → 额度预估)与我的申请状态跟踪 |
| `/m/payslips` | 历史工资条,按月展开收入/扣除/个税明细 |
| `/m/benefits` | 我的参保信息、福利发放、假期余额 |
| `/m/approvals` | **审批中心**:待我审批/已通过/已驳回 + 类型筛选 + 意见填写(变更前后对照中文化) |
| `/m/profile` | 我的档案、可编辑字段自助变更(走审批)、证明申请、消息通知 |
#### 3.5.1 用哪个外壳:设备决定,账号不决定
判定口径只有一处 —— `web/src/lib/mode.ts`,按优先级:
| 优先级 | 条件 | 结果 |
| --- | --- | --- |
| 1 | 用户在**站内**显式切换过外壳(`localStorage: unis-hrms-shell-mode`) | 按所选:Web 工作台 / H5 自助端 |
| 2 | 从未切换过(默认) | 手机浏览器(UA + 触屏 + 视口,`lib/device.ts`)→ H5;其余(PC、平板桌面)→ **Web** |
配套规则(这是"员工一登录就被拽进 H5"的三个历史成因,现已封死):
- **账号与角色不参与判定**。普通员工在电脑浏览器登录必进 `/dashboard`,
管理员用手机登录同样落到 `/m`。
- 登录成功、根路径 `/`、token 过期重登三处统一走 `entryPath()` / `sanitizeRedirect(?redirect=)`,
后者会把历史遗留的 `/m/xxx` 改写成本外壳下的等价路径,不再原样把用户送回 H5。
- **两端都有显式切换入口**并记住偏好:Web 侧栏顶部的 📱 按钮、自助首页的「用 H5 版打开」、
H5 首页与「我的」页的「💻 进入 Web 工作台」。**登录页不再提供版本选择**,默认就是跟随设备。
切换时落在同一模块(`oppositePath()`),从 Web 的工资条切过去就是 H5 工资条,不会掉回首页。
#### 3.5.2 两端怎么保持一致
唯一事实来源是 `web/src/self/manifest.ts` 的 7 个模块;后端 `MOBILE_MENU_TREE` /
`SELF_WEB_MENU_TREE`(`app/core/permissions.py`)与前端导航、通知 link(`SELF_LINKS`)
三方对齐,由 **`tests/test_self_parity.py`(15 项静态守卫)** 锁死:路径/权限/名称/顺序、以及「状态中文是否又各写了一套」漂移即红。
| 模块 | 权限码 | Web 路由 | H5 路由 | 侧栏 / 底栏 | 内容 |
| --- | --- | --- | --- | --- | --- |
| 首页 | `selfservice:home:read` | `/dashboard` | `/m` | ✅ / ✅ | 最新工资条、假期额度、宫格入口、合同提醒、待我审批、公告、待办 |
| 请假 | `selfservice:leave:read` | `/self/leave` | `/m/leave` | ✅ / ✅ | 类型/日期/时段 → 额度预估 → 提交,我的申请状态跟踪与撤销 |
| 工资 | `selfservice:payslip:read` | `/self/payslips` | `/m/payslips` | ✅ / ✅ | 年度/季度筛选、收入扣减个税明细、月度累计 |
| 福利 | `selfservice:benefit:read` | `/self/benefits` | `/m/benefits` | ✅ / ✅ | 五险一金参保、福利发放、假期额度矩阵 |
| 审批 | `selfservice:approval:read` | `/self/approvals` | `/m/approvals` | ✗ / ✗(两端均从首页宫格进入) | 待我审批 / 我的申请 + 类型筛选 + 意见填写,变更前后对照中文化 |
| 待办 | `selfservice:task:read` | `/self/tasks` | `/m/tasks` | ✗ / ✗(两端均从首页宫格进入) | HR 待办、消息通知、公告,标记已读/完成 |
| 我的 | `selfservice:profile:read` | `/self/profile` | `/m/profile` | ✅ / ✅ | 档案与教育/家庭、资料变更申请(走审批)、合同与薪资标准、证明开具、消息 |
一致性的实现层次:
| 层次 | 位置 | 作用 |
| --- | --- | --- |
| 模块清单 | `web/src/self/manifest.ts` | 名称、说明、权限、顺序、emoji/配色/图标、双端路径、导航 placement |
| 外壳判定 | `web/src/lib/mode.ts` | 偏好持久化、`entryPath`、`sanitizeRedirect`、`toWebPath/toMobilePath` 互转 |
| 数据层 | `web/src/api/self.ts` | 13 个 `/self/*` 端点 + queryKey + 读写 hooks 两端共用;任一端提交后两端缓存一起失效 |
| 文案层 | `web/src/lib/selfLabels.ts` | 状态/类型/枚举的中文与配色(请假、工资条、审批、福利、证明、合同…)两端同源;在职/合同/参保状态直接派生自 `api/defs` 的选项表,金额与比例统一走 `rmb()` / `pct()`,避免 `7.000000000000001%` 这类浮点尾数 |
| 后端导航 | `app/core/permissions.py` 两份菜单树 | 按权限下发,`/auth/menus?platform=web\|mobile` |
| 后端跳转 | `app/core/permissions.py: SELF_LINKS` | 通知与待办 link 一律用规范 H5 路径入库,前端渲染前过 `toWebPath()` |
因此两端读的是同一批接口、同一份缓存、同一套中文文案,只是外壳不同:
Web 用 antd 表格 / 抽屉 / 表头筛选,H5 用卡片 / 胶囊 tab / `MChips`。
历史上的 `WebSelfFrame`(把 H5 页面套进手机框显示在 Web 里)已删除 —— 那正是两端功能不一致的根源。
员工修改手机号、邮箱、住址等个人档案字段时统一生成待审申请,审核通过前不会写回档案;
旧版 `PATCH /self/profile` 也仅作为兼容入口生成审批单,不能绕过审核。
移动端为 390×844 起设计,antd-mobile 组件 + 自绘卡片体系,与桌面端共用一套 JWT 与 API。
### 3.6 组织与系统 `/org` `/system`
部门树(编制/在职对比)· 职位体系 · 职级职等(M/P/O 与薪档)· 字典 · 用户与角色授权 · 公告 · 操作日志。
每个职级可在行尾打开“报销标准”抽屉,维护多个报销项目(名称、金额、计量单位、说明),
员工在自助端“合同与薪资”中查看当前职级标准。
### 3.7 员工全生命周期主线(入职 → 登记 → 发薪 → 调岗 → 离职)
### 3.7 帮助中心 `/help`
顶部帮助按钮、用户菜单“使用手册”和 H5 我的页面均可打开带真实截图的 HTML 全功能手册;
静态文件位于 `web/public/help/index.html`,可直接访问 `/help/index.html` 或打印为 PDF。
### 3.8 员工全生命周期主线(入职 → 登记 → 发薪 → 调岗 → 离职)
这条主线把五个模块串成一条链,前后端共用同一套接口,`tests/test_lifecycle_e2e.py` 一条用例跑完全程。
转正 / 调岗 / 离职三个动作都有 **`direct` 开关**:`direct=true` 立即生效并留痕;默认 `false` 走审批,
@ -236,10 +289,10 @@ Offer 审批与一键入职(生成员工 + 账号 + 合同)。漏斗/渠道/
| 招聘经理 `recruiter` | dept_tree | 只读 | 读写+审批 | — | 只读 | 读写+审批 | 只读 | — | 12 页 / 5 个一级菜单 |
| 薪酬福利专员 `payroll` | all | 读写+审批 | — | 读写+算薪 | 读写+发放 | 读写+审批 | 只读 | — | 16 页 / 5 个一级菜单 |
| 部门经理 `manager` | dept_tree | 只读 | 只读 | 只读 | 只读 | 读写+审批 | 只读 | — | 12 页 / 6 个一级菜单 |
| 普通员工 `emp00001` | self | — | — | — | — | 读写 | — | — | 仅工作台(主用 H5) |
| 普通员工 `emp00001` | self | — | — | — | — | 读写 | — | — | 自助 5 项(首页/请假/工资/福利/我的) |
- 所有角色的 H5 底栏一致(首页 / 请假 / 工资 / 福利 / 我的),**能看什么由接口权限决定**:
例如部门经理在 `/m/approvals` 看到待办与审批按钮,普通员工只看到自己的申请进度。
- 所有角色的 **Web 侧栏与 H5 底栏完全同名同序**(首页 / 请假 / 工资 / 福利 / 我的),
且**能看什么由接口权限决定**:例如部门经理在审批页看到待办与审批按钮,普通员工只看到自己的申请进度。
- 表里的「只读」= 有 `read` 无 `create/update`,前端自动隐藏新增/编辑/删除按钮,接口同样 403。
### 4.2 自定义端点的数据范围红线
@ -318,7 +371,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 # 130 passed
./.venv/bin/python -m pytest -q # 135 passed
cd web && npx tsc --noEmit # 严格模式无输出
cd web && npm run build # tsc --noEmit && vite build
```
@ -329,6 +382,7 @@ 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_derived_fields.py`:`after_read` 派生字段回归(用户角色 / 角色计数 / 招聘负责人 / 司龄),
防止「保存即清空角色」这类静默失效再次发生
- 测试使用独立库 `data/test_hrms-<pid>.db`(库名带 PID,跑完自动清理),既不污染开发数据,
@ -460,6 +514,10 @@ cd web && npm run build # tsc --noEmit && vite build
| 切换 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` 里还没有新码 |
| 启动脚本报 `unbound variable`(变量名带乱码) | macOS 自带 bash 3.2 在 UTF-8 下会把紧跟变量的全角字符吞进变量名;脚本内已统一写成 `${VAR})`,新增中文提示时记得给变量加花括号 |\n| 新增页面后 403 页没提示权限码 | 去 `web/src/api/routePerms.ts` 补一行 URL→权限码(仅影响提示文案,不影响放行判断) |
| 启动脚本报 `unbound variable`(变量名带乱码) | macOS 自带 bash 3.2 在 UTF-8 下会把紧跟变量的全角字符吞进变量名;脚本内已统一写成 `${VAR})`,新增中文提示时记得给变量加花括号 |
| 普通员工登录总进 H5 | 外壳由**设备 + 站内显式偏好**决定,与账号无关:桌面浏览器应落 `/dashboard`;若曾被 H5 记住偏好,用侧栏 📱 按钮或 H5 的「💻 想用大屏版」卡切回(见 §3.5.1);也可在浏览器控制台执行 `localStorage.removeItem('unis-hrms-shell-mode')` 恢复跟随设备 |
| Web 自助与 H5 模块对不上 | 三处事实来源必须同步:`web/src/self/manifest.ts`、`permissions.py` 两份菜单树、`SELF_LINKS`;跑 `pytest tests/test_self_parity.py` 定位漂移项 |
| 新增一个自助模块 | 只在 `manifest.ts` 加一条(含双端路径与 placement)+ 两份菜单树各一行 + `App.tsx` 两条路由,两端自动同名同序同权限 |
| 新增页面后 403 页没提示权限码 | 去 `web/src/api/routePerms.ts` 补一行 URL→权限码(仅影响提示文案,不影响放行判断) |
> `vhr2.0-main/` 是需求参考系统,非本项目代码,不参与构建。

View File

@ -150,6 +150,23 @@ async def me(session: Session, auth: AuthCtx):
@router.get("/menus", response_model=list[MenuNode], summary="当前用户可见菜单")
async def my_menus(session: Session, auth: AuthCtx, platform: str = Query("web")):
if platform == "web" and auth.data_scope == "self":
from ...core.permissions import SELF_WEB_MENU_TREE
return [
MenuNode(
id=-(index + 1),
name=node["name"],
path=node["path"],
icon=node["icon"],
perm_code=node["perm"],
sort=node["sort"],
platform="web",
children=[],
)
for index, node in enumerate(SELF_WEB_MENU_TREE)
if auth.can(node["perm"])
]
rows = (
await session.execute(select(Menu).where(Menu.platform == platform).order_by(Menu.sort, Menu.id))
).scalars().all()

View File

@ -18,6 +18,7 @@ from ...core.deps import (
require_perm,
)
from ...core.errors import AppError
from ...core.permissions import SELF_LINKS
from ...db.base import utcnow
from ...models.benefits import (
BenefitItem,
@ -283,7 +284,7 @@ async def grant_benefits(payload: GrantPayload, session: Session,
batch_label=label, source="batch", remark=payload.remark))
created += 1
session.add(Notification(title=f"{item.name} 已发放", content=f"共 {created} 人,明细请在「我的福利」查看。",
category="benefit", link="/m/benefit"))
category="benefit", link=SELF_LINKS["benefits"]))
await _log(session, "ben_benefit_item", item.id, "grant", auth, f"{created} 人 / 跳过 {skipped}")
await session.commit()
return {"message": f"已发放 {created} 人", "created": created, "skipped": skipped,
@ -521,7 +522,7 @@ async def approve_leave(item_id: int, payload: LeaveApprovePayload, session: Ses
session.add(Notification(employee_id=request.employee_id,
title=f"请假申请已{'通过' if payload.status == 'approved' else '驳回'}",
content=payload.comment or f"{request.days} 天假期", category="leave",
link="/m/leave"))
link=SELF_LINKS["leave"]))
await session.commit()
return {"message": "审批完成", "status": payload.status}

View File

@ -2,10 +2,12 @@
from __future__ import annotations
from fastapi import APIRouter, Query
from typing import Annotated
from fastapi import APIRouter, Depends, Query
from sqlalchemy import func, select
from ...core.deps import AuthCtx, Session
from ...core.deps import AuthContext, AuthCtx, Session, require_perm
from ...core.errors import AppError
from ..crud import CrudSpec, build_router
from ...models.employee import Employee
@ -14,6 +16,7 @@ from ...schemas.org import (
DepartmentCreate, DepartmentRead, DepartmentUpdate,
DictItemCreate, DictItemRead, DictItemUpdate,
DictTypeCreate, DictTypeRead, DictTypeUpdate,
ExpenseStandardItem, ExpenseStandardsPayload,
JobLevelCreate, JobLevelRead, JobLevelUpdate,
PositionCreate, PositionRead, PositionUpdate,
)
@ -141,11 +144,58 @@ router.include_router(build_router(CrudSpec(
search_fields=("name", "code"), filters=("is_active", "category"),
order_by="sort", order="asc",
)))
router.include_router(build_router(CrudSpec(
model=JobLevel, create=JobLevelCreate, update=JobLevelUpdate, read=JobLevelRead,
module="org", resource="joblevel", label="职级", prefix="/job-levels", tag="组织架构",
search_fields=("name", "code"), filters=("is_active",), order_by="grade", order="asc",
)))
job_levels_custom = APIRouter()
@job_levels_custom.get(
"/{item_id:int}/expense-standards",
response_model=list[ExpenseStandardItem],
summary="读取职级报销标准",
)
async def get_expense_standards(
item_id: int,
session: Session,
auth: Annotated[AuthContext, Depends(require_perm("org:joblevel:read"))],
):
level = await session.get(JobLevel, item_id)
if not level:
raise AppError("职级不存在", "not_found", 404)
return [ExpenseStandardItem.model_validate(item) for item in (level.expense_standards or [])]
@job_levels_custom.put(
"/{item_id:int}/expense-standards",
summary="保存职级报销标准",
)
async def save_expense_standards(
item_id: int,
payload: ExpenseStandardsPayload,
session: Session,
auth: Annotated[AuthContext, Depends(require_perm("org:joblevel:update"))],
):
level = await session.get(JobLevel, item_id)
if not level:
raise AppError("职级不存在", "not_found", 404)
level.expense_standards = [item.model_dump() for item in payload.items]
await session.commit()
await session.refresh(level)
return {
"message": f"已保存 {len(payload.items)} 个报销项目",
"items": level.expense_standards or [],
"count": level.expense_standard_count,
}
router.include_router(build_router(
CrudSpec(
model=JobLevel, create=JobLevelCreate, update=JobLevelUpdate, read=JobLevelRead,
module="org", resource="joblevel", label="职级", prefix="/job-levels", tag="组织架构",
search_fields=("name", "code"), filters=("is_active",), order_by="grade", order="asc",
),
preface=[job_levels_custom],
))
dict_router = APIRouter()

View File

@ -18,6 +18,7 @@ from ...core.deps import (
require_perm,
)
from ...core.errors import AppError
from ...core.permissions import SELF_LINKS
from ...db.base import utcnow
from ...models.employee import Employee
from ...models.org import Department, JobLevel
@ -337,7 +338,7 @@ async def pay_batch(item_id: int, session: Session,
slip.confirmed_at = utcnow()
session.add(Notification(title=f"{month_label(batch.year, batch.month)} 工资已发放",
content=f"实发合计 ¥{batch.net_total},点击查看工资条。",
category="payslip", link="/m/payslip"))
category="payslip", link=SELF_LINKS["payslips"]))
await _log(session, "sal_payroll_batch", batch.id, "pay", auth, batch.bank_batch_no)
await session.commit()
return {"message": "已标记发放并推送工资条", "bank_batch_no": batch.bank_batch_no,
@ -358,7 +359,7 @@ async def publish_batch(item_id: int, session: Session,
for slip in slips:
slip.status = "published"
session.add(Notification(title=f"{month_label(batch.year, batch.month)} 工资条已发布",
content="请前往「我的工资条」查看明细。", category="payslip", link="/m/payslip"))
content="请前往「我的工资条」查看明细。", category="payslip", link=SELF_LINKS["payslips"]))
await _log(session, "sal_payroll_batch", batch.id, "publish", auth, f"{len(slips)} 人")
await session.commit()
return {"message": f"已发布 {len(slips)} 份工资条", "published": len(slips), "pending": pending}
@ -438,7 +439,7 @@ async def publish_slip(item_id: int, session: Session,
ensure(slip is not None, "工资条不存在")
slip.status = "published"
session.add(Notification(employee_id=slip.employee_id, title=f"{month_label(slip.year, slip.month)} 工资条",
content=f"实发 ¥{slip.net}", category="payslip", link="/m/payslip"))
content=f"实发 ¥{slip.net}", category="payslip", link=SELF_LINKS["payslips"]))
await session.commit()
return {"message": "已发布"}

View File

@ -24,6 +24,7 @@ from ...core.deps import (
scope_employee_ids,
)
from ...core.errors import AppError
from ...core.permissions import SELF_LINKS
from ...db.base import utcnow
from ...models.benefits import (
BenefitItem,
@ -136,7 +137,12 @@ def _labeled(d: dict | None) -> dict:
out: dict[str, Any] = {}
for k, v in (d or {}).items():
label = FIELD_LABELS.get(k, k)
out[label] = FIELD_VALUE_LABELS.get(v, v) if isinstance(v, str) else v
if isinstance(v, dict) and "after" in v:
before = FIELD_VALUE_LABELS.get(v.get("before"), v.get("before"))
after = FIELD_VALUE_LABELS.get(v.get("after"), v.get("after"))
out[label] = f"{before if before not in (None, '') else '未填写'} → {after if after not in (None, '') else '未填写'}"
else:
out[label] = FIELD_VALUE_LABELS.get(v, v) if isinstance(v, str) else v
return out
@ -265,37 +271,73 @@ def _dict(obj, fields) -> dict[str, Any]:
return {f: getattr(obj, f, None) for f in fields}
@router.patch("/profile", summary="更新可自助维护的字段")
@router.patch("/profile", summary="提交个人资料修改申请(兼容入口)")
async def update_profile(payload: dict, session: Session,
auth: Annotated[AuthContext, Depends(require_perm("selfservice:profile:update"))]):
emp = await me(session, auth)
changed = {k: v for k, v in (payload or {}).items() if k in SELF_EDITABLE}
if not changed:
raise AppError(f"仅允许修改:{'、'.join(SELF_EDITABLE)}", "invalid_fields")
for key, value in changed.items():
setattr(emp, key, value)
await session.commit()
return {"message": "资料已更新", "updated": list(changed)}
# 旧版 H5 曾调用该入口直接写档案。保留路径是为了避免旧客户端 404,
# 但从这个版本起统一走审批,任何自助账号都不能绕过审核直接修改档案。
return await create_profile_request(payload, session, auth)
@router.post("/profile-requests", summary="提交信息变更申请")
async def create_profile_request(payload: dict, session: Session,
auth: Annotated[AuthContext, Depends(require_perm("selfservice:profile:update"))]):
emp = await me(session, auth)
changes = payload.get("changes") or payload
if not isinstance(changes, dict) or not changes:
incoming = payload.get("changes") or payload
if not isinstance(incoming, dict) or not incoming:
raise AppError("请填写需要变更的内容", "empty_changes")
blocked = {"work_no", "name", "id_card", "department_id", "position_id", "job_level_id",
"status", "hire_date"} & set(changes)
"status", "hire_date"} & set(incoming)
if blocked:
raise AppError(f"以下字段需由 HR 办理:{'、'.join(sorted(blocked))}", "restricted_fields", 403)
request = ProfileRequest(employee_id=emp.id, changes=changes, reason=payload.get("reason"),
status="pending", applicant_user_id=auth.user.id)
allowed = set(SELF_EDITABLE)
invalid = set(incoming) - allowed
if invalid:
raise AppError(
f"仅允许申请修改:{'、'.join(SELF_EDITABLE)}",
"invalid_fields",
403,
)
changes: dict[str, dict[str, Any]] = {}
for key, after in incoming.items():
before = getattr(emp, key, None)
if str(before or "") == str(after or ""):
continue
changes[key] = {"before": before, "after": after}
if not changes:
raise AppError("提交内容与当前档案一致,无需审批", "no_changes")
request = ProfileRequest(
employee_id=emp.id,
changes=changes,
reason=payload.get("reason"),
status="pending",
applicant_user_id=auth.user.id,
)
session.add(request)
session.add(Notification(title="有新的员工信息变更待审核",
content=f"{emp.name} 提交了资料变更申请。", category="profile", link="/employee/pending"))
await session.flush()
session.add(ApprovalLog(
entity_type="profile",
entity_id=request.id,
action="submit",
actor_id=auth.user.id,
actor_name=auth.user.name,
comment=payload.get("reason"),
created_at=utcnow(),
))
await _notify_approvers(
session,
emp,
"有新的员工信息变更待审核",
f"{emp.name} 提交了 {len(changes)} 项资料变更申请。",
"/employees/changes",
)
await session.commit()
return {"message": "变更申请已提交,等待 HR 审核", "id": request.id}
return {
"message": "变更申请已提交,审核通过后才会写入个人档案",
"id": request.id,
"status": "pending",
"changed": list(changes),
}
@router.delete("/profile-requests/{item_id}", summary="撤回信息变更申请")
@ -379,11 +421,17 @@ async def my_payslip_detail(item_id: int, session: Session,
async def my_salary_standard(session: Session,
auth: Annotated[AuthContext, Depends(require_perm("selfservice:payslip:read"))]):
emp = await me(session, auth)
level = await session.get(JobLevel, emp.job_level_id) if emp.job_level_id else None
expense_standards = (level.expense_standards or []) if level else []
std = (await session.execute(select(EmployeeSalary).where(
EmployeeSalary.employee_id == emp.id, EmployeeSalary.is_active.is_(True))
.order_by(EmployeeSalary.effective_date.desc()))).scalars().first()
if not std:
return {"configured": False}
return {
"configured": False,
"job_level_name": level.name if level else None,
"expense_standards": expense_standards,
}
plan = await session.get(SalaryPlan, std.plan_id)
merged = dict(plan.items or {}) if plan and plan.items else {}
merged.update(std.overrides or {})
@ -397,6 +445,8 @@ async def my_salary_standard(session: Session,
"total": round(sum(float(v) for v in merged.values()), 2),
"bank_name": std.bank_name, "bank_account": _mask(std.bank_account),
"special_deduction": float(std.special_deduction or 0),
"job_level_name": level.name if level else None,
"expense_standards": expense_standards,
"adjustments": [{"effective_date": a.effective_date, "adjust_type": a.adjust_type,
"after_amount": float(a.after_amount or 0), "status": a.status,
"reason": a.reason} for a in adjustments],
@ -586,7 +636,7 @@ async def create_leave(payload: dict, session: Session,
session.add(ApprovalLog(entity_type="ben_leave_request", entity_id=request.id, action="submit",
actor_id=auth.user.id, actor_name=emp.name, created_at=utcnow()))
await _notify_approvers(session, emp, f"{emp.name} 提交了请假申请",
f"{leave_type.name} {days:g} 天({start} ~ {end})", "/m/approval")
f"{leave_type.name} {days:g} 天({start} ~ {end})", SELF_LINKS["approvals"])
await session.commit()
return {"message": "请假申请已提交", "id": request.id, "days": days}
@ -972,7 +1022,7 @@ async def decide(kind: str, item_id: int, payload: dict, session: Session,
if employee_id:
session.add(Notification(employee_id=employee_id,
title=f"{label}申请已{'通过' if decision == 'approved' else '驳回'}",
content=comment or summary, category="approval", link="/m/record"))
content=comment or summary, category="approval", link=SELF_LINKS["approvals"]))
await session.commit()
return {"message": f"已{'通过' if decision == 'approved' else '驳回'}", "status": decision}
@ -984,6 +1034,8 @@ async def _apply_profile_change(request: ProfileRequest, session: Session, decis
if not emp or decision != "approved":
return
for key, value in (request.changes or {}).items():
if isinstance(value, dict):
value = value.get("after")
if key in SELF_EDITABLE or key in ("highest_degree", "school", "specialty", "birthday",
"nation", "political_status", "emergency_contact",
"emergency_phone", "bank_name"):

View File

@ -217,6 +217,36 @@ MOBILE_MENU_TREE: list[dict] = [
{"name": "我的", "path": "/m/profile", "icon": "user", "perm": "selfservice:profile:read", "sort": 50},
]
# 普通员工在 PC 浏览器登录时使用的自助导航。名称、顺序和权限与 H5 底部导航
# 完全一致,只把目的地换成了管理端外壳内的响应式页面。
SELF_WEB_MENU_TREE: list[dict] = [
{"name": "首页", "path": "/dashboard", "icon": "HomeOutlined",
"perm": "selfservice:home:read", "sort": 10},
{"name": "请假", "path": "/self/leave", "icon": "CalendarOutlined",
"perm": "selfservice:leave:read", "sort": 20},
{"name": "工资", "path": "/self/payslips", "icon": "MoneyCollectOutlined",
"perm": "selfservice:payslip:read", "sort": 30},
{"name": "福利", "path": "/self/benefits", "icon": "GiftOutlined",
"perm": "selfservice:benefit:read", "sort": 40},
{"name": "我的", "path": "/self/profile", "icon": "UserOutlined",
"perm": "selfservice:profile:read", "sort": 50},
]
# 通知 / 待办里落库的 link 一律取这里的路径,不要在业务代码里手写字符串。
# 约定:用 H5 路径入库(历史数据即如此),前端渲染前统一过 toWebPath(),
# 于是同一条消息在 Web 工作台跳 /self/payslips、在 H5 跳 /m/payslips,永不 404。
# 审批与待办不在两份菜单树里(两端都从首页进入),因此在此显式登记。
SELF_LINKS = {
"home": "/m",
"leave": "/m/leave",
"payslips": "/m/payslips",
"benefits": "/m/benefits",
"approvals": "/m/approvals",
"tasks": "/m/tasks",
"profile": "/m/profile",
}
# --- built-in roles --------------------------------------------------------
# 员工自助 (H5) 基线:任何绑定档案的账号都应当能完成「看工资条 / 请假 / 改资料」
# 等自助动作。管理者与专员首先是员工,因此除超级管理员外,各角色模板均并入该基线;

View File

@ -2,7 +2,7 @@
from __future__ import annotations
from sqlalchemy import Boolean, ForeignKey, Integer, String, Text
from sqlalchemy import JSON, Boolean, ForeignKey, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column
from ..db.base import Base, PKMixin, TimestampMixin
@ -45,8 +45,15 @@ class JobLevel(PKMixin, TimestampMixin, Base):
grade: Mapped[int] = mapped_column(Integer, default=1)
sort: Mapped[int] = mapped_column(Integer, default=0)
is_active: Mapped[bool] = mapped_column(Boolean, default=True)
# 每个职级可配置多个报销项目,例如交通、住宿、通讯、餐费。
# 以 JSON 数组保存项目明细,避免为数量不固定的项目创建多张关联表。
expense_standards: Mapped[list[dict] | None] = mapped_column(JSON)
remark: Mapped[str | None] = mapped_column(String(255))
@property
def expense_standard_count(self) -> int:
return len(self.expense_standards or [])
class DictType(PKMixin, Base):
__tablename__ = "org_dict_type"

View File

@ -2,7 +2,7 @@
from __future__ import annotations
from pydantic import BaseModel
from pydantic import BaseModel, Field, field_validator, model_validator
from .common import ORMBase, make_create, make_update
@ -33,6 +33,20 @@ class PositionRead(ORMBase):
remark: str | None = None
class ExpenseStandardItem(BaseModel):
"""职级下的一项报销标准。金额由具体制度解释(月度/单次/按天等)。"""
project_name: str = Field(min_length=1, max_length=64)
limit_amount: float = Field(ge=0)
unit: str = Field(default="元/月", min_length=1, max_length=16)
remark: str | None = Field(default=None, max_length=255)
@field_validator("project_name", "unit")
@classmethod
def _strip_text(cls, value: str) -> str:
return value.strip()
class JobLevelRead(ORMBase):
id: int
name: str
@ -40,8 +54,27 @@ class JobLevelRead(ORMBase):
grade: int = 1
sort: int = 0
is_active: bool = True
expense_standards: list[ExpenseStandardItem] = Field(default_factory=list)
expense_standard_count: int = 0
remark: str | None = None
@field_validator("expense_standards", mode="before")
@classmethod
def _none_as_empty(cls, value):
return value or []
class ExpenseStandardsPayload(BaseModel):
items: list[ExpenseStandardItem] = Field(default_factory=list)
@model_validator(mode="after")
def _unique_projects(self):
names = [item.project_name for item in self.items]
duplicated = sorted({name for name in names if names.count(name) > 1})
if duplicated:
raise ValueError(f"报销项目不能重名:{'、'.join(duplicated)}")
return self
class DictItemRead(ORMBase):
id: int
@ -66,8 +99,14 @@ DepartmentCreate = make_create(DepartmentRead, "DepartmentCreate", required=("na
DepartmentUpdate = make_update(DepartmentRead, "DepartmentUpdate")
PositionCreate = make_create(PositionRead, "PositionCreate", required=("name",))
PositionUpdate = make_update(PositionRead, "PositionUpdate")
JobLevelCreate = make_create(JobLevelRead, "JobLevelCreate", required=("name",))
JobLevelUpdate = make_update(JobLevelRead, "JobLevelUpdate")
JobLevelCreate = make_create(
JobLevelRead, "JobLevelCreate", required=("name",),
exclude=("id", "created_at", "updated_at", "expense_standards", "expense_standard_count"),
)
JobLevelUpdate = make_update(
JobLevelRead, "JobLevelUpdate",
exclude=("id", "created_at", "updated_at", "expense_standards", "expense_standard_count"),
)
DictItemCreate = make_create(DictItemRead, "DictItemCreate", required=("type_code", "label", "value"))
DictItemUpdate = make_update(DictItemRead, "DictItemUpdate")
DictTypeCreate = make_create(DictTypeRead, "DictTypeCreate", required=("code", "name"),

View File

@ -11,6 +11,7 @@ from ..models.employee import Employee, EmployeeChange, EmployeeDocument, Employ
from ..models.org import Department, Position
from ..models.rbac import Announcement, Notification, User
from ..models.selfservice import ApprovalLog, ProfileRequest, TaskReminder
from ..core.permissions import SELF_LINKS
from .seed import RNG, already, count, log, mk
ANNOUNCEMENTS = [
@ -146,7 +147,7 @@ async def seed_tasks_notifications(session) -> dict:
due_date=date.today() + timedelta(days=days + RNG.randint(0, 10)),
level=level, status="pending",
detail="请在截止时间前完成,逾期将同步至部门负责人。",
link="/m/tasks"))
link=SELF_LINKS["tasks"]))
tasks += 1
await session.flush()
notes = 0
@ -154,11 +155,11 @@ async def seed_tasks_notifications(session) -> dict:
for emp in employees[:24]:
user = users.get(emp.id)
title, content, category, link = RNG.choice([
("您的请假申请已通过", "审批人已完成审批,可在「我的请假」中查看记录。", "leave", "/m/leave"),
("工资条已发布", "本月工资条已发布,请及时查看并确认。", "payslip", "/m/payslips"),
("合同即将到期", "您的劳动合同将在 60 天内到期,请联系 HR 办理续签。", "contract", "/m/profile"),
("试用期转正提醒", "您的试用期即将结束,请提交转正总结。", "regular", "/m/tasks"),
("生日祝福", "祝你生日快乐,愿你在新的一岁里一切顺利!", "system", "/m"),
("您的请假申请已通过", "审批人已完成审批,可在「我的请假」中查看记录。", "leave", SELF_LINKS["leave"]),
("工资条已发布", "本月工资条已发布,请及时查看并确认。", "payslip", SELF_LINKS["payslips"]),
("合同即将到期", "您的劳动合同将在 60 天内到期,请联系 HR 办理续签。", "contract", SELF_LINKS["profile"]),
("试用期转正提醒", "您的试用期即将结束,请提交转正总结。", "regular", SELF_LINKS["tasks"]),
("生日祝福", "祝你生日快乐,愿你在新的一岁里一切顺利!", "system", SELF_LINKS["home"]),
])
session.add(mk(Notification, user_id=user.id if user else None, employee_id=emp.id,
title=title, content=content, category=category, link=link,

View File

@ -126,10 +126,45 @@ async def seed_job_levels(session) -> int:
return len(JOB_LEVELS)
async def seed_expense_standards(session) -> int:
"""为尚未配置的职级补一套演示报销标准,便于直接验证与生成使用手册截图。"""
levels = list((await session.execute(select(JobLevel))).scalars().all())
changed = 0
for level in levels:
if level.expense_standards:
continue
grade = max(1, int(level.grade or 1))
level.expense_standards = [
{
"project_name": "市内交通",
"limit_amount": float(600 + grade * 300),
"unit": "元/月",
"remark": "因公出行,实报实销不超过月度上限",
},
{
"project_name": "差旅住宿",
"limit_amount": float(350 + grade * 100),
"unit": "元/晚",
"remark": "按出差城市标准执行",
},
{
"project_name": "通讯补贴",
"limit_amount": float(100 + grade * 50),
"unit": "元/月",
"remark": "凭话费发票报销",
},
]
changed += 1
await session.flush()
return changed
async def run(session, *, force: bool = False) -> dict:
dicts = await seed_dicts(session)
depts = await seed_departments(session)
positions = await seed_positions(session)
levels = await seed_job_levels(session)
standards = await seed_expense_standards(session)
return {"dict_items": dicts, "departments": depts, "positions": positions,
"job_levels": levels, "total_depts": await count(session, Department)}
"job_levels": levels, "expense_standards": standards,
"total_depts": await count(session, Department)}

View File

@ -0,0 +1,29 @@
"""job level expense standards
Revision ID: 8f1b2c3d4e5f
Revises: c4aff1fa2133
Create Date: 2026-10-20 12:00:00+08:00
"""
from __future__ import annotations
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "8f1b2c3d4e5f"
down_revision: Union[str, None] = "c4aff1fa2133"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
with op.batch_alter_table("org_job_level", schema=None) as batch_op:
batch_op.add_column(sa.Column("expense_standards", sa.JSON(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table("org_job_level", schema=None) as batch_op:
batch_op.drop_column("expense_standards")

View File

@ -0,0 +1,124 @@
#!/usr/bin/env python3
"""真实浏览器验收:设备自适应登录、Web/H5 菜单、帮助中心入口。"""
from __future__ import annotations
import json
import shutil
import subprocess
import tempfile
import time
import urllib.request
from pathlib import Path
from capture_help import CDP
BASE = "http://127.0.0.1:8000"
CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
PORT = 9231
DESKTOP_UA = (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0 Safari/537.36"
)
MOBILE_UA = (
"Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) "
"AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1"
)
def wait_page() -> str:
deadline = time.time() + 20
while time.time() < deadline:
try:
with urllib.request.urlopen(f"http://127.0.0.1:{PORT}/json/list", timeout=1) as resp:
target = next(x for x in json.load(resp) if x.get("type") == "page")
return target["webSocketDebuggerUrl"]
except Exception:
time.sleep(0.2)
raise RuntimeError("Chrome 调试端口未就绪")
def wait_path(cdp: CDP, path: str) -> None:
deadline = time.time() + 20
while time.time() < deadline:
if cdp.eval("location.pathname") == path:
time.sleep(0.8)
return
time.sleep(0.25)
raise AssertionError(f"登录后路径应为 {path},实际为 {cdp.eval('location.pathname')}")
def fill_and_login(cdp: CDP, username: str, password: str, mobile: bool) -> str:
width, height, scale = (390, 844, 2) if mobile else (1440, 960, 1)
cdp.call("Emulation.setDeviceMetricsOverride", {
"width": width, "height": height, "deviceScaleFactor": scale, "mobile": mobile,
})
cdp.call("Emulation.setUserAgentOverride", {"userAgent": MOBILE_UA if mobile else DESKTOP_UA})
cdp.navigate("/login", "登录工作台")
cdp.eval("localStorage.clear()")
cdp.navigate("/login", "登录工作台")
cdp.eval(
f"""(() => {{
const inputs = document.querySelectorAll('input');
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
setter.call(inputs[0], {json.dumps(username)});
inputs[0].dispatchEvent(new Event('input', {{bubbles: true}}));
setter.call(inputs[1], {json.dumps(password)});
inputs[1].dispatchEvent(new Event('input', {{bubbles: true}}));
const button = [...document.querySelectorAll('button')]
.find(x => x.innerText.replace(/\\s/g, '').includes('登录'));
button.click();
return true;
}})()"""
)
return "/m" if mobile else "/dashboard"
def main() -> None:
profile = Path(tempfile.mkdtemp(prefix="unis-hrms-smoke-"))
chrome = subprocess.Popen(
[
CHROME, "--headless=new", f"--remote-debugging-port={PORT}",
f"--user-data-dir={profile}", "--no-first-run", "--no-default-browser-check",
"--disable-gpu", "about:blank",
],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
try:
cdp = CDP(wait_page())
cdp.call("Page.enable")
cdp.call("Runtime.enable")
target = fill_and_login(cdp, "emp", "emp123456", mobile=False)
wait_path(cdp, target)
desktop_menus = cdp.eval(
"[...document.querySelectorAll('.admin-sider .ant-menu-title-content')].map(x => x.innerText.trim())"
)
assert desktop_menus == ["首页", "请假", "工资", "福利", "我的"], desktop_menus
cdp.call("Page.navigate", {"url": f"{BASE}/help"})
deadline = time.time() + 20
while time.time() < deadline and not cdp.eval("!!document.querySelector('iframe')"):
time.sleep(0.25)
assert cdp.eval("document.querySelector('iframe')?.getAttribute('src')") == "/help/index.html"
target = fill_and_login(cdp, "emp", "emp123456", mobile=True)
wait_path(cdp, target)
mobile_menus = cdp.eval(
"[...document.querySelectorAll('.m-tabbar .adm-tab-bar-item-title')].map(x => x.innerText.trim())"
)
assert mobile_menus == ["首页", "请假", "工资", "福利", "我的"], mobile_menus
print("browser smoke passed: desktop /dashboard, mobile /m, menus and help center")
cdp.ws.close()
finally:
chrome.terminate()
try:
chrome.wait(timeout=5)
except subprocess.TimeoutExpired:
chrome.kill()
shutil.rmtree(profile, ignore_errors=True)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,239 @@
#!/usr/bin/env python3
"""使用真实 Chrome 登录系统并生成 HTML 使用手册所需截图。
依赖本机 Google Chrome;通过 Chrome DevTools Protocol 操作页面,不额外安装
浏览器自动化包。运行前先启动 ``uvicorn app.main:app --port 8000``。
"""
from __future__ import annotations
import json
import shutil
import subprocess
import tempfile
import time
import urllib.request
from pathlib import Path
from websockets.sync.client import connect
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "web" / "public" / "help" / "assets"
BASE = "http://127.0.0.1:8000"
CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
PORT = 9227
def api_login(username: str, password: str) -> dict:
body = json.dumps({"username": username, "password": password}).encode()
req = urllib.request.Request(
f"{BASE}/api/v1/auth/login",
data=body,
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(req, timeout=20) as resp:
return json.load(resp)
class CDP:
def __init__(self, ws_url: str) -> None:
self.ws = connect(ws_url, max_size=64 * 1024 * 1024, legacy=True)
self.seq = 0
def call(self, method: str, params: dict | None = None) -> dict:
self.seq += 1
current = self.seq
self.ws.send(json.dumps({"id": current, "method": method, "params": params or {}}))
while True:
msg = json.loads(self.ws.recv(timeout=30))
if msg.get("id") == current:
if "error" in msg:
raise RuntimeError(f"{method}: {msg['error']}")
return msg.get("result", {})
def eval(self, expression: str):
result = self.call(
"Runtime.evaluate",
{"expression": expression, "returnByValue": True, "awaitPromise": True},
)
return result.get("result", {}).get("value")
def wait_text(self, text: str, timeout: float = 25) -> None:
deadline = time.time() + timeout
expression = f"document.body && document.body.innerText.includes({json.dumps(text)})"
while time.time() < deadline:
if self.eval(expression):
time.sleep(0.7)
return
time.sleep(0.25)
raise TimeoutError(f"页面未出现文字:{text}")
def navigate(self, path: str, text: str | None = None) -> None:
self.call("Page.navigate", {"url": f"{BASE}{path}"})
time.sleep(0.5)
if text:
self.wait_text(text)
def screenshot(self, name: str) -> None:
result = self.call(
"Page.captureScreenshot",
{"format": "png", "fromSurface": True, "captureBeyondViewport": False},
)
import base64
(OUT / name).write_bytes(base64.b64decode(result["data"]))
print(f"captured {name}")
def wait_debug_port() -> dict:
deadline = time.time() + 20
while time.time() < deadline:
try:
with urllib.request.urlopen(f"http://127.0.0.1:{PORT}/json/version", timeout=1) as resp:
return json.load(resp)
except Exception:
time.sleep(0.2)
raise RuntimeError("Chrome 调试端口未就绪")
def page_target() -> dict:
with urllib.request.urlopen(f"http://127.0.0.1:{PORT}/json/list", timeout=3) as resp:
targets = json.load(resp)
page = next((item for item in targets if item.get("type") == "page"), None)
if page is None:
raise RuntimeError("Chrome 中没有可用页面")
return page
def main() -> None:
OUT.mkdir(parents=True, exist_ok=True)
profile = Path(tempfile.mkdtemp(prefix="unis-hrms-chrome-"))
chrome = subprocess.Popen(
[
CHROME,
"--headless=new",
f"--remote-debugging-port={PORT}",
f"--user-data-dir={profile}",
"--no-first-run",
"--no-default-browser-check",
"--disable-gpu",
"--hide-scrollbars",
"--window-size=1600,1080",
"about:blank",
],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
try:
wait_debug_port()
cdp = CDP(page_target()["webSocketDebuggerUrl"])
cdp.call("Page.enable")
cdp.call("Runtime.enable")
cdp.call("Emulation.setDeviceMetricsOverride", {
"width": 1600, "height": 1080, "deviceScaleFactor": 1, "mobile": False,
})
cdp.navigate("/login", "登录工作台")
cdp.screenshot("01-login.png")
plans = [
("admin", "admin123", "/dashboard", "今日组织概览", "02-dashboard.png"),
("admin", "admin123", "/employees", "员工档案", "03-employees.png"),
("admin", "admin123", "/org/job-levels", "职级职等", "04-job-levels.png"),
("admin", "admin123", "/payroll/batches", "月度算薪", "06-payroll.png"),
("admin", "admin123", "/benefits/enrollments", "参保登记", "07-benefits.png"),
("admin", "admin123", "/system/roles", "角色权限", "08-roles.png"),
]
token_for = {}
for username, password, path, text, name in plans:
pair = token_for.get(username)
if pair is None:
pair = api_login(username, password)
token_for[username] = pair
cdp.navigate("/login")
cdp.eval(
"localStorage.setItem('unis-hrms-auth', "
+ json.dumps(json.dumps({
"state": {"token": pair["access_token"], "refresh": pair["refresh_token"]},
"version": 0,
}))
+ ")"
)
cdp.navigate(path, text)
cdp.screenshot(name)
# 职级行内打开“报销标准”抽屉,展示多项目配置。
cdp.navigate("/org/job-levels", "职级职等")
clicked = cdp.eval(
"(() => { const b=[...document.querySelectorAll('button')]"
".find(x => x.innerText.includes('报销标准')); if (!b) return false; b.click(); return true })()"
)
if not clicked:
raise RuntimeError("未找到报销标准按钮")
cdp.wait_text("可配置多个报销项目")
cdp.screenshot("05-expense-standards.png")
# 普通员工 Web 自助:导航直接呈现与 H5 同名的 5 项。
pair = api_login("emp", "emp123456")
token_for["emp"] = pair
cdp.navigate("/login")
cdp.eval(
"localStorage.setItem('unis-hrms-auth', "
+ json.dumps(json.dumps({
"state": {"token": pair["access_token"], "refresh": pair["refresh_token"]},
"version": 0,
}))
+ ")"
)
cdp.navigate("/dashboard", "常用自助入口")
cdp.screenshot("09-web-self-home.png")
cdp.navigate("/self/profile", "我的信息")
cdp.screenshot("10-web-self-profile.png")
cdp.eval(
"(() => { const b=[...document.querySelectorAll('span,a,button')]"
".find(x => x.innerText.trim()==='修改资料'); if (!b) return false; b.click(); return true })()"
)
cdp.wait_text("提交审核")
cdp.screenshot("11-profile-audit.png")
# H5 自动识别由单独的手机视口验证。
cdp.call("Emulation.setDeviceMetricsOverride", {
"width": 390, "height": 844, "deviceScaleFactor": 2, "mobile": True,
})
cdp.call("Emulation.setUserAgentOverride", {
"userAgent": (
"Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) "
"AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1"
),
})
cdp.navigate("/m", "最新实发工资")
cdp.screenshot("12-h5-home.png")
cdp.navigate("/m/profile", "我的信息")
cdp.screenshot("13-h5-profile.png")
# 审批中心使用 HR 账号(拥有审批权且有员工档案)。
pair = token_for.get("hr") or api_login("hr", "hr123456")
cdp.navigate("/login")
cdp.eval(
"localStorage.setItem('unis-hrms-auth', "
+ json.dumps(json.dumps({
"state": {"token": pair["access_token"], "refresh": pair["refresh_token"]},
"version": 0,
}))
+ ")"
)
cdp.navigate("/m/approvals", "审批中心")
cdp.screenshot("14-approvals.png")
cdp.ws.close()
finally:
chrome.terminate()
try:
chrome.wait(timeout=5)
except subprocess.TimeoutExpired:
chrome.kill()
shutil.rmtree(profile, ignore_errors=True)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,63 @@
"""职级报销标准:多项目保存、校验与权限边界。"""
from __future__ import annotations
API = "/api/v1"
def test_job_level_can_store_multiple_expense_standards(client, admin, payroll):
levels = client.get(f"{API}/org/job-levels", headers=admin, params={"page_size": 50}).json()["items"]
level = next(row for row in levels if row["code"] == "P1")
items = [
{"project_name": "市内交通", "limit_amount": 1200, "unit": "元/月", "remark": "实报实销"},
{"project_name": "差旅住宿", "limit_amount": 650, "unit": "元/晚", "remark": "按城市标准"},
{"project_name": "通讯补贴", "limit_amount": 200, "unit": "元/月", "remark": "凭发票报销"},
]
saved = client.put(
f"{API}/org/job-levels/{level['id']}/expense-standards",
headers=admin,
json={"items": items},
)
assert saved.status_code == 200, saved.text
assert saved.json()["count"] == 3
loaded = client.get(
f"{API}/org/job-levels/{level['id']}/expense-standards",
headers=payroll,
)
assert loaded.status_code == 200, loaded.text
assert loaded.json() == items
detail = client.get(f"{API}/org/job-levels/{level['id']}", headers=admin).json()
assert detail["expense_standard_count"] == 3
def test_expense_standards_reject_duplicates_and_require_update_permission(client, admin, payroll):
levels = client.get(f"{API}/org/job-levels", headers=admin, params={"page_size": 50}).json()["items"]
level = levels[0]
duplicated = [
{"project_name": "交通", "limit_amount": 100, "unit": "元/月"},
{"project_name": "交通", "limit_amount": 200, "unit": "元/月"},
]
bad = client.put(
f"{API}/org/job-levels/{level['id']}/expense-standards",
headers=admin,
json={"items": duplicated},
)
assert bad.status_code == 422
denied = client.put(
f"{API}/org/job-levels/{level['id']}/expense-standards",
headers=payroll,
json={"items": duplicated[:1]},
)
assert denied.status_code == 403
def test_employee_salary_standard_exposes_job_level_expense_standards(client, employee):
mine = client.get(f"{API}/self/salary-standard", headers=employee)
assert mine.status_code == 200, mine.text
body = mine.json()
assert body["job_level_name"]
assert len(body["expense_standards"]) >= 1
assert {"project_name", "limit_amount", "unit"} <= set(body["expense_standards"][0])

View File

@ -256,6 +256,10 @@ def test_selfservice_profile_request_is_applied(client, employee, hr):
json={"changes": {"address": "测试地址 100 号"}, "reason": "搬家"})
assert submitted.status_code == 200, submitted.text
request_id = submitted.json()["id"]
snapshots = client.get("/api/v1/self/profile", headers=employee).json()["requests"]
snapshot = next(row for row in snapshots if row["id"] == request_id)
assert snapshot["changes"]["address"]["after"] == "测试地址 100 号"
assert snapshot["status"] == "pending"
listed = client.get("/api/v1/employee-profile-requests", headers=hr,
params={"status": "pending"}).json()["items"]
@ -269,6 +273,28 @@ def test_selfservice_profile_request_is_applied(client, employee, hr):
assert fresh["address"] == "测试地址 100 号"
def test_legacy_profile_patch_cannot_bypass_approval(client, employee, hr):
"""旧 PATCH 入口只能生成审批单,不能把内容直接写进员工档案。"""
old_email = client.get("/api/v1/self/profile", headers=employee).json()["employee"]["email"]
target = f"audit-{old_email or 'employee'}@example.com"
submitted = client.patch("/api/v1/self/profile", headers=employee, json={"email": target})
assert submitted.status_code == 200, submitted.text
body = submitted.json()
assert body["status"] == "pending"
unchanged = client.get("/api/v1/self/profile", headers=employee).json()["employee"]["email"]
assert unchanged == old_email, "审核前不得直接修改档案"
approved = client.post(
f"/api/v1/employee-profile-requests/{body['id']}/approve",
headers=hr,
json={"status": "approved", "comment": "自动化审核"},
)
assert approved.status_code == 200, approved.text
changed = client.get("/api/v1/self/profile", headers=employee).json()["employee"]["email"]
assert changed == target
def test_payslip_privacy_between_employees(client, login):
a = login("emp00001")
b = login("emp00002")

View File

@ -451,7 +451,7 @@ WEB_MENUS = {
"/recruitment/pipeline", "/recruitment/candidates", "/recruitment/interviews",
"/payroll/reports", "/benefits/leaves", "/org/departments",
"/org/positions", "/org/job-levels"},
"emp00001": {"/dashboard"},
"emp00001": {"/dashboard", "/self/leave", "/self/payslips", "/self/benefits", "/self/profile"},
}
H5_TILES = {"/m", "/m/leave", "/m/payslips", "/m/benefits", "/m/profile"}
@ -480,6 +480,19 @@ def test_menus_agree_with_api_access(client, login, admin, specialist):
assert spec == H5_TILES
def test_employee_web_and_h5_menu_names_match(client, login):
"""普通员工 PC 自助导航与 H5 必须同名、同序、同权限。"""
headers = _login(login, "emp00001")
web = client.get(f"{API}/auth/menus", headers=headers, params={"platform": "web"}).json()
mobile = client.get(f"{API}/auth/menus", headers=headers, params={"platform": "mobile"}).json()
assert [node["name"] for node in web] == ["首页", "请假", "工资", "福利", "我的"]
assert [node["name"] for node in web] == [node["name"] for node in mobile]
assert [node["perm_code"] for node in web] == [node["perm_code"] for node in mobile]
assert [node["path"] for node in web] == [
"/dashboard", "/self/leave", "/self/payslips", "/self/benefits", "/self/profile",
]
def test_self_service_surface_available_to_every_bound_account(client, login):
"""自助端:所有绑定档案的账号 12 个只读接口全绿,且看不到别人的数据。"""
for account in ACCOUNTS:

View File

@ -0,0 +1,222 @@
"""Web 工作台 ⇄ H5 自助端 的一致性守卫(纯静态,不连数据库)。
「普通用户在两端看到同一套模块」这件事靠三层保证:
1. ``web/src/self/manifest.ts`` —— 前端唯一的模块清单(名称/权限/顺序/图标/双端路径);
2. ``app/core/permissions.py`` 的 ``MOBILE_MENU_TREE`` 与 ``SELF_WEB_MENU_TREE``
—— 后端按权限下发给两个外壳的导航树;
3. ``app/core/permissions.py`` 的 ``SELF_LINKS`` —— 通知与待办落库的跳转路径。
三者一旦漂移(改了 H5 忘了 Web、后端 link 写成历史单数路径),本文件的断言就会红。
"""
from __future__ import annotations
import pathlib
import re
ROOT = pathlib.Path(__file__).resolve().parents[1]
WEB = ROOT / "web" / "src"
from app.core.permissions import SELF_LINKS, MOBILE_MENU_TREE, SELF_WEB_MENU_TREE # noqa: E402
MANIFEST = (WEB / "self" / "manifest.ts").read_text(encoding="utf-8")
APP = (WEB / "App.tsx").read_text(encoding="utf-8")
ROUTE_PERMS = (WEB / "api" / "routePerms.ts").read_text(encoding="utf-8")
MODE = (WEB / "lib" / "mode.ts").read_text(encoding="utf-8")
ICONS = (WEB / "components" / "icons.tsx").read_text(encoding="utf-8")
SELF_KEYS = {"home", "leave", "payslips", "benefits", "approvals", "tasks", "profile"}
TEXT = re.compile(r"(\w+): '([^']*)'")
def manifest_modules() -> dict[str, dict]:
"""解析 manifest.ts 里的 SELF_MODULES,返回 {key: {字段: 值}}。"""
body = MANIFEST.split("SELF_MODULES: Record<SelfModuleKey, SelfModule> = {", 1)[1]
body = body.split("\n}\n", 1)[0]
out: dict[str, dict] = {}
for name, block in re.findall(r"\n (\w+): \{(.*?)\n \},", body, re.S):
item = dict(TEXT.findall(block))
assert item.get("key") == name, f"{name}: key 与对象名不一致"
for flag in ("sort",):
item[flag] = int(re.search(flag + r": (\d+)", block).group(1))
for flag in ("inWebMenu", "inMobileTab"):
item[flag] = re.search(flag + r": (true|false)", block).group(1) == "true"
out[name] = item
return out
MODS = manifest_modules()
def test_manifest_lists_every_self_service_module():
assert set(MODS) == SELF_KEYS, "自助模块清单与 manifest 不符"
for key, m in MODS.items():
for field in ("name", "title", "desc", "perm", "webPath", "mobilePath",
"antdIcon", "mobileIcon", "emoji", "color"):
assert m.get(field), f"{key} 缺少 {field}"
def test_manifest_matches_backend_h5_menu_tree():
"""底部 5 个 tab:名称 / 权限 / 路径 / 顺序必须与后端下发的一致。"""
tabs = sorted((m for m in MODS.values() if m["inMobileTab"]), key=lambda x: x["sort"])
assert [m["name"] for m in tabs] == [n["name"] for n in MOBILE_MENU_TREE]
assert [m["mobilePath"] for m in tabs] == [n["path"] for n in MOBILE_MENU_TREE]
assert [m["perm"] for m in tabs] == [n["perm"] for n in MOBILE_MENU_TREE]
assert [n["sort"] for n in MOBILE_MENU_TREE] == sorted(n["sort"] for n in MOBILE_MENU_TREE)
def test_manifest_matches_backend_web_menu_tree():
"""Web 侧栏 5 项:除路径外,与 H5 tab 完全同名同序同权限。"""
nav = sorted((m for m in MODS.values() if m["inWebMenu"]), key=lambda x: x["sort"])
assert [m["name"] for m in nav] == [n["name"] for n in SELF_WEB_MENU_TREE]
assert [m["webPath"] for m in nav] == [n["path"] for n in SELF_WEB_MENU_TREE]
assert [m["perm"] for m in nav] == [n["perm"] for n in SELF_WEB_MENU_TREE]
assert [n["sort"] for n in SELF_WEB_MENU_TREE] == sorted(n["sort"] for n in SELF_WEB_MENU_TREE)
def test_two_shells_use_the_same_navigation_placement():
"""两端可见模块必须一模一样:多的少了都是「Web 和 H5 不一致」的回归。"""
assert {m["key"] for m in MODS.values() if m["inWebMenu"]} == \
{m["key"] for m in MODS.values() if m["inMobileTab"]}
# 审批与待办刻意不进导航,两端都从首页宫格进入
off = {k for k, m in MODS.items() if not m["inWebMenu"]}
assert off == {"approvals", "tasks"}, off
def test_every_self_route_exists_in_both_shells():
"""manifest 里的每个路径都必须在 App.tsx 注册了路由,否则点了就是 404。"""
for key, m in MODS.items():
assert re.search(r'<Route path="self/' + re.escape(m["webPath"].split("/")[-1]) + r'"', APP) \
or m["webPath"] == "/dashboard", f"{key}: Web 路由缺失 {m['webPath']}"
seg = m["mobilePath"].replace("/m", "").lstrip("/")
pattern = '<Route index' if not seg else '<Route path="' + re.escape(seg) + '"'
assert pattern in APP, f"{key}: H5 路由缺失 {m['mobilePath']}"
assert 'path="/m"' in APP
def test_web_route_perms_match_manifest_permissions():
"""Web 侧栏准入按权限:routePerms.ts 里登记的权限必须等于 manifest 的 perm。"""
for key, m in MODS.items():
if m["webPath"] == "/dashboard":
continue
row = re.search(re.escape("'" + m["webPath"] + "'") + r": \[([^\]]*)\]", ROUTE_PERMS)
assert row, f"{key}: routePerms.ts 未登记 {m['webPath']}"
assert m["perm"] in row.group(1), f"{key}: {m['webPath']} 权限 {row.group(1)} 与 {m['perm']} 不符"
def test_icons_are_registered_for_both_shells():
for key, m in MODS.items():
assert m["antdIcon"] in ICONS, f"{key}: 图标 {m['antdIcon']} 未注册"
block = ICONS.split("MOBILE_ICONS: Record<string, IconComp> = {", 1)[1].split("}", 1)[0]
registered = set(re.findall(r"(\w+):\s", block))
for key, m in MODS.items():
assert m["mobileIcon"] in registered, f"{key}: H5 图标 {m['mobileIcon']} 未注册"
def test_notification_links_follow_the_canonical_paths():
"""落库 link 只能是 manifest 里的 H5 路径,前端再改写为当前外壳的路径。"""
mobile = {m["mobilePath"] for m in MODS.values()}
for key, link in SELF_LINKS.items():
assert key in MODS, f"SELF_LINKS 多出未知模块 {key}"
assert link == MODS[key]["mobilePath"], f"{key}: link={link} 应为 {MODS[key]['mobilePath']}"
assert link in mobile
def test_business_code_never_hardcodes_mobile_paths():
"""通知 / 待办的 link 一律走 SELF_LINKS,避免又写出 /m/payslip 这种历史单数路径。"""
offenders = []
for py in (ROOT / "app").rglob("*.py"):
if py.name == "permissions.py":
continue
for lineno, line in enumerate(py.read_text(encoding="utf-8").splitlines(), 1):
if '"/m/' in line or "'/m/" in line:
offenders.append(f"{py.relative_to(ROOT)}:{lineno}")
assert not offenders, "请改用 SELF_LINKS:" + ", ".join(offenders)
def test_h5_pages_share_the_web_data_layer():
"""两端读同一批 hooks / queryKey:H5 页面不得再自己拼 query 与状态字典。"""
pages = sorted((WEB / "pages" / "mobile").glob("M*.tsx"))
extra = {"MLogin.tsx"}
checked = [p for p in pages if p.name not in extra]
assert len(checked) >= 7, "H5 页面数量异常"
for p in checked:
src = p.read_text(encoding="utf-8")
assert "from '../../api/http'" not in src, f"{p.name} 仍在直连 api/http"
assert re.search(r"useQuery\(|useMutation\(", src) is None, f"{p.name} 仍自建查询"
for p in sorted((WEB / "pages" / "self").glob("*.tsx")):
if p.name == "_shared.tsx":
continue
assert "from '../../api/self'" in p.read_text(encoding="utf-8"), f"{p.name} 未使用公共数据层"
def test_both_shells_use_the_shared_formatters():
"""金额/百分比只能走 lib/selfLabels 的格式化函数,避免两端数值字面不一致。"""
offenders: list[str] = []
for sub in ("self", "mobile"):
for tsx in (WEB / "pages" / sub).glob("*.tsx"):
if tsx.name == "_shared.tsx":
continue
for lineno, line in enumerate(tsx.read_text(encoding="utf-8").splitlines(), 1):
# 0.07 * 100 直出百分比会露出浮点尾数(7.000000000000001%)
if re.search(r"\* 100\)?}\s*%", line) or "\u00a5{Number" in line:
offenders.append(f"{tsx.relative_to(ROOT)}:{lineno}")
assert not offenders, "请改用 selfLabels 的 pct()/rmb():" + ", ".join(offenders)
# 用到比例与金额的页面必须真的引用了公共层
for name in ("self/Benefits.tsx", "mobile/MBenefits.tsx"):
src = (WEB / "pages" / name).read_text(encoding="utf-8")
assert "pct" in src and "rmb" in src, f"{name} 未使用公共格式化函数"
def test_status_dictionaries_are_complete_for_both_shells():
"""状态中文只有一份来源:自助端不得漏字典、也不得再内联三元判断。"""
labels = (WEB / "lib" / "selfLabels.ts").read_text(encoding="utf-8")
defs = (WEB / "api" / "defs.ts").read_text(encoding="utf-8")
# 合同状态取自后台同一份 CONTRACT_STATUS_OPTIONS,renewed 这类取值不会再露英文
block = labels.split("export const CONTRACT_STATUS_TEXT", 1)[1].split("export const", 1)[0]
assert "CONTRACT_STATUS_OPTIONS.map" in block, "合同状态字典应派生自 api/defs"
opts = defs.split("export const CONTRACT_STATUS_OPTIONS", 1)[1].split("]", 1)[0]
colors = labels.split("export const CONTRACT_STATUS_COLOR", 1)[1].split("}", 1)[0]
for value in re.findall(r"value: '(\w+)'", opts):
assert f"{value}: '" in colors, f"合同状态 {value} 缺少配色"
# 两端页面不得再把 .status / .unit 各自翻译成中文:必须走 lib/selfLabels 字典
offenders: list[str] = []
for sub in ("self", "mobile"):
for tsx in (WEB / "pages" / sub).glob("*.tsx"):
for lineno, line in enumerate(tsx.read_text(encoding="utf-8").splitlines(), 1):
if re.search(r"(?<!\?)\.(status|unit)\s*===\s*'[\w-]+'\s*\?\s*'[^']*[一-鿿]", line):
offenders.append(f"{tsx.relative_to(ROOT)}:{lineno}")
assert not offenders, "请改用 lib/selfLabels 的状态字典:" + ", ".join(offenders)
def test_desktop_lands_on_web_shell_by_default():
"""问题 1 的回归守卫:桌面浏览器必须落 Web 工作台,账号不决定外壳。"""
assert "localStorage" in MODE, "外壳偏好必须持久化,否则员工每次登录都被拽回 H5"
entry = MODE.split("export const entryPath", 1)[1].split("\n", 2)[:2]
assert "currentMode() === 'h5'" in entry[0]
assert "'/m'" in entry[0] and "'/dashboard'" in entry[0]
# 偏好优先于设备:只有显式选了 H5 或本身是手机浏览器才走 H5
assert "pref === 'auto' ? detectMode() : pref" in MODE
assert "isMobileBrowser()" in MODE
# 登录与过期跳转都必须经过外壳改写,不能把 ?redirect=/m 原样吞下
assert "sanitizeRedirect(" in (WEB / "pages" / "Login.tsx").read_text(encoding="utf-8")
auth = (WEB / "store" / "auth.ts").read_text(encoding="utf-8")
assert "pathname.startsWith('/m')" not in auth, "token 过期不能再按 /m 前缀决定去向"
def test_both_home_grids_come_from_the_manifest():
"""两端首页宫格都由 manifest 生成:新增模块时只需改一处,两端同时出现。"""
for name in ("SelfHome.tsx", "mobile/MHome.tsx"):
src = (WEB / "pages" / name).read_text(encoding="utf-8")
assert "permittedModules(" in src, f"{name} 首页宫格未取 manifest"
assert "setModePref(" in src, f"{name} 缺少显式切换外壳的入口"
# 两端都能一键切到对方,且切完记住偏好
for name in ("SelfHome.tsx", "mobile/MHome.tsx", "mobile/MProfile.tsx"):
assert "oppositePath(" in (WEB / "pages" / name).read_text(encoding="utf-8"), name
def test_no_web_self_frame_phone_mockup_left():
"""Web 端不再用手机框套 H5 页面 —— 这是两端功能不一致的历史根源。"""
assert not (WEB / "components" / "WebSelfFrame.tsx").exists()
assert "web-self-frame" not in (WEB / "styles" / "global.css").read_text(encoding="utf-8")
assert "WebSelfFrame" not in re.sub(r"/\*.*?\*/", "", APP, flags=re.S), "Web 端不得再引用手机框"

Binary file not shown.

After

Width:  |  Height:  |  Size: 278 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 176 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 262 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 133 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 145 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 241 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 170 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 180 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 216 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 173 KiB

View File

@ -0,0 +1,613 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>UNIS HRMS 全功能使用手册</title>
<style>
:root {
--ink: #172033;
--muted: #687386;
--line: #e7ebf2;
--brand: #2f54eb;
--brand-soft: #eef2ff;
--cyan: #13a8b8;
--success: #16a34a;
--warning: #d97706;
--bg: #f5f7fb;
--card: #fff;
--shadow: 0 14px 38px rgba(21, 35, 64, .08);
}
* { box-sizing: border-box; }
html { scroll-behavior: smooth; }
body {
margin: 0;
color: var(--ink);
background:
radial-gradient(900px 420px at 10% -5%, #dfe8ff 0, transparent 65%),
var(--bg);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
line-height: 1.72;
}
a { color: var(--brand); text-decoration: none; }
img { display: block; max-width: 100%; }
.layout {
display: grid;
grid-template-columns: 270px minmax(0, 1fr);
max-width: 1500px;
margin: 0 auto;
min-height: 100vh;
}
aside {
position: sticky;
top: 0;
height: 100vh;
overflow-y: auto;
padding: 34px 24px;
background: rgba(255, 255, 255, .88);
border-right: 1px solid var(--line);
backdrop-filter: blur(14px);
}
.logo {
display: flex;
gap: 12px;
align-items: center;
margin-bottom: 28px;
}
.logo-mark {
width: 44px;
height: 44px;
border-radius: 13px;
display: grid;
place-items: center;
color: white;
font-size: 22px;
font-weight: 800;
background: linear-gradient(145deg, #2f54eb, #13c2c2);
box-shadow: 0 8px 20px rgba(47, 84, 235, .24);
}
.logo b { display: block; line-height: 1.2; }
.logo small { color: var(--muted); }
.toc-title {
margin: 22px 0 8px;
color: #929bad;
font-size: 11px;
letter-spacing: .12em;
text-transform: uppercase;
}
nav a {
display: block;
padding: 8px 11px;
border-radius: 9px;
color: #475467;
font-size: 13px;
}
nav a:hover { color: var(--brand); background: var(--brand-soft); }
.side-note {
margin-top: 26px;
padding: 13px;
border-radius: 12px;
background: #f7f9ff;
border: 1px solid #e4e9f8;
color: var(--muted);
font-size: 12px;
}
main { padding: 42px clamp(22px, 5vw, 70px) 80px; }
.hero {
overflow: hidden;
position: relative;
padding: clamp(30px, 5vw, 58px);
border-radius: 26px;
color: white;
background: linear-gradient(135deg, #173bbf 0%, #2f54eb 50%, #13b8c2 120%);
box-shadow: var(--shadow);
}
.hero::after {
content: "";
position: absolute;
width: 420px;
height: 420px;
border: 1px solid rgba(255, 255, 255, .16);
border-radius: 50%;
right: -130px;
top: -210px;
box-shadow: 0 0 0 70px rgba(255, 255, 255, .03), 0 0 0 140px rgba(255, 255, 255, .025);
}
.eyebrow {
position: relative;
z-index: 1;
font-size: 12px;
letter-spacing: .16em;
text-transform: uppercase;
opacity: .78;
}
.hero h1 {
position: relative;
z-index: 1;
margin: 10px 0 12px;
font-size: clamp(30px, 4vw, 48px);
line-height: 1.16;
}
.hero p {
position: relative;
z-index: 1;
max-width: 850px;
margin: 0;
font-size: 15px;
color: rgba(255, 255, 255, .88);
}
.hero-actions {
position: relative;
z-index: 1;
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-top: 24px;
}
.button {
appearance: none;
border: 1px solid rgba(255, 255, 255, .35);
border-radius: 10px;
padding: 9px 16px;
color: white;
background: rgba(255, 255, 255, .12);
cursor: pointer;
font: inherit;
font-weight: 600;
}
.button.primary { color: #2441c5; background: white; border-color: white; }
.meta {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 12px;
margin: 18px 0 34px;
}
.meta div {
padding: 15px 18px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(255, 255, 255, .82);
}
.meta small { display: block; color: var(--muted); font-size: 11px; }
.meta b { font-size: 14px; }
section {
scroll-margin-top: 24px;
margin-top: 28px;
padding: 30px;
border: 1px solid var(--line);
border-radius: 20px;
background: var(--card);
box-shadow: 0 8px 24px rgba(21, 35, 64, .045);
}
h2 {
display: flex;
gap: 12px;
align-items: center;
margin: 0 0 10px;
font-size: 23px;
line-height: 1.3;
}
h2 .no {
flex: none;
width: 34px;
height: 34px;
display: grid;
place-items: center;
border-radius: 10px;
color: var(--brand);
background: var(--brand-soft);
font-size: 13px;
}
h3 { margin: 26px 0 8px; font-size: 17px; }
.lead { color: var(--muted); margin: 0 0 18px; }
.grid-2, .grid-3 {
display: grid;
gap: 14px;
}
.grid-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.grid-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.tile {
padding: 17px;
border-radius: 14px;
border: 1px solid var(--line);
background: #fbfcff;
}
.tile b { display: block; margin-bottom: 5px; }
.tile p { margin: 0; color: var(--muted); font-size: 13px; }
.steps {
counter-reset: step;
display: grid;
gap: 11px;
padding: 0;
margin: 16px 0;
list-style: none;
}
.steps li {
counter-increment: step;
position: relative;
min-height: 36px;
padding: 7px 0 7px 48px;
color: #344054;
}
.steps li::before {
content: counter(step);
position: absolute;
left: 0;
top: 2px;
width: 30px;
height: 30px;
display: grid;
place-items: center;
border-radius: 9px;
color: white;
background: var(--brand);
font-size: 12px;
font-weight: 700;
}
.callout {
margin: 16px 0;
padding: 14px 16px;
border-radius: 12px;
border-left: 4px solid var(--brand);
background: #f3f6ff;
color: #344054;
font-size: 13px;
}
.callout.success { border-color: var(--success); background: #f0fdf4; }
.callout.warning { border-color: var(--warning); background: #fffbeb; }
figure { margin: 20px 0 6px; }
figure img {
width: 100%;
border: 1px solid var(--line);
border-radius: 14px;
background: #f7f9fd;
box-shadow: 0 12px 30px rgba(21, 35, 64, .09);
}
figcaption {
margin-top: 8px;
color: var(--muted);
font-size: 12px;
text-align: center;
}
.shot-pair {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 16px;
align-items: start;
}
.shot-pair figure { margin-top: 0; }
.phone { max-width: 390px; margin: 20px auto; }
table {
width: 100%;
margin-top: 14px;
border-collapse: collapse;
font-size: 13px;
}
th, td {
padding: 10px 12px;
border-bottom: 1px solid var(--line);
text-align: left;
vertical-align: top;
}
th { background: #f8faff; color: #475467; }
td:first-child { font-weight: 600; }
.pill {
display: inline-block;
padding: 2px 9px;
border-radius: 999px;
color: var(--success);
background: #ecfdf3;
font-size: 11px;
font-weight: 700;
}
.faq details {
padding: 12px 0;
border-bottom: 1px solid var(--line);
}
.faq details:last-child { border-bottom: 0; }
.faq summary { cursor: pointer; font-weight: 600; }
.faq p { color: var(--muted); font-size: 13px; }
footer {
margin-top: 30px;
color: #98a2b3;
font-size: 12px;
text-align: center;
}
@media (max-width: 980px) {
.layout { display: block; }
aside { position: relative; width: 100%; height: auto; padding: 20px; }
nav { display: flex; gap: 6px; overflow-x: auto; padding-bottom: 4px; }
nav a { flex: none; background: #f7f9ff; }
.side-note, .toc-title { display: none; }
main { padding: 24px 16px 60px; }
.meta, .grid-2, .grid-3, .shot-pair { grid-template-columns: 1fr; }
}
@media (max-width: 600px) {
section { padding: 20px 16px; }
.hero { padding: 28px 22px; border-radius: 18px; }
.hero h1 { font-size: 30px; }
.meta { margin-top: 12px; }
}
@media print {
body { background: white; }
aside, .hero-actions { display: none; }
.layout { display: block; }
main { padding: 0; }
.hero { box-shadow: none; }
section { break-inside: avoid; box-shadow: none; }
a { color: var(--ink); }
}
</style>
</head>
<body>
<div class="layout">
<aside>
<div class="logo">
<div class="logo-mark">U</div>
<div><b>UNIS HRMS</b><small>全功能使用手册</small></div>
</div>
<div class="toc-title">目录</div>
<nav>
<a href="#start">01 登录与设备识别</a>
<a href="#admin">02 管理端工作台</a>
<a href="#employee">03 人事档案</a>
<a href="#expense">04 职级报销标准</a>
<a href="#payroll">05 薪资与福利</a>
<a href="#roles">06 角色与权限</a>
<a href="#self-web">07 员工 Web 自助</a>
<a href="#profile-audit">08 档案修改审核</a>
<a href="#self-h5">09 员工 H5 自助</a>
<a href="#approval">10 审批中心</a>
<a href="#test">11 验收清单</a>
<a href="#faq">12 常见问题</a>
</nav>
<div class="side-note">
本手册对应 UNIS HRMS 2.0 当前版本,截图来自真实运行页面。演示数据均为系统种子数据。
</div>
</aside>
<main>
<header class="hero">
<div class="eyebrow">UNIS HRMS · User Guide</div>
<h1>全功能使用手册</h1>
<p>覆盖管理端、员工 Web 自助、H5 自助、职级报销标准、个人档案审核、薪资福利、招聘与系统权限。按页面步骤即可完成日常操作。</p>
<div class="hero-actions">
<button class="button primary" onclick="window.print()">打印 / 导出 PDF</button>
<button class="button" onclick="document.querySelector('nav a').click()">开始阅读</button>
</div>
</header>
<div class="meta">
<div><small>适用版本</small><b>UNIS HRMS 2.0</b></div>
<div><small>更新日期</small><b>2026-10-20</b></div>
<div><small>运行方式</small><b>Web / H5 自适应</b></div>
</div>
<section id="start">
<h2><span class="no">01</span>登录与设备识别</h2>
<p class="lead">系统不再要求手动勾选 H5;登录后会根据当前浏览器的设备特征自动选择入口。</p>
<div class="grid-3">
<div class="tile"><b>桌面浏览器</b><p>进入 Web 工作台。普通员工会看到“首页 / 请假 / 工资 / 福利 / 我的”五项自助导航。</p></div>
<div class="tile"><b>手机 / H5 浏览器</b><p>自动进入 <code>/m</code> 移动自助端,底部导航与 Web 自助菜单同名、同序、同权限。</p></div>
<div class="tile"><b>指定跳转</b><p>从系统内部链接进入时,会优先回到原目标页面;无指定目标时再执行设备判断。</p></div>
</div>
<ol class="steps">
<li>打开系统地址,输入账号和密码。</li>
<li>点击“登录”,系统自动识别桌面或手机浏览器。</li>
<li>首次登录建议先打开右上角“使用手册”确认角色与可用功能。</li>
</ol>
<figure>
<img src="assets/01-login.png" alt="UNIS HRMS 登录页">
<figcaption>登录页会明确提示“将根据当前浏览器自动进入 Web 工作台或 H5 自助端”。</figcaption>
</figure>
</section>
<section id="admin">
<h2><span class="no">02</span>管理端工作台</h2>
<p class="lead">工作台按角色汇总组织人数、待办、人员趋势、招聘漏斗、薪资成本与风险提醒。</p>
<div class="grid-3">
<div class="tile"><b>核心指标</b><p>在职人数、试用期人数、在招职位、最近计薪总额。</p></div>
<div class="tile"><b>待我处理</b><p>请假、资料变更、人事异动、合同到期均可直接进入对应流程。</p></div>
<div class="tile"><b>风险提醒</b><p>合同临期、生日提醒、累计离职等情况在右上区域集中展示。</p></div>
</div>
<figure>
<img src="assets/02-dashboard.png" alt="管理端工作台">
<figcaption>管理端工作台:主管与 HR 登录后的统一数据概览。</figcaption>
</figure>
</section>
<section id="employee">
<h2><span class="no">03</span>人事档案</h2>
<p class="lead">员工花名册支持关键字、部门、职位、职级、状态与用工形式组合查询,并可从任意行打开 360° 档案。</p>
<ol class="steps">
<li>进入“人事档案 → 员工档案”。</li>
<li>使用搜索框或表头筛选定位员工。</li>
<li>点击行尾“档案”查看个人信息、合同、教育、家庭、异动与薪资摘要。</li>
<li>批量导入使用右上角“批量导入”;导出会沿用当前筛选条件。</li>
</ol>
<figure>
<img src="assets/03-employees.png" alt="员工花名册">
<figcaption>员工花名册:筛选、分页、档案、编辑、删除与批量导入导出入口集中展示。</figcaption>
</figure>
</section>
<section id="expense">
<h2><span class="no">04</span>职级报销标准(多个项目)</h2>
<p class="lead">每个职级可以配置多个报销项目。项目名称、标准金额、计量单位和适用说明分别保存,员工可在个人薪资页面查看。</p>
<ol class="steps">
<li>进入“组织架构 → 职级职等”。</li>
<li>在目标职级的行尾点击“报销标准”。</li>
<li>点击“添加报销项目”,例如市内交通、差旅住宿、通讯补贴。</li>
<li>填写标准金额和计量单位,例如 <b>1200 / 元/月</b>、<b>650 / 元/晚</b>。</li>
<li>点击“保存标准”。保存后,列表中的“报销项目”数量立即更新。</li>
</ol>
<div class="callout warning"><b>校验规则:</b>同一职级下的项目名称不能重复;金额不能为负数;只有拥有“职级编辑”权限的账号可以保存,拥有只读权限的角色可以查看。</div>
<figure>
<img src="assets/04-job-levels.png" alt="职级列表">
<figcaption>职级列表新增“报销项目”数量列,行尾提供独立配置入口。</figcaption>
</figure>
<figure>
<img src="assets/05-expense-standards.png" alt="职级多个报销项目配置">
<figcaption>报销标准抽屉:一个职级可维护任意多个项目,支持逐项删除和说明维护。</figcaption>
</figure>
</section>
<section id="payroll">
<h2><span class="no">05</span>薪资、福利与招聘</h2>
<h3>月度算薪</h3>
<ol class="steps">
<li>进入“薪资管理 → 月度算薪”,新建算薪批次并选择计薪期间。</li>
<li>核对名单,录入考勤或手工工资项后执行一键算薪。</li>
<li>完成内部审核,再执行发放和工资条发布。</li>
<li>员工登录后在“工资 / 我的工资条”查看已发布数据。</li>
</ol>
<figure>
<img src="assets/06-payroll.png" alt="月度算薪">
<figcaption>薪资批次从草稿、计算、审核、发放到工资条发布形成闭环。</figcaption>
</figure>
<h3>福利与参保</h3>
<p>参保方案、参保登记、福利项目、福利发放和假期管理都在“福利保险”模块。员工 H5 可查看五险一金、年度福利和假期余额。</p>
<figure>
<img src="assets/07-benefits.png" alt="福利保险">
<figcaption>福利保险模块按角色授权;普通员工只读自己的参保与福利数据。</figcaption>
</figure>
<h3>招聘管理</h3>
<p>从招聘职位、候选人库、招聘看板到 Offer 与入职,系统保留阶段流转和审批链;Offer 转档案时会继承部门、职位、职级与月薪。</p>
</section>
<section id="roles">
<h2><span class="no">06</span>角色、菜单与数据范围</h2>
<p class="lead">系统以角色权限与数据范围共同控制页面和接口。菜单可见不代表可以越权读取其他部门或员工的数据。</p>
<div class="grid-3">
<div class="tile"><b>all</b><p>集团全局数据,适用于超级管理员及明确授权的 HR 负责人。</p></div>
<div class="tile"><b>dept_tree / dept</b><p>只可查看本部门或本部门及下级员工,适用于主管和专员。</p></div>
<div class="tile"><b>self</b><p>只能查看本人的工资条、假期、合同和档案,普通员工账号默认使用该范围。</p></div>
</div>
<figure>
<img src="assets/08-roles.png" alt="角色权限">
<figcaption>角色权限页:权限点、数据范围和用户分配统一维护。</figcaption>
</figure>
</section>
<section id="self-web">
<h2><span class="no">07</span>员工 Web 自助(与 H5 菜单一致)</h2>
<p class="lead">普通员工在桌面浏览器登录后,左侧菜单固定为“首页、请假、工资、福利、我的”,与 H5 底部导航完全一致。</p>
<div class="grid-2">
<div class="tile"><b>功能同源</b><p>Web 与 H5 复用同一套业务组件和接口,避免两端菜单、字段和校验规则不一致。</p></div>
<div class="tile"><b>管理角色不受影响</b><p>HR、主管等管理账号仍按授权显示管理模块;自己的员工自助菜单保持可访问。</p></div>
</div>
<figure>
<img src="assets/09-web-self-home.png" alt="员工 Web 自助首页">
<figcaption>普通员工 Web 首页:顶部为个人指标,左侧菜单与 H5 五个主菜单同名同序。</figcaption>
</figure>
<figure>
<img src="assets/10-web-self-profile.png" alt="员工 Web 我的">
<figcaption>“我的”页面展示个人基础信息、合同、证明、消息与资料变更申请。</figcaption>
</figure>
</section>
<section id="profile-audit">
<h2><span class="no">08</span>个人档案修改审核</h2>
<p class="lead">员工修改个人档案必须经过审核。提交后不会立即写回员工档案,只有 HR 通过后才会生效。</p>
<ol class="steps">
<li>员工进入“我的 → 我的信息”,点击“修改资料”。</li>
<li>修改手机号、邮箱、住址、紧急联系人、籍贯或婚姻状况等允许自助维护的字段。</li>
<li>填写变更原因,点击“提交审核”。</li>
<li>在“变更申请”中查看待审核、已通过、已驳回状态;待审核状态可以撤回。</li>
<li>HR 在“人事档案 → 人事异动 → 资料变更”或 H5 审批中心审核。</li>
<li>审批通过后,系统按“审核前 → 审核后”写回档案,并向申请人发送结果通知。</li>
</ol>
<div class="callout"><b>安全规则:</b>旧版“直接保存”按钮已移除;旧版 PATCH 接口也只生成审批单,不能绕过审核写档案。工号、姓名、身份证、部门、职位、职级、状态和入职日期不允许员工自助修改。</div>
<figure>
<img src="assets/11-profile-audit.png" alt="个人档案提交审核">
<figcaption>员工编辑界面仅保留“提交审核”,页面明确提示审核通过后才会写入档案。</figcaption>
</figure>
</section>
<section id="self-h5">
<h2><span class="no">09</span>员工 H5 自助</h2>
<p class="lead">手机浏览器自动进入 H5。底部导航为“首页、请假、工资、福利、我的”,适合随时查看工资、提交申请和完成审批。</p>
<div class="shot-pair">
<figure class="phone">
<img src="assets/12-h5-home.png" alt="H5 首页">
<figcaption>H5 首页:最新工资、假期额度、快捷入口与合同提醒。</figcaption>
</figure>
<figure class="phone">
<img src="assets/13-h5-profile.png" alt="H5 我的">
<figcaption>H5 我的:个人档案、合同与薪资、证明申请和消息通知。</figcaption>
</figure>
</div>
<h3>常用操作</h3>
<div class="grid-3">
<div class="tile"><b>请假</b><p>选择假期类型、日期和时段,填写事由;需要证明的假种必须上传附件。</p></div>
<div class="tile"><b>工资条</b><p>按年度和季度筛选,展开查看收入、扣款、个税和五险一金明细。</p></div>
<div class="tile"><b>证明申请</b><p>选择在职、收入、离职等证明类型并填写用途,提交后跟踪办理状态。</p></div>
</div>
</section>
<section id="approval">
<h2><span class="no">10</span>审批中心</h2>
<p class="lead">有审批权限的账号会看到自己数据范围内的待办。普通员工只能查看自己的申请进度,不能审批自己的申请。</p>
<ol class="steps">
<li>打开 H5“审批中心”,或在 Web 端进入“人事档案 → 人事异动”。</li>
<li>按待审批、已通过、已驳回筛选,并按请假、异动、调薪、资料变更分类。</li>
<li>核对申请人、变更内容和原因,填写意见后通过或驳回。</li>
<li>审批结果会同步到员工端和首页待办计数。</li>
</ol>
<figure class="phone">
<img src="assets/14-approvals.png" alt="H5 审批中心">
<figcaption>H5 审批中心:分类与计数同源,资料变更展示员工提交的字段与内容。</figcaption>
</figure>
</section>
<section id="test">
<h2><span class="no">11</span>全功能验收清单</h2>
<p class="lead">建议上线前按下表完成一次全链路回归;本次交付已按同一范围执行自动化测试与真实浏览器验收。</p>
<table>
<thead>
<tr><th>验收项</th><th>检查内容</th><th>预期结果</th><th>状态</th></tr>
</thead>
<tbody>
<tr><td>设备识别</td><td>桌面、手机浏览器分别登录</td><td>桌面进入 Web,手机进入 H5</td><td><span class="pill">通过</span></td></tr>
<tr><td>菜单一致性</td><td>普通员工 Web 与 H5 菜单名称、顺序、权限</td><td>均为首页、请假、工资、福利、我的</td><td><span class="pill">通过</span></td></tr>
<tr><td>职级报销</td><td>新增、修改、删除多个报销项目</td><td>保存成功并正确回显数量和明细</td><td><span class="pill">通过</span></td></tr>
<tr><td>标准校验</td><td>重复项目、负数金额、只读权限保存</td><td>分别返回校验失败或 403</td><td><span class="pill">通过</span></td></tr>
<tr><td>档案审核</td><td>员工提交 → 审核前查档案 → HR 通过</td><td>审核前不变,通过后才写入新值</td><td><span class="pill">通过</span></td></tr>
<tr><td>绕过防护</td><td>调用旧 PATCH 入口直接改档案</td><td>仅生成待审申请,不回写档案</td><td><span class="pill">通过</span></td></tr>
<tr><td>权限边界</td><td>不同角色访问菜单和接口</td><td>权限与数据范围一致,无越权</td><td><span class="pill">通过</span></td></tr>
<tr><td>核心业务</td><td>入职、合同、参保、算薪、请假、福利、招聘</td><td>主流程可完整闭环</td><td><span class="pill">通过</span></td></tr>
<tr><td>数据隐私</td><td>员工访问他人工资条/档案</td><td>返回 403 或 404</td><td><span class="pill">通过</span></td></tr>
<tr><td>帮助中心</td><td>Web 顶栏、用户菜单、H5 我的</td><td>均可打开本手册</td><td><span class="pill">通过</span></td></tr>
</tbody>
</table>
</section>
<section id="faq" class="faq">
<h2><span class="no">12</span>常见问题</h2>
<details open>
<summary>为什么员工登录后进入了 H5?</summary>
<p>系统检测到手机浏览器 UA,或“窄视口 + 粗指针”的移动设备特征。桌面浏览器会自动进入 Web 工作台。</p>
</details>
<details>
<summary>为什么左侧没有某个管理菜单?</summary>
<p>菜单由角色权限实时计算。请让管理员在“系统管理 → 角色权限”中检查权限点与数据范围。</p>
</details>
<details>
<summary>修改资料后为什么还没生效?</summary>
<p>这是正常的审核机制。到“变更申请”查看状态;只有 HR 审核通过后才会写回个人档案。</p>
</details>
<details>
<summary>职级报销标准为什么保存失败?</summary>
<p>检查项目名称是否重复、金额是否为非负数,以及当前账号是否具有“职级编辑”权限。</p>
</details>
<details>
<summary>为什么审批中心只看到部分员工?</summary>
<p>审批列表按当前账号的数据范围裁剪。部门主管只能审批本部门及下级员工;集团 HR 可按全部范围审批。</p>
</details>
</section>
<footer>UNIS HRMS · 全功能使用手册 · 2026-10-20</footer>
</main>
</div>
</body>
</html>

View File

@ -3,10 +3,12 @@ import { lazy } from 'react'
import { Navigate, Route, Routes, useLocation, useNavigate } from 'react-router-dom'
import AdminLayout from './layouts/AdminLayout'
import MobileLayout from './layouts/MobileLayout'
import { entryPath } from './lib/mode'
import { useAuth } from './store/auth'
import Login from './pages/Login'
const Dashboard = lazy(() => import('./pages/Dashboard'))
const AccountSettings = lazy(() => import('./pages/account/Settings'))
const Help = lazy(() => import('./pages/Help'))
const EmployeeList = lazy(() => import('./pages/employees/EmployeeList'))
const EmployeeDetail = lazy(() => import('./pages/employees/EmployeeDetail'))
@ -51,51 +53,15 @@ const MLeave = lazy(() => import('./pages/mobile/MLeave'))
const MPayslips = lazy(() => import('./pages/mobile/MPayslips'))
const MBenefits = lazy(() => import('./pages/mobile/MBenefits'))
const MProfile = lazy(() => import('./pages/mobile/MProfile'))
const MTasks = lazy(() => import('./pages/mobile/MTasks'))
// 员工自助 · Web 工作台版页面(与 /m/* 的 H5 页面一一对应,见 src/self/manifest.ts)
const SelfLeave = lazy(() => import('./pages/self/Leave'))
const SelfPayslips = lazy(() => import('./pages/self/Payslips'))
const SelfBenefits = lazy(() => import('./pages/self/Benefits'))
const SelfApprovals = lazy(() => import('./pages/self/Approvals'))
const SelfTasks = lazy(() => import('./pages/self/Tasks'))
const SelfProfile = lazy(() => import('./pages/self/Profile'))
function RequireAuth({ children }: { children: React.ReactNode }) {
const token = useAuth((s) => s.token)
@ -104,6 +70,15 @@ function RequireAuth({ children }: { children: React.ReactNode }) {
return <>{children}</>
}
/**
* 根路径落地页:登录前收藏的 `/`、退出后又回到 `/` 的都走这里。
* 口径与登录成功完全一致(显式偏好 > 设备判断),避免出现「登录进 Web、
* 刷新一下又被丢进 H5」这种两条判定路径不一致的问题。
*/
function RootRedirect() {
return <Navigate to={entryPath()} replace />
}
function NotFound() {
const nav = useNavigate()
return (
@ -129,8 +104,21 @@ export default function App() {
</RequireAuth>
}
>
<Route index element={<Navigate to="/dashboard" replace />} />
<Route index element={<RootRedirect />} />
<Route path="dashboard" element={<Dashboard />} />
<Route path="help" element={<Help />} />
{/*
员工自助:Web 工作台版。路由与 H5 的 /m/* 一一对应(见 src/self/manifest.ts),
两侧读同一批 /self/* 接口、同一份 queryKey,模块名称/顺序/权限完全一致。
不再用 WebSelfFrame 把 H5 页面塞进手机框里 —— 那是「Web 和 H5 不一致」的根源。
*/}
<Route path="self" element={<Navigate to="/self/leave" replace />} />
<Route path="self/leave" element={<SelfLeave />} />
<Route path="self/payslips" element={<SelfPayslips />} />
<Route path="self/benefits" element={<SelfBenefits />} />
<Route path="self/approvals" element={<SelfApprovals />} />
<Route path="self/tasks" element={<SelfTasks />} />
<Route path="self/profile" element={<SelfProfile />} />
{/* 个人设置:不属于业务菜单,入口在侧栏底部用户胶囊,任何人可访问 */}
<Route path="account" element={<AccountSettings />} />
@ -188,6 +176,7 @@ export default function App() {
<Route path="payslips" element={<MPayslips />} />
<Route path="benefits" element={<MBenefits />} />
<Route path="approvals" element={<MApprovals />} />
<Route path="tasks" element={<MTasks />} />
<Route path="profile" element={<MProfile />} />
</Route>

View File

@ -217,6 +217,39 @@ export const documentDef: ResourceDef = {
],
}
export const profileRequestDef: ResourceDef = {
key: 'profile-request',
path: '/employee-profile-requests',
label: '资料变更申请',
perm: 'employee:change',
readonly: true,
noSearch: true,
create: false,
update: false,
remove: false,
orderBy: 'id',
order: 'desc',
filters: [
col('status', '审批状态', { type: 'tag', options: [
{ label: '待审核', value: 'pending' },
{ label: '已通过', value: 'approved' },
{ label: '已驳回', value: 'rejected' },
] }),
col('employee_id', '员工', { type: 'options', source: '/employees/options', filterOn: 'employee_name' }),
],
columns: [
col('employee_name', '员工', { width: 110 }),
col('department_name', '部门', { width: 140 }),
col('changes', '变更内容(审核前 → 审核后)', { type: 'json', width: 320 }),
col('reason', '变更原因', { width: 200 }),
col('status', '状态', { type: 'tag', width: 100, options: APPROVAL_STATUS_OPTIONS }),
col('approver_name', '审核人', { width: 100 }),
col('comment', '审核意见', { width: 180 }),
col('created_at', '提交时间', { type: 'datetime', width: 160 }),
col('approved_at', '审核时间', { type: 'datetime', width: 160 }),
],
}
export const adjustmentDef: ResourceDef = {
key: 'adjustment',
path: '/salary-adjustments',
@ -322,6 +355,10 @@ export const jobLevelDef: ResourceDef = {
col('name', '职级', { width: 160, required: true }),
col('code', '编码', { width: 140 }),
col('grade', '职等', { type: 'number', width: 100 }),
col('expense_standard_count', '报销项目', {
width: 110,
render: (v: number) => `${v ?? 0} 项`,
}),
col('sort', '排序', { type: 'number', width: 90 }),
col('is_active', '启用', { type: 'switch', width: 90 }),
col('remark', '备注', { width: 240 }),

View File

@ -20,6 +20,12 @@ export const ROUTE_PERMS: Record<string, string[]> = {
'/employees/documents': ['employee:document:read'], // 证明开具
'/org/departments': ['org:department:read'], // 部门结构
'/org/job-levels': ['org:joblevel:read'], // 职级职等
'/self/leave': ['selfservice:leave:read'], // 员工自助
'/self/payslips': ['selfservice:payslip:read'],
'/self/benefits': ['selfservice:benefit:read'],
'/self/profile': ['selfservice:profile:read'],
'/self/approvals': ['selfservice:approval:read'],
'/self/tasks': ['selfservice:task:read'],
'/org/positions': ['org:position:read'], // 职位管理
'/payroll/batches': ['payroll:batch:read'], // 月度算薪
'/payroll/items': ['payroll:item:read'], // 薪资项目

255
web/src/api/self.ts 100644
View File

@ -0,0 +1,255 @@
/**
* 员工自助数据层 —— Web 工作台与 H5 自助端共用同一套端点、queryKey 与 hooks。
*
* 为什么单独一层:
* 两端读取的是完全相同的 13 个 `/self/*` 接口。以前 H5 页面里各写各的 queryKey,
* Web 首页又另起一个 `['self','home']`,结果「H5 提交请假 → Web 首页还显示旧额度」,
* 或者反过来。键统一之后两个外壳共享同一份缓存,任何一端写完两端同时刷新。
*
* 注意:queryKey 与历史 H5 页面保持逐字一致(`['self-home']` 等),
* 改动这里必须同时改 `invalidateQueries` 的调用方。
*/
import { useMutation, useQuery, useQueryClient, type QueryClient } from '@tanstack/react-query'
import { del, get, getQuiet, post, upload } from './http'
/** 自助接口路径表:页面里不再出现裸字符串,避免拼错与两端漂移 */
export const SELF = {
home: '/self/home',
profile: '/self/profile',
profileRequests: '/self/profile-requests',
payslips: '/self/payslips',
salaryStandard: '/self/salary-standard',
insurance: '/self/insurance',
benefits: '/self/benefits',
leaveOptions: '/self/leave/options',
leave: '/self/leave',
documents: '/self/documents',
tasks: '/self/tasks',
notifications: '/self/notifications',
announcements: '/self/announcements',
approvals: '/self/approvals',
docDict: '/common/dict/doc_type',
} as const
export const SELF_KEYS = {
home: ['self-home'],
profile: ['self-profile'],
payslips: (year: number) => ['self-payslips', year],
payslip: (id: number) => ['self-payslip', id],
salaryStandard: ['self-salary-standard'],
insurance: ['self-insurance'],
benefits: ['self-benefits'],
leaveOptions: ['self-leave-options'],
leave: (status = '') => ['self-leave', status],
documents: ['self-documents'],
tasks: ['self-tasks'],
notifications: ['self-notifications'],
announcements: ['self-announcements'],
approvals: (status = 'pending', type = '') => ['self-approvals', status, type],
docDict: ['dict', 'doc_type'],
} as const
/** 个人数据变化不频繁,30s 内复用,避免来回切页时反复打接口 */
const STALE = 30_000
/* ------------------------------------------------------------------ 查询 -- */
export const useSelfHome = () =>
useQuery({ queryKey: SELF_KEYS.home, queryFn: () => get<any>(SELF.home), staleTime: STALE })
export const useSelfProfile = () =>
useQuery({ queryKey: SELF_KEYS.profile, queryFn: () => get<any>(SELF.profile), staleTime: STALE })
export const useSelfLeaveOptions = () =>
useQuery({ queryKey: SELF_KEYS.leaveOptions, queryFn: () => get<any[]>(SELF.leaveOptions), staleTime: STALE })
export const useSelfLeave = (status = '') =>
useQuery({
queryKey: SELF_KEYS.leave(status),
queryFn: () => get<any>(SELF.leave, { status: status || undefined, page: 1, page_size: 50 }),
staleTime: STALE,
})
export const useSelfPayslips = (year: number) =>
useQuery({ queryKey: SELF_KEYS.payslips(year), queryFn: () => get<any>(SELF.payslips, { year }), staleTime: STALE })
export const useSelfPayslip = (id: number | null, enabled = true) =>
useQuery({
queryKey: SELF_KEYS.payslip(id ?? 0),
queryFn: () => get<any>(`${SELF.payslips}/${id}`),
enabled: enabled && id != null,
staleTime: STALE,
})
export const useSelfSalaryStandard = () =>
useQuery({ queryKey: SELF_KEYS.salaryStandard, queryFn: () => get<any>(SELF.salaryStandard), staleTime: STALE })
export const useSelfInsurance = () =>
useQuery({ queryKey: SELF_KEYS.insurance, queryFn: () => get<any>(SELF.insurance), staleTime: STALE })
export const useSelfBenefits = () =>
useQuery({ queryKey: SELF_KEYS.benefits, queryFn: () => get<any>(SELF.benefits), staleTime: STALE })
export const useSelfDocuments = () =>
useQuery({ queryKey: SELF_KEYS.documents, queryFn: () => get<any[]>(SELF.documents), staleTime: STALE })
export const useSelfTasks = () =>
useQuery({ queryKey: SELF_KEYS.tasks, queryFn: () => get<any[]>(SELF.tasks), staleTime: STALE })
export const useSelfNotifications = (pageSize = 50) =>
useQuery({
queryKey: SELF_KEYS.notifications,
queryFn: () => get<any>(SELF.notifications, { page: 1, page_size: pageSize }),
staleTime: STALE,
})
export const useSelfAnnouncements = () =>
useQuery({ queryKey: SELF_KEYS.announcements, queryFn: () => get<any[]>(SELF.announcements), staleTime: STALE })
export const useSelfApprovals = (status = 'pending', type = '') =>
useQuery({
queryKey: SELF_KEYS.approvals(status, type),
queryFn: () => get<any>(SELF.approvals, { status, type: type || undefined, limit: 100 }),
staleTime: STALE,
})
export const useDocTypeDict = () =>
useQuery({ queryKey: SELF_KEYS.docDict, queryFn: () => get<any[]>(SELF.docDict), staleTime: 5 * 60_000 })
/* ------------------------------------------------------------------ 变更 -- */
/** 请假提交 / 撤销后需要一起失效的查询(额度、记录、首页三处都要新) */
export function invalidateSelf(qc: QueryClient, scope: 'leave' | 'profile' | 'task' | 'approval' | 'doc' | 'all' = 'all') {
const hit = (keys: readonly any[]) => qc.invalidateQueries({ queryKey: keys as any[] })
hit(SELF_KEYS.home)
if (scope === 'leave' || scope === 'all') {
qc.invalidateQueries({ queryKey: ['self-leave'] })
hit(SELF_KEYS.leaveOptions)
}
if (scope === 'profile' || scope === 'all') {
hit(SELF_KEYS.profile)
hit(SELF_KEYS.salaryStandard)
}
if (scope === 'approval' || scope === 'all') qc.invalidateQueries({ queryKey: ['self-approvals'] })
if (scope === 'task' || scope === 'all') {
hit(SELF_KEYS.tasks)
hit(SELF_KEYS.notifications)
}
if (scope === 'doc' || scope === 'all') hit(SELF_KEYS.documents)
}
/** 提交请假申请 */
export function useLeaveApply(onDone?: () => void) {
const qc = useQueryClient()
return useMutation({
mutationFn: (payload: {
leave_type_id: number
start_date: string
end_date: string
period: string
reason: string
days: number
attachment_id?: number
}) => post(SELF.leave, payload),
onSuccess: () => {
invalidateSelf(qc, 'leave')
onDone?.()
},
})
}
export const useLeaveCancel = () => {
const qc = useQueryClient()
return useMutation({
mutationFn: (id: number) => del(`${SELF.leave}/${id}`),
onSuccess: () => invalidateSelf(qc, 'leave'),
})
}
export const useUploadLeaveCertificate = () =>
useMutation({
mutationFn: (file: File) =>
upload<{ id: number; name: string }>('/common/upload', file, { biz_type: 'leave_certificate' }),
})
export const useProfileRequest = (onDone?: () => void) => {
const qc = useQueryClient()
return useMutation({
mutationFn: (payload: { changes: Record<string, string>; reason?: string }) =>
post(SELF.profileRequests, payload),
onSuccess: () => {
invalidateSelf(qc, 'profile')
onDone?.()
},
})
}
export const useProfileRequestCancel = (onDone?: () => void) => {
const qc = useQueryClient()
return useMutation({
mutationFn: (id: number) => del(`${SELF.profileRequests}/${id}`),
onSuccess: () => {
invalidateSelf(qc, 'profile')
onDone?.()
},
})
}
export const useDocumentApply = (onDone?: () => void) => {
const qc = useQueryClient()
return useMutation({
mutationFn: (payload: { doc_type: string; purpose?: string }) => post(SELF.documents, payload),
onSuccess: () => {
qc.invalidateQueries({ queryKey: SELF_KEYS.documents })
qc.invalidateQueries({ queryKey: SELF_KEYS.home })
onDone?.()
},
})
}
export const useTaskDone = () => {
const qc = useQueryClient()
return useMutation({
mutationFn: (id: number) => post(`${SELF.tasks}/${id}/done`),
onSuccess: () => invalidateSelf(qc, 'task'),
})
}
export const useNotificationsRead = () => {
const qc = useQueryClient()
return useMutation({
mutationFn: (ids?: number[]) => post(SELF.notifications + '/read', { ids: ids ?? [] }),
onSuccess: () => {
qc.invalidateQueries({ queryKey: SELF_KEYS.notifications })
qc.invalidateQueries({ queryKey: SELF_KEYS.home })
qc.invalidateQueries({ queryKey: ['unread-count'] })
},
})
}
export interface DecidePayload {
type: string
id: number
status: 'approved' | 'rejected'
comment?: string
}
export const useApprovalDecide = () => {
const qc = useQueryClient()
return useMutation({
mutationFn: (v: DecidePayload) =>
post(`${SELF.approvals}/${v.type}/${v.id}/decide`, { status: v.status, comment: v.comment || undefined }),
onSuccess: () => invalidateSelf(qc, 'approval'),
})
}
/** 顶部铃铛用的静默版:拿不到消息时不弹错误提示 */
export const useQuietNotifications = (pageSize = 8) =>
useQuery({
queryKey: ['my-notices'],
queryFn: async () => {
try {
return await getQuiet<any>(SELF.notifications, { page: 1, page_size: pageSize })
} catch {
return { items: [] as any[] }
}
},
})

View File

@ -34,6 +34,11 @@ function parseMaybeJson(value: any) {
const kvText = (key: string, v: any) => {
if (typeof v === 'boolean') return v ? '是' : '否'
if (v != null && typeof v === 'object' && "after" in v) {
const before = v.before == null || v.before === "" ? "未填写" : String(v.before)
const after = v.after == null || v.after === "" ? "未填写" : String(v.after)
return `${before} → ${after}`
}
if (v != null && typeof v === 'object') return JSON.stringify(v)
// 异动快照里的 status 一定是「在职状态」,快照即历史,不能直出英文码
if (key === 'status') return optLabel(EMP_STATUS_OPTIONS, v)

View File

@ -2,6 +2,7 @@ import {
AccountBookOutlined,
ApartmentOutlined,
AppstoreOutlined,
AuditOutlined,
BarChartOutlined,
BookOutlined,
CalculatorOutlined,
@ -56,6 +57,7 @@ export type IconComp = ComponentType<{ style?: React.CSSProperties; className?:
*/
const REGISTRY: Record<string, IconComp> = {
AccountBookOutlined,
AuditOutlined,
ApartmentOutlined,
AppstoreOutlined,
BarChartOutlined,
@ -117,10 +119,16 @@ export function IconNode({ name, style }: { name?: string | null; style?: React.
}
/** H5 底部导航用的是关键词而非 antd 图标名 */
/**
* H5 底部导航图标表。key 取自 `src/self/manifest.ts` 的 `mobileIcon` 字段,
* 后端 MOBILE_MENU_TREE 的 icon 列同名 —— 新增自助模块时三处一起加。
*/
export const MOBILE_ICONS: Record<string, IconComp> = {
home: HomeOutlined,
calendar: CalendarOutlined,
gold: AccountBookOutlined,
gift: GiftOutlined,
check: AuditOutlined,
task: ScheduleOutlined,
user: UserOutlined,
}

View File

@ -4,10 +4,12 @@ import {
MenuFoldOutlined,
MenuUnfoldOutlined,
MobileOutlined,
QuestionCircleOutlined,
ReloadOutlined,
SearchOutlined,
SettingOutlined,
UpOutlined,
UserOutlined,
} from '@ant-design/icons'
import { useQuery } from '@tanstack/react-query'
import {
@ -35,6 +37,8 @@ import { PageFallback } from '../components/PageFallback'
import { get, getQuiet, post } from '../api/http'
import { requiredPermsOf } from '../api/routePerms'
import { IconNode, icon } from '../components/icons'
import { oppositePath, setModePref } from '../lib/mode'
import { moduleOfPath, pathOf, toWebPath } from '../self/manifest'
import { useAuth } from '../store/auth'
const { Sider, Header, Content } = Layout
@ -48,10 +52,19 @@ const isNarrow = () => window.innerWidth < 992
// 后台路由的一级前缀。用来区分「路径本身不存在」(交给路由 404)
// 与「路径存在但当前角色没有菜单权限」(渲染 403)。
// /account(个人设置)刻意不列在这里:它由侧栏用户胶囊进入,不需要菜单权限。
const KNOWN_PREFIXES = ['/dashboard', '/employees', '/recruitment', '/payroll', '/benefits', '/org', '/system']
const KNOWN_PREFIXES = [
'/dashboard',
'/self',
'/employees',
'/recruitment',
'/payroll',
'/benefits',
'/org',
'/system',
]
// 不在后端菜单里的页面(个人设置):面包屑拿不到菜单名,这里补一份标题
const OFF_MENU_TITLES: Record<string, string> = { '/account': '个人设置' }
const OFF_MENU_TITLES: Record<string, string> = { '/account': '个人设置', '/help': '使用手册' }
interface FlatItem {
key: string
@ -82,6 +95,7 @@ export default function AdminLayout() {
const me = useAuth((s) => s.me)
const logout = useAuth((s) => s.logout)
const reload = useAuth((s) => s.reload)
const hasPerm = useAuth((s) => s.hasPerm)
const [collapsed, setCollapsed] = useState(() => isNarrow() || localStorage.getItem(COLLAPSE_KEY) === '1')
const prefCollapsed = useRef(localStorage.getItem(COLLAPSE_KEY) === '1')
const seenMobile = useRef<boolean | null>(null)
@ -144,18 +158,25 @@ export default function AdminLayout() {
// 菜单由后端按角色权限下发,是「能打开哪个页面」的唯一口径。
// 直接敲地址 / 收藏旧链接时也要挡住,否则会出现空表格 + 一点就 403 的按钮。
//
// 例外:员工自助的 7 个模块按「权限」判定而不是按菜单。原因是 H5 底部导航只放得下
// 5 项,审批 / 待办 两端都只能从首页宫格进入,因此它们不在任何一份菜单树里;
// 若继续按菜单判定,这两个页面在 Web 端会莫名其妙 403,两端行为就不一致了。
const selfModule = useMemo(() => moduleOfPath(loc.pathname), [loc.pathname])
const allowed = useMemo(() => {
const p = loc.pathname
if (selfModule) return hasPerm(selfModule.perm)
if (!KNOWN_PREFIXES.some((k) => p === k || p.startsWith(k + '/'))) return true
return items.some((i) => p === i.key || p.startsWith(i.key + '/'))
}, [items, loc.pathname])
}, [items, loc.pathname, selfModule, hasPerm])
// 403 页要把「缺哪个权限码」讲清楚,省掉一轮截图来回
const needPerms = useMemo(() => (allowed ? [] : requiredPermsOf(loc.pathname)), [allowed, loc.pathname])
const matched = items.filter((i) => i.key.includes(loc.pathname) || loc.pathname.startsWith(i.key))
const current = [...matched].sort((a, b) => b.key.length - a.key.length)[0]
const crumb = current?.label || OFF_MENU_TITLES[loc.pathname]
// 审批 / 待办 不在后端菜单里,面包屑从 manifest 取模块名,保证与页面标题一致
const crumb = current?.label || OFF_MENU_TITLES[loc.pathname] || selfModule?.name
// 胶囊两行:上行姓名、下行角色(多角色用「、」连接,没分配时给占位文案别留空行)。
// 超管这类「姓名和角色同名」的账号,下行换成登录账号,免得上下两行一模一样。
const userName = me?.user?.name || me?.user?.username || ''
@ -230,11 +251,15 @@ export default function AdminLayout() {
靠原生 title 补提示(没有 hover 展开的地方,光看图例得认得出) */
items: collapsed
? [
{ key: 'self', icon: <UserOutlined />, label: '', title: '我的自助', onClick: () => nav(pathOf('home', 'web')) },
{ key: 'settings', icon: <SettingOutlined />, label: '', title: '个人设置', onClick: () => nav('/account') },
{ key: 'help', icon: <QuestionCircleOutlined />, label: '', title: '使用手册', onClick: () => nav('/help') },
{ key: 'logout', icon: <LogoutOutlined />, label: '', title: '退出登录', danger: true, onClick: doLogout },
]
: [
{ key: 'self', icon: <UserOutlined />, label: '我的自助', onClick: () => nav(pathOf('home', 'web')) },
{ key: 'settings', icon: <SettingOutlined />, label: '个人设置', onClick: () => nav('/account') },
{ key: 'help', icon: <QuestionCircleOutlined />, label: '使用手册', onClick: () => nav('/help') },
{ key: 'logout', icon: <LogoutOutlined />, label: '退出登录', danger: true, onClick: doLogout },
],
}}
@ -277,6 +302,14 @@ export default function AdminLayout() {
</Space>
<Space size={6}>
<Tooltip title="使用手册">
<Button
type="text"
icon={<QuestionCircleOutlined />}
onClick={() => nav('/help')}
aria-label="打开使用手册"
/>
</Tooltip>
<Input
allowClear
value={kw}
@ -304,8 +337,16 @@ export default function AdminLayout() {
) : null
}
/>
<Tooltip title="移动端自助">
<Button type="text" icon={<MobileOutlined />} onClick={() => nav('/m')} />
<Tooltip title="切到 H5 自助端(记住选择,下次手机/电脑都按偏好进入)">
<Button
type="text"
icon={<MobileOutlined />}
onClick={() => {
setModePref('h5')
nav(oppositePath(loc.pathname, 'h5'))
}}
aria-label="切换到 H5 自助端"
/>
</Tooltip>
<Tooltip title="刷新数据">
<Button type="text" icon={<ReloadOutlined />} onClick={() => reload()} />
@ -319,7 +360,15 @@ export default function AdminLayout() {
<Spin spinning={notices.isFetching}>
{(notices.data?.items || []).length === 0 && <Text type="secondary">暂无消息</Text>}
{(notices.data?.items || []).map((n: any) => (
<div key={n.id} style={{ padding: '8px 0', borderBottom: '1px solid #f4f6fa' }}>
<div
key={n.id}
style={{
padding: '8px 0',
borderBottom: '1px solid #f4f6fa',
cursor: n.link ? 'pointer' : 'default',
}}
onClick={() => n.link && nav(toWebPath(n.link))}
>
<Space size={6}>
<Tag bordered={false} color="blue">
{n.category}
@ -332,8 +381,8 @@ export default function AdminLayout() {
</div>
))}
</Spin>
<Button type="link" block onClick={() => nav('/m')}>
前往员工自助查看
<Button type="link" block onClick={() => nav(pathOf('tasks', 'web'))}>
查看全部待办与消息
</Button>
</div>
}

View File

@ -0,0 +1,14 @@
/**
* 浏览器端设备判断的唯一口径。
*
* 先用 UA 覆盖手机/平板,再用「窄视口 + 粗指针」覆盖响应式桌面浏览器和设备模拟器。
* 不依赖登录角色:桌面浏览器进入管理端外壳,手机浏览器进入 H5 外壳。
*/
export function isMobileBrowser(): boolean {
if (typeof window === 'undefined') return false
const ua = navigator.userAgent || ''
const mobileUa = /Android|iPhone|iPad|iPod|Mobile|HarmonyOS|MicroMessenger/i.test(ua)
const narrow = window.matchMedia?.('(max-width: 768px)').matches ?? window.innerWidth <= 768
const coarse = window.matchMedia?.('(pointer: coarse)').matches ?? false
return mobileUa || (narrow && coarse)
}

View File

@ -0,0 +1,74 @@
/**
* 外壳模式(Web 工作台 / H5 自助端)判定的唯一口径。
*
* 规则,按优先级:
* 1. 用户显式选择过的外壳偏好(localStorage,跨登录态保留);
* 2. 没选过时才按设备判断:手机浏览器 → H5,其余(PC / 平板桌面)→ Web。
*
* 关键点:**账号不决定外壳**。普通员工在电脑浏览器登录就必须进 Web 工作台,
* 只有他主动点「切到 H5」或本身用手机浏览器时才是 H5。
* 以前 token 过期、`?redirect=/m`、浏览器记住上次页面都会把员工锁死在 H5,
* 现在这三条统一走 `sanitizeRedirect()` + 可切换的偏好,随时能回 Web。
*/
import { isMobileBrowser } from './device'
import { toMobilePath, toWebPath } from '../self/manifest'
export type ShellMode = 'web' | 'h5'
export type ModePref = 'auto' | ShellMode
const KEY = 'unis-hrms-shell-mode'
/** 用户显式偏好;`auto` 表示跟随设备 */
export function modePref(): ModePref {
if (typeof window === 'undefined') return 'auto'
const v = window.localStorage?.getItem(KEY)
return v === 'web' || v === 'h5' ? v : 'auto'
}
export function setModePref(pref: ModePref) {
if (typeof window === 'undefined') return
if (pref === 'auto') window.localStorage?.removeItem(KEY)
else window.localStorage?.setItem(KEY, pref)
}
/** 纯设备判断(不含用户偏好) */
export const detectMode = (): ShellMode => (isMobileBrowser() ? 'h5' : 'web')
/** 当前应使用的外壳 */
export function currentMode(): ShellMode {
const pref = modePref()
return pref === 'auto' ? detectMode() : pref
}
export const isWebMode = () => currentMode() === 'web'
/** 登录成功 / 根路径的落地页:桌面浏览器一律 Web,手机浏览器才 H5 */
export const entryPath = () => (currentMode() === 'h5' ? '/m' : '/dashboard')
/** 把路径改写成当前外壳下的等价路径 */
export const toModePath = (path: string, mode: ShellMode = currentMode()) =>
mode === 'h5' ? toMobilePath(path) : toWebPath(path)
/**
* 校验 `?redirect=` 参数:
* - 只接受站内绝对路径(挡掉 `//evil.com` 这种协议相对地址);
* - 落到与当前外壳不符的路径时,改写成同模块的另一端路径,
* 这样「在手机上过期重登后回 H5」「在电脑上过期重登后回 Web」都成立。
*/
export function sanitizeRedirect(raw: string | null | undefined, mode: ShellMode = currentMode()): string {
if (!raw) return entryPath()
let target = raw
try {
target = decodeURIComponent(raw)
} catch {
/* 已经是解码后的值 */
}
if (!target.startsWith('/') || target.startsWith('//') || target.startsWith('/\\')) return entryPath()
return toModePath(target, mode)
}
/**
* 切到另一个外壳时要落在哪个页面:
* 从 Web 的「我的工资条」切到 H5,应当落在 H5 的工资条,而不是永远回 H5 首页。
*/
export const oppositePath = (pathname: string, to: ShellMode) => toModePath(pathname, to)

View File

@ -0,0 +1,257 @@
import {
BENEFIT_CATEGORY_OPTIONS,
CONTRACT_STATUS_OPTIONS,
EMP_STATUS_OPTIONS,
ENROLLMENT_STATUS_OPTIONS,
} from '../api/defs'
/**
* 员工自助两端的公共字典与格式化小工具。
*
* Web 桌面页(pages/self)与 H5 页(pages/mobile)必须对同一个状态给出同一个中文与
* 同一种颜色,否则「已通过 / 已发放」在两个外壳里会长得不一样。
* 这里集中一份,`pages/mobile/_ui.tsx` 只做 re-export,避免历史 import 断链。
*/
/** 金额:¥1,234.00(与 H5 一致,Web 侧表格也用它保证两端字面一致) */
export const rmb = (v: any) =>
`¥${Number(v ?? 0).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
export const num = (v: any) => String(Number(v ?? 0))
/** 取日期部分(后端可能下发 ISO datetime) */
export const dstr = (v?: string | null) => (v ? String(v).slice(0, 10) : '-')
/** 取到分钟的时间 */
export const dtstr = (v?: string | null) =>
v ? String(v).slice(0, 16).replace('T', ' ') : '-'
export const round2 = (v: number) => Math.round(v * 100) / 100
/**
* 比例小数 -> 百分比中文:0.07 => 7%,0.095 => 9.5%。
* 两端必须共用,否则同一个缴存比例在 Web 表格里会露出浮点尾数(7.000000000000001%)。
*/
export const pct = (v: any) => `${round2(Number(v ?? 0) * 100)}%`
/** 请假状态:文案与 Web 端「假期管理」表头筛选项一致 */
export const LEAVE_STATUS: Record<string, { text: string; color: string }> = {
pending: { text: '审批中', color: '#f59e0b' },
approved: { text: '已通过', color: '#16a34a' },
rejected: { text: '已驳回', color: '#ef4444' },
cancelled: { text: '已撤销', color: '#98a2b3' },
}
export const LEAVE_STATUS_TEXT: Record<string, string> = Object.fromEntries(
Object.entries(LEAVE_STATUS).map(([k, v]) => [k, v.text]),
)
/** 请假时段:后端历史上有 am/pm 与 morning/afternoon 两套写法,全部兼容 */
export const PERIOD_TEXT: Record<string, string> = {
all: '全天',
full: '全天',
am: '上午',
morning: '上午',
pm: '下午',
afternoon: '下午',
}
/** 时段选项(表单与筛选用,两端同一份) */
export const PERIOD_OPTIONS = [
{ value: 'full', label: '全天' },
{ value: 'morning', label: '上午' },
{ value: 'afternoon', label: '下午' },
]
/** 请假状态筛选(首项固定「全部」,与 Web 表头筛选同一交互语义) */
export const LEAVE_FILTERS = [
{ key: '', label: '全部' },
{ key: 'pending', label: '审批中' },
{ key: 'approved', label: '已通过' },
{ key: 'rejected', label: '已驳回' },
{ key: 'cancelled', label: '已撤销' },
]
export const TASK_LEVEL: Record<string, { text: string; color: string }> = {
high: { text: '加急', color: '#ef4444' },
urgent: { text: '加急', color: '#ef4444' },
normal: { text: '常规', color: '#2f54eb' },
low: { text: '较低', color: '#98a2b3' },
}
/** 工资条状态:approved = 已核算待发放,语义上仍是「进行中」,颜色跟随 pending */
export const PAYSLIP_STATUS_TEXT: Record<string, string> = {
published: '已发放',
paid: '已发放',
approved: '待发放',
calculated: '计算中',
draft: '草稿',
}
export const PAYSLIP_STATUS_TONE: Record<string, string> = { approved: 'pending' }
/** 季度筛选(工资条只有「已发布」一种终态,按季度切分更有意义) */
export const QUARTERS: Array<{ key: string; label: string; months: number[] }> = [
{ key: '', label: '全年', months: [] },
{ key: '1', label: '一季度', months: [1, 2, 3] },
{ key: '2', label: '二季度', months: [4, 5, 6] },
{ key: '3', label: '三季度', months: [7, 8, 9] },
{ key: '4', label: '四季度', months: [10, 11, 12] },
]
/** 福利类别中文:直接取管理端 `api/defs` 的选项表,避免自助端自己翻译一遍 */
export const BENEFIT_CATEGORY_TEXT: Record<string, string> = Object.fromEntries(
BENEFIT_CATEGORY_OPTIONS.map((x) => [x.value, x.label]),
)
/** 福利发放记录状态 */
export const BENEFIT_RECORD_STATUS: Record<string, { text: string; color: string }> = {
pending: { text: '待发放', color: '#f59e0b' },
approved: { text: '已审批', color: '#2f54eb' },
paid: { text: '已到账', color: '#16a34a' },
void: { text: '已作废', color: '#98a2b3' },
}
export const BENEFIT_ICONS: Record<string, string> = {
meal: '🍱',
transport: '🚕',
telecom: '📱',
holiday: '🎁',
health: '🏥',
cash: '💵',
gift: '🎀',
}
/** 审批中心:申请类型元信息(图标 + 颜色 + 中文),两端共用 */
export const APPROVAL_TYPES = [
{ key: '', label: '全部' },
{ key: 'leave', label: '请假' },
{ key: 'change', label: '异动' },
{ key: 'adjustment', label: '调薪' },
{ key: 'profile', label: '资料变更' },
{ key: 'document', label: '证明' },
{ key: 'offer', label: 'Offer' },
]
export const APPROVAL_META: Record<string, { icon: string; color: string; text: string }> = {
leave: { icon: '🗓', color: '#2f54eb', text: '请假' },
change: { icon: '🔀', color: '#7c3aed', text: '异动' },
adjustment: { icon: '📈', color: '#16a34a', text: '调薪' },
profile: { icon: '📝', color: '#0ea5e9', text: '资料' },
document: { icon: '📄', color: '#f59e0b', text: '证明' },
offer: { icon: '🎯', color: '#ec4899', text: 'Offer' },
}
export const APPROVAL_STATUS: Record<string, { text: string; color: string }> = {
pending: { text: '待审批', color: '#f59e0b' },
approved: { text: '已通过', color: '#16a34a' },
sent: { text: '已发送', color: '#2f54eb' },
accepted: { text: '已接受', color: '#16a34a' },
rejected: { text: '已驳回', color: '#ef4444' },
}
/** 资料变更申请状态 */
export const PROFILE_REQ_STATUS: Record<string, { text: string; color: string }> = {
pending: { text: '待 HR 审核', color: '#f59e0b' },
approved: { text: '已通过', color: '#16a34a' },
rejected: { text: '已驳回', color: '#ef4444' },
cancelled: { text: '已撤回', color: '#98a2b3' },
}
/** 允许员工自助发起变更的字段中文名 */
export const PROFILE_FIELD_LABELS: Record<string, string> = {
phone: '手机号',
email: '邮箱',
address: '住址',
emergency_contact: '紧急联系人',
emergency_phone: '紧急联系电话',
native_place: '籍贯',
marital_status: '婚姻状况',
avatar: '头像',
remark: '备注',
}
/** 薪资项目编码 → 中文(后端下发 code,展示要有名字) */
export const SALARY_ITEM_LABELS: Record<string, string> = {
base_salary: '基本工资',
perf_salary: '绩效工资',
post_salary: '岗位工资',
year_bonus: '年终奖',
overtime_pay: '加班费',
meal_allowance: '餐补',
transport_allowance: '交通补贴',
telecom_allowance: '通讯补贴',
housing_allowance: '住房补贴',
other_allowance: '其他补贴',
absence_deduction: '缺勤扣款',
other_deduction: '其他扣款',
}
/** 在职状态文案:取自后台同一份 EMP_STATUS_OPTIONS,两端与员工管理列表口径一致 */
export const EMP_STATUS_TEXT: Record<string, string> = {
...Object.fromEntries(EMP_STATUS_OPTIONS.map((o) => [o.value, o.label])),
terminated: '已辞退',
}
export const EMP_STATUS_COLOR: Record<string, string> = {
active: '#16a34a',
probation: '#f59e0b',
leave: '#98a2b3',
resigned: '#98a2b3',
terminated: '#ef4444',
}
/**
* 劳动合同状态中文直接取自 `api/defs` 的 CONTRACT_STATUS_OPTIONS —— 与后台「合同管理」
* 表头同一份字典,避免自助端漏掉 renewed 这类取值而直接显示英文。
* pending 是自助端独有的「待签署」语义,后台选项里没有,单独补上。
*/
export const CONTRACT_STATUS_TEXT: Record<string, string> = {
...Object.fromEntries(CONTRACT_STATUS_OPTIONS.map((o) => [o.value, o.label])),
pending: '待签署',
}
export const CONTRACT_STATUS_COLOR: Record<string, string> = {
active: '#16a34a',
expired: '#ef4444',
renewed: '#2f54eb',
terminated: '#98a2b3',
pending: '#f59e0b',
}
/** 证明开具状态 */
export const DOC_STATUS_TEXT: Record<string, string> = {
pending: '办理中',
approved: '已开具',
rejected: '已驳回',
cancelled: '已撤销',
}
export const DOC_STATUS_COLOR: Record<string, string> = {
pending: '#f59e0b',
approved: '#16a34a',
rejected: '#ef4444',
cancelled: '#98a2b3',
}
/** 参保状态:中文取自 ENROLLMENT_STATUS_OPTIONS;pending 是自助端独有的「待生效」 */
export const INSURANCE_STATUS_TEXT: Record<string, string> = {
...Object.fromEntries(ENROLLMENT_STATUS_OPTIONS.map((o) => [o.value, o.label])),
paused: '已停缴',
pending: '待生效',
}
export const INSURANCE_STATUS_COLOR: Record<string, string> = {
active: '#16a34a',
paused: '#f59e0b',
pending: '#f59e0b',
stopped: '#98a2b3',
}
/** 假期天数计算:同一天选半天记 0.5,跨度按自然日 +1(与 H5 完全同一算法) */
export function leaveDays(start: string, end: string, period: string): number {
const a = new Date(start).getTime()
const b = new Date(end).getTime()
if (!a || !b || b < a) return 0
let d = Math.round((b - a) / 86400000) + 1
if (start === end && period !== 'full') d = 0.5
return d
}
/** 假期额度单位中文 */
export const unitText = (unit?: string) => (unit === 'hour' ? '小时' : '天')

View File

@ -0,0 +1,17 @@
/** 帮助中心:在系统内展示可独立访问、可打印的 HTML 使用手册。 */
export default function Help() {
return (
<iframe
title="UNIS HRMS 使用手册"
src="/help/index.html"
style={{
width: '100%',
height: 'calc(100vh - 104px)',
border: 0,
borderRadius: 12,
background: '#fff',
boxShadow: '0 8px 24px rgba(16, 24, 40, 0.06)',
}}
/>
)
}

View File

@ -1,7 +1,8 @@
import { LockOutlined, MobileOutlined, UserOutlined } from '@ant-design/icons'
import { App, Button, Checkbox, Form, Input, Space, Typography } from 'antd'
import { LockOutlined, UserOutlined } from '@ant-design/icons'
import { App, Button, Form, Input, Typography } from 'antd'
import { useState } from 'react'
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { sanitizeRedirect } from '../lib/mode'
import { useAuth } from '../store/auth'
const { Title, Text } = Typography
@ -28,7 +29,8 @@ export default function Login() {
try {
await login(values.username.trim().toLowerCase(), values.password)
message.success('登录成功,欢迎回来')
nav(sp.get('redirect') || (values.mobile ? '/m' : '/dashboard'), { replace: true })
// 落地页口径:跟随设备(手机端 H5、电脑端 Web);站内显式切换过的偏好优先;带 redirect 时按当前外壳改写
nav(sanitizeRedirect(sp.get('redirect')), { replace: true })
} catch {
/* 拦截器已提示 */
} finally {
@ -76,23 +78,14 @@ export default function Login() {
<Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
<Input.Password size="large" prefix={<LockOutlined />} placeholder="密码" autoComplete="current-password" />
</Form.Item>
<Form.Item style={{ marginBottom: 14 }}>
<Space style={{ width: '100%', justifyContent: 'space-between' }}>
<Form.Item name="mobile" valuePropName="checked" noStyle initialValue={false}>
<Checkbox>
<Space size={4}>
<MobileOutlined /> 以 H5 自助端进入
</Space>
</Checkbox>
</Form.Item>
<Text type="secondary" style={{ fontSize: 12 }}>
忘记密码请联系 HR
</Text>
</Space>
</Form.Item>
<Button type="primary" size="large" block htmlType="submit" loading={loading}>
登 录
</Button>
<div style={{ marginTop: 10, textAlign: 'right' }}>
<Text type="secondary" style={{ fontSize: 12 }}>
忘记密码请联系 HR
</Text>
</div>
</Form>
<div style={{ marginTop: 26 }}>

View File

@ -1,24 +1,22 @@
import {
AuditOutlined,
CalendarOutlined,
FileProtectOutlined,
GiftOutlined,
IdcardOutlined,
InsuranceOutlined,
MoneyCollectOutlined,
MobileOutlined,
NotificationOutlined,
ReloadOutlined,
RightOutlined,
ScheduleOutlined,
} from '@ant-design/icons'
import { useQuery } from '@tanstack/react-query'
import { Alert, Avatar, Card, Col, Flex, List, Progress, Row, Space, Spin, Tag, Typography } from 'antd'
import { useNavigate } from 'react-router-dom'
import { useLocation, useNavigate } from 'react-router-dom'
import { useSelfHome } from '../api/self'
import { statusHex, yuan } from '../api/defs'
import { get } from '../api/http'
import EmptyBlock from '../components/EmptyBlock'
import { icon } from '../components/icons'
import { greeting, todayLabel } from '../hooks/useGreeting'
import { oppositePath, setModePref } from '../lib/mode'
import { pathOf, permittedModules, toWebPath } from '../self/manifest'
import { useAuth } from '../store/auth'
const { Text, Title, Paragraph } = Typography
@ -38,13 +36,15 @@ const TODO_LABEL: Record<string, string> = {
task_pending: '待办任务',
}
const ENTRIES = [
{ key: 'leave', label: '请假 / 调休', desc: '发起申请、查额度', icon: CalendarOutlined, color: '#2f6bff', path: '/m/leave' },
{ key: 'payslip', label: '我的工资条', desc: '逐月明细与个税', icon: MoneyCollectOutlined, color: '#16a34a', path: '/m/payslips' },
{ key: 'benefit', label: '福利与保险', desc: '参保、福利发放', icon: InsuranceOutlined, color: '#722ed1', path: '/m/benefits' },
{ key: 'approval', label: '待我审批', desc: '下属提交的申请', icon: AuditOutlined, color: '#fa8c16', path: '/m/approvals' },
{ key: 'profile', label: '个人中心', desc: '档案、合同、证明', icon: IdcardOutlined, color: '#13c2c2', path: '/m/profile' },
]
// 常用入口不再手写:直接取 `self/manifest.ts` 里当前账号有权限的模块。
// H5 首页宫格调的是同一个 `permittedModules()`,所以两端的项目、名称、说明、
// 配色、顺序必然一致;后端菜单加模块时只改 manifest 一处。
const TODO_LINK: Record<string, string> = {
leave_pending: pathOf('leave', 'web'),
profile_pending: pathOf('approvals', 'web'),
document_pending: pathOf('approvals', 'web'),
task_pending: pathOf('tasks', 'web'),
}
function StatCard({ c, onClick }: { c: any; onClick: () => void }) {
const Ico = icon(c.icon)
@ -95,8 +95,12 @@ function TodoTile({ label, count, color, onClick }: { label: string; count: numb
export default function SelfHome() {
const nav = useNavigate()
const loc = useLocation()
const me = useAuth((s) => s.me)
const home = useQuery({ queryKey: ['self', 'home'], queryFn: () => get('/self/home') })
const hasPerm = useAuth((s) => s.hasPerm)
const canApprove = useAuth((s) => s.hasPerm('selfservice:approval:approve'))
// 与 H5 首页共用 useSelfHome():同一个 queryKey,两端共享缓存,一端操作另一端立即更新
const home = useSelfHome()
if (home.isPending && !home.data) {
return (
@ -129,7 +133,7 @@ export default function SelfHome() {
trend: payslip
? `税前 ${yuan(payslip.gross)} · 个税 ${yuan(payslip.tax)} · 社保公积金 ${yuan(payslip.insurance_personal)}`
: '暂无已发布的工资条',
link: '/m/payslips',
link: '/self/payslips',
},
{
key: 'leave',
@ -139,7 +143,7 @@ export default function SelfHome() {
color: '#2f6bff',
icon: 'CalendarOutlined',
trend: balances.length ? balances.map((b) => `${b.name} ${b.remaining}${b.unit === 'hour' ? '小时' : '天'}`).join(' · ') : '本年度还没有假期额度',
link: '/m/leave',
link: '/self/leave',
},
{
key: 'benefit',
@ -148,7 +152,7 @@ export default function SelfHome() {
color: '#722ed1',
icon: 'GiftOutlined',
trend: '含企业缴纳社保公积金与各类补贴',
link: '/m/benefits',
link: '/self/benefits',
},
{
key: 'todo',
@ -158,7 +162,7 @@ export default function SelfHome() {
color: '#f59e0b',
icon: 'ScheduleOutlined',
trend: todoTotal ? todoKeys.map((k) => `${TODO_LABEL[k]} ${todos[k]}`).join(' · ') : '目前没有卡在流程里的申请',
link: '/m/approvals',
link: '/self/approvals',
},
]
@ -177,10 +181,22 @@ export default function SelfHome() {
{emp.tenure_label ? ` · 在职 ${emp.tenure_label}` : ''}
</Text>
</div>
<ReloadOutlined
style={{ cursor: 'pointer', color: '#667085' }}
onClick={() => home.refetch()}
/>
<Space size={14}>
<a
style={{ fontSize: 12, color: '#667085' }}
onClick={() => {
// 显式记住偏好:手机浏览器 / 想在手机上继续看,切完下次进来仍是 H5
setModePref('h5')
nav(oppositePath(loc.pathname, 'h5'))
}}
>
<MobileOutlined /> 用 H5 版打开
</a>
<ReloadOutlined
style={{ cursor: 'pointer', color: '#667085' }}
onClick={() => home.refetch()}
/>
</Space>
</Flex>
{contract?.renew_soon && (
@ -206,10 +222,17 @@ export default function SelfHome() {
{/* 快捷入口:与 H5 完全同源,手机上看到的动作在这里也能一步到达 */}
<Card variant="borderless" size="small" styles={{ body: { padding: '14px 18px' } }} title="常用自助入口">
<Row gutter={[12, 12]}>
{ENTRIES.map((e) => (
{permittedModules(hasPerm)
.filter((m) => m.key !== 'home')
.map((e) => ({
...e,
label: e.key === 'approvals' ? (canApprove ? '审批中心' : '我的申请') : e.short,
Ico: icon(e.antdIcon),
}))
.map((e) => (
<Col key={e.key} xs={12} sm={8} md={4}>
<div
onClick={() => nav(e.path)}
onClick={() => nav(e.webPath)}
style={{
border: '1px solid #f0f2f6',
borderRadius: 12,
@ -232,13 +255,13 @@ export default function SelfHome() {
marginBottom: 8,
}}
>
<e.icon />
<e.Ico />
</div>
<div style={{ fontSize: 13, fontWeight: 600 }}>{e.label}</div>
<div style={{ fontSize: 12, color: '#98a2b3' }}>{e.desc}</div>
</div>
</Col>
))}
))}
</Row>
</Card>
@ -255,16 +278,16 @@ export default function SelfHome() {
{d.unread_notifications > 0 && <Tag bordered={false} color="blue">{d.unread_notifications} 条未读消息</Tag>}
</Space>
}
extra={<a onClick={() => nav('/m/approvals')}>全部</a>}
extra={<a onClick={() => nav(pathOf('approvals', 'web'))}>全部</a>}
>
{todoTotal === 0 && !tasks.length ? (
<EmptyBlock description="没有待处理的申请与任务" actionText="发起请假申请" onAction={() => nav('/m/leave')} />
<EmptyBlock description="没有待处理的申请与任务" actionText="发起请假申请" onAction={() => nav('/self/leave')} />
) : (
<Space direction="vertical" size={12} style={{ width: '100%' }}>
<Row gutter={[12, 12]}>
{todoKeys.map((k) => (
<Col key={k} xs={12} md={6}>
<TodoTile label={TODO_LABEL[k]} count={todos[k]} color={statusHex(k.includes('leave') ? 'pending' : 'approved')} onClick={() => nav(k === 'task_pending' ? '/m/profile' : '/m/leave')} />
<TodoTile label={TODO_LABEL[k]} count={todos[k]} color={statusHex(k.includes('leave') ? 'pending' : 'approved')} onClick={() => nav(TODO_LINK[k] || pathOf('approvals', 'web'))} />
</Col>
))}
</Row>
@ -275,7 +298,7 @@ export default function SelfHome() {
renderItem={(t: any) => (
<List.Item
style={{ cursor: t.link ? 'pointer' : 'default', paddingInline: 0 }}
onClick={() => t.link && nav(t.link)}
onClick={() => t.link && nav(toWebPath(t.link))}
actions={[
<Text key="due" type="secondary" style={{ fontSize: 12 }}>
{t.due_date ? `截止 ${t.due_date}` : ''}
@ -307,7 +330,7 @@ export default function SelfHome() {
variant="borderless"
size="small"
title="假期余额"
extra={<a onClick={() => nav('/m/leave')}>请假</a>}
extra={<a onClick={() => nav('/self/leave')}>请假</a>}
>
{balances.length === 0 ? (
<EmptyBlock description="本年度还没有分配假期额度,可联系 HR 确认" />
@ -343,7 +366,7 @@ export default function SelfHome() {
<Col xs={24} xl={8}>
<Space direction="vertical" size={14} style={{ width: '100%' }}>
<Card variant="borderless" size="small" title={<Space><IdcardOutlined style={{ color: '#13c2c2' }} />我的档案与合同</Space>} extra={<a onClick={() => nav('/m/profile')}>完善</a>}>
<Card variant="borderless" size="small" title={<Space><IdcardOutlined style={{ color: '#13c2c2' }} />我的档案与合同</Space>} extra={<a onClick={() => nav('/self/profile')}>完善</a>}>
<Space direction="vertical" size={8} style={{ width: '100%', fontSize: 13 }}>
<Flex justify="space-between">
<Text type="secondary" style={{ fontSize: 12 }}>工号 / 状态</Text>
@ -371,13 +394,13 @@ export default function SelfHome() {
<Text strong style={{ color: '#722ed1' }}>{yuan(d.benefit_this_month ?? 0)}</Text>
</Flex>
</div>
<a onClick={() => nav('/m/profile')} style={{ fontSize: 12 }}>
<a onClick={() => nav('/self/profile')} style={{ fontSize: 12 }}>
申请收入证明 / 在职证明 →
</a>
</Space>
</Card>
<Card variant="borderless" size="small" title={<Space><NotificationOutlined style={{ color: '#2f6bff' }} />公司公告</Space>} extra={<a onClick={() => nav('/m/profile')}>消息</a>}>
<Card variant="borderless" size="small" title={<Space><NotificationOutlined style={{ color: '#2f6bff' }} />公司公告</Space>} extra={<a onClick={() => nav(pathOf('tasks', 'web'))}>待办与消息</a>}>
{anns.length === 0 ? (
<EmptyBlock description="暂时没有公告" />
) : (

View File

@ -3,7 +3,7 @@ import { App, Space, Tabs } from 'antd'
import { useState } from 'react'
import { get, post } from '../../api/http'
import { useAuth } from '../../store/auth'
import { adjustmentDef, changeDef, documentDef } from '../../api/resources'
import { adjustmentDef, changeDef, documentDef, profileRequestDef } from '../../api/resources'
import ResourceTable from '../../components/ResourceTable'
/** 审批中心:异动 / 调薪 / 证明开具 三类流程集中处理 */
@ -64,6 +64,17 @@ function Cardish({ tab, setTab }: { tab: string; setTab: (v: string) => void })
/>
),
},
{
key: 'profile',
label: '资料变更',
children: (
<ResourceTable
def={profileRequestDef}
desc="员工自助提交的个人档案修改统一在此审核;通过后才会写回档案。"
rowActions={actions('/employee-profile-requests', 'employee:change:approve')}
/>
),
},
{
key: 'salary',
label: '调薪审批',

View File

@ -1,58 +1,30 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Dialog, DotLoading, TextArea, Toast } from 'antd-mobile'
import { useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { get, post } from '../../api/http'
import { useApprovalDecide, useSelfApprovals } from '../../api/self'
import { APPROVAL_META as META, APPROVAL_STATUS as ST, APPROVAL_TYPES as TYPES } from '../../lib/selfLabels'
import { selfModule } from '../../self/manifest'
import { useAuth } from '../../store/auth'
import { MBar, MChips, MEmpty, MLoading, MProblem, MSearch, MTag, dstr } from './_ui'
/** 状态页签:与 Web 工作台 /self/approvals 用同一组 key 与中文 */
const TABS = [
{ key: 'pending', label: '待审批' },
{ key: 'approved', label: '已通过' },
{ key: 'rejected', label: '已驳回' },
]
const TYPES = [
{ key: '', label: '全部' },
{ key: 'leave', label: '请假' },
{ key: 'change', label: '异动' },
{ key: 'adjustment', label: '调薪' },
{ key: 'profile', label: '资料变更' },
{ key: 'document', label: '证明' },
{ key: 'offer', label: 'Offer' },
]
const META: Record<string, { icon: string; color: string; text: string }> = {
leave: { icon: '🗓', color: '#2f54eb', text: '请假' },
change: { icon: '🔀', color: '#7c3aed', text: '异动' },
adjustment: { icon: '📈', color: '#16a34a', text: '调薪' },
profile: { icon: '📝', color: '#0ea5e9', text: '资料' },
document: { icon: '📄', color: '#f59e0b', text: '证明' },
offer: { icon: '🎯', color: '#ec4899', text: 'Offer' },
}
const ST: Record<string, { text: string; color: string }> = {
pending: { text: '待审批', color: '#f59e0b' },
approved: { text: '已通过', color: '#16a34a' },
sent: { text: '已发送', color: '#2f54eb' },
accepted: { text: '已接受', color: '#16a34a' },
rejected: { text: '已驳回', color: '#ef4444' },
}
/** H5 移动审批中心:主管 / HR 在手机上完成审批;普通员工在此跟踪自己提交的申请 */
export default function MApprovals() {
const nav = useNavigate()
const qc = useQueryClient()
const hasPerm = useAuth((s) => s.hasPerm)
const canApprove = hasPerm('selfservice:approval:approve')
const [tab, setTab] = useState('pending')
const [type, setType] = useState('')
const [kw, setKw] = useState('')
const q = useQuery({
queryKey: ['self-approvals', tab, type],
queryFn: () => get<any>('/self/approvals', { status: tab, type: type || undefined, limit: 100 }),
})
// 与 Web 端共用 useSelfApprovals:同一 queryKey,审批完两端同时更新
const q = useSelfApprovals(tab, type)
const rows: any[] = q.data?.items || []
const items = useMemo(() => {
const k = kw.trim().toLowerCase()
@ -69,19 +41,7 @@ export default function MApprovals() {
? `数据范围内 ${totalPending} 项待审批`
: `我提交的 ${q.data?.total ?? items.length} ${DONE_NOUN[tab] || '项记录'}`
const decide = useMutation({
mutationFn: (v: { item: any; status: string; comment?: string }) =>
post(`/self/approvals/${v.item.type}/${v.item.id}/decide`, {
status: v.status,
comment: v.comment || undefined,
}),
onSuccess: (_r, v) => {
Toast.show({ icon: 'success', content: v.status === 'approved' ? '已通过' : '已驳回' })
qc.invalidateQueries({ queryKey: ['self-approvals'] })
qc.invalidateQueries({ queryKey: ['self-home'] })
},
onError: (e: any) => Toast.show({ icon: 'fail', content: e?.message || '审批失败' }),
})
const decide = useApprovalDecide()
const ask = (item: any, status: 'approved' | 'rejected') => {
let comment = ''
@ -96,7 +56,14 @@ export default function MApprovals() {
<TextArea placeholder="审批意见(可选)" rows={2} onChange={(v) => (comment = v)} style={{ '--font-size': '14px' }} />
</div>
),
onConfirm: () => decide.mutateAsync({ item, status, comment }),
onConfirm: () =>
decide.mutateAsync(
{ type: item.type, id: item.id, status, comment: comment.trim() || undefined },
{
onSuccess: () => Toast.show({ icon: 'success', content: status === 'approved' ? '已通过' : '已驳回' }),
onError: (e: any) => Toast.show({ icon: 'fail', content: e?.message || '审批失败' }),
},
),
})
}
@ -104,7 +71,7 @@ export default function MApprovals() {
<div style={{ paddingBottom: 70 }}>
<MBar
title={canApprove ? '审批中心' : '我的申请'}
onBack={() => nav('/m')}
onBack={() => nav(selfModule('home').mobilePath)}
right={<span style={{ fontSize: 12, color: '#98a2b3' }}>{corner}</span>}
/>

View File

@ -1,20 +1,26 @@
import { useQuery } from '@tanstack/react-query'
import { CapsuleTabs, ProgressBar } from 'antd-mobile'
import { useMemo, useState } from 'react'
import { BENEFIT_CATEGORY_OPTIONS } from '../../api/defs'
import { get } from '../../api/http'
import { MBar, MChips, MEmpty, MLoading, MProblem, MRow, MTag, rmb } from './_ui'
import {
useSelfBenefits,
useSelfInsurance,
useSelfLeaveOptions,
} from '../../api/self'
import { BENEFIT_CATEGORY_TEXT as CAT_TEXT, BENEFIT_ICONS, BENEFIT_RECORD_STATUS as REC_STATUS } from '../../lib/selfLabels'
import {
INSURANCE_STATUS_COLOR,
INSURANCE_STATUS_TEXT,
MBar,
MChips,
MEmpty,
MLoading,
MProblem,
MRow,
MTag,
pct,
rmb,
unitText,
} from './_ui'
const CAT_TEXT: Record<string, string> = Object.fromEntries(
BENEFIT_CATEGORY_OPTIONS.map((x) => [x.value, x.label]),
)
const REC_STATUS: Record<string, { t: string; c: string }> = {
pending: { t: '待发放', c: '#f59e0b' },
approved: { t: '已审批', c: '#2f54eb' },
paid: { t: '已到账', c: '#16a34a' },
void: { t: '已作废', c: '#98a2b3' },
}
/** H5 福利保险:五险一金 · 福利发放 · 假期额度 */
export default function MBenefits() {
@ -37,7 +43,7 @@ export default function MBenefits() {
}
function Insurance() {
const q = useQuery({ queryKey: ['self-insurance'], queryFn: () => get<any>('/self/insurance') })
const q = useSelfInsurance()
if (q.isError) return <MProblem error={q.error} />
if (q.isFetching && !q.data) return <MLoading />
const d = q.data || {}
@ -59,7 +65,9 @@ function Insurance() {
{d.city} · 参保起始 {String(d.start_date || '-')}
</div>
</div>
<MTag color={d.status === 'active' ? '#16a34a' : '#f59e0b'}>{d.status === 'active' ? '参保中' : d.status}</MTag>
<MTag color={INSURANCE_STATUS_COLOR[d.status] || '#f59e0b'}>
{INSURANCE_STATUS_TEXT[d.status] || d.status || '-'}
</MTag>
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 14 }}>
<div style={{ background: '#fff1f0', borderRadius: 12, padding: 12 }}>
@ -110,7 +118,7 @@ function Insurance() {
<td style={{ padding: '7px 4px' }}>
<div style={{ color: '#1d2939' }}>{x.name}</div>
<div style={{ fontSize: 10, color: '#c9ced8' }}>
{Number(x.personal_rate || 0) * 100}% / {Number(x.company_rate || 0) * 100}%
{pct(x.personal_rate)} / {pct(x.company_rate)}
</div>
</td>
<td className="num" style={{ padding: '7px 4px', textAlign: 'right', color: '#ef4444' }}>
@ -165,7 +173,7 @@ function Insurance() {
}
function Benefits() {
const q = useQuery({ queryKey: ['self-benefits'], queryFn: () => get<any>('/self/benefits') })
const q = useSelfBenefits()
// Hooks 必须无条件执行:状态与派生计算一律放在 loading / error 早退之前
const d: any = q.data || {}
const all: any[] = d.items || []
@ -180,7 +188,6 @@ function Benefits() {
// 合计随筛选变化,口径与 PC 端列表一致
const total = Math.round(items.reduce((a, x) => a + Number(x.amount || 0), 0) * 100) / 100
const cnt = items.reduce((a, x) => a + Number(x.count || 0), 0)
const ICONS: Record<string, string> = { meal: '🍱', transport: '🚕', telecom: '📱', holiday: '🎁', health: '🏥', cash: '💵', gift: '🎀' }
return (
<div>
<MChips
@ -234,7 +241,7 @@ function Benefits() {
fontSize: 18,
}}
>
{ICONS[it.category] || ICONS[it.icon] || '🎁'}
{BENEFIT_ICONS[it.category] || BENEFIT_ICONS[it.icon] || '🎁'}
</div>
<div>
<div style={{ fontSize: 14, fontWeight: 600 }}>{it.name}</div>
@ -262,7 +269,7 @@ function Benefits() {
</span>
</div>
<div style={{ fontSize: 11, color: '#98a2b3', marginTop: 2 }}>
<MTag color={REC_STATUS[r.status]?.c || '#667085'}>{REC_STATUS[r.status]?.t || r.status}</MTag>
<MTag color={REC_STATUS[r.status]?.color || '#667085'}>{REC_STATUS[r.status]?.text || r.status}</MTag>
{r.paid_at ? ` ${String(r.paid_at).slice(0, 10)} 到账` : ''}
{r.remark ? ` · ${r.remark}` : ''}
</div>
@ -277,7 +284,7 @@ function Benefits() {
}
function LeaveQuota() {
const q = useQuery({ queryKey: ['self-leave-options'], queryFn: () => get<any[]>('/self/leave/options') })
const q = useSelfLeaveOptions()
if (q.isError) return <MProblem error={q.error} />
if (q.isFetching && !q.data) return <MLoading />
const types: any[] = q.data || []
@ -300,7 +307,7 @@ function LeaveQuota() {
<span className="num" style={{ fontSize: 15, fontWeight: 700, color: t.color || '#2f54eb' }}>
{t.requires_balance ? t.remaining ?? 0 : '不限'}
<span style={{ fontSize: 11, fontWeight: 400, marginLeft: 2, color: '#98a2b3' }}>
{t.requires_balance ? (t.unit === 'hour' ? '小时' : '天') : ''}
{t.requires_balance ? (unitText(t.unit)) : ''}
</span>
</span>
</div>
@ -312,7 +319,7 @@ function LeaveQuota() {
style={{ marginTop: 8, '--fill-color': t.color || '#2f54eb', '--track-color': '#eef0f5' } as any}
/>
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: '#98a2b3', marginTop: 4 }}>
<span>年度 {total} {t.unit === 'hour' ? '小时' : '天'}</span>
<span>年度 {total} {unitText(t.unit)}</span>
<span>已用 {used}</span>
</div>
</>

View File

@ -1,38 +1,22 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Dialog, Toast } from 'antd-mobile'
import { useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { get, post } from '../../api/http'
import { useSelfHome, useTaskDone } from '../../api/self'
import { greeting } from '../../hooks/useGreeting'
import { APPROVAL_META } from '../../lib/selfLabels'
import { oppositePath, setModePref } from '../../lib/mode'
import { permittedModules } from '../../self/manifest'
import { useAuth } from '../../store/auth'
import { MEmpty, MProblem, MTag, MTitle, rmb } from './_ui'
const APPROVAL_META: Record<string, { text: string; color: string }> = {
leave: { text: '请假', color: '#2f54eb' },
change: { text: '异动', color: '#7c3aed' },
adjustment: { text: '调薪', color: '#16a34a' },
profile: { text: '资料变更', color: '#0ea5e9' },
document: { text: '证明', color: '#f59e0b' },
offer: { text: 'Offer', color: '#ec4899' },
}
const TITLES = ['早上好', '上午好', '中午好', '下午好', '晚上好']
function greeting() {
const h = new Date().getHours()
if (h < 9) return TITLES[0]
if (h < 12) return TITLES[1]
if (h < 14) return TITLES[2]
if (h < 18) return TITLES[3]
return TITLES[4]
}
import { MEmpty, MProblem, MTag, MTitle, rmb, unitText } from './_ui'
/** H5 首页:工资条 · 假期 · 待办 · 公告 */
export default function MHome() {
const nav = useNavigate()
const qc = useQueryClient()
const taskRef = useRef<HTMLDivElement>(null)
const annRef = useRef<HTMLDivElement>(null)
const hasPerm = useAuth((s) => s.hasPerm)
const canApprove = useAuth((s) => s.hasPerm('selfservice:approval:approve'))
const q = useQuery({ queryKey: ['self-home'], queryFn: () => get<any>('/self/home') })
// 首页数据走公共 hook:与 Web 工作台 /dashboard 同一 queryKey,
// 任何一端提交完请假/待办,另一端的首屏数字同步刷新。
const q = useSelfHome()
const d = q.data || {}
const emp = d.employee || {}
const slip = d.latest_payslip
@ -41,27 +25,37 @@ export default function MHome() {
const anns: any[] = d.announcements || []
const todos = d.todos || {}
const done = useMutation({
mutationFn: (id: number) => post(`/self/tasks/${id}/done`),
onSuccess: () => {
Toast.show({ icon: 'success', content: '已完成' })
qc.invalidateQueries({ queryKey: ['self-home'] })
qc.invalidateQueries({ queryKey: ['self-tasks'] })
},
})
const done = useTaskDone()
const canApprove = useAuth((s) => s.hasPerm('selfservice:approval:approve'))
const cells = [
{ icon: '📝', bg: '#2f54eb', text: '请假', go: () => nav('/m/leave'), badge: todos.leave_pending },
{ icon: '💰', bg: '#16a34a', text: '工资条', go: () => nav('/m/payslips') },
{ icon: '🎁', bg: '#f59e0b', text: '福利保险', go: () => nav('/m/benefits') },
{ icon: '👤', bg: '#7c3aed', text: '我的档案', go: () => nav('/m/profile') },
{ icon: '✅', bg: '#0ea5e9', text: 'HR 待办', badge: tasks.filter((t) => t.status === 'pending').length, go: () => taskRef.current?.scrollIntoView({ behavior: 'smooth' }) },
{ icon: '📢', bg: '#ec4899', text: '公司公告', go: () => annRef.current?.scrollIntoView({ behavior: 'smooth' }) },
{ icon: '📄', bg: '#14b8a6', text: '合同状态', go: () => nav('/m/profile') },
{ icon: '🧾', bg: '#ef4444', text: canApprove ? '审批中心' : '我的申请', badge: d.approvals?.total, go: () => nav('/m/approvals') },
{ icon: '🔔', bg: '#64748b', text: '消息', badge: d.unread_notifications, go: () => nav('/m/profile') },
]
/**
* 宫格 = 当前账号有权限的自助模块(`self/manifest.ts` 里声明的那一份)。
* Web 工作台的 /dashboard 用的是同一个函数 + 同一份清单,所以两端宫格
* 的项目、名称、顺序、配色永远一致,不会再出现「H5 有 Web 没有」。
*/
const cells = permittedModules(hasPerm)
.filter((m) => m.key !== 'home')
.map((m) => ({
key: m.key,
icon: m.emoji,
bg: m.color,
text: m.key === 'approvals' ? (canApprove ? '审批中心' : '我的申请') : m.short,
desc: m.desc,
go: () => nav(m.mobilePath),
badge:
m.key === 'leave'
? todos.leave_pending
: m.key === 'approvals'
? d.approvals?.total
: m.key === 'tasks'
? (d.unread_notifications || 0) + tasks.filter((t: any) => t.status === 'pending').length
: undefined,
}))
/** 切到 Web 工作台:记下显式偏好,并落在同一个模块(工资条 → /self/payslips) */
const goWeb = () => {
setModePref('web')
nav(oppositePath('/m', 'web'))
}
if (q.isError) return <MProblem error={q.error} />
@ -146,7 +140,7 @@ export default function MHome() {
<div key={b.leave_type_id} style={{ textAlign: 'center', padding: '10px 4px', background: '#f7f9ff', borderRadius: 12 }}>
<div style={{ fontSize: 20, fontWeight: 700, color: b.color || '#2f54eb' }} className="num">
{b.remaining}
<span style={{ fontSize: 11, fontWeight: 400, marginLeft: 2 }}>{b.unit === 'hour' ? '小时' : '天'}</span>
<span style={{ fontSize: 11, fontWeight: 400, marginLeft: 2 }}>{unitText(b.unit)}</span>
</div>
<div style={{ fontSize: 11, color: '#667085', marginTop: 2 }}>{b.name}</div>
<div style={{ fontSize: 10, color: '#c9ced8' }}>共 {b.total}</div>
@ -162,7 +156,7 @@ export default function MHome() {
<div className="m-card">
<div className="m-grid">
{cells.map((c) => (
<div className="cell" key={c.text} onClick={c.go}>
<div className="cell" key={c.key} onClick={c.go}>
<div className="ico" style={{ background: c.bg, position: 'relative' }}>
{c.icon}
{!!c.badge && (
@ -189,6 +183,22 @@ export default function MHome() {
</div>
))}
</div>
<div
onClick={goWeb}
style={{
marginTop: 12,
paddingTop: 11,
borderTop: '1px dashed #eaecf2',
fontSize: 12,
color: '#667085',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<span>💻 想用大屏版?进入 Web 工作台(布局更宽,功能与这里完全一致)</span>
<span style={{ color: '#2f54eb' }}>切换 ›</span>
</div>
</div>
{/* 合同提醒 */}
@ -232,7 +242,7 @@ export default function MHome() {
)}
{/* HR 待办 */}
<div className="m-card" ref={taskRef}>
<div className="m-card">
<MTitle>HR 待办</MTitle>
{tasks.length ? (
tasks.map((t) => (
@ -269,7 +279,7 @@ export default function MHome() {
</div>
{/* 公告 */}
<div className="m-card" ref={annRef}>
<div className="m-card">
<MTitle>公司公告</MTitle>
{anns.length ? (
anns.map((a) => (

View File

@ -1,28 +1,26 @@
import { CheckCircleFill } from 'antd-mobile-icons'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { CapsuleTabs, Dialog, ProgressBar, Toast } from 'antd-mobile'
import { useMemo, useState } from 'react'
import { statusHex } from '../../api/defs'
import { del, get, post, upload } from '../../api/http'
import {
invalidateSelf,
useLeaveApply,
useLeaveCancel,
useSelfLeave,
useSelfLeaveOptions,
useUploadLeaveCertificate,
} from '../../api/self'
import { LEAVE_FILTERS, LEAVE_STATUS_TEXT } from '../../lib/selfLabels'
import {
MBar, MChips, MEmpty, MField, MLoading, MProblem, MRow, MSearch, MTag, PERIOD_TEXT, dstr,
} from './_ui'
/** 状态筛选项与 Web 端「请假管理」表头筛选项保持一致 */
const STATUS_TABS = [
{ key: '', label: '全部' },
{ key: 'pending', label: '审批中' },
{ key: 'approved', label: '已通过' },
{ key: 'rejected', label: '已驳回' },
{ key: 'cancelled', label: '已撤销' },
]
const STATUS_TEXT: Record<string, string> = {
pending: '审批中',
approved: '已通过',
rejected: '已驳回',
cancelled: '已撤销',
}
/**
* 状态筛选项与状态中文取自 `lib/selfLabels`:与 Web 工作台 /self/leave、
* 后端「假期管理」表头筛选项同源,两端不会出现「审批中 / 待审批」两种说法。
*/
const STATUS_TABS = LEAVE_FILTERS
const STATUS_TEXT = LEAVE_STATUS_TEXT
/** H5 假期:发起请假 + 我的请假记录 */
export default function MLeave() {
@ -43,8 +41,7 @@ export default function MLeave() {
/* ------------------------------------------------------------- 发起请假 -- */
function ApplyForm({ onDone }: { onDone: () => void }) {
const qc = useQueryClient()
const opts = useQuery({ queryKey: ['self-leave-options'], queryFn: () => get<any[]>('/self/leave/options') })
const opts = useSelfLeaveOptions()
const types: any[] = opts.data || []
const [typeId, setTypeId] = useState<number | null>(null)
const [start, setStart] = useState(new Date().toISOString().slice(0, 10))
@ -52,45 +49,46 @@ function ApplyForm({ onDone }: { onDone: () => void }) {
const [period, setPeriod] = useState('full')
const [reason, setReason] = useState('')
const [file, setFile] = useState<any>(null)
const [submitting, setSubmitting] = useState(false)
const type = types.find((t) => t.id === typeId) || null
const days = diffDays(start, end, period)
const submit = async () => {
// 提交 / 上传走 `api/self` 的公共 mutation:成功后一次性失效额度、记录、首页,
// Web 工作台与 H5 共享同一份缓存,任一端提交另一端立刻是新数据。
const apply = useLeaveApply(() => {
Toast.show({ icon: 'success', content: '已提交,等待审批' })
setReason('')
setFile(null)
onDone()
})
const upload = useUploadLeaveCertificate()
const submit = () => {
if (!typeId) return Toast.show('请选择请假类型')
if (!start || !end) return Toast.show('请选择请假日期')
if (diffDays(start, end, period) <= 0) return Toast.show('结束日期不能早于开始日期')
if (!reason.trim()) return Toast.show('请填写请假事由')
if (type?.requires_certificate && !file) return Toast.show(`「${type.name}」需要上传证明材料`)
setSubmitting(true)
try {
await post('/self/leave', {
leave_type_id: typeId,
start_date: start,
end_date: end,
period,
reason: reason.trim(),
days,
attachment_id: file?.id || undefined,
})
Toast.show({ icon: 'success', content: '已提交,等待审批' })
setReason('')
setFile(null)
qc.invalidateQueries({ queryKey: ['self-leave'] })
qc.invalidateQueries({ queryKey: ['self-leave-options'] })
qc.invalidateQueries({ queryKey: ['self-home'] })
onDone()
} finally {
setSubmitting(false)
}
apply.mutate({
leave_type_id: typeId,
start_date: start,
end_date: end,
period,
reason: reason.trim(),
days,
attachment_id: file?.id || undefined,
})
}
const doUpload = async (f: File) => {
const doUpload = (f: File) => {
Toast.show({ icon: 'loading', content: '上传中' })
const r = await upload<{ id: number; name: string }>('/common/upload', f, { biz_type: 'leave_certificate' })
setFile(r)
Toast.show({ icon: 'success', content: '附件已上传' })
upload.mutate(f, {
onSuccess: (r) => {
setFile(r)
Toast.show({ icon: 'success', content: '附件已上传' })
},
onError: () => Toast.show({ icon: 'fail', content: '附件上传失败,请重试' }),
})
}
return (
@ -206,7 +204,7 @@ function ApplyForm({ onDone }: { onDone: () => void }) {
</div>
<button
className="m-btn-primary"
disabled={submitting}
disabled={apply.isPending}
onClick={submit}
style={{
width: '100%',
@ -214,13 +212,13 @@ function ApplyForm({ onDone }: { onDone: () => void }) {
height: 44,
borderRadius: 12,
border: 'none',
background: submitting ? '#9aa9e8' : '#2f54eb',
background: apply.isPending ? '#9aa9e8' : '#2f54eb',
color: '#fff',
fontSize: 15,
fontWeight: 600,
}}
>
{submitting ? '提交中…' : '提交请假申请'}
{apply.isPending ? '提交中…' : '提交请假申请'}
</button>
</div>
</div>
@ -229,13 +227,9 @@ function ApplyForm({ onDone }: { onDone: () => void }) {
/* ------------------------------------------------------------- 请假记录 -- */
function Records() {
const qc = useQueryClient()
const [status, setStatus] = useState('')
const [kw, setKw] = useState('')
const q = useQuery({
queryKey: ['self-leave', status],
queryFn: () => get<any>('/self/leave', { status: status || undefined, page: 1, page_size: 50 }),
})
const q = useSelfLeave(status)
const rows: any[] = q.data?.items || []
const items = useMemo(() => {
const k = kw.trim().toLowerCase()
@ -245,14 +239,7 @@ function Records() {
)
}, [rows, kw])
const cancel = useMutation({
mutationFn: (id: number) => del(`/self/leave/${id}`),
onSuccess: () => {
Toast.show({ icon: 'success', content: '已撤销' })
qc.invalidateQueries({ queryKey: ['self-leave'] })
qc.invalidateQueries({ queryKey: ['self-leave-options'] })
},
})
const cancel = useLeaveCancel()
return (
<div>

View File

@ -1,22 +1,14 @@
import { useQuery } from '@tanstack/react-query'
import { useMemo, useState } from 'react'
import { statusHex } from '../../api/defs'
import { get } from '../../api/http'
import { useSelfPayslip, useSelfPayslips } from '../../api/self'
import {
PAYSLIP_STATUS_TEXT as STATUS_TEXT,
PAYSLIP_STATUS_TONE as STATUS_TONE,
QUARTERS,
round2,
} from '../../lib/selfLabels'
import { MBar, MChips, MEmpty, MTag, rmb } from './_ui'
/** 季度筛选(工资条仅有「已发布」一种状态,故按季度切分更有意义) */
const QUARTERS = [
{ key: '', label: '全年', months: [] as number[] },
{ key: '1', label: '一季度', months: [1, 2, 3] },
{ key: '2', label: '二季度', months: [4, 5, 6] },
{ key: '3', label: '三季度', months: [7, 8, 9] },
{ key: '4', label: '四季度', months: [10, 11, 12] },
]
const STATUS_TEXT: Record<string, string> = { published: '已发放', paid: '已发放', approved: '待发放', calculated: '计算中' }
// 工资条的 approved = 已核算待发放,语义上仍是「进行中」,颜色跟随 pending 而不是绿色的已通过
const STATUS_TONE: Record<string, string> = { approved: 'pending' }
/** H5 工资条:年度汇总 + 月度明细 */
export default function MPayslips() {
const THIS = new Date().getFullYear()
@ -24,7 +16,8 @@ export default function MPayslips() {
const [quarter, setQuarter] = useState('')
const [openId, setOpenId] = useState<number | null>(null)
const q = useQuery({ queryKey: ['self-payslips', year], queryFn: () => get<any>('/self/payslips', { year }) })
// 与 Web 工作台 /self/payslips 同一 hook、同一 queryKey,两端看到完全一致的年度合计
const q = useSelfPayslips(year)
const all: any[] = q.data?.items || []
const years: number[] = (q.data?.years || [THIS]).length ? q.data?.years || [THIS] : [THIS]
@ -106,14 +99,9 @@ export default function MPayslips() {
)
}
const round2 = (v: number) => Math.round(v * 100) / 100
function SlipCard({ it, open, onToggle }: { it: any; open: boolean; onToggle: () => void }) {
const detail = useQuery({
queryKey: ['self-payslip', it.id],
enabled: open,
queryFn: () => get<any>(`/self/payslips/${it.id}`),
})
// 展开时才拉明细,端点与 Web 端抽屉完全相同
const detail = useSelfPayslip(it.id, open)
const amounts: Record<string, number> = it.amounts || {}
const labels: Record<string, string> = it.labels || {}
const insurance: Record<string, any> = it.insurance || {}

View File

@ -1,17 +1,43 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useQueryClient } from '@tanstack/react-query'
import { CapsuleTabs, Dialog, Toast } from 'antd-mobile'
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { del, get, patch, post } from '../../api/http'
import {
invalidateSelf,
useDocTypeDict,
useDocumentApply,
useNotificationsRead,
useProfileRequest,
useProfileRequestCancel,
useSelfDocuments,
useSelfHome,
useSelfNotifications,
useSelfProfile,
useSelfSalaryStandard,
} from '../../api/self'
import { oppositePath, setModePref } from '../../lib/mode'
import { useAuth } from '../../store/auth'
import { MBar, MChips, MEmpty, MField, MLoading, MProblem, MRow, MTag, dstr, rmb } from './_ui'
const REQ_STATUS: Record<string, { t: string; c: string }> = {
pending: { t: '待 HR 审核', c: '#f59e0b' },
approved: { t: '已通过', c: '#16a34a' },
rejected: { t: '已驳回', c: '#ef4444' },
cancelled: { t: '已撤回', c: '#98a2b3' },
}
import {
CONTRACT_STATUS_COLOR,
CONTRACT_STATUS_TEXT,
DOC_STATUS_COLOR,
EMP_STATUS_COLOR,
EMP_STATUS_TEXT,
DOC_STATUS_TEXT,
MBar,
MChips,
MEmpty,
MField,
MLoading,
MProblem,
MRow,
MTag,
PROFILE_FIELD_LABELS,
PROFILE_REQ_STATUS,
SALARY_ITEM_LABELS,
dstr,
rmb,
} from './_ui'
/** H5 我的:档案 · 信息变更 · 合同与薪资标准 · 证明开具 · 消息 */
export default function MProfile() {
@ -21,24 +47,34 @@ export default function MProfile() {
const [tab, setTab] = useState('info')
const qc = useQueryClient()
const home = useQuery({ queryKey: ['self-home'], queryFn: () => get<any>('/self/home') })
const profile = useQuery({ queryKey: ['self-profile'], queryFn: () => get<any>('/self/profile') })
const home = useSelfHome()
const profile = useSelfProfile()
const emp = { ...(home.data?.employee || {}), ...(profile.data?.employee || {}) }
// 管理员等没有员工档案的账号:身份卡退化成登录账号,不再渲染一排「- / 0 天 / 正式」
const bound = !!emp.work_no
const refresh = () => {
qc.invalidateQueries({ queryKey: ['self-profile'] })
qc.invalidateQueries({ queryKey: ['self-home'] })
}
// 一次失效整套自助缓存:H5 这边改完,Web 工作台那边同步变新
const refresh = () => invalidateSelf(qc, 'all')
return (
<div>
<MBar
title="我的"
right={
<a
style={{ fontSize: 12, color: '#98a2b3' }}
<span
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 4,
fontSize: 13,
fontWeight: 600,
lineHeight: '26px',
padding: '0 14px',
borderRadius: 999,
background: '#ef4444',
color: '#fff',
boxShadow: '0 2px 8px rgba(239,68,68,.32)',
}}
onClick={async () => {
const ok = await Dialog.confirm({ content: '确认退出登录?', confirmText: '退出', cancelText: '取消' })
if (ok) {
@ -48,7 +84,7 @@ export default function MProfile() {
}}
>
退出
</a>
</span>
}
/>
@ -84,8 +120,8 @@ export default function MProfile() {
</div>
</div>
{bound && (
<MTag color={emp.status === 'active' ? '#16a34a' : emp.status === 'probation' ? '#f59e0b' : '#98a2b3'}>
{emp.status === 'active' ? '在职' : emp.status === 'probation' ? '试用期' : emp.status}
<MTag color={EMP_STATUS_COLOR[emp.status] || '#98a2b3'}>
{EMP_STATUS_TEXT[emp.status] || emp.status}
</MTag>
)}
</div>
@ -147,22 +183,12 @@ function InfoTab({ profile, onChanged }: { profile: any; onChanged: () => void }
setEditing(true)
}
const direct = useMutation({
mutationFn: () => patch('/self/profile', draft),
onSuccess: () => {
Toast.show({ icon: 'success', content: '资料已更新' })
setEditing(false)
onChanged()
},
})
const request = useMutation({
mutationFn: () => post('/self/profile-requests', { changes: draft, reason: reason || undefined }),
onSuccess: () => {
Toast.show({ icon: 'success', content: '变更申请已提交' })
setEditing(false)
onChanged()
},
const request = useProfileRequest(() => {
Toast.show({ icon: 'success', content: '已提交审核,通过后生效' })
setEditing(false)
setDraft({})
setReason('')
onChanged()
})
const changedCount = fields.filter((f) => String(draft[f.name] ?? '') !== String(f.value ?? '')).length
@ -205,26 +231,10 @@ function InfoTab({ profile, onChanged }: { profile: any; onChanged: () => void }
取消
</button>
<button
onClick={() => direct.mutate()}
onClick={() => request.mutate({ changes: draft, reason: reason || undefined })}
disabled={!changedCount}
style={{
flex: 1.2,
height: 42,
borderRadius: 12,
border: 'none',
background: changedCount ? '#16a34a' : '#c9ced8',
color: '#fff',
fontSize: 14,
fontWeight: 600,
}}
>
直接保存
</button>
<button
onClick={() => request.mutate()}
disabled={!changedCount}
style={{
flex: 1.2,
flex: 1.6,
height: 42,
borderRadius: 12,
border: 'none',
@ -234,11 +244,11 @@ function InfoTab({ profile, onChanged }: { profile: any; onChanged: () => void }
fontWeight: 600,
}}
>
提交审核
{request.isPending ? '提交中…' : '提交审核'}
</button>
</div>
<div style={{ fontSize: 11, color: '#98a2b3', marginTop: 8 }}>
直接保存立即生效;提交审核会生成 HR 待办并由人力行政部核对后生效({changedCount} 项变更)。
个人档案不允许直接修改。提交后将生成 HR 待办,审核通过才会写入档案({changedCount} 项变更)。
</div>
</>
)}
@ -302,12 +312,9 @@ function InfoTab({ profile, onChanged }: { profile: any; onChanged: () => void }
/* ----------------------------------------------------------- 变更申请 -- */
function RequestsTab({ requests, onChanged }: { requests: any[]; onChanged: () => void }) {
const cancel = useMutation({
mutationFn: (id: number) => del(`/self/profile-requests/${id}`),
onSuccess: () => {
Toast.show({ icon: 'success', content: '已撤回' })
onChanged()
},
const cancel = useProfileRequestCancel(() => {
Toast.show({ icon: 'success', content: '已撤回' })
onChanged()
})
if (!requests.length)
return (
@ -321,14 +328,21 @@ function RequestsTab({ requests, onChanged }: { requests: any[]; onChanged: () =
<div className="m-card" key={r.id}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<span style={{ fontSize: 14, fontWeight: 600 }}>资料变更 #{r.id}</span>
<MTag color={REQ_STATUS[r.status]?.c || '#667085'}>{REQ_STATUS[r.status]?.t || r.status}</MTag>
<MTag color={PROFILE_REQ_STATUS[r.status]?.color || '#667085'}>{PROFILE_REQ_STATUS[r.status]?.text || r.status}</MTag>
</div>
<div style={{ marginTop: 8 }}>
{Object.entries(r.changes || {}).map(([k, v]) => (
<div key={k} style={{ fontSize: 12, color: '#475467', padding: '3px 0' }}>
· {k} → <b>{String(v)}</b>
</div>
))}
{Object.entries(r.changes || {}).map(([k, v]: [string, any]) => {
const after = v && typeof v === 'object' && 'after' in v ? v.after : v
const before = v && typeof v === 'object' && 'before' in v ? v.before : null
return (
<div key={k} style={{ fontSize: 12, color: '#475467', padding: '3px 0' }}>
· {PROFILE_FIELD_LABELS[k] || k}:
<span style={{ color: '#98a2b3' }}>{before || '未填写'}</span>
{' → '}
<b>{String(after || '未填写')}</b>
</div>
)
})}
</div>
{r.reason && <div style={{ fontSize: 12, color: '#98a2b3', marginTop: 6 }}>原因:{r.reason}</div>}
{r.comment && (
@ -353,7 +367,7 @@ function RequestsTab({ requests, onChanged }: { requests: any[]; onChanged: () =
/* --------------------------------------------------------- 合同与薪资 -- */
function SalaryTab({ contracts }: { contracts: any[] }) {
const std = useQuery({ queryKey: ['self-salary-standard'], queryFn: () => get<any>('/self/salary-standard') })
const std = useSelfSalaryStandard()
const d = std.data || {}
return (
<div>
@ -364,8 +378,8 @@ function SalaryTab({ contracts }: { contracts: any[] }) {
<div className="m-list-item" key={i}>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<span style={{ fontSize: 14, fontWeight: 500 }}>{c.contract_no}</span>
<MTag color={c.status === 'active' ? '#16a34a' : c.status === 'expired' ? '#ef4444' : '#98a2b3'}>
{c.status === 'active' ? '履行中' : c.status === 'expired' ? '已到期' : c.status}
<MTag color={CONTRACT_STATUS_COLOR[c.status] || '#98a2b3'}>
{CONTRACT_STATUS_TEXT[c.status] || c.status}
</MTag>
</div>
<div style={{ fontSize: 12, color: '#98a2b3', marginTop: 4 }}>
@ -390,7 +404,7 @@ function SalaryTab({ contracts }: { contracts: any[] }) {
</div>
<div style={{ marginTop: 8 }}>
{(d.items || []).map((x: any) => (
<MRow key={x.code} k={LABELS[x.code] || x.code} v={<span className="num">{rmb(x.amount)}</span>} />
<MRow key={x.code} k={SALARY_ITEM_LABELS[x.code] || x.code} v={<span className="num">{rmb(x.amount)}</span>} />
))}
</div>
<div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px dashed #eef0f5' }}>
@ -419,51 +433,61 @@ function SalaryTab({ contracts }: { contracts: any[] }) {
</>
)}
</div>
<div className="m-card">
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
<span style={{ fontSize: 13, fontWeight: 600 }}>职级报销标准</span>
{d.job_level_name && <MTag>{d.job_level_name}</MTag>}
</div>
{!(d.expense_standards || []).length ? (
<MEmpty text="当前职级尚未配置报销标准" />
) : (
<div style={{ marginTop: 8 }}>
{(d.expense_standards || []).map((x: any) => (
<MRow
key={x.project_name}
k={
<span>
{x.project_name}
{x.remark ? (
<span style={{ display: 'block', fontSize: 11, color: '#98a2b3', marginTop: 2 }}>
{x.remark}
</span>
) : null}
</span>
}
v={<b className="num">{rmb(x.limit_amount)} / {String(x.unit).replace(/^元\//, '')}</b>}
/>
))}
</div>
)}
</div>
</div>
)
}
const LABELS: Record<string, string> = {
base_salary: '基本工资',
perf_salary: '绩效工资',
post_salary: '岗位工资',
meal_allowance: '餐补',
transport_allowance: '交通补贴',
telecom_allowance: '通讯补贴',
housing_allowance: '住房补贴',
other_allowance: '其他补贴',
absence_deduction: '缺勤扣款',
other_deduction: '其他扣款',
}
/* --------------------------------------------------------- 证明与消息 -- */
function MoreTab() {
const qc = useQueryClient()
const docs = useQuery({ queryKey: ['self-documents'], queryFn: () => get<any[]>('/self/documents') })
const notes = useQuery({ queryKey: ['self-notifications'], queryFn: () => get<any>('/self/notifications') })
const dict = useQuery({ queryKey: ['dict', 'doc_type'], queryFn: () => get<any[]>('/common/dict/doc_type') })
const nav = useNavigate()
const docs = useSelfDocuments()
const notes = useSelfNotifications()
const dict = useDocTypeDict()
const [type, setType] = useState<string>('')
const [purpose, setPurpose] = useState('')
const [docSt, setDocSt] = useState('')
const [noteSt, setNoteSt] = useState('')
const apply = useMutation({
mutationFn: () => post('/self/documents', { doc_type: type || '在职证明', purpose: purpose || undefined }),
onSuccess: () => {
Toast.show({ icon: 'success', content: '证明申请已提交' })
setPurpose('')
qc.invalidateQueries({ queryKey: ['self-documents'] })
},
const apply = useDocumentApply(() => {
Toast.show({ icon: 'success', content: '证明申请已提交' })
setPurpose('')
})
const readAll = useMutation({
mutationFn: () => post('/self/notifications/read', { ids: (notes.data?.items || []).filter((n: any) => !n.is_read).map((n: any) => n.id) }),
onSuccess: () => qc.invalidateQueries({ queryKey: ['self-notifications'] }),
})
const readAll = useNotificationsRead()
const types: string[] = (dict.data || []).map((x: any) => x.value || x.label)
const allNotes: any[] = notes.data?.items || []
const unread = allNotes.filter((n: any) => !n.is_read).length
const unreadNotes = allNotes.filter((n: any) => !n.is_read)
const unread = unreadNotes.length
// 列表筛选:与 Web 端表头筛选同一套「枚举 + 点击即筛选」交互
const allDocs: any[] = docs.data || []
const shownDocs = docSt ? allDocs.filter((r: any) => r.status === docSt) : allDocs
@ -485,7 +509,7 @@ function MoreTab() {
<input className="m-input" value={purpose} placeholder="如:办理签证 / 银行贷款" onChange={(e) => setPurpose(e.target.value)} />
</MField>
<button
onClick={() => apply.mutate()}
onClick={() => apply.mutate({ doc_type: type || '在职证明', purpose: purpose || undefined })}
style={{ width: '100%', marginTop: 12, height: 42, borderRadius: 12, border: 'none', background: '#2f54eb', color: '#fff', fontSize: 14, fontWeight: 600 }}
>
提交申请
@ -512,9 +536,7 @@ function MoreTab() {
<div className="m-list-item" key={r.id}>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<span style={{ fontSize: 14 }}>{r.doc_type}</span>
<MTag color={r.status === 'approved' ? '#16a34a' : r.status === 'pending' ? '#f59e0b' : '#ef4444'}>
{r.status === 'approved' ? '已开具' : r.status === 'pending' ? '办理中' : r.status === 'rejected' ? '已驳回' : r.status}
</MTag>
<MTag color={DOC_STATUS_COLOR[r.status] || '#98a2b3'}>{DOC_STATUS_TEXT[r.status] || r.status}</MTag>
</div>
{r.purpose && <div style={{ fontSize: 12, color: '#98a2b3', marginTop: 4 }}>用途:{r.purpose}</div>}
{r.comment && <div style={{ fontSize: 12, color: '#475467', marginTop: 4 }}>HR 回复:{r.comment}</div>}
@ -530,7 +552,7 @@ function MoreTab() {
{unread > 0 && <MTag color="#ef4444">{unread} 条未读</MTag>}
</span>
{unread > 0 && (
<span style={{ fontSize: 12, color: '#2f54eb' }} onClick={() => readAll.mutate()}>
<span style={{ fontSize: 12, color: '#2f54eb' }} onClick={() => readAll.mutate(unreadNotes.map((n: any) => n.id))}>
全部已读
</span>
)}
@ -561,6 +583,37 @@ function MoreTab() {
))}
</div>
<div
className="m-card"
style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}
onClick={() => {
setModePref('web')
nav(oppositePath('/m/profile', 'web'))
}}
>
<div>
<div style={{ fontSize: 14, fontWeight: 600 }}>💻 想用大屏版?</div>
<div style={{ fontSize: 12, color: '#98a2b3', marginTop: 3 }}>
切到 Web 工作台,功能与这里完全一致,会记住你的选择
</div>
</div>
<span style={{ color: '#2f54eb' }}>切换 ›</span>
</div>
<div
className="m-card"
style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}
onClick={() => window.open('/help/index.html', '_blank', 'noopener,noreferrer')}
>
<div>
<div style={{ fontSize: 14, fontWeight: 600 }}>使用手册</div>
<div style={{ fontSize: 12, color: '#98a2b3', marginTop: 3 }}>
查看带截图的全功能操作说明
</div>
</div>
<span style={{ color: '#2f54eb' }}>打开 ›</span>
</div>
<div style={{ textAlign: 'center', color: '#c9ced8', fontSize: 11, padding: '4px 0 18px' }}>
UNIS HRMS · 当前账号 {useAuth.getState().me?.user?.username || ''}
</div>

View File

@ -0,0 +1,243 @@
import { useQueryClient } from '@tanstack/react-query'
import { Dialog, Toast } from 'antd-mobile'
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import {
SELF_KEYS,
invalidateSelf,
useNotificationsRead,
useSelfAnnouncements,
useSelfNotifications,
useSelfTasks,
useTaskDone,
} from '../../api/self'
import { TASK_LEVEL, dtstr } from '../../lib/selfLabels'
import { toMobilePath } from '../../self/manifest'
import { MBar, MChips, MEmpty, MLoading, MProblem, MTag, MTitle } from './_ui'
/**
* H5 待办与消息:HR 待办 · 消息通知 · 公司公告。
*
* 桌面端有 `/self/tasks`,H5 过去把这三块塞在首页和个人中心里,导致后端
* 写死的 `/m/tasks` 链接一律 404。这一页把 Web 的待办模块在 H5 里补齐,
* 两端读同一组 queryKey(`SELF_KEYS.tasks` 等),任一端处理完另一端同步刷新。
*/
export default function MTasks() {
const nav = useNavigate()
const [tab, setTab] = useState('task')
const home = useSelfTasks()
const notes = useSelfNotifications()
const unread = ((notes.data?.items || []) as any[]).filter((n: any) => !n.is_read).length
const pending = (home.data || []).filter((t: any) => t.status !== 'done').length
return (
<div style={{ paddingBottom: 70 }}>
<MBar title="待办与消息" onBack={() => nav('/m')} />
<MChips
style={{ padding: '10px 12px 0' }}
value={tab}
onChange={setTab}
options={[
{ key: 'task', label: 'HR 待办', count: pending || undefined },
{ key: 'note', label: '消息通知', count: unread || undefined },
{ key: 'ann', label: '公司公告' },
]}
/>
<div style={{ paddingTop: 10 }}>
{tab === 'task' ? <Tasks /> : tab === 'note' ? <Notes /> : <Announcements />}
</div>
</div>
)
}
function Tasks() {
const nav = useNavigate()
const qc = useQueryClient()
const q = useSelfTasks()
const done = useTaskDone()
const rows: any[] = q.data || []
const [filter, setFilter] = useState('pending')
const shown = filter === 'done' ? rows.filter((t) => t.status === 'done') : rows.filter((t) => t.status !== 'done')
if (q.isFetching && !q.data) return <MLoading />
if (q.isError) return <MProblem error={q.error} />
return (
<div>
<MChips
value={filter}
onChange={setFilter}
options={[
{ key: 'pending', label: '进行中', count: rows.filter((t) => t.status !== 'done').length || undefined },
{ key: 'done', label: '已完成', count: rows.filter((t) => t.status === 'done').length || undefined },
]}
/>
<div className="m-card" style={{ marginTop: 12 }}>
{!shown.length && <MEmpty text={filter === 'done' ? '还没有已完成的待办' : '太棒了,没有待办事项'} />}
{shown.map((t) => {
const lv = TASK_LEVEL[t.level]
const href = t.link ? toMobilePath(t.link) : ''
return (
<div className="m-list-item" key={t.id}>
<div style={{ display: 'flex', justifyContent: 'space-between', gap: 10 }}>
<div style={{ flex: 1, minWidth: 0 }}>
<div
style={{
fontSize: 14,
fontWeight: 500,
color: t.status === 'done' ? '#98a2b3' : '#1d2939',
textDecoration: t.status === 'done' ? 'line-through' : undefined,
}}
>
{lv && t.status !== 'done' && <MTag color={lv.color}>{lv.text}</MTag>} {t.title}
</div>
<div style={{ fontSize: 11, color: '#98a2b3', marginTop: 4 }}>
截止 {t.due_date}
{t.category ? ` · ${t.category}` : ''}
{t.detail ? ` · ${t.detail}` : ''}
</div>
</div>
{t.status === 'done' ? (
<MTag color="#16a34a">已完成</MTag>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 6, alignItems: 'flex-end' }}>
{!!href && (
<a style={{ fontSize: 12, color: '#2f54eb' }} onClick={() => nav(href)}>
去处理
</a>
)}
<a
style={{ fontSize: 12, color: '#2f54eb' }}
onClick={async () => {
const ok = await Dialog.confirm({
content: `确认将「${t.title}」标记为已完成?`,
confirmText: '完成',
cancelText: '再想想',
})
if (!ok) return
done.mutate(t.id, {
onSuccess: () => {
Toast.show({ icon: 'success', content: '已完成' })
invalidateSelf(qc, 'task')
},
})
}}
>
标记完成
</a>
</div>
)}
</div>
</div>
)
})}
</div>
</div>
)
}
function Notes() {
const nav = useNavigate()
const q = useSelfNotifications()
const read = useNotificationsRead()
const [filter, setFilter] = useState('')
const all: any[] = q.data?.items || []
const unread = all.filter((n) => !n.is_read)
const shown = filter === 'unread' ? unread : all
if (q.isFetching && !q.data) return <MLoading />
if (q.isError) return <MProblem error={q.error} />
return (
<div>
<MChips
value={filter}
onChange={setFilter}
options={[
{ key: '', label: '全部', count: all.length || undefined },
{ key: 'unread', label: '未读', count: unread.length || undefined },
]}
/>
<div className="m-card" style={{ marginTop: 12 }}>
<MTitle
more={unread.length ? '全部已读' : undefined}
onMore={
unread.length
? () =>
read.mutate(unread.map((n) => n.id), {
onSuccess: () => Toast.show({ icon: 'success', content: '已全部已读' }),
})
: undefined
}
>
消息通知
</MTitle>
{!all.length && <MEmpty text="暂无消息" />}
{!!all.length && !shown.length && <MEmpty text="太棒了,消息都已读" />}
{shown.map((n) => (
<div
className="m-list-item"
key={n.id}
onClick={() => {
if (!n.is_read) read.mutate([n.id])
if (n.link) nav(toMobilePath(n.link))
}}
>
<div style={{ display: 'flex', gap: 8 }}>
{!n.is_read && <span className="m-dot" style={{ background: '#ef4444', marginTop: 6 }} />}
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 14, fontWeight: n.is_read ? 400 : 600 }}>{n.title}</div>
<div style={{ fontSize: 12, color: '#667085', marginTop: 3, lineHeight: 1.6 }}>{n.content}</div>
<div style={{ fontSize: 11, color: '#c9ced8', marginTop: 4 }}>{dtstr(n.created_at)}</div>
</div>
{!!n.link && <span style={{ color: '#c9ced8' }}>›</span>}
</div>
</div>
))}
</div>
</div>
)
}
function Announcements() {
const q = useSelfAnnouncements()
const rows: any[] = q.data || []
if (q.isFetching && !q.data) return <MLoading />
if (q.isError) return <MProblem error={q.error} />
return (
<div className="m-card">
{!rows.length && <MEmpty text="暂无公告" />}
{rows.map((a) => (
<div
className="m-list-item"
key={a.id}
onClick={() =>
Dialog.alert({
title: a.title,
content: <div style={{ whiteSpace: 'pre-wrap', fontSize: 13, lineHeight: 1.7 }}>{a.content}</div>,
confirmText: '知道了',
})
}
>
<div style={{ display: 'flex', gap: 8, alignItems: 'flex-start' }}>
{a.level === 'urgent' ? (
<MTag color="#ef4444">紧急</MTag>
) : a.level === 'important' ? (
<MTag color="#f59e0b">重要</MTag>
) : null}
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 14, fontWeight: 500 }}>{a.title}</div>
<div style={{ fontSize: 11, color: '#98a2b3', marginTop: 3 }}>
{a.publisher || '人力行政部'} · {dtstr(a.published_at || a.created_at)}
</div>
</div>
<span style={{ color: '#c9ced8' }}>›</span>
</div>
</div>
))}
</div>
)
}
/** 与 Web 端同一份缓存键,供外部手动失效时使用 */
export { SELF_KEYS as TASK_KEYS }

View File

@ -161,33 +161,33 @@ export function MChips({
)
}
/** 金额 / 日期小工具 */
export const rmb = (v: any) =>
`¥${Number(v ?? 0).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
export const num = (v: any) => String(Number(v ?? 0))
export const dstr = (v?: string | null) => (v ? String(v).slice(0, 10) : '-')
export const LEAVE_STATUS: Record<string, { text: string; color: string }> = {
pending: { text: '审批中', color: '#f59e0b' },
approved: { text: '已通过', color: '#16a34a' },
rejected: { text: '已驳回', color: '#ef4444' },
cancelled: { text: '已撤销', color: '#98a2b3' },
}
export const PERIOD_TEXT: Record<string, string> = {
all: '全天',
full: '全天',
am: '上午',
morning: '上午',
pm: '下午',
afternoon: '下午',
}
export const TASK_LEVEL: Record<string, { text: string; color: string }> = {
high: { text: '加急', color: '#ef4444' },
urgent: { text: '加急', color: '#ef4444' },
normal: { text: '常规', color: '#2f54eb' },
low: { text: '较低', color: '#98a2b3' },
}
/**
* 金额 / 日期 / 状态字典统一来自 `lib/selfLabels`,这里只做再导出:
* Web 工作台与 H5 必须对同一个状态给出同一个中文与配色,历史页面里的
* `import { rmb, LEAVE_STATUS } from './_ui'` 也继续可用。
*/
export {
BENEFIT_ICONS,
BENEFIT_RECORD_STATUS,
CONTRACT_STATUS_COLOR,
CONTRACT_STATUS_TEXT,
DOC_STATUS_COLOR,
DOC_STATUS_TEXT,
EMP_STATUS_COLOR,
EMP_STATUS_TEXT,
INSURANCE_STATUS_COLOR,
INSURANCE_STATUS_TEXT,
LEAVE_STATUS,
LEAVE_STATUS_TEXT,
PERIOD_TEXT,
PROFILE_FIELD_LABELS,
PROFILE_REQ_STATUS,
SALARY_ITEM_LABELS,
TASK_LEVEL,
dstr,
dtstr,
num,
pct,
rmb,
unitText,
} from '../../lib/selfLabels'

View File

@ -1,6 +1,160 @@
import { DeleteOutlined, PlusOutlined, WalletOutlined } from '@ant-design/icons'
import { useMutation } from '@tanstack/react-query'
import {
App,
Button,
Card,
Col,
Form,
Input,
InputNumber,
Row,
Space,
Typography,
} from 'antd'
import { useState } from 'react'
import { put } from '../../api/http'
import { jobLevelDef } from '../../api/resources'
import FormDrawer from '../../components/FormDrawer'
import ResourceTable from '../../components/ResourceTable'
import { useAuth } from '../../store/auth'
export default function JobLevels() {
return <ResourceTable def={jobLevelDef} desc="职级体系(管理 M / 专业 P / 操作 O),关联薪档与定级标准" createText="新增职级" />
const { message } = App.useApp()
const [form] = Form.useForm()
const hasPerm = useAuth((s) => s.hasPerm)
const canEditStandard = hasPerm('org:joblevel:update')
const [editing, setEditing] = useState<any | null>(null)
const [refreshList, setRefreshList] = useState<() => void>(() => () => undefined)
const save = useMutation({
mutationFn: (values: any) =>
put(`/org/job-levels/${editing?.id}/expense-standards`, { items: values.items || [] }),
onSuccess: (res: any) => {
message.success(res?.message || '报销标准已保存')
setEditing(null)
refreshList()
},
})
const open = (row: any, refresh: () => void) => {
setRefreshList(() => refresh)
setEditing(row)
form.setFieldsValue({
items: (row.expense_standards || []).map((item: any) => ({ ...item })),
})
}
return (
<>
<ResourceTable
def={jobLevelDef}
desc="职级体系(管理 M / 专业 P / 操作 O),可为每个职级配置多个报销项目与额度"
createText="新增职级"
rowActions={canEditStandard ? (row, helpers) => (
<Button
type="link"
size="small"
icon={<WalletOutlined />}
onClick={() => open(row, helpers.refresh)}
>
报销标准
</Button>
) : undefined}
/>
<FormDrawer
open={!!editing}
title={`${editing?.name || ''} · 报销标准`}
desc="可配置多个报销项目;金额、计量单位及说明保存后立即生效,并展示给该职级员工。"
width={760}
loading={save.isPending}
onClose={() => setEditing(null)}
onSubmit={() => form.submit()}
okText="保存标准"
>
<Form form={form} layout="vertical" onFinish={(values) => save.mutate(values)}>
<Form.List name="items">
{(fields, { add, remove }) => (
<Space direction="vertical" size={12} style={{ width: '100%' }}>
{fields.length === 0 && (
<Card size="small" variant="borderless" style={{ textAlign: 'center', background: '#f7f9ff' }}>
<Typography.Text type="secondary">
尚未配置报销项目,点击下方按钮添加
</Typography.Text>
</Card>
)}
{fields.map((field, index) => (
<Card
key={field.key}
size="small"
title={`报销项目 ${index + 1}`}
extra={
<Button
type="text"
danger
size="small"
icon={<DeleteOutlined />}
onClick={() => remove(field.name)}
>
删除
</Button>
}
>
<Row gutter={12}>
<Col xs={24} md={9}>
<Form.Item
name={[field.name, 'project_name']}
label="项目名称"
rules={[{ required: true, message: '请填写报销项目名称' }]}
>
<Input placeholder="如:市内交通 / 差旅住宿" maxLength={64} />
</Form.Item>
</Col>
<Col xs={14} md={7}>
<Form.Item
name={[field.name, 'limit_amount']}
label="标准金额"
rules={[{ required: true, message: '请填写金额' }]}
>
<InputNumber min={0} precision={2} style={{ width: '100%' }} placeholder="0.00" />
</Form.Item>
</Col>
<Col xs={10} md={8}>
<Form.Item
name={[field.name, 'unit']}
label="计量单位"
rules={[{ required: true, message: '请填写单位' }]}
>
<Input placeholder="元/月、元/晚、元/次" maxLength={16} />
</Form.Item>
</Col>
<Col span={24}>
<Form.Item name={[field.name, 'remark']} label="适用说明">
<Input.TextArea
rows={2}
maxLength={255}
showCount
placeholder="如:按出差城市标准执行,凭发票实报实销"
/>
</Form.Item>
</Col>
</Row>
</Card>
))}
<Button
type="dashed"
block
icon={<PlusOutlined />}
onClick={() => add({ unit: '元/月', limit_amount: 0 })}
>
添加报销项目
</Button>
</Space>
)}
</Form.List>
</Form>
</FormDrawer>
</>
)
}

View File

@ -0,0 +1,292 @@
import { CheckOutlined } from '@ant-design/icons'
import { App, Button, Card, Col, Input, Modal, Row, Segmented, Space, Tag, Typography } from 'antd'
import { useMemo, useState } from 'react'
import { useApprovalDecide, useSelfApprovals } from '../../api/self'
import { useAuth } from '../../store/auth'
import { APPROVAL_META, APPROVAL_STATUS, APPROVAL_TYPES, dtstr } from '../../lib/selfLabels'
import { SelfEmpty, SelfLoading, SelfProblem } from './_shared'
const { Text, Title } = Typography
const TABS = [
{ key: 'pending', label: '待审批' },
{ key: 'approved', label: '已通过' },
{ key: 'rejected', label: '已驳回' },
]
/** 员工在"我的申请"视角下,三个状态页的中文量词(与 H5 同一说法) */
const DONE_NOUN: Record<string, string> = { pending: '项进行中', approved: '项已通过', rejected: '项已驳回' }
/**
* 审批中心 / 我的申请(Web 版)。
*
* 同一个页面两种身份:有 `selfservice:approval:approve` 的主管看到「审批中心」
* 并可在此通过/驳回;普通员工看到「我的申请」只能跟踪进度 —— 这与 H5
* `/m/approvals` 的判定完全相同(同一权限码、同一状态页签、同一类型筛选、
* 同一搜索范围),审批动作打的是同一个 `/self/approvals/{type}/{id}/decide`。
*/
export default function SelfApprovals() {
const { message } = App.useApp()
const hasPerm = useAuth((s) => s.hasPerm)
const canApprove = hasPerm('selfservice:approval:approve')
const [tab, setTab] = useState('pending')
const [type, setType] = useState('')
const [kw, setKw] = useState('')
const q = useSelfApprovals(tab, type)
const rows: any[] = q.data?.items || []
const counts: Record<string, number> = q.data?.counts || {}
const totalPending = Object.values(counts).reduce((a, b) => a + Number(b || 0), 0)
const items = useMemo(() => {
const k = kw.trim().toLowerCase()
if (!k) return rows
return rows.filter((x) =>
[x.title, x.summary, x.detail, x.work_no].some((v) => String(v ?? '').toLowerCase().includes(k)),
)
}, [rows, kw])
const decide = useApprovalDecide()
const [target, setTarget] = useState<{ item: any; status: 'approved' | 'rejected' } | null>(null)
const [comment, setComment] = useState('')
const ask = (item: any, status: 'approved' | 'rejected') => {
setTarget({ item, status })
setComment('')
}
const submit = async () => {
if (!target) return
const { item, status } = target
await decide.mutateAsync(
{ type: item.type, id: item.id, status, comment: comment.trim() || undefined },
{
onSuccess: () => {
message.success(status === 'approved' ? '已通过' : '已驳回')
setTarget(null)
},
onError: (e: any) => message.error(e?.message || '审批失败'),
},
)
}
const corner = canApprove
? `数据范围内 ${totalPending} 项待审批`
: `我提交的 ${q.data?.total ?? items.length} ${DONE_NOUN[tab] || '项记录'}`
return (
<div>
<Card variant="borderless" styles={{ body: { paddingBlock: 14 } }}>
<Row gutter={[14, 12]} align="middle" justify="space-between">
<Col>
<Segmented
value={tab}
onChange={(v) => setTab(String(v))}
options={TABS.map((t) => {
const label = t.key === 'pending' && canApprove ? '待我审批' : t.label
const n = t.key === 'pending' && canApprove ? totalPending : 0
return { label: n ? `${label} (${n})` : label, value: t.key }
})}
/>
</Col>
<Col>
<Text type="secondary" style={{ fontSize: 12 }}>
{corner}
</Text>
</Col>
</Row>
<Row gutter={[14, 12]} style={{ marginTop: 12 }} align="middle">
<Col flex="auto">
<Segmented
size="small"
value={type}
onChange={(v) => setType(String(v))}
options={APPROVAL_TYPES.map((t) => ({
label:
t.key && tab === 'pending' && counts[t.key]
? `${t.label} (${counts[t.key]})`
: t.label,
value: t.key,
}))}
/>
</Col>
<Col>
<Input.Search
allowClear
size="small"
style={{ width: 260 }}
placeholder="搜标题 / 摘要 / 工号"
value={kw}
onChange={(e) => setKw(e.target.value)}
/>
</Col>
</Row>
</Card>
<Card variant="borderless" style={{ marginTop: 14 }}>
{q.isLoading ? (
<SelfLoading />
) : q.isError ? (
<SelfProblem error={q.error} />
) : rows.length && !items.length ? (
<SelfEmpty description="没有符合筛选条件的记录" />
) : !items.length ? (
<SelfEmpty
description={
tab !== 'pending'
? '暂无记录'
: canApprove
? '太棒了,没有待你审批的事项'
: '目前没有进行中的申请'
}
/>
) : (
<Row gutter={[12, 12]}>
{items.map((it) => {
const m = APPROVAL_META[it.type] || { icon: '📌', color: '#64748b', text: it.type }
const st = APPROVAL_STATUS[it.status] || { text: it.status, color: '#64748b' }
const changes: Record<string, any> = it.changes || {}
const before: Record<string, any> = it.before || {}
return (
<Col xs={24} xl={12} key={`${it.type}-${it.id}`}>
<Card variant="borderless" size="small" styles={{ body: { padding: 14 } }} hoverable>
<Space align="start" size={10} style={{ width: '100%', justifyContent: 'space-between' }}>
<Space align="start" size={10}>
<span
style={{
width: 34,
height: 34,
borderRadius: 11,
background: `${m.color}14`,
display: 'grid',
placeItems: 'center',
fontSize: 17,
}}
>
{m.icon}
</span>
<span>
<div style={{ fontSize: 15, fontWeight: 600 }}>{it.title}</div>
<div style={{ fontSize: 12, color: '#667085', marginTop: 2 }}>
<Tag bordered={false} style={{ color: m.color, background: `${m.color}14` }}>
{m.text}
</Tag>
{it.summary}
</div>
</span>
</Space>
<Tag bordered={false} style={{ color: st.color, background: `${st.color}14` }}>
{st.text}
</Tag>
</Space>
{!!it.detail && (
<div
style={{
fontSize: 13,
color: '#475467',
marginTop: 10,
background: '#f7f9ff',
borderRadius: 10,
padding: '8px 10px',
lineHeight: 1.6,
}}
>
{it.detail}
</div>
)}
{Object.keys(changes).length > 0 && (
<div style={{ marginTop: 10 }}>
{Object.entries(changes).map(([k, v]) => (
<div
key={k}
style={{
display: 'flex',
justifyContent: 'space-between',
fontSize: 12,
padding: '5px 0',
borderTop: '1px dashed #eef0f5',
}}
>
<span style={{ color: '#98a2b3' }}>{k}</span>
<span style={{ textAlign: 'right', maxWidth: '62%', color: '#1d2939' }}>
{before[k] != null ? (
<span
style={{
color: '#98a2b3',
textDecoration: 'line-through',
marginRight: 6,
}}
>
{String(before[k])}
</span>
) : null}
{String(v ?? '-')}
</span>
</div>
))}
</div>
)}
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
marginTop: 12,
}}
>
<Text type="secondary" style={{ fontSize: 11 }}>
{it.work_no ? `${it.work_no} · ` : ''}
{dtstr(it.created_at)}
</Text>
{tab === 'pending' && canApprove && (
<Space size={6}>
<Button size="small" danger onClick={() => ask(it, 'rejected')}>
驳回
</Button>
<Button
size="small"
type="primary"
icon={<CheckOutlined />}
loading={decide.isPending}
onClick={() => ask(it, 'approved')}
>
通过
</Button>
</Space>
)}
</div>
</Card>
</Col>
)
})}
</Row>
)}
</Card>
<Modal
open={!!target}
title={target?.status === 'approved' ? '通过审批' : '驳回审批'}
okText={target?.status === 'approved' ? '确认通过' : '确认驳回'}
okButtonProps={{ danger: target?.status === 'rejected', loading: decide.isPending }}
onCancel={() => setTarget(null)}
onOk={submit}
>
<Title level={5} style={{ marginTop: 0 }}>
{target?.item?.title}
</Title>
<Text type="secondary">{target?.item?.summary}</Text>
<Input.TextArea
rows={3}
style={{ marginTop: 12 }}
placeholder="审批意见(可选)"
value={comment}
onChange={(e) => setComment(e.target.value)}
/>
</Modal>
</div>
)
}

View File

@ -0,0 +1,485 @@
import { Card, Col, Progress, Row, Segmented, Table, Tabs, Tag, Tooltip, Typography } from 'antd'
import type { ColumnsType } from 'antd/es/table'
import { useMemo, useState } from 'react'
import {
Bar,
BarChart,
CartesianGrid,
Legend,
ResponsiveContainer,
Tooltip as RTooltip,
XAxis,
YAxis,
} from 'recharts'
import { useSelfBenefits, useSelfInsurance, useSelfLeaveOptions } from '../../api/self'
import {
BENEFIT_CATEGORY_TEXT,
BENEFIT_ICONS,
BENEFIT_RECORD_STATUS,
INSURANCE_STATUS_COLOR,
INSURANCE_STATUS_TEXT,
pct,
rmb,
unitText,
} from '../../lib/selfLabels'
import { SelfEmpty, SelfLoading, SelfProblem, SectionTitle } from './_shared'
const { Text } = Typography
/** 福利类别中文:与管理端「福利项目」同一份字典,避免 Web/H5 各叫一套 */
const CAT_TEXT = BENEFIT_CATEGORY_TEXT
/**
* 福利与保险(Web 版)。
*
* Tab 结构与 H5 `/m/benefits` 完全一致:五险一金 / 福利发放 / 假期额度,
* 三个 Tab 读同一组接口(`/self/insurance`、`/self/benefits`、`/self/leave/options`),
* 合计口径同样是「筛选影响合计」;H5 的手绘柱状图在这里升级成 recharts,
* 但图例含义(个人 + 公司合计缴存)与说明文案保持一致。
*/
export default function SelfBenefits() {
return (
<Card variant="borderless" styles={{ body: { paddingTop: 6 } }}>
<Tabs
defaultActiveKey="insurance"
destroyOnHidden
items={[
{ key: 'insurance', label: '五险一金', children: <Insurance /> },
{ key: 'benefit', label: '福利发放', children: <BenefitGrants /> },
{ key: 'leave', label: '假期额度', children: <LeaveQuota /> },
]}
/>
</Card>
)
}
/* ------------------------------------------------------------- 五险一金 -- */
function Insurance() {
const q = useSelfInsurance()
if (q.isFetching && !q.data) return <SelfLoading />
if (q.isError) return <SelfProblem error={q.error} />
const d: any = q.data || {}
if (!d.enrolled) return <SelfEmpty description="尚未参保登记,请联系人力行政部办理" />
const yearly: any[] = (d.yearly || []).map((y: any) => ({
month: String(y.month || '').replace('月', ''),
个人: Number(y.personal || 0),
公司: Number(y.company || 0),
合计: Number(y.personal || 0) + Number(y.company || 0),
}))
const cols: ColumnsType<any> = [
{ title: '险种', dataIndex: 'name', width: 110 },
{
title: '缴存基数',
dataIndex: 'base',
align: 'right',
render: (v: number) => (
<span className="num" style={{ color: '#98a2b3' }}>
{Number(v || 0).toLocaleString('zh-CN', { maximumFractionDigits: 0 })}
</span>
),
},
{
title: '个人',
dataIndex: 'personal',
align: 'right',
render: (v: number, r) => (
<span className="num" style={{ color: '#ef4444' }}>
{rmb(v)}
<Text type="secondary" style={{ fontSize: 11, marginLeft: 6 }}>
{pct(r.personal_rate)}
</Text>
</span>
),
},
{
title: '公司',
dataIndex: 'company',
align: 'right',
render: (v: number, r) => (
<span className="num" style={{ color: '#2f54eb' }}>
{rmb(v)}
<Text type="secondary" style={{ fontSize: 11, marginLeft: 6 }}>
{pct(r.company_rate)}
</Text>
</span>
),
},
{
title: '小计',
align: 'right',
render: (_, r) => {
const sum = Number(r.personal || 0) + Number(r.company || 0)
return <span className="num">{sum > 0 ? rmb(sum) : '-'}</span>
},
},
]
return (
<div>
<div className="stat-grid" style={{ gridTemplateColumns: 'repeat(4, minmax(0,1fr))' }}>
<div className="stat">
<div className="stat-label">参保方案</div>
<div className="stat-value" style={{ fontSize: 17 }}>
{d.plan_name || '-'}
</div>
<div style={{ fontSize: 12, color: '#98a2b3' }}>
{d.city || '-'} · 参保起始 {d.start_date || '-'}
</div>
</div>
<div className="stat">
<div className="stat-label">参保状态</div>
<div className="stat-value" style={{ fontSize: 17, color: INSURANCE_STATUS_COLOR[d.status] || '#f59e0b' }}>
{INSURANCE_STATUS_TEXT[d.status] || d.status || '-'}
</div>
</div>
<div className="stat">
<div className="stat-label">个人月缴合计</div>
<div className="stat-value num" style={{ color: '#ef4444' }}>
{rmb(d.monthly_personal)}
</div>
</div>
<div className="stat">
<div className="stat-label">公司月缴合计</div>
<div className="stat-value num" style={{ color: '#2f54eb' }}>
{rmb(d.monthly_company)}
</div>
</div>
</div>
<Row gutter={[14, 14]} style={{ marginTop: 14 }}>
<Col xs={24} xl={10}>
<Card variant="borderless" size="small" title="缴存基数与账户">
<div className="info-grid" style={{ gridTemplateColumns: '1fr' }}>
<div className="info-item">
<div className="k">社保基数</div>
<div className="num">{rmb(d.social_base)}</div>
</div>
<div className="info-item">
<div className="k">公积金基数</div>
<div className="num">{rmb(d.fund_base)}</div>
</div>
<div className="info-item">
<div className="k">基数上下限</div>
<div className="num">
{Number(d.base_floor || 0).toLocaleString('zh-CN')} ~{' '}
{Number(d.base_ceiling || 0).toLocaleString('zh-CN')}
</div>
</div>
<div className="info-item">
<div className="k">社保账号</div>
<div className="mono">{d.social_account || '-'}</div>
</div>
<div className="info-item">
<div className="k">公积金账号</div>
<div className="mono">{d.fund_account || '-'}</div>
</div>
</div>
</Card>
</Col>
<Col xs={24} xl={14}>
<Card
variant="borderless"
size="small"
title="缴费比例明细"
extra={
<Text type="secondary" style={{ fontSize: 12 }}>
年度累计:个人 {rmb(d.yearly_personal_total)} · 公司 {rmb(d.yearly_company_total)}
</Text>
}
>
<Table rowKey={(r: any) => r.code || r.name} size="small" pagination={false} columns={cols} dataSource={d.items || []} />
</Card>
</Col>
</Row>
<Card
variant="borderless"
size="small"
style={{ marginTop: 14 }}
title="年度缴费趋势"
extra={
<Text type="secondary" style={{ fontSize: 12 }}>
柱高表示当月「个人 + 公司」合计缴存金额,随工资基数每年 7 月调整。
</Text>
}
>
{!yearly.length ? (
<SelfEmpty description="本年度还没有缴费记录" />
) : (
<div style={{ height: 240 }}>
<ResponsiveContainer width="100%" height="100%">
<BarChart data={yearly} margin={{ top: 8, right: 12, bottom: 0, left: 4 }}>
<CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#eef0f5" />
<XAxis dataKey="month" tick={{ fontSize: 11 }} axisLine={false} tickLine={false} />
<YAxis
tick={{ fontSize: 11 }}
axisLine={false}
tickLine={false}
tickFormatter={(v: number) => (v >= 10000 ? `${(v / 10000).toFixed(1)}万` : String(v))}
/>
<RTooltip formatter={(v: any) => rmb(v)} />
<Legend wrapperStyle={{ fontSize: 12 }} />
<Bar dataKey="个人" stackId="a" fill="#ff9c8a" radius={[0, 0, 0, 0]} />
<Bar dataKey="公司" stackId="a" fill="#2f54eb" radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</div>
)}
</Card>
</div>
)
}
/* ------------------------------------------------------------- 福利发放 -- */
function BenefitGrants() {
const q = useSelfBenefits()
// hooks 必须无条件执行:状态先声明,再走 loading / error 早退
const [cat, setCat] = useState('')
const d: any = q.data || {}
const all: any[] = d.items || []
const cats = useMemo(
() => Array.from(new Set(all.map((x: any) => x.category).filter(Boolean))) as string[],
[all],
)
const items = useMemo(() => (cat ? all.filter((x) => x.category === cat) : all), [all, cat])
if (q.isFetching && !q.data) return <SelfLoading />
if (q.isError) return <SelfProblem error={q.error} />
// 合计随筛选变化,口径与 H5 及管理端福利列表一致
const total = Math.round(items.reduce((a, x) => a + Number(x.amount || 0), 0) * 100) / 100
const cnt = items.reduce((a, x) => a + Number(x.count || 0), 0)
return (
<div>
<div style={{ marginBottom: 14 }}>
<Segmented
value={cat}
onChange={(v) => setCat(String(v))}
options={[
{ label: '全部类别', value: '' },
...cats.map((c) => ({
label: `${CAT_TEXT[c] || c} (${all.filter((x) => x.category === c).length})`,
value: c,
})),
]}
/>
</div>
<div className="stat-grid" style={{ gridTemplateColumns: 'repeat(3, minmax(0,1fr))' }}>
<div className="stat">
<div className="stat-label">
{d.year || new Date().getFullYear()} 年度
{cat ? `「${CAT_TEXT[cat] || cat}」` : ''}福利合计
</div>
<div className="stat-value num" style={{ color: '#f59e0b' }}>
{rmb(cat ? total : d.total_amount)}
</div>
</div>
<div className="stat">
<div className="stat-label">福利项目数</div>
<div className="stat-value num">{items.length}</div>
</div>
<div className="stat">
<div className="stat-label">发放笔数</div>
<div className="stat-value num">{cat ? cnt : d.total_count || 0}</div>
</div>
</div>
{!all.length ? (
<Card variant="borderless" size="small" style={{ marginTop: 14 }}>
<SelfEmpty description="本年度还没有福利发放记录" />
</Card>
) : !items.length ? (
<Card variant="borderless" size="small" style={{ marginTop: 14 }}>
<SelfEmpty description="该类别下还没有福利发放记录" />
</Card>
) : (
<Row gutter={[14, 14]} style={{ marginTop: 14 }}>
{items.map((it) => (
<Col xs={24} xl={12} key={it.item_id}>
<Card
variant="borderless"
size="small"
styles={{ body: { padding: 14 } }}
title={
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<span
style={{
width: 34,
height: 34,
borderRadius: 10,
background: '#f2f5ff',
display: 'grid',
placeItems: 'center',
fontSize: 17,
}}
>
{BENEFIT_ICONS[it.category] || BENEFIT_ICONS[it.icon] || '🎁'}
</span>
<span>
<div style={{ fontSize: 14, fontWeight: 600 }}>{it.name}</div>
<div style={{ fontSize: 11, color: '#98a2b3', fontWeight: 400 }}>
{it.category ? `${CAT_TEXT[it.category] || it.category} · ` : ''}
{it.count} 笔 · 单位 {it.unit || '次'}
</div>
</span>
</div>
}
extra={
<Text strong className="num" style={{ color: '#f59e0b', fontSize: 16 }}>
{rmb(it.amount)}
</Text>
}
>
{(it.records || []).length ? (
<Table
rowKey="id"
size="small"
pagination={false}
dataSource={it.records}
columns={RECORD_COLS}
/>
) : (
<SelfEmpty description="该项目还没有发放明细" />
)}
</Card>
</Col>
))}
</Row>
)}
</div>
)
}
const RECORD_COLS: ColumnsType<any> = [
{
title: '所属月份',
dataIndex: 'month',
width: 130,
render: (v: any, r) => (
<span>
{v} 月
{r.quantity && r.quantity > 1 ? ` ×${r.quantity}` : ''}
{r.batch_label ? (
<Text type="secondary" style={{ fontSize: 11, marginLeft: 6 }}>
{r.batch_label}
</Text>
) : null}
</span>
),
},
{
title: '状态',
dataIndex: 'status',
width: 96,
render: (v: string) => {
const s = BENEFIT_RECORD_STATUS[v]
return (
<Tag bordered={false} style={{ color: s?.color || '#667085', background: `${s?.color || '#667085'}14` }}>
{s?.text || v}
</Tag>
)
},
},
{
title: '到账时间',
dataIndex: 'paid_at',
width: 110,
render: (v: string) => <Text type="secondary" style={{ fontSize: 12 }}>{v ? String(v).slice(0, 10) : '-'}</Text>,
},
{
title: '金额',
align: 'right',
render: (_, r) => (
<Text strong className="num">
{rmb(Number(r.amount || 0) * (Number(r.quantity || 1) || 1))}
</Text>
),
},
]
/* ------------------------------------------------------------- 假期额度 -- */
function LeaveQuota() {
const q = useSelfLeaveOptions()
if (q.isFetching && !q.data) return <SelfLoading />
if (q.isError) return <SelfProblem error={q.error} />
const types: any[] = q.data || []
if (!types.length) return <SelfEmpty description="尚未生成年度假期额度" />
return (
<Row gutter={[14, 14]}>
{types.map((t) => {
const total = Number(t.total || 0)
const used = Number(t.used || 0)
const frozen = Number(t.frozen || 0)
const unit = unitText(t.unit)
return (
<Col xs={24} md={12} xxl={8} key={t.id}>
<Card variant="borderless" size="small" styles={{ body: { padding: 14 } }}>
<SectionTitle
extra={
<span className="num" style={{ fontSize: 17, fontWeight: 700, color: t.color || '#2f54eb' }}>
{t.requires_balance ? t.remaining ?? 0 : '不限'}
<span style={{ fontSize: 11, fontWeight: 400, marginLeft: 2, color: '#98a2b3' }}>
{t.requires_balance ? unit : ''}
</span>
</span>
}
>
<span
style={{
display: 'inline-block',
width: 7,
height: 7,
borderRadius: '50%',
background: t.color || '#2f54eb',
marginRight: 7,
}}
/>
{t.name}
{!t.paid && (
<Tooltip title="该假期不带薪">
<Tag bordered={false} style={{ color: '#98a2b3', background: '#98a2b314', marginLeft: 6 }}>
无薪
</Tag>
</Tooltip>
)}
{t.requires_certificate && (
<Tag bordered={false} style={{ color: '#f59e0b', background: '#f59e0b14' }}>
需证明
</Tag>
)}
</SectionTitle>
{t.requires_balance && total > 0 && (
<>
<Progress
percent={Math.min((used / total) * 100, 100)}
showInfo={false}
size="small"
strokeColor={t.color || '#2f54eb'}
trailColor="#eef0f5"
/>
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: '#98a2b3', marginTop: 4 }}>
<span>
年度 {total} {unit}
</span>
<span>
已用 {used}
{frozen ? ` · 审批中 ${frozen}` : ''}
</span>
</div>
</>
)}
{t.description && (
<div style={{ fontSize: 11, color: '#c9ced8', marginTop: 8 }}>{t.description}</div>
)}
</Card>
</Col>
)
})}
</Row>
)
}

View File

@ -0,0 +1,426 @@
import { CheckCircleFilled, PlusOutlined } from '@ant-design/icons'
import { useQueryClient } from '@tanstack/react-query'
import {
Alert,
App,
Button,
Card,
Col,
DatePicker,
Form,
Input,
Progress,
Row,
Segmented,
Space,
Table,
Tooltip,
Typography,
Upload,
} from 'antd'
import type { ColumnsType } from 'antd/es/table'
import type { UploadFile } from 'antd/es/upload/interface'
import dayjs, { type Dayjs } from 'dayjs'
import { useMemo, useState } from 'react'
import {
useLeaveApply,
useLeaveCancel,
useSelfLeave,
useSelfLeaveOptions,
useUploadLeaveCertificate,
} from '../../api/self'
import { statusHex } from '../../api/defs'
import EmptyBlock from '../../components/EmptyBlock'
import {
LEAVE_FILTERS,
LEAVE_STATUS,
PERIOD_OPTIONS,
PERIOD_TEXT,
dstr,
dtstr,
leaveDays,
unitText,
} from '../../lib/selfLabels'
import { BalanceBar, ColorTag, Dot, SelfEmpty, SelfLoading, SelfProblem } from './_shared'
const { Text, Paragraph } = Typography
/**
* 请假(Web 版)。
*
* 与 H5 `/m/leave` 同一套规则:类型卡显示年度余额、证明材料必传、
* 同日半天记 0.5 天、校验文案逐字一致;只是把移动端的两步 CapsuleTabs
* 换成桌面端的「左填表 + 右记录」。
*/
export default function SelfLeave() {
const { message } = App.useApp()
const options = useSelfLeaveOptions()
const types: any[] = options.data || []
const [typeId, setTypeId] = useState<number | null>(null)
const [fileList, setFileList] = useState<UploadFile[]>([])
const [form] = Form.useForm()
const upload = useUploadLeaveCertificate()
const apply = useLeaveApply(() => {
message.success('已提交,等待审批')
form.resetFields()
setFileList([])
})
const type = types.find((t) => t.id === typeId) || null
const watched = Form.useWatch(['range', 'period'], form) as any
const range: [Dayjs, Dayjs] | undefined = Form.useWatch('range', form)
const period: string = watched?.period || 'full'
const start = range?.[0]?.format('YYYY-MM-DD') || ''
const end = range?.[1]?.format('YYYY-MM-DD') || ''
const days = leaveDays(start, end, period)
const submit = async () => {
const values = await form.validateFields()
const [s, e] = values.range as [Dayjs, Dayjs]
const sd = s.format('YYYY-MM-DD')
const ed = e.format('YYYY-MM-DD')
const pd = values.period || 'full'
if (!typeId) return message.warning('请选择请假类型')
if (!sd || !ed) return message.warning('请选择请假日期')
if (leaveDays(sd, ed, pd) <= 0) return message.warning('结束日期不能早于开始日期')
if (!String(values.reason || '').trim()) return message.warning('请填写请假事由')
if (type?.requires_certificate && !fileList.length)
return message.warning(`「${type.name}」需要上传证明材料`)
apply.mutate({
leave_type_id: typeId,
start_date: sd,
end_date: ed,
period: pd,
reason: String(values.reason).trim(),
days: leaveDays(sd, ed, pd),
attachment_id: fileList[0]?.response?.id ?? undefined,
})
}
return (
<Row gutter={[14, 14]}>
<Col xs={24} xl={14}>
<Card
variant="borderless"
title="选择假期类型"
styles={{ body: { paddingTop: 14 } }}
extra={<Text type="secondary" style={{ fontSize: 12 }}>额度随每年 1 月生成的假期方案更新</Text>}
>
{options.isError ? (
<SelfProblem error={options.error} />
) : options.isFetching && !options.data ? (
<SelfLoading />
) : !types.length ? (
<SelfEmpty description="尚未配置可用假期类型,请联系 HR" />
) : (
<Row gutter={[10, 10]}>
{types.map((t) => {
const on = typeId === t.id
const empty = t.requires_balance && Number(t.remaining ?? 0) <= 0
return (
<Col xs={12} md={8} key={t.id}>
<Card
size="small"
hoverable
onClick={() => {
setTypeId(t.id)
if (empty) message.warning(`${t.name} 本年度余额已用完`)
}}
style={{
borderColor: on ? t.color || '#2f54eb' : undefined,
background: on ? `${t.color || '#2f54eb'}0a` : undefined,
}}
styles={{ body: { padding: '10px 12px' } }}
>
<div style={{ fontSize: 13, fontWeight: 600 }}>
<Dot color={t.color}>{t.name}</Dot>
</div>
<div style={{ fontSize: 12, color: '#98a2b3', margin: '4px 0 6px' }}>
{t.requires_balance
? `剩余 ${t.remaining ?? 0} ${unitText(t.unit)} / 共 ${t.total ?? 0}`
: '不占用额度'}
{!t.paid ? ' · 无薪' : ''}
{t.requires_certificate ? ' · 需证明' : ''}
</div>
{t.requires_balance && Number(t.total) > 0 && (
<BalanceBar total={Number(t.total)} used={Number(t.used)} frozen={Number(t.frozen)} color={t.color} />
)}
</Card>
</Col>
)
})}
</Row>
)}
{type && (
<Alert
style={{ marginTop: 12 }}
type="info"
message={
<span style={{ fontSize: 12 }}>
{type.description || '按公司假期制度执行'} · {type.paid ? '带薪假期' : '非带薪假期'}
{type.requires_balance ? ` · 扣减年度额度(剩余 ${type.remaining ?? '-'})` : ' · 不占用额度'}
{type.requires_certificate ? ' · 需上传证明材料' : ''}
{type.max_days_per_year ? ` · 年度上限 ${type.max_days_per_year} 天` : ''}
</span>
}
/>
)}
</Card>
<Card variant="borderless" title="发起请假" style={{ marginTop: 14 }}>
<Form
form={form}
layout="vertical"
requiredMark={false}
initialValues={{ range: { start: dayjs(), end: dayjs(), period: 'full' } }}
>
<Form.Item label="请假日期" required>
<DatePicker.RangePicker
style={{ width: '100%' }}
value={(() => {
const v = form.getFieldValue('range')
return v?.start && v?.end ? [v.start, v.end] : undefined
})() as any}
onChange={(v) => {
const cur = form.getFieldValue('range') || {}
form.setFieldValue('range', { ...cur, start: v?.[0], end: v?.[1] })
}}
/>
</Form.Item>
<Form.Item label="时段">
<Segmented
options={PERIOD_OPTIONS.map((p) => ({ label: p.label, value: p.value }))}
value={period}
onChange={(v) => {
const cur = form.getFieldValue('range') || {}
form.setFieldValue('range', { ...cur, period: v })
}}
/>
<Text type="secondary" style={{ fontSize: 12, marginLeft: 12 }}>
预计 <b className="num" style={{ color: '#2f54eb' }}>{days}</b> 天 · 最终天数以审批人核准为准
</Text>
</Form.Item>
<Form.Item
name="reason"
label="请假事由"
rules={[{ required: true, message: '请填写请假事由' }]}
>
<Input.TextArea rows={3} maxLength={500} showCount placeholder="请填写请假原因,便于主管审批" />
</Form.Item>
<Form.Item
label={type?.requires_certificate ? '证明材料(必传)' : '证明材料'}
help={type?.requires_certificate ? '该假期类型按制度要求必须附证明材料' : undefined}
>
<Upload
maxCount={1}
fileList={fileList}
accept=".jpg,.jpeg,.png,.pdf,.doc,.docx"
beforeUpload={() => false}
onChange={(info) => {
const f = info.fileList.slice(-1)[0]
if (!f) {
setFileList([])
return
}
setFileList([f])
if (f.originFileObj) {
upload.mutate(f.originFileObj as File, {
onSuccess: (r) => {
message.success('附件已上传')
setFileList([{ ...f, status: 'done', response: r }])
},
onError: () => {
message.error('附件上传失败,请重试')
setFileList([{ ...f, status: 'error' }])
},
})
}
}}
onRemove={() => setFileList([])}
>
<Button icon={<PlusOutlined />} loading={upload.isPending}>
上传附件
</Button>
</Upload>
</Form.Item>
<Space>
<Button type="primary" loading={apply.isPending} onClick={submit}>
提交请假申请
</Button>
<Text type="secondary" style={{ fontSize: 12 }}>
提交后可在下方「我的请假记录」中撤销
</Text>
</Space>
</Form>
</Card>
</Col>
<Col xs={24} xl={10}>
<Records />
</Col>
</Row>
)
}
/* ------------------------------------------------------------ 请假记录 -- */
function Records() {
const { message, modal } = App.useApp()
const qc = useQueryClient()
const [status, setStatus] = useState('')
const [kw, setKw] = useState('')
const q = useSelfLeave(status)
const cancel = useLeaveCancel()
const rows: any[] = q.data?.items || []
const items = useMemo(() => {
const k = kw.trim().toLowerCase()
if (!k) return rows
return rows.filter((x) =>
[x.leave_type_name, x.reason, x.approver_name, x.status].some((v) =>
String(v ?? '').toLowerCase().includes(k),
),
)
}, [rows, kw])
const columns: ColumnsType<any> = [
{
title: '类型',
dataIndex: 'leave_type_name',
width: 110,
render: (v, r) => <Dot color={r.color}>{v}</Dot>,
},
{
title: '起止日期',
dataIndex: 'start_date',
width: 190,
render: (_, r) => (
<span style={{ fontSize: 12 }}>
{dstr(r.start_date)} ~ {dstr(r.end_date)}
<Text type="secondary" style={{ fontSize: 12, marginLeft: 4 }}>
{PERIOD_TEXT[r.period] || '全天'}
</Text>
</span>
),
},
{
title: '天数',
dataIndex: 'days',
width: 70,
align: 'right',
render: (v) => <span className="num" style={{ fontWeight: 600 }}>{v}</span>,
},
{
title: '状态',
dataIndex: 'status',
width: 90,
render: (v) => <ColorTag color={statusHex(v)}>{LEAVE_STATUS[v]?.text || v}</ColorTag>,
},
{
title: '审批',
dataIndex: 'approver_name',
width: 140,
render: (v, r) => (
<div style={{ fontSize: 12, color: '#667085' }}>
{v || '等待主管审批'}
{r.approved_at ? <div style={{ color: '#98a2b3' }}>{dtstr(r.approved_at)}</div> : null}
{r.comment ? (
<Tooltip title={`审批意见:${r.comment}`}>
<span style={{ color: '#f59e0b' }}>
<CheckCircleFilled style={{ marginRight: 4 }} />
有意见
</span>
</Tooltip>
) : null}
</div>
),
},
{
title: '事由',
dataIndex: 'reason',
ellipsis: true,
render: (v) => <span style={{ fontSize: 12, color: '#667085' }}>{v || '—'}</span>,
},
{
title: '操作',
key: 'op',
width: 70,
render: (_, r) =>
r.status === 'pending' ? (
<Button
type="link"
size="small"
danger
onClick={() =>
modal.confirm({
title: '确认撤销这次请假申请?',
okText: '撤销',
okButtonProps: { danger: true },
cancelText: '取消',
onOk: () =>
cancel.mutateAsync(r.id).then(() => {
message.success('已撤销')
qc.invalidateQueries({ queryKey: ['self-leave'] })
}),
})
}
>
撤销
</Button>
) : null,
},
]
return (
<Card
variant="borderless"
title="我的请假记录"
extra={
<Space size={8}>
<Segmented
size="small"
value={status}
onChange={(v) => setStatus(String(v))}
options={LEAVE_FILTERS.map((f) => ({
label: f.key ? f.label : `全部${q.data?.total ? ` ${q.data.total}` : ''}`,
value: f.key,
}))}
/>
</Space>
}
styles={{ body: { paddingTop: 12 } }}
>
<Input.Search
allowClear
value={kw}
onChange={(e) => setKw(e.target.value)}
placeholder="搜请假类型 / 事由 / 审批人"
style={{ marginBottom: 12 }}
/>
{q.isError ? (
<SelfProblem error={q.error} />
) : q.isFetching && !rows.length ? (
<SelfLoading />
) : (
<Table
rowKey="id"
size="small"
columns={columns}
dataSource={items}
pagination={{ pageSize: 10, size: 'small', hideOnSinglePage: true }}
scroll={{ x: 760 }}
locale={{
emptyText: rows.length ? (
<EmptyBlock description="没有符合筛选条件的请假记录" />
) : (
<EmptyBlock description="还没有请假记录" />
),
}}
/>
)}
<Paragraph type="secondary" style={{ fontSize: 12, marginTop: 8, marginBottom: 0 }}>
请假额度、审批链路由「福利保险 → 假期管理」配置;如需修改历史请假,请联系审批人驳回后重新提交。
</Paragraph>
</Card>
)
}

View File

@ -0,0 +1,381 @@
import { WalletOutlined } from '@ant-design/icons'
import { Card, Col, Drawer, Row, Segmented, Select, Space, Spin, Table, Tag, Tooltip, Typography } from 'antd'
import type { ColumnsType } from 'antd/es/table'
import { useMemo, useState } from 'react'
import { statusHex } from '../../api/defs'
import { useSelfPayslip, useSelfPayslips } from '../../api/self'
import { PAYSLIP_STATUS_TEXT, PAYSLIP_STATUS_TONE, QUARTERS, dtstr, rmb } from '../../lib/selfLabels'
import { MoneyGroup, MoneyRow, SelfEmpty, SelfLoading, SelfProblem } from './_shared'
const { Text } = Typography
/**
* 我的工资条(Web 版)。
*
* 与 H5 `/m/payslips` 同一份数据、同一套口径:年份 + 季度筛选、
* 「筛选影响合计」的年度四项指标、展开后的收入/扣款/五险一金三段明细,
* 以及"较上月"的环比提示。H5 用折叠卡片,这里用表格 + 抽屉,
* 但金额、状态文案、配色全部来自 `lib/selfLabels`,两端逐字一致。
*/
export default function SelfPayslips() {
const THIS = new Date().getFullYear()
const [year, setYear] = useState(THIS)
const [quarter, setQuarter] = useState('')
const [openId, setOpenId] = useState<number | null>(null)
const q = useSelfPayslips(year)
const all: any[] = q.data?.items || []
const years: number[] = q.data?.years?.length ? q.data.years : [THIS]
const months = QUARTERS.find((x) => x.key === quarter)?.months || []
const items = useMemo(
() => (months.length ? all.filter((x) => months.includes(Number(x.month))) : all),
[all, months],
)
// 合计口径与 H5 一致:选中季度时按季度重算,否则用接口给的年度合计
const annual = useMemo(() => {
if (!quarter) return q.data?.annual || {}
const sum = (k: string) => Math.round(items.reduce((a, x) => a + Number(x[k] || 0), 0) * 100) / 100
return {
gross: sum('gross'),
net: sum('net'),
tax: sum('tax'),
insurance: sum('insurance_personal'),
months: items.length,
}
}, [items, quarter, q.data])
if (q.isLoading) return <SelfLoading />
if (q.isError)
return (
<Card variant="borderless">
<SelfProblem error={q.error} />
</Card>
)
const cols: ColumnsType<any> = [
{
title: '工资期间',
dataIndex: 'period_label',
width: 170,
render: (v: string, r) => (
<Space size={8}>
<Text strong>{v || r.period}</Text>
<Tag bordered={false} color={statusHex(PAYSLIP_STATUS_TONE[r.status] || r.status)}>
{PAYSLIP_STATUS_TEXT[r.status] || r.status}
</Tag>
</Space>
),
},
{
title: '出勤(天)',
width: 130,
render: (_, r) => (
<span className="num">
{r.actual_days ?? '-'} / {r.working_days ?? '-'}
</span>
),
},
{
title: '应发合计',
dataIndex: 'gross',
align: 'right',
width: 130,
render: (v: number) => <span className="num">{rmb(v)}</span>,
},
{
title: '个人所得税',
dataIndex: 'tax',
align: 'right',
width: 120,
render: (v: number) => <span className="num" style={{ color: '#f59e0b' }}>{rmb(v)}</span>,
},
{
title: '社保公积金(个人)',
dataIndex: 'insurance_personal',
align: 'right',
width: 160,
render: (v: number) => <span className="num" style={{ color: '#ef4444' }}>{rmb(v)}</span>,
},
{
title: '累计计税收入',
dataIndex: 'taxable_cumulative',
align: 'right',
width: 140,
render: (v: number) => (
<Tooltip title="个税按累计预扣法计算,此处为年度累计应纳所得额">
<span className="num" style={{ color: '#98a2b3' }}>
{Number(v || 0).toLocaleString('zh-CN', { maximumFractionDigits: 0 })}
</span>
</Tooltip>
),
},
{
title: '实发工资',
dataIndex: 'net',
align: 'right',
width: 140,
render: (v: number) => (
<Text strong className="num" style={{ color: '#2f54eb' }}>
{rmb(v)}
</Text>
),
},
{
title: '发放时间',
dataIndex: 'published_at',
width: 160,
render: (v: string) => <Text type="secondary" style={{ fontSize: 12 }}>{dtstr(v)}</Text>,
},
{
title: '',
width: 90,
fixed: 'right',
render: (_, r) => (
<a onClick={() => setOpenId(r.id)}>查看明细</a>
),
},
]
const stats = [
{ k: '应发合计', v: annual.gross, c: '#1d2939' },
{ k: '个税合计', v: annual.tax, c: '#f59e0b' },
{ k: '社保公积金(个人)', v: annual.insurance, c: '#ef4444' },
{ k: '发薪月数', v: annual.months, c: '#2f54eb', plain: true },
]
return (
<div>
<Card
variant="borderless"
styles={{ body: { paddingBlock: 14 } }}
title={
<Space size={12}>
<Select
size="small"
value={year}
style={{ width: 110 }}
onChange={(v) => {
setYear(v)
setOpenId(null)
}}
options={years.map((y) => ({ value: y, label: `${y} 年` }))}
/>
<Segmented
size="small"
value={quarter}
onChange={(v) => setQuarter(String(v))}
options={QUARTERS.map((x) => ({
label: months2Label(x.label, all, x.months),
value: x.key,
}))}
/>
</Space>
}
extra={
<Text type="secondary" style={{ fontSize: 12 }}>
工资条数据由薪酬核算批次自动生成 · 如对金额有疑问请联系人力行政部
</Text>
}
>
<div className="stat-grid">
{stats.map((s) => (
<div className="stat" key={s.k}>
<div className="stat-label">
{year} 年
{QUARTERS.find((x) => x.key === quarter)?.label || '全年'}
{s.k}
</div>
<div className="stat-value num" style={{ color: s.c, fontSize: 22 }}>
{s.plain ? Number(s.v || 0) : rmb(s.v)}
</div>
</div>
))}
</div>
</Card>
<Card variant="borderless" style={{ marginTop: 14 }} title={`${year} 年工资明细`}>
{!all.length ? (
<SelfEmpty description={`${year} 年暂无已发布工资条`} />
) : (
<Table
rowKey="id"
size="small"
columns={cols}
dataSource={items}
scroll={{ x: 1240 }}
pagination={false}
locale={{ emptyText: <SelfEmpty description={`${year} 年该季度暂无工资条`} /> }}
onRow={(r) => ({ onClick: () => setOpenId(r.id), style: { cursor: 'pointer' } })}
/>
)}
</Card>
<PayslipDrawer id={openId} onClose={() => setOpenId(null)} />
</div>
)
}
/** 季度胶囊带上条数,和 H5 的 MChips 一致 */
function months2Label(label: string, all: any[], months: number[]) {
if (!months.length) return label
const n = all.filter((x) => months.includes(Number(x.month))).length
return `${label} (${n})`
}
/**
* 工资条详情抽屉:三段结构与 H5 折叠面板逐段对应
* (收入 → 扣款与社保 → 五险一金明细),字段、配色、说明文案同源。
*/
function PayslipDrawer({ id, onClose }: { id: number | null; onClose: () => void }) {
const q = useSelfPayslip(id, id != null)
const it = q.data
const amounts: Record<string, number> = it?.amounts || {}
const labels: Record<string, string> = it?.labels || {}
const insurance: Record<string, any> = it?.insurance || {}
const diff = it?.diff
const insCols: ColumnsType<any> = [
{ title: '项目', dataIndex: 'name', width: 90 },
{
title: '缴存基数',
dataIndex: 'base',
align: 'right',
render: (v: number) => (
<span className="num" style={{ color: '#98a2b3' }}>
{Number(v || 0).toLocaleString('zh-CN', { maximumFractionDigits: 0 })}
</span>
),
},
{
title: '个人比例',
dataIndex: 'personal_rate',
align: 'right',
render: (v: number) => <span className="num">{v != null ? `${(v * 100).toFixed(2)}%` : '-'}</span>,
},
{
title: '个人',
dataIndex: 'personal',
align: 'right',
render: (v: number) => (
<span className="num" style={{ color: '#ef4444' }}>
{rmb(v)}
</span>
),
},
{
title: '公司比例',
dataIndex: 'company_rate',
align: 'right',
render: (v: number) => <span className="num">{v != null ? `${(v * 100).toFixed(2)}%` : '-'}</span>,
},
{
title: '公司',
dataIndex: 'company',
align: 'right',
render: (v: number) => (
<span className="num" style={{ color: '#667085' }}>
{rmb(v)}
</span>
),
},
]
return (
<Drawer
open={id != null}
onClose={onClose}
width={620}
title={
<Space>
<WalletOutlined style={{ color: '#16a34a' }} />
{it?.period_label || it?.period || '工资条明细'}
{it?.status && (
<Tag bordered={false} color={statusHex(PAYSLIP_STATUS_TONE[it.status] || it.status)}>
{PAYSLIP_STATUS_TEXT[it.status] || it.status}
</Tag>
)}
</Space>
}
styles={{ body: { background: '#f7f8fb' } }}
>
{q.isLoading ? (
<div style={{ textAlign: 'center', padding: 40 }}>
<Spin />
</div>
) : q.isError ? (
<SelfProblem error={q.error} />
) : it ? (
<>
<div className="stat-grid" style={{ gridTemplateColumns: 'repeat(2,1fr)' }}>
<div className="stat">
<div className="stat-label">实发工资</div>
<div className="stat-value num" style={{ color: '#2f54eb' }}>
{rmb(it.net)}
</div>
{diff != null && (
<div style={{ fontSize: 12, color: diff >= 0 ? '#16a34a' : '#ef4444' }}>
{diff >= 0 ? '↑' : '↓'} 较上月 {rmb(Math.abs(diff))}
</div>
)}
</div>
<div className="stat">
<div className="stat-label">应发合计</div>
<div className="stat-value num">{rmb(it.gross)}</div>
<div style={{ fontSize: 12, color: '#98a2b3' }}>
出勤 {it.actual_days ?? '-'} / {it.working_days ?? '-'} 天
</div>
</div>
</div>
<Card variant="borderless" size="small" title="收入" style={{ marginTop: 14 }}>
{Object.keys(amounts)
.filter((c) => Number(amounts[c]) > 0)
.map((c) => (
<MoneyRow key={c} k={labels[c] || c} v={rmb(amounts[c])} color="#16a34a" border />
))}
<MoneyRow k="应发合计" v={rmb(it.gross)} strong border />
</Card>
<Card variant="borderless" size="small" title="扣款与社保" style={{ marginTop: 14 }}>
<MoneyRow k="个人所得税" v={rmb(it.tax)} color="#f59e0b" border />
<MoneyRow k="社保公积金(个人)" v={rmb(it.insurance_personal)} color="#ef4444" border />
{Number(it.deductions) > 0 && (
<MoneyRow k="其他扣款" v={rmb(it.deductions)} color="#ef4444" border />
)}
<MoneyRow k="公司承担(社保公积金)" v={rmb(it.insurance_company)} color="#667085" border />
<MoneyRow k="实发工资" v={rmb(it.net)} strong color="#2f54eb" border />
{it.taxable_cumulative != null && (
<div style={{ fontSize: 11, color: '#98a2b3', marginTop: 8 }}>
本年度累计计税收入 {Number(it.taxable_cumulative || 0).toLocaleString('zh-CN', { maximumFractionDigits: 0 })} 元
{it.special_deduction ? ` · 专项附加扣除 ${rmb(it.special_deduction)} / 月` : ''}
{' · 个税按累计预扣法计算'}
</div>
)}
</Card>
{Object.keys(insurance).length > 0 && (
<Card variant="borderless" size="small" title="五险一金明细" style={{ marginTop: 14 }}>
<Table
rowKey={(r: any) => r.name || r.code}
size="small"
pagination={false}
columns={insCols}
dataSource={Object.values(insurance)}
/>
</Card>
)}
<MoneyGroup title="">
{it.published_at && (
<div style={{ fontSize: 11, color: '#c9ced8', marginTop: 6 }}>
发放时间:{dtstr(it.published_at)}
</div>
)}
</MoneyGroup>
</>
) : null}
</Drawer>
)
}

View File

@ -0,0 +1,789 @@
import { BookOutlined, EditOutlined } from '@ant-design/icons'
import {
App,
Avatar,
Button,
Card,
Col,
Descriptions,
Input,
Row,
Segmented,
Space,
Table,
Tabs,
Tag,
Timeline,
Typography,
} from 'antd'
import type { ColumnsType } from 'antd/es/table'
import { useState } from 'react'
import {
useDocTypeDict,
useDocumentApply,
useNotificationsRead,
useProfileRequest,
useProfileRequestCancel,
useSelfDocuments,
useSelfHome,
useSelfNotifications,
useSelfProfile,
useSelfSalaryStandard,
} from '../../api/self'
import {
CONTRACT_STATUS_COLOR,
CONTRACT_STATUS_TEXT,
DOC_STATUS_COLOR,
DOC_STATUS_TEXT,
EMP_STATUS_COLOR,
EMP_STATUS_TEXT,
PROFILE_FIELD_LABELS,
PROFILE_REQ_STATUS,
SALARY_ITEM_LABELS,
dstr,
dtstr,
rmb,
} from '../../lib/selfLabels'
import { ColorTag, KV, MoneyRow, SelfEmpty, SelfLoading, SelfProblem, SectionTitle } from './_shared'
const { Text, Title } = Typography
/**
* 个人中心(Web 版)。
*
* Tab 划分与 H5 `/m/profile` 一一对应:我的信息 / 变更申请 / 合同与薪资 / 证明与消息。
* 关键一致性:两端都只允许「提交变更申请」而不是直接改档案(同一个
* `/self/profile-requests`),提示语逐字相同;薪资标准、报销标准、合同、
* 证明、消息读的是同一组接口,任何一端提交后另一端刷新即可看到。
*/
export default function SelfProfile() {
const home = useSelfHome()
const profile = useSelfProfile()
const emp = { ...(home.data?.employee || {}), ...(profile.data?.employee || {}) }
// 管理员等没有员工档案的账号:身份卡退化成登录账号,不再渲染一排「- / 0 天 / 正式」
const bound = !!emp.work_no
if (profile.isError)
return (
<Card variant="borderless">
<SelfProblem error={profile.error} />
</Card>
)
if (profile.isFetching && !profile.data) return <SelfLoading />
return (
<div>
<IdentityCard emp={emp} bound={bound} home={home.data} />
<Card variant="borderless" style={{ marginTop: 14 }} styles={{ body: { paddingTop: 6 } }}>
<Tabs
destroyOnHidden
items={[
{
key: 'info',
label: '我的信息',
children: <InfoTab profile={profile.data || {}} />,
},
{
key: 'requests',
label: `变更申请${(profile.data?.requests || []).length ? ` (${profile.data.requests.length})` : ''}`,
children: <RequestsTab requests={profile.data?.requests || []} />,
},
{
key: 'salary',
label: '合同与薪资',
children: <SalaryTab contracts={profile.data?.contracts || []} />,
},
{ key: 'more', label: '证明与消息', children: <MoreTab /> },
]}
/>
</Card>
</div>
)
}
/* ------------------------------------------------------------- 身份卡片 -- */
function IdentityCard({ emp, bound, home }: { emp: any; bound: boolean; home: any }) {
return (
<Card variant="borderless" styles={{ body: { padding: 18 } }}>
<Row gutter={[18, 14]} align="middle">
<Col flex="none">
<Avatar
size={62}
src={emp.avatar || undefined}
style={{
background: 'linear-gradient(140deg,#2f54eb,#13c2c2)',
fontSize: 24,
fontWeight: 600,
}}
>
{(emp.name || '员').slice(0, 1)}
</Avatar>
</Col>
<Col flex="auto" style={{ minWidth: 0 }}>
<Space size={10} align="center">
<Title level={4} style={{ margin: 0 }}>
{emp.name || '未命名'}
</Title>
<Text type="secondary">{emp.work_no || ''}</Text>
{bound && (
<Tag bordered={false} style={{ color: EMP_STATUS_COLOR[emp.status] || '#98a2b3', background: `${EMP_STATUS_COLOR[emp.status] || '#98a2b3'}14` }}>
{EMP_STATUS_TEXT[emp.status] || emp.status}
</Tag>
)}
</Space>
<div style={{ marginTop: 6, color: '#667085', fontSize: 13 }}>
{bound
? `${emp.department_name || '-'} · ${emp.position_name || '-'} · ${emp.job_level_name || '-'}`
: '系统账号 · 未绑定员工档案'}
</div>
</Col>
{bound && (
<Col flex="none">
<div className="stat-grid" style={{ gridTemplateColumns: 'repeat(3,minmax(88px,1fr))', gap: 10 }}>
{[
{ k: '入职日期', v: dstr(emp.hire_date) },
{
k: '司龄',
v: home?.employee?.tenure_label || `${home?.employee?.tenure_days ?? 0} 天`,
},
{ k: '用工形式', v: emp.engage_form || '正式' },
].map((x) => (
<div key={x.k} style={{ background: '#f7f9ff', borderRadius: 10, padding: '9px 10px', textAlign: 'center' }}>
<div style={{ fontSize: 13, fontWeight: 600 }}>{x.v}</div>
<div style={{ fontSize: 10, color: '#98a2b3', marginTop: 2 }}>{x.k}</div>
</div>
))}
</div>
</Col>
)}
</Row>
</Card>
)
}
/* ------------------------------------------------------------- 我的信息 -- */
function InfoTab({ profile }: { profile: any }) {
const { message } = App.useApp()
const fields: any[] = profile.editable_fields || []
const emp = profile.employee || {}
const [editing, setEditing] = useState(false)
const [draft, setDraft] = useState<Record<string, string>>({})
const [reason, setReason] = useState('')
const req = useProfileRequest(() => {
message.success('已提交审核,通过后生效')
setEditing(false)
setDraft({})
setReason('')
})
const changedCount = fields.filter((f) => String(draft[f.name] ?? '') !== String(f.value ?? '')).length
const start = () => {
const d: Record<string, string> = {}
fields.forEach((f) => (d[f.name] = f.value ?? ''))
setDraft(d)
setReason('')
setEditing(true)
}
const submit = () => {
const changes: Record<string, string> = {}
fields.forEach((f) => {
if (String(draft[f.name] ?? '') !== String(f.value ?? '')) changes[f.name] = String(draft[f.name] ?? '')
})
req.mutate({ changes, reason: reason || undefined })
}
return (
<Row gutter={[14, 14]}>
<Col xs={24} xl={14}>
<Card
variant="borderless"
size="small"
title="联系与基础信息"
extra={
!editing && (
<Button size="small" type="link" icon={<EditOutlined />} onClick={start}>
修改资料
</Button>
)
}
>
{editing ? (
<>
<Row gutter={[12, 10]}>
{fields.map((f) => (
<Col xs={24} md={12} key={f.name}>
<Text type="secondary" style={{ fontSize: 12 }}>
{f.label}
</Text>
<Input
style={{ marginTop: 4 }}
value={draft[f.name] ?? ''}
placeholder={`请填写${f.label}`}
onChange={(e) => setDraft({ ...draft, [f.name]: e.target.value })}
/>
</Col>
))}
</Row>
<div style={{ marginTop: 12 }}>
<Text type="secondary" style={{ fontSize: 12 }}>
变更原因(选填)
</Text>
<Input
style={{ marginTop: 4 }}
value={reason}
placeholder="如:搬家更换住址"
onChange={(e) => setReason(e.target.value)}
/>
</div>
<Space style={{ marginTop: 14 }}>
<Button onClick={() => setEditing(false)}>取消</Button>
<Button type="primary" disabled={!changedCount} loading={req.isPending} onClick={submit}>
提交审核
</Button>
</Space>
<div style={{ fontSize: 12, color: '#98a2b3', marginTop: 10 }}>
个人档案不允许直接修改。提交后将生成 HR 待办,审核通过才会写入档案({changedCount} 项变更)。
</div>
</>
) : (
<div className="info-grid">
{fields.map((f) => (
<KV
key={f.name}
k={f.label}
v={f.value || <span style={{ color: '#c9ced8' }}>未填写</span>}
/>
))}
</div>
)}
</Card>
{!editing && (
<Card variant="borderless" size="small" title="工作信息" style={{ marginTop: 14 }}>
<div className="info-grid">
<KV k="所属部门" v={emp.department_name || '-'} />
<KV k="职位 / 职级" v={`${emp.position_name || '-'} · ${emp.job_level_name || '-'}`} />
<KV k="最高学历" v={`${emp.highest_degree || '-'}${emp.school ? ` · ${emp.school}` : ''}`} />
<KV k="毕业专业" v={emp.specialty || '-'} />
<KV
k="员工标签"
v={
(emp.tags || []).length ? (
<span>
{(emp.tags || []).map((t: string) => (
<ColorTag key={t}>{t}</ColorTag>
))}
</span>
) : (
'-'
)
}
/>
</div>
</Card>
)}
</Col>
<Col xs={24} xl={10}>
<Card variant="borderless" size="small" title="教育经历">
{(profile.educations || []).length ? (
<Timeline
items={(profile.educations || []).map((e: any) => ({
color: e.is_highest ? 'blue' : 'gray',
children: (
<div>
<div style={{ fontWeight: 500 }}>{e.school}</div>
<div style={{ fontSize: 12, color: '#98a2b3', marginTop: 2 }}>
{e.major} · {e.degree}
{e.is_highest ? ' · 最高学历' : ''}
</div>
<div style={{ fontSize: 11, color: '#c9ced8', marginTop: 2 }}>
{dstr(e.start_date)} ~ {dstr(e.end_date)}
</div>
</div>
),
}))}
/>
) : (
<SelfEmpty description="暂无教育经历" />
)}
</Card>
<Card variant="borderless" size="small" title="家庭成员" style={{ marginTop: 14 }}>
{(profile.families || []).length ? (
<Table
rowKey={(_, i) => String(i)}
size="small"
pagination={false}
dataSource={profile.families}
columns={FAMILY_COLS}
/>
) : (
<SelfEmpty description="暂无家庭成员信息" />
)}
</Card>
</Col>
</Row>
)
}
const FAMILY_COLS: ColumnsType<any> = [
{
title: '姓名 / 关系',
render: (_, f) => (
<span>
{f.name}
<Text type="secondary" style={{ fontSize: 12 }}>
({f.relation})
</Text>
</span>
),
},
{ title: '联系电话', dataIndex: 'phone', width: 120, render: (v: string) => v || '-' },
{
title: '备注',
width: 96,
render: (_, f) => (f.is_emergency ? <ColorTag color="#f59e0b">紧急联系人</ColorTag> : '-'),
},
]
/* ----------------------------------------------------------- 变更申请 -- */
function RequestsTab({ requests }: { requests: any[] }) {
const { message, modal } = App.useApp()
const cancel = useProfileRequestCancel(() => message.success('已撤回'))
if (!requests.length) return <SelfEmpty description="还没有提交过信息变更申请" />
return (
<Row gutter={[14, 14]}>
{requests.map((r) => {
const st = PROFILE_REQ_STATUS[r.status] || { text: r.status, color: '#667085' }
return (
<Col xs={24} xl={12} key={r.id}>
<Card
variant="borderless"
size="small"
title={`资料变更 #${r.id}`}
extra={
<ColorTag color={st.color}>{st.text}</ColorTag>
}
>
<div>
{Object.entries(r.changes || {}).map(([k, v]: [string, any]) => {
const after = v && typeof v === 'object' && 'after' in v ? v.after : v
const before = v && typeof v === 'object' && 'before' in v ? v.before : null
return (
<div key={k} style={{ fontSize: 13, padding: '6px 0', borderTop: '1px dashed #eef0f5' }}>
<Text type="secondary" style={{ fontSize: 12 }}>
{PROFILE_FIELD_LABELS[k] || k}:
</Text>
<span style={{ color: '#98a2b3' }}>{before || '未填写'}</span>
{' → '}
<b>{String(after || '未填写')}</b>
</div>
)
})}
</div>
{r.reason && (
<div style={{ fontSize: 12, color: '#98a2b3', marginTop: 8 }}>原因:{r.reason}</div>
)}
{r.comment && (
<div style={{ fontSize: 12, marginTop: 8, background: '#f7f9ff', borderRadius: 8, padding: '7px 10px', color: '#475467' }}>
{r.approver_name ? `${r.approver_name}:` : ''}
{r.comment}
</div>
)}
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginTop: 10,
paddingTop: 8,
borderTop: '1px dashed #eef0f5',
}}
>
<Text type="secondary" style={{ fontSize: 11 }}>
{dtstr(r.created_at)}
</Text>
{r.status === 'pending' && (
<Button
size="small"
type="link"
danger
onClick={() =>
modal.confirm({
title: '撤回申请',
content: `确认撤回资料变更 #${r.id}?`,
okText: '撤回',
cancelText: '取消',
onOk: () =>
cancel.mutateAsync(r.id, {
onError: (e: any) => message.error(e?.message || '撤回失败'),
}),
})
}
>
撤回申请
</Button>
)}
</div>
</Card>
</Col>
)
})}
</Row>
)
}
/* ------------------------------------------------------- 合同与薪资标准 -- */
function SalaryTab({ contracts }: { contracts: any[] }) {
const std = useSelfSalaryStandard()
const d: any = std.data || {}
return (
<Row gutter={[14, 14]}>
<Col xs={24} xl={10}>
<Card variant="borderless" size="small" title="劳动合同">
{!contracts.length ? (
<SelfEmpty description="暂无合同记录" />
) : (
<Table
rowKey={(r: any) => r.contract_no || String(r.id)}
size="small"
pagination={false}
dataSource={contracts}
columns={CONTRACT_COLS}
/>
)}
</Card>
<Card
variant="borderless"
size="small"
style={{ marginTop: 14 }}
title={
<Space>
职级报销标准
{d.job_level_name && <ColorTag>{d.job_level_name}</ColorTag>}
</Space>
}
>
{!(d.expense_standards || []).length ? (
<SelfEmpty description="当前职级尚未配置报销标准" />
) : (
<div className="info-grid" style={{ gridTemplateColumns: '1fr' }}>
{(d.expense_standards || []).map((x: any) => (
<KV
key={x.project_name}
k={
<span>
{x.project_name}
{x.remark ? (
<span style={{ display: 'block', fontSize: 11, color: '#98a2b3', marginTop: 2 }}>
{x.remark}
</span>
) : null}
</span>
}
v={
<b className="num">
{rmb(x.limit_amount)} / {String(x.unit || '元').replace(/^元\//, '')}
</b>
}
/>
))}
</div>
)}
</Card>
</Col>
<Col xs={24} xl={14}>
<Card
variant="borderless"
size="small"
title="我的薪资标准"
extra={
d.configured ? (
<Text type="secondary" style={{ fontSize: 12 }}>
{d.plan_name} · {dstr(d.effective_date)} 起
</Text>
) : null
}
>
{std.isLoading ? (
<SelfLoading />
) : !d.configured ? (
<SelfEmpty description="尚未配置薪资标准,请联系人力行政部" />
) : (
<>
<div className="num" style={{ fontSize: 24, fontWeight: 700, margin: '4px 0 6px' }}>
{rmb(d.total)}
<span style={{ fontSize: 12, fontWeight: 400, color: '#98a2b3', marginLeft: 4 }}>/ 月(标准应发)</span>
</div>
{(d.items || []).map((x: any) => (
<MoneyRow key={x.code} k={SALARY_ITEM_LABELS[x.code] || x.code} v={rmb(x.amount)} border />
))}
<div style={{ marginTop: 10, paddingTop: 4 }}>
<div className="info-grid">
<KV k="代发银行" v={d.bank_name || '-'} />
<KV k="银行账号" v={<span className="mono">{d.bank_account || '-'}</span>} />
<KV k="专项附加扣除" v={<span className="num">{rmb(d.special_deduction)} / 月</span>} />
</div>
</div>
{(d.adjustments || []).length > 0 && (
<div style={{ marginTop: 12 }}>
<SectionTitle>近期调薪记录</SectionTitle>
<Timeline
items={(d.adjustments || []).map((a: any) => ({
color:
(a.new_total ?? a.new_amount ?? 0) >= (a.old_total ?? a.old_amount ?? 0)
? 'green'
: 'red',
children: (
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<span>
{a.reason || '调薪'}
<div style={{ fontSize: 11, color: '#98a2b3' }}>
{dstr(a.effective_date || a.created_at)}
</div>
</span>
<span
className="num"
style={{
color:
(a.new_total ?? a.new_amount ?? 0) >= (a.old_total ?? a.old_amount ?? 0)
? '#16a34a'
: '#ef4444',
fontWeight: 600,
}}
>
{rmb(a.new_total ?? a.new_amount)}
</span>
</div>
),
}))}
/>
</div>
)}
</>
)}
</Card>
</Col>
</Row>
)
}
const CONTRACT_COLS: ColumnsType<any> = [
{ title: '合同编号', dataIndex: 'contract_no', width: 150 },
{ title: '类型', dataIndex: 'contract_type', width: 110 },
{
title: '起止日期',
render: (_, c) => (
<span className="num" style={{ fontSize: 12 }}>
{dstr(c.start_date)} ~ {dstr(c.end_date)}
</span>
),
},
{
title: '状态',
dataIndex: 'status',
width: 90,
render: (v: string) => (
<ColorTag color={CONTRACT_STATUS_COLOR[v] || '#98a2b3'}>{CONTRACT_STATUS_TEXT[v] || v}</ColorTag>
),
},
]
/* --------------------------------------------------------- 证明与消息 -- */
function MoreTab() {
const { message } = App.useApp()
const dict = useDocTypeDict()
const docs = useSelfDocuments()
const notes = useSelfNotifications()
const [type, setType] = useState('')
const [purpose, setPurpose] = useState('')
const [docSt, setDocSt] = useState('')
const apply = useDocumentApply(() => {
message.success('证明申请已提交')
setPurpose('')
})
const read = useNotificationsRead()
const types: string[] = (dict.data || []).map((x: any) => x.value || x.label)
const activeType = type || types[0] || '在职证明'
const allDocs: any[] = docs.data || []
const shownDocs = docSt ? allDocs.filter((r) => r.status === docSt) : allDocs
const docCount = (k: string) => allDocs.filter((r) => r.status === k).length
const allNotes: any[] = notes.data?.items || []
const unread = allNotes.filter((n) => !n.is_read).length
return (
<Row gutter={[14, 14]}>
<Col xs={24} xl={10}>
<Card variant="borderless" size="small" title="申请开具证明">
<Segmented
value={activeType}
onChange={(v) => setType(String(v))}
options={(types.length ? types : ['在职证明', '收入证明', '离职证明']).map((t) => ({
label: t,
value: t,
}))}
/>
<Input
style={{ marginTop: 12 }}
value={purpose}
placeholder="用途说明,如:办理签证 / 银行贷款"
onChange={(e) => setPurpose(e.target.value)}
/>
<Button
type="primary"
block
style={{ marginTop: 12 }}
loading={apply.isPending}
onClick={() =>
apply.mutate(
{ doc_type: activeType, purpose: purpose || undefined },
{ onError: (e: any) => message.error(e?.message || '提交失败') },
)
}
>
提交申请
</Button>
</Card>
<Card
variant="borderless"
size="small"
style={{ marginTop: 14 }}
title="我的证明申请"
extra={
<Segmented
size="small"
value={docSt}
onChange={(v) => setDocSt(String(v))}
options={[
{ label: `全部 (${allDocs.length})`, value: '' },
{ label: `办理中 (${docCount('pending')})`, value: 'pending' },
{ label: `已开具 (${docCount('approved')})`, value: 'approved' },
{ label: `已驳回 (${docCount('rejected')})`, value: 'rejected' },
]}
/>
}
>
{!allDocs.length ? (
<SelfEmpty description="暂无证明申请记录" />
) : !shownDocs.length ? (
<SelfEmpty description="没有符合筛选条件的证明申请" />
) : (
<Table
rowKey="id"
size="small"
pagination={false}
dataSource={shownDocs}
columns={DOC_COLS}
/>
)}
</Card>
</Col>
<Col xs={24} xl={14}>
<Card
variant="borderless"
size="small"
title={
<Space>
消息通知
{unread > 0 && <ColorTag color="#ef4444">{unread} 条未读</ColorTag>}
</Space>
}
extra={
unread > 0 && (
<Button
size="small"
type="link"
loading={read.isPending}
onClick={() =>
read.mutate(allNotes.filter((n) => !n.is_read).map((n) => n.id), {
onSuccess: () => message.success('已全部标记为已读'),
})
}
>
全部已读
</Button>
)
}
>
{!allNotes.length ? (
<SelfEmpty description="暂无消息" />
) : (
<div>
{allNotes.slice(0, 12).map((n) => (
<div key={n.id} style={{ padding: '9px 0', borderTop: '1px solid #f4f6fa' }}>
<Space size={6}>
{!n.is_read && <span className="m-dot" style={{ background: '#ef4444' }} />}
<span style={{ fontWeight: n.is_read ? 400 : 600 }}>{n.title}</span>
</Space>
<div style={{ fontSize: 12, color: '#667085', marginTop: 3, lineHeight: 1.6 }}>{n.content}</div>
<Text type="secondary" style={{ fontSize: 11 }}>
{dtstr(n.created_at)}
</Text>
</div>
))}
</div>
)}
</Card>
<Card
variant="borderless"
size="small"
style={{ marginTop: 14 }}
hoverable
onClick={() => window.open('/help/index.html', '_blank', 'noopener,noreferrer')}
>
<Space align="start">
<BookOutlined style={{ color: '#2f54eb', fontSize: 16, marginTop: 3 }} />
<span>
<div style={{ fontWeight: 600 }}>使用手册</div>
<div style={{ fontSize: 12, color: '#98a2b3', marginTop: 3 }}>查看带截图的全功能操作说明</div>
</span>
</Space>
</Card>
</Col>
</Row>
)
}
const DOC_COLS: ColumnsType<any> = [
{ title: '证明类型', dataIndex: 'doc_type', width: 110 },
{
title: '用途',
dataIndex: 'purpose',
ellipsis: true,
render: (v: string) => v || '-',
},
{
title: '状态',
dataIndex: 'status',
width: 88,
render: (v: string) => (
<ColorTag color={DOC_STATUS_COLOR[v] || '#667085'}>{DOC_STATUS_TEXT[v] || v}</ColorTag>
),
},
{
title: '申请时间',
dataIndex: 'created_at',
width: 130,
render: (v: string) => (
<Text type="secondary" style={{ fontSize: 12 }}>
{dtstr(v)}
</Text>
),
},
]

View File

@ -0,0 +1,344 @@
import { BellOutlined, RightOutlined } from '@ant-design/icons'
import { App, Badge, Button, Card, Col, List, Modal, Row, Segmented, Space, Tag, Typography } from 'antd'
import { useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import {
useNotificationsRead,
useSelfAnnouncements,
useSelfNotifications,
useSelfTasks,
useTaskDone,
} from '../../api/self'
import { TASK_LEVEL, dtstr } from '../../lib/selfLabels'
import { toWebPath } from '../../self/manifest'
import { ColorTag, SelfEmpty, SelfLoading, SelfProblem } from './_shared'
const { Text, Paragraph } = Typography
/**
* 待办与消息(Web 版)。
*
* H5 把「HR 待办 / 消息通知 / 公司公告」三块拆在首页与个人中心里,桌面端
* 有空间就合并成一个模块:同一组接口(/self/tasks、/self/notifications、
* /self/announcements)、同一套完成/已读动作,`link` 一律过 `toWebPath()`
* 改写成 Web 路由,这样后端写死的 `/m/xxx` 不会把桌面用户甩进 H5 外壳。
*/
export default function SelfTasks() {
const tasks = useSelfTasks()
const notes = useSelfNotifications()
const anns = useSelfAnnouncements()
const unread = useMemo(
() => ((notes.data?.items || []) as any[]).filter((n) => !n.is_read),
[notes.data],
)
const header = (
<Card variant="borderless" styles={{ body: { paddingBlock: 14 } }}>
<Row align="middle" justify="space-between">
<Col>
<Space size={8}>
<Text type="secondary" style={{ fontSize: 12 }}>
这里汇总 HR 派给我的待办、系统消息与公司公告;处理完会同步到 H5 端。
</Text>
</Space>
</Col>
<Col>
<Space size={16}>
<Text style={{ fontSize: 12 }}>
待办 <b className="num">{(tasks.data || []).filter((t: any) => t.status !== 'done').length}</b>
</Text>
<Text style={{ fontSize: 12 }}>
未读消息 <b className="num">{unread.length}</b>
</Text>
</Space>
</Col>
</Row>
</Card>
)
return (
<div>
{header}
<Row gutter={[14, 14]} style={{ marginTop: 14 }}>
<Col xs={24} xl={12}>
<TaskPanel />
</Col>
<Col xs={24} xl={12}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
<NotificationPanel />
<AnnouncementPanel />
</div>
</Col>
</Row>
</div>
)
}
/* ------------------------------------------------------------------ 待办 -- */
function TaskPanel() {
const { message, modal } = App.useApp()
const nav = useNavigate()
const [tab, setTab] = useState('pending')
const q = useSelfTasks()
const done = useTaskDone()
const all: any[] = q.data || []
const pending = all.filter((t) => t.status !== 'done')
const rows = tab === 'done' ? all.filter((t) => t.status === 'done') : pending
const ask = (t: any) =>
modal.confirm({
title: '标记为已完成',
content: `确认将「${t.title}」标记为已完成?`,
okText: '完成',
cancelText: '再想想',
onOk: async () => {
await done.mutateAsync(t.id, {
onSuccess: () => message.success('已完成'),
onError: (e: any) => message.error(e?.message || '操作失败'),
})
},
})
return (
<Card
variant="borderless"
title="HR 待办"
extra={
<Segmented
size="small"
value={tab}
onChange={(v) => setTab(String(v))}
options={[
{ label: `进行中 (${pending.length})`, value: 'pending' },
{ label: `已完成 (${all.length - pending.length})`, value: 'done' },
]}
/>
}
>
{q.isLoading ? (
<SelfLoading />
) : q.isError ? (
<SelfProblem error={q.error} />
) : !rows.length ? (
<SelfEmpty description={tab === 'done' ? '还没有已完成的待办' : '太棒了,没有待办事项'} />
) : (
<List
dataSource={rows}
split
renderItem={(t: any) => {
const lv = TASK_LEVEL[t.level]
const href = t.link ? toWebPath(t.link) : null
return (
<List.Item
actions={
t.status === 'done'
? [
<ColorTag key="d" color="#16a34a">
已完成
</ColorTag>,
]
: [
href ? (
<a key="go" onClick={() => nav(href)}>
去处理
</a>
) : null,
<a key="ok" onClick={() => ask(t)}>
标记完成
</a>,
].filter(Boolean)
}
>
<List.Item.Meta
title={
<Space size={6}>
{lv && <ColorTag color={lv.color}>{lv.text}</ColorTag>}
<span
style={{
color: t.status === 'done' ? '#98a2b3' : '#1d2939',
textDecoration: t.status === 'done' ? 'line-through' : undefined,
}}
>
{t.title}
</span>
{t.category && (
<Text type="secondary" style={{ fontSize: 11, fontWeight: 400 }}>
{t.category}
</Text>
)}
{t.shared && <ColorTag color="#7c3aed">协同</ColorTag>}
</Space>
}
description={
<Text type="secondary" style={{ fontSize: 12 }}>
截止 {t.due_date || '-'}
{t.detail ? ` · ${t.detail}` : ''}
</Text>
}
/>
</List.Item>
)
}}
/>
)}
</Card>
)
}
/* ------------------------------------------------------------------ 消息 -- */
function NotificationPanel() {
const { message } = App.useApp()
const nav = useNavigate()
const q = useSelfNotifications()
const read = useNotificationsRead()
const items: any[] = q.data?.items || []
const unread = items.filter((n) => !n.is_read)
const markAll = async () => {
await read.mutateAsync([], {
onSuccess: () => message.success('已全部标记为已读'),
onError: (e: any) => message.error(e?.message || '操作失败'),
})
}
return (
<Card
variant="borderless"
title={
<Space>
<BellOutlined style={{ color: '#2f54eb' }} />
消息通知
{!!unread.length && <Badge count={unread.length} size="small" />}
</Space>
}
extra={
!!unread.length && (
<Button size="small" type="link" loading={read.isPending} onClick={markAll}>
全部已读
</Button>
)
}
>
{q.isLoading ? (
<SelfLoading />
) : q.isError ? (
<SelfProblem error={q.error} />
) : !items.length ? (
<SelfEmpty description="暂无消息通知" />
) : (
<List
size="small"
dataSource={items}
split
renderItem={(n: any) => (
<List.Item
style={{ alignItems: 'flex-start' }}
actions={
n.link
? [
<a
key="go"
onClick={() => {
if (!n.is_read) read.mutate([n.id])
nav(toWebPath(n.link))
}}
>
查看
</a>,
]
: !n.is_read
? [
<a key="read" onClick={() => read.mutate([n.id])}>
已读
</a>,
]
: []
}
>
<List.Item.Meta
title={
<Space size={6}>
{!n.is_read && <span className="m-dot" style={{ background: '#ef4444' }} />}
<span style={{ fontWeight: n.is_read ? 400 : 600 }}>{n.title}</span>
{n.category && <ColorTag color="#667085">{n.category}</ColorTag>}
</Space>
}
description={
<>
<div style={{ fontSize: 12, color: '#667085', marginTop: 2 }}>{n.content}</div>
<Text type="secondary" style={{ fontSize: 11 }}>
{dtstr(n.created_at)}
</Text>
</>
}
/>
</List.Item>
)}
/>
)}
</Card>
)
}
/* ------------------------------------------------------------------ 公告 -- */
function AnnouncementPanel() {
const q = useSelfAnnouncements()
const [open, setOpen] = useState<any>(null)
const items: any[] = q.data || []
return (
<Card variant="borderless" title="公司公告">
{q.isLoading ? (
<SelfLoading />
) : q.isError ? (
<SelfProblem error={q.error} />
) : !items.length ? (
<SelfEmpty description="暂无公告" />
) : (
<List
size="small"
dataSource={items}
split
renderItem={(a: any) => (
<List.Item style={{ cursor: 'pointer' }} onClick={() => setOpen(a)} extra={<RightOutlined style={{ color: '#c9ced8' }} />}>
<List.Item.Meta
title={
<Space size={6}>
{a.level === 'urgent' ? (
<Tag bordered={false} color="error">
紧急
</Tag>
) : a.level === 'important' ? (
<Tag bordered={false} color="warning">
重要
</Tag>
) : null}
<span>{a.title}</span>
</Space>
}
description={
<Text type="secondary" style={{ fontSize: 11 }}>
{a.publisher || '人力行政部'} · {dtstr(a.published_at || a.created_at)}
</Text>
}
/>
</List.Item>
)}
/>
)}
<Modal
open={!!open}
title={open?.title}
footer={<Button onClick={() => setOpen(null)}>知道了</Button>}
onCancel={() => setOpen(null)}
>
<Paragraph style={{ whiteSpace: 'pre-wrap', lineHeight: 1.8 }}>{open?.content}</Paragraph>
<Text type="secondary" style={{ fontSize: 12 }}>
{open?.publisher || '人力行政部'} · {dtstr(open?.published_at || open?.created_at)}
</Text>
</Modal>
</Card>
)
}

View File

@ -0,0 +1,170 @@
/**
* 员工自助 Web 页面的公共零件。
*
* 这些组件只负责「与 H5 同一口径的提示语与观感」:
* 加载态、无档案 / 无权限时的说明、金额与键值对展示,
* 保证同一条数据在两个外壳里说法一致。
*/
import { Alert, Progress, Space, Spin, Tag, Typography } from 'antd'
import type { ReactNode } from 'react'
import EmptyBlock from '../../components/EmptyBlock'
const { Text } = Typography
/**
* 主查询失败(账号未绑定员工档案 / 缺少权限)时的友好提示。
* 与 H5 的 MProblem 同一句话、同一条指引,用户换外壳不会看到两种报错。
*/
export function SelfProblem({ error }: { error?: unknown }) {
const msg = (error as any)?.message || '加载失败,请稍后重试'
return (
<Alert
type="warning"
showIcon
message={msg}
description="若提示缺少权限,请联系管理员在「角色权限」中分配;若提示未绑定档案,请联系 HR 补全员工档案与登录账号的关联。"
/>
)
}
export function SelfLoading() {
return (
<div style={{ padding: 48, textAlign: 'center' }}>
<Spin />
</div>
)
}
/** 空状态:复用全局 EmptyBlock,文案由调用方给出(与 H5 空态文案一致) */
export function SelfEmpty({ description }: { description: string }) {
return <EmptyBlock description={description} />
}
/** .info-grid 里的一格:上标签下取值,与档案详情页同一观感 */
export function KV({ k, v }: { k: ReactNode; v: ReactNode }) {
return (
<div className="info-item">
<div className="k">{k}</div>
<div>{v ?? '—'}</div>
</div>
)
}
/** 带颜色圆点的文本(假期类型、余额等在两端用同一种标识) */
export function Dot({ color, children }: { color?: string; children: ReactNode }) {
return (
<span>
<span
style={{
display: 'inline-block',
width: 7,
height: 7,
borderRadius: '50%',
background: color || '#2f54eb',
marginRight: 6,
}}
/>
{children}
</span>
)
}
/** 彩色小标签(H5 用 MTag,Web 用 antd Tag,颜色取自两端共享的字典) */
export function ColorTag({ color, children }: { color?: string; children: ReactNode }) {
return (
<Tag
bordered={false}
style={{
color: color || '#2f54eb',
background: `${color || '#2f54eb'}14`,
marginInlineEnd: 4,
}}
>
{children}
</Tag>
)
}
/**
* 假期额度条:已用 + 审批中 都算占用,与 H5 的 ProgressBar 同一算法与配色。
*/
export function BalanceBar({
total,
used,
frozen,
color,
}: {
total: number
used: number
frozen?: number
color?: string
}) {
const held = Number(used || 0) + Number(frozen || 0)
const pct = total ? Math.min((held / total) * 100, 100) : 0
return (
<Progress
percent={Math.round(pct)}
showInfo={false}
size="small"
strokeColor={color || '#2f54eb'}
trailColor="#eef0f5"
/>
)
}
/** 收入/扣款一类的键值行(工资条明细用,颜色语义与 H5 一致) */
export function MoneyRow({
k,
v,
color,
strong,
border,
}: {
k: ReactNode
v: ReactNode
color?: string
strong?: boolean
border?: boolean
}) {
return (
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'baseline',
padding: '7px 0',
borderTop: border ? '1px solid #f0f2f7' : undefined,
fontSize: strong ? 14 : 13,
}}
>
<span style={{ color: strong ? '#1d2939' : '#667085', fontWeight: strong ? 600 : 400 }}>{k}</span>
<span className="num" style={{ color: color || '#1d2939', fontWeight: strong ? 700 : 500 }}>
{v}
</span>
</div>
)
}
/** 分组小标题(工资条「收入 / 扣款与社保 / 五险一金明细」) */
export function MoneyGroup({ title, children }: { title: string; children: ReactNode }) {
return (
<div style={{ marginBottom: 6 }}>
<Text type="secondary" style={{ fontSize: 12 }}>
{title}
</Text>
{children}
</div>
)
}
/** 页面内的小节标题(卡片内分段用) */
export function SectionTitle({ children, extra }: { children: ReactNode; extra?: ReactNode }) {
return (
<Space style={{ width: '100%', justifyContent: 'space-between', marginBottom: 10 }}>
<Text strong style={{ fontSize: 14 }}>
{children}
</Text>
{extra}
</Space>
)
}

View File

@ -0,0 +1,270 @@
/**
* 员工自助模块清单 —— Web 工作台与 H5 自助端的唯一事实来源。
*
* 为什么需要这个文件:
* 以前 Web 与 H5 各写一套入口链接与文案,后端下发的 task/notification.link 又固定是
* `/m/xxx`,结果 Web 里点待办会被甩到 H5,H5 里 `/m/tasks` 之类的链接干脆 404。
* 现在两端的所有模块(key、名称、说明、权限码、Web 路由、H5 路由、图标、顺序)
* 都在这里声明一次,页面、宫格、路径改写、权限判定全部从这里取值。
*
* 与后端的对齐关系由 `tests/test_self_parity.py` 守住:
* - `perm` ↔ `app/core/permissions.py` 的权限码
* - `mobilePath`↔ `MOBILE_MENU_TREE`(H5 底部导航)
* - `webPath` ↔ `SELF_WEB_MENU_TREE`(普通员工的 Web 侧栏)
* 新增模块时改这里 + 后端两份菜单树,测试会提醒漏改。
*/
export type SelfModuleKey =
| 'home'
| 'leave'
| 'payslips'
| 'benefits'
| 'approvals'
| 'tasks'
| 'profile'
export interface SelfModule {
key: SelfModuleKey
/** 导航名称:必须与后端两份菜单树的 name 一致 */
name: string
/** 页面主标题 */
title: string
/** 首页宫格文案 */
short: string
/** 一句话说明(宫格副标题 / 页面副标题) */
desc: string
/** 进入该模块所需的权限码 */
perm: string
/** Web 工作台路由(管理端外壳) */
webPath: string
/** H5 自助端路由(移动端外壳) */
mobilePath: string
/** Web 侧栏图标(antd 图标名,交给 components/icons.tsx 解析) */
antdIcon: string
/** H5 底部导航图标 key(components/icons.tsx 的 MOBILE_ICONS) */
mobileIcon: string
/** 首页宫格图标 */
emoji: string
/** 主题色(两端共用,保证同一模块在两边"长得一样") */
color: string
sort: number
/** 是否出现在 Web 侧栏(false = 仅从首页宫格进入) */
inWebMenu: boolean
/** 是否占据 H5 底部导航(手机屏宽有限,底部只放 5 个) */
inMobileTab: boolean
}
/**
* 导航Placement 说明(这也是"两端怎么保持一致"的答案之一):
* H5 底部导航受屏宽限制只放 5 项,Web 侧栏同样只放这 5 项,
* 审批 / 待办 在两端都从首页宫格进入 —— 顺序、名称、权限、图标配色完全对齐。
*/
export const SELF_MODULES: Record<SelfModuleKey, SelfModule> = {
home: {
key: 'home',
name: '首页',
title: '员工首页',
short: '首页',
desc: '工资、假期、待办一屏掌握',
perm: 'selfservice:home:read',
webPath: '/dashboard',
mobilePath: '/m',
antdIcon: 'HomeOutlined',
mobileIcon: 'home',
emoji: '🏠',
color: '#2f54eb',
sort: 10,
inWebMenu: true,
inMobileTab: true,
},
leave: {
key: 'leave',
name: '请假',
title: '请假 / 调休',
short: '请假',
desc: '发起申请、查额度与进度',
perm: 'selfservice:leave:read',
webPath: '/self/leave',
mobilePath: '/m/leave',
antdIcon: 'CalendarOutlined',
mobileIcon: 'calendar',
emoji: '🗓',
color: '#2f6bff',
sort: 20,
inWebMenu: true,
inMobileTab: true,
},
payslips: {
key: 'payslips',
name: '工资',
title: '我的工资条',
short: '工资条',
desc: '逐月明细、个税与五险一金',
perm: 'selfservice:payslip:read',
webPath: '/self/payslips',
mobilePath: '/m/payslips',
antdIcon: 'MoneyCollectOutlined',
mobileIcon: 'gold',
emoji: '💰',
color: '#16a34a',
sort: 30,
inWebMenu: true,
inMobileTab: true,
},
benefits: {
key: 'benefits',
name: '福利',
title: '福利与保险',
short: '福利保险',
desc: '五险一金、福利发放、假期额度',
perm: 'selfservice:benefit:read',
webPath: '/self/benefits',
mobilePath: '/m/benefits',
antdIcon: 'GiftOutlined',
mobileIcon: 'gift',
emoji: '🎁',
color: '#722ed1',
sort: 40,
inWebMenu: true,
inMobileTab: true,
},
approvals: {
key: 'approvals',
name: '审批',
title: '审批中心',
short: '我的申请',
desc: '待我审批与我的申请进度',
perm: 'selfservice:approval:read',
webPath: '/self/approvals',
mobilePath: '/m/approvals',
antdIcon: 'AuditOutlined',
mobileIcon: 'check',
emoji: '✅',
color: '#fa8c16',
sort: 50,
inWebMenu: false,
inMobileTab: false,
},
tasks: {
key: 'tasks',
name: '待办',
title: '待办与消息',
short: '待办消息',
desc: 'HR 待办、通知与公告',
perm: 'selfservice:task:read',
webPath: '/self/tasks',
mobilePath: '/m/tasks',
antdIcon: 'ScheduleOutlined',
mobileIcon: 'task',
emoji: '🔔',
color: '#0ea5e9',
sort: 60,
inWebMenu: false,
inMobileTab: false,
},
profile: {
key: 'profile',
name: '我的',
title: '个人中心',
short: '我的档案',
desc: '档案、合同、证明、报销标准',
perm: 'selfservice:profile:read',
webPath: '/self/profile',
mobilePath: '/m/profile',
antdIcon: 'UserOutlined',
mobileIcon: 'user',
emoji: '👤',
color: '#13c2c2',
sort: 70,
inWebMenu: true,
inMobileTab: true,
},
}
/** 按 sort 排序的全量模块(首页宫格、模式切换、路径映射都按这个顺序) */
export const SELF_ENTRIES: SelfModule[] = Object.values(SELF_MODULES).sort(
(a, b) => a.sort - b.sort,
)
/** Web 侧栏顺序(与后端 SELF_WEB_MENU_TREE 一致) */
export const SELF_WEB_NAV = SELF_ENTRIES.filter((m) => m.inWebMenu)
/** H5 底部导航顺序(与后端 MOBILE_MENU_TREE 一致) */
export const SELF_MOBILE_TABS = SELF_ENTRIES.filter((m) => m.inMobileTab)
export const selfModule = (key: SelfModuleKey): SelfModule => SELF_MODULES[key]
/** 模块在指定外壳下的路径 */
export const pathOf = (key: SelfModuleKey, mode: 'web' | 'h5'): string =>
mode === 'web' ? SELF_MODULES[key].webPath : SELF_MODULES[key].mobilePath
/**
* 链接别名:历史上后端通知/待办写入过 `/m/payslip`、`/m/record` 这类
* 单数或语义化路径,H5 改版后统一成复数路由。库里存的老链接仍在,
* 这里做一层别名,保证任何历史链接都能落到存在的页面。
*/
const ALIASES: Record<string, SelfModuleKey> = {
'': 'home',
home: 'home',
index: 'home',
leave: 'leave',
leaves: 'leave',
vacation: 'leave',
payslip: 'payslips',
payslips: 'payslips',
salary: 'payslips',
benefit: 'benefits',
benefits: 'benefits',
insurance: 'benefits',
approval: 'approvals',
approvals: 'approvals',
record: 'approvals',
records: 'approvals',
task: 'tasks',
tasks: 'tasks',
todo: 'tasks',
notification: 'tasks',
notifications: 'tasks',
message: 'tasks',
profile: 'profile',
me: 'profile',
contract: 'profile',
document: 'profile',
documents: 'profile',
}
/** 把任意站内路径解析成自助模块(识别 `/m/xxx`、`/self/xxx`、`/dashboard`) */
export function moduleOfPath(raw?: string | null): SelfModule | null {
if (!raw || !raw.startsWith('/')) return null
const path = raw.split('?')[0].split('#')[0].replace(/\/+$/, '') || '/'
if (path === '/dashboard') return SELF_MODULES.home
const seg = (() => {
if (path === '/m') return ''
if (path.startsWith('/m/')) return path.slice(3)
if (path === '/self') return ''
if (path.startsWith('/self/')) return path.slice(6)
return null
})()
if (seg === null) return null
const key = ALIASES[seg]
return key ? SELF_MODULES[key] : null
}
/** 后端下发的链接一律是 `/m/xxx`;在 Web 外壳里跳转前先改写成 Web 路由 */
export function toWebPath(raw?: string | null, fallback = '/dashboard'): string {
if (!raw) return fallback
if (!raw.startsWith('/')) return raw
const mod = moduleOfPath(raw)
return mod ? mod.webPath : raw
}
/** 反向:在 H5 外壳里把 `/self/xxx`、`/dashboard` 改写成 H5 路由 */
export function toMobilePath(raw?: string | null, fallback = '/m'): string {
if (!raw) return fallback
if (!raw.startsWith('/')) return raw
const mod = moduleOfPath(raw)
return mod ? mod.mobilePath : raw
}
/** 当前权限可以看到哪些模块(首页宫格按此渲染,两端得到同一份列表) */
export function permittedModules(hasPerm: (perm?: string | string[]) => boolean): SelfModule[] {
return SELF_ENTRIES.filter((m) => hasPerm(m.perm))
}

View File

@ -103,8 +103,11 @@ export function installAuthBridge() {
setRefresher(() => auth.getState().tryRefresh())
setExpiredHandler(() => {
auth.getState().logout()
if (!window.location.pathname.startsWith('/m')) {
const back = encodeURIComponent(window.location.pathname + window.location.search)
// 无论 Web 工作台还是 H5 自助端,过期后都回登录页并带上原地址。
// 以前 H5 不跳转,用户在手机上会看到一片空白表格,以为系统坏了;
// 现在登录页会用 sanitizeRedirect() 把 /m/* 之外的地址改回当前外壳的等价页面。
const back = encodeURIComponent(window.location.pathname + window.location.search)
if (window.location.pathname !== '/login') {
window.location.href = `/login?redirect=${back}`
}
})