| 1 | from odoo import api, models, fields, Command |
| 2 | from odoo.exceptions import ValidationError |
| 3 | from odoo.tools.float_utils import float_is_zero, float_round |
| 4 | |
| 5 | |
| 6 | class BankAccountAllocationWizard(models.TransientModel): |
| 7 | _name = 'hr.bank.account.allocation.wizard' |
| 8 | _description = 'Bank Account Allocation Wizard' |
| 9 | |
| 10 | employee_id = fields.Many2one('hr.employee', required=True) |
| 11 | allocation_ids = fields.One2many('hr.bank.account.allocation.wizard.line', 'wizard_id', string="Allocations", readonly=False) |
| 12 | |
| 13 | def _prepare_allocations_from_employee(self): |
| 14 | self.ensure_one() |
| 15 | wizard_lines = [] |
| 16 | distribution = self.employee_id.salary_distribution or {} |
| 17 | for ba in self.employee_id.bank_account_ids: |
| 18 | if str(ba.id) not in distribution: |
| 19 | raise ValidationError(self.env._("Bank account %s not found within the salary distribution of the employee", ba)) |
| 20 | dist_entry = distribution.get(str(ba.id)) |
| 21 | amount = dist_entry.get('amount') |
| 22 | is_percentage = dist_entry.get('amount_is_percentage') |
| 23 | sequence = dist_entry.get('sequence') |
| 24 | wizard_lines.append(Command.create({ |
| 25 | 'bank_account_id': ba.id, |
| 26 | 'amount': amount, |
| 27 | 'amount_type': 'percentage' if is_percentage else 'fixed', |
| 28 | 'trusted': ba.allow_out_payment, |
| 29 | 'sequence': sequence, |
| 30 | })) |
| 31 | self.write({'allocation_ids': wizard_lines}) |
| 32 | |
| 33 | @api.model_create_multi |
| 34 | def create(self, vals_list): |
| 35 | records = super().create(vals_list) |
| 36 | for wizard in records: |
| 37 | wizard._prepare_allocations_from_employee() |
| 38 | return records |
| 39 | |
| 40 | def action_save(self): |
| 41 | self.ensure_one() |
| 42 | |
| 43 | distribution = {} |
| 44 | total = 0.0 |
| 45 | check_for_total = False |
| 46 | |
| 47 | for index, line in enumerate(self.allocation_ids): |
| 48 | line_amount = float_round(line.amount, precision_digits=2, rounding_method="DOWN") |
| 49 | distribution[str(line.bank_account_id.id)] = { |
| 50 | 'amount': line_amount, |
| 51 | 'sequence': line.sequence, |
| 52 | 'amount_is_percentage': line.amount_type == 'percentage' |
| 53 | } |
| 54 | if line.amount_type == 'percentage': |
| 55 | total += line_amount |
| 56 | check_for_total = True |
| 57 | line.bank_account_id.sudo().write({ |
| 58 | 'allow_out_payment': line.trusted |
| 59 | }) |
| 60 | if check_for_total and not float_is_zero(total - 100.0, precision_digits=4): |
| 61 | raise ValidationError(self.env._("Total percentage allocation must equal 100%.")) |
| 62 | |
| 63 | self.employee_id.salary_distribution = distribution |