416 lines
17 KiB
Python
416 lines
17 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""DN Bank Reconciliation — statement line matching workspace.
|
|
|
|
Independent implementation for Odoo 20 Community, LGPL-3. It reuses only
|
|
community APIs from ``account`` (``account.bank.statement.line`` and
|
|
``account.reconcile.model``); no enterprise file is used or derived.
|
|
|
|
The workflow implemented here mirrors what an accountant expects:
|
|
|
|
1. Pick a bank journal. Unreconciled statement lines are listed.
|
|
2. For the selected line the engine proposes candidate journal items,
|
|
ranked by amount, partner and label similarity.
|
|
3. The user either
|
|
* matches one or more candidates (partial or full), or
|
|
* creates a new entry on a chosen counterpart account (with tax).
|
|
4. The result is written as a balanced journal entry and reconciled.
|
|
"""
|
|
import logging
|
|
import re
|
|
from difflib import SequenceMatcher
|
|
|
|
from odoo import _, api, fields, models
|
|
from odoo.exceptions import UserError, ValidationError
|
|
from odoo.tools import float_compare, float_is_zero
|
|
|
|
_logger = logging.getLogger(__name__)
|
|
|
|
# How strongly each signal weighs when suggesting a candidate.
|
|
WEIGHT_AMOUNT_EXACT = 100
|
|
WEIGHT_AMOUNT_CLOSE = 40
|
|
WEIGHT_PARTNER = 60
|
|
WEIGHT_LABEL = 30
|
|
MAX_SUGGESTIONS = 20
|
|
|
|
|
|
def _normalise(text):
|
|
"""Lowercase, strip digits and punctuation, so labels can be compared."""
|
|
text = (text or "").lower()
|
|
text = re.sub(r"[^a-z0-9\u4e00-\u9fff ]+", " ", text)
|
|
return " ".join(text.split())
|
|
|
|
|
|
def _similarity(left, right):
|
|
left, right = _normalise(left), _normalise(right)
|
|
if not left or not right:
|
|
return 0.0
|
|
return SequenceMatcher(None, left, right).ratio()
|
|
|
|
|
|
class DnBankRecWizard(models.TransientModel):
|
|
"""Holds the state of one reconciliation session for a statement line."""
|
|
|
|
_name = "dn.bank.rec.wizard"
|
|
_description = "DN Bank Reconciliation Session"
|
|
|
|
statement_line_id = fields.Many2one(
|
|
"account.bank.statement.line", required=True, ondelete="cascade",
|
|
string="Bank Transaction",
|
|
)
|
|
journal_id = fields.Many2one(related="statement_line_id.journal_id", string="Journal")
|
|
company_id = fields.Many2one(related="statement_line_id.company_id", string="Company")
|
|
currency_id = fields.Many2one(related="statement_line_id.currency_id", string="Currency")
|
|
amount = fields.Monetary(related="statement_line_id.amount", string="Statement Amount")
|
|
partner_id = fields.Many2one(related="statement_line_id.partner_id", string="Partner")
|
|
payment_ref = fields.Char(related="statement_line_id.payment_ref", string="Label")
|
|
date = fields.Date(related="statement_line_id.date", string="Date")
|
|
|
|
candidate_ids = fields.One2many(
|
|
"dn.bank.rec.candidate", "wizard_id", string="Candidates",
|
|
)
|
|
selected_aml_ids = fields.Many2many(
|
|
"account.move.line", string="Selected Journal Items",
|
|
help="Journal items the user chose to reconcile against the statement line.",
|
|
)
|
|
remaining_amount = fields.Monetary(
|
|
compute="_compute_remaining", string="Amount Left to Match",
|
|
)
|
|
suggestion_count = fields.Integer(compute="_compute_remaining",
|
|
string="Suggestions")
|
|
|
|
# Manual entry fallback
|
|
counterpart_account_id = fields.Many2one(
|
|
"account.account", string="Counterpart Account",
|
|
domain="[('account_type', 'not in', ['asset_receivable', 'liability_payable', 'off_balance']), ('company_ids', 'in', company_id)]",
|
|
)
|
|
manual_amount = fields.Monetary(string="Amount")
|
|
# These two mirror statement_line's `payment_ref` / `partner_id` but are
|
|
# editable, so they must not reuse the same label: Odoo warns on duplicate
|
|
# field labels and the user cannot tell the two apart in the UI.
|
|
manual_label = fields.Char(string="Counterpart Label")
|
|
manual_partner_id = fields.Many2one("res.partner", string="Counterpart Partner")
|
|
manual_tax_id = fields.Many2one(
|
|
"account.tax", string="Tax",
|
|
domain="[('type_tax_use', 'in', ['sale', 'purchase']), ('company_id', '=', company_id)]",
|
|
)
|
|
|
|
@api.model
|
|
def create_from_statement_line(self, statement_line_id):
|
|
"""Open a reconciliation session for the given statement line.
|
|
|
|
Called from the statement line's button; the caller always receives the
|
|
wizard record so it can act on the suggestions.
|
|
"""
|
|
wizard = self.create({"statement_line_id": statement_line_id})
|
|
wizard._refresh_candidates()
|
|
return wizard
|
|
|
|
# ------------------------------------------------------------ compute
|
|
@api.depends("selected_aml_ids", "statement_line_id")
|
|
def _compute_remaining(self):
|
|
for wizard in self:
|
|
total = 0.0
|
|
for aml in wizard.selected_aml_ids:
|
|
total += aml.balance
|
|
wizard.remaining_amount = wizard.amount + total
|
|
wizard.suggestion_count = len(wizard.candidate_ids)
|
|
|
|
# ----------------------------------------------------------- candidates
|
|
def _refresh_candidates(self):
|
|
"""Rebuild the ranked candidate list for the statement line."""
|
|
self.ensure_one()
|
|
self.candidate_ids.unlink()
|
|
candidates = self._collect_candidates()
|
|
vals_list = []
|
|
for aml, score, reason in candidates[:MAX_SUGGESTIONS]:
|
|
vals_list.append({
|
|
"wizard_id": self.id,
|
|
"move_line_id": aml.id,
|
|
"score": score,
|
|
"reason": reason,
|
|
})
|
|
if vals_list:
|
|
self.env["dn.bank.rec.candidate"].create(vals_list)
|
|
return True
|
|
|
|
def action_refresh_candidates(self):
|
|
"""Recompute suggestions, e.g. after new entries were posted."""
|
|
self.ensure_one()
|
|
self._refresh_candidates()
|
|
return {
|
|
"type": "ir.actions.client",
|
|
"tag": "display_notification",
|
|
"params": {
|
|
"title": _("Candidates"),
|
|
"message": _("%s candidates recomputed.", len(self.candidate_ids)),
|
|
"type": "success",
|
|
"sticky": False,
|
|
},
|
|
}
|
|
|
|
def _collect_candidates(self):
|
|
"""Score unreconciled journal items against the statement line."""
|
|
self.ensure_one()
|
|
st_line = self.statement_line_id
|
|
domain = st_line._get_default_amls_matching_domain(allow_draft=False)
|
|
domain += [
|
|
("company_id", "=", st_line.company_id.id),
|
|
("date", "<=", st_line.date or fields.Date.context_today(self)),
|
|
]
|
|
amls = self.env["account.move.line"].sudo().search(domain, limit=2000)
|
|
|
|
scored = []
|
|
line_amount = abs(st_line.amount or 0.0)
|
|
company_currency = st_line.company_id.currency_id
|
|
for aml in amls:
|
|
score = 0
|
|
reasons = []
|
|
|
|
aml_amount = abs(aml.amount_residual or aml.balance or 0.0)
|
|
if float_is_zero(aml_amount - line_amount, precision_rounding=0.01):
|
|
score += WEIGHT_AMOUNT_EXACT
|
|
reasons.append(_("same amount"))
|
|
elif line_amount and abs(aml_amount - line_amount) / line_amount < 0.02:
|
|
score += WEIGHT_AMOUNT_CLOSE
|
|
reasons.append(_("close amount"))
|
|
|
|
if st_line.partner_id and aml.partner_id == st_line.partner_id:
|
|
score += WEIGHT_PARTNER
|
|
reasons.append(_("same partner"))
|
|
|
|
label_score = _similarity(st_line.payment_ref, aml.name)
|
|
if label_score > 0.5:
|
|
score += int(WEIGHT_LABEL * label_score)
|
|
reasons.append(_("similar label"))
|
|
|
|
# A deposit (+amount) is debited to the bank, so its counterpart
|
|
# carries a credit balance, i.e. a negative one. A withdrawal is
|
|
# the mirror image. This is what keeps a 4,000 receipt from
|
|
# matching a 4,000 payment.
|
|
if st_line.amount and aml.balance:
|
|
opposite_side = (st_line.amount > 0) == (aml.balance < 0)
|
|
if opposite_side:
|
|
score += 10
|
|
else:
|
|
score -= 20
|
|
|
|
if score > 0:
|
|
scored.append((aml, score, " / ".join(reasons) or _("automatic match")))
|
|
|
|
scored.sort(key=lambda item: item[1], reverse=True)
|
|
return scored
|
|
|
|
# -------------------------------------------------------------- actions
|
|
def action_match_selected(self):
|
|
"""Reconcile the statement line against the selected journal items.
|
|
|
|
A statement line's own entry holds a liquidity item (on the bank
|
|
account) and a suspense item. Those two can never be reconciled against
|
|
a receivable: reconciliation only works between items of the *same*
|
|
account. So the suspense item is first re-pointed at the account of the
|
|
selected items, which turns it into a genuine counterpart on, say,
|
|
receivables. Only then are the two sides reconciled.
|
|
"""
|
|
self.ensure_one()
|
|
if not self.selected_aml_ids:
|
|
raise UserError(_("Select at least one journal item to match."))
|
|
|
|
st_line = self.statement_line_id
|
|
accounts = self.selected_aml_ids.mapped("account_id")
|
|
if len(accounts) > 1:
|
|
raise UserError(
|
|
_("The selected items belong to different accounts (%s). "
|
|
"Only items of one account can be reconciled together.",
|
|
", ".join(accounts.mapped("display_name")))
|
|
)
|
|
target_account = accounts[:1]
|
|
|
|
_liquidity_lines, suspense_lines, _other = st_line._seek_for_lines()
|
|
counterpart = suspense_lines[:1]
|
|
if not counterpart:
|
|
raise UserError(_("This bank transaction has no journal entry yet, "
|
|
"so it cannot be reconciled."))
|
|
|
|
counterpart.account_id = target_account
|
|
if st_line.partner_id and not counterpart.partner_id:
|
|
counterpart.partner_id = st_line.partner_id
|
|
|
|
(counterpart | self.selected_aml_ids).reconcile()
|
|
st_line.modified(['is_reconciled', 'amount_residual'])
|
|
st_line.invalidate_recordset(['is_reconciled', 'amount_residual'])
|
|
return {"type": "ir.actions.act_window_close"}
|
|
|
|
def action_create_counterpart(self):
|
|
"""Create a new journal item on the chosen account and reconcile."""
|
|
self.ensure_one()
|
|
st_line = self.statement_line_id
|
|
if not self.counterpart_account_id:
|
|
raise UserError(_("Choose a counterpart account."))
|
|
if not self.manual_amount:
|
|
self.manual_amount = st_line.amount
|
|
|
|
move = st_line.move_id
|
|
if not move:
|
|
raise UserError(_("This bank transaction has no linked journal entry."))
|
|
|
|
vals = {
|
|
"move_id": move.id,
|
|
"account_id": self.counterpart_account_id.id,
|
|
"name": self.manual_label or st_line.payment_ref or _("Bank reconciliation"),
|
|
"partner_id": (self.manual_partner_id or st_line.partner_id).id,
|
|
"balance": -self.manual_amount,
|
|
"currency_id": st_line.currency_id.id,
|
|
"company_id": st_line.company_id.id,
|
|
}
|
|
if self.manual_tax_id:
|
|
vals["tax_ids"] = [(6, 0, self.manual_tax_id.ids)]
|
|
|
|
new_line = self.env["account.move.line"].create(vals)
|
|
move.action_post()
|
|
|
|
liquidity_lines, suspense_lines, _other = st_line._seek_for_lines()
|
|
to_reconcile = liquidity_lines[:1] | new_line
|
|
if not float_is_zero(
|
|
st_line.amount + new_line.balance,
|
|
precision_rounding=st_line.currency_id.rounding,
|
|
) and suspense_lines:
|
|
to_reconcile |= suspense_lines[:1]
|
|
to_reconcile.reconcile()
|
|
st_line.modified(['is_reconciled', 'amount_residual'])
|
|
st_line.invalidate_recordset(['is_reconciled', 'amount_residual'])
|
|
return {"type": "ir.actions.act_window_close"}
|
|
|
|
def action_apply_rules(self):
|
|
"""Run the configured reconciliation models over open statement lines."""
|
|
self.ensure_one()
|
|
models_to_run = self.env["account.reconcile.model"].search([
|
|
("company_id", "=", self.company_id.id),
|
|
("rule_type", "=", "writeoff_suggestion"),
|
|
])
|
|
applied = 0
|
|
open_lines = self.env["account.bank.statement.line"].search([
|
|
("journal_id", "=", self.journal_id.id),
|
|
("is_reconciled", "=", False),
|
|
])
|
|
for st_line in open_lines:
|
|
for rule in models_to_run:
|
|
if self._rule_matches(rule, st_line):
|
|
self._apply_rule(rule, st_line)
|
|
applied += 1
|
|
break
|
|
return {
|
|
"type": "ir.actions.client",
|
|
"tag": "display_notification",
|
|
"params": {
|
|
"title": _("Reconciliation Rules"),
|
|
"message": _("%s bank transactions processed.", applied),
|
|
"type": "success",
|
|
},
|
|
}
|
|
|
|
@staticmethod
|
|
def _rule_matches(rule, st_line):
|
|
if rule.match_journal_ids and st_line.journal_id not in rule.match_journal_ids:
|
|
return False
|
|
amount = abs(st_line.amount or 0.0)
|
|
if rule.match_amount == "lower" and amount >= rule.match_amount_max:
|
|
return False
|
|
if rule.match_amount == "greater" and amount <= rule.match_amount_min:
|
|
return False
|
|
if rule.match_amount == "between":
|
|
if not (rule.match_amount_min <= amount <= rule.match_amount_max):
|
|
return False
|
|
if rule.match_label == "contains" and rule.match_label_param:
|
|
if rule.match_label_param.lower() not in (st_line.payment_ref or "").lower():
|
|
return False
|
|
if rule.match_partner_ids and st_line.partner_id not in rule.match_partner_ids:
|
|
return False
|
|
return True
|
|
|
|
def _apply_rule(self, rule, st_line):
|
|
"""Write off the statement line following a reconciliation model."""
|
|
account = rule.line_ids[:1].account_id
|
|
if not account:
|
|
return False
|
|
liquidity_lines, suspense_lines, _other = st_line._seek_for_lines()
|
|
liquidity = liquidity_lines[:1]
|
|
if not liquidity:
|
|
return False
|
|
move = st_line.move_id
|
|
new_line = self.env["account.move.line"].create({
|
|
"move_id": move.id,
|
|
"account_id": account.id,
|
|
"name": rule.line_ids[:1].label or st_line.payment_ref,
|
|
"partner_id": st_line.partner_id.id,
|
|
"balance": -st_line.amount,
|
|
"currency_id": st_line.currency_id.id,
|
|
"company_id": st_line.company_id.id,
|
|
})
|
|
move.action_post()
|
|
(liquidity | new_line).reconcile()
|
|
st_line.modified(['is_reconciled', 'amount_residual'])
|
|
st_line.invalidate_recordset(['is_reconciled', 'amount_residual'])
|
|
return True
|
|
|
|
def action_unreconcile(self):
|
|
"""Undo the reconciliation of the statement line."""
|
|
self.ensure_one()
|
|
return self.statement_line_id.action_undo_reconciliation()
|
|
|
|
|
|
class DnBankRecCandidate(models.TransientModel):
|
|
"""One scored suggestion shown in the matching panel."""
|
|
|
|
_name = "dn.bank.rec.candidate"
|
|
_description = "DN Bank Reconciliation Candidate"
|
|
_order = "score desc, id"
|
|
|
|
wizard_id = fields.Many2one(
|
|
"dn.bank.rec.wizard", required=True, ondelete="cascade",
|
|
)
|
|
move_line_id = fields.Many2one("account.move.line", required=True,
|
|
string="Journal Item")
|
|
score = fields.Integer(string="Score", default=0)
|
|
reason = fields.Char(string="Why")
|
|
selected = fields.Boolean(string="Selected", default=False)
|
|
|
|
date = fields.Date(related="move_line_id.date")
|
|
move_name = fields.Char(related="move_line_id.move_name", string="Entry")
|
|
label = fields.Text(related="move_line_id.name", string="Label")
|
|
partner_id = fields.Many2one(related="move_line_id.partner_id", string="Partner")
|
|
account_id = fields.Many2one(related="move_line_id.account_id", string="Account")
|
|
balance = fields.Monetary(related="move_line_id.balance", string="Balance")
|
|
amount_residual = fields.Monetary(related="move_line_id.amount_residual",
|
|
string="Amount Due")
|
|
currency_id = fields.Many2one(related="move_line_id.currency_id")
|
|
|
|
def action_toggle(self):
|
|
self.ensure_one()
|
|
self.selected = not self.selected
|
|
wizard = self.wizard_id
|
|
if self.selected:
|
|
wizard.selected_aml_ids = [(4, self.move_line_id.id)]
|
|
else:
|
|
wizard.selected_aml_ids = [(3, self.move_line_id.id)]
|
|
return True
|
|
|
|
|
|
class AccountBankStatementLine(models.Model):
|
|
"""Add a reconciliation entry point on the standard statement line."""
|
|
|
|
_inherit = "account.bank.statement.line"
|
|
|
|
def action_open_dn_reconciliation(self):
|
|
"""Open the DN matching workspace for this statement line."""
|
|
self.ensure_one()
|
|
wizard = self.env["dn.bank.rec.wizard"].create_from_statement_line(self.id)
|
|
return {
|
|
"type": "ir.actions.act_window",
|
|
"name": _("Bank reconciliation: %s", self.payment_ref or self.move_id.name or ""),
|
|
"res_model": "dn.bank.rec.wizard",
|
|
"res_id": wizard.id,
|
|
"view_mode": "form",
|
|
"target": "current",
|
|
"context": {"create": False},
|
|
}
|