improve
[odoo/odoo.git] / addons / account / account_bank_statement.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution   
5 #    Copyright (C) 2004-2008 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 import time
23 import netsvc
24 from osv import fields, osv
25
26 from tools.misc import currency
27 from tools.translate import _
28
29 import mx.DateTime
30 from mx.DateTime import RelativeDateTime, now, DateTime, localtime
31
32
33 class account_bank_statement(osv.osv):
34     def _default_journal_id(self, cr, uid, context={}):
35         if context.get('journal_id', False):
36             return context['journal_id']
37         return False
38
39     def _default_balance_start(self, cr, uid, context={}):
40         cr.execute('select id from account_bank_statement where journal_id=%d order by date desc limit 1', (1,))
41         res = cr.fetchone()
42         if res:
43             return self.browse(cr, uid, [res[0]], context)[0].balance_end
44         return 0.0
45
46     def _end_balance(self, cursor, user, ids, name, attr, context=None):
47         res_currency_obj = self.pool.get('res.currency')
48         res_users_obj = self.pool.get('res.users')
49
50         res = {}
51
52         company_currency_id = res_users_obj.browse(cursor, user, user,
53                 context=context).company_id.currency_id.id
54
55         statements = self.browse(cursor, user, ids, context=context)
56         for statement in statements:
57             res[statement.id] = statement.balance_start
58             currency_id = statement.currency.id
59             for line in statement.move_line_ids:
60                 if line.debit > 0:
61                     if line.account_id.id == \
62                             statement.journal_id.default_debit_account_id.id:
63                         res[statement.id] += res_currency_obj.compute(cursor,
64                                 user, company_currency_id, currency_id,
65                                 line.debit, context=context)
66                 else:
67                     if line.account_id.id == \
68                             statement.journal_id.default_credit_account_id.id:
69                         res[statement.id] += res_currency_obj.compute(cursor,
70                                 user, company_currency_id, currency_id,
71                                 line.credit, context=context)
72             if statement.state == 'draft':
73                 for line in statement.line_ids:
74                     res[statement.id] += line.amount
75         for r in res:
76             res[r] = round(res[r], 2)
77         return res
78
79     def _get_period(self, cr, uid, context={}):
80         periods = self.pool.get('account.period').find(cr, uid)
81         if periods:
82             return periods[0]
83         else:
84             return False
85
86     def _currency(self, cursor, user, ids, name, args, context=None):
87         res = {}
88         res_currency_obj = self.pool.get('res.currency')
89         res_users_obj = self.pool.get('res.users')
90         default_currency = res_users_obj.browse(cursor, user,
91                 user, context=context).company_id.currency_id
92         for statement in self.browse(cursor, user, ids, context=context):
93             currency = statement.journal_id.currency
94             if not currency:
95                 currency = default_currency
96             res[statement.id] = currency.id
97         currency_names = {}
98         for currency_id, currency_name in res_currency_obj.name_get(cursor,
99                 user, [x for x in res.values()], context=context):
100             currency_names[currency_id] = currency_name
101         for statement_id in res.keys():
102             currency_id = res[statement_id]
103             res[statement_id] = (currency_id, currency_names[currency_id])
104         return res
105
106     _order = "date desc"
107     _name = "account.bank.statement"
108     _description = "Bank Statement"
109     _columns = {
110         'name': fields.char('Name', size=64, required=True),
111         'date': fields.date('Date', required=True,
112             states={'confirm': [('readonly', True)]}),
113         'journal_id': fields.many2one('account.journal', 'Journal', required=True,
114             states={'confirm': [('readonly', True)]}, domain=[('type', '=', 'cash')]),
115         'period_id': fields.many2one('account.period', 'Period', required=True,
116             states={'confirm':[('readonly', True)]}),
117         'balance_start': fields.float('Starting Balance', digits=(16,2),
118             states={'confirm':[('readonly',True)]}),
119         'balance_end_real': fields.float('Ending Balance', digits=(16,2),
120             states={'confirm':[('readonly', True)]}),
121         'balance_end': fields.function(_end_balance, method=True, string='Balance'),
122         'line_ids': fields.one2many('account.bank.statement.line',
123             'statement_id', 'Statement lines',
124             states={'confirm':[('readonly', True)]}),
125         'move_line_ids': fields.one2many('account.move.line', 'statement_id',
126             'Entry lines', states={'confirm':[('readonly',True)]}),
127         'state': fields.selection([('draft', 'Draft'),('confirm', 'Confirm')],
128             'State', required=True,
129             states={'confirm': [('readonly', True)]}, readonly="1"),
130         'currency': fields.function(_currency, method=True, string='Currency',
131             type='many2one', relation='res.currency'),
132     }
133
134     _defaults = {
135         'name': lambda self, cr, uid, context=None: \
136                 self.pool.get('ir.sequence').get(cr, uid, 'account.bank.statement'),
137         'date': lambda *a: time.strftime('%Y-%m-%d'),
138         'state': lambda *a: 'draft',
139         'balance_start': _default_balance_start,
140         'journal_id': _default_journal_id,
141         'period_id': _get_period,
142     }
143
144     def button_confirm(self, cr, uid, ids, context=None):
145         done = []
146         res_currency_obj = self.pool.get('res.currency')
147         res_users_obj = self.pool.get('res.users')
148         account_move_obj = self.pool.get('account.move')
149         account_move_line_obj = self.pool.get('account.move.line')
150         account_bank_statement_line_obj = \
151                 self.pool.get('account.bank.statement.line')
152
153         company_currency_id = res_users_obj.browse(cr, uid, uid,
154                 context=context).company_id.currency_id.id
155
156         for st in self.browse(cr, uid, ids, context):
157             if not st.state=='draft':
158                 continue
159
160             if not (abs(st.balance_end - st.balance_end_real) < 0.0001):
161                 raise osv.except_osv(_('Error !'),
162                         _('The statement balance is incorrect !\n') +
163                         _('The expected balance (%.2f) is different than the computed one. (%.2f)') % (st.balance_end_real, st.balance_end))
164             if (not st.journal_id.default_credit_account_id) \
165                     or (not st.journal_id.default_debit_account_id):
166                 raise osv.except_osv(_('Configration Error !'),
167                         _('Please verify that an account is defined in the journal.'))
168
169             for line in st.move_line_ids:
170                 if line.state <> 'valid':
171                     raise osv.except_osv(_('Error !'),
172                             _('The account entries lines are not in valid state.'))
173
174             for move in st.line_ids:
175                 move_id = account_move_obj.create(cr, uid, {
176                     'journal_id': st.journal_id.id,
177                     'period_id': st.period_id.id,
178                 }, context=context)
179                 account_bank_statement_line_obj.write(cr, uid, [move.id], {
180                     'move_ids': [(4,move_id, False)]
181                 })
182                 if not move.amount:
183                     continue
184
185                 torec = []
186                 if move.amount >= 0:
187                     account_id = st.journal_id.default_credit_account_id.id
188                 else:
189                     account_id = st.journal_id.default_debit_account_id.id
190                 acc_cur = ((move.amount<=0) and st.journal_id.default_debit_account_id) or move.account_id
191                 amount = res_currency_obj.compute(cr, uid, st.currency.id,
192                         company_currency_id, move.amount, context=context,
193                         account=acc_cur)
194                 if move.reconcile_id and move.reconcile_id.line_new_ids:
195                     for newline in move.reconcile_id.line_new_ids:
196                         amount += newline.amount
197
198                 val = {
199                     'name': move.name,
200                     'date': move.date,
201                     'ref': move.ref,
202                     'move_id': move_id,
203                     'partner_id': ((move.partner_id) and move.partner_id.id) or False,
204                     'account_id': (move.account_id) and move.account_id.id,
205                     'credit': ((amount>0) and amount) or 0.0,
206                     'debit': ((amount<0) and -amount) or 0.0,
207                     'statement_id': st.id,
208                     'journal_id': st.journal_id.id,
209                     'period_id': st.period_id.id,
210                     'currency_id': st.currency.id,
211                 }
212
213                 amount = res_currency_obj.compute(cr, uid, st.currency.id,
214                         company_currency_id, move.amount, context=context,
215                         account=acc_cur)
216
217                 if move.account_id and move.account_id.currency_id:
218                     val['currency_id'] = move.account_id.currency_id.id
219                     if company_currency_id==move.account_id.currency_id.id:
220                         amount_cur = move.amount
221                     else:
222                         amount_cur = res_currency_obj.compute(cr, uid, company_currency_id,
223                                 move.account_id.currency_id.id, amount, context=context,
224                                 account=acc_cur)
225                     val['amount_currency'] = amount_cur
226
227                 torec.append(account_move_line_obj.create(cr, uid, val , context=context))
228
229                 if move.reconcile_id and move.reconcile_id.line_new_ids:
230                     for newline in move.reconcile_id.line_new_ids:
231                         account_move_line_obj.create(cr, uid, {
232                             'name': newline.name or move.name,
233                             'date': move.date,
234                             'ref': move.ref,
235                             'move_id': move_id,
236                             'partner_id': ((move.partner_id) and move.partner_id.id) or False,
237                             'account_id': (newline.account_id) and newline.account_id.id,
238                             'debit': newline.amount>0 and newline.amount or 0.0,
239                             'credit': newline.amount<0 and -newline.amount or 0.0,
240                             'statement_id': st.id,
241                             'journal_id': st.journal_id.id,
242                             'period_id': st.period_id.id,
243                         }, context=context)
244
245                 # Fill the secondary amount/currency
246                 # if currency is not the same than the company
247                 amount_currency = False
248                 currency_id = False
249                 if st.currency.id <> company_currency_id:
250                     amount_currency = move.amount
251                     currency_id = st.currency.id
252
253                 account_move_line_obj.create(cr, uid, {
254                     'name': move.name,
255                     'date': move.date,
256                     'ref': move.ref,
257                     'move_id': move_id,
258                     'partner_id': ((move.partner_id) and move.partner_id.id) or False,
259                     'account_id': account_id,
260                     'credit': ((amount < 0) and -amount) or 0.0,
261                     'debit': ((amount > 0) and amount) or 0.0,
262                     'statement_id': st.id,
263                     'journal_id': st.journal_id.id,
264                     'period_id': st.period_id.id,
265                     'amount_currency': amount_currency,
266                     'currency_id': currency_id,
267                     }, context=context)
268
269                 for line in account_move_line_obj.browse(cr, uid, [x.id for x in
270                         account_move_obj.browse(cr, uid, move_id,
271                             context=context).line_id],
272                         context=context):
273                     if line.state <> 'valid':
274                         raise osv.except_osv(_('Error !'),
275                                 _('Account move line "%s" is not valid') % line.name)
276
277                 if move.reconcile_id and move.reconcile_id.line_ids:
278                     torec += map(lambda x: x.id, move.reconcile_id.line_ids)
279                     try:
280                         if abs(move.reconcile_amount-move.amount)<0.0001:
281                             account_move_line_obj.reconcile(cr, uid, torec, 'statement', context)
282                         else:
283                             account_move_line_obj.reconcile_partial(cr, uid, torec, 'statement', context)
284                     except:
285                         raise osv.except_osv(_('Error !'), _('Unable to reconcile entry "%s": %.2f') % (move.name, move.amount))
286
287                 if st.journal_id.entry_posted:
288                     account_move_obj.write(cr, uid, [move_id], {'state':'posted'})
289             done.append(st.id)
290         self.write(cr, uid, done, {'state':'confirm'}, context=context)
291         return True
292
293     def button_cancel(self, cr, uid, ids, context={}):
294         done = []
295         for st in self.browse(cr, uid, ids, context):
296             if st.state=='draft':
297                 continue
298             ids = []
299             for line in st.line_ids:
300                 ids += [x.id for x in line.move_ids]
301             self.pool.get('account.move').unlink(cr, uid, ids, context)
302             done.append(st.id)
303         self.write(cr, uid, done, {'state':'draft'}, context=context)
304         return True
305
306     def onchange_journal_id(self, cursor, user, statement_id, journal_id, context=None):
307         if not journal_id:
308             return {'value': {'currency': False}}
309
310         account_journal_obj = self.pool.get('account.journal')
311         res_users_obj = self.pool.get('res.users')
312         res_currency_obj = self.pool.get('res.currency')
313
314         cursor.execute('SELECT balance_end_real \
315                 FROM account_bank_statement \
316                 WHERE journal_id = %d \
317                 ORDER BY date DESC,id DESC LIMIT 1', (journal_id,))
318         res = cursor.fetchone()
319         balance_start = res and res[0] or 0.0
320
321         currency_id = account_journal_obj.browse(cursor, user, journal_id,
322                 context=context).currency.id
323         if not currency_id:
324             currency_id = res_users_obj.browse(cursor, user, user,
325                     context=context).company_id.currency_id.id
326         currency = res_currency_obj.name_get(cursor, user, [currency_id],
327                 context=context)[0]
328         return {'value': {'balance_start': balance_start, 'currency': currency}}
329
330 account_bank_statement()
331
332
333 class account_bank_statement_reconcile(osv.osv):
334     _name = "account.bank.statement.reconcile"
335     _description = "Statement reconcile"
336
337     def _total_entry(self, cursor, user, ids, name, attr, context=None):
338         result = {}
339         for o in self.browse(cursor, user, ids, context=context):
340             result[o.id] = 0.0
341             for line in o.line_ids:
342                 result[o.id] += line.debit - line.credit
343         return result
344
345     def _total_new(self, cursor, user, ids, name, attr, context=None):
346         result = {}
347         for o in self.browse(cursor, user, ids, context=context):
348             result[o.id] = 0.0
349             for line in o.line_new_ids:
350                 result[o.id] += line.amount
351         return result
352
353     def _total_balance(self, cursor, user, ids, name, attr, context=None):
354         result = {}
355         for o in self.browse(cursor, user, ids, context=context):
356             result[o.id] = o.total_new - o.total_entry + o.total_amount
357         return result
358
359     def _total_amount(self, cursor, user, ids, name, attr, context=None):
360         res = {}
361         res_currency_obj = self.pool.get('res.currency')
362         res_users_obj = self.pool.get('res.users')
363
364         company_currency_id = res_users_obj.browse(cursor, user, user,
365                 context=context).company_id.currency_id.id
366         currency_id = context.get('currency_id', company_currency_id)
367
368         acc_cur = None
369         if context.get('journal_id', False) and context.get('account_id',False):
370             st =self.pool.get('account.journal').browse(cursor, user, context['journal_id'])
371             acc = self.pool.get('account.account').browse(cursor, user, context['account_id'])
372             acc_cur = (( context.get('amount',0.0)<=0) and st.default_debit_account_id) or acc
373
374         for reconcile_id in ids:
375             res[reconcile_id] = res_currency_obj.compute(cursor, user,
376                     currency_id, company_currency_id,
377                     context.get('amount', 0.0), context=context, account=acc_cur)
378         return res
379
380     def _default_amount(self, cursor, user, context=None):
381         if context is None:
382             context = {}
383         res_currency_obj = self.pool.get('res.currency')
384         res_users_obj = self.pool.get('res.users')
385
386         company_currency_id = res_users_obj.browse(cursor, user, user,
387                 context=context).company_id.currency_id.id
388         currency_id = context.get('currency_id', company_currency_id)
389
390         acc_cur = None
391         if context.get('journal_id', False) and context.get('account_id',False):
392             st =self.pool.get('account.journal').browse(cursor, user, context['journal_id'])
393             acc = self.pool.get('account.account').browse(cursor, user, context['account_id'])
394             acc_cur = (( context.get('amount',0.0)<=0) and st.default_debit_account_id) or acc
395
396         return res_currency_obj.compute(cursor, user,
397                 currency_id, company_currency_id,
398                 context.get('amount', 0.0), context=context, account=acc_cur)
399
400     def _total_currency(self, cursor, user, ids, name, attrs, context=None):
401         res = {}
402         res_users_obj = self.pool.get('res.users')
403
404         company_currency_id = res_users_obj.browse(cursor, user, user,
405                 context=context).company_id.currency_id.id
406
407         for reconcile_id in ids:
408             res[reconcile_id] = company_currency_id
409         return res
410
411     def _default_currency(self, cursor, user, context=None):
412         res_users_obj = self.pool.get('res.users')
413
414         return res_users_obj.browse(cursor, user, user,
415                 context=context).company_id.currency_id.id
416
417
418     def _total_second_amount(self, cursor, user, ids, name, attr,
419             context=None):
420         res = {}
421         for reconcile_id in ids:
422             res[reconcile_id] = context.get('amount', 0.0)
423         return res
424
425     def _total_second_currency(self, cursor, user, ids, name, attr, context=None):
426         res = {}
427         for reconcile_id in ids:
428             res[reconcile_id] = context.get('currency_id', False)
429         return res
430
431     def name_get(self, cursor, user, ids, context=None):
432         res= []
433         for o in self.browse(cursor, user, ids, context=context):
434             td = ''
435             if o.total_amount:
436                 td = 'P '
437             res.append((o.id, '%s[%.2f]' % (td, o.total_amount)))
438         return res
439
440     _columns = {
441         'name': fields.char('Date', size=64, required=True),
442         'partner_id': fields.many2one('res.partner', 'Partner', readonly=True),
443         'line_new_ids': fields.one2many('account.bank.statement.reconcile.line',
444             'line_id', 'Write-Off'),
445         'total_entry': fields.function(_total_entry, method=True,
446             string='Total entries'),
447         'total_new': fields.function(_total_new, method=True,
448             string='Total write-off'),
449         'total_second_amount': fields.function(_total_second_amount,
450             method=True, string='Payment amount',
451             help='The amount in the currency of the journal'),
452         'total_second_currency': fields.function(_total_second_currency, method=True,
453             string='Currency', type='many2one', relation='res.currency',
454             help='The currency of the journal'),
455         'total_amount': fields.function(_total_amount, method=True,
456             string='Payment amount'),
457         'total_currency': fields.function(_total_currency, method=True,
458             string='Currency', type='many2one', relation='res.currency'),
459         'total_balance': fields.function(_total_balance, method=True,
460             string='Balance'),
461         #line_ids define in account.py
462         'statement_line': fields.one2many('account.bank.statement.line',
463              'reconcile_id', 'Bank Statement Line'),
464     }
465     _defaults = {
466         'name': lambda *a: time.strftime('%Y-%m-%d'),
467         'partner_id': lambda obj, cursor, user, context=None: \
468                 context.get('partner', False),
469         'total_amount': _default_amount,
470         'total_currency': _default_currency,
471         'total_second_amount':  lambda obj, cursor, user, context=None: \
472                 context.get('amount', 0.0),
473         'total_second_currency': lambda obj, cursor, user, context=None: \
474                 context.get('currency_id', False),
475         'total_balance': _default_amount,
476     }
477 account_bank_statement_reconcile()
478
479 class account_bank_statement_reconcile_line(osv.osv):
480     _name = "account.bank.statement.reconcile.line"
481     _description = "Statement reconcile line"
482     _columns = {
483         'name': fields.char('Description', size=64),
484         'account_id': fields.many2one('account.account', 'Account', required=True),
485         'line_id': fields.many2one('account.bank.statement.reconcile', 'Reconcile'),
486         'amount': fields.float('Amount', required=True),
487     }
488 account_bank_statement_reconcile_line()
489
490
491 class account_bank_statement_line(osv.osv):
492
493     def onchange_partner_id(self, cursor, user, line_id, partner_id, type, currency_id,
494             context={}):
495         if not partner_id:
496             return {}
497         res_currency_obj = self.pool.get('res.currency')
498         res_users_obj = self.pool.get('res.users')
499
500         company_currency_id = res_users_obj.browse(cursor, user, user,
501                 context=context).company_id.currency_id.id
502
503         if not currency_id:
504             currency_id = company_currency_id
505
506         part = self.pool.get('res.partner').browse(cursor, user, partner_id,
507                 context=context)
508         if type == 'supplier':
509             account_id = part.property_account_payable.id
510         else:
511             account_id =  part.property_account_receivable.id
512
513         cursor.execute('SELECT sum(debit-credit) \
514                 FROM account_move_line \
515                 WHERE (reconcile_id is null) \
516                     AND partner_id = %d \
517                     AND account_id=%d', (partner_id, account_id))
518         res = cursor.fetchone()
519         balance = res and res[0] or 0.0
520
521         balance = res_currency_obj.compute(cursor, user, company_currency_id,
522                 currency_id, balance, context=context)
523         return {'value': {'amount': balance, 'account_id': account_id}}
524
525     def _reconcile_amount(self, cursor, user, ids, name, args, context=None):
526         if not ids:
527             return {}
528         res_currency_obj = self.pool.get('res.currency')
529         res_users_obj = self.pool.get('res.users')
530
531         res = {}
532         company_currency_id = res_users_obj.browse(cursor, user, user,
533                 context=context).company_id.currency_id.id
534
535         for line in self.browse(cursor, user, ids, context=context):
536             if line.reconcile_id:
537                 res[line.id] = res_currency_obj.compute(cursor, user,
538                         company_currency_id, line.statement_id.currency.id,
539                         line.reconcile_id.total_entry, context=context)
540             else:
541                 res[line.id] = 0.0
542         return res
543
544     _order = "date,name desc"
545     _name = "account.bank.statement.line"
546     _description = "Bank Statement Line"
547     _columns = {
548         'name': fields.char('Name', size=64, required=True),
549         'date': fields.date('Date', required=True),
550         'amount': fields.float('Amount'),
551         'type': fields.selection([
552             ('supplier','Supplier'),
553             ('customer','Customer'),
554             ('general','General')
555             ], 'Type', required=True),
556         'partner_id': fields.many2one('res.partner', 'Partner'),
557         'account_id': fields.many2one('account.account','Account',
558             required=True),
559         'statement_id': fields.many2one('account.bank.statement', 'Statement',
560             select=True, required=True),
561         'reconcile_id': fields.many2one('account.bank.statement.reconcile',
562             'Reconcile', states={'confirm':[('readonly',True)]}),
563         'move_ids': fields.many2many('account.move',
564             'account_bank_statement_line_move_rel', 'move_id','statement_id',
565             'Moves'),
566         'ref': fields.char('Ref.', size=32),
567         'note': fields.text('Notes'),
568         'reconcile_amount': fields.function(_reconcile_amount,
569             string='Amount reconciled', method=True, type='float'),
570     }
571     _defaults = {
572         'name': lambda self,cr,uid,context={}: self.pool.get('ir.sequence').get(cr, uid, 'account.bank.statement.line'),
573         'date': lambda *a: time.strftime('%Y-%m-%d'),
574         'type': lambda *a: 'general',
575     }
576
577 account_bank_statement_line()
578
579
580
581 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
582