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