accountant_cn

This commit is contained in:
2026-11-17 17:57:08 +08:00
parent 9b924747c5
commit 5fc4382687
771 changed files with 18102 additions and 820280 deletions

View File

@@ -0,0 +1,16 @@
# -*- coding: utf-8 -*-
from . import account_groups
# report engines
from . import dn_report
from . import dn_fr
# accounting essentials
from . import dn_fiscal_year
from . import dn_bank_rec
# loans (journal first: dn_loan imports from it)
from . import dn_loan_journal
from . import dn_loan
from . import dn_loan_line
from . import dn_loan_move
# audit working files
from . import dn_audit_return
from . import dn_audit_check

View File

@@ -0,0 +1,57 @@
# -*- coding: utf-8 -*-
"""Group wiring for the Accounting application.
Odoo 20 Community stops the accounting group chain early:
group_account_manager -> group_account_invoice
which leaves a full accounting *administrator* without
``group_account_readonly`` (needed by every report action and most Accounting
menu entries) and without ``group_account_basic`` (needed by the dashboard).
Enterprise repairs it across `accountant` and `account_accountant`. We do the
same in one place below, so the reports installed by this suite are actually
reachable by the person who installed them.
"""
import logging
from odoo import api, models
_logger = logging.getLogger(__name__)
class ResGroups(models.Model):
_inherit = "res.groups"
@api.model
def _dn_ensure_accounting_feature_groups(self):
"""Make every accounting administrator a full accounting user.
``implied_ids`` is normally enough: Odoo resolves group membership
transitively through ``all_implied_ids``, so a user in
``group_account_manager`` automatically benefits from the groups it now
implies. This method additionally *materialises* the membership for
users who already existed before the upgrade, which keeps
``res_groups_users_rel`` consistent for anything that reads it directly
(ACLs, record rules, some reports) instead of going through the ORM
cache.
"""
manager = self.env.ref("account.group_account_manager", raise_if_not_found=False)
user_group = self.env.ref("account.group_account_user", raise_if_not_found=False)
if not manager or not user_group:
return
# Repair the chain if a later module re-broke it.
if user_group not in manager.implied_ids:
manager.write({"implied_ids": [(4, user_group.id)]})
users = manager.user_ids
missing = users - user_group.user_ids
if missing:
user_group.write({"user_ids": [(4, uid) for uid in missing.ids]})
_logger.info(
"DN Accounting Menu: granted full accounting features to %s user(s): %s",
len(missing),
", ".join(missing.mapped("login")),
)

View File

@@ -0,0 +1,131 @@
# -*- coding: utf-8 -*-
"""Checks: the individual items an accountant works through.
A check is deliberately small. It records *what* has to be looked at, *how* it
is recorded (cleared, not applicable, or with a comment), and who touched it.
It does not try to evaluate anything by itself - an automated check that
silently decides the books are fine is worse than no check at all, because it
hides the judgement the reviewer was supposed to make.
"""
from odoo import api, fields, models, _
class DnAuditCheck(models.Model):
_name = "dn.audit.check"
_description = "Audit Check"
# mail.thread so `tracking` on `result` is meaningful: the trail of who
# cleared which check, and when, is the audit evidence this model exists to
# produce. Without it `tracking=True` is silently ignored.
_inherit = ["mail.thread"]
_order = "return_id, sequence, id"
return_id = fields.Many2one(
comodel_name="dn.audit.return",
string="Working File",
required=True,
ondelete="cascade",
index=True,
)
company_id = fields.Many2one(related="return_id.company_id", store=True, index=True)
currency_id = fields.Many2one(related="return_id.currency_id", readonly=True)
name = fields.Char(string="Name", required=True, translate=True)
sequence = fields.Integer(default=10)
check_type = fields.Selection(
selection=[
("check", "Check"),
("file", "Upload Document"),
],
string="Type",
default="check",
required=True,
)
description = fields.Html(string="Description", translate=True)
template_id = fields.Many2one(
comodel_name="dn.audit.check.template",
string="Template",
ondelete="set null",
)
cycle_id = fields.Many2one(
comodel_name="dn.audit.cycle",
string="Cycle",
ondelete="set null",
)
result = fields.Selection(
selection=[
("todo", "To Do"),
("done", "Done"),
("na", "Not Applicable"),
("comment", "Commented"),
],
string="Result",
default="todo",
required=True,
tracking=True,
)
comment = fields.Text(string="Comment")
user_id = fields.Many2one(
comodel_name="res.users",
string="Reviewed By",
default=lambda self: self.env.user,
)
date_review = fields.Datetime(string="Reviewed On")
attachment_ids = fields.Many2many(
comodel_name="ir.attachment",
relation="dn_audit_check_attachment_rel",
column1="check_id",
column2="attachment_id",
string="Documents",
)
attachment_count = fields.Integer(
string="Documents Uploaded", compute="_compute_attachment_count")
# Surfaced on the check so the reviewer does not have to open the file to
# know which period the check belongs to.
date_from = fields.Date(related="return_id.date_from")
date_to = fields.Date(related="return_id.date_to")
@api.depends("attachment_ids")
def _compute_attachment_count(self):
for record in self:
record.attachment_count = len(record.attachment_ids)
@api.onchange("result")
def _onchange_result(self):
"""Stamp the reviewer and the moment the result changes.
Done in an onchange rather than in ``write`` so a bulk write from the
kanban drag does not overwrite the timestamp with "whenever this was
last saved"; the value only trails an explicit result change.
"""
if self.result != "todo":
self.user_id = self.env.user
self.date_review = fields.Datetime.now()
def action_set_result(self, result):
self.write({
"result": result,
"user_id": self.env.user.id,
"date_review": fields.Datetime.now(),
})
def action_mark_done(self):
self.action_set_result("done")
def action_mark_na(self):
self.action_set_result("na")
def action_open(self):
self.ensure_one()
return {
"type": "ir.actions.act_window",
"name": self.name,
"res_model": "dn.audit.check",
"res_id": self.id,
"view_mode": "form",
"target": "current",
}

View File

@@ -0,0 +1,348 @@
# -*- coding: utf-8 -*-
"""Working files: one period of review work.
Deliberately independent of the enterprise ``account.return`` model. The shape
below is driven by what the Review > Audit > Working Files screen has to do,
not by any enterprise implementation:
* a working file covers a date range and belongs to one company;
* it is filed under one or more *cycles* (bank, payroll, cut-off, ...), which
are just labelled buckets used to slice the review;
* it carries *checks* - the things an accountant has to look at - and a
check has its own result independent of the file's status;
* the file has a review status (ongoing / paused / done) that is *not*
derived from the checks, because "I am still working on this" and "the
checks pass" are two different facts and an accountant needs to record
both.
The completion rule is the one place the two meet: a file cannot be marked
done while checks are still on to-do.
"""
from odoo import api, fields, models, _
from odoo.exceptions import UserError
class DnAuditCycle(models.Model):
"""A labelled bucket a working file can be filed under.
Cycles exist so a review can be split the way an audit is actually split:
by area rather than by account. They carry nothing but a name and a code,
because anything richer would be knowledge the module cannot verify.
"""
_name = "dn.audit.cycle"
_description = "Audit Cycle"
_order = "sequence, name, id"
name = fields.Char(string="Name", required=True, translate=True)
code = fields.Char(string="Code", required=True)
sequence = fields.Integer(default=10)
active = fields.Boolean(default=True)
description = fields.Text(string="Description", translate=True)
_code_uniq = models.Constraint(
"unique (code)",
"Audit cycle codes must be unique.",
)
class DnAuditCheckTemplate(models.Model):
"""A reusable check definition.
A month-end close runs the same checks every month. Keeping them as
templates means the checks are written once and stamped onto each new
working file, instead of being retyped (and quietly dropped) every period.
"""
_name = "dn.audit.check.template"
_description = "Audit Check Template"
_order = "cycle_id, sequence, name, id"
name = fields.Char(string="Name", required=True, translate=True)
sequence = fields.Integer(default=10)
check_type = fields.Selection(
selection=[
("check", "Check"),
("file", "Upload Document"),
],
string="Type",
default="check",
required=True,
help="A check is something to be reviewed and cleared; a document is "
"an attachment that has to be provided.",
)
cycle_id = fields.Many2one(
comodel_name="dn.audit.cycle",
string="Cycle",
ondelete="set null",
)
description = fields.Html(string="Instructions", translate=True)
active = fields.Boolean(default=True)
def _prepare_check_values(self):
"""Values to stamp onto a working file's checks.
Kept on the template so the copy lives in one place: a change to what a
check means should not have to be made in the template *and* in every
place that instantiates it.
"""
self.ensure_one()
return {
"name": self.name,
"check_type": self.check_type,
"cycle_id": self.cycle_id.id,
"description": self.description,
"template_id": self.id,
}
class DnAuditReturn(models.Model):
"""One period of review work (a "working file")."""
_name = "dn.audit.return"
_description = "Audit Working File"
_inherit = ["mail.thread", "mail.activity.mixin"]
_order = "is_completed, date_deadline, date_from desc, id desc"
name = fields.Char(
string="Name",
required=True,
translate=True,
tracking=True,
help="Usually the period, e.g. \"2026-10 Close\".",
)
active = fields.Boolean(default=True, tracking=True)
company_id = fields.Many2one(
comodel_name="res.company",
string="Company",
required=True,
default=lambda self: self.env.company,
index=True,
)
currency_id = fields.Many2one(
related="company_id.currency_id",
string="Currency",
readonly=True,
)
date_from = fields.Date(string="Start Date", required=True, tracking=True)
date_to = fields.Date(string="End Date", required=True, tracking=True)
date_deadline = fields.Date(string="Deadline", tracking=True)
cycle_ids = fields.Many2many(
comodel_name="dn.audit.cycle",
relation="dn_audit_return_cycle_rel",
column1="return_id",
column2="cycle_id",
string="Cycles",
tracking=True,
)
# ---- review status -------------------------------------------------
# Not derived from the checks on purpose: "paused" is a statement about the
# reviewer's intent, not about the data. A file whose checks all pass can
# still be paused because the reviewer is waiting for an explanation.
review_state = fields.Selection(
selection=[
("ongoing", "Ongoing"),
("paused", "Paused"),
("done", "Done"),
],
string="Review Status",
default="ongoing",
required=True,
tracking=True,
)
is_completed = fields.Boolean(
string="Completed",
default=False,
tracking=True,
help="Set when the period has been signed off. Completing a file is "
"what removes it from the default Ongoing filter.",
)
notes = fields.Html(string="Notes", translate=True)
# ---- checks --------------------------------------------------------
check_ids = fields.One2many(
comodel_name="dn.audit.check",
inverse_name="return_id",
string="Checks",
)
check_count = fields.Integer(
string="Checks Total", compute="_compute_check_counts")
resolved_check_count = fields.Integer(
string="Checks Passed", compute="_compute_check_counts")
unresolved_check_count = fields.Integer(
string="Issues", compute="_compute_check_counts")
progress = fields.Float(
string="Progress (%)",
compute="_compute_check_counts",
help="Share of the checks that are no longer on to-do.",
)
# ---- helpers used by the kanban card -------------------------------
days_to_deadline = fields.Integer(
string="Days to Deadline", compute="_compute_days_to_deadline")
is_late = fields.Boolean(string="Late", compute="_compute_days_to_deadline")
_date_range_check = models.Constraint(
"CHECK (date_to >= date_from)",
"The end date must not be before the start date.",
)
# ------------------------------------------------------------------
# Compute
# ------------------------------------------------------------------
@api.depends("check_ids", "check_ids.result")
def _compute_check_counts(self):
for record in self:
total = len(record.check_ids)
# `na` counts as resolved: a check that does not apply to this
# period has been dealt with, and leaving it in the "issues" count
# would keep the file permanently red.
resolved = len(record.check_ids.filtered(
lambda c: c.result in ("done", "na")))
record.check_count = total
record.resolved_check_count = resolved
record.unresolved_check_count = total - resolved
record.progress = (resolved / total * 100.0) if total else 0.0
@api.depends("date_deadline", "is_completed")
def _compute_days_to_deadline(self):
today = fields.Date.context_today(self)
for record in self:
if not record.date_deadline:
record.days_to_deadline = 0
record.is_late = False
continue
delta = (record.date_deadline - today).days
record.days_to_deadline = delta
record.is_late = bool(delta < 0 and not record.is_completed)
# ------------------------------------------------------------------
# Constraints / onchange
# ------------------------------------------------------------------
@api.constrains("date_from", "date_to")
def _check_dates(self):
for record in self:
if record.date_from and record.date_to and record.date_to < record.date_from:
raise UserError(_(
"The end date (%(end)s) cannot be before the start date "
"(%(start)s).",
end=record.date_to,
start=record.date_from,
))
@api.onchange("date_from")
def _onchange_date_from(self):
# Filling the start date suggests a name, so a new file does not have to
# be named by hand and end up as "New" in the kanban.
if self.date_from and not self.name:
self.name = _("%(period)s Close", period=self.date_from.strftime("%Y-%m"))
# ------------------------------------------------------------------
# Actions
# ------------------------------------------------------------------
def action_pause(self):
self.write({"review_state": "paused"})
def action_resume(self):
self.write({"review_state": "ongoing"})
def action_mark_done(self):
"""Sign the period off.
Refuses while checks are unresolved. This is the only place the review
status and the check results are allowed to constrain each other, and
it is a guard rather than a computation: an accountant *can* still set
a check to n/a to get past a check that genuinely does not apply.
"""
for record in self:
blocking = record.check_ids.filtered(lambda c: c.result == "todo")
if blocking:
raise UserError(_(
"%(name)s still has %(count)s unresolved check(s). "
"Resolve them, or mark them as not applicable, before "
"completing the file.",
name=record.name,
count=len(blocking),
))
self.write({"review_state": "done", "is_completed": True})
def action_reset_to_ongoing(self):
self.write({"review_state": "ongoing", "is_completed": False})
def action_load_templates(self):
"""Stamp the active templates onto this file.
Only templates whose cycle is already on the file are added when the
file has cycles; a file with no cycles gets every active template. This
keeps "I filed this under Bank" from silently pulling in the payroll
checks as well.
Loading twice is a no-op rather than a duplicate: a template already
present on the file is skipped by ``template_id``. The button therefore
stays safe to press again after adding a cycle.
A button that can legitimately do nothing has to say so - otherwise the
reviewer presses it, sees no change, and concludes the feature is
broken (or worse, that the checks were already there).
"""
Check = self.env["dn.audit.check"]
added = 0
for record in self:
templates = self.env["dn.audit.check.template"].search([])
if record.cycle_ids:
templates = templates.filtered(
lambda t: not t.cycle_id or t.cycle_id in record.cycle_ids)
existing = record.check_ids.mapped("template_id")
values = []
for template in templates - existing:
vals = template._prepare_check_values()
vals["return_id"] = record.id
values.append(vals)
if values:
Check.create(values)
added += len(values)
if not added:
return self._notify(_(
"Nothing to load: every check template matching this file's "
"cycles has already been added. Add more templates, or put the "
"file under another cycle first.",
))
return self._notify(_(
"%(count)s check(s) added to the working file.",
count=added,
))
def _notify(self, message):
"""A ``display_notification`` action carrying ``message``.
The button has to answer. Loading templates either adds checks (the
form has to re-read them, hence ``soft_reload``) or adds nothing
(nothing changes, so only the message is needed) - and in both cases
silence reads as a broken button.
"""
return {
"type": "ir.actions.client",
"tag": "display_notification",
"params": {
"type": "info",
"message": message,
"sticky": False,
"next": {"type": "ir.actions.client", "tag": "soft_reload"},
},
}
def action_view_checks(self):
self.ensure_one()
return {
"type": "ir.actions.act_window",
"name": _("Checks"),
"res_model": "dn.audit.check",
"view_mode": "kanban,list,form",
"domain": [("return_id", "=", self.id)],
"context": {"default_return_id": self.id},
}

View File

@@ -0,0 +1,415 @@
# -*- 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},
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,688 @@
from dateutil.relativedelta import relativedelta
from odoo import _, api, Command, fields, models
from odoo.exceptions import UserError, ValidationError
from odoo.tools import float_compare, format_date
class DnLoan(models.Model):
_name = 'dn.loan'
_description = 'Loan'
_inherit = ['mail.thread', 'mail.activity.mixin', 'analytic.mixin']
_order = 'date desc, id desc'
_check_company_auto = True
# -- identity --------------------------------------------------------
name = fields.Char(
string='Name', required=True, tracking=True, index='trigram',
help="Reference of the loan, usually the contract number.",
)
company_id = fields.Many2one(
'res.company', string='Company', required=True, index=True,
default=lambda self: self.env.company,
)
currency_id = fields.Many2one(related='company_id.currency_id', store=True)
active = fields.Boolean(default=True)
state = fields.Selection(
selection=[
('draft', 'Draft'),
('running', 'Running'),
('closed', 'Closed'),
('cancelled', 'Cancelled'),
],
string='Status', default='draft', required=True, tracking=True,
copy=False,
)
# -- terms -----------------------------------------------------------
date = fields.Date(
string='Loan Date', index='btree_not_null', tracking=True,
help="Date the money was borrowed. Interest starts accruing on this day.",
)
amount_borrowed = fields.Monetary(string='Amount Borrowed', tracking=True)
interest = fields.Monetary(
string='Interest', tracking=True,
help="Total interest over the whole schedule. Filled in when the "
"schedule is computed, and checked against it before confirming.",
)
duration = fields.Integer(
string='Duration',
help="Number of installments. Filled in when the schedule is computed.",
)
method = fields.Selection(
selection=[
('annuity', 'Annuity'),
('linear', 'Linear'),
('interest_only', 'Interest Only'),
],
string='Repayment Method', default='annuity', required=True,
help="Annuity: every installment pays the same total. "
"Linear: every installment repays the same principal. "
"Interest Only: only interest is paid until a balloon payment.",
)
skip_until_date = fields.Date(
string='Skip until',
help="Installments due on or before this date are not posted. Use it "
"when the first payments were already booked by hand before the "
"loan was recorded here.",
)
# -- accounts and journal --------------------------------------------
long_term_account_id = fields.Many2one(
'account.account', string='Long Term Account', tracking=True,
check_company=True,
help="Liability account for the part of the principal due after "
"twelve months.",
)
short_term_account_id = fields.Many2one(
'account.account', string='Short Term Account', tracking=True,
check_company=True,
help="Liability account for the part of the principal due within "
"twelve months. Payments are booked against this account.",
)
expense_account_id = fields.Many2one(
'account.account', string='Expense Account', tracking=True,
check_company=True,
domain="[('account_type', 'in', ('expense', 'expense_depreciation', "
"'expense_other'))]",
help="Account the interest is charged to.",
)
journal_id = fields.Many2one(
'account.journal', string='Journal', tracking=True, check_company=True,
domain="[('type', '=', 'general')]",
)
loan_properties = fields.Properties(
string='Properties', definition='journal_id.loan_properties_definition',
)
line_ids = fields.One2many(
'dn.loan.line', 'loan_id', string='Amortization Schedule',
copy=True,
)
move_ids = fields.One2many(
'account.move', 'dn_loan_id', string='Generated Entries', readonly=True,
)
# -- computed --------------------------------------------------------
display_name = fields.Char(
string='Loan name', compute='_compute_display_name', store=True,
# Stored because the pivot view groups by it, and a non-stored field
# cannot be used as a group-by.
)
start_date = fields.Date(compute='_compute_start_end_date', store=True)
end_date = fields.Date(compute='_compute_start_end_date', store=True)
is_wrong_date = fields.Boolean(compute='_compute_is_wrong_date')
amount_borrowed_difference = fields.Monetary(
compute='_compute_differences',
help="Amount borrowed minus the sum of the principals in the schedule.",
)
interest_difference = fields.Monetary(
compute='_compute_differences',
help="Interest minus the sum of the interest in the schedule.",
)
duration_difference = fields.Integer(compute='_compute_differences')
outstanding_balance = fields.Monetary(
string='Outstanding Balance', compute='_compute_outstanding_balance',
help="Principal still owed, according to the entries actually posted.",
)
nb_posted_entries = fields.Integer(compute='_compute_nb_posted_entries')
count_lines = fields.Integer(compute='_compute_count_lines')
# -- defaults --------------------------------------------------------
@api.model
def default_get(self, field_names):
"""Copy the accounts and journal from the previous loan.
A company borrows repeatedly, and every loan uses the same three
accounts. Asking for them again on each record is the kind of friction
that makes people stop using the feature.
"""
values = super().default_get(field_names)
if not any(f in field_names for f in (
'expense_account_id', 'long_term_account_id',
'short_term_account_id', 'journal_id')):
return values
previous = self.search([
('company_id', '=', self.env.company.id),
('expense_account_id', '!=', False),
('long_term_account_id', '!=', False),
('short_term_account_id', '!=', False),
('journal_id', '!=', False),
], limit=1, order='id desc')
if previous:
for field_name in ('expense_account_id', 'long_term_account_id',
'short_term_account_id', 'journal_id'):
values[field_name] = previous[field_name].id
return values
# -- constrains ------------------------------------------------------
@api.constrains('amount_borrowed', 'interest', 'duration')
def _check_positive_values(self):
for loan in self:
rounding = loan.currency_id.rounding or 0.01
if float_compare(loan.amount_borrowed, 0.0, precision_rounding=rounding) < 0:
raise ValidationError(_("The amount borrowed cannot be negative."))
if float_compare(loan.interest, 0.0, precision_rounding=rounding) < 0:
raise ValidationError(_("The interest cannot be negative."))
if loan.duration < 0:
raise ValidationError(_("The duration cannot be negative."))
@api.constrains('long_term_account_id', 'short_term_account_id', 'expense_account_id')
def _check_accounts(self):
"""Long and short term must be different accounts.
If they are the same, the monthly reclassification moves money from an
account to itself: the entry is balanced but meaningless, and the
balance sheet shows nothing at all. Catching it here is much cheaper
than explaining the empty balance sheet later.
"""
for loan in self:
if (loan.long_term_account_id and loan.short_term_account_id
and loan.long_term_account_id == loan.short_term_account_id):
raise ValidationError(_(
"The long term and short term accounts must be different: "
"the monthly reclassification would otherwise move the "
"principal from an account to itself."))
# -- computes --------------------------------------------------------
@api.depends('name', 'start_date', 'end_date')
def _compute_display_name(self):
for loan in self:
if loan.name and loan.start_date and loan.end_date:
loan.display_name = "%s: %s - %s" % (
loan.name,
format_date(self.env, loan.start_date, date_format='MM y'),
format_date(self.env, loan.end_date, date_format='MM y'),
)
else:
loan.display_name = loan.name or _("New Loan")
@api.depends('line_ids.date')
def _compute_start_end_date(self):
for loan in self:
dates = loan.line_ids.mapped('date')
loan.start_date = min(dates) if dates else False
loan.end_date = max(dates) if dates else False
@api.depends('date', 'line_ids.date')
def _compute_is_wrong_date(self):
"""Whether the loan date is unusable.
An installment dated before the loan itself means interest would be
charged for time that had not elapsed yet, so the schedule is rejected.
"""
for loan in self:
loan.is_wrong_date = bool(
not loan.date
or any(d < loan.date for d in loan.line_ids.mapped('date'))
)
@api.depends('amount_borrowed', 'interest', 'duration', 'line_ids.principal',
'line_ids.interest', 'currency_id')
def _compute_differences(self):
for loan in self:
rounding = loan.currency_id.rounding or 0.01
principal_sum = sum(loan.line_ids.mapped('principal'))
interest_sum = sum(loan.line_ids.mapped('interest'))
loan.amount_borrowed_difference = loan.currency_id.round(
loan.amount_borrowed - principal_sum
)
loan.interest_difference = loan.currency_id.round(loan.interest - interest_sum)
loan.duration_difference = loan.duration - len(loan.line_ids)
# Silence the unused variable warning while keeping the rounding
# precision explicit at the call site.
del rounding
@api.depends('amount_borrowed', 'state', 'line_ids.principal',
'line_ids.is_payment_move_posted', 'skip_until_date',
'line_ids.date')
def _compute_outstanding_balance(self):
"""Principal still owed, based only on what has been posted.
Deriving this from the schedule instead would show a loan as partly
repaid as soon as the schedule exists, even though no entry has been
booked. The balance sheet would disagree with the loan list, and the
loan list is what people check.
"""
for loan in self:
if loan.state != 'running':
loan.outstanding_balance = loan.amount_borrowed
continue
repaid = sum(
line.principal for line in loan.line_ids
if line.is_payment_move_posted
or (loan.skip_until_date and line.date < loan.skip_until_date)
)
loan.outstanding_balance = loan.currency_id.round(
loan.amount_borrowed - repaid
)
@api.depends('move_ids.state')
def _compute_nb_posted_entries(self):
for loan in self:
loan.nb_posted_entries = len(
loan.move_ids.filtered(lambda m: m.state == 'posted')
)
@api.depends('line_ids')
def _compute_count_lines(self):
for loan in self:
loan.count_lines = len(loan.line_ids)
# -- schedule helpers -------------------------------------------------
def _schedule_summary(self):
"""Totals of the schedule, used by the preview and the confirm check."""
self.ensure_one()
return {
'principal': sum(self.line_ids.mapped('principal')),
'interest': sum(self.line_ids.mapped('interest')),
'count': len(self.line_ids),
}
def _next_reclassification_amount(self, line):
"""Principal due in the twelve months following ``line``.
This is what the monthly reclassification moves from long term to short
term: at each payment date, whatever falls due over the coming year has
to sit on the short term account.
"""
self.ensure_one()
ordered = self.line_ids.sorted(lambda l: (l.date, l.id))
try:
index = ordered.ids.index(line.id)
except ValueError:
return 0.0
return sum(ordered[index + 1:index + 13].mapped('principal'))
# -- actions ---------------------------------------------------------
def action_open_compute_wizard(self):
"""Open the schedule generator, pre-filled from the current record."""
self.ensure_one()
if not self.name:
raise UserError(_("Please give the loan a name before computing it."))
wizard = self.env['dn.loan.compute.wizard'].create({
'loan_id': self.id,
'loan_amount': self.amount_borrowed or 0.0,
'start_date': self.date or fields.Date.context_today(self),
'first_payment_date': (self.date or fields.Date.context_today(self)).replace(
day=1) + relativedelta(months=1),
'method': self.method,
})
return {
'name': _("Compute Loan"),
'res_id': wizard.id,
'type': 'ir.actions.act_window',
'res_model': 'dn.loan.compute.wizard',
'target': 'new',
'views': [[False, 'form']],
}
def action_confirm(self):
"""Post every installment that is due, plus the reclassifications.
Two kinds of entry are produced per installment:
* the payment entry, which moves the principal out of the short term
liability and books the interest as an expense;
* the reclassification entry, which moves the principal falling due in
the next twelve months from long term to short term, and its mirror
image at the start of the following month.
The reclassification exists because a loan is long term as a whole but
the part due within a year must be reported as current. Without it the
balance sheet overstates non-current liabilities by up to a full year of
repayments.
"""
for loan in self:
loan._check_confirmable()
payment_values = []
reclass_values = []
reclass_reverse_values = []
ordered = loan.line_ids.sorted(lambda l: (l.date, l.id))
for index, line in enumerate(ordered):
if loan.skip_until_date and line.date < loan.skip_until_date:
continue
# Book into the month of the due date, but never before the loan
# itself: an installment due on the 1st for a loan signed on the
# 20th still belongs to the loan's month.
accounting_date = max(line.date.replace(day=1), loan.date)
period_label = format_date(self.env, line.date, date_format='MM/y')
prefix = "%s - " % loan.name
payment_values.append(
loan._prepare_payment_move(line, accounting_date, prefix, period_label)
)
if index == len(ordered) - 1:
continue # nothing left to reclassify on the final row
next_lines = ordered[index + 1:index + 13]
if not next_lines:
continue
moving = sum(next_lines.mapped('principal'))
if not moving:
continue
from_label = format_date(self.env, next_lines[0].date, date_format='MM/y')
to_label = format_date(self.env, next_lines[-1].date, date_format='MM/y')
reclass_values.append(loan._prepare_reclassification_move(
line, accounting_date, moving, from_label, to_label, prefix,
))
reclass_reverse_values.append(loan._prepare_reclassification_reversal(
line, moving, from_label, to_label, prefix,
accounting_date + relativedelta(months=1, day=1),
))
payment_moves = self.env['account.move'].create(payment_values)
reclass_moves = self.env['account.move'].create(reclass_values)
reverse_moves = self.env['account.move'].create(reclass_reverse_values)
# Entries dated in the future stay in draft, so the schedule can be
# corrected without reversing anything. `auto_post` is what makes
# them post themselves once the date arrives.
to_post = (payment_moves | reclass_moves | reverse_moves).filtered(
lambda m: m.date <= fields.Date.context_today(self)
)
to_post.action_post()
loan._link_reversals(reclass_moves, reverse_moves)
loan.state = 'running'
loan.message_post(body=_(
"Loan confirmed: %(count)s installments scheduled, "
"%(posted)s entries posted and %(draft)s left for later dates.",
count=len(ordered),
posted=len(to_post),
draft=len(payment_moves | reclass_moves | reverse_moves) - len(to_post),
))
return True
def _check_confirmable(self):
"""Refuse to confirm a loan whose schedule does not add up.
Each of these conditions would produce entries that cannot be reconciled
against the contract, so the loan is blocked rather than booked wrongly.
"""
self.ensure_one()
rounding = self.currency_id.rounding or 0.01
if not self.name:
raise UserError(_("The loan name should be set."))
if not self.line_ids:
raise UserError(_("The loan has no amortization schedule. Compute or "
"import it before confirming the loan."))
if self.is_wrong_date:
raise UserError(_(
"The loan date must be on or before the first installment date."))
if float_compare(self.amount_borrowed_difference, 0.0,
precision_rounding=rounding) != 0:
raise UserError(_(
"The amount borrowed (%(amount)s) must equal the sum of the "
"principals in the schedule (%(principal)s), a difference of "
"%(difference)s remains.",
amount=self.currency_id.format(self.amount_borrowed),
principal=self.currency_id.format(
sum(self.line_ids.mapped('principal'))),
difference=self.currency_id.format(self.amount_borrowed_difference),
))
if float_compare(self.interest_difference, 0.0,
precision_rounding=rounding) != 0:
raise UserError(_(
"The interest (%(interest)s) must equal the sum of the interest "
"in the schedule (%(schedule)s).",
interest=self.currency_id.format(self.interest),
schedule=self.currency_id.format(sum(self.line_ids.mapped('interest'))),
))
if self.duration_difference != 0:
raise UserError(_(
"The duration (%(duration)s) must equal the number of "
"installments in the schedule (%(lines)s).",
duration=self.duration, lines=len(self.line_ids),
))
if not (self.long_term_account_id and self.short_term_account_id
and self.expense_account_id):
raise UserError(_(
"The long term, short term and interest expense accounts should "
"all be set before confirming the loan."))
if not self.journal_id:
raise UserError(_("The loan journal should be set before "
"confirming the loan."))
# -- entry preparation ------------------------------------------------
def _move_common_values(self, line, accounting_date, ref, is_payment):
self.ensure_one()
return {
'company_id': self.company_id.id,
'journal_id': self.journal_id.id,
'date': accounting_date,
'ref': ref,
'auto_post': 'at_date',
'dn_loan_line_id': line.id,
'is_loan_payment_move': is_payment,
}
def _prepare_payment_move(self, line, accounting_date, prefix, period_label):
"""The entry that actually pays one installment."""
self.ensure_one()
return {
**self._move_common_values(
line, accounting_date,
_("%(loan)s - Principal & Interest %(period)s",
loan=self.name, period=period_label),
is_payment=True,
),
'line_ids': [
Command.create({
'account_id': self.long_term_account_id.id,
'debit': line.principal,
'name': _("%(loan)s - Principal %(period)s",
loan=self.name, period=period_label),
'analytic_distribution': self.analytic_distribution,
}),
Command.create({
'account_id': self.short_term_account_id.id,
'credit': line.payment,
'name': _("%(loan)s - Due %(period)s (Principal %(principal)s "
"+ Interest %(interest)s)",
loan=self.name, period=period_label,
principal=self.currency_id.format(line.principal),
interest=self.currency_id.format(line.interest)),
'analytic_distribution': self.analytic_distribution,
'date_maturity': line.date,
}),
Command.create({
'account_id': self.expense_account_id.id,
'debit': line.interest,
'name': _("%(loan)s - Interest %(period)s",
loan=self.name, period=period_label),
'analytic_distribution': self.analytic_distribution,
}),
],
}
def _prepare_reclassification_move(self, line, accounting_date, amount,
from_label, to_label, prefix):
"""Move the principal due within a year to the short term account."""
self.ensure_one()
label = _("Reclassification LT - ST %(from_date)s to %(to_date)s",
from_date=from_label, to_date=to_label)
return {
**self._move_common_values(
line, accounting_date, "%s%s" % (prefix, label), is_payment=False,
),
'line_ids': [
Command.create({
'account_id': self.long_term_account_id.id,
'debit': amount,
'name': "%s%s (To %s)" % (prefix, label, self.short_term_account_id.code),
'analytic_distribution': self.analytic_distribution,
}),
Command.create({
'account_id': self.short_term_account_id.id,
'credit': amount,
'name': "%s%s (From %s)" % (prefix, label, self.long_term_account_id.code),
'analytic_distribution': self.analytic_distribution,
}),
],
}
def _prepare_reclassification_reversal(self, line, amount, from_label,
to_label, prefix, reversal_date):
"""The mirror of the reclassification, on the first of the next month.
The reclassification is not a carry-forward: it only restates the split
as of the closing date. Leaving it in place would double the short term
liability every month, so it is reversed immediately.
"""
self.ensure_one()
label = _("Reversal reclassification LT - ST %(from_date)s to %(to_date)s",
from_date=from_label, to_date=to_label)
return {
**self._move_common_values(
line, reversal_date, "%s%s" % (prefix, label), is_payment=False,
),
'line_ids': [
Command.create({
'account_id': self.long_term_account_id.id,
'credit': amount,
'name': "%s%s (To %s)" % (prefix, label, self.short_term_account_id.code),
'analytic_distribution': self.analytic_distribution,
}),
Command.create({
'account_id': self.short_term_account_id.id,
'debit': amount,
'name': "%s%s (From %s)" % (prefix, label, self.long_term_account_id.code),
'analytic_distribution': self.analytic_distribution,
}),
],
}
def _link_reversals(self, reclass_moves, reverse_moves):
"""Tie each reversal to its original, both ways, with a log message."""
self.ensure_one()
bodies = {}
for original, reversal in zip(reclass_moves, reverse_moves):
reversal.reversed_entry_id = original.id
reversal.message_post(body=_(
"This entry reverses %s.",
original._get_html_link(),
))
bodies[original.id] = _(
"This entry has been reversed by %s.",
reversal._get_html_link(title=_("reversed")),
)
if bodies:
reclass_moves._message_log_batch(bodies=bodies)
# -- lifecycle --------------------------------------------------------
def action_set_to_draft(self):
"""Undo the confirmation, removing the entries it produced."""
for loan in self:
loan.move_ids.filtered(lambda m: m.state != 'cancel')._unlink_or_reverse()
loan.state = 'draft'
loan.message_post(body=_("Loan reset to draft."))
def action_cancel(self):
for loan in self:
loan.move_ids.filtered(lambda m: m.state != 'cancel')._unlink_or_reverse()
loan.state = 'cancelled'
loan.message_post(body=_("Loan cancelled."))
def action_reset_schedule(self):
"""Clear the schedule so it can be computed again."""
for loan in self:
loan.line_ids.unlink()
loan.message_post(body=_("Amortization schedule cleared."))
def action_close(self):
"""Open the wizard that closes the loan at a chosen date."""
self.ensure_one()
wizard = self.env['dn.loan.close.wizard'].create({'loan_id': self.id})
return {
'name': _("Close Loan"),
'view_mode': 'form',
'res_model': 'dn.loan.close.wizard',
'type': 'ir.actions.act_window',
'target': 'new',
'res_id': wizard.id,
}
def action_reopen(self):
"""Put a closed loan back in progress, keeping its schedule."""
for loan in self:
if loan.state != 'closed':
continue
loan.state = 'running'
loan.message_post(body=_("Loan reopened."))
# -- navigation -------------------------------------------------------
def action_open_loan_entries(self):
self.ensure_one()
return {
'name': _("Loan Entries"),
'view_mode': 'list,form',
'res_model': 'account.move',
'views': [(self.env.ref(
'accountant_cn.dn_loan_move_list_view').id, 'list'),
(False, 'form')],
'type': 'ir.actions.act_window',
'domain': [('id', 'in', self.move_ids.ids)],
}
# -- import -----------------------------------------------------------
def action_upload_amortization_schedule(self):
"""Let the user drop a spreadsheet and map its columns.
Reusing the standard import wizard keeps the behaviour people already
know, instead of inventing a bespoke CSV parser.
"""
self.ensure_one()
return {
'type': 'ir.actions.act_window',
'name': _("Import Amortization Schedule"),
'res_model': 'base_import.import',
'view_mode': 'form',
'target': 'new',
'context': {
'default_res_model': 'dn.loan.line',
'default_loan_id': self.id,
},
}
# -- crud -------------------------------------------------------------
@api.ondelete(at_uninstall=False)
def _unlink_loan(self):
"""Remove the loan's entries together with the loan.
`dn_loan_line_id` cascades at the database level, but a posted entry
cannot be deleted, only reversed. Handling it explicitly keeps the
ledger consistent instead of raising a foreign key error.
"""
for loan in self:
loan.move_ids._unlink_or_reverse()
loan.line_ids.unlink()
def unlink(self):
if any(loan.state == 'running' for loan in self):
raise UserError(_(
"A running loan cannot be deleted: its entries are in the "
"ledger. Cancel it first, then delete it."))
return super().unlink()

View File

@@ -0,0 +1,12 @@
from odoo import fields, models
class AccountJournal(models.Model):
_inherit = 'account.journal'
loan_properties_definition = fields.PropertiesDefinition(
string='Loan Properties',
help="Fields offered on the Properties tab of the loans booked in this "
"journal. Defining them per journal keeps each kind of borrowing "
"recording the attributes it actually has.",
)

View File

@@ -0,0 +1,127 @@
from odoo import _, api, fields, models
class DnLoanLine(models.Model):
_name = 'dn.loan.line'
_description = 'Loan Installment'
_order = 'date, id'
_check_company_auto = True
sequence = fields.Integer(string='#', compute='_compute_sequence')
loan_id = fields.Many2one(
'dn.loan', string='Loan', required=True, ondelete='cascade', index=True,
)
company_id = fields.Many2one(related='loan_id.company_id', store=True, index=True)
currency_id = fields.Many2one(related='loan_id.currency_id')
loan_state = fields.Selection(related='loan_id.state', store=True)
loan_name = fields.Char(related='loan_id.name', store=True)
date = fields.Date(string='Date', required=True)
principal = fields.Monetary(string='Principal')
interest = fields.Monetary(string='Interest')
payment = fields.Monetary(
string='Payment', compute='_compute_payment', store=True,
# Stored so the pivot view can sum it.
)
outstanding_balance = fields.Monetary(
string='Outstanding Balance', compute='_compute_outstanding_balance',
help="Principal still owed once this installment has been paid.",
)
long_term_theoretical_balance = fields.Monetary(
string='Long-Term', compute='_compute_theoretical_balances', store=True,
help="Principal still owed more than twelve months after this date. "
"Stored so a pivot can sum it.",
)
short_term_theoretical_balance = fields.Monetary(
string='Short-Term', compute='_compute_theoretical_balances', store=True,
help="Principal due within twelve months after this date.",
)
move_ids = fields.One2many(
'account.move', 'dn_loan_line_id', string='Generated Entries',
readonly=True, copy=False,
help="Entries generated from this installment.",
)
is_payment_move_posted = fields.Boolean(
compute='_compute_is_payment_move_posted',
help="Whether the payment entry for this installment is in the ledger.",
)
# -- computes --------------------------------------------------------
@api.depends('principal', 'interest')
def _compute_payment(self):
for line in self:
line.payment = line.principal + line.interest
@api.depends('loan_id.amount_borrowed', 'loan_id.line_ids.principal',
'loan_id.line_ids.date', 'date', 'principal')
def _compute_outstanding_balance(self):
"""Theoretical balance after paying this installment.
This is the schedule's own view of the balance, used in the schedule
table. The loan's `outstanding_balance` is the accounting one and can
legitimately differ while entries are still in draft.
"""
for line in self:
if not line.date:
line.outstanding_balance = line.loan_id.amount_borrowed
continue
repaid = sum(
other.principal for other in line.loan_id.line_ids
if other.date and other.date <= line.date
)
line.outstanding_balance = line.loan_id.amount_borrowed - repaid
@api.depends('date', 'loan_id.line_ids.date', 'loan_id.line_ids.principal')
def _compute_theoretical_balances(self):
"""Split the remaining principal into the part due within a year.
This is what the reclassification entry books, shown next to each row
so the amounts can be checked before anything is posted.
"""
for line in self:
if not line.date:
line.long_term_theoretical_balance = 0.0
line.short_term_theoretical_balance = 0.0
continue
later = line.loan_id.line_ids.filtered(
lambda other: other.date and other.date > line.date
).sorted(lambda other: (other.date, other.id))
line.short_term_theoretical_balance = sum(
later[:12].mapped('principal'))
line.long_term_theoretical_balance = sum(
later[12:].mapped('principal'))
@api.depends('date', 'loan_id.line_ids.date')
def _compute_sequence(self):
for line in self.sorted(lambda l: (l.date or fields.Date.today(), l.id)):
if not line.date:
line.sequence = 0
continue
line.sequence = len(line.loan_id.line_ids.filtered(
lambda other: other.date and other.date <= line.date
))
@api.depends('move_ids.state', 'move_ids.is_loan_payment_move',
'move_ids.reversal_move_ids')
def _compute_is_payment_move_posted(self):
for line in self:
payments = line.move_ids.filtered(lambda m: m.is_loan_payment_move)
# When the audit trail is enabled a loan can be cancelled and
# confirmed again, which leaves several payment entries. The one
# that still stands is the one without a reversal.
if len(payments) > 1 and any(m.reversal_move_ids for m in payments):
payments = payments.filtered(lambda m: not m.reversal_move_ids)
line.is_payment_move_posted = any(m.state == 'posted' for m in payments)
# -- constrains ------------------------------------------------------
@api.constrains('principal', 'interest')
def _check_positive_amounts(self):
for line in self:
if line.principal < 0 or line.interest < 0:
from odoo.exceptions import ValidationError
raise ValidationError(_(
"An installment cannot have a negative principal or a "
"negative interest."))

View File

@@ -0,0 +1,56 @@
from odoo import _, fields, models
class AccountMove(models.Model):
_inherit = 'account.move'
dn_loan_line_id = fields.Many2one(
'dn.loan.line', string='Loan Installment',
help="Installment of the loan that generated this entry.",
copy=False, readonly=True, index=True, ondelete='cascade',
)
dn_loan_id = fields.Many2one(
related='dn_loan_line_id.loan_id', string='Loan', store=True, index=True,
)
is_loan_payment_move = fields.Boolean(
string='Is Loan Payment',
help="True for the entry that pays an installment, false for the "
"reclassification and its reversal.",
)
def _post(self, soft=True):
"""Close the loan once its last installment has been posted.
Checking here rather than on the installment keeps the state correct no
matter where the posting comes from: the confirm action, a manual post,
or the scheduler honouring `auto_post`.
"""
posted = super()._post(soft=soft)
loans = self.env['dn.loan']
for move in self:
loan = move.dn_loan_id
if not loan or loan.state != 'running':
continue
skip = loan.skip_until_date
if all(
line.is_payment_move_posted
or (skip and line.date < skip)
for line in loan.line_ids
):
loans |= loan
if loans:
loans.write({'state': 'closed'})
for loan in loans:
loan.message_post(body=_(
"All installments are posted, the loan is now closed."))
return posted
def action_open_dn_loan(self):
self.ensure_one()
return {
'type': 'ir.actions.act_window',
'name': _("Loan"),
'views': [(False, 'form')],
'res_model': 'dn.loan',
'res_id': self.dn_loan_id.id,
}

View File

@@ -0,0 +1,431 @@
# -*- coding: utf-8 -*-
"""
DN Financial Report Engine — original implementation for Odoo 20 Community.
Design (written from scratch, inspired by the generic "report as data" pattern):
A report is pure DATA: a tree of lines, each line owning expressions.
An expression is one calculation unit with an "engine" and a "formula":
domain Python domain on account.move.line -> SUM(balance)
account_codes Comma separated account-code prefixes -> SUM(balance)
aggregation Arithmetic over other expression labels, e.g. "CA + RE"
text A literal label
The engine evaluates every expression once per "column group" (a period),
then assembles the line tree. Rendering is delegated to a client action so
the same payload can later be drawn as HTML / PDF / XLSX.
Only depends on the LGPL-3 community `account` module.
Odoo 20 notes (these differ from 17/18 and are the reason for several choices):
* `read_group()` returns *tuples* and takes `aggregates=` (not list-of-dicts).
`_read_group()` is the modern entry point and is used here.
* Backend view tag is `<list>`, `<tree>` no longer exists.
* `_sql_constraints` is deprecated -> `models.Constraint(...)`.
* QWeb uses `t-out` (`t-esc` is legacy).
"""
import ast
import logging
import re
from odoo import _, api, fields, models
from odoo.exceptions import UserError
_logger = logging.getLogger(__name__)
# Aggregation formulas are arithmetic only; keep the sandbox deliberately tiny.
_SAFE_GLOBALS = {"__builtins__": {}, "abs": abs, "round": round, "max": max, "min": min}
_TOKEN_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
_SIGNED_NUMBER_RE = re.compile(r"^\s*-\s*\d")
def _eval_aggregation(formula, variables):
"""Evaluate an arithmetic formula (e.g. ``CA + RE``) over `variables`."""
try:
return eval(formula, _SAFE_GLOBALS, dict(variables)) # noqa: S307 - sandboxed
except Exception as exc: # noqa: BLE001 - turn into a readable report error
raise UserError(
_("Invalid aggregation formula '%(f)s': %(e)s", f=formula, e=exc)
) from exc
class DnReport(models.Model):
_name = "dn.report"
_description = "DN Financial Report"
_order = "sequence, id"
name = fields.Char(required=True, translate=True)
code = fields.Char(required=True, help="Unique technical code of the report.")
sequence = fields.Integer(default=10)
active = fields.Boolean(default=True)
description = fields.Text(translate=True)
line_ids = fields.One2many("dn.report.line", "report_id", string="Lines")
column_ids = fields.One2many("dn.report.column", "report_id", string="Columns")
group_by_account = fields.Boolean(
default=False, help="Generate one dynamic line per account (for ledgers)."
)
_code_uniq = models.Constraint("unique(code)", "Report code must be unique.")
# ------------------------------------------------------------------
# Public entry point (client action / controller)
# ------------------------------------------------------------------
def get_report_data(self, options=None):
"""Return ``{columns, headers, lines}`` ready for rendering.
:param options: dict with date_from, date_to, company_ids,
column_groups, unfold_all
"""
self.ensure_one()
options = self._normalize_options(options or {})
groups = self._column_groups(options)
columns = [
{
"key": "c%d" % idx,
"label": g["label"],
"date_from": g.get("date_from"),
"date_to": g.get("date_to"),
}
for idx, g in enumerate(groups)
]
return {
"report_id": self.id,
"name": self.name,
"code": self.code,
"columns": columns,
"headers": [c["label"] for c in columns],
"lines": self._compute_lines(options, groups),
}
# ------------------------------------------------------------------
# Options & columns
# ------------------------------------------------------------------
def _normalize_options(self, options):
options = dict(options or {})
if not options.get("company_ids"):
options["company_ids"] = self.env.company.ids
return options
def _column_groups(self, options):
groups = options.get("column_groups")
if groups:
normalized = []
for idx, g in enumerate(groups):
normalized.append(
{
"label": g.get("label") or _("Period %s", idx + 1),
"date_from": g.get("date_from"),
"date_to": g.get("date_to"),
}
)
return normalized
return [
{
"label": options.get("column_label") or _("Amount of the period"),
"date_from": options.get("date_from"),
"date_to": options.get("date_to"),
}
]
# ------------------------------------------------------------------
# Calculation
# ------------------------------------------------------------------
def _compute_lines(self, options, column_groups):
expressions = self.line_ids.expression_ids
values_per_column = {}
for idx, group in enumerate(column_groups):
values_per_column["c%d" % idx] = self._compute_expressions(
options, group, expressions
)
account_breakdown = None
if self.group_by_account:
account_breakdown = [
self._account_breakdown(options, group) for group in column_groups
]
result = []
for line in self.line_ids.filtered(lambda l: not l.parent_id).sorted("sequence"):
result.append(
self._serialize_line(line, values_per_column, level=0,
account_breakdown=account_breakdown)
)
return result
def _serialize_line(self, line, values_per_column, level, account_breakdown=None):
children = [
self._serialize_line(child, values_per_column, level + 1)
for child in line.children_ids.sorted("sequence")
]
# Leaf ledger lines can be drilled down to one row per account.
if not children and account_breakdown and not line.is_total:
children = self._account_children(line, account_breakdown, level + 1)
row = {
"id": line.id,
"code": line.code or "",
"name": line.name,
"level": level,
"is_total": line.is_total,
"foldable": bool(children),
"values": {
key: self._line_value(line, expr_values)
for key, expr_values in values_per_column.items()
},
"children": children,
}
return row
# ------------------------------------------------------------------
# Optional drill-down: one child row per account
# ------------------------------------------------------------------
def _account_breakdown(self, options, group):
"""Return {account_id: {code, name, balance}} for the period."""
domain = self._base_domain(options, group)
rows = self.env["account.move.line"].sudo()._read_group(
domain,
groupby=["account_id"],
aggregates=["balance:sum"],
)
breakdown = {}
for account, balance in rows:
if not account:
continue
breakdown[account.id] = {
"code": account.code or "",
"name": account.name or "",
"balance": float(balance or 0.0),
}
return breakdown
def _account_children(self, line, account_breakdown, level):
"""Build one child row per account matching the line's expressions."""
matching = self._matching_account_ids(line, account_breakdown)
if not matching:
return []
children = []
for col_idx, breakdown in enumerate(account_breakdown):
for account_id in matching:
if account_id not in breakdown:
continue
info = breakdown[account_id]
children.append(
{
"id": "acc-%s-%s" % (line.id, account_id),
"code": info["code"],
"name": info["name"],
"level": level,
"is_total": False,
"foldable": False,
"values": {"c%d" % col_idx: info["balance"]},
"children": [],
}
)
# Merge rows coming from several periods into a single row per account.
merged = {}
for child in children:
existing = merged.setdefault(
child["id"],
dict(child, values={}, level=level, foldable=False, children=[]),
)
existing["values"].update(child["values"])
return sorted(merged.values(), key=lambda c: (c["code"] or "", c["name"] or ""))
def _matching_account_ids(self, line, account_breakdown):
"""Accounts whose journal items satisfy at least one expression.
The discovery query runs on ``account.move.line`` (the expressions are
written for that model), then the resulting accounts are intersected
with the accounts that actually have a balance in the period.
"""
ids = set()
ledger_exprs = line.expression_ids.filtered(
lambda e: e.engine in ("domain", "account_codes")
)
if not ledger_exprs:
return ids
for expr in ledger_exprs:
try:
if expr.engine == "domain":
domain = self._parse_domain(expr.formula)
else:
domain = self._account_code_domain(expr.formula)
except UserError:
continue
rows = self.env["account.move.line"].sudo()._read_group(
domain, groupby=["account_id"]
)
ids.update(account.id for account, in rows if account)
if account_breakdown:
ids &= set(account_breakdown[0])
return ids
def _line_value(self, line, expr_values):
"""An explicit aggregation wins, otherwise the line's own sum."""
aggregation = line.expression_ids.filtered(lambda e: e.engine == "aggregation")
for expr in aggregation:
if expr.id in expr_values:
return expr_values[expr.id]["value"]
for expr in line.expression_ids:
if expr.id in expr_values:
return expr_values[expr.id]["value"]
return 0.0
def _compute_expressions(self, options, group, expressions):
"""Evaluate every expression of the report for one column group."""
values = {}
# 1) Ledger engines
for expr in expressions.filtered(lambda e: e.engine in ("domain", "account_codes")):
values[expr.id] = {
"value": self._run_balance_engine(expr, options, group),
"is_text": False,
}
# 2) Text engine
for expr in expressions.filtered(lambda e: e.engine == "text"):
values[expr.id] = {"value": expr.formula or "", "is_text": True}
# 3) Aggregation — a formula may reference a label produced by another
# aggregation, so keep looping until a round resolves nothing.
pending = expressions.filtered(lambda e: e.engine == "aggregation")
for _round in range(len(pending) + 1):
if not pending:
break
resolved = self.env["dn.report.expression"]
label_map = self._label_value_map(expressions, values)
for expr in pending:
try:
computed = _eval_aggregation(expr.formula, label_map)
except UserError:
# Probably a label that is not computed yet: retry next round.
continue
values[expr.id] = {"value": computed, "is_text": False}
resolved |= expr
if expr.label:
label_map[expr.label] = computed
pending -= resolved
if not resolved:
_logger.warning(
"DN report %s: unresolved aggregation formulas %s",
self.code,
pending.mapped("label"),
)
break
return values
@staticmethod
def _label_value_map(expressions, values):
"""Map expression label -> numeric value for aggregation formulas."""
label_map = {}
for expr in expressions:
payload = values.get(expr.id)
if not payload or payload["is_text"] or not expr.label:
continue
label_map[expr.label] = label_map.get(expr.label, 0.0) + payload["value"]
return label_map
# ------------------------------------------------------------------
# Ledger engine — the only place that reads account.move.line
# ------------------------------------------------------------------
def _run_balance_engine(self, expr, options, group):
domain = self._base_domain(options, group)
if expr.engine == "domain":
domain = domain + self._parse_domain(expr.formula)
else: # account_codes
domain = domain + self._account_code_domain(expr.formula)
if not domain:
return 0.0
rows = self.env["account.move.line"].sudo()._read_group(
domain, aggregates=["balance:sum"]
)
# With no groupby, _read_group returns a single (sum,) row; an empty
# recordset yields (None,) or (0,).
return float(rows[0][0] or 0.0) if rows else 0.0
def _base_domain(self, options, group):
domain = [("parent_state", "=", "posted")]
company_ids = options.get("company_ids") or self.env.company.ids
domain.append(("company_id", "in", company_ids))
date_from = group.get("date_from") or options.get("date_from")
date_to = group.get("date_to") or options.get("date_to")
if date_from:
domain.append(("date", ">=", date_from))
if date_to:
domain.append(("date", "<=", date_to))
return domain
@staticmethod
def _account_code_domain(formula):
"""Build an OR-ed prefix domain: ``"60,62"`` -> 60* or 62*."""
prefixes = [p.strip() for p in (formula or "").split(",") if p.strip()]
if not prefixes:
return []
domain = []
for prefix in prefixes[:-1]:
domain += ["|", ("account_id.code", "=like", prefix + "%")]
domain.append(("account_id.code", "=like", prefixes[-1] + "%"))
return domain
@staticmethod
def _parse_domain(formula):
try:
parsed = ast.literal_eval((formula or "").strip())
except (ValueError, SyntaxError) as exc:
raise UserError(_("Invalid domain formula: %s", formula)) from exc
if not isinstance(parsed, (list, tuple)):
raise UserError(_("Domain formula must be a list: %s", formula))
return list(parsed)
class DnReportLine(models.Model):
_name = "dn.report.line"
_description = "DN Report Line"
_order = "sequence, id"
report_id = fields.Many2one("dn.report", required=True, ondelete="cascade")
parent_id = fields.Many2one("dn.report.line", ondelete="cascade")
children_ids = fields.One2many("dn.report.line", "parent_id")
name = fields.Char(required=True, translate=True)
code = fields.Char(help="Line code, unique within a report.")
sequence = fields.Integer(default=10)
is_total = fields.Boolean(default=False)
expression_ids = fields.One2many("dn.report.expression", "report_line_id")
class DnReportExpression(models.Model):
_name = "dn.report.expression"
_description = "DN Report Expression (calculation unit)"
_order = "sequence, id"
report_line_id = fields.Many2one("dn.report.line", required=True, ondelete="cascade")
label = fields.Char(help="Name used by aggregation formulas.")
formula = fields.Text(required=True)
engine = fields.Selection(
[
("domain", "Domain on Journal Items"),
("account_codes", "Account Code Prefixes"),
("aggregation", "Aggregation"),
("text", "Text"),
],
default="domain",
required=True,
)
sequence = fields.Integer(default=10)
figure_type = fields.Selection(
[("monetary", "Monetary"), ("integer", "Integer"), ("text", "Text")],
default="monetary",
)
class DnReportColumn(models.Model):
_name = "dn.report.column"
_description = "DN Report Column"
_order = "sequence, id"
report_id = fields.Many2one("dn.report", required=True, ondelete="cascade")
name = fields.Char(required=True, translate=True)
sequence = fields.Integer(default=10)