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