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