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