[IMP] removal of usages of the deprecated node.getchildren call, better usage of...
[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-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 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=%s 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             # for bank.statement.lines
174             # In line we get reconcile_id on bank.ste.rec.
175             # in bank stat.rec we get line_new_ids on bank.stat.rec.line
176             for move in st.line_ids:
177                 move_id = account_move_obj.create(cr, uid, {
178                     'journal_id': st.journal_id.id,
179                     'period_id': st.period_id.id,
180                 }, context=context)
181                 account_bank_statement_line_obj.write(cr, uid, [move.id], {
182                     'move_ids': [(4,move_id, False)]
183                 })
184                 if not move.amount:
185                     continue
186
187                 torec = []
188                 if move.amount >= 0:
189                     account_id = st.journal_id.default_credit_account_id.id
190                 else:
191                     account_id = st.journal_id.default_debit_account_id.id
192                 acc_cur = ((move.amount<=0) and st.journal_id.default_debit_account_id) or move.account_id
193                 amount = res_currency_obj.compute(cr, uid, st.currency.id,
194                         company_currency_id, move.amount, context=context,
195                         account=acc_cur)
196                 if move.reconcile_id and move.reconcile_id.line_new_ids:
197                     for newline in move.reconcile_id.line_new_ids:
198                         amount += newline.amount
199
200                 val = {
201                     'name': move.name,
202                     'date': move.date,
203                     'ref': move.ref,
204                     'move_id': move_id,
205                     'partner_id': ((move.partner_id) and move.partner_id.id) or False,
206                     'account_id': (move.account_id) and move.account_id.id,
207                     'credit': ((amount>0) and amount) or 0.0,
208                     'debit': ((amount<0) and -amount) or 0.0,
209                     'statement_id': st.id,
210                     'journal_id': st.journal_id.id,
211                     'period_id': st.period_id.id,
212                     'currency_id': st.currency.id,
213                 }
214                 
215                 amount = res_currency_obj.compute(cr, uid, st.currency.id,
216                         company_currency_id, move.amount, context=context,
217                         account=acc_cur)
218                 if st.currency.id <> company_currency_id:
219                     amount_cur = res_currency_obj.compute(cr, uid, company_currency_id,
220                                 st.currency.id, amount, context=context,
221                                 account=acc_cur)
222                     val['amount_currency'] = -amount_cur
223
224                 if move.account_id and move.account_id.currency_id and move.account_id.currency_id.id <> company_currency_id:
225                     val['currency_id'] = move.account_id.currency_id.id
226                     if company_currency_id==move.account_id.currency_id.id:
227                         amount_cur = move.amount
228                     else:
229                         amount_cur = res_currency_obj.compute(cr, uid, company_currency_id,
230                                 move.account_id.currency_id.id, amount, context=context,
231                                 account=acc_cur)
232                     val['amount_currency'] = amount_cur
233
234                 torec.append(account_move_line_obj.create(cr, uid, val , context=context))
235
236                 if move.reconcile_id and move.reconcile_id.line_new_ids:
237                     for newline in move.reconcile_id.line_new_ids:
238                         account_move_line_obj.create(cr, uid, {
239                             'name': newline.name or move.name,
240                             'date': move.date,
241                             'ref': move.ref,
242                             'move_id': move_id,
243                             'partner_id': ((move.partner_id) and move.partner_id.id) or False,
244                             'account_id': (newline.account_id) and newline.account_id.id,
245                             'debit': newline.amount>0 and newline.amount or 0.0,
246                             'credit': newline.amount<0 and -newline.amount or 0.0,
247                             'statement_id': st.id,
248                             'journal_id': st.journal_id.id,
249                             'period_id': st.period_id.id,
250
251                         }, context=context)
252
253                 # Fill the secondary amount/currency
254                 # if currency is not the same than the company
255                 amount_currency = False
256                 currency_id = False
257                 if st.currency.id <> company_currency_id:
258                     amount_currency = move.amount
259                     currency_id = st.currency.id
260                 account_move_line_obj.create(cr, uid, {
261                     'name': move.name,
262                     'date': move.date,
263                     'ref': move.ref,
264                     'move_id': move_id,
265                     'partner_id': ((move.partner_id) and move.partner_id.id) or False,
266                     'account_id': account_id,
267                     'credit': ((amount < 0) and -amount) or 0.0,
268                     'debit': ((amount > 0) and amount) or 0.0,
269                     'statement_id': st.id,
270                     'journal_id': st.journal_id.id,
271                     'period_id': st.period_id.id,
272                     'amount_currency': amount_currency,
273                     'currency_id': currency_id,
274                     }, context=context)
275
276                 for line in account_move_line_obj.browse(cr, uid, [x.id for x in
277                         account_move_obj.browse(cr, uid, move_id,
278                             context=context).line_id],
279                         context=context):
280                     if line.state <> 'valid':
281                         raise osv.except_osv(_('Error !'),
282                                 _('Account move line "%s" is not valid') % line.name)
283
284                 if move.reconcile_id and move.reconcile_id.line_ids:
285                     torec += map(lambda x: x.id, move.reconcile_id.line_ids)
286                     #try:
287                     if abs(move.reconcile_amount-move.amount)<0.0001:
288                         account_move_line_obj.reconcile(cr, uid, torec, 'statement', writeoff_period_id=st.period_id.id, writeoff_journal_id=st.journal_id.id, context=context)
289                     else:
290                         account_move_line_obj.reconcile_partial(cr, uid, torec, 'statement', context)
291                     #except:
292                     #    raise osv.except_osv(_('Error !'), _('Unable to reconcile entry "%s": %.2f') % (move.name, move.amount))
293
294                 if st.journal_id.entry_posted:
295                     account_move_obj.write(cr, uid, [move_id], {'state':'posted'})
296             done.append(st.id)
297         self.write(cr, uid, done, {'state':'confirm'}, context=context)
298         return True
299
300     def button_cancel(self, cr, uid, ids, context={}):
301         done = []
302         for st in self.browse(cr, uid, ids, context):
303             if st.state=='draft':
304                 continue
305             ids = []
306             for line in st.line_ids:
307                 ids += [x.id for x in line.move_ids]
308             self.pool.get('account.move').unlink(cr, uid, ids, context)
309             done.append(st.id)
310         self.write(cr, uid, done, {'state':'draft'}, context=context)
311         return True
312
313     def onchange_journal_id(self, cursor, user, statement_id, journal_id, context=None):
314         if not journal_id:
315             return {'value': {'currency': False}}
316
317         account_journal_obj = self.pool.get('account.journal')
318         res_users_obj = self.pool.get('res.users')
319         res_currency_obj = self.pool.get('res.currency')
320
321         cursor.execute('SELECT balance_end_real \
322                 FROM account_bank_statement \
323                 WHERE journal_id = %s \
324                 ORDER BY date DESC,id DESC LIMIT 1', (journal_id,))
325         res = cursor.fetchone()
326         balance_start = res and res[0] or 0.0
327
328         currency_id = account_journal_obj.browse(cursor, user, journal_id,
329                 context=context).currency.id
330         if not currency_id:
331             currency_id = res_users_obj.browse(cursor, user, user,
332                     context=context).company_id.currency_id.id
333         currency = res_currency_obj.name_get(cursor, user, [currency_id],
334                 context=context)[0]
335         return {'value': {'balance_start': balance_start, 'currency': currency}}
336
337 account_bank_statement()
338
339
340 class account_bank_statement_reconcile(osv.osv):
341     _name = "account.bank.statement.reconcile"
342     _description = "Statement reconcile"
343
344     def _total_entry(self, cursor, user, ids, name, attr, context=None):
345         result = {}
346         for o in self.browse(cursor, user, ids, context=context):
347             result[o.id] = 0.0
348             for line in o.line_ids:
349                 result[o.id] += line.debit - line.credit
350         return result
351
352     def _total_new(self, cursor, user, ids, name, attr, context=None):
353         result = {}
354         for o in self.browse(cursor, user, ids, context=context):
355             result[o.id] = 0.0
356             for line in o.line_new_ids:
357                 result[o.id] += line.amount
358         return result
359
360     def _total_balance(self, cursor, user, ids, name, attr, context=None):
361         result = {}
362         for o in self.browse(cursor, user, ids, context=context):
363             result[o.id] = o.total_new - o.total_entry + o.total_amount
364         return result
365
366     def _total_amount(self, cursor, user, ids, name, attr, context=None):
367         res = {}
368         res_currency_obj = self.pool.get('res.currency')
369         res_users_obj = self.pool.get('res.users')
370
371         company_currency_id = res_users_obj.browse(cursor, user, user,
372                 context=context).company_id.currency_id.id
373         currency_id = context.get('currency_id', company_currency_id)
374
375         acc_cur = None
376         if context.get('journal_id', False) and context.get('account_id',False):
377             st =self.pool.get('account.journal').browse(cursor, user, context['journal_id'])
378             acc = self.pool.get('account.account').browse(cursor, user, context['account_id'])
379             acc_cur = (( context.get('amount',0.0)<=0) and st.default_debit_account_id) or acc
380
381         for reconcile_id in ids:
382             res[reconcile_id] = res_currency_obj.compute(cursor, user,
383                     currency_id, company_currency_id,
384                     context.get('amount', 0.0), context=context, account=acc_cur)
385         return res
386
387     def _default_amount(self, cursor, user, context=None):
388         if context is None:
389             context = {}
390         res_currency_obj = self.pool.get('res.currency')
391         res_users_obj = self.pool.get('res.users')
392
393         company_currency_id = res_users_obj.browse(cursor, user, user,
394                 context=context).company_id.currency_id.id
395         currency_id = context.get('currency_id', company_currency_id)
396
397         acc_cur = None
398         if context.get('journal_id', False) and context.get('account_id',False):
399             st =self.pool.get('account.journal').browse(cursor, user, context['journal_id'])
400             acc = self.pool.get('account.account').browse(cursor, user, context['account_id'])
401             acc_cur = (( context.get('amount',0.0)<=0) and st.default_debit_account_id) or acc
402
403         return res_currency_obj.compute(cursor, user,
404                 currency_id, company_currency_id,
405                 context.get('amount', 0.0), context=context, account=acc_cur)
406
407     def _total_currency(self, cursor, user, ids, name, attrs, context=None):
408         res = {}
409         res_users_obj = self.pool.get('res.users')
410
411         company_currency_id = res_users_obj.browse(cursor, user, user,
412                 context=context).company_id.currency_id.id
413
414         for reconcile_id in ids:
415             res[reconcile_id] = company_currency_id
416         return res
417
418     def _default_currency(self, cursor, user, context=None):
419         res_users_obj = self.pool.get('res.users')
420
421         return res_users_obj.browse(cursor, user, user,
422                 context=context).company_id.currency_id.id
423
424
425     def _total_second_amount(self, cursor, user, ids, name, attr,
426             context=None):
427         res = {}
428         for reconcile_id in ids:
429             res[reconcile_id] = context.get('amount', 0.0)
430         return res
431
432     def _total_second_currency(self, cursor, user, ids, name, attr, context=None):
433         res = {}
434         for reconcile_id in ids:
435             res[reconcile_id] = context.get('currency_id', False)
436         return res
437
438     def name_get(self, cursor, user, ids, context=None):
439         res= []
440         for o in self.browse(cursor, user, ids, context=context):
441             result = 0.0
442             res_currency = ''
443             for line in o.line_ids:
444                 if line.amount_currency and line.currency_id:
445                     result += line.amount_currency
446                     res_currency = line.currency_id.code
447                 else:
448                     result += line.debit - line.credit
449             if res_currency:
450                 res_currency = ' ' + res_currency
451             res.append((o.id, '[%.2f'% (result - o.total_new,) + res_currency + ']' ))
452         return res
453
454     _columns = {
455         'name': fields.char('Date', size=64, required=True),
456         'partner_id': fields.many2one('res.partner', 'Partner', readonly=True),
457         'line_new_ids': fields.one2many('account.bank.statement.reconcile.line',
458             'line_id', 'Write-Off'),
459         'total_entry': fields.function(_total_entry, method=True,
460             string='Total entries'),
461         'total_new': fields.function(_total_new, method=True,
462             string='Total write-off'),
463         'total_second_amount': fields.function(_total_second_amount,
464             method=True, string='Payment amount',
465             help='The amount in the currency of the journal'),
466         'total_second_currency': fields.function(_total_second_currency, method=True,
467             string='Currency', type='many2one', relation='res.currency',
468             help='The currency of the journal'),
469         'total_amount': fields.function(_total_amount, method=True,
470             string='Payment amount'),
471         'total_currency': fields.function(_total_currency, method=True,
472             string='Currency', type='many2one', relation='res.currency'),
473         'total_balance': fields.function(_total_balance, method=True,
474             string='Balance'),
475         #line_ids define in account.py
476         'statement_line': fields.one2many('account.bank.statement.line',
477              'reconcile_id', 'Bank Statement Line'),
478     }
479     _defaults = {
480         'name': lambda *a: time.strftime('%Y-%m-%d'),
481         'partner_id': lambda obj, cursor, user, context=None: \
482                 context.get('partner', False),
483         'total_amount': _default_amount,
484         'total_currency': _default_currency,
485         'total_second_amount':  lambda obj, cursor, user, context=None: \
486                 context.get('amount', 0.0),
487         'total_second_currency': lambda obj, cursor, user, context=None: \
488                 context.get('currency_id', False),
489         'total_balance': _default_amount,
490     }
491 account_bank_statement_reconcile()
492
493 class account_bank_statement_reconcile_line(osv.osv):
494     _name = "account.bank.statement.reconcile.line"
495     _description = "Statement reconcile line"
496     _columns = {
497         'name': fields.char('Description', size=64, required=True),
498         'account_id': fields.many2one('account.account', 'Account', required=True),
499         'line_id': fields.many2one('account.bank.statement.reconcile', 'Reconcile'),
500         'amount': fields.float('Amount', required=True),
501     }
502     _defaults = {
503         'name': lambda *a: 'Write-Off',
504     }
505 account_bank_statement_reconcile_line()
506
507
508 class account_bank_statement_line(osv.osv):
509
510     def onchange_partner_id(self, cursor, user, line_id, partner_id, type, currency_id,
511             context={}):
512         if not partner_id:
513             return {}
514         res_currency_obj = self.pool.get('res.currency')
515         res_users_obj = self.pool.get('res.users')
516
517         company_currency_id = res_users_obj.browse(cursor, user, user,
518                 context=context).company_id.currency_id.id
519
520         if not currency_id:
521             currency_id = company_currency_id
522
523         part = self.pool.get('res.partner').browse(cursor, user, partner_id,
524                 context=context)
525         if type == 'supplier':
526             account_id = part.property_account_payable.id
527         else:
528             account_id =  part.property_account_receivable.id
529
530         cursor.execute('SELECT sum(debit-credit) \
531                 FROM account_move_line \
532                 WHERE (reconcile_id is null) \
533                     AND partner_id = %s \
534                     AND account_id=%s', (partner_id, account_id))
535         res = cursor.fetchone()
536         balance = res and res[0] or 0.0
537
538         balance = res_currency_obj.compute(cursor, user, company_currency_id,
539                 currency_id, balance, context=context)
540         return {'value': {'amount': balance, 'account_id': account_id}}
541
542     def _reconcile_amount(self, cursor, user, ids, name, args, context=None):
543         if not ids:
544             return {}
545         res_currency_obj = self.pool.get('res.currency')
546         res_users_obj = self.pool.get('res.users')
547
548         res = {}
549         company_currency_id = res_users_obj.browse(cursor, user, user,
550                 context=context).company_id.currency_id.id
551
552         for line in self.browse(cursor, user, ids, context=context):
553             if line.reconcile_id:
554                 res[line.id] = res_currency_obj.compute(cursor, user,
555                         company_currency_id, line.statement_id.currency.id,
556                         line.reconcile_id.total_entry, context=context)
557             else:
558                 res[line.id] = 0.0
559         return res
560
561     _order = "date,name desc"
562     _name = "account.bank.statement.line"
563     _description = "Bank Statement Line"
564     _columns = {
565         'name': fields.char('Name', size=64, required=True),
566         'date': fields.date('Date', required=True),
567         'amount': fields.float('Amount'),
568         'type': fields.selection([
569             ('supplier','Supplier'),
570             ('customer','Customer'),
571             ('general','General')
572             ], 'Type', required=True),
573         'partner_id': fields.many2one('res.partner', 'Partner'),
574         'account_id': fields.many2one('account.account','Account',
575             required=True),
576         'statement_id': fields.many2one('account.bank.statement', 'Statement',
577             select=True, required=True),
578         'reconcile_id': fields.many2one('account.bank.statement.reconcile',
579             'Reconcile', states={'confirm':[('readonly',True)]}),
580         'move_ids': fields.many2many('account.move',
581             'account_bank_statement_line_move_rel', 'move_id','statement_id',
582             'Moves'),
583         'ref': fields.char('Ref.', size=32),
584         'note': fields.text('Notes'),
585         'reconcile_amount': fields.function(_reconcile_amount,
586             string='Amount reconciled', method=True, type='float'),
587     }
588     _defaults = {
589         'name': lambda self,cr,uid,context={}: self.pool.get('ir.sequence').get(cr, uid, 'account.bank.statement.line'),
590         'date': lambda *a: time.strftime('%Y-%m-%d'),
591         'type': lambda *a: 'general',
592     }
593
594 account_bank_statement_line()
595
596
597
598 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
599