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