[IMP]: Remove commented code.
[odoo/odoo.git] / addons / account / account_bank_statement.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 import time
23
24 from osv import fields, osv
25 from tools.translate import _
26 import decimal_precision as dp
27
28 class account_bank_statement(osv.osv):
29
30     def create(self, cr, uid, vals, context=None):
31         seq = 0
32         if 'line_ids' in vals:
33             for line in vals['line_ids']:
34                 seq += 1
35                 line[2]['sequence'] = seq
36                 vals[seq - 1] = line
37         return super(account_bank_statement, self).create(cr, uid, vals, context=context)
38
39     def write(self, cr, uid, ids, vals, context=None):
40         res = super(account_bank_statement, self).write(cr, uid, ids, vals, context=context)
41         account_bank_statement_line_obj = self.pool.get('account.bank.statement.line')
42         for statement in self.browse(cr, uid, ids, context):
43             seq = 0
44             for line in statement.line_ids:
45                 seq += 1
46                 if not line.sequence:
47                     account_bank_statement_line_obj.write(cr, uid, [line.id], {'sequence': seq}, context=context)
48         return res
49
50     def button_import_invoice(self, cr, uid, ids, context=None):
51         mod_obj = self.pool.get('ir.model.data')
52         if context is None:
53             context = {}
54         model_data_ids = mod_obj.search(cr, uid, [('model','=','ir.ui.view'),('name','=','view_account_statement_from_invoice')], context=context)
55         resource_id = mod_obj.read(cr, uid, model_data_ids, fields=['res_id'], context=context)[0]['res_id']
56         context.update({'statement_id': ids[0]})
57
58         return {
59             'name': _('Import Invoice'),
60             'context': context,
61             'view_type': 'form',
62             'view_mode': 'tree,form',
63             'res_model': 'account.statement.from.invoice',
64             'views': [(resource_id,'form')],
65             'type': 'ir.actions.act_window',
66             'target': 'new',
67             'nodestroy': True
68         }
69
70     def _default_journal_id(self, cr, uid, context={}):
71         journal_pool = self.pool.get('account.journal')
72         journal_type = context.get('journal_type', False)
73         journal_id = False
74         if journal_type:
75             ids = journal_pool.search(cr, uid, [('type', '=', journal_type)])
76             if ids:
77                 journal_id = ids[0]
78         return journal_id
79
80     def _default_balance_start(self, cr, uid, context={}):
81         cr.execute('select id from account_bank_statement where journal_id=%s order by date desc limit 1', (1,))
82         res = cr.fetchone()
83         if res:
84             return self.browse(cr, uid, [res[0]], context)[0].balance_end
85         return 0.0
86
87     def _end_balance(self, cursor, user, ids, name, attr, context=None):
88         res_currency_obj = self.pool.get('res.currency')
89         res_users_obj = self.pool.get('res.users')
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         account_move_obj = self.pool.get('account.move')
220         account_move_line_obj = self.pool.get('account.move.line')
221         account_bank_statement_line_obj = self.pool.get('account.bank.statement.line')
222         st_line = account_bank_statement_line_obj.browse(cr, uid, st_line_id, context)
223         st = st_line.statement_id
224
225         context.update({'date': st_line.date})
226
227         move_id = account_move_obj.create(cr, uid, {
228             'journal_id': st.journal_id.id,
229             'period_id': st.period_id.id,
230             'date': st_line.date,
231             'name': st_line_number,
232         }, context=context)
233         account_bank_statement_line_obj.write(cr, uid, [st_line.id], {
234             'move_ids': [(4, move_id, False)]
235         })
236
237         torec = []
238         if st_line.amount >= 0:
239             account_id = st.journal_id.default_credit_account_id.id
240         else:
241             account_id = st.journal_id.default_debit_account_id.id
242
243         acc_cur = ((st_line.amount<=0) and st.journal_id.default_debit_account_id) or st_line.account_id
244         amount = res_currency_obj.compute(cr, uid, st.currency.id,
245                 company_currency_id, st_line.amount, context=context,
246                 account=acc_cur)
247
248         val = {
249             'name': st_line.name,
250             'date': st_line.date,
251             'ref': st_line.ref,
252             'move_id': move_id,
253             'partner_id': ((st_line.partner_id) and st_line.partner_id.id) or False,
254             'account_id': (st_line.account_id) and st_line.account_id.id,
255             'credit': ((amount>0) and amount) or 0.0,
256             'debit': ((amount<0) and -amount) or 0.0,
257             'statement_id': st.id,
258             'journal_id': st.journal_id.id,
259             'period_id': st.period_id.id,
260             'currency_id': st.currency.id,
261             'analytic_account_id': st_line.analytic_account_id and st_line.analytic_account_id.id or False
262         }
263
264         amount = res_currency_obj.compute(cr, uid, st.currency.id,
265                 company_currency_id, st_line.amount, context=context,
266                 account=acc_cur)
267         if st.currency.id <> company_currency_id:
268             amount_cur = res_currency_obj.compute(cr, uid, company_currency_id,
269                         st.currency.id, amount, context=context,
270                         account=acc_cur)
271             val['amount_currency'] = -amount_cur
272
273         if st_line.account_id and st_line.account_id.currency_id and st_line.account_id.currency_id.id <> company_currency_id:
274             val['currency_id'] = st_line.account_id.currency_id.id
275             if company_currency_id==st_line.account_id.currency_id.id:
276                 amount_cur = st_line.amount
277             else:
278                 amount_cur = res_currency_obj.compute(cr, uid, company_currency_id,
279                         st_line.account_id.currency_id.id, amount, context=context,
280                         account=acc_cur)
281             val['amount_currency'] = amount_cur
282
283         move_line_id = account_move_line_obj.create(cr, uid, val, context=context)
284         torec.append(move_line_id)
285
286         # Fill the secondary amount/currency
287         # if currency is not the same than the company
288         amount_currency = False
289         currency_id = False
290         if st.currency.id <> company_currency_id:
291             amount_currency = st_line.amount
292             currency_id = st.currency.id
293         account_move_line_obj.create(cr, uid, {
294             'name': st_line.name,
295             'date': st_line.date,
296             'ref': st_line.ref,
297             'move_id': move_id,
298             'partner_id': ((st_line.partner_id) and st_line.partner_id.id) or False,
299             'account_id': account_id,
300             'credit': ((amount < 0) and -amount) or 0.0,
301             'debit': ((amount > 0) and amount) or 0.0,
302             'statement_id': st.id,
303             'journal_id': st.journal_id.id,
304             'period_id': st.period_id.id,
305             'amount_currency': amount_currency,
306             'currency_id': currency_id,
307             }, context=context)
308
309         for line in account_move_line_obj.browse(cr, uid, [x.id for x in
310                 account_move_obj.browse(cr, uid, move_id,
311                     context=context).line_id],
312                 context=context):
313             if line.state <> 'valid':
314                 raise osv.except_osv(_('Error !'),
315                         _('Journal Item "%s" is not valid') % line.name)
316
317         # Bank statements will not consider boolean on journal entry_posted
318         account_move_obj.post(cr, uid, [move_id], context=context)
319         return move_id
320
321     def get_next_st_line_number(self, cr, uid, st_number, st_line, context=None):
322         return st_number + ' - ' + str(st_line.sequence)
323
324     def balance_check(self, cr, uid, st_id, journal_type='bank', context=None):
325         st = self.browse(cr, uid, st_id, context)
326         if not (abs((st.balance_end or 0.0) - st.balance_end_real) < 0.0001):
327             raise osv.except_osv(_('Error !'),
328                     _('The statement balance is incorrect !\n') +
329                     _('The expected balance (%.2f) is different than the computed one. (%.2f)') % (st.balance_end_real, st.balance_end))
330         return True
331
332     def statement_close(self, cr, uid, ids, journal_type='bank', context=None):
333         return self.write(cr, uid, ids, {'state':'confirm'}, context=context)
334
335     def check_status_condition(self, cr, uid, state, journal_type='bank'):
336         return state=='draft'
337
338     def button_confirm_bank(self, cr, uid, ids, context=None):
339         done = []
340         obj_seq = self.pool.get('ir.sequence')
341         if context is None:
342             context = {}
343
344         for st in self.browse(cr, uid, ids, context):
345             j_type = st.journal_id.type
346             company_currency_id = st.journal_id.company_id.currency_id.id
347             if not self.check_status_condition(cr, uid, st.state, journal_type=j_type):
348                 continue
349
350             self.balance_check(cr, uid, st.id, journal_type=j_type, context=context)
351             if (not st.journal_id.default_credit_account_id) \
352                     or (not st.journal_id.default_debit_account_id):
353                 raise osv.except_osv(_('Configuration Error !'),
354                         _('Please verify that an account is defined in the journal.'))
355
356             if not st.name == '/':
357                 st_number = st.name
358             else:
359                 if st.journal_id.sequence_id:
360                     c = {'fiscalyear_id': st.period_id.fiscalyear_id.id}
361                     st_number = obj_seq.get_id(cr, uid, st.journal_id.sequence_id.id, context=c)
362                 else:
363                     st_number = obj_seq.get(cr, uid, 'account.bank.statement')
364
365             for line in st.move_line_ids:
366                 if line.state <> 'valid':
367                     raise osv.except_osv(_('Error !'),
368                             _('The account entries lines are not in valid state.'))
369             for st_line in st.line_ids:
370                 if st_line.analytic_account_id:
371                     if not st.journal_id.analytic_journal_id:
372                         raise osv.except_osv(_('No Analytic Journal !'),_("You have to define an analytic journal on the '%s' journal!") % (st.journal_id.name,))
373                 if not st_line.amount:
374                     continue
375                 st_line_number = self.get_next_st_line_number(cr, uid, st_number, st_line, context)
376                 self.create_move_from_st_line(cr, uid, st_line.id, company_currency_id, st_line_number, context)
377
378             self.write(cr, uid, [st.id], {'name': st_number}, context=context)
379             self.log(cr, uid, st.id, _('Statement %s is confirmed, journal items are created.') % (st_number,))
380             done.append(st.id)
381         return self.write(cr, uid, ids, {'state':'confirm'}, context=context)
382
383     def button_cancel(self, cr, uid, ids, context=None):
384         done = []
385         account_move_obj = self.pool.get('account.move')
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             account_move_obj.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         cursor.execute('SELECT balance_end_real \
398                 FROM account_bank_statement \
399                 WHERE journal_id = %s AND NOT state = %s \
400                 ORDER BY date DESC,id DESC LIMIT 1', (journal_id, 'draft'))
401         res = cursor.fetchone()
402         balance_start = res and res[0] or 0.0
403         return {'value': {'balance_start': balance_start}}
404
405     def unlink(self, cr, uid, ids, context=None):
406         stat = self.read(cr, uid, ids, ['state'])
407         unlink_ids = []
408         for t in stat:
409             if t['state'] in ('draft'):
410                 unlink_ids.append(t['id'])
411             else:
412                 raise osv.except_osv(_('Invalid action !'), _('Cannot delete bank statement(s) which are already confirmed !'))
413         osv.osv.unlink(self, cr, uid, unlink_ids, context=context)
414         return True
415
416     def copy(self, cr, uid, id, default=None, context=None):
417         if default is None:
418             default = {}
419         if context is None:
420             context = {}
421         default = default.copy()
422         default['move_line_ids'] = []
423         return super(account_bank_statement, self).copy(cr, uid, id, default, context=context)
424
425 account_bank_statement()
426
427 class account_bank_statement_line(osv.osv):
428
429     def onchange_partner_id(self, cursor, user, line_id, partner_id, type, currency_id, context=None):
430         res_users_obj = self.pool.get('res.users')
431         res_currency_obj = self.pool.get('res.currency')
432         res = {'value': {}}
433         obj_partner = self.pool.get('res.partner')
434         if context is None:
435             context = {}
436         if not partner_id:
437             return res
438         account_id = False
439         line = self.browse(cursor, user, line_id)
440         if not line or (line and not line[0].account_id):
441             part = obj_partner.browse(cursor, user, partner_id, context=context)
442             if type == 'supplier':
443                 account_id = part.property_account_payable.id
444             else:
445                 account_id = part.property_account_receivable.id
446             res['value']['account_id'] = account_id
447
448         if account_id and (not line or (line and not line[0].amount)) and not context.get('amount', False):
449             company_currency_id = res_users_obj.browse(cursor, user, user,
450                     context=context).company_id.currency_id.id
451             if not currency_id:
452                 currency_id = company_currency_id
453
454             cursor.execute('SELECT sum(debit-credit) \
455                 FROM account_move_line \
456                 WHERE (reconcile_id is null) \
457                     AND partner_id = %s \
458                     AND account_id=%s', (partner_id, account_id))
459             pgres = cursor.fetchone()
460             balance = pgres and pgres[0] or 0.0
461
462             balance = res_currency_obj.compute(cursor, user, company_currency_id,
463                 currency_id, balance, context=context)
464             res['value']['amount'] = balance
465         return res
466
467     _order = "statement_id desc, sequence"
468     _name = "account.bank.statement.line"
469     _description = "Bank Statement Line"
470     _columns = {
471         'name': fields.char('Name', size=64, required=True),
472         'date': fields.date('Date', required=True),
473         'amount': fields.float('Amount'),
474         'type': fields.selection([
475             ('supplier','Supplier'),
476             ('customer','Customer'),
477             ('general','General')
478             ], 'Type', required=True),
479         'partner_id': fields.many2one('res.partner', 'Partner'),
480         'account_id': fields.many2one('account.account','Account',
481             required=True),
482         'statement_id': fields.many2one('account.bank.statement', 'Statement',
483             select=True, required=True, ondelete='cascade'),
484         'analytic_account_id': fields.many2one('account.analytic.account', 'Analytic Account'),
485         'move_ids': fields.many2many('account.move',
486             'account_bank_statement_line_move_rel', 'move_id','statement_id',
487             'Moves'),
488         'ref': fields.char('Reference', size=32),
489         'note': fields.text('Notes'),
490         'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of bank statement lines."),
491         'company_id': fields.related('statement_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True),
492     }
493     _defaults = {
494         'name': lambda self,cr,uid,context={}: self.pool.get('ir.sequence').get(cr, uid, 'account.bank.statement.line'),
495         'date': time.strftime('%Y-%m-%d'),
496         'type': 'general',
497     }
498
499 account_bank_statement_line()
500
501 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: