Public release from ruodoo-project: 19.0 - 2026-11-01 22:52:25 UTC

This commit is contained in:
CI Publish Bot
2026-11-01 22:54:30 +00:00
commit 26250aa580
2492 changed files with 664277 additions and 0 deletions

View File

@@ -0,0 +1,16 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import hr_contract
from . import hr_employee
from . import hr_payroll_structure
from . import hr_salary_rule
from . import hr_salary_rule_category
from . import hr_rule_input
from . import hr_contribution_register
from . import base_browsable
from . import hr_payslip
from . import hr_payslip_line
from . import hr_payslip_input
from . import hr_payslip_worked_days
from . import hr_payslip_run
from . import res_config_settings

View File

@@ -0,0 +1,101 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo import fields
_logger = logging.getLogger(__name__)
class BaseBrowsableObject:
def __init__(self, vals_dict):
self.__dict__["base_fields"] = ["base_fields", "dict"]
self.dict = vals_dict
def __getattr__(self, attr):
return attr in self.dict and self.dict.__getitem__(attr) or 0.0
def __setattr__(self, attr, value):
_fields = self.__dict__["base_fields"]
if attr in _fields:
return super().__setattr__(attr, value)
self.__dict__["dict"][attr] = value
def __str__(self):
return str(self.__dict__)
# These classes are used in the _get_payslip_lines() method
class BrowsableObject(BaseBrowsableObject):
def __init__(self, employee_id, vals_dict, env):
super().__init__(vals_dict)
self.base_fields += ["employee_id", "env"]
self.employee_id = employee_id
self.env = env
class InputLine(BrowsableObject):
"""a class that will be used into the python code, mainly for
usability purposes"""
def sum(self, code, from_date, to_date=None):
if to_date is None:
to_date = fields.Date.today()
self.env.cr.execute(
"""
SELECT sum(amount) as sum
FROM hr_payslip as hp, hr_payslip_input as pi
WHERE hp.employee_id = %s AND hp.state = 'done'
AND hp.date_from >= %s AND hp.date_to <= %s
AND hp.id = pi.payslip_id AND pi.code = %s""",
(self.employee_id, from_date, to_date, code),
)
return self.env.cr.fetchone()[0] or 0.0
class WorkedDays(BrowsableObject):
"""a class that will be used into the python code, mainly for
usability purposes"""
def _sum(self, code, from_date, to_date=None):
if to_date is None:
to_date = fields.Date.today()
self.env.cr.execute(
"""
SELECT sum(number_of_days) as number_of_days,
sum(number_of_hours) as number_of_hours
FROM hr_payslip as hp, hr_payslip_worked_days as pi
WHERE hp.employee_id = %s AND hp.state = 'done'
AND hp.date_from >= %s AND hp.date_to <= %s
AND hp.id = pi.payslip_id AND pi.code = %s""",
(self.employee_id, from_date, to_date, code),
)
return self.env.cr.fetchone()
def sum(self, code, from_date, to_date=None):
res = self._sum(code, from_date, to_date)
return res and res[0] or 0.0
def sum_hours(self, code, from_date, to_date=None):
res = self._sum(code, from_date, to_date)
return res and res[1] or 0.0
class Payslips(BrowsableObject):
"""a class that will be used into the python code, mainly for
usability purposes"""
def sum(self, code, from_date, to_date=None):
if to_date is None:
to_date = fields.Date.today()
self.env.cr.execute(
"""SELECT sum(case when hp.credit_note = False then
(pl.total) else (-pl.total) end)
FROM hr_payslip as hp, hr_payslip_line as pl
WHERE hp.employee_id = %s AND hp.state = 'done'
AND hp.date_from >= %s AND hp.date_to <= %s AND
hp.id = pl.slip_id AND pl.code = %s""",
(self.employee_id, from_date, to_date, code),
)
res = self.env.cr.fetchone()
return res and res[0] or 0.0

View File

@@ -0,0 +1,48 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class HrContract(models.Model):
"""
Employee contract based on the visa, work permits
allows to configure different Salary structure
"""
_inherit = "hr.version"
_description = "Employee Contract / Version"
struct_id = fields.Many2one("hr.payroll.structure", string="Salary Structure")
schedule_pay = fields.Selection(
[
("monthly", "Monthly"),
("quarterly", "Quarterly"),
("semi-annually", "Semi-annually"),
("annually", "Annually"),
("weekly", "Weekly"),
("bi-weekly", "Bi-weekly"),
("bi-monthly", "Bi-monthly"),
],
string="Scheduled Pay",
index=True,
default="monthly",
help="Defines the frequency of the wage payment.",
)
resource_calendar_id = fields.Many2one(help="Employee's working schedule.")
@api.model
def _get_whitelist_fields_from_template(self):
whitelist = super()._get_whitelist_fields_from_template()
for field_name in ("schedule_pay", "struct_id"):
if field_name not in whitelist:
whitelist.append(field_name)
return whitelist
def get_all_structures(self):
"""
@return: the structures linked to the given contracts, ordered by
hierachy (parent=False first, then first level children and
so on) and without duplicates
"""
# TODO: remove, too simple and not used
return self.struct_id.get_structure_with_parents()

View File

@@ -0,0 +1,20 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class HrContributionRegister(models.Model):
_name = "hr.contribution.register"
_description = "Contribution Register"
company_id = fields.Many2one(
"res.company",
string="Company",
default=lambda self: self.env.company,
)
partner_id = fields.Many2one("res.partner", string="Partner")
name = fields.Char(required=True)
register_line_ids = fields.One2many(
"hr.payslip.line", "register_id", string="Register Line", readonly=True
)
note = fields.Text(string="Description")

View File

@@ -0,0 +1,20 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class HrEmployee(models.Model):
_inherit = "hr.employee"
_description = "Employee"
slip_ids = fields.One2many(
"hr.payslip", "employee_id", string="Payslips", readonly=True
)
payslip_count = fields.Integer(
compute="_compute_payslip_count",
groups="payroll.group_payroll_user",
)
def _compute_payslip_count(self):
for employee in self:
employee.payslip_count = len(employee.slip_ids)

View File

@@ -0,0 +1,87 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.exceptions import ValidationError
class HrPayrollStructure(models.Model):
"""
Salary structure used to defined
- Basic
- Allowances
- Deductions
"""
_name = "hr.payroll.structure"
_description = "Salary Structure"
@api.model
def _get_parent(self):
return self.env.ref("hr_payroll.structure_base", False)
name = fields.Char(required=True)
code = fields.Char(string="Reference")
company_id = fields.Many2one(
"res.company",
string="Company",
required=True,
copy=False,
default=lambda self: self.env.company,
)
note = fields.Text(string="Description")
parent_id = fields.Many2one(
"hr.payroll.structure",
string="Parent",
default=lambda self: self._get_parent(),
)
children_ids = fields.One2many(
"hr.payroll.structure", "parent_id", string="Children", copy=True
)
rule_ids = fields.Many2many(
"hr.salary.rule",
"hr_structure_salary_rule_rel",
"struct_id",
"rule_id",
string="Salary Rules",
)
require_code = fields.Boolean(
"Require code",
compute="_compute_require_code",
default=lambda self: self._compute_require_code(),
)
def _compute_require_code(self):
require = (
self.env["ir.config_parameter"]
.sudo()
.get_param("payroll.require_code_and_category")
)
self.require_code = require
return require
@api.constrains("parent_id")
def _check_parent_id(self):
if self._has_cycle():
raise ValidationError(
self.env._("You cannot create a recursive salary structure.")
)
def copy(self, default=None):
self.ensure_one()
default = dict(
default or {},
code=self.env._("%(code)s (copy)", code=self.code),
)
return super().copy(default)
def get_all_rules(self):
"""
@return: recordset with all struct rules, ordered by sequence
"""
return self.rule_ids._recursive_search_of_rules().sorted("sequence")
def get_structure_with_parents(self):
if not self:
return self.env["hr.payroll.structure"]
else:
return self.parent_id.get_structure_with_parents() + self

View File

@@ -0,0 +1,806 @@
# Part of Odoo. LICENSE file for full copyright and licensing details.
import logging
import math
from datetime import date, datetime, time
import babel
from dateutil.relativedelta import relativedelta
from pytz import timezone
from odoo import api, fields, models
from odoo.exceptions import UserError, ValidationError
from .base_browsable import (
BaseBrowsableObject,
BrowsableObject,
InputLine,
Payslips,
WorkedDays,
)
_logger = logging.getLogger(__name__)
class HrPayslip(models.Model):
_name = "hr.payslip"
_inherit = ["mail.thread", "mail.activity.mixin"]
_description = "Payslip"
_order = "id desc"
struct_id = fields.Many2one(
"hr.payroll.structure",
string="Structure",
readonly=True,
help="Defines the rules that have to be applied to this payslip, "
"accordingly to the contract chosen. If you let empty the field "
"contract, this field isn't mandatory anymore and thus the rules "
"applied will be all the rules set on the structure of all contracts "
"of the employee valid for the chosen period",
)
name = fields.Char(string="Payslip Name")
number = fields.Char(
string="Reference",
readonly=True,
copy=False,
)
employee_id = fields.Many2one(
"hr.employee",
string="Employee",
required=True,
readonly=True,
)
date_from = fields.Date(
readonly=True,
required=True,
default=lambda self: fields.Date.to_string(date.today().replace(day=1)),
tracking=True,
)
date_to = fields.Date(
readonly=True,
required=True,
default=lambda self: fields.Date.to_string(
(datetime.now() + relativedelta(months=+1, day=1, days=-1)).date()
),
tracking=True,
)
state = fields.Selection(
[
("draft", "Draft"),
("verify", "Waiting"),
("done", "Done"),
("cancel", "Rejected"),
],
string="Status",
index=True,
readonly=True,
copy=False,
default="draft",
tracking=True,
help="""* When the payslip is created the status is \'Draft\'
\n* If the payslip is under verification, the status is \'Waiting\'.
\n* If the payslip is confirmed then status is set to \'Done\'.
\n* When user cancel payslip the status is \'Rejected\'.""",
)
line_ids = fields.One2many(
"hr.payslip.line",
"slip_id",
string="Payslip Lines",
readonly=True,
)
company_id = fields.Many2one(
"res.company",
string="Company",
readonly=True,
copy=False,
default=lambda self: self.env.company,
)
worked_days_line_ids = fields.One2many(
"hr.payslip.worked_days",
"payslip_id",
string="Payslip Worked Days",
copy=True,
readonly=True,
)
input_line_ids = fields.One2many(
"hr.payslip.input",
"payslip_id",
string="Payslip Inputs",
readonly=True,
)
paid = fields.Boolean(
string="Made Payment Order ? ",
readonly=True,
copy=False,
)
note = fields.Text(
string="Internal Note",
readonly=True,
tracking=True,
)
contract_id = fields.Many2one(
"hr.version",
string="Contract",
readonly=True,
tracking=True,
)
dynamic_filtered_payslip_lines = fields.One2many(
"hr.payslip.line",
compute="_compute_dynamic_filtered_payslip_lines",
)
credit_note = fields.Boolean(
readonly=True,
help="Indicates this payslip has a refund of another",
)
payslip_run_id = fields.Many2one(
"hr.payslip.run",
string="Payslip Batches",
readonly=True,
copy=False,
tracking=True,
)
payslip_count = fields.Integer(
compute="_compute_payslip_count", string="Payslip Computation Details"
)
hide_child_lines = fields.Boolean(default=False)
hide_invisible_lines = fields.Boolean(
string="Show only lines that appear on payslip", default=False
)
compute_date = fields.Date()
refunded_id = fields.Many2one(
"hr.payslip", string="Refunded Payslip", readonly=True
)
allow_cancel_payslips = fields.Boolean(
"Allow Canceling Payslips", compute="_compute_allow_cancel_payslips"
)
prevent_compute_on_confirm = fields.Boolean(
"Prevent Compute on Confirm", compute="_compute_prevent_compute_on_confirm"
)
def _compute_allow_cancel_payslips(self):
self.allow_cancel_payslips = (
self.env["ir.config_parameter"]
.sudo()
.get_param("payroll.allow_cancel_payslips")
)
def _compute_prevent_compute_on_confirm(self):
self.prevent_compute_on_confirm = (
self.env["ir.config_parameter"]
.sudo()
.get_param("payroll.prevent_compute_on_confirm")
)
@api.depends("line_ids", "hide_child_lines", "hide_invisible_lines")
def _compute_dynamic_filtered_payslip_lines(self):
for payslip in self:
lines = payslip.line_ids
if payslip.hide_child_lines:
lines = lines.filtered(lambda line: not line.parent_rule_id)
if payslip.hide_invisible_lines:
lines = lines.filtered(lambda line: line.appears_on_payslip)
payslip.dynamic_filtered_payslip_lines = lines
def _compute_payslip_count(self):
for payslip in self:
payslip.payslip_count = len(payslip.line_ids)
@api.constrains("date_from", "date_to")
def _check_dates(self):
if any(self.filtered(lambda payslip: payslip.date_from > payslip.date_to)):
raise ValidationError(
self.env._("Payslip 'Date From' must be earlier than 'Date To'.")
)
def copy(self, default=None):
rec = super().copy(default)
for line in self.input_line_ids:
line.copy({"payslip_id": rec.id})
for line in self.line_ids:
line.copy({"slip_id": rec.id, "input_ids": []})
return rec
def action_payslip_draft(self):
return self.write({"state": "draft"})
def action_payslip_done(self):
if (
not self.env.context.get("without_compute_sheet")
and not self.prevent_compute_on_confirm
):
self.compute_sheet()
return self.write({"state": "done"})
def action_payslip_cancel(self):
for payslip in self:
if payslip.allow_cancel_payslips:
if payslip.refunded_id and payslip.refunded_id.state != "cancel":
raise ValidationError(
self.env._(
"""To cancel the Original Payslip the
Refunded Payslip needs to be canceled first!"""
)
)
else:
if self.filtered(lambda slip: slip.state == "done"):
raise UserError(self.env._("Cannot cancel a payslip that is done."))
return self.write({"state": "cancel"})
def refund_sheet(self):
copied_payslips = self.env["hr.payslip"]
for payslip in self:
# Create a refund slip
copied_payslip = payslip.copy(
{
"credit_note": True,
"name": self.env._("Refund: %(name)s", name=payslip.name),
}
)
# Assign a number
number = copied_payslip.number or self.env["ir.sequence"].next_by_code(
"salary.slip"
)
copied_payslip.write({"number": number})
# Validated refund slip
copied_payslip.with_context(
without_compute_sheet=True
).action_payslip_done()
# Write refund reference on payslip
payslip.write(
{"refunded_id": copied_payslip.id if copied_payslip else False}
)
# Add to list of refund slips
copied_payslips |= copied_payslip
# Action to open list view of refund slips
formview_ref = self.env.ref("payroll.hr_payslip_view_form", False)
treeview_ref = self.env.ref("payroll.hr_payslip_view_tree", False)
res = {
"name": self.env._("Refund Payslip"),
"view_mode": "list, form",
"view_id": False,
"res_model": "hr.payslip",
"type": "ir.actions.act_window",
"target": "current",
"domain": [("id", "in", copied_payslips.ids)],
"views": [
(treeview_ref and treeview_ref.id or False, "list"),
(formview_ref and formview_ref.id or False, "form"),
],
"context": {},
}
return res
@api.ondelete(at_uninstall=False)
def _unlink_except_draft_cancel(self):
if any(self.filtered(lambda payslip: payslip.state not in ("draft", "cancel"))):
raise UserError(
self.env._(
"You cannot delete a payslip which is not draft or cancelled"
)
)
def compute_sheet(self):
for payslip in self:
# delete old payslip lines
payslip.line_ids.unlink()
# write payslip lines
number = payslip.number or self.env["ir.sequence"].next_by_code(
"salary.slip"
)
lines = [(0, 0, line) for line in list(payslip.get_lines_dict().values())]
payslip.write(
{
"line_ids": lines,
"number": number,
"state": "verify",
"compute_date": fields.Date.today(),
}
)
return True
@api.model
def get_worked_day_lines(self, contracts, date_from, date_to):
"""
@param contracts: Browse record of contracts
@return: returns a list of dict containing the input that should be
applied for the given contract between date_from and date_to
"""
res = []
for contract in contracts.filtered(
lambda contract: contract.resource_calendar_id
):
day_from = datetime.combine(date_from, time.min)
day_to = datetime.combine(date_to, time.max)
day_contract_start = datetime.combine(contract.date_start, time.min)
# Support for the hr_public_holidays module.
contract = contract.with_context(
employee_id=self.employee_id.id, exclude_public_holidays=True
)
# only use payslip day_from if it's greather than contract start date
if day_from < day_contract_start:
day_from = day_contract_start
# == compute leave days == #
leaves = self._compute_leave_days(contract, day_from, day_to)
res.extend(leaves)
# == compute worked days == #
attendances = self._compute_worked_days(contract, day_from, day_to)
res.append(attendances)
return res
def _compute_leave_days(self, contract, day_from, day_to):
"""
Leave days computation
@return: returns a list containing the leave inputs for the period
of the payslip. One record per leave type.
"""
leaves_positive = (
self.env["ir.config_parameter"].sudo().get_param("payroll.leaves_positive")
)
leaves = {}
calendar = contract.resource_calendar_id
tz = timezone(calendar.tz or contract.employee_id.tz or "UTC")
day_leave_intervals = contract.employee_id.list_leaves(
day_from, day_to, calendar=contract.resource_calendar_id
)
for day, hours, leave in day_leave_intervals:
holiday = leave[:1].holiday_id
current_leave_struct = leaves.setdefault(
holiday.holiday_status_id,
{
"name": holiday.holiday_status_id.name
or self.env._("Global Leaves"),
"sequence": getattr(
getattr(holiday.holiday_status_id, "work_entry_type_id", None),
"sequence",
5,
),
"code": getattr(
getattr(holiday.holiday_status_id, "work_entry_type_id", None),
"code",
"GLOBAL",
),
"number_of_days": 0.0,
"number_of_hours": 0.0,
"contract_id": contract.id,
},
)
if leaves_positive:
current_leave_struct["number_of_hours"] += hours
else:
current_leave_struct["number_of_hours"] -= hours
work_hours = calendar.get_work_hours_count(
tz.localize(datetime.combine(day, time.min)),
tz.localize(datetime.combine(day, time.max)),
compute_leaves=False,
)
if work_hours:
if leaves_positive:
current_leave_struct["number_of_days"] += hours / work_hours
else:
current_leave_struct["number_of_days"] -= hours / work_hours
return leaves.values()
def _compute_worked_days(self, contract, day_from, day_to):
"""
Worked days computation
@return: returns a list containing the total worked_days for the period
of the payslip. This returns the FULL work days expected for the resource
calendar selected for the employee (it don't substract leaves by default).
"""
work_data = contract.employee_id._get_work_days_data_batch(
day_from,
day_to,
calendar=contract.resource_calendar_id,
compute_leaves=False,
)
return {
"name": self.env._("Normal Working Days paid at 100%"),
"sequence": 1,
"code": "WORK100",
"number_of_days": work_data[contract.employee_id.id]["days"],
"number_of_hours": work_data[contract.employee_id.id]["hours"],
"contract_id": contract.id,
}
@api.model
def get_inputs(self, contracts, date_from, date_to):
# TODO: We leave date_from and date_to params here for backwards
# compatibility reasons for the ones who inherit this function
# in another modules, but they are not used.
# Will be removed in next versions.
"""
Inputs computation.
@returns: Returns a dict with the inputs that are fetched from the salary_structure
associated rules for the given contracts.
""" # noqa: E501
res = []
payslip_inputs = self._get_salary_rules().input_ids
for contract in contracts:
for payslip_input in payslip_inputs:
res.append(
{
"name": payslip_input.name,
"code": payslip_input.code,
"contract_id": contract.id,
}
)
return res
def _init_payroll_dict_contracts(self):
return {
"count": 0,
}
def get_payroll_dict(self, contracts):
"""Setup miscellaneous dictionary values.
Other modules may overload this method to inject discreet values into
the salary rules. Such values will be available to the salary rule
under the `payroll.` prefix.
This method is evaluated once per payslip.
:param contracts: Recordset of all hr.contract records in this payslip
:return: a dictionary of discreet values and/or Browsable Objects
"""
self.ensure_one()
res = {
# In salary rules refer to this as: payroll.contracts.count
"contracts": BaseBrowsableObject(self._init_payroll_dict_contracts()),
}
res["contracts"].count = len(contracts)
return res
def get_current_contract_dict(self, contract, contracts):
"""Contract dependent dictionary values.
This method is called just before the salary rules are evaluated for
contract.
This method is evaluated once for every contract in the payslip.
:param contract: The current hr.contract being processed
:param contracts: Recordset of all hr.contract records in this payslip
:return: a dictionary of discreet values and/or Browsable Objects
"""
self.ensure_one()
# res = super().get_current_contract_dict(contract, contracts)
# res.update({
# # In salary rules refer to these as:
# # current_contract.foo
# # current_contract.foo.bar.baz
# "foo": 0,
# "bar": BaseBrowsableObject(
# {
# "baz": 0
# }
# )
# })
# <do something to update values in res>
# return res
return {}
def _get_tools_dict(self):
# _get_tools_dict() is intended to be inherited by other private modules
# to add tools or python libraries available in localdict
return {"math": math} # "math" object is useful for doing calculations
def _get_baselocaldict(self, contracts):
self.ensure_one()
worked_days_dict = {
line.code: line for line in self.worked_days_line_ids if line.code
}
input_lines_dict = {
line.code: line for line in self.input_line_ids if line.code
}
localdict = {
"payslips": Payslips(self.employee_id.id, self, self.env),
"worked_days": WorkedDays(self.employee_id.id, worked_days_dict, self.env),
"inputs": InputLine(self.employee_id.id, input_lines_dict, self.env),
"payroll": BrowsableObject(
self.employee_id.id, self.get_payroll_dict(contracts), self.env
),
"current_contract": BrowsableObject(self.employee_id.id, {}, self.env),
"categories": BrowsableObject(self.employee_id.id, {}, self.env),
"rules": BrowsableObject(self.employee_id.id, {}, self.env),
"result_rules": BrowsableObject(self.employee_id.id, {}, self.env),
"tools": BrowsableObject(
self.employee_id.id, self._get_tools_dict(), self.env
),
}
return localdict
def _get_salary_rules(self):
"Return rules for the Paylips, sorted by sequence"
# Only compute rules when there is at least one valid contract in the period
contracts = self._get_employee_contracts()
if not contracts:
return self.env["hr.salary.rule"]
current_structure = self.struct_id
if current_structure:
structures = current_structure.get_structure_with_parents()
else:
structures = contracts.struct_id.get_structure_with_parents()
return structures.get_all_rules()
def _compute_payslip_line(self, rule, localdict, lines_dict):
self.ensure_one()
# check if there is already a rule computed with that code
previous_amount = rule.code in localdict and localdict[rule.code] or 0.0
# compute the rule to get some values for the payslip line
values = rule._compute_rule(localdict)
key = (rule.code or "id" + str(rule.id)) + "-" + str(localdict["contract"].id)
return self._get_lines_dict(
rule, localdict, lines_dict, key, values, previous_amount
)
def _get_lines_dict(
self, rule, localdict, lines_dict, key, values, previous_amount
):
total = values["quantity"] * values["rate"] * values["amount"] / 100.0
values["total"] = total
# set/overwrite the amount computed for this rule in the localdict
if rule.code:
localdict[rule.code] = total
localdict["rules"].dict[rule.code] = rule
localdict["result_rules"].dict[rule.code] = BaseBrowsableObject(values)
# sum the amount for its salary category
localdict = self._sum_salary_rule_category(
localdict, rule.category_id, total - previous_amount
)
# create/overwrite the line in the temporary results
line_dict = {
"salary_rule_id": rule.id,
"employee_id": localdict["employee"].id,
"contract_id": localdict["contract"].id,
"code": rule.code,
"category_id": rule.category_id.id,
"sequence": rule.sequence,
"appears_on_payslip": rule.appears_on_payslip,
"parent_rule_id": rule.parent_rule_id.id,
"condition_select": rule.condition_select,
"condition_python": rule.condition_python,
"condition_range": rule.condition_range,
"condition_range_min": rule.condition_range_min,
"condition_range_max": rule.condition_range_max,
"amount_select": rule.amount_select,
"amount_fix": rule.amount_fix,
"amount_python_compute": rule.amount_python_compute,
"amount_percentage": rule.amount_percentage,
"amount_percentage_base": rule.amount_percentage_base,
"register_id": rule.register_id.id,
}
line_dict.update(values)
lines_dict[key] = line_dict
return localdict, lines_dict
@api.model
def _get_payslip_lines(self, _contract_ids, payslip_id):
_logger.warning(
"Use of _get_payslip_lines() is deprecated. Use get_lines_dict() instead."
)
return self.browse(payslip_id).get_lines_dict()
def get_lines_dict(self):
lines_dict = {}
blacklist = self.env["hr.salary.rule"]
for payslip in self:
contracts = payslip._get_employee_contracts()
baselocaldict = payslip._get_baselocaldict(contracts)
for contract in contracts:
# assign "current_contract" dict
baselocaldict["current_contract"] = BrowsableObject(
payslip.employee_id.id,
payslip.get_current_contract_dict(contract, contracts),
payslip.env,
)
# set up localdict with current contract and employee values
localdict = dict(
baselocaldict,
employee=contract.employee_id,
contract=contract,
payslip=payslip,
)
for rule in payslip._get_salary_rules():
localdict = rule._reset_localdict_values(localdict)
# check if the rule can be applied
if rule._satisfy_condition(localdict) and rule not in blacklist:
localdict, _dict = payslip._compute_payslip_line(
rule, localdict, lines_dict
)
lines_dict.update(_dict)
else:
# blacklist this rule and its children
blacklist += rule._recursive_search_of_rules()
# call localdict_hook
localdict = payslip.localdict_hook(localdict)
# reset "current_contract" dict
baselocaldict["current_contract"] = {}
return lines_dict
def localdict_hook(self, localdict):
# This hook is called when the function _get_lines_dict ends the loop
# and before its returns. This method by itself don't add any functionality
# and is intedend to be inherited to access localdict from other functions.
return localdict
def get_payslip_vals(
self, date_from, date_to, employee_id=False, contract_id=False, struct_id=False
):
# Normalize incoming dates (tests may pass datetimes)
date_from = fields.Date.to_date(date_from) if date_from else date_from
date_to = fields.Date.to_date(date_to) if date_to else date_to
# Initial default values for generated payslips
employee = self.env["hr.employee"].browse(employee_id)
res = {
"value": {
"line_ids": [],
"input_line_ids": [(2, x) for x in self.input_line_ids.ids],
"worked_days_line_ids": [(2, x) for x in self.worked_days_line_ids.ids],
"name": "",
"contract_id": False,
"struct_id": False,
}
}
# If we don't have employee or date data, we return.
if (not employee_id) or (not date_from) or (not date_to):
return res
# We check if contract_id is present, if not we pick the contract(s)
# of the employee in the given period. If no contract present, we return.
if not self.env.context.get("contract"):
contracts_by_emp = employee._get_contracts(
date_start=date_from,
date_end=date_to,
)
default_versions = self.env["hr.version"]
contract_ids = contracts_by_emp.get(employee.id, default_versions).ids
else:
if contract_id:
contract_ids = [contract_id]
else:
contracts_by_emp = employee._get_contracts(
date_start=date_from,
date_end=date_to,
)
default_versions = self.env["hr.version"]
contract_ids = contracts_by_emp.get(employee.id, default_versions).ids
if not contract_ids:
return res
contract = self.env["hr.version"].browse(contract_ids[0])
res["value"].update({"contract_id": contract.id})
# We check if struct_id is already filled, otherwise we assign the contract struct. # noqa: E501
# If contract don't have a struct, we return.
if struct_id:
res["value"].update({"struct_id": struct_id[0]})
else:
struct = contract.struct_id
if not struct:
return res
res["value"].update({"struct_id": struct.id})
# Computation of the salary input and worked_day_lines
contracts = self.env["hr.version"].browse(contract_ids)
worked_days_line_ids = self.get_worked_day_lines(contracts, date_from, date_to)
input_line_ids = self.get_inputs(contracts, date_from, date_to)
res["value"].update(
{
"worked_days_line_ids": worked_days_line_ids,
"input_line_ids": input_line_ids,
}
)
return res
def _sum_salary_rule_category(self, localdict, category, amount):
self.ensure_one()
if category.parent_id:
localdict = self._sum_salary_rule_category(
localdict, category.parent_id, amount
)
if category.code:
localdict["categories"].dict[category.code] = (
localdict["categories"].dict.get(category.code, 0) + amount
)
return localdict
def _get_employee_contracts(self):
contracts = self.env["hr.version"]
for payslip in self:
if payslip.contract_id.ids:
# only keep contract if it overlaps the payslip period
if payslip.contract_id._is_overlapping_period(
payslip.date_from, payslip.date_to
):
contracts |= payslip.contract_id
else:
contracts_by_emp = payslip.employee_id._get_contracts(
date_start=payslip.date_from, date_end=payslip.date_to
)
contracts |= contracts_by_emp.get(
payslip.employee_id.id, payslip.env["hr.version"]
)
return contracts
@api.onchange("struct_id")
def onchange_struct_id(self):
for payslip in self:
if not payslip.struct_id:
payslip.input_line_ids.unlink()
return
input_lines = payslip.input_line_ids.browse([])
input_line_ids = payslip.get_inputs(
payslip._get_employee_contracts(), payslip.date_from, payslip.date_to
)
for r in input_line_ids:
input_lines += input_lines.new(r)
payslip.input_line_ids = input_lines
@api.onchange("date_from", "date_to")
def onchange_dates(self):
for payslip in self:
if not payslip.date_from or not payslip.date_to:
return
worked_days_lines = payslip.worked_days_line_ids.browse([])
worked_days_line_ids = payslip.get_worked_day_lines(
payslip._get_employee_contracts(), payslip.date_from, payslip.date_to
)
for line in worked_days_line_ids:
worked_days_lines += worked_days_lines.new(line)
payslip.worked_days_line_ids = worked_days_lines
@api.onchange("employee_id", "date_from", "date_to")
def onchange_employee(self):
for payslip in self:
# Return if required values are not present.
if (
(not payslip.employee_id)
or (not payslip.date_from)
or (not payslip.date_to)
):
continue
# Assign contract_id automatically when the user don't selected one.
if not payslip.env.context.get("contract") or not payslip.contract_id:
contract_ids = payslip._get_employee_contracts().ids
if not contract_ids:
continue
payslip.contract_id = payslip.env["hr.version"].browse(contract_ids[0])
# Assign struct_id automatically when the user don't selected one.
if not payslip.struct_id and not payslip.env.context.get("struct_id"):
if not payslip.contract_id.struct_id:
continue
payslip.struct_id = payslip.contract_id.struct_id
# Compute payslip name
payslip._compute_name()
# Call worked_days_lines computation when employee is changed.
payslip.onchange_dates()
# Call input_lines computation when employee is changed.
payslip.onchange_struct_id()
# Assign company_id automatically based on employee selected.
payslip.company_id = payslip.employee_id.company_id
def _compute_name(self):
for record in self:
date_formatted = babel.dates.format_date(
date=datetime.combine(record.date_from, time.min),
format="MMMM-y",
locale=record.env.context.get("lang") or "en_US",
)
record.name = record.env._(
"Salary Slip of %(name)s for %(dt)s",
name=record.employee_id.name,
dt=str(date_formatted),
)
@api.onchange("contract_id")
def onchange_contract(self):
if not self.contract_id:
self.struct_id = False
self.with_context(contract=True).onchange_employee()
return
def get_salary_line_total(self, code):
self.ensure_one()
line = self.line_ids.filtered(lambda line: line.code == code)
if line:
return line[0].total
else:
return 0.0

View File

@@ -0,0 +1,32 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class HrPayslipInput(models.Model):
_name = "hr.payslip.input"
_description = "Payslip Input"
_order = "payslip_id, sequence"
name = fields.Char(string="Description", required=True)
payslip_id = fields.Many2one(
"hr.payslip", string="Pay Slip", required=True, ondelete="cascade", index=True
)
sequence = fields.Integer(required=True, index=True, default=10)
code = fields.Char(
required=True, help="The code that can be used in the salary rules"
)
amount = fields.Float(
help="It is used in computation. For e.g. A rule for sales having "
"1% commission of basic salary for per product can defined in "
"expression like result = inputs.SALEURO.amount * contract.wage*0.01."
)
amount_qty = fields.Float(
"Amount Quantity", help="It can be used in computation for other inputs"
)
contract_id = fields.Many2one(
"hr.version",
string="Contract",
required=True,
help="The contract for which applied this input",
)

View File

@@ -0,0 +1,97 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.exceptions import UserError
class HrPayslipLine(models.Model):
_name = "hr.payslip.line"
_inherit = "hr.salary.rule"
_description = "Payslip Line"
_order = "contract_id, sequence"
slip_id = fields.Many2one(
"hr.payslip", string="Pay Slip", required=True, ondelete="cascade"
)
date_from = fields.Date("Date From", related="slip_id.date_from", store=True)
payslip_run_id = fields.Many2one(
"hr.payslip.run", related="slip_id.payslip_run_id", string="Payslip Batch"
)
child_ids = fields.One2many(
"hr.payslip.line", "parent_line_id", string="Child Payslip Lines"
)
parent_line_id = fields.Many2one(
"hr.payslip.line",
string="Parent Payslip Line",
compute="_compute_parent_line_id",
store=True,
)
salary_rule_id = fields.Many2one("hr.salary.rule", string="Rule", required=True)
employee_id = fields.Many2one("hr.employee", string="Employee", required=True)
contract_id = fields.Many2one(
"hr.version", string="Contract", required=True, index=True
)
rate = fields.Float(string="Rate (%)", digits="Payroll Rate", default=100.0)
amount = fields.Float(digits="Payroll")
quantity = fields.Float(digits="Payroll", default=1.0)
total = fields.Float(
compute="_compute_total",
digits="Payroll",
store=True,
)
allow_edit_payslip_lines = fields.Boolean(
"Allow editing", compute="_compute_allow_edit_payslip_lines"
)
def _compute_allow_edit_payslip_lines(self):
self.allow_edit_payslip_lines = (
self.env["ir.config_parameter"]
.sudo()
.get_param("payroll.allow_edit_payslip_lines")
)
@api.depends("parent_rule_id", "contract_id", "slip_id")
def _compute_parent_line_id(self):
for line in self:
if line.parent_rule_id:
parent_line = line.slip_id.line_ids.filtered(
lambda record, line=line: record.salary_rule_id
== line.parent_rule_id
and record.contract_id == line.contract_id
and record.slip_id == line.slip_id
)
if parent_line and len(parent_line) > 1:
msg = self.env._(
"Recursion error. Only one line should be parent of %(rule)s",
rule=line.parent_rule_id.name,
)
raise UserError(msg)
line.parent_line_id = (
parent_line[0].id if len(parent_line) == 1 else False
)
else:
line.parent_line_id = False
@api.depends("quantity", "amount", "rate")
def _compute_total(self):
for line in self:
line.total = float(line.quantity) * line.amount * line.rate / 100
@api.model_create_multi
def create(self, vals_list):
for values in vals_list:
if "employee_id" not in values or "contract_id" not in values:
payslip = self.env["hr.payslip"].browse(values.get("slip_id"))
values["employee_id"] = (
values.get("employee_id") or payslip.employee_id.id
)
values["contract_id"] = (
values.get("contract_id")
or payslip.contract_id
and payslip.contract_id.id
)
if not values["contract_id"]:
raise UserError(
self.env._("You must set a contract to create a payslip line.")
)
return super().create(vals_list)

View File

@@ -0,0 +1,70 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from dateutil.relativedelta import relativedelta
from odoo import fields, models
class HrPayslipRun(models.Model):
_name = "hr.payslip.run"
_inherit = ["mail.thread", "mail.activity.mixin"]
_description = "Payslip Batches"
_order = "id desc"
name = fields.Char(required=True, readonly=True)
slip_ids = fields.One2many(
"hr.payslip",
"payslip_run_id",
string="Payslips",
readonly=True,
)
state = fields.Selection(
[("draft", "Draft"), ("close", "Close")],
string="Status",
index=True,
readonly=True,
copy=False,
tracking=1,
default="draft",
)
company_id = fields.Many2one(
"res.company",
string="Company",
required=True,
copy=False,
default=lambda self: self.env.company,
)
date_start = fields.Date(
string="Date From",
required=True,
readonly=True,
default=lambda self: fields.Date.today().replace(day=1),
)
date_end = fields.Date(
string="Date To",
required=True,
readonly=True,
default=lambda self: fields.Date.today().replace(day=1)
+ relativedelta(months=+1, day=1, days=-1),
)
credit_note = fields.Boolean(
readonly=True,
help="If its checked, indicates that all payslips generated from here "
"are refund payslips.",
)
struct_id = fields.Many2one(
"hr.payroll.structure",
string="Structure",
readonly=True,
help="Defines the rules that have to be applied to this payslip batch, "
"accordingly to the contract chosen. If you let empty the field "
"contract, this field isn't mandatory anymore and thus the rules "
"applied will be all the rules set on the structure of all contracts "
"of the employee valid for the chosen period",
)
def draft_payslip_run(self):
return self.write({"state": "draft"})
def close_payslip_run(self):
return self.write({"state": "close"})

View File

@@ -0,0 +1,26 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class HrPayslipWorkedDays(models.Model):
_name = "hr.payslip.worked_days"
_description = "Payslip Worked Days"
_order = "payslip_id, sequence"
name = fields.Char(string="Description", required=True)
payslip_id = fields.Many2one(
"hr.payslip", string="Pay Slip", required=True, ondelete="cascade", index=True
)
sequence = fields.Integer(required=True, index=True, default=10)
code = fields.Char(
required=True, help="The code that can be used in the salary rules"
)
number_of_days = fields.Float(string="Number of Days")
number_of_hours = fields.Float(string="Number of Hours")
contract_id = fields.Many2one(
"hr.version",
string="Contract",
required=True,
help="The contract for which applied this input",
)

View File

@@ -0,0 +1,16 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class HrRuleInput(models.Model):
_name = "hr.rule.input"
_description = "Salary Rule Input"
name = fields.Char(string="Description", required=True)
code = fields.Char(
required=True, help="The code that can be used in the salary rules"
)
input_id = fields.Many2one(
"hr.salary.rule", string="Salary Rule Input", required=True
)

View File

@@ -0,0 +1,336 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import traceback
from odoo import api, fields, models
from odoo.exceptions import UserError, ValidationError
from odoo.tools.safe_eval import safe_eval
class HrSalaryRule(models.Model):
_name = "hr.salary.rule"
_order = "sequence, id"
_description = "Salary Rule"
name = fields.Char(required=True, translate=True)
code = fields.Char(
help="The code of salary rules can be used as reference in computation "
"of other rules. In that case, it is case sensitive.",
)
sequence = fields.Integer(
required=True, index=True, default=5, help="Use to arrange calculation sequence"
)
quantity = fields.Char(
default="1.0",
help="It is used in computation for percentage and fixed amount. "
"For e.g. A rule for Meal Voucher having fixed amount of "
"1€ per worked day can have its quantity defined in expression "
"like worked_days.WORK100.number_of_days.",
)
category_id = fields.Many2one("hr.salary.rule.category", string="Category")
active = fields.Boolean(
default=True,
help="If the active field is set to false, it will allow you to hide"
" the salary rule without removing it.",
)
appears_on_payslip = fields.Boolean(
string="Appears on Payslip",
default=True,
help="Used to display the salary rule on payslip.",
)
parent_rule_id = fields.Many2one(
comodel_name="hr.salary.rule", string="Parent Salary Rule", index=True
)
company_id = fields.Many2one(
"res.company",
string="Company",
default=lambda self: self.env.company,
)
condition_select = fields.Selection(
[("none", "Always True"), ("range", "Range"), ("python", "Python Expression")],
string="Condition Based on",
default="none",
required=True,
)
condition_range = fields.Char(
string="Range Based on",
default="contract.wage",
help="This will be used to compute the % fields values; in general it "
"is on basic, but you can also use categories code fields in "
"lowercase as a variable names (hra, ma, lta, etc.) and the "
"variable basic.",
)
condition_python = fields.Text(
string="Python Condition",
required=True,
default="""# Available variables:
#-------------------------------
# payslip: hr.payslip object
# payslips: object containing payslips (browsable)
# employee: hr.employee object
# contract: hr.contract object
# rules: object containing the rules code (previously computed)
# categories: object containing the computed salary rule categories
# (sum of amount of all rules belonging to that category).
# worked_days: object containing the computed worked days.
# inputs: object containing the computed inputs.
# payroll: object containing miscellaneous values related to payroll
# current_contract: object with values calculated from the current contract
# result_rules: object with a dict of qty, rate, amount an total of calculated rules
# tools: object that contain libraries and tools that can be used in calculations
# Available compute variables:
#-------------------------------
# result: returned value have to be set in the variable 'result'
# Example:
#-------------------------------
# result = worked_days.WORK0 and worked_days.WORK0.number_of_days > 0""", # noqa: E501
help="Applied this rule for calculation if condition is true. You can "
"specify condition like basic > 1000.",
)
condition_range_min = fields.Float(
string="Minimum Range", help="The minimum amount, applied for this rule."
)
condition_range_max = fields.Float(
string="Maximum Range", help="The maximum amount, applied for this rule."
)
amount_select = fields.Selection(
[
("percentage", "Percentage (%)"),
("fix", "Fixed Amount"),
("code", "Python Code"),
],
string="Amount Type",
index=True,
required=True,
default="fix",
help="The computation method for the rule amount.",
)
amount_fix = fields.Float(string="Fixed Amount", digits="Payroll")
amount_percentage = fields.Float(
string="Percentage (%)",
digits="Payroll Rate",
help="For example, enter 50.0 to apply a percentage of 50%",
)
amount_python_compute = fields.Text(
string="Python Code",
default="""# Available variables:
#-------------------------------
# payslip: hr.payslip object
# payslips: object containing payslips (browsable)
# employee: hr.employee object
# contract: hr.contract object
# rules: object containing the rules code (previously computed)
# categories: object containing the computed salary rule categories
# (sum of amount of all rules belonging to that category).
# worked_days: object containing the computed worked days.
# inputs: object containing the computed inputs.
# payroll: object containing miscellaneous values related to payroll
# current_contract: object with values calculated from the current contract
# result_rules: object with a dict of qty, rate, amount an total of calculated rules
# tools: object that contain libraries and tools that can be used in calculations
# Available compute variables:
#-------------------------------
# result: returned value have to be set in the variable 'result'
# result_rate: the rate that will be applied to "result".
# result_qty: the quantity of units that will be multiplied to "result".
# result_name: if this variable is computed, it will contain the name of the line.
# Example:
#-------------------------------
# result = contract.wage * 0.10""", # noqa: E501
)
amount_percentage_base = fields.Char(
string="Percentage based on", help="result will be affected to a variable"
)
child_ids = fields.One2many(
"hr.salary.rule", "parent_rule_id", string="Child Salary Rule", copy=True
)
register_id = fields.Many2one(
"hr.contribution.register",
string="Contribution Register",
help="Eventual third party involved in the salary payment of the employees.",
)
input_ids = fields.One2many("hr.rule.input", "input_id", string="Inputs", copy=True)
note = fields.Text(string="Description")
require_code_and_category = fields.Boolean(
"Require code and category",
compute="_compute_require_code_and_category",
default=lambda self: self._compute_require_code_and_category(),
)
@api.constrains("parent_rule_id")
def _check_parent_rule_id(self):
if self.env.registry[self._name]._name != "hr.salary.rule":
# HrPayslipLine inherits from "hr.salary.rule" and we don't
# want to do this check on a payslip line
return
for rule in self:
if rule._has_cycle(field_name="parent_rule_id"):
raise ValidationError(
self.env._(
"Error! You cannot create recursive hierarchy of Salary Rules."
)
)
def _recursive_search_of_rules(self):
"""
Returns the rules in reverse dependency order, children first
@return: recordset of rules
"""
if not self:
return self.env["hr.salary.rule"]
else:
return self.child_ids._recursive_search_of_rules() | self
def _reset_localdict_values(self, localdict):
localdict["result_name"] = None
localdict["result_qty"] = 1.0
localdict["result_rate"] = 100
localdict["result"] = None
return localdict
def _compute_require_code_and_category(self):
require = (
self.env["ir.config_parameter"]
.sudo()
.get_param("payroll.require_code_and_category")
)
self.require_code_and_category = require
return require
# TODO should add some checks on the type of result (should be float)
def _compute_rule(self, localdict):
"""
:param localdict: dictionary containing the environement in which to
compute the rule
:return: returns a dict with values for the payslip line.
The dict should minimum have "name", "quantity", "rate" and "amount".
:rtype: {"name": string, "quantity": float, "rate": float, "amount": float}
"""
self.ensure_one()
method = f"_compute_rule_{self.amount_select}"
compute = getattr(self, method)
return compute(localdict)
def _compute_rule_fix(self, localdict):
try:
return {
"name": self.name,
"quantity": float(safe_eval(self.quantity, localdict)),
"rate": 100.0,
"amount": self.amount_fix,
}
except Exception as ex:
raise UserError(
self.env._(
"Wrong quantity defined for salary rule %(nm)s (%(code)s) "
"for employee %(ee)s.",
nm=self.name,
code=self.code,
ee=localdict["employee"].name,
)
) from ex
def _compute_rule_percentage(self, localdict):
try:
return {
"name": self.name,
"quantity": float(safe_eval(self.quantity, localdict)),
"rate": self.amount_percentage,
"amount": float(safe_eval(self.amount_percentage_base, localdict)),
}
except Exception as ex:
raise UserError(
self.env._(
"Wrong percentage base or quantity defined for salary "
"rule %(nm)s (%(code)s) for employee %(ee)s.",
nm=self.name,
code=self.code,
ee=localdict["employee"].name,
)
) from ex
def _compute_rule_code(self, localdict):
try:
safe_eval(self.amount_python_compute, localdict, mode="exec")
except Exception as ex:
exc_text = "".join(traceback.format_exception(ex))
raise UserError(
self.env._(
"\nWrong python code defined for salary rule %(nm)s "
"(%(code)s) for employee %(ee)s.\nHere is the error "
"received:\n\n%(err)s\n",
nm=self.name,
code=self.code,
ee=localdict["employee"].name,
err=exc_text,
)
) from ex
return self._get_rule_dict(localdict)
def _get_rule_dict(self, localdict):
name = localdict.get("result_name") or self.name
quantity = float(localdict["result_qty"]) if "result_qty" in localdict else 1.0
rate = float(localdict["result_rate"]) if "result_rate" in localdict else 100.0
return {
"name": name,
"quantity": quantity,
"rate": rate,
"amount": float(localdict["result"]),
}
def _satisfy_condition(self, localdict):
"""
@param contract_id: id of hr.contract to be tested
@return: returns True if the given rule match the condition for the
given contract. Return False otherwise.
"""
self.ensure_one()
method = f"_satisfy_condition_{self.condition_select}"
check = getattr(self, method)
if self.parent_rule_id:
current_result = check(localdict)
parent_result = self.parent_rule_id._satisfy_condition(localdict)
return current_result and parent_result
return check(localdict)
def _satisfy_condition_none(self, localdict):
return True
def _satisfy_condition_range(self, localdict):
try:
result = safe_eval(self.condition_range, localdict)
return (
self.condition_range_min <= result <= self.condition_range_max or False
)
except Exception as ex:
raise UserError(
self.env._(
"Wrong range condition defined for salary rule %(nm)s "
"(%(code)s) for employee %(ee)s.",
nm=self.name,
code=self.code,
ee=localdict["employee"].name,
)
) from ex
def _satisfy_condition_python(self, localdict):
try:
safe_eval(self.condition_python, localdict, mode="exec")
except Exception as ex:
exc_text = "".join(traceback.format_exception(ex))
raise UserError(
self.env._(
"\nWrong python condition defined for salary rule %(nm)s "
"(%(code)s) for employee %(ee)s.\nHere is the error "
"received:\n\n%(err)s\n",
nm=self.name,
code=self.code,
ee=localdict["employee"].name,
err=exc_text,
)
) from ex
return "result" in localdict and localdict["result"] or False

View File

@@ -0,0 +1,54 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.exceptions import ValidationError
class HrSalaryRuleCategory(models.Model):
_name = "hr.salary.rule.category"
_description = "Salary Rule Category"
name = fields.Char(required=True, translate=True)
code = fields.Char()
parent_id = fields.Many2one(
"hr.salary.rule.category",
string="Parent",
help="Linking a salary category to its parent is used only for the "
"reporting purpose.",
)
children_ids = fields.One2many(
"hr.salary.rule.category", "parent_id", string="Children"
)
salary_rules_ids = fields.One2many(
"hr.salary.rule", "category_id", string="Salary Rule Categories"
)
note = fields.Text(string="Description")
company_id = fields.Many2one(
"res.company",
string="Company",
default=lambda self: self.env.company,
)
require_code = fields.Boolean(
"Require code",
compute="_compute_require_code",
default=lambda self: self._compute_require_code(),
)
def _compute_require_code(self):
require = (
self.env["ir.config_parameter"]
.sudo()
.get_param("payroll.require_code_and_category")
)
self.require_code = require
return require
@api.constrains("parent_id")
def _check_parent_id(self):
if self._has_cycle():
raise ValidationError(
self.env._(
"Error! You cannot create recursive hierarchy of Salary "
"Rule Category."
)
)

View File

@@ -0,0 +1,37 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
module_payroll_account = fields.Boolean(string="Payroll Accounting")
leaves_positive = fields.Boolean(
config_parameter="payroll.leaves_positive",
string="Leaves with positive values",
help="In payslip worked days, leave days/hours have positive values",
)
allow_cancel_payslips = fields.Boolean(
config_parameter="payroll.allow_cancel_payslips",
string="Allow canceling confirmed payslips",
help="Allow users to cancel confirmed payslips.",
)
prevent_compute_on_confirm = fields.Boolean(
config_parameter="payroll.prevent_compute_on_confirm",
string="Confirm payslips without recomputing",
help="Prevent payslips from being recomputed when confirming them",
default=True,
)
allow_edit_payslip_lines = fields.Boolean(
config_parameter="payroll.allow_edit_payslip_lines",
string="Allow editing payslip lines",
help="Allow users to edit some payslip line fields manually",
default=False,
)
require_code_and_category = fields.Boolean(
config_parameter="payroll.require_code_and_category",
string="Require code/category on rules, categories and structures",
help="Require rule.code, rule.category, category.code, structure.code",
default=False,
)