[FIX] account, wizard of fiscalyear closing: speed up the closing method of balance...
[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=None):
54     """
55     This function close account fiscalyear and create entries in new fiscalyear
56     @param cr: the current row, from the database cursor,
57     @param uid: the current user’s ID for security checks,
58     @param ids: List of Account fiscalyear close state’s IDs
59
60     """
61     pool = pooler.get_pool(cr.dbname)
62     obj_acc_period = pool.get('account.period')
63     obj_acc_fiscalyear = pool.get('account.fiscalyear')
64     obj_acc_journal = pool.get('account.journal')
65     obj_acc_move = pool.get('account.move')
66     obj_acc_move_line = pool.get('account.move.line')
67     obj_acc_account = pool.get('account.account')
68     obj_acc_journal_period = pool.get('account.journal.period')
69     currency_obj = pool.get('res.currency')
70
71     if context is None:
72         context = {}
73     fy_id = data['form']['fy_id']
74
75     cr.execute("SELECT id FROM account_period WHERE date_stop < (SELECT date_start FROM account_fiscalyear WHERE id = %s)", (str(data['form']['fy2_id']),))
76     fy_period_set = ','.join(map(lambda id: str(id[0]), cr.fetchall()))
77     cr.execute("SELECT id FROM account_period WHERE date_start > (SELECT date_stop FROM account_fiscalyear WHERE id = %s)", (str(fy_id),))
78     fy2_period_set = ','.join(map(lambda id: str(id[0]), cr.fetchall()))
79
80     period = obj_acc_period.browse(cr, uid, data['form']['period_id'], context=context)
81     new_fyear = obj_acc_fiscalyear.browse(cr, uid, data['form']['fy2_id'], context=context)
82     old_fyear = obj_acc_fiscalyear.browse(cr, uid, data['form']['fy_id'], context=context)
83
84     new_journal = data['form']['journal_id']
85     new_journal = obj_acc_journal.browse(cr, uid, new_journal, context=context)
86
87     if not new_journal.default_credit_account_id or not new_journal.default_debit_account_id:
88         raise osv.except_osv(_('UserError'),
89                 _('The journal must have default credit and debit account'))
90     if (not new_journal.centralisation) or new_journal.entry_posted:
91         raise osv.except_osv(_('UserError'),
92                 _('The journal must have centralised counterpart without the Skipping draft state option checked!'))
93
94     move_ids = obj_acc_move_line.search(cr, uid, [
95         ('journal_id', '=', new_journal.id), ('period_id.fiscalyear_id', '=', new_fyear.id)])
96
97     if move_ids:
98         raise wizard.except_wizard(_('UserError'),
99                 _('The opening journal must not have any entry in the new fiscal year !'))
100     #if move_ids:
101         #obj_acc_move_line._remove_move_reconcile(cr, uid, move_ids, context=context)
102     #    obj_acc_move_line.unlink(cr, uid, move_ids, context=context)
103
104     cr.execute("SELECT id FROM account_fiscalyear WHERE date_stop < %s", (str(new_fyear.date_start),))
105     result = cr.dictfetchall()
106     fy_ids = ','.join([str(x['id']) for x in result])
107     query_line = obj_acc_move_line._query_get(cr, uid,
108             obj='account_move_line', context={'fiscalyear': fy_ids})
109     #create the opening move
110     vals = {
111         'name': '/',
112         'ref': '',
113         'period_id': period.id,
114         'journal_id': new_journal.id,
115     }
116     move_id = obj_acc_move.create(cr, uid, vals, context=context)
117
118     #1. report of the accounts with defferal method == 'unreconciled'
119     cr.execute('''
120         SELECT a.id 
121         FROM account_account a
122         LEFT JOIN account_account_type t ON (a.user_type = t.id)
123         WHERE a.active 
124           AND a.type != 'view'
125           AND t.close_method = %s''', ('unreconciled', ))
126     account_ids = map(lambda x: x[0], cr.fetchall())
127
128     if account_ids:
129         cr.execute('''
130             INSERT INTO account_move_line (
131                  name, create_uid, create_date, write_uid, write_date,
132                  statement_id, journal_id, currency_id, date_maturity,
133                  partner_id, blocked, credit, state, debit,
134                  ref, account_id, period_id, date, move_id, amount_currency, 
135                  quantity, product_id) 
136               (SELECT name, create_uid, create_date, write_uid, write_date,
137                  statement_id, %s,currency_id, date_maturity, partner_id,
138                  blocked, credit, 'draft', debit, ref, account_id,
139                  %s, date, %s, amount_currency, quantity,product_id
140                FROM account_move_line
141                WHERE account_id IN %s 
142                  AND ''' + query_line + ''' 
143                  AND reconcile_id IS NULL)''', (new_journal.id, period.id, move_id, tuple(account_ids),))
144
145
146         #We have also to consider all move_lines that were reconciled
147         #on another fiscal year, and report them too
148         cr.execute('''
149             INSERT INTO account_move_line (
150                  name, create_uid, create_date, write_uid, write_date,
151                  statement_id, journal_id, currency_id, date_maturity,
152                  partner_id, blocked, credit, state, debit,
153                  ref, account_id, period_id, date, move_id, amount_currency,
154                  quantity, product_id)
155               (SELECT
156                  b.name, b.create_uid, b.create_date, b.write_uid, b.write_date,
157                  b.statement_id, %s, b.currency_id, b.date_maturity,
158                  b.partner_id, b.blocked, b.credit, 'draft', b.debit,
159                  b.ref, b.account_id, %s, b.date, %s, b.amount_currency,
160                  b.quantity, b.product_id
161                  FROM account_move_line b
162                  WHERE b.account_id IN %s
163                    AND b.reconcile_id IS NOT NULL
164                    AND b.period_id IN ('''+fy_period_set+''')
165                    AND b.reconcile_id IN (SELECT DISTINCT(reconcile_id)
166                                       FROM account_move_line a
167                                       WHERE a.period_id IN ('''+fy2_period_set+''')))''', (new_journal.id, period.id, move_id, tuple(account_ids),))
168
169     #2. report of the accounts with defferal method == 'detail'
170     cr.execute('''
171         SELECT a.id
172         FROM account_account a
173         LEFT JOIN account_account_type t ON (a.user_type = t.id)
174         WHERE a.active
175           AND a.type != 'view'
176           AND t.close_method = %s''', ('detail', ))
177     account_ids = map(lambda x: x[0], cr.fetchall())
178
179     if account_ids:
180         cr.execute('''
181             INSERT INTO account_move_line (
182                  name, create_uid, create_date, write_uid, write_date,
183                  statement_id, journal_id, currency_id, date_maturity,
184                  partner_id, blocked, credit, state, debit,
185                  ref, account_id, period_id, date, move_id, amount_currency,
186                  quantity, product_id)
187               (SELECT name, create_uid, create_date, write_uid, write_date,
188                  statement_id, %s,currency_id, date_maturity, partner_id,
189                  blocked, credit, 'draft', debit, ref, account_id,
190                  %s, date, %s, amount_currency, quantity,product_id
191                FROM account_move_line
192                WHERE account_id IN %s
193                  AND ''' + query_line + ''')
194                  ''', (new_journal.id, period.id, move_id, tuple(account_ids),))
195
196
197     #3. report of the accounts with defferal method == 'balance'
198     cr.execute('''
199         SELECT a.id
200         FROM account_account a
201         LEFT JOIN account_account_type t ON (a.user_type = t.id)
202         WHERE a.active
203           AND a.type != 'view'
204           AND t.close_method = %s''', ('balance', ))
205     account_ids = map(lambda x: x[0], cr.fetchall())
206
207     query_1st_part = """
208             INSERT INTO account_move_line (
209                  debit, credit, name, date, move_id, journal_id, period_id,
210                  account_id, currency_id, amount_currency) VALUES 
211     """
212     query_2nd_part = ""
213     query_2nd_part_args = []
214     for account in obj_acc_account.browse(cr, uid, account_ids, context={'fiscalyear': fy_id}):
215         accnt_type_data = account.user_type
216         if accnt_type_data.close_method == 'balance':
217             balance_in_currency = 0.0
218             if account.currency_id:
219                 cr.execute('SELECT sum(amount_currency) as balance_in_currency FROM account_move_line ' \
220                         'WHERE account_id = %s ' \
221                             'AND ' + query_line + ' ' \
222                             'AND currency_id = %s', (account.id, account.currency_id.id)) 
223                 balance_in_currency = cr.dictfetchone()['balance_in_currency']
224
225             company_currency_id = pool.get('res.users').browse(cr, uid, uid).company_id.currency_id
226             if not currency_obj.is_zero(cr, uid, company_currency_id, abs(account.balance)):
227                 if query_2nd_part:
228                     query_2nd_part += ','
229                 query_2nd_part += "(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
230                 query_2nd_part_args += (account.balance > 0 and account.balance or 0.0,
231                        account.balance < 0 and -account.balance or 0.0,
232                        data['form']['report_name'],
233                        period.date_start,
234                        move_id,
235                        new_journal.id,
236                        period.id,
237                        account.id,
238                        account.currency_id and account.currency_id.id or None,
239                        balance_in_currency)
240     if query_2nd_part:
241         cr.execute(query_1st_part + query_2nd_part, tuple(query_2nd_part_args))
242
243     #validate and centralize the opening move
244     obj_acc_move.validate(cr, uid, [move_id], context=context)
245
246     #reconcile all the move.line of the opening move
247     ids = obj_acc_move_line.search(cr, uid, [('journal_id','=',new_journal.id),
248         ('period_id.fiscalyear_id','=',new_fyear.id)])
249     context['fy_closing'] = True
250     if ids:
251         obj_acc_move_line.reconcile(cr, uid, ids, context=context)
252
253     #create the journal.period object and link it to the old fiscalyear
254     new_period = data['form']['period_id']
255     ids = obj_acc_journal_period.search(cr, uid, [('journal_id','=',new_journal.id),('period_id','=',new_period)])
256     if not ids:
257         ids = [obj_acc_journal_period.create(cr, uid, {
258                'name': (new_journal.name or '')+':'+(period.code or ''),
259                'journal_id': new_journal.id,
260                'period_id': period.id
261            })]
262     cr.execute('UPDATE account_fiscalyear ' \
263                 'SET end_journal_period_id = %s ' \
264                 'WHERE id = %s', (ids[0], old_fyear.id))
265
266     return {'type': 'ir.actions.act_window_close'}
267
268
269 class wiz_journal_close(wizard.interface):
270     states = {
271         'init': {
272             'actions': [_data_load],
273             'result': {'type': 'form', 'arch':_transaction_form, 'fields':_transaction_fields, 'state':[('end','Cancel'),('close','Create entries')]}
274         },
275         'close': {
276             'actions': [_data_save],
277             'result': {'type': 'state', 'state':'end'}
278         }
279     }
280 wiz_journal_close('account.fiscalyear.close')
281