Files
tryton/modules/account/period.py
T

339 lines
13 KiB
Python
Raw Normal View History

2014-12-02 12:54:29 +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.
2018-12-29 14:20:28 +01:00
from trytond.i18n import gettext
from trytond.model import ModelView, ModelSQL, Workflow, fields
2018-12-29 14:20:28 +01:00
from trytond.model.exceptions import AccessError
2021-03-11 23:00:09 +01:00
from trytond.pyson import Eval, Id
2010-08-19 22:02:00 +02:00
from trytond.transaction import Transaction
2011-07-03 13:18:40 +02:00
from trytond.pool import Pool
2012-09-24 22:17:29 +02:00
from trytond.const import OPERATORS
2018-12-29 14:20:28 +01:00
from .exceptions import (PeriodNotFoundError, ClosePeriodError,
PeriodDatesError, PeriodSequenceError)
2008-03-17 18:32:06 +01:00
_STATES = {
'readonly': Eval('state') != 'open',
2008-03-13 23:22:59 +01:00
}
2011-08-04 16:57:14 +02:00
_DEPENDS = ['state']
2008-03-13 23:22:59 +01:00
class Period(Workflow, ModelSQL, ModelView):
2008-03-13 23:22:59 +01:00
'Period'
2012-09-24 22:17:29 +02:00
__name__ = 'account.period'
2008-09-16 19:43:07 +02:00
name = fields.Char('Name', required=True)
start_date = fields.Date('Starting Date', required=True, states=_STATES,
domain=[('start_date', '<=', Eval('end_date', None))],
depends=_DEPENDS + ['end_date'], select=True)
2008-09-16 19:43:07 +02:00
end_date = fields.Date('Ending Date', required=True, states=_STATES,
domain=[('end_date', '>=', Eval('start_date', None))],
depends=_DEPENDS + ['start_date'], select=True)
2008-03-13 23:22:59 +01:00
fiscalyear = fields.Many2One('account.fiscalyear', 'Fiscal Year',
2012-03-05 10:52:56 +01:00
required=True, states=_STATES, depends=_DEPENDS, select=True)
2008-03-13 23:22:59 +01:00
state = fields.Selection([
('open', 'Open'),
('close', 'Close'),
('locked', 'Locked'),
], 'State', readonly=True, required=True)
2012-04-03 20:06:15 +02:00
post_move_sequence = fields.Many2One('ir.sequence', 'Post Move Sequence',
2014-12-03 16:13:08 +01:00
domain=[
2021-03-11 23:00:09 +01:00
('sequence_type', '=',
Id('account', 'sequence_type_account_move')),
2014-12-03 16:13:08 +01:00
['OR',
('company', '=', None),
('company', '=', Eval('company', -1)),
],
],
depends=['company'])
2008-09-16 19:43:07 +02:00
type = fields.Selection([
2011-08-04 16:57:14 +02:00
('standard', 'Standard'),
('adjustment', 'Adjustment'),
], 'Type', required=True,
2012-03-05 10:52:56 +01:00
states=_STATES, depends=_DEPENDS, select=True)
company = fields.Function(fields.Many2One('company.company', 'Company',),
2014-12-03 16:13:08 +01:00
'on_change_with_company', searcher='search_company')
icon = fields.Function(fields.Char("Icon"), 'get_icon')
2008-03-13 23:22:59 +01:00
2012-09-24 22:17:29 +02:00
@classmethod
def __setup__(cls):
super(Period, cls).__setup__()
2021-03-07 11:13:53 +01:00
cls.__access__.add('fiscalyear')
2012-09-24 22:17:29 +02:00
cls._order.insert(0, ('start_date', 'ASC'))
cls._transitions |= set((
('open', 'close'),
('close', 'locked'),
('close', 'open'),
))
cls._buttons.update({
'close': {
'invisible': Eval('state') != 'open',
2018-02-19 11:36:13 +01:00
'depends': ['state'],
},
'reopen': {
'invisible': Eval('state') != 'close',
2018-02-19 11:36:13 +01:00
'depends': ['state'],
},
'lock': {
'invisible': Eval('state') != 'close',
2018-02-19 11:36:13 +01:00
'depends': ['state'],
},
})
2012-09-24 22:17:29 +02:00
@staticmethod
def default_state():
2008-03-13 23:22:59 +01:00
return 'open'
2012-09-24 22:17:29 +02:00
@staticmethod
def default_type():
2008-09-16 19:43:07 +02:00
return 'standard'
2019-10-16 21:17:39 +02:00
@fields.depends('fiscalyear', '_parent_fiscalyear.company')
2014-12-03 16:13:08 +01:00
def on_change_with_company(self, name=None):
if self.fiscalyear:
return self.fiscalyear.company.id
2012-09-24 22:17:29 +02:00
@classmethod
def search_company(cls, name, clause):
2017-09-27 18:37:24 +02:00
return [('fiscalyear.' + clause[0],) + tuple(clause[1:])]
def get_icon(self, name):
return {
'open': 'tryton-account-open',
'close': 'tryton-account-close',
'locked': 'tryton-account-block',
}.get(self.state)
@classmethod
def validate(cls, periods):
super(Period, cls).validate(periods)
for period in periods:
period.check_dates()
period.check_fiscalyear_dates()
period.check_post_move_sequence()
2012-09-24 22:17:29 +02:00
def check_dates(self):
if self.type != 'standard':
return True
2016-07-07 10:06:50 +02:00
transaction = Transaction()
connection = transaction.connection
transaction.database.lock(connection, self._table)
2013-09-06 22:33:47 +02:00
table = self.__table__()
2016-07-07 10:06:50 +02:00
cursor = connection.cursor()
2013-09-06 22:33:47 +02:00
cursor.execute(*table.select(table.id,
where=(((table.start_date <= self.start_date)
& (table.end_date >= self.start_date))
| ((table.start_date <= self.end_date)
& (table.end_date >= self.end_date))
| ((table.start_date >= self.start_date)
& (table.end_date <= self.end_date)))
& (table.fiscalyear == self.fiscalyear.id)
& (table.type == 'standard')
& (table.id != self.id)))
period_id = cursor.fetchone()
if period_id:
overlapping_period = self.__class__(period_id[0])
2018-12-29 14:20:28 +01:00
raise PeriodDatesError(
gettext('account.msg_period_overlap',
first=self.rec_name,
second=overlapping_period.rec_name))
2012-09-24 22:17:29 +02:00
def check_fiscalyear_dates(self):
if (self.start_date < self.fiscalyear.start_date
or self.end_date > self.fiscalyear.end_date):
2018-12-29 14:20:28 +01:00
raise PeriodDatesError(
gettext('account.msg_period_fiscalyear_dates',
period=self.rec_name,
fiscalyear=self.fiscalyear.rec_name))
2012-09-24 22:17:29 +02:00
def check_post_move_sequence(self):
2013-01-22 16:14:24 +01:00
if not self.post_move_sequence:
return
periods = self.search([
('post_move_sequence', '=', self.post_move_sequence.id),
('fiscalyear', '!=', self.fiscalyear.id),
])
if periods:
2018-12-29 14:20:28 +01:00
raise PeriodSequenceError(
gettext('account.msg_period_same_sequence',
first=self.rec_name,
second=periods[0].rec_name))
2012-09-24 22:17:29 +02:00
@classmethod
def find(cls, company_id, date=None, exception=True, test_state=True):
2008-03-13 23:22:59 +01:00
'''
Return the period for the company_id
at the date or the current date.
2008-03-13 23:22:59 +01:00
If exception is set the function will raise an exception
2012-06-16 14:26:05 +05:30
if no period is found.
2012-09-24 22:17:29 +02:00
If test_state is true, it will search on non-closed periods
2008-03-13 23:22:59 +01:00
'''
pool = Pool()
Date = pool.get('ir.date')
Lang = pool.get('ir.lang')
2008-10-08 12:17:47 +02:00
2008-03-13 23:22:59 +01:00
if not date:
2012-09-24 22:17:29 +02:00
date = Date.today()
clause = [
2008-03-13 23:22:59 +01:00
('start_date', '<=', date),
('end_date', '>=', date),
('fiscalyear.company', '=', company_id),
2008-09-16 19:43:07 +02:00
('type', '=', 'standard'),
]
if test_state:
clause.append(('state', '=', 'open'))
2012-09-24 22:17:29 +02:00
periods = cls.search(clause, order=[('start_date', 'DESC')], limit=1)
if not periods:
2008-03-13 23:22:59 +01:00
if exception:
2017-11-15 00:16:39 +01:00
lang = Lang.get()
2018-12-29 14:20:28 +01:00
raise PeriodNotFoundError(
gettext('account.msg_no_period_date',
date=lang.strftime(date)))
2008-03-13 23:22:59 +01:00
else:
2012-03-27 10:43:03 +02:00
return None
2012-09-24 22:17:29 +02:00
return periods[0].id
2008-03-13 23:22:59 +01:00
2012-09-24 22:17:29 +02:00
@classmethod
def _check(cls, periods):
Move = Pool().get('account.move')
moves = Move.search([
('period', 'in', [p.id for p in periods]),
], limit=1)
if moves:
2018-12-29 14:20:28 +01:00
raise AccessError(
gettext('account.msg_modify_delete_period_moves',
period=moves[0].period.rec_name))
2012-09-24 22:17:29 +02:00
@classmethod
def search(cls, args, offset=0, limit=None, order=None, count=False,
2013-09-06 22:33:47 +02:00
query=False):
args = args[:]
2012-04-03 20:06:15 +02:00
2008-09-04 18:24:33 +02:00
def process_args(args):
i = 0
while i < len(args):
# add test for xmlrpc and pyson that doesn't handle tuple
2020-03-01 12:33:50 +01:00
if ((
isinstance(args[i], tuple)
2013-02-16 18:54:35 +01:00
or (isinstance(args[i], list) and len(args[i]) > 2
and args[i][1] in OPERATORS))
and args[i][0] in ('start_date', 'end_date')
and isinstance(args[i][2], (list, tuple))):
if not args[i][2][0]:
args[i] = ('id', '!=', '0')
else:
2012-11-07 10:59:00 +01:00
period = cls(args[i][2][0])
2012-04-03 20:06:15 +02:00
args[i] = (args[i][0], args[i][1],
2012-11-07 10:59:00 +01:00
getattr(period, args[i][2][1]))
elif isinstance(args[i], list):
process_args(args[i])
2008-09-04 18:24:33 +02:00
i += 1
process_args(args)
2012-09-24 22:17:29 +02:00
return super(Period, cls).search(args, offset=offset, limit=limit,
2013-09-06 22:33:47 +02:00
order=order, count=count, query=query)
2012-09-24 22:17:29 +02:00
@classmethod
2013-01-06 22:18:13 +01:00
def create(cls, vlist):
2012-09-24 22:17:29 +02:00
FiscalYear = Pool().get('account.fiscalyear')
2013-01-06 22:18:13 +01:00
vlist = [x.copy() for x in vlist]
for vals in vlist:
if vals.get('fiscalyear'):
fiscalyear = FiscalYear(vals['fiscalyear'])
if fiscalyear.state != 'open':
2018-12-29 14:20:28 +01:00
raise AccessError(
gettext('account.msg_create_period_closed_fiscalyear',
fiscalyear=fiscalyear.rec_name))
2013-01-06 22:18:13 +01:00
if not vals.get('post_move_sequence'):
vals['post_move_sequence'] = (
fiscalyear.post_move_sequence.id)
return super(Period, cls).create(vlist)
2012-09-24 22:17:29 +02:00
@classmethod
2013-12-19 14:44:33 +01:00
def write(cls, *args):
2012-09-24 22:17:29 +02:00
Move = Pool().get('account.move')
2013-12-19 14:44:33 +01:00
actions = iter(args)
args = []
for periods, values in zip(actions, actions):
2018-06-26 19:11:40 +02:00
for key, value in values.items():
2013-12-19 14:44:33 +01:00
if key in ('start_date', 'end_date', 'fiscalyear'):
2015-03-23 21:19:09 +01:00
def modified(period):
if key in ['start_date', 'end_date']:
return getattr(period, key) != value
else:
return period.fiscalyear .id != value
2018-06-26 19:11:40 +02:00
cls._check(list(filter(modified, periods)))
2013-12-19 14:44:33 +01:00
break
if values.get('state') == 'open':
for period in periods:
if period.fiscalyear.state != 'open':
2018-12-29 14:20:28 +01:00
raise AccessError(
gettext(
'account.msg_open_period_closed_fiscalyear',
period=period.rec_name,
fiscalyear=period.fiscalyear.rec_name))
2013-12-19 14:44:33 +01:00
if values.get('post_move_sequence'):
for period in periods:
if (period.post_move_sequence
2020-03-01 12:33:50 +01:00
and period.post_move_sequence.id
!= values['post_move_sequence']):
2013-12-19 14:44:33 +01:00
if Move.search([
('period', '=', period.id),
('state', '=', 'posted'),
]):
2018-12-29 14:20:28 +01:00
raise AccessError(
gettext('account'
'.msg_change_period_post_move_sequence',
period=period.rec_name))
2013-12-19 14:44:33 +01:00
args.extend((periods, values))
super(Period, cls).write(*args)
2012-09-24 22:17:29 +02:00
@classmethod
def delete(cls, periods):
cls._check(periods)
super(Period, cls).delete(periods)
2012-09-24 22:17:29 +02:00
@classmethod
@ModelView.button
@Workflow.transition('close')
2012-09-24 22:17:29 +02:00
def close(cls, periods):
pool = Pool()
JournalPeriod = pool.get('account.journal.period')
Move = pool.get('account.move')
transaction = Transaction()
database = transaction.database
connection = transaction.connection
2022-01-04 22:17:13 +01:00
# Lock period and move to be sure no new record will be created
database.lock(connection, JournalPeriod._table)
2022-01-04 22:17:13 +01:00
database.lock(connection, Move._table)
2008-03-31 14:41:54 +02:00
unposted_moves = Move.search([
2013-03-25 18:35:52 +00:00
('period', 'in', [p.id for p in periods]),
('state', '!=', 'posted'),
], limit=1)
if unposted_moves:
unposted_move, = unposted_moves
2018-12-29 14:20:28 +01:00
raise ClosePeriodError(
gettext('account.msg_close_period_non_posted_moves',
period=unposted_move.period.rec_name,
2020-10-28 23:44:17 +01:00
moves=unposted_move.rec_name))
2012-09-24 22:17:29 +02:00
journal_periods = JournalPeriod.search([
('period', 'in', [p.id for p in periods]),
2010-08-19 22:02:00 +02:00
])
2012-09-24 22:17:29 +02:00
JournalPeriod.close(journal_periods)
2012-09-24 22:17:29 +02:00
@classmethod
@ModelView.button
@Workflow.transition('open')
def reopen(cls, periods):
"Re-open period"
pass
@classmethod
@ModelView.button
@Workflow.transition('locked')
def lock(cls, periods):
pass
2012-01-02 17:54:33 +01:00
2013-01-22 16:14:24 +01:00
@property
def post_move_sequence_used(self):
return self.post_move_sequence or self.fiscalyear.post_move_sequence