[FIX] account: several fixes on the new bank statement reconciliation widget
[odoo/odoo.git] / addons / account / wizard / account_automatic_reconcile.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 import time
23
24 from openerp.osv import fields, osv
25 from openerp.tools.translate import _
26
27 class account_automatic_reconcile(osv.osv_memory):
28     _name = 'account.automatic.reconcile'
29     _description = 'Automatic Reconcile'
30
31     _columns = {
32         'account_ids': fields.many2many('account.account', 'reconcile_account_rel', 'reconcile_id', 'account_id', 'Accounts to Reconcile', domain = [('reconcile','=',1)],),
33         'writeoff_acc_id': fields.many2one('account.account', 'Account'),
34         'journal_id': fields.many2one('account.journal', 'Journal'),
35         'period_id': fields.many2one('account.period', 'Period'),
36         'max_amount': fields.float('Maximum write-off amount'),
37         'power': fields.selection([(p, str(p)) for p in range(2, 5)], 'Power', required=True, help='Number of partial amounts that can be combined to find a balance point can be chosen as the power of the automatic reconciliation'),
38         'reconciled': fields.integer('Reconciled transactions', readonly=True),
39         'unreconciled': fields.integer('Not reconciled transactions', readonly=True),
40         'allow_write_off': fields.boolean('Allow write off')
41     }
42
43     def _get_reconciled(self, cr, uid, context=None):
44         if context is None:
45             context = {}
46         return context.get('reconciled', 0)
47
48     def _get_unreconciled(self, cr, uid, context=None):
49         if context is None:
50             context = {}
51         return context.get('unreconciled', 0)
52
53     _defaults = {
54         'reconciled': _get_reconciled,
55         'unreconciled': _get_unreconciled,
56         'power': 2
57     }
58
59     #TODO: cleanup and comment this code... For now, it is awfulllll
60     # (way too complex, and really slow)...
61     def do_reconcile(self, cr, uid, credits, debits, max_amount, power, writeoff_acc_id, period_id, journal_id, context=None):
62         """
63         for one value of a credit, check all debits, and combination of them
64         depending on the power. It starts with a power of one and goes up
65         to the max power allowed.
66         """
67         move_line_obj = self.pool.get('account.move.line')
68         if context is None:
69             context = {}
70         def check2(value, move_list, power):
71             def check(value, move_list, power):
72                 for i in range(len(move_list)):
73                     move = move_list[i]
74                     if power == 1:
75                         if abs(value - move[1]) <= max_amount + 0.00001:
76                             return [move[0]]
77                     else:
78                         del move_list[i]
79                         res = check(value - move[1], move_list, power-1)
80                         move_list[i:i] = [move]
81                         if res:
82                             res.append(move[0])
83                             return res
84                 return False
85
86             for p in range(1, power+1):
87                 res = check(value, move_list, p)
88                 if res:
89                     return res
90             return False
91
92         
93         def check4(list1, list2, power):
94             """
95             for a list of credit and debit and a given power, check if there
96             are matching tuples of credit and debits, check all debits, and combination of them
97             depending on the power. It starts with a power of one and goes up
98             to the max power allowed.
99             """
100             def check3(value, list1, list2, list1power, power):
101                 for i in range(len(list1)):
102                     move = list1[i]
103                     if list1power == 1:
104                         res = check2(value + move[1], list2, power - 1)
105                         if res:
106                             return ([move[0]], res)
107                     else:
108                         del list1[i]
109                         res = check3(value + move[1], list1, list2, list1power-1, power-1)
110                         list1[i:i] = [move]
111                         if res:
112                             x, y = res
113                             x.append(move[0])
114                             return (x, y)
115                 return False
116
117             for p in range(1, power):
118                 res = check3(0, list1, list2, p, power)
119                 if res:
120                     return res
121             return False
122
123         def check5(list1, list2, max_power):
124             for p in range(2, max_power+1):
125                 res = check4(list1, list2, p)
126                 if res:
127                     return res
128             return False
129
130         ok = True
131         reconciled = 0
132         while credits and debits and ok:
133             res = check5(credits, debits, power)
134             if res:
135                 move_line_obj.reconcile(cr, uid, res[0] + res[1], 'auto', writeoff_acc_id, period_id, journal_id, context)
136                 reconciled += len(res[0]) + len(res[1])
137                 credits = [(id, credit) for (id, credit) in credits if id not in res[0]]
138                 debits = [(id, debit) for (id, debit) in debits if id not in res[1]]
139             else:
140                 ok = False
141         return (reconciled, len(credits)+len(debits))
142
143     def reconcile(self, cr, uid, ids, context=None):
144         move_line_obj = self.pool.get('account.move.line')
145         obj_model = self.pool.get('ir.model.data')
146         if context is None:
147             context = {}
148         form = self.browse(cr, uid, ids, context=context)[0]
149         max_amount = form.max_amount or 0.0
150         power = form.power
151         allow_write_off = form.allow_write_off
152         reconciled = unreconciled = 0
153         if not form.account_ids:
154             raise osv.except_osv(_('User Error!'), _('You must select accounts to reconcile.'))
155         for account_id in form.account_ids:
156             params = (account_id.id,)
157             if not allow_write_off:
158                 query = """SELECT partner_id FROM account_move_line WHERE account_id=%s AND reconcile_id IS NULL
159                 AND state <> 'draft' GROUP BY partner_id
160                 HAVING ABS(SUM(debit-credit)) = 0.0 AND count(*)>0"""
161             else:
162                 query = """SELECT partner_id FROM account_move_line WHERE account_id=%s AND reconcile_id IS NULL
163                 AND state <> 'draft' GROUP BY partner_id
164                 HAVING ABS(SUM(debit-credit)) < %s AND count(*)>0"""
165                 params += (max_amount,)
166             # reconcile automatically all transactions from partners whose balance is 0
167             cr.execute(query, params)
168             partner_ids = [id for (id,) in cr.fetchall()]
169             for partner_id in partner_ids:
170                 cr.execute(
171                     "SELECT id " \
172                     "FROM account_move_line " \
173                     "WHERE account_id=%s " \
174                     "AND partner_id=%s " \
175                     "AND state <> 'draft' " \
176                     "AND reconcile_id IS NULL",
177                     (account_id.id, partner_id))
178                 line_ids = [id for (id,) in cr.fetchall()]
179                 if line_ids:
180                     reconciled += len(line_ids)
181                     if allow_write_off:
182                         move_line_obj.reconcile(cr, uid, line_ids, 'auto', form.writeoff_acc_id.id, form.period_id.id, form.journal_id.id, context)
183                     else:
184                         move_line_obj.reconcile_partial(cr, uid, line_ids, 'manual', context=context)
185
186             # get the list of partners who have more than one unreconciled transaction
187             cr.execute(
188                 "SELECT partner_id " \
189                 "FROM account_move_line " \
190                 "WHERE account_id=%s " \
191                 "AND reconcile_id IS NULL " \
192                 "AND state <> 'draft' " \
193                 "AND partner_id IS NOT NULL " \
194                 "GROUP BY partner_id " \
195                 "HAVING count(*)>1",
196                 (account_id.id,))
197             partner_ids = [id for (id,) in cr.fetchall()]
198             #filter?
199             for partner_id in partner_ids:
200                 # get the list of unreconciled 'debit transactions' for this partner
201                 cr.execute(
202                     "SELECT id, debit " \
203                     "FROM account_move_line " \
204                     "WHERE account_id=%s " \
205                     "AND partner_id=%s " \
206                     "AND reconcile_id IS NULL " \
207                     "AND state <> 'draft' " \
208                     "AND debit > 0 " \
209                     "ORDER BY date_maturity",
210                     (account_id.id, partner_id))
211                 debits = cr.fetchall()
212
213                 # get the list of unreconciled 'credit transactions' for this partner
214                 cr.execute(
215                     "SELECT id, credit " \
216                     "FROM account_move_line " \
217                     "WHERE account_id=%s " \
218                     "AND partner_id=%s " \
219                     "AND reconcile_id IS NULL " \
220                     "AND state <> 'draft' " \
221                     "AND credit > 0 " \
222                     "ORDER BY date_maturity",
223                     (account_id.id, partner_id))
224                 credits = cr.fetchall()
225
226                 (rec, unrec) = self.do_reconcile(cr, uid, credits, debits, max_amount, power, form.writeoff_acc_id.id, form.period_id.id, form.journal_id.id, context)
227                 reconciled += rec
228                 unreconciled += unrec
229
230             # add the number of transactions for partners who have only one
231             # unreconciled transactions to the unreconciled count
232             partner_filter = partner_ids and 'AND partner_id not in (%s)' % ','.join(map(str, filter(None, partner_ids))) or ''
233             cr.execute(
234                 "SELECT count(*) " \
235                 "FROM account_move_line " \
236                 "WHERE account_id=%s " \
237                 "AND reconcile_id IS NULL " \
238                 "AND state <> 'draft' " + partner_filter,
239                 (account_id.id,))
240             additional_unrec = cr.fetchone()[0]
241             unreconciled = unreconciled + additional_unrec
242         context = dict(context, reconciled=reconciled, unreconciled=unreconciled)
243         model_data_ids = obj_model.search(cr,uid,[('model','=','ir.ui.view'),('name','=','account_automatic_reconcile_view1')])
244         resource_id = obj_model.read(cr, uid, model_data_ids, fields=['res_id'])[0]['res_id']
245         return {
246             'view_type': 'form',
247             'view_mode': 'form',
248             'res_model': 'account.automatic.reconcile',
249             'views': [(resource_id,'form')],
250             'type': 'ir.actions.act_window',
251             'target': 'new',
252             'context': context,
253         }
254
255
256 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: