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,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()