← Back to Pull requests

[18.0][FIX] payroll_account: company-aware accounts, real reversal on cancel, computed journal #308

Merged
nimarosa merged 11 files (1133 lines) on Nov 25, 2026 17:21 UTC
View on GitHub
nimarosa nimarosa commented on Sep 22, 2026 15:11 UTC
Author

  • Debit/credit accounts, analytic account and taxes are now resolved in the

  • payslip's own company instead of the confirming user's active company.
  • Cancelling a payslip reverses its posted entry instead of deleting it, and

  • confirming twice no longer duplicates the accounting entry.
  • journal_id is a real computed/editable field (batch > contract) instead

  • of a readonly mirror of the contract's journal.
  • Adds a README, a smart button to the journal entry, clearer error

  • messages, and fixes a broken test fixture.

    Diff: 1133 lines (+1015 / -118) across 11 files Reviewer: dreispt Review duration: 92289m
    All Vouch review confidence checks passed
    Residual risk 0.15 = Change Risk (0.81) × (1 − Review Confidence (0.82)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.81 · 1133 lines diff across 11 files
    0.81
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.73 · 5 substantive comment(s)
    0.73
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    81%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Sensitive Paths sensitive_paths
    0.081
    Real PR Conversation Timeline
    26 items
    OCA-git-bot OCA-git-bot commented on Sep 22, 2026 15:12 UTC
    Bot

    Hi @appstogrow,
    some modules you are maintaining are being modified, check this out!

    nimarosa nimarosa commented on Oct 08, 2026 11:45 UTC
    Author

    Friendly ping, could someone take a look at this one? It's been a couple of weeks. Thanks.

    mileo mileo commented on Oct 22, 2026 16:56 UTC
    Contributor

    Thanks for this, it fixes the empty journal we hit on 18.0 when the payslip is created from the form.

    One case is still left: a payslip with no batch and a contract without journal_id keeps journal_id empty, and
    confirming it fails later in payroll_account. In 16.0 the default fell back to the first general journal of the
    company (_get_default_journal in payroll_account/models/hr_payslip.py). Would you add that as the last step of
    _compute_journal_id, something like
    or self.env["account.journal"].search([("type", "=", "general"), ("company_id", "=", payslip.company_id.id)], limit=1)?
    Happy to open a follow-up PR on top of this one if you prefer to keep the scope.

    nimarosa nimarosa commented on Nov 01, 2026 15:28 UTC
    Author

    Thanks @mileo, good catch. Added here instead of a follow-up, in bf82060:

  • _compute_journal_id now falls back to the first general journal of the payslip's own company (same default the batch already uses), after the batch and the contract. A journal of another company is not kept when the payslip's company changes.

  • Confirming a payslip that still has no journal (company without any general journal) raises a clear UserError before building the entry, instead of failing on account.move.

  • Three new tests: no batch and contract without journal, the multi-company case, and the company without a general journal. readme/CONFIGURE.md lists the fallback as the last step of the journal precedence.
  • Small note for the record: in 16.0 this was an inline default= on the field, without a company filter, not a _get_default_journal method.

    @mileo @appstogrow @CristianoMafraJunior @SirPyTech @marcelsavegnago @dreispt a review would be much appreciated. Thanks!

    nimarosa nimarosa commented on Nov 10, 2026 22:25 UTC
    Author

    @dreispt @mileo can you review and approve? We need to merge this before migrating modules to other versions.

    dreispt dreispt commented on code on Nov 11, 2026 11:47 UTC
    Code Review
    payroll_account/models/hr_payslip.py:1
    @@ -11,72 +11,182 @@
     class HrPayslip(models.Model):
         _inherit = "hr.payslip"
     
    -    journal_id = fields.Many2one(related="contract_id.journal_id", store=True)
    +    journal_id = fields.Many2one(
    +        "account.journal",
    +        "Salary Journal",
    +        compute="_compute_journal_id",
    +        store=True,
    +        readonly=False,
    +        precompute=True,
    +        check_company=True,
    +        domain="[('company_id', '=', company_id)]",
    +    )
         date = fields.Date(
             "Date Account",
             help="Keep empty to use the period of the validation(Payslip) date.",
         )
         move_id = fields.Many2one(
             "account.move", "Accounting Entry", readonly=True, copy=False
         )
    +    cancelled_move_ids = fields.Many2many(
    +        "account.move",
    +        "hr_payslip_cancelled_move_rel",
    +        "payslip_id",
    +        "move_id",
    +        string="Cancelled Accounting Entries",
    +        readonly=True,
    +        copy=False,
    +        help="Accounting entries generated by this payslip and reversed when "
    +        "it was cancelled, kept for the audit trail.",
    +    )
    +
    +    @api.depends("payslip_run_id", "contract_id", "company_id")

        @api.depends("payslip_run_id.journal_id", "contract_id.journal_id", "company_id")
    

    dreispt dreispt commented on code on Nov 11, 2026 11:48 UTC
    Code Review
    payroll_account/models/hr_payslip.py:1
    @@ -11,72 +11,182 @@
     class HrPayslip(models.Model):
         _inherit = "hr.payslip"
     
    -    journal_id = fields.Many2one(related="contract_id.journal_id", store=True)
    +    journal_id = fields.Many2one(
    +        "account.journal",
    +        "Salary Journal",
    +        compute="_compute_journal_id",
    +        store=True,
    +        readonly=False,
    +        precompute=True,
    +        check_company=True,
    +        domain="[('company_id', '=', company_id)]",
    +    )
         date = fields.Date(
             "Date Account",
             help="Keep empty to use the period of the validation(Payslip) date.",
         )
         move_id = fields.Many2one(
             "account.move", "Accounting Entry", readonly=True, copy=False
         )
    +    cancelled_move_ids = fields.Many2many(
    +        "account.move",
    +        "hr_payslip_cancelled_move_rel",
    +        "payslip_id",
    +        "move_id",
    +        string="Cancelled Accounting Entries",
    +        readonly=True,
    +        copy=False,
    +        help="Accounting entries generated by this payslip and reversed when "
    +        "it was cancelled, kept for the audit trail.",
    +    )
    +
    +    @api.depends("payslip_run_id", "contract_id", "company_id")
    +    def _compute_journal_id(self):
    +        """Propose a journal for the payslip, once.
    +
    +        ``journal_id`` used to be a stored *related* field on the contract.
    +        Being related, it was readonly -- the form shows it as required, but
    +        nothing could be typed into it -- and it was recomputed from the
    +        contract, so a value chosen for one payslip (by the batch wizard's
    +        ``default_journal_id``, or by hand) was thrown away, and editing the
    +        contract's journal silently rewrote the journal of payslips that were
    +        already confirmed.
    +
    +        It is a plain computed field now: it depends on the contract and the
    +        batch themselves, not on their journal, so it proposes a value when
    +        either changes and never overwrites the payslip afterwards. The
    +        batch's journal wins over the contract's -- that is what the batch
    +        wizard means when it passes ``default_journal_id``.
     
    -    @api.onchange("contract_id")
    -    def onchange_contract(self):
    -        res = super().onchange_contract()
    -        self.journal_id = (
    -            self.contract_id.journal_id.id
    -            or (
    -                not self.contract_id
    -                and self.default_get(["journal_id"]).get("journal_id")
    +        When neither the batch nor the contract has a journal, the journal
    +        of ``_get_default_salary_journal`` is proposed; a journal of another
    +        company is never kept.
    +        """
    +        for payslip in self:
    +            current = payslip.journal_id.filtered(
    +                lambda journal, slip=payslip: journal.company_id == slip.company_id
    +            )

    Seems overcomplicated.
    I expect the payslip to have benn browsed with the right company context, and not need this.

    dreispt dreispt commented on code on Nov 11, 2026 11:51 UTC
    Code Review
    payroll_account/models/hr_payslip.py:1
    @@ -11,72 +11,182 @@
     class HrPayslip(models.Model):
         _inherit = "hr.payslip"
     
    -    journal_id = fields.Many2one(related="contract_id.journal_id", store=True)
    +    journal_id = fields.Many2one(
    +        "account.journal",
    +        "Salary Journal",
    +        compute="_compute_journal_id",
    +        store=True,
    +        readonly=False,
    +        precompute=True,
    +        check_company=True,
    +        domain="[('company_id', '=', company_id)]",
    +    )
         date = fields.Date(
             "Date Account",
             help="Keep empty to use the period of the validation(Payslip) date.",
         )
         move_id = fields.Many2one(
             "account.move", "Accounting Entry", readonly=True, copy=False
         )
    +    cancelled_move_ids = fields.Many2many(
    +        "account.move",
    +        "hr_payslip_cancelled_move_rel",
    +        "payslip_id",
    +        "move_id",
    +        string="Cancelled Accounting Entries",
    +        readonly=True,
    +        copy=False,
    +        help="Accounting entries generated by this payslip and reversed when "
    +        "it was cancelled, kept for the audit trail.",
    +    )
    +
    +    @api.depends("payslip_run_id", "contract_id", "company_id")
    +    def _compute_journal_id(self):
    +        """Propose a journal for the payslip, once.
    +
    +        ``journal_id`` used to be a stored *related* field on the contract.
    +        Being related, it was readonly -- the form shows it as required, but
    +        nothing could be typed into it -- and it was recomputed from the
    +        contract, so a value chosen for one payslip (by the batch wizard's
    +        ``default_journal_id``, or by hand) was thrown away, and editing the
    +        contract's journal silently rewrote the journal of payslips that were
    +        already confirmed.
    +
    +        It is a plain computed field now: it depends on the contract and the
    +        batch themselves, not on their journal, so it proposes a value when
    +        either changes and never overwrites the payslip afterwards. The
    +        batch's journal wins over the contract's -- that is what the batch
    +        wizard means when it passes ``default_journal_id``.
     
    -    @api.onchange("contract_id")
    -    def onchange_contract(self):
    -        res = super().onchange_contract()
    -        self.journal_id = (
    -            self.contract_id.journal_id.id
    -            or (
    -                not self.contract_id
    -                and self.default_get(["journal_id"]).get("journal_id")
    +        When neither the batch nor the contract has a journal, the journal
    +        of ``_get_default_salary_journal`` is proposed; a journal of another
    +        company is never kept.
    +        """
    +        for payslip in self:
    +            current = payslip.journal_id.filtered(
    +                lambda journal, slip=payslip: journal.company_id == slip.company_id
    +            )
    +            payslip.journal_id = (
    +                payslip.payslip_run_id.journal_id
    +                or payslip.contract_id.journal_id
    +                or current
    +                or payslip._get_default_salary_journal()
                 )
    -            or self.journal_id
    +
    +    def _get_default_salary_journal(self):
    +        """Journal proposed when neither the batch nor the contract has one.
    +
    +        By default, the first general journal of the payslip's own company, as
    +        the batch does. Submodules may override it to propose a journal
    +        configured on the company, and call ``super()`` when there is none.
    +        """
    +        self.ensure_one()
    +        return self.env["account.journal"].search(
    +            [
    +                ("type", "=", "general"),
    +                ("company_id", "=", self.company_id.id),
    +            ],
    +            limit=1,
             )
    -        return res
     
         def action_payslip_cancel(self):
    -        for payslip in self:
    -            if not payslip.move_id.journal_id.restrict_mode_hash_table:
    -                payslip.move_id.with_context(force_delete=True).button_cancel()
    -                payslip.move_id.with_context(force_delete=True).unlink()
    -            else:
    -                payslip.move_id._reverse_moves()
    -                payslip.move_id = False
    -        return super().action_payslip_cancel()
    +        # Cancel the payslip FIRST: ``super()`` still refuses the cancellation
    +        # in several cases (a payslip that is done in a database that does not
    +        # allow cancelling one, a refunded payslip whose refund is not
    +        # cancelled yet), and touching the accounting entry before that would
    +        # undo an entry whose payslip stays confirmed.
    +        res = super().action_payslip_cancel()
    +        for payslip in self.filtered("move_id"):
    +            payslip._cancel_accounting_entry()

            self._cancel_accounting_entry()
    

    And have _cancel_accounting_entry() be recorset aware and behave properly for records without move_id

    dreispt dreispt commented on code on Nov 11, 2026 11:54 UTC
    Code Review
    payroll_account/models/hr_payslip.py:1
    @@ -11,72 +11,182 @@
     class HrPayslip(models.Model):
         _inherit = "hr.payslip"
     
    -    journal_id = fields.Many2one(related="contract_id.journal_id", store=True)
    +    journal_id = fields.Many2one(
    +        "account.journal",
    +        "Salary Journal",
    +        compute="_compute_journal_id",
    +        store=True,
    +        readonly=False,
    +        precompute=True,
    +        check_company=True,
    +        domain="[('company_id', '=', company_id)]",
    +    )
         date = fields.Date(
             "Date Account",
             help="Keep empty to use the period of the validation(Payslip) date.",
         )
         move_id = fields.Many2one(
             "account.move", "Accounting Entry", readonly=True, copy=False
         )
    +    cancelled_move_ids = fields.Many2many(
    +        "account.move",
    +        "hr_payslip_cancelled_move_rel",
    +        "payslip_id",
    +        "move_id",
    +        string="Cancelled Accounting Entries",
    +        readonly=True,
    +        copy=False,
    +        help="Accounting entries generated by this payslip and reversed when "
    +        "it was cancelled, kept for the audit trail.",
    +    )
    +
    +    @api.depends("payslip_run_id", "contract_id", "company_id")
    +    def _compute_journal_id(self):
    +        """Propose a journal for the payslip, once.
    +
    +        ``journal_id`` used to be a stored *related* field on the contract.
    +        Being related, it was readonly -- the form shows it as required, but
    +        nothing could be typed into it -- and it was recomputed from the
    +        contract, so a value chosen for one payslip (by the batch wizard's
    +        ``default_journal_id``, or by hand) was thrown away, and editing the
    +        contract's journal silently rewrote the journal of payslips that were
    +        already confirmed.
    +
    +        It is a plain computed field now: it depends on the contract and the
    +        batch themselves, not on their journal, so it proposes a value when
    +        either changes and never overwrites the payslip afterwards. The
    +        batch's journal wins over the contract's -- that is what the batch
    +        wizard means when it passes ``default_journal_id``.
     
    -    @api.onchange("contract_id")
    -    def onchange_contract(self):
    -        res = super().onchange_contract()
    -        self.journal_id = (
    -            self.contract_id.journal_id.id
    -            or (
    -                not self.contract_id
    -                and self.default_get(["journal_id"]).get("journal_id")
    +        When neither the batch nor the contract has a journal, the journal
    +        of ``_get_default_salary_journal`` is proposed; a journal of another
    +        company is never kept.
    +        """
    +        for payslip in self:
    +            current = payslip.journal_id.filtered(
    +                lambda journal, slip=payslip: journal.company_id == slip.company_id
    +            )
    +            payslip.journal_id = (
    +                payslip.payslip_run_id.journal_id
    +                or payslip.contract_id.journal_id
    +                or current
    +                or payslip._get_default_salary_journal()
                 )
    -            or self.journal_id
    +
    +    def _get_default_salary_journal(self):
    +        """Journal proposed when neither the batch nor the contract has one.
    +
    +        By default, the first general journal of the payslip's own company, as
    +        the batch does. Submodules may override it to propose a journal
    +        configured on the company, and call ``super()`` when there is none.
    +        """
    +        self.ensure_one()
    +        return self.env["account.journal"].search(
    +            [
    +                ("type", "=", "general"),
    +                ("company_id", "=", self.company_id.id),
    +            ],
    +            limit=1,
             )
    -        return res
     
         def action_payslip_cancel(self):
    -        for payslip in self:
    -            if not payslip.move_id.journal_id.restrict_mode_hash_table:
    -                payslip.move_id.with_context(force_delete=True).button_cancel()
    -                payslip.move_id.with_context(force_delete=True).unlink()
    -            else:
    -                payslip.move_id._reverse_moves()
    -                payslip.move_id = False
    -        return super().action_payslip_cancel()
    +        # Cancel the payslip FIRST: ``super()`` still refuses the cancellation
    +        # in several cases (a payslip that is done in a database that does not
    +        # allow cancelling one, a refunded payslip whose refund is not
    +        # cancelled yet), and touching the accounting entry before that would
    +        # undo an entry whose payslip stays confirmed.
    +        res = super().action_payslip_cancel()
    +        for payslip in self.filtered("move_id"):
    +            payslip._cancel_accounting_entry()
    +        return res
    +
    +    def _cancel_accounting_entry(self):
    +        """Undo the accounting entry of a cancelled payslip.
    +
    +        A posted entry is never deleted: deleting it destroys the audit trail
    +        and leaves a hole in the journal's sequence. It is reversed instead,
    +        and the payslip keeps a reference to it in ``cancelled_move_ids`` so
    +        that confirming the payslip again generates a new entry rather than
    +        reusing the reversed one.
    +        """
    +        self.ensure_one()
    +        move = self.move_id
    +        if move.state == "draft":
    +            # Nothing ever reached the books, so there is nothing to reverse.
    +            move.unlink()
    +            return move.browse()
    +        reversal_date = max(move.date, fields.Date.context_today(self))
    +        reversal = move._reverse_moves([{"date": reversal_date}], cancel=True)
    +        self.write(
    +            {
    +                "move_id": False,
    +                "cancelled_move_ids": [
    +                    Command.link(move.id),
    +                    Command.link(reversal.id),
    +                ],
    +            }
    +        )
    +        return reversal
    +
    +    def unlink(self):
    +        if self.filtered(lambda payslip: payslip.move_id.state == "posted"):
    +            raise UserError(
    +                _(
    +                    "You cannot delete a payslip linked to a posted accounting "
    +                    "entry. Cancel the payslip first, so that its entry is "
    +                    "reversed."
    +                )
    +            )
    +        return super().unlink()
     
         def action_payslip_done(self):
             res = super().action_payslip_done()
     
             for slip in self:
    +            if slip.move_id:
    +                # The payslip was already confirmed once. Generating a second
    +                # entry would double every amount in the books.
    +                logger.info(
    +                    "Payslip %s already has the accounting entry %s; "
    +                    "no new entry generated",
    +                    slip.number,
    +                    slip.move_id.name,
    +                )

    This sounds like a silent data error - the old move_id would have different values from the current payslip.
    I understand this would be an exception case, and it would be reasonable to error and request manual correction.

    dreispt dreispt commented on code on Nov 11, 2026 11:55 UTC
    Code Review
    payroll_account/models/hr_payslip.py:1
    @@ -11,72 +11,182 @@
     class HrPayslip(models.Model):
         _inherit = "hr.payslip"
     
    -    journal_id = fields.Many2one(related="contract_id.journal_id", store=True)
    +    journal_id = fields.Many2one(
    +        "account.journal",
    +        "Salary Journal",
    +        compute="_compute_journal_id",
    +        store=True,
    +        readonly=False,
    +        precompute=True,
    +        check_company=True,
    +        domain="[('company_id', '=', company_id)]",
    +    )
         date = fields.Date(
             "Date Account",
             help="Keep empty to use the period of the validation(Payslip) date.",
         )
         move_id = fields.Many2one(
             "account.move", "Accounting Entry", readonly=True, copy=False
         )
    +    cancelled_move_ids = fields.Many2many(
    +        "account.move",
    +        "hr_payslip_cancelled_move_rel",
    +        "payslip_id",
    +        "move_id",
    +        string="Cancelled Accounting Entries",
    +        readonly=True,
    +        copy=False,
    +        help="Accounting entries generated by this payslip and reversed when "
    +        "it was cancelled, kept for the audit trail.",
    +    )
    +
    +    @api.depends("payslip_run_id", "contract_id", "company_id")
    +    def _compute_journal_id(self):
    +        """Propose a journal for the payslip, once.
    +
    +        ``journal_id`` used to be a stored *related* field on the contract.
    +        Being related, it was readonly -- the form shows it as required, but
    +        nothing could be typed into it -- and it was recomputed from the
    +        contract, so a value chosen for one payslip (by the batch wizard's
    +        ``default_journal_id``, or by hand) was thrown away, and editing the
    +        contract's journal silently rewrote the journal of payslips that were
    +        already confirmed.
    +
    +        It is a plain computed field now: it depends on the contract and the
    +        batch themselves, not on their journal, so it proposes a value when
    +        either changes and never overwrites the payslip afterwards. The
    +        batch's journal wins over the contract's -- that is what the batch
    +        wizard means when it passes ``default_journal_id``.
     
    -    @api.onchange("contract_id")
    -    def onchange_contract(self):
    -        res = super().onchange_contract()
    -        self.journal_id = (
    -            self.contract_id.journal_id.id
    -            or (
    -                not self.contract_id
    -                and self.default_get(["journal_id"]).get("journal_id")
    +        When neither the batch nor the contract has a journal, the journal
    +        of ``_get_default_salary_journal`` is proposed; a journal of another
    +        company is never kept.
    +        """
    +        for payslip in self:
    +            current = payslip.journal_id.filtered(
    +                lambda journal, slip=payslip: journal.company_id == slip.company_id
    +            )
    +            payslip.journal_id = (
    +                payslip.payslip_run_id.journal_id
    +                or payslip.contract_id.journal_id
    +                or current
    +                or payslip._get_default_salary_journal()
                 )
    -            or self.journal_id
    +
    +    def _get_default_salary_journal(self):
    +        """Journal proposed when neither the batch nor the contract has one.
    +
    +        By default, the first general journal of the payslip's own company, as
    +        the batch does. Submodules may override it to propose a journal
    +        configured on the company, and call ``super()`` when there is none.
    +        """
    +        self.ensure_one()
    +        return self.env["account.journal"].search(
    +            [
    +                ("type", "=", "general"),
    +                ("company_id", "=", self.company_id.id),
    +            ],
    +            limit=1,
             )
    -        return res
     
         def action_payslip_cancel(self):
    -        for payslip in self:
    -            if not payslip.move_id.journal_id.restrict_mode_hash_table:
    -                payslip.move_id.with_context(force_delete=True).button_cancel()
    -                payslip.move_id.with_context(force_delete=True).unlink()
    -            else:
    -                payslip.move_id._reverse_moves()
    -                payslip.move_id = False
    -        return super().action_payslip_cancel()
    +        # Cancel the payslip FIRST: ``super()`` still refuses the cancellation
    +        # in several cases (a payslip that is done in a database that does not
    +        # allow cancelling one, a refunded payslip whose refund is not
    +        # cancelled yet), and touching the accounting entry before that would
    +        # undo an entry whose payslip stays confirmed.
    +        res = super().action_payslip_cancel()
    +        for payslip in self.filtered("move_id"):
    +            payslip._cancel_accounting_entry()
    +        return res
    +
    +    def _cancel_accounting_entry(self):
    +        """Undo the accounting entry of a cancelled payslip.
    +
    +        A posted entry is never deleted: deleting it destroys the audit trail
    +        and leaves a hole in the journal's sequence. It is reversed instead,
    +        and the payslip keeps a reference to it in ``cancelled_move_ids`` so
    +        that confirming the payslip again generates a new entry rather than
    +        reusing the reversed one.
    +        """
    +        self.ensure_one()
    +        move = self.move_id
    +        if move.state == "draft":
    +            # Nothing ever reached the books, so there is nothing to reverse.
    +            move.unlink()
    +            return move.browse()
    +        reversal_date = max(move.date, fields.Date.context_today(self))
    +        reversal = move._reverse_moves([{"date": reversal_date}], cancel=True)
    +        self.write(
    +            {
    +                "move_id": False,
    +                "cancelled_move_ids": [
    +                    Command.link(move.id),
    +                    Command.link(reversal.id),
    +                ],
    +            }
    +        )
    +        return reversal
    +
    +    def unlink(self):
    +        if self.filtered(lambda payslip: payslip.move_id.state == "posted"):
    +            raise UserError(
    +                _(
    +                    "You cannot delete a payslip linked to a posted accounting "
    +                    "entry. Cancel the payslip first, so that its entry is "
    +                    "reversed."
    +                )
    +            )
    +        return super().unlink()
     
         def action_payslip_done(self):
             res = super().action_payslip_done()
     
             for slip in self:
    +            if slip.move_id:
    +                # The payslip was already confirmed once. Generating a second
    +                # entry would double every amount in the books.
    +                logger.info(
    +                    "Payslip %s already has the accounting entry %s; "
    +                    "no new entry generated",
    +                    slip.number,
    +                    slip.move_id.name,
    +                )
    +                continue
                 line_ids = []
                 debit_sum = 0.0
                 credit_sum = 0.0
                 date = slip.date or slip.date_to
    -            currency = (
    -                slip.company_id.currency_id or slip.journal_id.company_id.currency_id
    -            )
    +            company = slip._get_accounting_company()

    It would be more efficient to just have this as a field on the payslip.

    dreispt dreispt commented on code on Nov 11, 2026 11:56 UTC
    Code Review
    payroll_account/models/hr_payslip.py:1
    @@ -11,72 +11,182 @@
     class HrPayslip(models.Model):
         _inherit = "hr.payslip"
     
    -    journal_id = fields.Many2one(related="contract_id.journal_id", store=True)
    +    journal_id = fields.Many2one(
    +        "account.journal",
    +        "Salary Journal",
    +        compute="_compute_journal_id",
    +        store=True,
    +        readonly=False,
    +        precompute=True,
    +        check_company=True,
    +        domain="[('company_id', '=', company_id)]",
    +    )
         date = fields.Date(
             "Date Account",
             help="Keep empty to use the period of the validation(Payslip) date.",
         )
         move_id = fields.Many2one(
             "account.move", "Accounting Entry", readonly=True, copy=False
         )
    +    cancelled_move_ids = fields.Many2many(
    +        "account.move",
    +        "hr_payslip_cancelled_move_rel",
    +        "payslip_id",
    +        "move_id",
    +        string="Cancelled Accounting Entries",
    +        readonly=True,
    +        copy=False,
    +        help="Accounting entries generated by this payslip and reversed when "
    +        "it was cancelled, kept for the audit trail.",
    +    )
    +
    +    @api.depends("payslip_run_id", "contract_id", "company_id")
    +    def _compute_journal_id(self):
    +        """Propose a journal for the payslip, once.
    +
    +        ``journal_id`` used to be a stored *related* field on the contract.
    +        Being related, it was readonly -- the form shows it as required, but
    +        nothing could be typed into it -- and it was recomputed from the
    +        contract, so a value chosen for one payslip (by the batch wizard's
    +        ``default_journal_id``, or by hand) was thrown away, and editing the
    +        contract's journal silently rewrote the journal of payslips that were
    +        already confirmed.
    +
    +        It is a plain computed field now: it depends on the contract and the
    +        batch themselves, not on their journal, so it proposes a value when
    +        either changes and never overwrites the payslip afterwards. The
    +        batch's journal wins over the contract's -- that is what the batch
    +        wizard means when it passes ``default_journal_id``.
     
    -    @api.onchange("contract_id")
    -    def onchange_contract(self):
    -        res = super().onchange_contract()
    -        self.journal_id = (
    -            self.contract_id.journal_id.id
    -            or (
    -                not self.contract_id
    -                and self.default_get(["journal_id"]).get("journal_id")
    +        When neither the batch nor the contract has a journal, the journal
    +        of ``_get_default_salary_journal`` is proposed; a journal of another
    +        company is never kept.
    +        """
    +        for payslip in self:
    +            current = payslip.journal_id.filtered(
    +                lambda journal, slip=payslip: journal.company_id == slip.company_id
    +            )
    +            payslip.journal_id = (
    +                payslip.payslip_run_id.journal_id
    +                or payslip.contract_id.journal_id
    +                or current
    +                or payslip._get_default_salary_journal()
                 )
    -            or self.journal_id
    +
    +    def _get_default_salary_journal(self):
    +        """Journal proposed when neither the batch nor the contract has one.
    +
    +        By default, the first general journal of the payslip's own company, as
    +        the batch does. Submodules may override it to propose a journal
    +        configured on the company, and call ``super()`` when there is none.
    +        """
    +        self.ensure_one()
    +        return self.env["account.journal"].search(
    +            [
    +                ("type", "=", "general"),
    +                ("company_id", "=", self.company_id.id),
    +            ],
    +            limit=1,
             )
    -        return res
     
         def action_payslip_cancel(self):
    -        for payslip in self:
    -            if not payslip.move_id.journal_id.restrict_mode_hash_table:
    -                payslip.move_id.with_context(force_delete=True).button_cancel()
    -                payslip.move_id.with_context(force_delete=True).unlink()
    -            else:
    -                payslip.move_id._reverse_moves()
    -                payslip.move_id = False
    -        return super().action_payslip_cancel()
    +        # Cancel the payslip FIRST: ``super()`` still refuses the cancellation
    +        # in several cases (a payslip that is done in a database that does not
    +        # allow cancelling one, a refunded payslip whose refund is not
    +        # cancelled yet), and touching the accounting entry before that would
    +        # undo an entry whose payslip stays confirmed.
    +        res = super().action_payslip_cancel()
    +        for payslip in self.filtered("move_id"):
    +            payslip._cancel_accounting_entry()
    +        return res
    +
    +    def _cancel_accounting_entry(self):
    +        """Undo the accounting entry of a cancelled payslip.
    +
    +        A posted entry is never deleted: deleting it destroys the audit trail
    +        and leaves a hole in the journal's sequence. It is reversed instead,
    +        and the payslip keeps a reference to it in ``cancelled_move_ids`` so
    +        that confirming the payslip again generates a new entry rather than
    +        reusing the reversed one.
    +        """
    +        self.ensure_one()
    +        move = self.move_id
    +        if move.state == "draft":
    +            # Nothing ever reached the books, so there is nothing to reverse.
    +            move.unlink()
    +            return move.browse()
    +        reversal_date = max(move.date, fields.Date.context_today(self))
    +        reversal = move._reverse_moves([{"date": reversal_date}], cancel=True)
    +        self.write(
    +            {
    +                "move_id": False,
    +                "cancelled_move_ids": [
    +                    Command.link(move.id),
    +                    Command.link(reversal.id),
    +                ],
    +            }
    +        )
    +        return reversal
    +
    +    def unlink(self):
    +        if self.filtered(lambda payslip: payslip.move_id.state == "posted"):
    +            raise UserError(
    +                _(
    +                    "You cannot delete a payslip linked to a posted accounting "
    +                    "entry. Cancel the payslip first, so that its entry is "
    +                    "reversed."
    +                )
    +            )
    +        return super().unlink()
     
         def action_payslip_done(self):
             res = super().action_payslip_done()
     
             for slip in self:
    +            if slip.move_id:
    +                # The payslip was already confirmed once. Generating a second
    +                # entry would double every amount in the books.
    +                logger.info(
    +                    "Payslip %s already has the accounting entry %s; "
    +                    "no new entry generated",
    +                    slip.number,
    +                    slip.move_id.name,
    +                )
    +                continue
                 line_ids = []
                 debit_sum = 0.0
                 credit_sum = 0.0
                 date = slip.date or slip.date_to
    -            currency = (
    -                slip.company_id.currency_id or slip.journal_id.company_id.currency_id
    -            )
    +            company = slip._get_accounting_company()
    +            currency = company.currency_id or slip.journal_id.company_id.currency_id
     
                 name = _("Payslip of %s") % (slip.employee_id.name)
                 move_dict = {
                     "narration": name,
                     "ref": slip.number,
                     "journal_id": slip.journal_id.id,
    +                "company_id": company.id,
                     "date": date,
                 }

    Use the _prepare_method pattern

    dreispt dreispt commented on code on Nov 11, 2026 11:58 UTC
    Code Review
    payroll_account/models/hr_payslip.py:1
    @@ -11,72 +11,182 @@
     class HrPayslip(models.Model):
         _inherit = "hr.payslip"
     
    -    journal_id = fields.Many2one(related="contract_id.journal_id", store=True)
    +    journal_id = fields.Many2one(
    +        "account.journal",
    +        "Salary Journal",
    +        compute="_compute_journal_id",
    +        store=True,
    +        readonly=False,
    +        precompute=True,
    +        check_company=True,
    +        domain="[('company_id', '=', company_id)]",
    +    )
         date = fields.Date(
             "Date Account",
             help="Keep empty to use the period of the validation(Payslip) date.",
         )
         move_id = fields.Many2one(
             "account.move", "Accounting Entry", readonly=True, copy=False
         )
    +    cancelled_move_ids = fields.Many2many(
    +        "account.move",
    +        "hr_payslip_cancelled_move_rel",
    +        "payslip_id",
    +        "move_id",
    +        string="Cancelled Accounting Entries",
    +        readonly=True,
    +        copy=False,
    +        help="Accounting entries generated by this payslip and reversed when "
    +        "it was cancelled, kept for the audit trail.",
    +    )
    +
    +    @api.depends("payslip_run_id", "contract_id", "company_id")
    +    def _compute_journal_id(self):
    +        """Propose a journal for the payslip, once.
    +
    +        ``journal_id`` used to be a stored *related* field on the contract.
    +        Being related, it was readonly -- the form shows it as required, but
    +        nothing could be typed into it -- and it was recomputed from the
    +        contract, so a value chosen for one payslip (by the batch wizard's
    +        ``default_journal_id``, or by hand) was thrown away, and editing the
    +        contract's journal silently rewrote the journal of payslips that were
    +        already confirmed.
    +
    +        It is a plain computed field now: it depends on the contract and the
    +        batch themselves, not on their journal, so it proposes a value when
    +        either changes and never overwrites the payslip afterwards. The
    +        batch's journal wins over the contract's -- that is what the batch
    +        wizard means when it passes ``default_journal_id``.
     
    -    @api.onchange("contract_id")
    -    def onchange_contract(self):
    -        res = super().onchange_contract()
    -        self.journal_id = (
    -            self.contract_id.journal_id.id
    -            or (
    -                not self.contract_id
    -                and self.default_get(["journal_id"]).get("journal_id")
    +        When neither the batch nor the contract has a journal, the journal
    +        of ``_get_default_salary_journal`` is proposed; a journal of another
    +        company is never kept.
    +        """
    +        for payslip in self:
    +            current = payslip.journal_id.filtered(
    +                lambda journal, slip=payslip: journal.company_id == slip.company_id
    +            )
    +            payslip.journal_id = (
    +                payslip.payslip_run_id.journal_id
    +                or payslip.contract_id.journal_id
    +                or current
    +                or payslip._get_default_salary_journal()
                 )
    -            or self.journal_id
    +
    +    def _get_default_salary_journal(self):
    +        """Journal proposed when neither the batch nor the contract has one.
    +
    +        By default, the first general journal of the payslip's own company, as
    +        the batch does. Submodules may override it to propose a journal
    +        configured on the company, and call ``super()`` when there is none.
    +        """
    +        self.ensure_one()
    +        return self.env["account.journal"].search(
    +            [
    +                ("type", "=", "general"),
    +                ("company_id", "=", self.company_id.id),
    +            ],
    +            limit=1,
             )
    -        return res
     
         def action_payslip_cancel(self):
    -        for payslip in self:
    -            if not payslip.move_id.journal_id.restrict_mode_hash_table:
    -                payslip.move_id.with_context(force_delete=True).button_cancel()
    -                payslip.move_id.with_context(force_delete=True).unlink()
    -            else:
    -                payslip.move_id._reverse_moves()
    -                payslip.move_id = False
    -        return super().action_payslip_cancel()
    +        # Cancel the payslip FIRST: ``super()`` still refuses the cancellation
    +        # in several cases (a payslip that is done in a database that does not
    +        # allow cancelling one, a refunded payslip whose refund is not
    +        # cancelled yet), and touching the accounting entry before that would
    +        # undo an entry whose payslip stays confirmed.
    +        res = super().action_payslip_cancel()
    +        for payslip in self.filtered("move_id"):
    +            payslip._cancel_accounting_entry()
    +        return res
    +
    +    def _cancel_accounting_entry(self):
    +        """Undo the accounting entry of a cancelled payslip.
    +
    +        A posted entry is never deleted: deleting it destroys the audit trail
    +        and leaves a hole in the journal's sequence. It is reversed instead,
    +        and the payslip keeps a reference to it in ``cancelled_move_ids`` so
    +        that confirming the payslip again generates a new entry rather than
    +        reusing the reversed one.
    +        """
    +        self.ensure_one()
    +        move = self.move_id
    +        if move.state == "draft":
    +            # Nothing ever reached the books, so there is nothing to reverse.
    +            move.unlink()
    +            return move.browse()
    +        reversal_date = max(move.date, fields.Date.context_today(self))
    +        reversal = move._reverse_moves([{"date": reversal_date}], cancel=True)
    +        self.write(
    +            {
    +                "move_id": False,
    +                "cancelled_move_ids": [
    +                    Command.link(move.id),
    +                    Command.link(reversal.id),
    +                ],
    +            }
    +        )
    +        return reversal
    +
    +    def unlink(self):
    +        if self.filtered(lambda payslip: payslip.move_id.state == "posted"):
    +            raise UserError(
    +                _(
    +                    "You cannot delete a payslip linked to a posted accounting "
    +                    "entry. Cancel the payslip first, so that its entry is "
    +                    "reversed."
    +                )
    +            )
    +        return super().unlink()
     
         def action_payslip_done(self):
             res = super().action_payslip_done()
     
             for slip in self:
    +            if slip.move_id:
    +                # The payslip was already confirmed once. Generating a second
    +                # entry would double every amount in the books.
    +                logger.info(
    +                    "Payslip %s already has the accounting entry %s; "
    +                    "no new entry generated",
    +                    slip.number,
    +                    slip.move_id.name,
    +                )
    +                continue
                 line_ids = []
                 debit_sum = 0.0
                 credit_sum = 0.0
                 date = slip.date or slip.date_to
    -            currency = (
    -                slip.company_id.currency_id or slip.journal_id.company_id.currency_id
    -            )
    +            company = slip._get_accounting_company()
    +            currency = company.currency_id or slip.journal_id.company_id.currency_id
     
                 name = _("Payslip of %s") % (slip.employee_id.name)
                 move_dict = {
                     "narration": name,
                     "ref": slip.number,
                     "journal_id": slip.journal_id.id,
    +                "company_id": company.id,
                     "date": date,
                 }
                 for line in slip.line_ids:
                     amount = currency.round(slip.credit_note and -line.total or line.total)
                     if currency.is_zero(amount):
                         continue
    -                debit_account_id = line.salary_rule_id.account_debit.id
    -                credit_account_id = line.salary_rule_id.account_credit.id
    +                # ``account_debit``/``account_credit`` are company-dependent, so
    +                # they must be read in the payslip's company and not in whatever
    +                # company the user happens to be working in.
    +                salary_rule = line.salary_rule_id.with_company(company)

    The per line with_company causes a reread of the record data and is inefficient.
    Favor a single top level with_company operation on the recordset instead (when starting computation, for example)

    dreispt dreispt commented on code on Nov 11, 2026 11:59 UTC
    Code Review
    payroll_account/models/hr_payslip.py:1
    @@ -97,13 +207,29 @@ def action_payslip_done(self):
                         line_ids.append((0, 0, credit_line))
                         credit_sum += credit_line["credit"] - credit_line["debit"]
     
    +            if line_ids and not slip.journal_id:
    +                # Only an entry needs a journal: a payslip whose rules have no
    +                # accounts (e.g. a company without accounting) confirms
    +                # without one, and the adjustment lines below can only exist
    +                # when there are accounted lines.
    +                raise UserError(
    +                    _(
    +                        'The payslip "%(payslip)s" has no salary journal: set one '
    +                        "on the payslip, its batch or its contract, or create a "
    +                        'general journal in the company "%(company)s".',
    +                        payslip=slip.number or slip.name,
    +                        company=slip.company_id.name,
    +                    )
    +                )
    +
                 if currency.compare_amounts(credit_sum, debit_sum) == -1:
                     acc_id = slip.journal_id.default_account_id.id
                     if not acc_id:
                         raise UserError(
                             _(
    -                            'The Expense Journal "%s" has not properly '
    -                            "configured the Credit Account!"
    +                            'The salary journal "%s" needs a default account: '
    +                            "the payslip debits more than it credits, and the "
    +                            "difference is balanced on that account."

    Avoid changing translatable terms, unless it is really important, because it breaks existing translations.

    dreispt dreispt commented on code on Nov 11, 2026 12:03 UTC
    Code Review
    payroll_account/__manifest__.py:1
    @@ -1,7 +1,7 @@
     # Part of Odoo. See LICENSE file for full copyright and licensing details.
     {
         "name": "Payroll Accounting",
    -    "version": "18.0.1.0.6",
    +    "version": "18.0.1.1.0",

    Leave version to be bumped by the ocabot.

    dreispt dreispt commented on Nov 11, 2026 12:06 UTC
    Reviewer

    I have concerns with:

  • Possibly unneeded message rewrites, breaking translations.

  • Excessive low level uses of with_company triggering inefficient records rebrowse
  • nimarosa nimarosa commented on Nov 11, 2026 14:15 UTC
    Author

    Thanks for the review @dreispt. Pushed the changes:

    1. Translations: restored the original wording of the two journal messages.
    2. with_company: one with_company per payslip at the start of action_payslip_done, and none in the line helpers.
    3. _cancel_accounting_entry: works on recordsets now and skips payslips without an entry.
    4. Confirming a payslip that already has an entry: it raises instead of skipping.
    5. Move values: moved to a _prepare_account_move_vals() method.
    6. Version: reverted, I leave the bump to the bot.
    7. Journal compute: dropped the "keep the current journal" step, it is simpler.
    8. @api.depends: I would keep it on the records, not on their journal. With contract_id.journal_id there, changing the journal on a contract rewrites it on all its payslips, including confirmed ones. That is one of the bugs this PR fixes.
    9. _get_accounting_company: it is just company_id with a fallback, no extra reads. I would keep it as a small hook since another module uses it, but I can inline company_id if you prefer.

    dreispt dreispt commented on Nov 11, 2026 14:41 UTC
    Contributor

    On 8. good point, you're right.
    I also see the below flag on my end that can be worth checking:

    payroll_account/models/hr_payslip.py:R65-68

    Custom salary journal silently replaced

    When a payslip changes contracts or batches without a configured journal, _compute_journal_id replaces its manually selected journal with the general fallback. Confirming the payslip then posts its entry to the wrong journal.

    I see one more thing worth investigating:

    payroll_account/models/hr_payslip.py:R178

    Wrong partner on cross-company payroll entries

    When account types differ across companies, salary_rule supplies the payslip company's account but partner selection uses the active company's account. The [partner helper](payroll_account/models/hr_payslip_line.py:34-38) reads the rule without switching companies, leaving payable items without their intended partner.

    A salary rule has company-dependent debit and credit accounts. The entry builder now reads them with the payslip's company, but [_get_partner_id](payroll_account/models/hr_payslip_line.py:34-38) reads the same fields from the original payslip line in the active company. Partner selection therefore can disagree with the account actually posted. This matters for payable, receivable, and current-liability accounts, whose partner is chosen from either the contribution register or the employee.

    Example: Company A's credit account is an expense and company B's credit account is payable. A user active in A confirms a B payslip; its move uses B's payable account, but partner selection sees A's expense account and assigns no register partner.

    dreispt dreispt approved these changes on Nov 11, 2026 14:41 UTC
    Approved Reviewer

    Approved these changes.

    nimarosa nimarosa commented on Nov 11, 2026 15:12 UTC
    Author

    Thanks @dreispt!

    1. Journal replaced: that is what the step I dropped in point 7 was for. It kept a journal picked by hand when the new contract has none. I put it back, with a test.
    2. Partner: this one is fine. After the with_company change the lines come from slip.line_ids in the payslip's company, so _get_partner_id reads the rule accounts in that company. I added a test for the case you describe and it passes.

    JuanMarta JuanMarta approved these changes on Nov 25, 2026 16:52 UTC
    Approved Reviewer

    Code review only.

    This is a comprehensive and well-thought-out set of fixes for payroll_account:

  • Resolving rule accounts, taxes, and journals via with_company(payslip.company_id) prevents silent multi-company posting bugs.

  • Reversing posted moves on cancellation (moving the reversed pair to cancelled_move_ids) and blocking double-confirmation or deletion of posted entries properly preserves the accounting audit trail.

  • Making journal_id a stored computed field with the fallback chain (batch > contract > default general journal, keeping manual selections intact) and only requiring it when an entry actually needs to be posted addresses the earlier review feedback cleanly.
  • The added hook for submodules, cross-company partner tests, and updated documentation look very solid.

    OCA-git-bot OCA-git-bot commented on Nov 25, 2026 17:00 UTC
    Bot

    This PR has the approved label and has been created more than 5 days ago. It should therefore be ready to merge by a maintainer (or a PSC member if the concerned addon has no declared maintainer). 🤖

    dreispt dreispt commented on Nov 25, 2026 17:13 UTC
    Contributor

    /ocabot merge minor

    OCA-git-bot OCA-git-bot commented on Nov 25, 2026 17:13 UTC
    Bot

    Hey, thanks for contributing! Proceeding to merge this for you.
    Prepared branch 18.0-ocabot-merge-pr-308-by-dreispt-bump-minor, awaiting test results.

    CristianoMafraJunior CristianoMafraJunior approved these changes on Nov 25, 2026 17:16 UTC
    Approved Reviewer

    Approved these changes.

    OCA-git-bot OCA-git-bot commented on Nov 25, 2026 17:21 UTC
    Bot

    Congratulations, your PR was merged at ecda16882f24fffa58f8ca42ae09e280d889ab68. Thanks a lot for contributing to OCA. ❤️

    Reviewers
    Assignees
    nimarosa nimarosa
    Labels
    risk: low confidence: 81.7% reviewed sensitive_module
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 80.8% (HIGH) · Higher = larger blast radius
    80.8%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 81.7% · Lower = rushed or shallow review
    81.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 14.8% · Safe to merge
    14.8%
    Repository