unis_hrms/app/services/seed_payroll.py

178 lines
8.9 KiB
Python

"""薪资项目、账套、薪资标准、期间、批次与工资条播种。"""
from __future__ import annotations
from datetime import date, timedelta
from decimal import Decimal
from sqlalchemy import select
from ..db.base import utcnow
from ..models.employee import Employee
from ..models.org import Department, JobLevel
from ..models.payroll import (EmployeeSalary, PayrollBatch, PayrollPeriod, SalaryItem,
SalaryPlan, Payslip)
from .seed import RNG, already, count, log, mk
from ..services.payroll_service import calculate_batch, month_label
ITEMS = [
# code, name, category, calc_type, include_in_gross, taxable, sort, is_system, remark
("base_salary", "基本工资", "earning", "fixed", True, True, 10, True, "按月固定发放"),
("perf_salary", "绩效工资", "earning", "manual", True, True, 20, True, "按绩效考核结果发放"),
("overtime", "加班费", "earning", "manual", True, True, 30, False, "平日/周末加班"),
("commission", "销售提成", "earning", "manual", True, True, 40, False, "销售岗位提成"),
("bonus", "奖金", "earning", "manual", True, True, 50, False, "专项奖金/项目奖"),
("meal_allowance", "餐补", "allowance", "fixed", True, True, 60, False, "每个工作日 30 元"),
("transport_allowance", "交通补贴", "allowance", "fixed", True, True, 70, False, ""),
("telecom_allowance", "通讯补贴", "allowance", "fixed", True, True, 80, False, ""),
("housing_allowance", "住房补贴", "allowance", "fixed", True, True, 90, False, "异地员工"),
("attendance_bonus", "全勤奖", "allowance", "manual", True, True, 100, False, "无缺勤记录"),
("absence_deduction", "缺勤扣款", "deduction", "manual", False, False, 110, True, "事假/迟到早退"),
("other_deduction", "其他扣款", "deduction", "manual", False, False, 120, False, "工会费、代扣款项"),
("compensation", "经济补偿金", "earning", "manual", True, False, 130, False, "离职补偿,单独计税"),
]
PLANS = [
# code, name, extra items, pay_day
("PL-COM", "标准薪套(全员)", {"meal_allowance": 600, "transport_allowance": 400,
"telecom_allowance": 200, "absence_deduction": 0,
"other_deduction": 0}, 10),
("PL-Tech", "研发序列薪套", {"meal_allowance": 900, "transport_allowance": 500,
"telecom_allowance": 300, "housing_allowance": 0,
"absence_deduction": 0, "other_deduction": 0}, 10),
("PL-Sales", "销售序列薪套", {"meal_allowance": 600, "transport_allowance": 800,
"telecom_allowance": 400, "absence_deduction": 0,
"other_deduction": 0}, 10),
("PL-Mgmt", "管理层薪套", {"meal_allowance": 1000, "transport_allowance": 1200,
"telecom_allowance": 500, "housing_allowance": 2000,
"absence_deduction": 0, "other_deduction": 0}, 10),
]
TECH_DEPTS = {"RD", "RD-BE", "RD-FE", "RD-QA", "RD-AI", "RD-OPS", "PD"}
SALES_DEPTS = {"SALES", "SALES-EAST", "SALES-NORTH", "MKT", "MKT-BD", "CS"}
MGMT_DEPTS = {"UNIS", "TBO"}
BANKS = ["招商银行", "中国工商银行", "中国建设银行", "中国银行", "交通银行", "浦发银行"]
SPECIAL_DEDUCTIONS = [0, 0, 1000, 1500, 2000, 1000, 0, 3000]
def _plan_for(dept_code: str | None, level_grade: int) -> str:
if dept_code in MGMT_DEPTS or level_grade >= 8:
return "PL-Mgmt"
if dept_code in SALES_DEPTS:
return "PL-Sales"
if dept_code in TECH_DEPTS:
return "PL-Tech"
return "PL-COM"
async def seed_items(session) -> int:
if await already(session, SalaryItem):
return 0
for code, name, category, calc, gross, taxable, sort, system, remark in ITEMS:
session.add(mk(SalaryItem, code=code, name=name, category=category, calc_type=calc,
include_in_gross=gross, taxable=taxable, sort=sort, is_system=system,
is_active=True, remark=remark))
await session.flush()
return len(ITEMS)
async def seed_plans(session) -> int:
if await already(session, SalaryPlan):
return 0
depts = {d.code: d for d in (await session.execute(select(Department))).scalars().all()}
for code, name, items, pay_day in PLANS:
session.add(mk(SalaryPlan, code=code, name=name, department_id=None,
effective_date=date(date.today().year - 1, 1, 1),
items={k: float(v) for k, v in items.items()}, pay_day=pay_day,
currency="CNY", is_active=True, remark="演示账套"))
await session.flush()
return len(PLANS)
async def seed_standards(session) -> int:
if await already(session, EmployeeSalary):
return 0
plans = {p.code: p for p in (await session.execute(select(SalaryPlan))).scalars().all()}
depts = {d.id: d.code for d in (await session.execute(select(Department))).scalars().all()}
grades = {j.id: j.grade for j in (await session.execute(select(JobLevel))).scalars().all()}
employees = list((await session.execute(
select(Employee).order_by(Employee.id))).scalars().all())
made = 0
for emp in employees:
custom = emp.custom_fields or {}
base = float(custom.get("base_salary") or RNG.choice([12000, 16000, 20000, 24000]))
level_grade = grades.get(emp.job_level_id or 0, 3)
plan_code = _plan_for(depts.get(emp.department_id), level_grade)
plan = plans.get(plan_code) or next(iter(plans.values()))
overrides = {"base_salary": round(base * 0.72 / 100) * 100,
"perf_salary": round(base * 0.28 / 100) * 100}
session.add(mk(EmployeeSalary, employee_id=emp.id, plan_id=plan.id, overrides=overrides,
effective_date=date(date.today().year - 1, 1, 1),
bank_name=RNG.choice(BANKS),
bank_account="62" + "".join(str(RNG.randint(0, 9)) for _ in range(16)),
special_deduction=RNG.choice(SPECIAL_DEDUCTIONS),
is_active=True, remark=None))
made += 1
await session.flush()
return made
async def seed_batches(session, months: int = 2) -> dict:
today = date.today()
periods: list[PayrollPeriod] = []
for back in range(months, 0, -1):
year, month = today.year, today.month - back
while month <= 0:
month += 12
year -= 1
period = (await session.execute(select(PayrollPeriod).where(
PayrollPeriod.year == year, PayrollPeriod.month == month))).scalar_one_or_none()
if period is None:
period = mk(PayrollPeriod, year=year, month=month, label=month_label(year, month),
pay_date=date(year, month, 10) if date(year, month, 10).weekday() < 5
else date(year, month, 11),
status="open", remark=None)
session.add(period)
await session.flush()
periods.append(period)
made: list[dict] = []
for index, period in enumerate(periods):
batch = (await session.execute(select(PayrollBatch).where(
PayrollBatch.period_id == period.id))).scalars().first()
if batch is not None:
made.append({"id": batch.id, "period": period.label, "status": batch.status})
continue
batch = mk(PayrollBatch, name=f"{period.label}工资表", period_id=period.id,
year=period.year, month=period.month, scope={}, status="draft",
remark="系统播种生成")
session.add(batch)
await session.flush()
result = await calculate_batch(session, batch, scope={}, prorate=True)
last = index == len(periods) - 1
if not last:
batch.status = "paid"
batch.approved_at = utcnow()
batch.approved_by = None
batch.paid_at = utcnow()
batch.bank_batch_no = f"BANK{period.year}{period.month:02d}{RNG.randint(1000, 9999)}"
slips = list((await session.execute(select(Payslip).where(
Payslip.batch_id == batch.id))).scalars().all())
for slip in slips:
slip.status = "published"
slip.confirmed_at = utcnow()
made.append({"id": batch.id, "period": period.label, "status": batch.status,
"count": result["employee_count"], "net": result["net_total"]})
await session.flush()
return {"batches": made}
async def run(session, *, force: bool = False) -> dict:
items = await seed_items(session)
plans = await seed_plans(session)
standards = await seed_standards(session)
batches = await seed_batches(session)
return {"items": await count(session, SalaryItem), "new_items": items,
"plans": await count(session, SalaryPlan), "new_plans": plans,
"standards": standards, **batches}