334 lines
15 KiB
Python
334 lines
15 KiB
Python
"""算薪引擎:应发 / 五险一金 / 个税(累计预扣法).
|
|
|
|
The engine is deliberately pure so it can be unit-tested and reused by the
|
|
self-service "salary calculator" preview.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import calendar
|
|
from datetime import date
|
|
from decimal import Decimal, ROUND_HALF_UP
|
|
from typing import Any, Iterable
|
|
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from ..core.errors import AppError
|
|
from ..models.benefits import Enrollment, InsurancePlan
|
|
from ..models.employee import Employee
|
|
from ..models.org import Department
|
|
from ..models.payroll import EmployeeSalary, PayrollBatch, PayrollPeriod, Payslip, SalaryItem, SalaryPlan
|
|
from ..models.selfservice import TaskReminder
|
|
|
|
TAX_THRESHOLD = Decimal("5000") # 个税起征点(每月)
|
|
|
|
# 个人所得税税率表(综合所得,按月累计预扣)
|
|
TAX_BRACKETS: list[tuple[Decimal, Decimal, Decimal]] = [
|
|
(Decimal("36000"), Decimal("0.03"), Decimal("0")),
|
|
(Decimal("144000"), Decimal("0.10"), Decimal("2520")),
|
|
(Decimal("300000"), Decimal("0.20"), Decimal("16920")),
|
|
(Decimal("420000"), Decimal("0.25"), Decimal("31920")),
|
|
(Decimal("660000"), Decimal("0.30"), Decimal("52920")),
|
|
(Decimal("960000"), Decimal("0.35"), Decimal("85920")),
|
|
]
|
|
|
|
|
|
def q2(value: Any) -> Decimal:
|
|
return Decimal(str(value if value is not None else 0)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
|
|
|
|
|
def default_working_days(year: int, month: int) -> float:
|
|
return float(calendar.monthrange(year, month)[1])
|
|
|
|
|
|
def tax_on_cumulative(taxable: Decimal) -> Decimal:
|
|
"""Cumulative tax payable for a given cumulative taxable income."""
|
|
if taxable <= 0:
|
|
return Decimal("0.00")
|
|
for ceiling, rate, quick in TAX_BRACKETS:
|
|
if taxable <= ceiling:
|
|
return q2(taxable * rate - quick)
|
|
ceiling, rate, quick = TAX_BRACKETS[-1]
|
|
return q2(taxable * Decimal("0.45") - Decimal("181920"))
|
|
|
|
|
|
def insurance_split(plan: InsurancePlan | None, enrollment: Enrollment | None,
|
|
monthly_salary: Decimal) -> tuple[Decimal, Decimal, dict[str, Any]]:
|
|
"""Return (personal, company, detail) for one employee's social insurance + housing fund."""
|
|
if not plan or not enrollment:
|
|
return Decimal("0.00"), Decimal("0.00"), {}
|
|
rules = plan.rules or {}
|
|
personal = Decimal("0.00")
|
|
company = Decimal("0.00")
|
|
detail: dict[str, Any] = {}
|
|
for key, rule in rules.items():
|
|
if not isinstance(rule, dict):
|
|
continue
|
|
base_kind = rule.get("base", "social") # social | fund | salary
|
|
if base_kind == "fund":
|
|
base = enrollment.fund_base or enrollment.social_base or monthly_salary
|
|
floor, ceiling = plan.fund_base_floor, plan.fund_base_ceiling
|
|
elif base_kind == "social":
|
|
base = enrollment.social_base or monthly_salary
|
|
floor, ceiling = plan.base_floor, plan.base_ceiling
|
|
else:
|
|
base, floor, ceiling = monthly_salary, None, None
|
|
base = q2(base)
|
|
if floor and base < Decimal(str(floor)):
|
|
base = Decimal(str(floor))
|
|
if ceiling and base > Decimal(str(ceiling)):
|
|
base = Decimal(str(ceiling))
|
|
p_rate = Decimal(str(rule.get("personal", 0) or 0))
|
|
c_rate = Decimal(str(rule.get("company", 0) or 0))
|
|
p_amount, c_amount = q2(base * p_rate), q2(base * c_rate)
|
|
personal += p_amount
|
|
company += c_amount
|
|
detail[key] = {"name": rule.get("name", key), "base": float(base),
|
|
"personal": float(p_amount), "company": float(c_amount),
|
|
"personal_rate": float(p_rate), "company_rate": float(c_rate)}
|
|
return q2(personal), q2(company), detail
|
|
|
|
|
|
def working_days_between(year: int, month: int) -> float:
|
|
"""Weekdays of the month (a simple, explainable payroll calendar)."""
|
|
days = calendar.monthrange(year, month)[1]
|
|
return float(sum(1 for d in range(1, days + 1) if date(year, month, d).weekday() < 5))
|
|
|
|
|
|
class CalculationError(AppError):
|
|
pass
|
|
|
|
|
|
async def resolve_items(session: AsyncSession) -> dict[str, dict[str, Any]]:
|
|
items = (await session.execute(select(SalaryItem).where(SalaryItem.is_active.is_(True))
|
|
.order_by(SalaryItem.sort))).scalars().all()
|
|
return {i.code: {"code": i.code, "name": i.name, "category": i.category,
|
|
"calc_type": i.calc_type, "include_in_gross": i.include_in_gross,
|
|
"taxable": i.taxable} for i in items}
|
|
|
|
|
|
async def employees_for_scope(session: AsyncSession, scope: dict | None) -> list[Employee]:
|
|
# 停用的档案与离职一样不参与算薪:``is_active`` 是全站唯一的业务启停位
|
|
stmt = select(Employee).where(
|
|
Employee.status.in_(["probation", "active", "leave"]),
|
|
Employee.is_active.is_(True),
|
|
)
|
|
scope = scope or {}
|
|
dept_ids = list(scope.get("department_ids") or [])
|
|
emp_ids = list(scope.get("employee_ids") or [])
|
|
if dept_ids:
|
|
from ..core.deps import department_subtree
|
|
|
|
collected: list[int] = []
|
|
for dept_id in dept_ids:
|
|
collected.extend(await department_subtree(session, dept_id))
|
|
stmt = stmt.where(Employee.department_id.in_(collected or [-1]))
|
|
if emp_ids:
|
|
stmt = stmt.where(Employee.id.in_(emp_ids))
|
|
return list((await session.execute(stmt.order_by(Employee.work_no))).scalars().all())
|
|
|
|
|
|
async def _cumulative_context(session: AsyncSession, employee_id: int, year: int, month: int
|
|
) -> tuple[Decimal, Decimal]:
|
|
"""(cumulative taxable income before this month, cumulative tax already paid this year)."""
|
|
rows = (await session.execute(
|
|
select(Payslip.gross, Payslip.insurance_personal, Payslip.special_deduction, Payslip.tax)
|
|
.where(Payslip.employee_id == employee_id, Payslip.year == year, Payslip.month < month)
|
|
)).all()
|
|
taxable = Decimal("0")
|
|
paid = Decimal("0")
|
|
for gross, ins, special, tax in rows:
|
|
taxable += q2(gross) - q2(ins) - q2(special) - TAX_THRESHOLD
|
|
paid += q2(tax)
|
|
return taxable, paid
|
|
|
|
|
|
async def calculate_batch(session: AsyncSession, batch: PayrollBatch, *, scope: dict | None = None,
|
|
prorate: bool = True, working_days: float | None = None,
|
|
manual: dict[str, dict] | None = None, include_insurance: bool = True,
|
|
include_tax: bool = True) -> dict[str, Any]:
|
|
"""Recompute every payslip of ``batch``. Returns a run summary."""
|
|
manual = manual or {}
|
|
period = await session.get(PayrollPeriod, batch.period_id)
|
|
if not period:
|
|
raise CalculationError("薪资期间不存在")
|
|
year, month = batch.year, batch.month
|
|
items_meta = await resolve_items(session)
|
|
plans = {p.id: p for p in (await session.execute(select(SalaryPlan))).scalars().all()}
|
|
employees = await employees_for_scope(session, scope if scope is not None else batch.scope)
|
|
if not employees:
|
|
raise CalculationError("没有符合条件的员工,请调整计薪范围")
|
|
|
|
standards = {}
|
|
for std in (await session.execute(
|
|
select(EmployeeSalary).where(EmployeeSalary.employee_id.in_([e.id for e in employees]),
|
|
EmployeeSalary.is_active.is_(True))
|
|
.order_by(EmployeeSalary.effective_date.asc(), EmployeeSalary.id.asc())
|
|
)).scalars().all():
|
|
standards[std.employee_id] = std # latest effective record wins
|
|
|
|
enrollments = {}
|
|
if include_insurance:
|
|
for enr in (await session.execute(
|
|
select(Enrollment).where(Enrollment.employee_id.in_([e.id for e in employees]),
|
|
Enrollment.status == "active",
|
|
Enrollment.include_in_payroll.is_(True))
|
|
)).scalars().all():
|
|
enrollments[enr.employee_id] = enr
|
|
ins_plans = {p.id: p for p in (await session.execute(select(InsurancePlan))).scalars().all()}
|
|
|
|
dept_names = {d.id: d.name for d in (await session.execute(select(Department))).scalars().all()}
|
|
wd = float(working_days or (batch.scope or {}).get("working_days") or 0) \
|
|
or working_days_between(year, month)
|
|
|
|
# drop previous draft payslips for this period so re-running is idempotent
|
|
stale = list((await session.execute(
|
|
select(Payslip).where(Payslip.period_id == period.id, Payslip.status != "published")
|
|
)).scalars().all())
|
|
for row in stale:
|
|
await session.delete(row)
|
|
await session.flush()
|
|
|
|
summary = {"gross": Decimal("0"), "insurance_personal": Decimal("0"), "insurance_company": Decimal("0"),
|
|
"tax": Decimal("0"), "deduction": Decimal("0"), "net": Decimal("0")}
|
|
missing_standard: list[str] = []
|
|
created: list[Payslip] = []
|
|
|
|
for emp in employees:
|
|
std = standards.get(emp.id)
|
|
entry = manual.get(str(emp.id)) or manual.get(emp.id) or {}
|
|
entry_items = {k: float(v) for k, v in (entry.get("items") or {}).items()}
|
|
actual = entry.get("actual_days")
|
|
emp_working_days = float(entry.get("working_days") or wd)
|
|
actual_days = float(actual) if actual is not None else emp_working_days
|
|
ratio = Decimal(str(actual_days)) / Decimal(str(emp_working_days or 1)) if prorate else Decimal("1")
|
|
ratio = min(max(ratio, Decimal("0")), Decimal("3"))
|
|
|
|
plan = plans.get(std.plan_id) if std else None
|
|
base_values: dict[str, Decimal] = {}
|
|
for code, value in ((plan.items if plan and plan.items else {}) or {}).items():
|
|
base_values[code] = q2(value)
|
|
for code, value in ((std.overrides if std else None) or {}).items():
|
|
base_values[code] = q2(value)
|
|
for code, value in entry_items.items():
|
|
base_values[code] = q2(value)
|
|
|
|
if not std:
|
|
missing_standard.append(emp.name)
|
|
|
|
amounts: dict[str, float] = {}
|
|
gross = Decimal("0")
|
|
manual_items = set(entry_items)
|
|
for code, value in base_values.items():
|
|
meta = items_meta.get(code, {})
|
|
if meta and not meta["include_in_gross"]:
|
|
amounts[code] = float(value)
|
|
continue
|
|
scaled = q2(value * ratio) if (prorate and meta.get("calc_type") != "manual"
|
|
and code not in manual_items) else q2(value)
|
|
amounts[code] = float(scaled)
|
|
if not meta or meta.get("include_in_gross"):
|
|
gross += scaled
|
|
gross = q2(gross)
|
|
|
|
ins_personal = ins_company = Decimal("0.00")
|
|
ins_detail: dict[str, Any] = {}
|
|
enrollment = enrollments.get(emp.id)
|
|
ins_plan = ins_plans.get(enrollment.plan_id) if enrollment else None
|
|
if include_insurance and enrollment and ins_plan:
|
|
ins_personal, ins_company, ins_detail = insurance_split(ins_plan, enrollment, gross)
|
|
|
|
special = q2(std.special_deduction if std else 0)
|
|
cum_before, tax_paid_before = await _cumulative_context(session, emp.id, year, month)
|
|
taxable_this = gross - ins_personal - special - TAX_THRESHOLD
|
|
cum_taxable = max(Decimal("0"), cum_before + taxable_this)
|
|
cum_tax = tax_on_cumulative(cum_taxable) if include_tax else Decimal("0.00")
|
|
tax = max(Decimal("0.00"), q2(cum_tax - tax_paid_before)) if include_tax else Decimal("0.00")
|
|
|
|
extra_deductions = Decimal("0")
|
|
for code, value in amounts.items():
|
|
meta = items_meta.get(code)
|
|
if meta and meta["category"] == "deduction":
|
|
extra_deductions += q2(value)
|
|
deductions = q2(ins_personal + tax + extra_deductions)
|
|
net = q2(gross - deductions)
|
|
if net < 0:
|
|
net = Decimal("0.00")
|
|
|
|
slip = Payslip(
|
|
batch_id=batch.id, employee_id=emp.id, period_id=period.id, year=year, month=month,
|
|
items={"amounts": amounts, "insurance": ins_detail, "labels": {
|
|
code: items_meta.get(code, {}).get("name", code) for code in amounts}},
|
|
gross=gross, insurance_personal=ins_personal, insurance_company=ins_company,
|
|
special_deduction=special, taxable_cumulative=cum_taxable, tax=tax, deductions=deductions,
|
|
net=net, working_days=emp_working_days, actual_days=actual_days,
|
|
insurance_plan_id=ins_plan.id if ins_plan else None, status="draft",
|
|
remark=entry.get("remark"),
|
|
)
|
|
session.add(slip)
|
|
created.append(slip)
|
|
summary["gross"] += gross
|
|
summary["insurance_personal"] += ins_personal
|
|
summary["insurance_company"] += ins_company
|
|
summary["tax"] += tax
|
|
summary["deduction"] += deductions
|
|
summary["net"] += net
|
|
|
|
await session.flush()
|
|
batch.employee_count = len(created)
|
|
batch.gross_total = summary["gross"]
|
|
batch.deduction_total = summary["deduction"]
|
|
batch.net_total = summary["net"]
|
|
batch.tax_total = summary["tax"]
|
|
batch.insurance_total = summary["insurance_personal"] + summary["insurance_company"]
|
|
batch.status = "calculated"
|
|
from ..db.base import utcnow
|
|
|
|
batch.calculated_at = utcnow()
|
|
batch.calculated_by = None
|
|
await session.flush()
|
|
return {
|
|
"employee_count": len(created),
|
|
"gross_total": float(summary["gross"]),
|
|
"insurance_personal_total": float(summary["insurance_personal"]),
|
|
"insurance_company_total": float(summary["insurance_company"]),
|
|
"tax_total": float(summary["tax"]),
|
|
"deduction_total": float(summary["deduction"]),
|
|
"net_total": float(summary["net"]),
|
|
"missing_standard": missing_standard[:20],
|
|
"working_days": wd,
|
|
}
|
|
|
|
|
|
async def recalc_payslip(session: AsyncSession, slip: Payslip, items_meta: dict | None = None
|
|
) -> Payslip:
|
|
"""Re-derive totals after a manual item edit on a single payslip."""
|
|
items_meta = items_meta or await resolve_items(session)
|
|
payload = dict(slip.items or {})
|
|
amounts = {k: q2(v) for k, v in (payload.get("amounts") or {}).items()}
|
|
gross = Decimal("0")
|
|
deductions_only = Decimal("0")
|
|
for code, value in amounts.items():
|
|
meta = items_meta.get(code, {})
|
|
if meta.get("include_in_gross", True):
|
|
gross += value
|
|
if meta.get("category") == "deduction":
|
|
deductions_only += value
|
|
tax = max(Decimal("0.00"), q2(slip.tax))
|
|
slip.gross = q2(gross)
|
|
slip.deductions = q2(q2(slip.insurance_personal) + tax + deductions_only)
|
|
slip.net = q2(max(Decimal("0"), slip.gross - slip.deductions))
|
|
slip.items = {**payload, "amounts": {k: float(v) for k, v in amounts.items()}}
|
|
await session.flush()
|
|
return slip
|
|
|
|
|
|
def month_label(year: int, month: int) -> str:
|
|
return f"{year}年{month:02d}月"
|
|
|
|
|
|
async def ensure_batch_editable(batch: PayrollBatch) -> None:
|
|
if batch.status in ("approved", "paid"):
|
|
raise AppError(f"工资表已{('发放' if batch.status == 'paid' else '审核')},不能修改", "locked", 409)
|