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