195 lines
7.9 KiB
Python
195 lines
7.9 KiB
Python
from dateutil.relativedelta import relativedelta
|
|
|
|
from odoo import _, api, fields, models
|
|
from odoo.exceptions import ValidationError
|
|
|
|
from ..lib.amortization import Schedule
|
|
|
|
|
|
class DnLoanComputeWizard(models.TransientModel):
|
|
_name = 'dn.loan.compute.wizard'
|
|
_description = 'Loan Schedule Wizard'
|
|
|
|
loan_id = fields.Many2one('dn.loan', string='Loan', required=True,
|
|
ondelete='cascade')
|
|
currency_id = fields.Many2one(related='loan_id.currency_id')
|
|
company_id = fields.Many2one(related='loan_id.company_id')
|
|
|
|
loan_amount = fields.Monetary(string='Loan Amount', required=True)
|
|
interest_rate = fields.Float(
|
|
string='Annual Interest Rate', required=True, digits=(12, 6),
|
|
help="Percentage per year, for example 5 for 5%.",
|
|
)
|
|
loan_term = fields.Integer(
|
|
string='Installments', required=True, default=12,
|
|
help="Number of installments, not years.",
|
|
)
|
|
payments_per_year = fields.Selection(
|
|
selection=[('12', 'Monthly'), ('4', 'Quarterly'),
|
|
('2', 'Semi-annually'), ('1', 'Annually')],
|
|
string='Frequency', default='12', required=True,
|
|
)
|
|
method = fields.Selection(
|
|
selection=[('annuity', 'Annuity'), ('linear', 'Linear'),
|
|
('interest_only', 'Interest Only')],
|
|
string='Repayment Method', default='annuity', required=True,
|
|
)
|
|
start_date = fields.Date(
|
|
string='Start Date', required=True, default=fields.Date.context_today,
|
|
)
|
|
first_payment_date = fields.Date(
|
|
string='First Payment', required=True,
|
|
default=lambda self: fields.Date.context_today(self).replace(day=1)
|
|
+ relativedelta(months=1),
|
|
)
|
|
day_count = fields.Selection(
|
|
selection=[('30E/360', '30E/360'), ('A/360', 'A/360'),
|
|
('A/365F', 'A/365F')],
|
|
string='Day Count', default='30E/360', required=True,
|
|
help="How the interest of a period is prorated. 30E/360 treats every "
|
|
"month as thirty days, which is the usual convention for corporate "
|
|
"loans; the actual/actual variants follow the calendar.",
|
|
)
|
|
preview = fields.Text(string='Preview', compute='_compute_preview')
|
|
|
|
# -- validation -------------------------------------------------------
|
|
|
|
@api.constrains('loan_amount', 'interest_rate', 'loan_term', 'start_date',
|
|
'first_payment_date')
|
|
def _check_values(self):
|
|
for wizard in self:
|
|
if wizard.loan_amount <= 0:
|
|
raise ValidationError(_("The loan amount must be positive."))
|
|
if not 0 <= wizard.interest_rate <= 100:
|
|
raise ValidationError(_("The interest rate must be between 0 and 100."))
|
|
if wizard.loan_term <= 0:
|
|
raise ValidationError(_("The number of installments must be positive."))
|
|
if (wizard.first_payment_date and wizard.start_date
|
|
and wizard.first_payment_date <= wizard.start_date):
|
|
raise ValidationError(_(
|
|
"The first payment must come after the start date."))
|
|
|
|
@api.onchange('start_date')
|
|
def _onchange_start_date(self):
|
|
"""Keep the first payment one month after the start date."""
|
|
if self.start_date:
|
|
self.first_payment_date = self.start_date.replace(day=1) \
|
|
+ relativedelta(months=1)
|
|
|
|
# -- computation ------------------------------------------------------
|
|
|
|
def _get_schedule(self):
|
|
"""Build the engine for the current values.
|
|
|
|
Kept separate from the preview so the saved schedule and the previewed
|
|
one can never come from different code paths.
|
|
"""
|
|
self.ensure_one()
|
|
return Schedule(
|
|
amount=self.loan_amount,
|
|
annual_rate=self.interest_rate,
|
|
term=self.loan_term,
|
|
start_date=self.start_date,
|
|
first_payment_date=self.first_payment_date,
|
|
method=self.method,
|
|
payments_per_year=int(self.payments_per_year),
|
|
day_count=self.day_count,
|
|
)
|
|
|
|
@api.depends('loan_amount', 'interest_rate', 'loan_term', 'start_date',
|
|
'first_payment_date', 'method', 'payments_per_year', 'day_count')
|
|
def _compute_preview(self):
|
|
"""Show the first and last five installments plus the totals.
|
|
|
|
A full sixty-row schedule would not fit in a wizard and could not be
|
|
read anyway. What matters before saving is whether the first payments
|
|
and the final balance look right.
|
|
"""
|
|
for wizard in self:
|
|
if not (wizard.loan_amount and wizard.loan_term and wizard.start_date):
|
|
wizard.preview = ''
|
|
continue
|
|
try:
|
|
rows = wizard._get_schedule().installments()
|
|
except ValueError as error:
|
|
wizard.preview = str(error)
|
|
continue
|
|
|
|
# `%Ns` right-aligns strings in Python's %-formatting, which is what
|
|
# the currency columns need; `%-Ns` left-aligns the date column.
|
|
header = "%-12s%15s%15s%15s%15s" % (
|
|
_("Date"), _("Principal"), _("Interest"), _("Payment"),
|
|
_("Balance"))
|
|
body = [header]
|
|
|
|
def money(amount):
|
|
"""`res.currency.format()` adds 0.0 to its argument, so it only
|
|
accepts floats while the engine works with Decimals."""
|
|
return wizard.currency_id.format(float(amount))
|
|
|
|
def row(installment):
|
|
return "%-12s%15s%15s%15s%15s" % (
|
|
installment.date.strftime('%Y-%m-%d'),
|
|
money(installment.principal),
|
|
money(installment.interest),
|
|
money(installment.payment),
|
|
money(installment.balance),
|
|
)
|
|
|
|
for installment in rows[:5]:
|
|
body.append(row(installment))
|
|
if len(rows) > 10:
|
|
body.append("%-12s%15s%15s%15s%15s" % (
|
|
'...', '...', '...', '...', '...'))
|
|
if len(rows) > 5:
|
|
for installment in rows[-5:]:
|
|
body.append(row(installment))
|
|
|
|
principal = sum(r.principal for r in rows)
|
|
interest = sum(r.interest for r in rows)
|
|
body.append('')
|
|
body.append(_("Installments: %(count)s", count=len(rows)))
|
|
body.append(_("Total principal: %(amount)s",
|
|
amount=money(principal)))
|
|
body.append(_("Total interest: %(amount)s",
|
|
amount=money(interest)))
|
|
wizard.preview = "\n".join(body)
|
|
|
|
# -- actions ----------------------------------------------------------
|
|
|
|
def action_save(self):
|
|
"""Replace the loan's schedule with the computed one."""
|
|
self.ensure_one()
|
|
rows = self._get_schedule().installments()
|
|
|
|
self.loan_id.line_ids.unlink()
|
|
self.env['dn.loan.line'].create([{
|
|
'loan_id': self.loan_id.id,
|
|
'date': installment.date,
|
|
'principal': float(installment.principal),
|
|
'interest': float(installment.interest),
|
|
} for installment in rows])
|
|
|
|
self.loan_id.write({
|
|
'date': self.start_date,
|
|
'amount_borrowed': self.loan_amount,
|
|
'interest': sum(r.interest for r in rows),
|
|
'duration': len(rows),
|
|
'method': self.method,
|
|
})
|
|
self.loan_id.message_post(body=_(
|
|
"Amortization schedule computed: %(count)s installments, "
|
|
"%(interest)s of total interest.",
|
|
count=len(rows),
|
|
interest=self.currency_id.format(float(sum(r.interest for r in rows))),
|
|
))
|
|
|
|
return {
|
|
'name': self.loan_id.display_name,
|
|
'res_id': self.loan_id.id,
|
|
'type': 'ir.actions.act_window',
|
|
'res_model': 'dn.loan',
|
|
'target': 'current',
|
|
'views': [[False, 'form']],
|
|
}
|