Files
tryton/modules/account_invoice/payment_term.py
T

325 lines
12 KiB
Python
Raw Normal View History

2014-12-02 12:54:39 +01:00
# This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
from decimal import Decimal
2021-12-11 17:58:41 +01:00
from dateutil.relativedelta import relativedelta
2018-12-29 14:20:28 +01:00
from trytond.i18n import gettext
2018-03-26 14:09:12 +02:00
from trytond.model import (
Check, DeactivableMixin, ModelSQL, ModelView, fields, sequence_ordered)
2021-12-11 17:58:41 +01:00
from trytond.modules.currency.fields import Monetary
from trytond.pool import Pool
from trytond.pyson import Eval, If
2010-08-19 22:02:49 +02:00
from trytond.transaction import Transaction
2021-12-11 17:58:41 +01:00
from trytond.wizard import Button, StateView, Wizard
2009-01-02 17:54:34 +01:00
2021-12-11 17:58:41 +01:00
from .exceptions import PaymentTermComputeError, PaymentTermValidationError
2018-12-29 14:20:28 +01:00
2009-01-02 17:54:34 +01:00
2018-03-26 14:09:12 +02:00
class PaymentTerm(DeactivableMixin, ModelSQL, ModelView):
2012-09-24 22:17:32 +02:00
__name__ = 'account.invoice.payment_term'
name = fields.Char('Name', size=None, required=True, translate=True)
2009-01-02 17:54:34 +01:00
description = fields.Text('Description', translate=True)
lines = fields.One2Many('account.invoice.payment_term.line', 'payment',
'Lines')
2012-09-24 22:17:32 +02:00
@classmethod
def __setup__(cls):
2025-04-04 00:45:18 +02:00
super().__setup__()
2012-09-24 22:17:32 +02:00
cls._order.insert(0, ('name', 'ASC'))
2009-01-02 17:54:34 +01:00
@classmethod
2022-04-11 23:24:20 +02:00
def validate_fields(cls, terms, field_names):
super().validate_fields(terms, field_names)
cls.check_remainder(terms, field_names)
2022-04-11 23:24:20 +02:00
@classmethod
def check_remainder(cls, terms, field_names=None):
2025-02-10 01:33:51 +01:00
if Transaction().user == 0:
return
2022-04-11 23:24:20 +02:00
if field_names and 'lines' not in field_names:
return
for term in terms:
if not term.lines or not term.lines[-1].type == 'remainder':
raise PaymentTermValidationError(gettext(
'account_invoice'
'.msg_payment_term_missing_last_remainder',
payment_term=term.rec_name))
def compute(self, amount, currency, date):
"""Calculate payment terms and return a list of tuples
with (date, amount) for each payment term line.
2012-04-01 18:22:06 +02:00
2012-09-24 22:17:32 +02:00
amount must be a Decimal used for the calculation.
"""
2014-12-02 12:54:39 +01:00
# TODO implement business_days
2009-01-02 17:54:34 +01:00
# http://pypi.python.org/pypi/BusinessHours/
sign = 1 if amount >= Decimal(0) else -1
2009-01-02 17:54:34 +01:00
res = []
remainder = amount
2012-09-24 22:17:32 +02:00
for line in self.lines:
value = line.get_value(remainder, amount, currency)
value_date = line.get_date(date)
2016-05-25 12:59:48 +02:00
if value is None or not value_date:
2020-03-01 12:33:51 +01:00
continue
if ((remainder - value) * sign) < Decimal(0):
res.append((value_date, remainder))
break
2016-05-25 12:59:48 +02:00
if value:
res.append((value_date, value))
2009-01-02 17:54:34 +01:00
remainder -= value
2016-05-25 12:59:48 +02:00
else:
# Enforce to have at least one term
if not res:
res.append((date, Decimal(0)))
2012-09-24 22:17:32 +02:00
if not currency.is_zero(remainder):
2018-12-29 14:20:28 +01:00
raise PaymentTermComputeError(
gettext('account_invoice.msg_payment_term_missing_remainder',
payment_term=self.rec_name))
2009-01-02 17:54:34 +01:00
return res
2016-09-13 14:03:55 +02:00
class PaymentTermLine(sequence_ordered(), ModelSQL, ModelView):
2012-09-24 22:17:32 +02:00
__name__ = 'account.invoice.payment_term.line'
2009-01-02 17:54:34 +01:00
payment = fields.Many2One('account.invoice.payment_term', 'Payment Term',
required=True, ondelete="CASCADE")
type = fields.Selection([
('fixed', 'Fixed'),
('percent', 'Percentage on Remainder'),
('percent_on_total', 'Percentage on Total'),
('remainder', 'Remainder'),
2014-01-26 14:28:52 +01:00
], 'Type', required=True)
2016-02-03 21:26:47 +01:00
ratio = fields.Numeric('Ratio', digits=(14, 10),
domain=[
If(Eval('type').in_(['percent', 'percent_on_total'])
& ~Eval('divisor', 0),
('ratio', '!=', 0),
()),
],
2011-08-04 16:57:16 +02:00
states={
'invisible': ~Eval('type').in_(['percent', 'percent_on_total']),
'required': Eval('type').in_(['percent', 'percent_on_total']),
})
2016-02-03 21:26:47 +01:00
divisor = fields.Numeric('Divisor', digits=(10, 14),
states={
'invisible': ~Eval('type').in_(['percent', 'percent_on_total']),
'required': Eval('type').in_(['percent', 'percent_on_total']),
})
2021-08-21 09:09:55 +02:00
amount = Monetary(
"Amount", currency='currency', digits='currency',
2011-08-04 16:57:16 +02:00
states={
2011-08-21 11:20:30 +02:00
'invisible': Eval('type') != 'fixed',
'required': Eval('type') == 'fixed',
})
2009-01-02 17:54:34 +01:00
currency = fields.Many2One('currency.currency', 'Currency',
2011-08-04 16:57:16 +02:00
states={
2011-08-21 11:20:30 +02:00
'invisible': Eval('type') != 'fixed',
'required': Eval('type') == 'fixed',
})
relativedeltas = fields.One2Many(
'account.invoice.payment_term.line.delta', 'line', 'Deltas')
2009-01-02 17:54:34 +01:00
2021-03-07 11:13:53 +01:00
@classmethod
def __setup__(cls):
super().__setup__()
t = cls.__table__()
cls._sql_constraints += [
('non_zero_ratio_divisor',
Check(t,
(t.ratio != 0) | (t.divisor != 0)
| ~t.type.in_(['percent', 'percent_on_total'])),
'account_invoice.msg_payment_term_non_zero_ratio_divisor'),
]
2021-03-07 11:13:53 +01:00
cls.__access__.add('payment')
2012-09-24 22:17:32 +02:00
@staticmethod
def default_type():
return 'remainder'
2009-01-02 17:54:34 +01:00
@classmethod
def default_relativedeltas(cls):
if Transaction().user == 0:
return []
return [{}]
2014-01-26 14:28:52 +01:00
@fields.depends('type')
2012-09-24 22:17:32 +02:00
def on_change_type(self):
if self.type != 'fixed':
self.amount = Decimal(0)
2014-10-29 20:39:13 +01:00
self.currency = None
2012-09-24 22:17:32 +02:00
if self.type not in ('percent', 'percent_on_total'):
self.ratio = None
self.divisor = None
2009-01-02 17:54:34 +01:00
2016-02-03 21:26:47 +01:00
@fields.depends('ratio')
def on_change_ratio(self):
if not self.ratio:
self.divisor = self.ratio
2014-10-29 20:39:13 +01:00
else:
2016-02-03 21:26:47 +01:00
self.divisor = self.round(1 / self.ratio,
2014-10-29 20:39:13 +01:00
self.__class__.divisor.digits[1])
2014-01-26 14:28:52 +01:00
@fields.depends('divisor')
2012-09-24 22:17:32 +02:00
def on_change_divisor(self):
if not self.divisor:
self.ratio = self.divisor
2014-10-29 20:39:13 +01:00
else:
2016-02-03 21:26:47 +01:00
self.ratio = self.round(1 / self.divisor,
self.__class__.ratio.digits[1])
2012-09-24 22:17:32 +02:00
def get_date(self, date):
for relativedelta_ in self.relativedeltas:
date += relativedelta_.get()
return date
2012-09-24 22:17:32 +02:00
def get_value(self, remainder, amount, currency):
Currency = Pool().get('currency.currency')
if self.type == 'fixed':
fixed = Currency.compute(self.currency, self.amount, currency)
return fixed.copy_sign(amount)
2012-09-24 22:17:32 +02:00
elif self.type == 'percent':
2016-02-03 21:26:47 +01:00
return currency.round(remainder * self.ratio)
2012-09-24 22:17:32 +02:00
elif self.type == 'percent_on_total':
2016-02-03 21:26:47 +01:00
return currency.round(amount * self.ratio)
2012-09-24 22:17:32 +02:00
elif self.type == 'remainder':
return currency.round(remainder)
return None
@staticmethod
def round(number, digits):
quantize = Decimal(10) ** -Decimal(digits)
return Decimal(number).quantize(quantize)
@classmethod
2022-04-11 23:24:20 +02:00
def validate_fields(cls, lines, field_names):
super().validate_fields(lines, field_names)
cls.check_ratio_and_divisor(lines, field_names)
2012-09-24 22:17:32 +02:00
@classmethod
2022-04-11 23:24:20 +02:00
def check_ratio_and_divisor(cls, lines, field_names=None):
2016-02-03 21:26:47 +01:00
"Check consistency between ratio and divisor"
2022-04-11 23:24:20 +02:00
if field_names and not (field_names & {'type', 'ratio', 'divisor'}):
return
for line in lines:
if line.type not in ('percent', 'percent_on_total'):
continue
2016-02-03 21:26:47 +01:00
if line.ratio is None or line.divisor is None:
2018-12-29 14:20:28 +01:00
raise PaymentTermValidationError(
gettext('account_invoice'
'.msg_payment_term_invalid_ratio_divisor',
line=line.rec_name))
if (line.ratio != round(
1 / line.divisor, cls.ratio.digits[1])
and line.divisor != round(
1 / line.ratio, cls.divisor.digits[1])):
2018-12-29 14:20:28 +01:00
raise PaymentTermValidationError(
gettext('account_invoice'
'.msg_payment_term_invalid_ratio_divisor',
line=line.rec_name))
2015-03-02 23:21:06 +01:00
2016-09-13 14:03:55 +02:00
class PaymentTermLineRelativeDelta(sequence_ordered(), ModelSQL, ModelView):
__name__ = 'account.invoice.payment_term.line.delta'
line = fields.Many2One('account.invoice.payment_term.line',
'Payment Term Line', required=True, ondelete='CASCADE')
day = fields.Integer('Day of Month',
domain=['OR',
('day', '=', None),
[('day', '>=', 1), ('day', '<=', 31)],
])
2019-01-01 15:47:23 +01:00
month = fields.Many2One('ir.calendar.month', "Month")
weekday = fields.Many2One('ir.calendar.day', "Day of Week")
months = fields.Integer('Number of Months', required=True)
weeks = fields.Integer('Number of Weeks', required=True)
days = fields.Integer('Number of Days', required=True)
2021-03-07 11:13:53 +01:00
@classmethod
def __setup__(cls):
super().__setup__()
cls.__access__.add('line')
@staticmethod
def default_months():
return 0
@staticmethod
def default_weeks():
return 0
@staticmethod
def default_days():
return 0
def get(self):
"Return the relativedelta"
return relativedelta(
day=self.day,
2019-01-01 15:47:23 +01:00
month=int(self.month.index) if self.month else None,
days=self.days,
weeks=self.weeks,
months=self.months,
2019-01-01 15:47:23 +01:00
weekday=int(self.weekday.index) if self.weekday else None,
)
2015-03-02 23:21:06 +01:00
class TestPaymentTerm(Wizard):
__name__ = 'account.invoice.payment_term.test'
start_state = 'test'
test = StateView('account.invoice.payment_term.test',
'account_invoice.payment_term_test_view_form',
[Button('Close', 'end', 'tryton-close', default=True)])
def default_test(self, fields):
default = {}
if (self.model
and self.model.__name__ == 'account.invoice.payment_term'):
default['payment_term'] = self.record.id if self.record else None
2015-03-02 23:21:06 +01:00
return default
class TestPaymentTermView(ModelView):
__name__ = 'account.invoice.payment_term.test'
payment_term = fields.Many2One('account.invoice.payment_term',
'Payment Term', required=True)
2022-08-08 22:25:23 +02:00
date = fields.Date("Date", required=True)
2021-08-21 09:09:55 +02:00
amount = Monetary(
"Amount", currency='currency', digits='currency', required=True)
2015-03-02 23:21:06 +01:00
currency = fields.Many2One('currency.currency', 'Currency', required=True)
result = fields.One2Many('account.invoice.payment_term.test.result',
None, 'Result', readonly=True)
2022-08-08 22:25:23 +02:00
@classmethod
def default_date(cls):
return Pool().get('ir.date').today()
2015-03-02 23:21:06 +01:00
@staticmethod
def default_currency():
pool = Pool()
Company = pool.get('company.company')
company = Transaction().context.get('company')
if company is not None and company >= 0:
2015-03-02 23:21:06 +01:00
return Company(company).currency.id
@fields.depends('payment_term', 'date', 'amount', 'currency', 'result')
def on_change_with_result(self):
pool = Pool()
Result = pool.get('account.invoice.payment_term.test.result')
result = []
2022-08-08 22:25:23 +02:00
if (self.payment_term and self.amount and self.currency and self.date):
2015-03-02 23:21:06 +01:00
for date, amount in self.payment_term.compute(
self.amount, self.currency, self.date):
result.append(Result(
2020-10-09 19:09:05 +02:00
date=date,
amount=amount,
2021-08-21 09:09:55 +02:00
currency=self.currency))
return result
2015-03-02 23:21:06 +01:00
class TestPaymentTermViewResult(ModelView):
__name__ = 'account.invoice.payment_term.test.result'
date = fields.Date('Date', readonly=True)
2021-08-21 09:09:55 +02:00
amount = Monetary(
"Amount", currency='currency', digits='currency', readonly=True)
2020-10-09 19:09:05 +02:00
currency = fields.Many2One('currency.currency', "Currency")