1e5ce569097ed0615355b772246f8ab00610eb7a
[odoo/odoo.git] / addons / account / wizard / wizard_fiscalyear_close.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
6 #    $Id$
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU General Public License as published by
10 #    the Free Software Foundation, either version 3 of the License, or
11 #    (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU General Public License for more details.
17 #
18 #    You should have received a copy of the GNU General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21 ##############################################################################
22
23 import wizard
24 import osv
25 import pooler
26 from tools.translate import _
27
28 _transaction_form = '''<?xml version="1.0"?>
29 <form string="Close Fiscal Year with new entries">
30     <field name="fy_id"/>
31     <field name="fy2_id"/>
32     <field name="journal_id"/>
33     <field name="period_id"/>
34     <field name="report_name" colspan="4"/>
35
36     <separator string="Are you sure you want to create entries?" colspan="4"/>
37     <field name="sure"/>
38 </form>'''
39
40 _transaction_fields = {
41     'fy_id': {'string':'Fiscal Year to close', 'type':'many2one', 'relation': 'account.fiscalyear','required':True, 'domain':[('state','=','draft')]},
42     'journal_id': {'string':'Opening Entries Journal', 'type':'many2one', 'relation': 'account.journal','required':True},
43     'period_id': {'string':'Opening Entries Period', 'type':'many2one', 'relation': 'account.period','required':True, 'domain':"[('fiscalyear_id','=',fy2_id)]"},
44     'fy2_id': {'string':'New Fiscal Year', 'type':'many2one', 'relation': 'account.fiscalyear', 'domain':[('state','=','draft')], 'required':True},
45     'report_name': {'string':'Name of new entries', 'type':'char', 'size': 64, 'required':True},
46     'sure': {'string':'Check this box', 'type':'boolean'},
47 }
48
49 def _data_load(self, cr, uid, data, context):
50     data['form']['report_name'] = _('End of Fiscal Year Entry')
51     return data['form']
52
53 def _data_save(self, cr, uid, data, context):
54     if not data['form']['sure']:
55         raise wizard.except_wizard(_('UserError'), _('Closing of fiscal year cancelled, please check the box !'))
56     pool = pooler.get_pool(cr.dbname)
57
58     fy_id = data['form']['fy_id']
59     period_ids = pool.get('account.period').search(cr, uid, [('fiscalyear_id', '=', fy_id)])
60     cr.execute("SELECT id FROM account_period WHERE date_stop < (SELECT date_start FROM account_fiscalyear WHERE id = %s)" , (str(data['form']['fy2_id']),))
61     fy_period_set = ','.join(map(lambda id: str(id[0]), cr.fetchall()))
62     cr.execute("SELECT id FROM account_period WHERE date_start > (SELECT date_stop FROM account_fiscalyear WHERE id = %s)" , (str(fy_id),))
63     fy2_period_set = ','.join(map(lambda id: str(id[0]), cr.fetchall()))
64     period = pool.get('account.period').browse(cr, uid, data['form']['period_id'], context=context)
65     new_fyear = pool.get('account.fiscalyear').browse(cr, uid, data['form']['fy2_id'], context=context)
66     old_fyear = pool.get('account.fiscalyear').browse(cr, uid, data['form']['fy_id'], context=context)
67     
68     new_journal = data['form']['journal_id']
69     new_journal = pool.get('account.journal').browse(cr, uid, new_journal, context=context)
70
71     if not new_journal.default_credit_account_id or not new_journal.default_debit_account_id:
72         raise wizard.except_wizard(_('UserError'),
73                 _('The journal must have default credit and debit account'))
74     if (not new_journal.centralisation) or new_journal.entry_posted:
75         raise wizard.except_wizard(_('UserError'),
76                 _('The journal must have centralised counterpart without the Skipping draft state option checked!'))
77
78     move_ids = pool.get('account.move.line').search(cr, uid, [
79         ('journal_id','=',new_journal.id),('period_id.fiscalyear_id','=',new_fyear.id)])
80     if move_ids:
81         raise wizard.except_wizard(_('UserError'),
82                 _('The opening journal must not have any entry in the new fiscal year !'))
83     cr.execute("SELECT id FROM account_fiscalyear WHERE date_stop < %s", (str(new_fyear.date_start),))
84     result = cr.dictfetchall()
85     fy_ids = ','.join([str(x['id']) for x in result])
86     query_line = pool.get('account.move.line')._query_get(cr, uid,
87             obj='account_move_line', context={'fiscalyear': fy_ids})
88     cr.execute('select id from account_account WHERE active')
89     ids = map(lambda x: x[0], cr.fetchall())
90     for account in pool.get('account.account').browse(cr, uid, ids,
91         context={'fiscalyear': fy_id}):
92         
93         accnt_type_data = account.user_type
94         if not accnt_type_data:
95             continue
96         if accnt_type_data.close_method=='none' or account.type == 'view':
97             continue
98         if accnt_type_data.close_method=='balance':
99             if abs(account.balance)>0.0001:
100                 pool.get('account.move.line').create(cr, uid, {
101                     'debit': account.balance>0 and account.balance,
102                     'credit': account.balance<0 and -account.balance,
103                     'name': data['form']['report_name'],
104                     'date': period.date_start,
105                     'journal_id': new_journal.id,
106                     'period_id': period.id,
107                     'account_id': account.id
108                 }, {'journal_id': new_journal.id, 'period_id':period.id})
109         if accnt_type_data.close_method == 'unreconciled':
110             offset = 0
111             limit = 100
112             while True:
113                 cr.execute('SELECT id, name, quantity, debit, credit, account_id, ref, ' \
114                             'amount_currency, currency_id, blocked, partner_id, ' \
115                             'date_maturity, date_created ' \
116                         'FROM account_move_line ' \
117                         'WHERE account_id = %s ' \
118                             'AND ' + query_line + ' ' \
119                             'AND reconcile_id is NULL ' \
120                         'ORDER BY id ' \
121                         'LIMIT %s OFFSET %s', (account.id, limit, offset))
122                 result = cr.dictfetchall()
123                 if not result:
124                     break
125                 for move in result:
126                     move.pop('id')
127                     move.update({
128                         'date': period.date_start,
129                         'journal_id': new_journal.id,
130                         'period_id': period.id,
131                     })
132                     pool.get('account.move.line').create(cr, uid, move, {
133                         'journal_id': new_journal.id,
134                         'period_id': period.id,
135                         })
136                 offset += limit
137
138             #We have also to consider all move_lines that were reconciled 
139             #on another fiscal year, and report them too
140             offset = 0
141             limit = 100
142             while True:
143                 cr.execute('SELECT DISTINCT b.id, b.name, b.quantity, b.debit, b.credit, b.account_id, b.ref, ' \
144                             'b.amount_currency, b.currency_id, b.blocked, b.partner_id, ' \
145                             'b.date_maturity, b.date_created ' \
146                         'FROM account_move_line a, account_move_line b ' \
147                         'WHERE b.account_id = %s ' \
148                             'AND b.reconcile_id is NOT NULL ' \
149                             'AND a.reconcile_id = b.reconcile_id ' \
150                             'AND b.period_id IN ('+fy_period_set+') ' \
151                             'AND a.period_id IN ('+fy2_period_set+') ' \
152                         'ORDER BY id ' \
153                         'LIMIT %s OFFSET %s', (account.id, limit, offset))
154                 result = cr.dictfetchall()
155                 if not result:
156                     break
157                 for move in result:
158                     move.pop('id')
159                     move.update({
160                         'date': period.date_start,
161                         'journal_id': new_journal.id,
162                         'period_id': period.id,
163                     })
164                     pool.get('account.move.line').create(cr, uid, move, {
165                         'journal_id': new_journal.id,
166                         'period_id': period.id,
167                         })
168                 offset += limit
169         if accnt_type_data.close_method=='detail':
170             offset = 0
171             limit = 100
172             while True:
173                 cr.execute('SELECT id, name, quantity, debit, credit, account_id, ref, ' \
174                             'amount_currency, currency_id, blocked, partner_id, ' \
175                             'date_maturity, date_created ' \
176                         'FROM account_move_line ' \
177                         'WHERE account_id = %s ' \
178                             'AND ' + query_line + ' ' \
179                         'ORDER BY id ' \
180                         'LIMIT %s OFFSET %s', (account.id, limit, offset))
181                 
182                 result = cr.dictfetchall()
183                 if not result:
184                     break
185                 for move in result:
186                     move.pop('id')
187                     move.update({
188                         'date': period.date_start,
189                         'journal_id': new_journal.id,
190                         'period_id': period.id,
191                     })
192                     pool.get('account.move.line').create(cr, uid, move)
193                 offset += limit
194     ids = pool.get('account.move.line').search(cr, uid, [('journal_id','=',new_journal.id),
195         ('period_id.fiscalyear_id','=',new_fyear.id)])
196     context['fy_closing'] = True
197
198     if ids:
199         pool.get('account.move.line').reconcile(cr, uid, ids, context=context)
200     new_period = data['form']['period_id']
201     ids = pool.get('account.journal.period').search(cr, uid, [('journal_id','=',new_journal.id),('period_id','=',new_period)])
202     if not ids:
203         ids = [pool.get('account.journal.period').create(cr, uid, {
204                'name': (new_journal.name or '')+':'+(period.code or ''),
205                'journal_id': new_journal.id,
206                'period_id': period.id
207            })]
208     cr.execute('UPDATE account_fiscalyear ' \
209                 'SET end_journal_period_id = %s ' \
210                 'WHERE id = %s', (ids[0], old_fyear.id))
211
212     return {}
213
214 class wiz_journal_close(wizard.interface):
215     states = {
216         'init': {
217             'actions': [_data_load],
218             'result': {'type': 'form', 'arch':_transaction_form, 'fields':_transaction_fields, 'state':[('end','Cancel'),('close','Create entries')]}
219         },
220         'close': {
221             'actions': [_data_save],
222             'result': {'type': 'state', 'state':'end'}
223         }
224     }
225 wiz_journal_close('account.fiscalyear.close')
226
227
228 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
229