[MERGE] OPW 381537: force date and period update on voucher when confirming bank...
[odoo/odoo.git] / addons / account / account_bank_statement.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 import time
23
24 from osv import fields, osv
25 from tools.translate import _
26 import decimal_precision as dp
27
28 class account_bank_statement(osv.osv):
29
30     def create(self, cr, uid, vals, context=None):
31         seq = 0
32         if 'line_ids' in vals:
33             for line in vals['line_ids']:
34                 seq += 1
35                 line[2]['sequence'] = seq
36                 vals[seq - 1] = line
37         return super(account_bank_statement, self).create(cr, uid, vals, context=context)
38
39     def write(self, cr, uid, ids, vals, context=None):
40         res = super(account_bank_statement, self).write(cr, uid, ids, vals, context=context)
41         account_bank_statement_line_obj = self.pool.get('account.bank.statement.line')
42         for statement in self.browse(cr, uid, ids, context):
43             seq = 0
44             for line in statement.line_ids:
45                 seq += 1
46                 account_bank_statement_line_obj.write(cr, uid, [line.id], {'sequence': seq}, context=context)
47         return res
48
49     def _default_journal_id(self, cr, uid, context=None):
50         if context is None:
51             context = {}
52         journal_pool = self.pool.get('account.journal')
53         journal_type = context.get('journal_type', False)
54         journal_id = False
55         if journal_type:
56             ids = journal_pool.search(cr, uid, [('type', '=', journal_type)])
57             if ids:
58                 journal_id = ids[0]
59         return journal_id
60
61     def _default_balance_start(self, cr, uid, context=None):
62         cr.execute('select id from account_bank_statement where journal_id=%s order by date desc limit 1', (1,))
63         res = cr.fetchone()
64         if res:
65             return self.browse(cr, uid, res[0], context=context).balance_end
66         return 0.0
67
68     def _end_balance(self, cursor, user, ids, name, attr, context=None):
69         res_currency_obj = self.pool.get('res.currency')
70         res_users_obj = self.pool.get('res.users')
71         res = {}
72
73         company_currency_id = res_users_obj.browse(cursor, user, user,
74                 context=context).company_id.currency_id.id
75
76         statements = self.browse(cursor, user, ids, context=context)
77         for statement in statements:
78             res[statement.id] = statement.balance_start
79             currency_id = statement.currency.id
80             for line in statement.move_line_ids:
81                 if line.debit > 0:
82                     if line.account_id.id == \
83                             statement.journal_id.default_debit_account_id.id:
84                         res[statement.id] += res_currency_obj.compute(cursor,
85                                 user, company_currency_id, currency_id,
86                                 line.debit, context=context)
87                 else:
88                     if line.account_id.id == \
89                             statement.journal_id.default_credit_account_id.id:
90                         res[statement.id] -= res_currency_obj.compute(cursor,
91                                 user, company_currency_id, currency_id,
92                                 line.credit, context=context)
93             if statement.state == 'draft':
94                 for line in statement.line_ids:
95                     res[statement.id] += line.amount
96         for r in res:
97             res[r] = round(res[r], 2)
98         return res
99
100     def _get_period(self, cr, uid, context=None):
101         periods = self.pool.get('account.period').find(cr, uid)
102         if periods:
103             return periods[0]
104         return False
105
106     def _currency(self, cursor, user, ids, name, args, context=None):
107         res = {}
108         res_currency_obj = self.pool.get('res.currency')
109         res_users_obj = self.pool.get('res.users')
110         default_currency = res_users_obj.browse(cursor, user,
111                 user, context=context).company_id.currency_id
112         for statement in self.browse(cursor, user, ids, context=context):
113             currency = statement.journal_id.currency
114             if not currency:
115                 currency = default_currency
116             res[statement.id] = currency.id
117         currency_names = {}
118         for currency_id, currency_name in res_currency_obj.name_get(cursor,
119                 user, [x for x in res.values()], context=context):
120             currency_names[currency_id] = currency_name
121         for statement_id in res.keys():
122             currency_id = res[statement_id]
123             res[statement_id] = (currency_id, currency_names[currency_id])
124         return res
125
126     _order = "date desc, id desc"
127     _name = "account.bank.statement"
128     _description = "Bank Statement"
129     _columns = {
130         'name': fields.char('Name', size=64, required=True, help='if you give the Name other then /, its created Accounting Entries Move will be with same name as statement name. This allows the statement entries to have the same references than the statement itself', states={'confirm': [('readonly', True)]}),
131         'date': fields.date('Date', required=True, states={'confirm': [('readonly', True)]}),
132         'journal_id': fields.many2one('account.journal', 'Journal', required=True,
133             readonly=True, states={'draft':[('readonly',False)]}),
134         'period_id': fields.many2one('account.period', 'Period', required=True,
135             states={'confirm':[('readonly', True)]}),
136         'balance_start': fields.float('Starting Balance', digits_compute=dp.get_precision('Account'),
137             states={'confirm':[('readonly',True)]}),
138         'balance_end_real': fields.float('Ending Balance', digits_compute=dp.get_precision('Account'),
139             states={'confirm':[('readonly', True)]}),
140         'balance_end': fields.function(_end_balance, method=True, string='Balance'),
141         'company_id': fields.related('journal_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True),
142         'line_ids': fields.one2many('account.bank.statement.line',
143             'statement_id', 'Statement lines',
144             states={'confirm':[('readonly', True)]}),
145         'move_line_ids': fields.one2many('account.move.line', 'statement_id',
146             'Entry lines', states={'confirm':[('readonly',True)]}),
147         'state': fields.selection([('draft', 'Draft'),('confirm', 'Confirmed')],
148             'State', required=True,
149             states={'confirm': [('readonly', True)]}, readonly="1",
150             help='When new statement is created the state will be \'Draft\'. \
151             \n* And after getting confirmation from the bank it will be in \'Confirmed\' state.'),
152         'currency': fields.function(_currency, method=True, string='Currency',
153             type='many2one', relation='res.currency'),
154         'account_id': fields.related('journal_id', 'default_debit_account_id', type='many2one', relation='account.account', string='Account used in this journal', readonly=True, help='used in statement reconciliation domain, but shouldn\'t be used elswhere.'),
155     }
156
157     _defaults = {
158         'name': "/",
159         'date': lambda *a: time.strftime('%Y-%m-%d'),
160         'state': 'draft',
161         'balance_start': _default_balance_start,
162         'journal_id': _default_journal_id,
163         'period_id': _get_period,
164     }
165
166     def onchange_date(self, cr, user, ids, date, context=None):
167         """
168         Returns a dict that contains new values and context
169         @param cr: A database cursor
170         @param user: ID of the user currently logged in
171         @param date: latest value from user input for field date
172         @param args: other arguments
173         @param context: context arguments, like lang, time zone
174         @return: Returns a dict which contains new values, and context
175         """
176         res = {}
177         period_pool = self.pool.get('account.period')
178
179         if context is None:
180             context = {}
181
182         pids = period_pool.search(cr, user, [('date_start','<=',date), ('date_stop','>=',date)])
183         if pids:
184             res.update({
185                 'period_id':pids[0]
186             })
187             context.update({
188                 'period_id':pids[0]
189             })
190
191         return {
192             'value':res,
193             'context':context,
194         }
195
196     def button_dummy(self, cr, uid, ids, context=None):
197         return self.write(cr, uid, ids, {}, context=context)
198
199     def create_move_from_st_line(self, cr, uid, st_line_id, company_currency_id, st_line_number, context=None):
200         if context is None:
201             context = {}
202         res_currency_obj = self.pool.get('res.currency')
203         account_move_obj = self.pool.get('account.move')
204         account_move_line_obj = self.pool.get('account.move.line')
205         account_bank_statement_line_obj = self.pool.get('account.bank.statement.line')
206         st_line = account_bank_statement_line_obj.browse(cr, uid, st_line_id, context=context)
207         st = st_line.statement_id
208
209         context.update({'date': st_line.date})
210
211         move_id = account_move_obj.create(cr, uid, {
212             'journal_id': st.journal_id.id,
213             'period_id': st.period_id.id,
214             'date': st_line.date,
215             'name': st_line_number,
216         }, context=context)
217         account_bank_statement_line_obj.write(cr, uid, [st_line.id], {
218             'move_ids': [(4, move_id, False)]
219         })
220
221         torec = []
222         if st_line.amount >= 0:
223             account_id = st.journal_id.default_credit_account_id.id
224         else:
225             account_id = st.journal_id.default_debit_account_id.id
226
227         acc_cur = ((st_line.amount<=0) and st.journal_id.default_debit_account_id) or st_line.account_id
228         context.update({
229                 'res.currency.compute.account': acc_cur,
230             })
231         amount = res_currency_obj.compute(cr, uid, st.currency.id,
232                 company_currency_id, st_line.amount, context=context)
233
234         val = {
235             'name': st_line.name,
236             'date': st_line.date,
237             'ref': st_line.ref,
238             'move_id': move_id,
239             'partner_id': ((st_line.partner_id) and st_line.partner_id.id) or False,
240             'account_id': (st_line.account_id) and st_line.account_id.id,
241             'credit': ((amount>0) and amount) or 0.0,
242             'debit': ((amount<0) and -amount) or 0.0,
243             'statement_id': st.id,
244             'journal_id': st.journal_id.id,
245             'period_id': st.period_id.id,
246             'currency_id': st.currency.id,
247             'analytic_account_id': st_line.analytic_account_id and st_line.analytic_account_id.id or False
248         }
249
250         if st.currency.id <> company_currency_id:
251             amount_cur = res_currency_obj.compute(cr, uid, company_currency_id,
252                         st.currency.id, amount, context=context)
253             val['amount_currency'] = -amount_cur
254
255         if st_line.account_id and st_line.account_id.currency_id and st_line.account_id.currency_id.id <> company_currency_id:
256             val['currency_id'] = st_line.account_id.currency_id.id
257             amount_cur = res_currency_obj.compute(cr, uid, company_currency_id,
258                     st_line.account_id.currency_id.id, amount, context=context)
259             val['amount_currency'] = -amount_cur
260
261         move_line_id = account_move_line_obj.create(cr, uid, val, context=context)
262         torec.append(move_line_id)
263
264         # Fill the secondary amount/currency
265         # if currency is not the same than the company
266         amount_currency = False
267         currency_id = False
268         if st.currency.id <> company_currency_id:
269             amount_currency = st_line.amount
270             currency_id = st.currency.id
271         account_move_line_obj.create(cr, uid, {
272             'name': st_line.name,
273             'date': st_line.date,
274             'ref': st_line.ref,
275             'move_id': move_id,
276             'partner_id': ((st_line.partner_id) and st_line.partner_id.id) or False,
277             'account_id': account_id,
278             'credit': ((amount < 0) and -amount) or 0.0,
279             'debit': ((amount > 0) and amount) or 0.0,
280             'statement_id': st.id,
281             'journal_id': st.journal_id.id,
282             'period_id': st.period_id.id,
283             'amount_currency': amount_currency,
284             'currency_id': currency_id,
285             }, context=context)
286
287         for line in account_move_line_obj.browse(cr, uid, [x.id for x in
288                 account_move_obj.browse(cr, uid, move_id,
289                     context=context).line_id],
290                 context=context):
291             if line.state <> 'valid':
292                 raise osv.except_osv(_('Error !'),
293                         _('Journal Item "%s" is not valid') % line.name)
294
295         if st.journal_id.entry_posted:
296             account_move_obj.post(cr, uid, [move_id], context=context)
297         return move_id
298
299     def get_next_st_line_number(self, cr, uid, st_number, st_line, context=None):
300         return st_number + '/' + str(st_line.sequence)
301
302     def balance_check(self, cr, uid, st_id, journal_type='bank', context=None):
303         st = self.browse(cr, uid, st_id, context=context)
304         if not (abs((st.balance_end or 0.0) - st.balance_end_real) < 0.0001):
305             raise osv.except_osv(_('Error !'),
306                     _('The statement balance is incorrect !\n') +
307                     _('The expected balance (%.2f) is different than the computed one. (%.2f)') % (st.balance_end_real, st.balance_end))
308         return True
309
310     def statement_close(self, cr, uid, ids, journal_type='bank', context=None):
311         return self.write(cr, uid, ids, {'state':'confirm'}, context=context)
312
313     def check_status_condition(self, cr, uid, state, journal_type='bank'):
314         return state=='draft'
315
316     def button_confirm_bank(self, cr, uid, ids, context=None):
317         done = []
318         obj_seq = self.pool.get('ir.sequence')
319         if context is None:
320             context = {}
321
322         for st in self.browse(cr, uid, ids, context=context):
323             j_type = st.journal_id.type
324             company_currency_id = st.journal_id.company_id.currency_id.id
325             if not self.check_status_condition(cr, uid, st.state, journal_type=j_type):
326                 continue
327
328             self.balance_check(cr, uid, st.id, journal_type=j_type, context=context)
329             if (not st.journal_id.default_credit_account_id) \
330                     or (not st.journal_id.default_debit_account_id):
331                 raise osv.except_osv(_('Configuration Error !'),
332                         _('Please verify that an account is defined in the journal.'))
333
334             if not st.name == '/':
335                 st_number = st.name
336             else:
337                 if st.journal_id.sequence_id:
338                     c = {'fiscalyear_id': st.period_id.fiscalyear_id.id}
339                     st_number = obj_seq.get_id(cr, uid, st.journal_id.sequence_id.id, context=c)
340                 else:
341                     st_number = obj_seq.get(cr, uid, 'account.bank.statement')
342
343             for line in st.move_line_ids:
344                 if line.state <> 'valid':
345                     raise osv.except_osv(_('Error !'),
346                             _('The account entries lines are not in valid state.'))
347             for st_line in st.line_ids:
348                 if st_line.analytic_account_id:
349                     if not st.journal_id.analytic_journal_id:
350                         raise osv.except_osv(_('No Analytic Journal !'),_("You have to define an analytic journal on the '%s' journal!") % (st.journal_id.name,))
351                 if not st_line.amount:
352                     continue
353                 st_line_number = self.get_next_st_line_number(cr, uid, st_number, st_line, context)
354                 self.create_move_from_st_line(cr, uid, st_line.id, company_currency_id, st_line_number, context)
355
356             self.write(cr, uid, [st.id], {'name': st_number}, context=context)
357             self.log(cr, uid, st.id, _('Statement %s is confirmed, journal items are created.') % (st_number,))
358             done.append(st.id)
359         return self.write(cr, uid, ids, {'state':'confirm'}, context=context)
360
361     def button_cancel(self, cr, uid, ids, context=None):
362         done = []
363         account_move_obj = self.pool.get('account.move')
364         for st in self.browse(cr, uid, ids, context=context):
365             if st.state=='draft':
366                 continue
367             ids = []
368             for line in st.line_ids:
369                 ids += [x.id for x in line.move_ids]
370             account_move_obj.unlink(cr, uid, ids, context)
371             done.append(st.id)
372         return self.write(cr, uid, done, {'state':'draft'}, context=context)
373
374     def onchange_journal_id(self, cr, uid, statement_id, journal_id, context=None):
375         cr.execute('SELECT balance_end_real \
376                 FROM account_bank_statement \
377                 WHERE journal_id = %s AND NOT state = %s \
378                 ORDER BY date DESC,id DESC LIMIT 1', (journal_id, 'draft'))
379         res = cr.fetchone()
380         balance_start = res and res[0] or 0.0
381         account_id = self.pool.get('account.journal').read(cr, uid, journal_id, ['default_debit_account_id'], context=context)['default_debit_account_id']
382         return {'value': {'balance_start': balance_start, 'account_id': account_id}}
383
384     def unlink(self, cr, uid, ids, context=None):
385         stat = self.read(cr, uid, ids, ['state'], context=context)
386         unlink_ids = []
387         for t in stat:
388             if t['state'] in ('draft'):
389                 unlink_ids.append(t['id'])
390             else:
391                 raise osv.except_osv(_('Invalid action !'), _('Cannot delete bank statement(s) which are already confirmed !'))
392         osv.osv.unlink(self, cr, uid, unlink_ids, context=context)
393         return True
394
395     def copy(self, cr, uid, id, default=None, context=None):
396         if default is None:
397             default = {}
398         if context is None:
399             context = {}
400         default = default.copy()
401         default['move_line_ids'] = []
402         return super(account_bank_statement, self).copy(cr, uid, id, default, context=context)
403
404 account_bank_statement()
405
406 class account_bank_statement_line(osv.osv):
407
408     def onchange_partner_id(self, cr, uid, ids, partner_id, context=None):
409         obj_partner = self.pool.get('res.partner')
410         if context is None:
411             context = {}
412         if not partner_id:
413             return {}
414         part = obj_partner.browse(cr, uid, partner_id, context=context)
415         if not part.supplier and not part.customer:
416             type = 'general'
417         elif part.supplier and part.customer:
418             type = 'general'
419         else:
420             if part.supplier == True:
421                 type = 'supplier'
422             if part.customer == True:
423                 type = 'customer'
424         res_type = self.onchange_type(cr, uid, ids, partner_id=partner_id, type=type, context=context)
425         if res_type['value'] and res_type['value'].get('account_id', False):
426             return {'value': {'type': type, 'account_id': res_type['value']['account_id']}}
427         return {'value': {'type': type}}
428
429     def onchange_type(self, cr, uid, line_id, partner_id, type, context=None):
430         res = {'value': {}}
431         obj_partner = self.pool.get('res.partner')
432         if context is None:
433             context = {}
434         if not partner_id:
435             return res
436         account_id = False
437         line = self.browse(cr, uid, line_id, context=context)
438         if not line or (line and not line[0].account_id):
439             part = obj_partner.browse(cr, uid, partner_id, context=context)
440             if type == 'supplier':
441                 account_id = part.property_account_payable.id
442             else:
443                 account_id = part.property_account_receivable.id
444             res['value']['account_id'] = account_id
445         return res
446
447     _order = "statement_id desc, sequence"
448     _name = "account.bank.statement.line"
449     _description = "Bank Statement Line"
450     _columns = {
451         'name': fields.char('Communication', size=64, required=True),
452         'date': fields.date('Date', required=True),
453         'amount': fields.float('Amount', digits_compute=dp.get_precision('Account')),
454         'type': fields.selection([
455             ('supplier','Supplier'),
456             ('customer','Customer'),
457             ('general','General')
458             ], 'Type', required=True),
459         'partner_id': fields.many2one('res.partner', 'Partner'),
460         'account_id': fields.many2one('account.account','Account',
461             required=True),
462         'statement_id': fields.many2one('account.bank.statement', 'Statement',
463             select=True, required=True, ondelete='cascade'),
464         'analytic_account_id': fields.many2one('account.analytic.account', 'Analytic Account'),
465         'move_ids': fields.many2many('account.move',
466             'account_bank_statement_line_move_rel', 'move_id','statement_id',
467             'Moves'),
468         'ref': fields.char('Reference', size=32),
469         'note': fields.text('Notes'),
470         'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of bank statement lines."),
471         'company_id': fields.related('statement_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True),
472     }
473     _defaults = {
474         'name': lambda self,cr,uid,context={}: self.pool.get('ir.sequence').get(cr, uid, 'account.bank.statement.line'),
475         'date': lambda self, cr, uid, context, *a: context.get('date'),
476         'type': 'general',
477     }
478
479 account_bank_statement_line()
480
481 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: