unis_hrms/app/services/seed_content.py

178 lines
11 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""公告、通知、HR 待办、审批流样例(异动/调薪/证明/信息变更)播种。"""
from __future__ import annotations
from datetime import date, datetime, timedelta
from decimal import Decimal
from sqlalchemy import select
from ..models.employee import Employee, EmployeeChange, EmployeeDocument, EmployeeSalaryAdjustment
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 = [
("关于 2026 年度调薪窗口的通知",
"各位同事:\n\n2026 年度调薪窗口将于本月 20 日开启,请各部门负责人于 15 日前完成下属绩效评定与调薪建议提交。人力行政部将结合公司经营状况与个人表现统一评审。\n\n人力行政部", "policy", "important", "张丽丽"),
("全员数据安全与合规培训",
"为保障客户数据安全,公司将于本月底前完成全员数据安全与合规培训,请在「HR 待办」中确认参加并完成在线考试。", "policy", "urgent", "王建国"),
("中秋节放假安排",
"根据国家法定节假日规定,中秋节放假 3 天,调休安排详见 OA。节前最后一个工作日请提前提交假期申请。", "notice", "normal", "赵敏"),
("研发中心新办公区启用",
"研发中心 12F 新办公区正式启用,工位调整由行政部统一安排,请于本周内完成工位确认。", "notice", "normal", "赵敏"),
("内部推荐奖励计划升级",
"技术类岗位内部推荐奖励提升至 8000 元,被推荐人转正后 30 天内发放。欢迎推荐优秀人才。", "activity", "normal", "刘敏"),
("员工自助 H5 上线",
"员工自助 H5 已正式上线,手机端可完成请假、查看工资条、五险一金与福利记录。入口:/m", "notice", "important", "张丽丽"),
]
TASKS = [
("training", "完成《数据安全与合规》在线课程", 7, "high"),
("cert", "更新个人紧急联系人信息", 5, "normal"),
("health", "预约年度体检", 20, "normal"),
("contract", "确认劳动合同续签材料", 10, "high"),
("expense", "提交上季度培训费用报销", 3, "normal"),
]
CHANGE_TYPES = [
("transfer", "部门调动", {"department_id": "研发一组", "position_id": "后端工程师"}),
("promotion", "职级晋升", {"job_level_id": "P4"}),
("regular", "转正", {"status": "active"}),
]
async def seed_announcements(session) -> int:
if await already(session, Announcement):
return 0
now = datetime.now()
for index, (title, content, category, level, publisher) in enumerate(ANNOUNCEMENTS):
session.add(mk(Announcement, title=title, content=content, category=category, level=level,
publisher=publisher, published_at=now - timedelta(days=index * 4 + 1),
expires_at=now + timedelta(days=60), is_published=True, target="all"))
await session.flush()
return len(ANNOUNCEMENTS)
async def seed_approvals(session) -> dict:
employees = list((await session.execute(
select(Employee).where(Employee.is_active.is_(True)).order_by(Employee.id))).scalars().all())
users = {u.employee_id: u for u in (await session.execute(select(User))).scalars().all()
if u.employee_id}
depts = {d.id: d.name for d in (await session.execute(select(Department))).scalars().all()}
positions = {p.id: p.name for p in (await session.execute(select(Position))).scalars().all()}
made = {"changes": 0, "adjustments": 0, "documents": 0, "profiles": 0}
if not await count(session, EmployeeChange):
for emp in RNG.sample(employees, min(len(employees), 14)):
ctype, label, after = RNG.choice(CHANGE_TYPES)
status = RNG.choices(["approved", "approved", "pending", "rejected"],
weights=[55, 15, 25, 5])[0]
before = {"department_id": depts.get(emp.department_id, "-"),
"position_id": positions.get(emp.position_id, "-"),
"job_level_id": "P3", "status": "probation"}
user = users.get(emp.id)
change = mk(EmployeeChange, employee_id=emp.id, change_type=ctype,
effective_date=date.today() + timedelta(days=RNG.randint(-40, 20)),
before_value=before, after_value=after,
reason=RNG.choice(["组织架构调整", "个人发展", "项目需要", "绩效优秀", "转正评估通过"]),
status=status, applicant_id=user.id if user else None,
approver_id=None,
approved_at=None, comment="同意" if status == "approved" else None)
session.add(change)
await session.flush()
made["changes"] += 1
if not await count(session, EmployeeSalaryAdjustment):
for emp in RNG.sample(employees, min(len(employees), 12)):
std = (emp.custom_fields or {}).get("base_salary") or 18000
after = round(std * RNG.choice([1.06, 1.08, 1.1, 1.15, 1.2]))
status = RNG.choices(["approved", "pending", "pending", "rejected"],
weights=[50, 30, 15, 5])[0]
session.add(mk(EmployeeSalaryAdjustment, employee_id=emp.id,
effective_date=date.today().replace(day=1) + timedelta(days=30 * RNG.randint(0, 2)),
before_amount=Decimal(str(std)), after_amount=Decimal(str(after)),
adjust_type=RNG.choice(["promotion", "annual", "market", "probation"]),
reason=RNG.choice(["年度绩效调薪", "晋升调薪", "试用期转正调薪", "市场水平校准"]),
status=status, approver_id=None, approved_at=None,
comment=None))
made["adjustments"] += 1
if not await count(session, EmployeeDocument):
for emp in RNG.sample(employees, min(len(employees), 10)):
status = RNG.choices(["approved", "pending", "pending"], weights=[50, 30, 20])[0]
user = users.get(emp.id)
session.add(mk(EmployeeDocument, employee_id=emp.id,
doc_type=RNG.choice(["在职证明", "收入证明", "离职证明", "其他"]),
purpose=RNG.choice(["办理签证", "银行贷款", "租房备案", "子女入学"]),
status=status, requester_name=emp.name,
applicant_id=user.id if user else None,
approver_id=None, approved_at=None, comment=None))
made["documents"] += 1
if not await count(session, ProfileRequest):
for emp in RNG.sample(employees, min(len(employees), 6)):
user = users.get(emp.id)
if user is None:
continue
status = RNG.choices(["pending", "approved"], weights=[70, 30])[0]
session.add(mk(ProfileRequest, employee_id=emp.id,
changes=RNG.choice([
{"phone": "13800001234"},
{"address": "上海市闵行区新镇路 100 弄"},
{"email": "new.mail@example.com", "marital_status": "已婚"},
{"emergency_contact": "李静", "emergency_phone": "13900002222"},
]),
reason=RNG.choice(["换手机号", "搬家更新住址", "婚姻状况变更", "更新紧急联系人"]),
status=status, applicant_user_id=user.id, approver_id=None,
approver_name="张丽丽" if status == "approved" else None,
comment="信息已核实" if status == "approved" else None))
await session.flush()
if status == "approved":
session.add(mk(ApprovalLog, entity_type="profile", entity_id=1, action="approve",
actor_id=None, actor_name="张丽丽", comment="信息已核实"))
made["profiles"] += 1
await session.flush()
return made
async def seed_tasks_notifications(session) -> dict:
employees = list((await session.execute(
select(Employee).where(Employee.is_active.is_(True)).order_by(Employee.id))).scalars().all())
users = {u.employee_id: u for u in (await session.execute(select(User))).scalars().all()
if u.employee_id}
tasks = 0
if not await count(session, TaskReminder):
for emp in employees:
for category, title, days, level in RNG.sample(TASKS, RNG.randint(1, 3)):
session.add(mk(TaskReminder, category=category, title=title, employee_id=emp.id,
due_date=date.today() + timedelta(days=days + RNG.randint(0, 10)),
level=level, status="pending",
detail="请在截止时间前完成,逾期将同步至部门负责人。",
link=SELF_LINKS["tasks"]))
tasks += 1
await session.flush()
notes = 0
if not await count(session, Notification):
for emp in employees[:24]:
user = users.get(emp.id)
title, content, category, link = RNG.choice([
("您的请假申请已通过", "审批人已完成审批,可在「我的请假」中查看记录。", "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,
is_read=RNG.random() < 0.35,
created_at=datetime.now() - timedelta(days=RNG.randint(0, 20))))
notes += 1
await session.flush()
return {"tasks": tasks, "notifications": notes}
async def run(session, *, force: bool = False) -> dict:
ann = await seed_announcements(session)
approvals = await seed_approvals(session)
misc = await seed_tasks_notifications(session)
return {"announcements": ann, **approvals, **misc}