4d9c3f3efbdec77f444ee9662588a583020c8b28
[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 from openerp.osv import fields, osv
23 from openerp.tools.translate import _
24 import openerp.addons.decimal_precision as dp
25 from openerp.report import report_sxw
26
27 class account_bank_statement(osv.osv):
28     def create(self, cr, uid, vals, context=None):
29         if vals.get('name', '/') == '/':
30             journal_id = vals.get('journal_id', self._default_journal_id(cr, uid, context=context))
31             vals['name'] = self._compute_default_statement_name(cr, uid, journal_id, context=context)
32         if 'line_ids' in vals:
33             for idx, line in enumerate(vals['line_ids']):
34                 line[2]['sequence'] = idx + 1
35         return super(account_bank_statement, self).create(cr, uid, vals, context=context)
36
37     def write(self, cr, uid, ids, vals, context=None):
38         res = super(account_bank_statement, self).write(cr, uid, ids, vals, context=context)
39         account_bank_statement_line_obj = self.pool.get('account.bank.statement.line')
40         for statement in self.browse(cr, uid, ids, context):
41             for idx, line in enumerate(statement.line_ids):
42                 account_bank_statement_line_obj.write(cr, uid, [line.id], {'sequence': idx + 1}, context=context)
43         return res
44
45     def _default_journal_id(self, cr, uid, context=None):
46         if context is None:
47             context = {}
48         journal_pool = self.pool.get('account.journal')
49         journal_type = context.get('journal_type', False)
50         company_id = self.pool.get('res.company')._company_default_get(cr, uid, 'account.bank.statement',context=context)
51         if journal_type:
52             ids = journal_pool.search(cr, uid, [('type', '=', journal_type),('company_id','=',company_id)])
53             if ids:
54                 return ids[0]
55         return False
56
57     def _end_balance(self, cursor, user, ids, name, attr, context=None):
58         res = {}
59         for statement in self.browse(cursor, user, ids, context=context):
60             res[statement.id] = statement.balance_start
61             for line in statement.line_ids:
62                 res[statement.id] += line.amount
63         return res
64
65     def _get_period(self, cr, uid, context=None):
66         periods = self.pool.get('account.period').find(cr, uid, context=context)
67         if periods:
68             return periods[0]
69         return False
70
71     def _compute_default_statement_name(self, cr, uid, journal_id, context=None):
72         context = dict(context or {})
73         obj_seq = self.pool.get('ir.sequence')
74         period = self.pool.get('account.period').browse(cr, uid, self._get_period(cr, uid, context=context), context=context)
75         context['fiscalyear_id'] = period.fiscalyear_id.id
76         journal = self.pool.get('account.journal').browse(cr, uid, journal_id, None)
77         return obj_seq.next_by_id(cr, uid, journal.sequence_id.id, context=context)
78
79     def _currency(self, cursor, user, ids, name, args, context=None):
80         res = {}
81         res_currency_obj = self.pool.get('res.currency')
82         res_users_obj = self.pool.get('res.users')
83         default_currency = res_users_obj.browse(cursor, user,
84                 user, context=context).company_id.currency_id
85         for statement in self.browse(cursor, user, ids, context=context):
86             currency = statement.journal_id.currency
87             if not currency:
88                 currency = default_currency
89             res[statement.id] = currency.id
90         currency_names = {}
91         for currency_id, currency_name in res_currency_obj.name_get(cursor,
92                 user, [x for x in res.values()], context=context):
93             currency_names[currency_id] = currency_name
94         for statement_id in res.keys():
95             currency_id = res[statement_id]
96             res[statement_id] = (currency_id, currency_names[currency_id])
97         return res
98
99     def _get_statement(self, cr, uid, ids, context=None):
100         result = {}
101         for line in self.pool.get('account.bank.statement.line').browse(cr, uid, ids, context=context):
102             result[line.statement_id.id] = True
103         return result.keys()
104
105     def _all_lines_reconciled(self, cr, uid, ids, name, args, context=None):
106         res = {}
107         for statement in self.browse(cr, uid, ids, context=context):
108             res[statement.id] = all([line.journal_entry_id.id for line in statement.line_ids])
109         return res
110
111     _order = "date desc, id desc"
112     _name = "account.bank.statement"
113     _description = "Bank Statement"
114     _inherit = ['mail.thread']
115     _columns = {
116         'name': fields.char(
117             'Reference', states={'draft': [('readonly', False)]},
118             readonly=True, # readonly for account_cash_statement
119             copy=False,
120             help='if you give the Name other then /, its created Accounting Entries Move '
121                  'will be with same name as statement name. '
122                  'This allows the statement entries to have the same references than the '
123                  'statement itself'),
124         'date': fields.date('Date', required=True, states={'confirm': [('readonly', True)]},
125                             select=True, copy=False),
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)]}, help="Computed using the cash control lines"),
134         'balance_end': fields.function(_end_balance,
135             store = {
136                 'account.bank.statement': (lambda self, cr, uid, ids, c={}: ids, ['line_ids','move_line_ids','balance_start'], 10),
137                 'account.bank.statement.line': (_get_statement, ['amount'], 10),
138             },
139             string="Computed Balance", help='Balance as calculated based on Opening Balance and transaction lines'),
140         'company_id': fields.related('journal_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True),
141         'line_ids': fields.one2many('account.bank.statement.line',
142                                     'statement_id', 'Statement lines',
143                                     states={'confirm':[('readonly', True)]}, copy=True),
144         'move_line_ids': fields.one2many('account.move.line', 'statement_id',
145                                          'Entry lines', states={'confirm':[('readonly',True)]}),
146         'state': fields.selection([('draft', 'New'),
147                                    ('open','Open'), # used by cash statements
148                                    ('confirm', 'Closed')],
149                                    'Status', required=True, readonly="1",
150                                    copy=False,
151                                    help='When new statement is created the status will be \'Draft\'.\n'
152                                         'And after getting confirmation from the bank it will be in \'Confirmed\' status.'),
153         'currency': fields.function(_currency, string='Currency',
154             type='many2one', relation='res.currency'),
155         '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.'),
156         'cash_control': fields.related('journal_id', 'cash_control' , type='boolean', relation='account.journal',string='Cash control'),
157         'all_lines_reconciled': fields.function(_all_lines_reconciled, string='All lines reconciled', type='boolean'),
158     }
159
160     _defaults = {
161         'name': '/', 
162         'date': fields.date.context_today,
163         'state': 'draft',
164         'journal_id': _default_journal_id,
165         'period_id': _get_period,
166         'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.bank.statement',context=c),
167     }
168
169     def _check_company_id(self, cr, uid, ids, context=None):
170         for statement in self.browse(cr, uid, ids, context=context):
171             if statement.company_id.id != statement.period_id.company_id.id:
172                 return False
173         return True
174
175     _constraints = [
176         (_check_company_id, 'The journal and period chosen have to belong to the same company.', ['journal_id','period_id']),
177     ]
178
179     def onchange_date(self, cr, uid, ids, date, company_id, context=None):
180         """
181             Find the correct period to use for the given date and company_id, return it and set it in the context
182         """
183         res = {}
184         period_pool = self.pool.get('account.period')
185
186         if context is None:
187             context = {}
188         ctx = context.copy()
189         ctx.update({'company_id': company_id})
190         pids = period_pool.find(cr, uid, dt=date, context=ctx)
191         if pids:
192             res.update({'period_id': pids[0]})
193             context = dict(context, period_id=pids[0])
194
195         return {
196             'value':res,
197             'context':context,
198         }
199
200     def button_dummy(self, cr, uid, ids, context=None):
201         return self.write(cr, uid, ids, {}, context=context)
202
203     def _prepare_move(self, cr, uid, st_line, st_line_number, context=None):
204         """Prepare the dict of values to create the move from a
205            statement line. This method may be overridden to implement custom
206            move generation (making sure to call super() to establish
207            a clean extension chain).
208
209            :param browse_record st_line: account.bank.statement.line record to
210                   create the move from.
211            :param char st_line_number: will be used as the name of the generated account move
212            :return: dict of value to create() the account.move
213         """
214         return {
215             'journal_id': st_line.statement_id.journal_id.id,
216             'period_id': st_line.statement_id.period_id.id,
217             'date': st_line.date,
218             'name': st_line_number,
219             'ref': st_line.ref,
220         }
221
222     def _get_counter_part_account(sefl, cr, uid, st_line, context=None):
223         """Retrieve the account to use in the counterpart move.
224
225            :param browse_record st_line: account.bank.statement.line record to create the move from.
226            :return: int/long of the account.account to use as counterpart
227         """
228         if st_line.amount >= 0:
229             return st_line.statement_id.journal_id.default_credit_account_id.id
230         return st_line.statement_id.journal_id.default_debit_account_id.id
231
232     def _get_counter_part_partner(sefl, cr, uid, st_line, context=None):
233         """Retrieve the partner to use in the counterpart move.
234
235            :param browse_record st_line: account.bank.statement.line record to create the move from.
236            :return: int/long of the res.partner to use as counterpart
237         """
238         return st_line.partner_id and st_line.partner_id.id or False
239
240     def _prepare_bank_move_line(self, cr, uid, st_line, move_id, amount, company_currency_id, context=None):
241         """Compute the args to build the dict of values to create the counter part move line from a
242            statement line by calling the _prepare_move_line_vals. 
243
244            :param browse_record st_line: account.bank.statement.line record to create the move from.
245            :param int/long move_id: ID of the account.move to link the move line
246            :param float amount: amount of the move line
247            :param int/long company_currency_id: ID of currency of the concerned company
248            :return: dict of value to create() the bank account.move.line
249         """
250         account_id = self._get_counter_part_account(cr, uid, st_line, context=context)
251         partner_id = self._get_counter_part_partner(cr, uid, st_line, context=context)
252         debit = ((amount > 0) and amount) or 0.0
253         credit = ((amount < 0) and -amount) or 0.0
254         cur_id = False
255         amt_cur = False
256         if st_line.statement_id.currency.id != company_currency_id:
257             amt_cur = st_line.amount
258             cur_id = st_line.currency_id or st_line.statement_id.currency.id
259         if st_line.currency_id and st_line.amount_currency:
260             amt_cur = st_line.amount_currency
261             cur_id = st_line.currency_id.id
262         return self._prepare_move_line_vals(cr, uid, st_line, move_id, debit, credit,
263             amount_currency=amt_cur, currency_id=cur_id, account_id=account_id,
264             partner_id=partner_id, context=context)
265
266     def _prepare_move_line_vals(self, cr, uid, st_line, move_id, debit, credit, currency_id=False,
267                 amount_currency=False, account_id=False, partner_id=False, context=None):
268         """Prepare the dict of values to create the move line from a
269            statement line.
270
271            :param browse_record st_line: account.bank.statement.line record to
272                   create the move from.
273            :param int/long move_id: ID of the account.move to link the move line
274            :param float debit: debit amount of the move line
275            :param float credit: credit amount of the move line
276            :param int/long currency_id: ID of currency of the move line to create
277            :param float amount_currency: amount of the debit/credit expressed in the currency_id
278            :param int/long account_id: ID of the account to use in the move line if different
279                   from the statement line account ID
280            :param int/long partner_id: ID of the partner to put on the move line
281            :return: dict of value to create() the account.move.line
282         """
283         acc_id = account_id or st_line.account_id.id
284         cur_id = currency_id or st_line.statement_id.currency.id
285         par_id = partner_id or (((st_line.partner_id) and st_line.partner_id.id) or False)
286         return {
287             'name': st_line.name,
288             'date': st_line.date,
289             'ref': st_line.ref,
290             'move_id': move_id,
291             'partner_id': par_id,
292             'account_id': acc_id,
293             'credit': credit,
294             'debit': debit,
295             'statement_id': st_line.statement_id.id,
296             'journal_id': st_line.statement_id.journal_id.id,
297             'period_id': st_line.statement_id.period_id.id,
298             'currency_id': amount_currency and cur_id,
299             'amount_currency': amount_currency,
300         }
301
302     def balance_check(self, cr, uid, st_id, journal_type='bank', context=None):
303         st = self.browse(cr, uid, st_id, context=context)
304         if not ((abs((st.balance_end or 0.0) - st.balance_end_real) < 0.0001) or (abs((st.balance_end or 0.0) - st.balance_end_real) < 0.0001)):
305             raise osv.except_osv(_('Error!'),
306                     _('The statement balance is incorrect !\nThe expected balance (%.2f) is different than the computed one. (%.2f)') % (st.balance_end_real, st.balance_end))
307         return True
308
309     def statement_close(self, cr, uid, ids, journal_type='bank', context=None):
310         return self.write(cr, uid, ids, {'state':'confirm'}, context=context)
311
312     def check_status_condition(self, cr, uid, state, journal_type='bank'):
313         return state in ('draft','open')
314
315     def button_confirm_bank(self, cr, uid, ids, context=None):
316         if context is None:
317             context = {}
318
319         for st in self.browse(cr, uid, ids, context=context):
320             j_type = st.journal_id.type
321             if not self.check_status_condition(cr, uid, st.state, journal_type=j_type):
322                 continue
323
324             self.balance_check(cr, uid, st.id, journal_type=j_type, context=context)
325             if (not st.journal_id.default_credit_account_id) \
326                     or (not st.journal_id.default_debit_account_id):
327                 raise osv.except_osv(_('Configuration Error!'), _('Please verify that an account is defined in the journal.'))
328             for line in st.move_line_ids:
329                 if line.state != 'valid':
330                     raise osv.except_osv(_('Error!'), _('The account entries lines are not in valid state.'))
331             move_ids = []
332             for st_line in st.line_ids:
333                 if not st_line.amount:
334                     continue
335                 if st_line.account_id and not st_line.journal_entry_id.id:
336                     #make an account move as before
337                     vals = {
338                         'debit': st_line.amount < 0 and -st_line.amount or 0.0,
339                         'credit': st_line.amount > 0 and st_line.amount or 0.0,
340                         'account_id': st_line.account_id.id,
341                         'name': st_line.name
342                     }
343                     self.pool.get('account.bank.statement.line').process_reconciliation(cr, uid, st_line.id, [vals], context=context)
344                 elif not st_line.journal_entry_id.id:
345                     raise osv.except_osv(_('Error!'), _('All the account entries lines must be processed in order to close the statement.'))
346                 move_ids.append(st_line.journal_entry_id.id)
347             if move_ids:
348                 self.pool.get('account.move').post(cr, uid, move_ids, context=context)
349             self.message_post(cr, uid, [st.id], body=_('Statement %s confirmed, journal items were created.') % (st.name,), context=context)
350         self.link_bank_to_partner(cr, uid, ids, context=context)
351         return self.write(cr, uid, ids, {'state': 'confirm'}, context=context)
352
353     def button_cancel(self, cr, uid, ids, context=None):
354         bnk_st_line_ids = []
355         for st in self.browse(cr, uid, ids, context=context):
356             bnk_st_line_ids += [line.id for line in st.line_ids]
357         self.pool.get('account.bank.statement.line').cancel(cr, uid, bnk_st_line_ids, context=context)
358         return self.write(cr, uid, ids, {'state': 'draft'}, context=context)
359
360     def _compute_balance_end_real(self, cr, uid, journal_id, context=None):
361         res = False
362         if journal_id:
363             journal = self.pool.get('account.journal').browse(cr, uid, journal_id, context=context)
364             if journal.with_last_closing_balance:
365                 cr.execute('SELECT balance_end_real \
366                       FROM account_bank_statement \
367                       WHERE journal_id = %s AND NOT state = %s \
368                       ORDER BY date DESC,id DESC LIMIT 1', (journal_id, 'draft'))
369                 res = cr.fetchone()
370         return res and res[0] or 0.0
371
372     def onchange_journal_id(self, cr, uid, statement_id, journal_id, context=None):
373         if not journal_id:
374             return {}
375         balance_start = self._compute_balance_end_real(cr, uid, journal_id, context=context)
376         journal = self.pool.get('account.journal').browse(cr, uid, journal_id, context=context)
377         currency = journal.currency or journal.company_id.currency_id
378         res = {'balance_start': balance_start, 'company_id': journal.company_id.id, 'currency': currency.id}
379         if journal.type == 'cash':
380             res['cash_control'] = journal.cash_control
381         return {'value': res}
382
383     def unlink(self, cr, uid, ids, context=None):
384         for item in self.browse(cr, uid, ids, context=context):
385             if item.state != 'draft':
386                 raise osv.except_osv(
387                     _('Invalid Action!'), 
388                     _('In order to delete a bank statement, you must first cancel it to delete related journal items.')
389                 )
390         return super(account_bank_statement, self).unlink(cr, uid, ids, context=context)
391
392     def button_journal_entries(self, cr, uid, ids, context=None):
393         ctx = (context or {}).copy()
394         ctx['journal_id'] = self.browse(cr, uid, ids[0], context=context).journal_id.id
395         return {
396             'name': _('Journal Items'),
397             'view_type':'form',
398             'view_mode':'tree',
399             'res_model':'account.move.line',
400             'view_id':False,
401             'type':'ir.actions.act_window',
402             'domain':[('statement_id','in',ids)],
403             'context':ctx,
404         }
405
406     def number_of_lines_reconciled(self, cr, uid, id, context=None):
407         bsl_obj = self.pool.get('account.bank.statement.line')
408         return bsl_obj.search_count(cr, uid, [('statement_id', '=', id), ('journal_entry_id', '!=', False)], context=context)
409         
410     def get_format_currency_js_function(self, cr, uid, id, context=None):
411         """ Returns a string that can be used to instanciate a javascript function.
412             That function formats a number according to the statement line's currency or the statement currency"""
413         company_currency = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.currency_id
414         st = id and self.browse(cr, uid, id, context=context)
415         if not st:
416             return
417         statement_currency = st.journal_id.currency or company_currency
418         digits = 2 # TODO : from currency_obj
419         function = ""
420         done_currencies = []
421         for st_line in st.line_ids:
422             st_line_currency = st_line.currency_id or statement_currency
423             if st_line_currency.id not in done_currencies:
424                 if st_line_currency.position == 'after':
425                     return_str = "return amount.toFixed(" + str(digits) + ") + ' " + st_line_currency.symbol + "';"
426                 else:
427                     return_str = "return '" + st_line_currency.symbol + " ' + amount.toFixed(" + str(digits) + ");"
428                 function += "if (currency_id === " + str(st_line_currency.id) + "){ " + return_str + " }"
429                 done_currencies.append(st_line_currency.id)
430         return function
431
432     def link_bank_to_partner(self, cr, uid, ids, context=None):
433         for statement in self.browse(cr, uid, ids, context=context):
434             for st_line in statement.line_ids:
435                 if st_line.bank_account_id and st_line.partner_id and st_line.bank_account_id.partner_id.id != st_line.partner_id.id:
436                     self.pool.get('res.partner.bank').write(cr, uid, [st_line.bank_account_id.id], {'partner_id': st_line.partner_id.id}, context=context)
437
438 class account_bank_statement_line(osv.osv):
439
440     def cancel(self, cr, uid, ids, context=None):
441         account_move_obj = self.pool.get('account.move')
442         move_ids = []
443         for line in self.browse(cr, uid, ids, context=context):
444             if line.journal_entry_id:
445                 move_ids.append(line.journal_entry_id.id)
446                 for aml in line.journal_entry_id.line_id:
447                     if aml.reconcile_id:
448                         move_lines = [l.id for l in aml.reconcile_id.line_id]
449                         move_lines.remove(aml.id)
450                         self.pool.get('account.move.reconcile').unlink(cr, uid, [aml.reconcile_id.id], context=context)
451                         if len(move_lines) >= 2:
452                             self.pool.get('account.move.line').reconcile_partial(cr, uid, move_lines, 'auto', context=context)
453         if move_ids:
454             account_move_obj.button_cancel(cr, uid, move_ids, context=context)
455             account_move_obj.unlink(cr, uid, move_ids, context)
456
457     def get_data_for_reconciliations(self, cr, uid, ids, context=None):
458         """ Used to instanciate a batch of reconciliations in a single request """
459         # Build a list of reconciliations data
460         ret = []
461         statement_line_done = {}
462         mv_line_ids_selected = []
463         for st_line in self.browse(cr, uid, ids, context=context):
464             # look for structured communication first
465             exact_match_id = self.search_structured_com(cr, uid, st_line, context=context)
466             if exact_match_id:
467                 reconciliation_data = {
468                     'st_line': self.get_statement_line_for_reconciliation(cr, uid, st_line.id, context),
469                     'reconciliation_proposition': self.make_counter_part_lines(cr, uid, st_line, [exact_match_id], context=context)
470                 }
471                 for mv_line in reconciliation_data['reconciliation_proposition']:
472                     mv_line_ids_selected.append(mv_line['id'])
473                 statement_line_done[st_line.id] = reconciliation_data
474                 
475         for st_line_id in ids:
476             if statement_line_done.get(st_line_id):
477                 ret.append(statement_line_done.get(st_line_id))
478             else:
479                 reconciliation_data = {
480                     'st_line': self.get_statement_line_for_reconciliation(cr, uid, st_line_id, context),
481                     'reconciliation_proposition': self.get_reconciliation_proposition(cr, uid, st_line_id, mv_line_ids_selected, context)
482                 }
483                 for mv_line in reconciliation_data['reconciliation_proposition']:
484                     mv_line_ids_selected.append(mv_line['id'])
485                 ret.append(reconciliation_data)
486
487         # Check if, now that 'candidate' move lines were selected, there are moves left for statement lines
488         #for reconciliation_data in ret:
489         #    if not reconciliation_data['st_line']['has_no_partner']:
490         #        st_line = self.browse(cr, uid, reconciliation_data['st_line']['id'], context=context)
491         #        if not self.get_move_lines_counterparts(cr, uid, st_line, excluded_ids=mv_line_ids_selected, count=True, context=context):
492         #            reconciliation_data['st_line']['no_match'] = True
493         return ret
494
495     def get_statement_line_for_reconciliation(self, cr, uid, id, context=None):
496         """ Returns the data required by the bank statement reconciliation use case """
497         line = self.browse(cr, uid, id, context=context)
498         statement_currency = line.journal_id.currency or line.journal_id.company_id.currency_id
499         amount = line.amount
500         rml_parser = report_sxw.rml_parse(cr, uid, 'statement_line_widget', context=context)
501         amount_str = line.amount > 0 and line.amount or -line.amount
502         amount_str = rml_parser.formatLang(amount_str, currency_obj=statement_currency)
503         amount_currency_str = ""
504         if line.amount_currency and line.currency_id:
505             amount_currency_str = amount_str
506             amount_str = rml_parser.formatLang(line.amount_currency, currency_obj=line.currency_id)
507             amount = line.amount_currency
508
509         data = {
510             'id': line.id,
511             'ref': line.ref,
512             'note': line.note or "",
513             'name': line.name,
514             'date': line.date,
515             'amount': amount,
516             'amount_str': amount_str,
517             'currency_id': line.currency_id.id or statement_currency.id,
518             'no_match': self.get_move_lines_counterparts(cr, uid, line, count=True, context=context) == 0,
519             'partner_id': line.partner_id.id,
520             'statement_id': line.statement_id.id,
521             'account_code': line.journal_id.default_debit_account_id.code,
522             'account_name': line.journal_id.default_debit_account_id.name,
523             'partner_name': line.partner_id.name,
524             'amount_currency_str': amount_currency_str,
525             'has_no_partner': not line.partner_id.id,
526         }
527         if line.partner_id.id:
528             data['open_balance_account_id'] = line.partner_id.property_account_payable.id
529             if amount > 0:
530                 data['open_balance_account_id'] = line.partner_id.property_account_receivable.id
531         return data
532
533     def search_structured_com(self, cr, uid, st_line, context=None):
534         if not st_line.ref:
535             return
536         domain = [('ref', '=', st_line.ref)]
537         if st_line.partner_id:
538             domain += [('partner_id', '=', st_line.partner_id.id)]
539         ids = self.pool.get('account.move.line').search(cr, uid, domain, limit=1, context=context)
540         return ids and ids[0] or False
541
542     def get_reconciliation_proposition(self, cr, uid, id, excluded_ids=[], context=None):
543         """ Returns move lines that constitute the best guess to reconcile a statement line. """
544         st_line = self.browse(cr, uid, id, context=context)
545         company_currency = st_line.journal_id.company_id.currency_id.id
546         statement_currency = st_line.journal_id.currency.id or company_currency
547         # either use the unsigned debit/credit fields or the signed amount_currency field
548         sign = 1
549         if statement_currency == company_currency:
550             amount_field = 'credit'
551             if st_line.amount > 0:
552                 amount_field = 'debit'
553         else:
554             amount_field = 'amount_currency'
555             if st_line.amount < 0:
556                 sign = -1
557
558         #we don't propose anything if there is no partner detected
559         if not st_line.partner_id.id:
560             return []
561         # look for exact match
562         exact_match_id = self.get_move_lines_counterparts(cr, uid, st_line, excluded_ids=excluded_ids, additional_domain=[(amount_field, '=', (sign * st_line.amount))])
563         if exact_match_id:
564             return exact_match_id
565
566         # select oldest move lines
567         if sign == -1:
568             mv_lines = self.get_move_lines_counterparts(cr, uid, st_line, excluded_ids=excluded_ids, additional_domain=[(amount_field, '<', 0)])
569         else:
570             mv_lines = self.get_move_lines_counterparts(cr, uid, st_line, excluded_ids=excluded_ids, additional_domain=[(amount_field, '>', 0)])
571         ret = []
572         total = 0
573         # get_move_lines_counterparts inverts debit and credit
574         amount_field = 'debit' if amount_field == 'credit' else 'credit'
575         for line in mv_lines:
576             if total + line[amount_field] <= abs(st_line.amount):
577                 ret.append(line)
578                 total += line[amount_field]
579             if total >= abs(st_line.amount):
580                 break
581         return ret
582
583     def get_move_lines_counterparts_id(self, cr, uid, st_line_id, excluded_ids=[], additional_domain=[], count=False, context=None):
584         st_line = self.browse(cr, uid, st_line_id, context=context)
585         return self.get_move_lines_counterparts(cr, uid, st_line, excluded_ids, additional_domain, count, context=context)
586
587     def get_move_lines_counterparts(self, cr, uid, st_line, excluded_ids=[], additional_domain=[], count=False, context=None):
588         """ Find the move lines that could be used to reconcile a statement line and returns the counterpart that could be created to reconcile them
589             If count is true, only returns the count.
590
591             :param st_line: the browse record of the statement line
592             :param integers list excluded_ids: ids of move lines that should not be fetched
593             :param string filter_str: string to filter lines
594             :param integer offset: offset of the request
595             :param integer limit: number of lines to fetch
596             :param boolean count: just return the number of records
597             :param tuples list domain: additional domain restrictions
598         """
599         mv_line_pool = self.pool.get('account.move.line')
600
601         domain = additional_domain + [('reconcile_id', '=', False),('state', '=', 'valid')]
602         if st_line.partner_id.id:
603             domain += [('partner_id', '=', st_line.partner_id.id),
604                 '|', ('account_id.type', '=', 'receivable'),
605                 ('account_id.type', '=', 'payable')]
606         else:
607             domain += [('account_id.reconcile', '=', True)]
608             #domain += [('account_id.reconcile', '=', True), ('account_id.type', '=', 'other')]
609         if excluded_ids:
610             domain.append(('id', 'not in', excluded_ids))
611         line_ids = mv_line_pool.search(cr, uid, domain, order="date_maturity asc, id asc", context=context)
612         return self.make_counter_part_lines(cr, uid, st_line, line_ids, count=count, context=context)
613
614     def make_counter_part_lines(self, cr, uid, st_line, line_ids, count=False, context=None):
615         if context is None:
616             context = {}
617         mv_line_pool = self.pool.get('account.move.line')
618         currency_obj = self.pool.get('res.currency')
619         company_currency = st_line.journal_id.company_id.currency_id
620         statement_currency = st_line.journal_id.currency or company_currency
621         rml_parser = report_sxw.rml_parse(cr, uid, 'statement_line_counterpart_widget', context=context)
622         #partially reconciled lines can be displayed only once
623         reconcile_partial_ids = []
624         if count:
625             nb_lines = 0
626             for line in mv_line_pool.browse(cr, uid, line_ids, context=context):
627                 if line.reconcile_partial_id and line.reconcile_partial_id.id in reconcile_partial_ids:
628                     continue
629                 nb_lines += 1
630                 if line.reconcile_partial_id:
631                     reconcile_partial_ids.append(line.reconcile_partial_id.id)
632             return nb_lines
633         else:
634             ret = []
635             for line in mv_line_pool.browse(cr, uid, line_ids, context=context):
636                 if line.reconcile_partial_id and line.reconcile_partial_id.id in reconcile_partial_ids:
637                     continue
638                 amount_currency_str = ""
639                 if line.currency_id and line.amount_currency:
640                     amount_currency_str = rml_parser.formatLang(line.amount_currency, currency_obj=line.currency_id)
641                 ret_line = {
642                     'id': line.id,
643                     'name': line.move_id.name,
644                     'ref': line.move_id.ref,
645                     'account_code': line.account_id.code,
646                     'account_name': line.account_id.name,
647                     'account_type': line.account_id.type,
648                     'date_maturity': line.date_maturity,
649                     'date': line.date,
650                     'period_name': line.period_id.name,
651                     'journal_name': line.journal_id.name,
652                     'amount_currency_str': amount_currency_str,
653                     'partner_id': line.partner_id.id,
654                     'partner_name': line.partner_id.name,
655                     'has_no_partner': not bool(st_line.partner_id.id),
656                 }
657                 st_line_currency = st_line.currency_id or statement_currency
658                 if st_line.currency_id and line.currency_id and line.currency_id.id == st_line.currency_id.id:
659                     if line.amount_residual_currency < 0:
660                         ret_line['debit'] = 0
661                         ret_line['credit'] = -line.amount_residual_currency
662                     else:
663                         ret_line['debit'] = line.amount_residual_currency if line.credit != 0 else 0
664                         ret_line['credit'] = line.amount_residual_currency if line.debit != 0 else 0
665                     ret_line['amount_currency_str'] = rml_parser.formatLang(line.amount_residual, currency_obj=company_currency)
666                 else:
667                     if line.amount_residual < 0:
668                         ret_line['debit'] = 0
669                         ret_line['credit'] = -line.amount_residual
670                     else:
671                         ret_line['debit'] = line.amount_residual if line.credit != 0 else 0
672                         ret_line['credit'] = line.amount_residual if line.debit != 0 else 0
673                     ctx = context.copy()
674                     ctx.update({'date': st_line.date})
675                     ret_line['debit'] = currency_obj.compute(cr, uid, st_line_currency.id, company_currency.id, ret_line['debit'], context=ctx)
676                     ret_line['credit'] = currency_obj.compute(cr, uid, st_line_currency.id, company_currency.id, ret_line['credit'], context=ctx)
677                 ret_line['debit_str'] = rml_parser.formatLang(ret_line['debit'], currency_obj=st_line_currency)
678                 ret_line['credit_str'] = rml_parser.formatLang(ret_line['credit'], currency_obj=st_line_currency)
679                 ret.append(ret_line)
680                 if line.reconcile_partial_id:
681                     reconcile_partial_ids.append(line.reconcile_partial_id.id)
682             return ret
683
684     def get_currency_rate_line(self, cr, uid, st_line, currency_diff, move_id, context=None):
685         if currency_diff < 0:
686             account_id = st_line.company_id.expense_currency_exchange_account_id.id
687             if not account_id:
688                 raise osv.except_osv(_('Insufficient Configuration!'), _("You should configure the 'Loss Exchange Rate Account' in the accounting settings, to manage automatically the booking of accounting entries related to differences between exchange rates."))
689         else:
690             account_id = st_line.company_id.income_currency_exchange_account_id.id
691             if not account_id:
692                 raise osv.except_osv(_('Insufficient Configuration!'), _("You should configure the 'Gain Exchange Rate Account' in the accounting settings, to manage automatically the booking of accounting entries related to differences between exchange rates."))
693         return {
694             'move_id': move_id,
695             'name': _('change') + ': ' + (st_line.name or '/'),
696             'period_id': st_line.statement_id.period_id.id,
697             'journal_id': st_line.journal_id.id,
698             'partner_id': st_line.partner_id.id,
699             'company_id': st_line.company_id.id,
700             'statement_id': st_line.statement_id.id,
701             'debit': currency_diff < 0 and -currency_diff or 0,
702             'credit': currency_diff > 0 and currency_diff or 0,
703             'date': st_line.date,
704             'account_id': account_id
705             }
706
707     def process_reconciliation(self, cr, uid, id, mv_line_dicts, context=None):
708         """ Creates a move line for each item of mv_line_dicts and for the statement line. Reconcile a new move line with its counterpart_move_line_id if specified. Finally, mark the statement line as reconciled by putting the newly created move id in the column journal_entry_id.
709
710             :param int id: id of the bank statement line
711             :param list of dicts mv_line_dicts: move lines to create. If counterpart_move_line_id is specified, reconcile with it
712         """
713         if context is None:
714             context = {}
715         st_line = self.browse(cr, uid, id, context=context)
716         company_currency = st_line.journal_id.company_id.currency_id
717         statement_currency = st_line.journal_id.currency or company_currency
718         bs_obj = self.pool.get('account.bank.statement')
719         am_obj = self.pool.get('account.move')
720         aml_obj = self.pool.get('account.move.line')
721         currency_obj = self.pool.get('res.currency')
722
723         # Checks
724         if st_line.journal_entry_id.id:
725             raise osv.except_osv(_('Error!'), _('The bank statement line was already reconciled.'))
726         for mv_line_dict in mv_line_dicts:
727             for field in ['debit', 'credit', 'amount_currency']:
728                 if field not in mv_line_dict:
729                     mv_line_dict[field] = 0.0
730             if mv_line_dict.get('counterpart_move_line_id'):
731                 mv_line = aml_obj.browse(cr, uid, mv_line_dict.get('counterpart_move_line_id'), context=context)
732                 if mv_line.reconcile_id:
733                     raise osv.except_osv(_('Error!'), _('A selected move line was already reconciled.'))
734
735         # Create the move
736         move_name = st_line.statement_id.name + "/" + str(st_line.sequence)
737         move_vals = bs_obj._prepare_move(cr, uid, st_line, move_name, context=context)
738         move_id = am_obj.create(cr, uid, move_vals, context=context)
739
740         # Create the move line for the statement line
741         if st_line.statement_id.currency.id != company_currency.id:
742             ctx = context.copy()
743             ctx['date'] = st_line.date
744             amount = currency_obj.compute(cr, uid, st_line.statement_id.currency.id, company_currency.id, st_line.amount_currency, context=ctx)
745         else:
746             amount = st_line.amount
747         bank_st_move_vals = bs_obj._prepare_bank_move_line(cr, uid, st_line, move_id, amount, company_currency.id, context=context)
748         aml_obj.create(cr, uid, bank_st_move_vals, context=context)
749         # Complete the dicts
750         st_line_currency = st_line.currency_id or statement_currency
751         st_line_currency_rate = st_line.currency_id and statement_currency.id == company_currency.id and (st_line.amount_currency / st_line.amount) or False
752         to_create = []
753         for mv_line_dict in mv_line_dicts:
754             if mv_line_dict.get('is_tax_line'):
755                 continue
756             mv_line_dict['ref'] = move_name
757             mv_line_dict['move_id'] = move_id
758             mv_line_dict['period_id'] = st_line.statement_id.period_id.id
759             mv_line_dict['journal_id'] = st_line.journal_id.id
760             mv_line_dict['company_id'] = st_line.company_id.id
761             mv_line_dict['statement_id'] = st_line.statement_id.id
762             if mv_line_dict.get('counterpart_move_line_id'):
763                 mv_line = aml_obj.browse(cr, uid, mv_line_dict['counterpart_move_line_id'], context=context)
764                 mv_line_dict['account_id'] = mv_line.account_id.id
765             if st_line_currency.id != company_currency.id:
766                 mv_line_dict['amount_currency'] = mv_line_dict['debit'] - mv_line_dict['credit']
767                 mv_line_dict['currency_id'] = st_line_currency.id
768                 if st_line.currency_id and statement_currency.id == company_currency.id and st_line_currency_rate:
769                     debit_at_current_rate = self.pool.get('res.currency').round(cr, uid, company_currency, mv_line_dict['debit'] / st_line_currency_rate)
770                     credit_at_current_rate = self.pool.get('res.currency').round(cr, uid, company_currency, mv_line_dict['credit'] / st_line_currency_rate)
771                 else:
772                     debit_at_current_rate = currency_obj.compute(cr, uid, st_line_currency.id, company_currency.id, mv_line_dict['debit'], context=context)
773                     credit_at_current_rate = currency_obj.compute(cr, uid, st_line_currency.id, company_currency.id, mv_line_dict['credit'], context=context)
774                 if mv_line_dict.get('counterpart_move_line_id'):
775                     #post an account line that use the same currency rate than the counterpart (to balance the account) and post the difference in another line
776                     ctx = context.copy()
777                     ctx['date'] = mv_line.date
778                     debit_at_old_rate = currency_obj.compute(cr, uid, st_line_currency.id, company_currency.id, mv_line_dict['debit'], context=ctx)
779                     credit_at_old_rate = currency_obj.compute(cr, uid, st_line_currency.id, company_currency.id, mv_line_dict['credit'], context=ctx)
780                     mv_line_dict['credit'] = credit_at_old_rate
781                     mv_line_dict['debit'] = debit_at_old_rate
782                     if debit_at_old_rate - debit_at_current_rate:
783                         currency_diff = debit_at_current_rate - debit_at_old_rate
784                         to_create.append(self.get_currency_rate_line(cr, uid, st_line, currency_diff, move_id, context=context))
785                     if credit_at_old_rate - credit_at_current_rate:
786                         currency_diff = credit_at_current_rate - credit_at_old_rate
787                         to_create.append(self.get_currency_rate_line(cr, uid, st_line, currency_diff, move_id, context=context))
788                 else:
789                     mv_line_dict['debit'] = debit_at_current_rate
790                     mv_line_dict['credit'] = credit_at_current_rate
791             to_create.append(mv_line_dict)
792         # Create move lines
793         move_line_pairs_to_reconcile = []
794         for mv_line_dict in to_create:
795             counterpart_move_line_id = None # NB : this attribute is irrelevant for aml_obj.create() and needs to be removed from the dict
796             if mv_line_dict.get('counterpart_move_line_id'):
797                 counterpart_move_line_id = mv_line_dict['counterpart_move_line_id']
798                 del mv_line_dict['counterpart_move_line_id']
799             new_aml_id = aml_obj.create(cr, uid, mv_line_dict, context=context)
800             if counterpart_move_line_id != None:
801                 move_line_pairs_to_reconcile.append([new_aml_id, counterpart_move_line_id])
802
803         # Reconcile
804         for pair in move_line_pairs_to_reconcile:
805             # TODO : too slow
806             aml_obj.reconcile_partial(cr, uid, pair, context=context)
807
808         # Mark the statement line as reconciled
809         self.write(cr, uid, id, {'journal_entry_id': move_id}, context=context)
810
811     # FIXME : if it wasn't for the multicompany security settings in account_security.xml, the method would just
812     # return [('journal_entry_id', '=', False)]
813     # Unfortunately, that spawns a "no access rights" error ; it shouldn't.
814     def _needaction_domain_get(self, cr, uid, context=None):
815         user = self.pool.get("res.users").browse(cr, uid, uid)
816         return ['|',('company_id','=',False),('company_id','child_of',[user.company_id.id]),('journal_entry_id', '=', False)]
817
818     _order = "statement_id desc, sequence"
819     _name = "account.bank.statement.line"
820     _description = "Bank Statement Line"
821     _inherit = ['ir.needaction_mixin']
822     _columns = {
823         'name': fields.char('Description', required=True),
824         'date': fields.date('Date', required=True),
825         'amount': fields.float('Amount', digits_compute=dp.get_precision('Account')),
826         'partner_id': fields.many2one('res.partner', 'Partner'),
827         'bank_account_id': fields.many2one('res.partner.bank','Bank Account'),
828         'account_id': fields.many2one('account.account', 'Account', help="This technical field can be used at the statement line creation/import time in order to avoid the reconciliation process on it later on. The statement line will simply create a counterpart on this account"),
829         'statement_id': fields.many2one('account.bank.statement', 'Statement', select=True, required=True, ondelete='cascade'),
830         'journal_id': fields.related('statement_id', 'journal_id', type='many2one', relation='account.journal', string='Journal', store=True, readonly=True),
831         'ref': fields.char('Structured Communication'),
832         'note': fields.text('Notes'),
833         'sequence': fields.integer('Sequence', select=True, help="Gives the sequence order when displaying a list of bank statement lines."),
834         'company_id': fields.related('statement_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True),
835         'journal_entry_id': fields.many2one('account.move', 'Journal Entry', copy=False),
836         'amount_currency': fields.float('Amount Currency', help="The amount expressed in an optional other currency if it is a multi-currency entry.", digits_compute=dp.get_precision('Account')),
837         'currency_id': fields.many2one('res.currency', 'Currency', help="The optional other currency if it is a multi-currency entry."),
838     }
839     _defaults = {
840         'name': lambda self,cr,uid,context={}: self.pool.get('ir.sequence').get(cr, uid, 'account.bank.statement.line'),
841         'date': lambda self,cr,uid,context={}: context.get('date', fields.date.context_today(self,cr,uid,context=context)),
842     }
843
844 class account_statement_operation_template(osv.osv):
845     _name = "account.statement.operation.template"
846     _description = "Preset for the lines that can be created in a bank statement reconciliation"
847     _columns = {
848         'name': fields.char('Button Label', required=True),
849         'account_id': fields.many2one('account.account', 'Account', ondelete='cascade', domain=[('type','!=','view')]),
850         'label': fields.char('Label'),
851         'amount_type': fields.selection([('fixed', 'Fixed'),('percentage_of_total','Percentage of total amount'),('percentage_of_balance', 'Percentage of open balance')],
852                                    'Amount type', required=True),
853         'amount': fields.float('Amount', digits_compute=dp.get_precision('Account'), help="Leave to 0 to ignore."),
854         'tax_id': fields.many2one('account.tax', 'Tax', ondelete='cascade'),
855         'analytic_account_id': fields.many2one('account.analytic.account', 'Analytic Account', ondelete='cascade'),
856     }
857     _defaults = {
858         'amount_type': 'fixed',
859         'amount': 0.0
860     }
861
862 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: