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