[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         for statement in self.browse(cr, uid, ids, context):
42             seq = 0
43             for line in statement.line_ids:
44                 seq += 1
45                 if not line.sequence:
46                     self.pool.get('account.bank.statement.line').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"
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': 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         res_users_obj = self.pool.get('res.users')
219         account_move_obj = self.pool.get('account.move')
220         account_move_line_obj = self.pool.get('account.move.line')
221         account_analytic_line_obj = self.pool.get('account.analytic.line')
222         account_bank_statement_line_obj = self.pool.get('account.bank.statement.line')
223         st_line = account_bank_statement_line_obj.browse(cr, uid, st_line_id, context)
224         st = st_line.statement_id
225
226         context.update({'date': st_line.date})
227
228         move_id = account_move_obj.create(cr, uid, {
229             'journal_id': st.journal_id.id,
230             'period_id': st.period_id.id,
231             'date': st_line.date,
232             'name': st_line_number,
233         }, context=context)
234         account_bank_statement_line_obj.write(cr, uid, [st_line.id], {
235             'move_ids': [(4, move_id, False)]
236         })
237
238         torec = []
239         if st_line.amount >= 0:
240             account_id = st.journal_id.default_credit_account_id.id
241         else:
242             account_id = st.journal_id.default_debit_account_id.id
243
244         acc_cur = ((st_line.amount<=0) and st.journal_id.default_debit_account_id) or st_line.account_id
245         amount = res_currency_obj.compute(cr, uid, st.currency.id,
246                 company_currency_id, st_line.amount, context=context,
247                 account=acc_cur)
248
249         val = {
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': (st_line.account_id) and st_line.account_id.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             'currency_id': st.currency.id,
262             'analytic_account_id': st_line.analytic_account_id and st_line.analytic_account_id.id or False
263         }
264
265         amount = res_currency_obj.compute(cr, uid, st.currency.id,
266                 company_currency_id, st_line.amount, context=context,
267                 account=acc_cur)
268         if st.currency.id <> company_currency_id:
269             amount_cur = res_currency_obj.compute(cr, uid, company_currency_id,
270                         st.currency.id, amount, context=context,
271                         account=acc_cur)
272             val['amount_currency'] = -amount_cur
273
274         if st_line.account_id and st_line.account_id.currency_id and st_line.account_id.currency_id.id <> company_currency_id:
275             val['currency_id'] = st_line.account_id.currency_id.id
276             if company_currency_id==st_line.account_id.currency_id.id:
277                 amount_cur = st_line.amount
278             else:
279                 amount_cur = res_currency_obj.compute(cr, uid, company_currency_id,
280                         st_line.account_id.currency_id.id, amount, context=context,
281                         account=acc_cur)
282             val['amount_currency'] = amount_cur
283
284         move_line_id = account_move_line_obj.create(cr, uid, val, context=context)
285         torec.append(move_line_id)
286
287         # Fill the secondary amount/currency
288         # if currency is not the same than the company
289         amount_currency = False
290         currency_id = False
291         if st.currency.id <> company_currency_id:
292             amount_currency = st_line.amount
293             currency_id = st.currency.id
294         account_move_line_obj.create(cr, uid, {
295             'name': st_line.name,
296             'date': st_line.date,
297             'ref': st_line.ref,
298             'move_id': move_id,
299             'partner_id': ((st_line.partner_id) and st_line.partner_id.id) or False,
300             'account_id': account_id,
301             'credit': ((amount < 0) and -amount) or 0.0,
302             'debit': ((amount > 0) and amount) or 0.0,
303             'statement_id': st.id,
304             'journal_id': st.journal_id.id,
305             'period_id': st.period_id.id,
306             'amount_currency': amount_currency,
307             'currency_id': currency_id,
308             }, context=context)
309
310         for line in account_move_line_obj.browse(cr, uid, [x.id for x in
311                 account_move_obj.browse(cr, uid, move_id,
312                     context=context).line_id],
313                 context=context):
314             if line.state <> 'valid':
315                 raise osv.except_osv(_('Error !'),
316                         _('Journal Item "%s" is not valid') % line.name)
317
318         # Bank statements will not consider boolean on journal entry_posted
319         account_move_obj.post(cr, uid, [move_id], context=context)
320         return move_id
321
322     def get_next_st_line_number(self, cr, uid, st_number, st_line, context=None):
323         return st_number + ' - ' + str(st_line.sequence)
324
325     def balance_check(self, cr, uid, st_id, journal_type='bank', context=None):
326         st = self.browse(cr, uid, st_id, context)
327         if not (abs((st.balance_end or 0.0) - st.balance_end_real) < 0.0001):
328             raise osv.except_osv(_('Error !'),
329                     _('The statement balance is incorrect !\n') +
330                     _('The expected balance (%.2f) is different than the computed one. (%.2f)') % (st.balance_end_real, st.balance_end))
331         return True
332
333     def statement_close(self, cr, uid, ids, journal_type='bank', context=None):
334         return self.write(cr, uid, ids, {'state':'confirm'}, context=context)
335
336     def check_status_condition(self, cr, uid, state, journal_type='bank'):
337         return state=='draft'
338
339     def button_confirm_bank(self, cr, uid, ids, context=None):
340         done = []
341         obj_seq = self.pool.get('ir.sequence')
342         if context is None:
343             context = {}
344
345         for st in self.browse(cr, uid, ids, context):
346             j_type = st.journal_id.type
347             company_currency_id = st.journal_id.company_id.currency_id.id
348             if not self.check_status_condition(cr, uid, st.state, journal_type=j_type):
349                 continue
350
351             self.balance_check(cr, uid, st.id, journal_type=j_type, context=context)
352             if (not st.journal_id.default_credit_account_id) \
353                     or (not st.journal_id.default_debit_account_id):
354                 raise osv.except_osv(_('Configuration Error !'),
355                         _('Please verify that an account is defined in the journal.'))
356
357             if not st.name == '/':
358                 st_number = st.name
359             else:
360                 if st.journal_id.sequence_id:
361                     c = {'fiscalyear_id': st.period_id.fiscalyear_id.id}
362                     st_number = obj_seq.get_id(cr, uid, st.journal_id.sequence_id.id, context=c)
363                 else:
364                     st_number = obj_seq.get(cr, uid, 'account.bank.statement')
365
366             for line in st.move_line_ids:
367                 if line.state <> 'valid':
368                     raise osv.except_osv(_('Error !'),
369                             _('The account entries lines are not in valid state.'))
370             for st_line in st.line_ids:
371                 if st_line.analytic_account_id:
372                     if not st.journal_id.analytic_journal_id:
373                         raise osv.except_osv(_('No Analytic Journal !'),_("You have to define an analytic journal on the '%s' journal!") % (st.journal_id.name,))
374                 if not st_line.amount:
375                     continue
376                 st_line_number = self.get_next_st_line_number(cr, uid, st_number, st_line, context)
377                 self.create_move_from_st_line(cr, uid, st_line.id, company_currency_id, st_line_number, context)
378
379             self.write(cr, uid, [st.id], {'name': st_number}, context=context)
380             self.log(cr, uid, st.id, _('Statement %s is confirmed and entries are created.') % st_number)
381             done.append(st.id)
382         return self.write(cr, uid, ids, {'state':'confirm'}, context=context)
383
384     def button_cancel(self, cr, uid, ids, context=None):
385         done = []
386         for st in self.browse(cr, uid, ids, context):
387             if st.state=='draft':
388                 continue
389             ids = []
390             for line in st.line_ids:
391                 ids += [x.id for x in line.move_ids]
392             self.pool.get('account.move').unlink(cr, uid, ids, context)
393             done.append(st.id)
394         return self.write(cr, uid, done, {'state':'draft'}, context=context)
395
396     def onchange_journal_id(self, cursor, user, statement_id, journal_id, context=None):
397         account_journal_obj = self.pool.get('account.journal')
398         res_users_obj = self.pool.get('res.users')
399         cursor.execute('SELECT balance_end_real \
400                 FROM account_bank_statement \
401                 WHERE journal_id = %s AND NOT state = %s \
402                 ORDER BY date DESC,id DESC LIMIT 1', (journal_id, 'draft'))
403         res = cursor.fetchone()
404         balance_start = res and res[0] or 0.0
405         return {'value': {'balance_start': balance_start}}
406
407     def unlink(self, cr, uid, ids, context=None):
408         stat = self.read(cr, uid, ids, ['state'])
409         unlink_ids = []
410         for t in stat:
411             if t['state'] in ('draft'):
412                 unlink_ids.append(t['id'])
413             else:
414                 raise osv.except_osv(_('Invalid action !'), _('Cannot delete bank statement(s) which are already confirmed !'))
415         osv.osv.unlink(self, cr, uid, unlink_ids, context=context)
416         return True
417
418     def copy(self, cr, uid, id, default=None, context=None):
419         if default is None:
420             default = {}
421         if context is None:
422             context = {}
423         default = default.copy()
424         default['move_line_ids'] = []
425         return super(account_bank_statement, self).copy(cr, uid, id, default, context=context)
426
427 account_bank_statement()
428
429 class account_bank_statement_line(osv.osv):
430
431     def onchange_partner_id(self, cursor, user, line_id, partner_id, type, currency_id, context=None):
432         res_users_obj = self.pool.get('res.users')
433         res_currency_obj = self.pool.get('res.currency')
434         res = {'value': {}}
435         obj_partner = self.pool.get('res.partner')
436         if context is None:
437             context = {}
438         if not partner_id:
439             return res
440         account_id = False
441         line = self.browse(cursor, user, line_id)
442         if not line or (line and not line[0].account_id):
443             part = obj_partner.browse(cursor, user, partner_id, context=context)
444             if type == 'supplier':
445                 account_id = part.property_account_payable.id
446             else:
447                 account_id = part.property_account_receivable.id
448             res['value']['account_id'] = account_id
449
450         if account_id and (not line or (line and not line[0].amount)) and not context.get('amount', False):
451             company_currency_id = res_users_obj.browse(cursor, user, user,
452                     context=context).company_id.currency_id.id
453             if not currency_id:
454                 currency_id = company_currency_id
455
456             cursor.execute('SELECT sum(debit-credit) \
457                 FROM account_move_line \
458                 WHERE (reconcile_id is null) \
459                     AND partner_id = %s \
460                     AND account_id=%s', (partner_id, account_id))
461             pgres = cursor.fetchone()
462             balance = pgres and pgres[0] or 0.0
463
464             balance = res_currency_obj.compute(cursor, user, company_currency_id,
465                 currency_id, balance, context=context)
466             res['value']['amount'] = balance
467         return res
468
469     _order = "statement_id desc, sequence"
470     _name = "account.bank.statement.line"
471     _description = "Bank Statement Line"
472     _columns = {
473         'name': fields.char('Name', size=64, required=True),
474         'date': fields.date('Date', required=True),
475         'amount': fields.float('Amount'),
476         'type': fields.selection([
477             ('supplier','Supplier'),
478             ('customer','Customer'),
479             ('general','General')
480             ], 'Type', required=True),
481         'partner_id': fields.many2one('res.partner', 'Partner'),
482         'account_id': fields.many2one('account.account','Account',
483             required=True),
484         'statement_id': fields.many2one('account.bank.statement', 'Statement',
485             select=True, required=True, ondelete='cascade'),
486         'analytic_account_id': fields.many2one('account.analytic.account', 'Analytic Account'),
487         'move_ids': fields.many2many('account.move',
488             'account_bank_statement_line_move_rel', 'move_id','statement_id',
489             'Moves'),
490         'ref': fields.char('Reference', size=32),
491         'note': fields.text('Notes'),
492         'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of bank statement lines."),
493         'company_id': fields.related('statement_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True),
494     }
495     _defaults = {
496         'name': lambda self,cr,uid,context={}: self.pool.get('ir.sequence').get(cr, uid, 'account.bank.statement.line'),
497         'date': time.strftime('%Y-%m-%d'),
498         'type': 'general',
499     }
500
501 account_bank_statement_line()
502
503 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: