fe33bded92bf268fc68b2f7074a997f484e5e091
[odoo/odoo.git] / addons / account / account_move_line.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 from datetime import datetime
24
25 from openerp import workflow
26 from openerp.osv import fields, osv
27 from openerp.tools.translate import _
28 import openerp.addons.decimal_precision as dp
29 from openerp import tools
30 from openerp.report import report_sxw
31 import openerp
32
33 class account_move_line(osv.osv):
34     _name = "account.move.line"
35     _description = "Journal Items"
36
37     def _query_get(self, cr, uid, obj='l', context=None):
38         fiscalyear_obj = self.pool.get('account.fiscalyear')
39         fiscalperiod_obj = self.pool.get('account.period')
40         account_obj = self.pool.get('account.account')
41         fiscalyear_ids = []
42         context = dict(context or {})
43         initial_bal = context.get('initial_bal', False)
44         company_clause = " "
45         if context.get('company_id', False):
46             company_clause = " AND " +obj+".company_id = %s" % context.get('company_id', False)
47         if not context.get('fiscalyear', False):
48             if context.get('all_fiscalyear', False):
49                 #this option is needed by the aged balance report because otherwise, if we search only the draft ones, an open invoice of a closed fiscalyear won't be displayed
50                 fiscalyear_ids = fiscalyear_obj.search(cr, uid, [])
51             else:
52                 fiscalyear_ids = fiscalyear_obj.search(cr, uid, [('state', '=', 'draft')])
53         else:
54             #for initial balance as well as for normal query, we check only the selected FY because the best practice is to generate the FY opening entries
55             fiscalyear_ids = [context['fiscalyear']]
56
57         fiscalyear_clause = (','.join([str(x) for x in fiscalyear_ids])) or '0'
58         state = context.get('state', False)
59         where_move_state = ''
60         where_move_lines_by_date = ''
61
62         if context.get('date_from', False) and context.get('date_to', False):
63             if initial_bal:
64                 where_move_lines_by_date = " AND " +obj+".move_id IN (SELECT id FROM account_move WHERE date < '" +context['date_from']+"')"
65             else:
66                 where_move_lines_by_date = " AND " +obj+".move_id IN (SELECT id FROM account_move WHERE date >= '" +context['date_from']+"' AND date <= '"+context['date_to']+"')"
67
68         if state:
69             if state.lower() not in ['all']:
70                 where_move_state= " AND "+obj+".move_id IN (SELECT id FROM account_move WHERE account_move.state = '"+state+"')"
71         if context.get('period_from', False) and context.get('period_to', False) and not context.get('periods', False):
72             if initial_bal:
73                 period_company_id = fiscalperiod_obj.browse(cr, uid, context['period_from'], context=context).company_id.id
74                 first_period = fiscalperiod_obj.search(cr, uid, [('company_id', '=', period_company_id)], order='date_start', limit=1)[0]
75                 context['periods'] = fiscalperiod_obj.build_ctx_periods(cr, uid, first_period, context['period_from'])
76             else:
77                 context['periods'] = fiscalperiod_obj.build_ctx_periods(cr, uid, context['period_from'], context['period_to'])
78         if context.get('periods', False):
79             if initial_bal:
80                 query = obj+".state <> 'draft' AND "+obj+".period_id IN (SELECT id FROM account_period WHERE fiscalyear_id IN (%s)) %s %s" % (fiscalyear_clause, where_move_state, where_move_lines_by_date)
81                 period_ids = fiscalperiod_obj.search(cr, uid, [('id', 'in', context['periods'])], order='date_start', limit=1)
82                 if period_ids and period_ids[0]:
83                     first_period = fiscalperiod_obj.browse(cr, uid, period_ids[0], context=context)
84                     ids = ','.join([str(x) for x in context['periods']])
85                     query = obj+".state <> 'draft' AND "+obj+".period_id IN (SELECT id FROM account_period WHERE fiscalyear_id IN (%s) AND date_start <= '%s' AND id NOT IN (%s)) %s %s" % (fiscalyear_clause, first_period.date_start, ids, where_move_state, where_move_lines_by_date)
86             else:
87                 ids = ','.join([str(x) for x in context['periods']])
88                 query = obj+".state <> 'draft' AND "+obj+".period_id IN (SELECT id FROM account_period WHERE fiscalyear_id IN (%s) AND id IN (%s)) %s %s" % (fiscalyear_clause, ids, where_move_state, where_move_lines_by_date)
89         else:
90             query = obj+".state <> 'draft' AND "+obj+".period_id IN (SELECT id FROM account_period WHERE fiscalyear_id IN (%s)) %s %s" % (fiscalyear_clause, where_move_state, where_move_lines_by_date)
91
92         if initial_bal and not context.get('periods', False) and not where_move_lines_by_date:
93             #we didn't pass any filter in the context, and the initial balance can't be computed using only the fiscalyear otherwise entries will be summed twice
94             #so we have to invalidate this query
95             raise osv.except_osv(_('Warning!'),_("You have not supplied enough arguments to compute the initial balance, please select a period and a journal in the context."))
96
97
98         if context.get('journal_ids', False):
99             query += ' AND '+obj+'.journal_id IN (%s)' % ','.join(map(str, context['journal_ids']))
100
101         if context.get('chart_account_id', False):
102             child_ids = account_obj._get_children_and_consol(cr, uid, [context['chart_account_id']], context=context)
103             query += ' AND '+obj+'.account_id IN (%s)' % ','.join(map(str, child_ids))
104
105         query += company_clause
106         return query
107
108     def _amount_residual(self, cr, uid, ids, field_names, args, context=None):
109         """
110            This function returns the residual amount on a receivable or payable account.move.line.
111            By default, it returns an amount in the currency of this journal entry (maybe different
112            of the company currency), but if you pass 'residual_in_company_currency' = True in the
113            context then the returned amount will be in company currency.
114         """
115         res = {}
116         if context is None:
117             context = {}
118         cur_obj = self.pool.get('res.currency')
119         for move_line in self.browse(cr, uid, ids, context=context):
120             res[move_line.id] = {
121                 'amount_residual': 0.0,
122                 'amount_residual_currency': 0.0,
123             }
124
125             if move_line.reconcile_id:
126                 continue
127             if not move_line.account_id.reconcile:
128                 #this function does not suport to be used on move lines not related to a reconcilable account
129                 continue
130
131             if move_line.currency_id:
132                 move_line_total = move_line.amount_currency
133                 sign = move_line.amount_currency < 0 and -1 or 1
134             else:
135                 move_line_total = move_line.debit - move_line.credit
136                 sign = (move_line.debit - move_line.credit) < 0 and -1 or 1
137             line_total_in_company_currency =  move_line.debit - move_line.credit
138             context_unreconciled = context.copy()
139             if move_line.reconcile_partial_id:
140                 for payment_line in move_line.reconcile_partial_id.line_partial_ids:
141                     if payment_line.id == move_line.id:
142                         continue
143                     if payment_line.currency_id and move_line.currency_id and payment_line.currency_id.id == move_line.currency_id.id:
144                             move_line_total += payment_line.amount_currency
145                     else:
146                         if move_line.currency_id:
147                             context_unreconciled.update({'date': payment_line.date})
148                             amount_in_foreign_currency = cur_obj.compute(cr, uid, move_line.company_id.currency_id.id, move_line.currency_id.id, (payment_line.debit - payment_line.credit), round=False, context=context_unreconciled)
149                             move_line_total += amount_in_foreign_currency
150                         else:
151                             move_line_total += (payment_line.debit - payment_line.credit)
152                     line_total_in_company_currency += (payment_line.debit - payment_line.credit)
153
154             result = move_line_total
155             res[move_line.id]['amount_residual_currency'] =  sign * (move_line.currency_id and self.pool.get('res.currency').round(cr, uid, move_line.currency_id, result) or result)
156             res[move_line.id]['amount_residual'] = sign * line_total_in_company_currency
157         return res
158
159     def default_get(self, cr, uid, fields, context=None):
160         data = self._default_get(cr, uid, fields, context=context)
161         for f in data.keys():
162             if f not in fields:
163                 del data[f]
164         return data
165
166     def _prepare_analytic_line(self, cr, uid, obj_line, context=None):
167         """
168         Prepare the values given at the create() of account.analytic.line upon the validation of a journal item having
169         an analytic account. This method is intended to be extended in other modules.
170
171         :param obj_line: browse record of the account.move.line that triggered the analytic line creation
172         """
173         return {'name': obj_line.name,
174                 'date': obj_line.date,
175                 'account_id': obj_line.analytic_account_id.id,
176                 'unit_amount': obj_line.quantity,
177                 'product_id': obj_line.product_id and obj_line.product_id.id or False,
178                 'product_uom_id': obj_line.product_uom_id and obj_line.product_uom_id.id or False,
179                 'amount': (obj_line.credit or  0.0) - (obj_line.debit or 0.0),
180                 'general_account_id': obj_line.account_id.id,
181                 'journal_id': obj_line.journal_id.analytic_journal_id.id,
182                 'ref': obj_line.ref,
183                 'move_id': obj_line.id,
184                 'user_id': uid,
185                }
186
187     def create_analytic_lines(self, cr, uid, ids, context=None):
188         acc_ana_line_obj = self.pool.get('account.analytic.line')
189         for obj_line in self.browse(cr, uid, ids, context=context):
190             if obj_line.analytic_account_id:
191                 if not obj_line.journal_id.analytic_journal_id:
192                     raise osv.except_osv(_('No Analytic Journal!'),_("You have to define an analytic journal on the '%s' journal!") % (obj_line.journal_id.name, ))
193                 if obj_line.analytic_lines:
194                     acc_ana_line_obj.unlink(cr,uid,[obj.id for obj in obj_line.analytic_lines])
195                 vals_line = self._prepare_analytic_line(cr, uid, obj_line, context=context)
196                 acc_ana_line_obj.create(cr, uid, vals_line)
197         return True
198
199     def _default_get_move_form_hook(self, cursor, user, data):
200         '''Called in the end of default_get method for manual entry in account_move form'''
201         if data.has_key('analytic_account_id'):
202             del(data['analytic_account_id'])
203         if data.has_key('account_tax_id'):
204             del(data['account_tax_id'])
205         return data
206
207     def convert_to_period(self, cr, uid, context=None):
208         if context is None:
209             context = {}
210         period_obj = self.pool.get('account.period')
211         #check if the period_id changed in the context from client side
212         if context.get('period_id', False):
213             period_id = context.get('period_id')
214             if type(period_id) == str:
215                 ids = period_obj.search(cr, uid, [('name', 'ilike', period_id)])
216                 context = dict(context, period_id=ids and ids[0] or False)
217         return context
218
219     def _default_get(self, cr, uid, fields, context=None):
220         #default_get should only do the following:
221         #   -propose the next amount in debit/credit in order to balance the move
222         #   -propose the next account from the journal (default debit/credit account) accordingly
223         context = dict(context or {})
224         account_obj = self.pool.get('account.account')
225         period_obj = self.pool.get('account.period')
226         journal_obj = self.pool.get('account.journal')
227         move_obj = self.pool.get('account.move')
228         tax_obj = self.pool.get('account.tax')
229         fiscal_pos_obj = self.pool.get('account.fiscal.position')
230         partner_obj = self.pool.get('res.partner')
231         currency_obj = self.pool.get('res.currency')
232
233         if not context.get('journal_id', False):
234             context['journal_id'] = context.get('search_default_journal_id', False)
235         if not context.get('period_id', False):
236             context['period_id'] = context.get('search_default_period_id', False)
237         context = self.convert_to_period(cr, uid, context)
238
239         # Compute simple values
240         data = super(account_move_line, self).default_get(cr, uid, fields, context=context)
241         if context.get('journal_id'):
242             total = 0.0
243             #in account.move form view, it is not possible to compute total debit and credit using
244             #a browse record. So we must use the context to pass the whole one2many field and compute the total
245             if context.get('line_id'):
246                 for move_line_dict in move_obj.resolve_2many_commands(cr, uid, 'line_id', context.get('line_id'), context=context):
247                     data['name'] = data.get('name') or move_line_dict.get('name')
248                     data['partner_id'] = data.get('partner_id') or move_line_dict.get('partner_id')
249                     total += move_line_dict.get('debit', 0.0) - move_line_dict.get('credit', 0.0)
250             elif context.get('period_id'):
251                 #find the date and the ID of the last unbalanced account.move encoded by the current user in that journal and period
252                 move_id = False
253                 cr.execute('''SELECT move_id, date FROM account_move_line
254                     WHERE journal_id = %s AND period_id = %s AND create_uid = %s AND state = %s
255                     ORDER BY id DESC limit 1''', (context['journal_id'], context['period_id'], uid, 'draft'))
256                 res = cr.fetchone()
257                 move_id = res and res[0] or False
258                 data['date'] = res and res[1] or period_obj.browse(cr, uid, context['period_id'], context=context).date_start
259                 data['move_id'] = move_id
260                 if move_id:
261                     #if there exist some unbalanced accounting entries that match the journal and the period,
262                     #we propose to continue the same move by copying the ref, the name, the partner...
263                     move = move_obj.browse(cr, uid, move_id, context=context)
264                     data.setdefault('name', move.line_id[-1].name)
265                     for l in move.line_id:
266                         data['partner_id'] = data.get('partner_id') or l.partner_id.id
267                         data['ref'] = data.get('ref') or l.ref
268                         total += (l.debit or 0.0) - (l.credit or 0.0)
269
270             #compute the total of current move
271             data['debit'] = total < 0 and -total or 0.0
272             data['credit'] = total > 0 and total or 0.0
273             #pick the good account on the journal accordingly if the next proposed line will be a debit or a credit
274             journal_data = journal_obj.browse(cr, uid, context['journal_id'], context=context)
275             account = total > 0 and journal_data.default_credit_account_id or journal_data.default_debit_account_id
276             #map the account using the fiscal position of the partner, if needed
277             part = data.get('partner_id') and partner_obj.browse(cr, uid, data['partner_id'], context=context) or False
278             if account and data.get('partner_id'):
279                 account = fiscal_pos_obj.map_account(cr, uid, part and part.property_account_position or False, account.id)
280                 account = account_obj.browse(cr, uid, account, context=context)
281             data['account_id'] =  account and account.id or False
282             #compute the amount in secondary currency of the account, if needed
283             if account and account.currency_id:
284                 data['currency_id'] = account.currency_id.id
285                 #set the context for the multi currency change
286                 compute_ctx = context.copy()
287                 compute_ctx.update({
288                         #the following 2 parameters are used to choose the currency rate, in case where the account
289                         #doesn't work with an outgoing currency rate method 'at date' but 'average'
290                         'res.currency.compute.account': account,
291                         'res.currency.compute.account_invert': True,
292                     })
293                 if data.get('date'):
294                     compute_ctx.update({'date': data['date']})
295                 data['amount_currency'] = currency_obj.compute(cr, uid, account.company_id.currency_id.id, data['currency_id'], -total, context=compute_ctx)
296         data = self._default_get_move_form_hook(cr, uid, data)
297         return data
298
299     def on_create_write(self, cr, uid, id, context=None):
300         if not id:
301             return []
302         ml = self.browse(cr, uid, id, context=context)
303         return map(lambda x: x.id, ml.move_id.line_id)
304
305     def _balance(self, cr, uid, ids, name, arg, context=None):
306         if context is None:
307             context = {}
308         c = context.copy()
309         c['initital_bal'] = True
310         sql = """SELECT l1.id, COALESCE(SUM(l2.debit-l2.credit), 0)
311                     FROM account_move_line l1 LEFT JOIN account_move_line l2
312                     ON (l1.account_id = l2.account_id
313                       AND l2.id <= l1.id
314                       AND """ + \
315                 self._query_get(cr, uid, obj='l2', context=c) + \
316                 ") WHERE l1.id IN %s GROUP BY l1.id"
317
318         cr.execute(sql, [tuple(ids)])
319         return dict(cr.fetchall())
320
321     def _invoice(self, cursor, user, ids, name, arg, context=None):
322         invoice_obj = self.pool.get('account.invoice')
323         res = {}
324         for line_id in ids:
325             res[line_id] = False
326         cursor.execute('SELECT l.id, i.id ' \
327                         'FROM account_move_line l, account_invoice i ' \
328                         'WHERE l.move_id = i.move_id ' \
329                         'AND l.id IN %s',
330                         (tuple(ids),))
331         invoice_ids = []
332         for line_id, invoice_id in cursor.fetchall():
333             res[line_id] = invoice_id
334             invoice_ids.append(invoice_id)
335         invoice_names = {False: ''}
336         for invoice_id, name in invoice_obj.name_get(cursor, user, invoice_ids, context=context):
337             invoice_names[invoice_id] = name
338         for line_id in res.keys():
339             invoice_id = res[line_id]
340             res[line_id] = (invoice_id, invoice_names[invoice_id])
341         return res
342
343     def name_get(self, cr, uid, ids, context=None):
344         if not ids:
345             return []
346         result = []
347         for line in self.browse(cr, uid, ids, context=context):
348             if line.ref:
349                 result.append((line.id, (line.move_id.name or '')+' ('+line.ref+')'))
350             else:
351                 result.append((line.id, line.move_id.name))
352         return result
353
354     def _balance_search(self, cursor, user, obj, name, args, domain=None, context=None):
355         if context is None:
356             context = {}
357         if not args:
358             return []
359         where = ' AND '.join(map(lambda x: '(abs(sum(debit-credit))'+x[1]+str(x[2])+')',args))
360         cursor.execute('SELECT id, SUM(debit-credit) FROM account_move_line \
361                      GROUP BY id, debit, credit having '+where)
362         res = cursor.fetchall()
363         if not res:
364             return [('id', '=', '0')]
365         return [('id', 'in', [x[0] for x in res])]
366
367     def _invoice_search(self, cursor, user, obj, name, args, context=None):
368         if not args:
369             return []
370         invoice_obj = self.pool.get('account.invoice')
371         i = 0
372         while i < len(args):
373             fargs = args[i][0].split('.', 1)
374             if len(fargs) > 1:
375                 args[i] = (fargs[0], 'in', invoice_obj.search(cursor, user,
376                     [(fargs[1], args[i][1], args[i][2])]))
377                 i += 1
378                 continue
379             if isinstance(args[i][2], basestring):
380                 res_ids = invoice_obj.name_search(cursor, user, args[i][2], [],
381                         args[i][1])
382                 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
383             i += 1
384         qu1, qu2 = [], []
385         for x in args:
386             if x[1] != 'in':
387                 if (x[2] is False) and (x[1] == '='):
388                     qu1.append('(i.id IS NULL)')
389                 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
390                     qu1.append('(i.id IS NOT NULL)')
391                 else:
392                     qu1.append('(i.id %s %s)' % (x[1], '%s'))
393                     qu2.append(x[2])
394             elif x[1] == 'in':
395                 if len(x[2]) > 0:
396                     qu1.append('(i.id IN (%s))' % (','.join(['%s'] * len(x[2]))))
397                     qu2 += x[2]
398                 else:
399                     qu1.append(' (False)')
400         if qu1:
401             qu1 = ' AND' + ' AND'.join(qu1)
402         else:
403             qu1 = ''
404         cursor.execute('SELECT l.id ' \
405                 'FROM account_move_line l, account_invoice i ' \
406                 'WHERE l.move_id = i.move_id ' + qu1, qu2)
407         res = cursor.fetchall()
408         if not res:
409             return [('id', '=', '0')]
410         return [('id', 'in', [x[0] for x in res])]
411
412     def _get_move_lines(self, cr, uid, ids, context=None):
413         result = []
414         for move in self.pool.get('account.move').browse(cr, uid, ids, context=context):
415             for line in move.line_id:
416                 result.append(line.id)
417         return result
418
419     def _get_reconcile(self, cr, uid, ids,name, unknow_none, context=None):
420         res = dict.fromkeys(ids, False)
421         for line in self.browse(cr, uid, ids, context=context):
422             if line.reconcile_id:
423                 res[line.id] = str(line.reconcile_id.name)
424             elif line.reconcile_partial_id:
425                 res[line.id] = str(line.reconcile_partial_id.name)
426         return res
427
428     def _get_move_from_reconcile(self, cr, uid, ids, context=None):
429         move = {}
430         for r in self.pool.get('account.move.reconcile').browse(cr, uid, ids, context=context):
431             for line in r.line_partial_ids:
432                 move[line.move_id.id] = True
433             for line in r.line_id:
434                 move[line.move_id.id] = True
435         move_line_ids = []
436         if move:
437             move_line_ids = self.pool.get('account.move.line').search(cr, uid, [('journal_id','in',move.keys())], context=context)
438         return move_line_ids
439
440
441     _columns = {
442         'name': fields.char('Name', required=True),
443         'quantity': fields.float('Quantity', digits=(16,2), help="The optional quantity expressed by this line, eg: number of product sold. The quantity is not a legal requirement but is very useful for some reports."),
444         'product_uom_id': fields.many2one('product.uom', 'Unit of Measure'),
445         'product_id': fields.many2one('product.product', 'Product'),
446         'debit': fields.float('Debit', digits_compute=dp.get_precision('Account')),
447         'credit': fields.float('Credit', digits_compute=dp.get_precision('Account')),
448         'account_id': fields.many2one('account.account', 'Account', required=True, ondelete="cascade", domain=[('type','<>','view'), ('type', '<>', 'closed')], select=2),
449         'move_id': fields.many2one('account.move', 'Journal Entry', ondelete="cascade", help="The move of this entry line.", select=2, required=True),
450         'narration': fields.related('move_id','narration', type='text', relation='account.move', string='Internal Note'),
451         'ref': fields.related('move_id', 'ref', string='Reference', type='char', store=True),
452         'statement_id': fields.many2one('account.bank.statement', 'Statement', help="The bank statement used for bank reconciliation", select=1, copy=False),
453         'reconcile_id': fields.many2one('account.move.reconcile', 'Reconcile', readonly=True, ondelete='set null', select=2, copy=False),
454         'reconcile_partial_id': fields.many2one('account.move.reconcile', 'Partial Reconcile', readonly=True, ondelete='set null', select=2, copy=False),
455         'reconcile_ref': fields.function(_get_reconcile, type='char', string='Reconcile Ref', oldname='reconcile', store={
456                     'account.move.line': (lambda self, cr, uid, ids, c={}: ids, ['reconcile_id','reconcile_partial_id'], 50),'account.move.reconcile': (_get_move_from_reconcile, None, 50)}),
457         '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')),
458         'amount_residual_currency': fields.function(_amount_residual, string='Residual Amount in Currency', multi="residual", help="The residual amount on a receivable or payable of a journal entry expressed in its currency (maybe different of the company currency)."),
459         'amount_residual': fields.function(_amount_residual, string='Residual Amount', multi="residual", help="The residual amount on a receivable or payable of a journal entry expressed in the company currency."),
460         'currency_id': fields.many2one('res.currency', 'Currency', help="The optional other currency if it is a multi-currency entry."),
461         'journal_id': fields.related('move_id', 'journal_id', string='Journal', type='many2one', relation='account.journal', required=True, select=True,
462                                 store = {
463                                     'account.move': (_get_move_lines, ['journal_id'], 20)
464                                 }),
465         'period_id': fields.related('move_id', 'period_id', string='Period', type='many2one', relation='account.period', required=True, select=True,
466                                 store = {
467                                     'account.move': (_get_move_lines, ['period_id'], 20)
468                                 }),
469         'blocked': fields.boolean('No Follow-up', help="You can check this box to mark this journal item as a litigation with the associated partner"),
470         'partner_id': fields.many2one('res.partner', 'Partner', select=1, ondelete='restrict'),
471         'date_maturity': fields.date('Due date', select=True ,help="This field is used for payable and receivable journal entries. You can put the limit date for the payment of this line."),
472         'date': fields.related('move_id','date', string='Effective date', type='date', required=True, select=True,
473                                 store = {
474                                     'account.move': (_get_move_lines, ['date'], 20)
475                                 }),
476         'date_created': fields.date('Creation date', select=True),
477         'analytic_lines': fields.one2many('account.analytic.line', 'move_id', 'Analytic lines'),
478         'centralisation': fields.selection([('normal','Normal'),('credit','Credit Centralisation'),('debit','Debit Centralisation'),('currency','Currency Adjustment')], 'Centralisation', size=8),
479         'balance': fields.function(_balance, fnct_search=_balance_search, string='Balance'),
480         'state': fields.selection([('draft','Unbalanced'), ('valid','Balanced')], 'Status', readonly=True, copy=False),
481         'tax_code_id': fields.many2one('account.tax.code', 'Tax Account', help="The Account can either be a base tax code or a tax code account."),
482         'tax_amount': fields.float('Tax/Base Amount', digits_compute=dp.get_precision('Account'), select=True, help="If the Tax account is a tax code account, this field will contain the taxed amount.If the tax account is base tax code, "\
483                     "this field will contain the basic amount(without tax)."),
484         'invoice': fields.function(_invoice, string='Invoice',
485             type='many2one', relation='account.invoice', fnct_search=_invoice_search),
486         'account_tax_id':fields.many2one('account.tax', 'Tax', copy=False),
487         'analytic_account_id': fields.many2one('account.analytic.account', 'Analytic Account'),
488         'company_id': fields.related('account_id', 'company_id', type='many2one', relation='res.company',
489                             string='Company', store=True, readonly=True)
490     }
491
492     def _get_date(self, cr, uid, context=None):
493         if context is None:
494             context or {}
495         period_obj = self.pool.get('account.period')
496         dt = time.strftime('%Y-%m-%d')
497         if context.get('journal_id') and context.get('period_id'):
498             cr.execute('SELECT date FROM account_move_line ' \
499                     'WHERE journal_id = %s AND period_id = %s ' \
500                     'ORDER BY id DESC limit 1',
501                     (context['journal_id'], context['period_id']))
502             res = cr.fetchone()
503             if res:
504                 dt = res[0]
505             else:
506                 period = period_obj.browse(cr, uid, context['period_id'], context=context)
507                 dt = period.date_start
508         return dt
509
510     def _get_currency(self, cr, uid, context=None):
511         if context is None:
512             context = {}
513         if not context.get('journal_id', False):
514             return False
515         cur = self.pool.get('account.journal').browse(cr, uid, context['journal_id']).currency
516         return cur and cur.id or False
517
518     def _get_period(self, cr, uid, context=None):
519         """
520         Return  default account period value
521         """
522         context = context or {}
523         if context.get('period_id', False):
524             return context['period_id']
525         account_period_obj = self.pool.get('account.period')
526         ids = account_period_obj.find(cr, uid, context=context)
527         period_id = False
528         if ids:
529             period_id = ids[0]
530         return period_id
531
532     def _get_journal(self, cr, uid, context=None):
533         """
534         Return journal based on the journal type
535         """
536         context = context or {}
537         if context.get('journal_id', False):
538             return context['journal_id']
539         journal_id = False
540
541         journal_pool = self.pool.get('account.journal')
542         if context.get('journal_type', False):
543             jids = journal_pool.search(cr, uid, [('type','=', context.get('journal_type'))])
544             if not jids:
545                 model, action_id = self.pool['ir.model.data'].get_object_reference(cr, uid, 'account', 'action_account_journal_form')
546                 msg = _("""Cannot find any account journal of "%s" type for this company, You should create one.\n Please go to Journal Configuration""") % context.get('journal_type').replace('_', ' ').title()
547                 raise openerp.exceptions.RedirectWarning(msg, action_id, _('Go to the configuration panel'))
548             journal_id = jids[0]
549         return journal_id
550
551
552     _defaults = {
553         'blocked': False,
554         'centralisation': 'normal',
555         'date': _get_date,
556         'date_created': fields.date.context_today,
557         'state': 'draft',
558         'currency_id': _get_currency,
559         'journal_id': _get_journal,
560         'credit': 0.0,
561         'debit': 0.0,
562         'amount_currency': 0.0,
563         'account_id': lambda self, cr, uid, c: c.get('account_id', False),
564         'period_id': _get_period,
565         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.move.line', context=c)
566     }
567     _order = "date desc, id desc"
568     _sql_constraints = [
569         ('credit_debit1', 'CHECK (credit*debit=0)',  'Wrong credit or debit value in accounting entry !'),
570         ('credit_debit2', 'CHECK (credit+debit>=0)', 'Wrong credit or debit value in accounting entry !'),
571     ]
572
573     def _auto_init(self, cr, context=None):
574         res = super(account_move_line, self)._auto_init(cr, context=context)
575         cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = \'account_move_line_journal_id_period_id_index\'')
576         if not cr.fetchone():
577             cr.execute('CREATE INDEX account_move_line_journal_id_period_id_index ON account_move_line (journal_id, period_id)')
578         cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = %s', ('account_move_line_date_id_index',))
579         if not cr.fetchone():
580             cr.execute('CREATE INDEX account_move_line_date_id_index ON account_move_line (date DESC, id desc)')
581         return res
582
583     def _check_no_view(self, cr, uid, ids, context=None):
584         lines = self.browse(cr, uid, ids, context=context)
585         for l in lines:
586             if l.account_id.type in ('view', 'consolidation'):
587                 return False
588         return True
589
590     def _check_no_closed(self, cr, uid, ids, context=None):
591         lines = self.browse(cr, uid, ids, context=context)
592         for l in lines:
593             if l.account_id.type == 'closed':
594                 raise osv.except_osv(_('Error!'), _('You cannot create journal items on a closed account %s %s.') % (l.account_id.code, l.account_id.name))
595         return True
596
597     def _check_company_id(self, cr, uid, ids, context=None):
598         lines = self.browse(cr, uid, ids, context=context)
599         for l in lines:
600             if l.company_id != l.account_id.company_id or l.company_id != l.period_id.company_id:
601                 return False
602         return True
603
604     def _check_date(self, cr, uid, ids, context=None):
605         for l in self.browse(cr, uid, ids, context=context):
606             if l.journal_id.allow_date:
607                 if not time.strptime(l.date[:10],'%Y-%m-%d') >= time.strptime(l.period_id.date_start, '%Y-%m-%d') or not time.strptime(l.date[:10], '%Y-%m-%d') <= time.strptime(l.period_id.date_stop, '%Y-%m-%d'):
608                     return False
609         return True
610
611     def _check_currency(self, cr, uid, ids, context=None):
612         for l in self.browse(cr, uid, ids, context=context):
613             if l.account_id.currency_id:
614                 if not l.currency_id or not l.currency_id.id == l.account_id.currency_id.id:
615                     return False
616         return True
617
618     def _check_currency_and_amount(self, cr, uid, ids, context=None):
619         for l in self.browse(cr, uid, ids, context=context):
620             if (l.amount_currency and not l.currency_id):
621                 return False
622         return True
623
624     def _check_currency_amount(self, cr, uid, ids, context=None):
625         for l in self.browse(cr, uid, ids, context=context):
626             if l.amount_currency:
627                 if (l.amount_currency > 0.0 and l.credit > 0.0) or (l.amount_currency < 0.0 and l.debit > 0.0):
628                     return False
629         return True
630
631     def _check_currency_company(self, cr, uid, ids, context=None):
632         for l in self.browse(cr, uid, ids, context=context):
633             if l.currency_id.id == l.company_id.currency_id.id:
634                 return False
635         return True
636
637     _constraints = [
638         (_check_no_view, 'You cannot create journal items on an account of type view or consolidation.', ['account_id']),
639         (_check_no_closed, 'You cannot create journal items on closed account.', ['account_id']),
640         (_check_company_id, 'Account and Period must belong to the same company.', ['company_id']),
641         (_check_date, 'The date of your Journal Entry is not in the defined period! You should change the date or remove this constraint from the journal.', ['date']),
642         (_check_currency, 'The selected account of your Journal Entry forces to provide a secondary currency. You should remove the secondary currency on the account or select a multi-currency view on the journal.', ['currency_id']),
643         (_check_currency_and_amount, "You cannot create journal items with a secondary currency without recording both 'currency' and 'amount currency' field.", ['currency_id','amount_currency']),
644         (_check_currency_amount, 'The amount expressed in the secondary currency must be positive when account is debited and negative when account is credited.', ['amount_currency']),
645         (_check_currency_company, "You cannot provide a secondary currency if it is the same than the company one." , ['currency_id']),
646     ]
647
648     #TODO: ONCHANGE_ACCOUNT_ID: set account_tax_id
649     def onchange_currency(self, cr, uid, ids, account_id, amount, currency_id, date=False, journal=False, context=None):
650         if context is None:
651             context = {}
652         account_obj = self.pool.get('account.account')
653         journal_obj = self.pool.get('account.journal')
654         currency_obj = self.pool.get('res.currency')
655         if (not currency_id) or (not account_id):
656             return {}
657         result = {}
658         acc = account_obj.browse(cr, uid, account_id, context=context)
659         if (amount>0) and journal:
660             x = journal_obj.browse(cr, uid, journal).default_credit_account_id
661             if x: acc = x
662         context = dict(context)
663         context.update({
664                 'date': date,
665                 'res.currency.compute.account': acc,
666             })
667         v = currency_obj.compute(cr, uid, currency_id, acc.company_id.currency_id.id, amount, context=context)
668         result['value'] = {
669             'debit': v > 0 and v or 0.0,
670             'credit': v < 0 and -v or 0.0
671         }
672         return result
673
674     def onchange_partner_id(self, cr, uid, ids, move_id, partner_id, account_id=None, debit=0, credit=0, date=False, journal=False, context=None):
675         partner_obj = self.pool.get('res.partner')
676         payment_term_obj = self.pool.get('account.payment.term')
677         journal_obj = self.pool.get('account.journal')
678         fiscal_pos_obj = self.pool.get('account.fiscal.position')
679         val = {}
680         val['date_maturity'] = False
681
682         if not partner_id:
683             return {'value':val}
684         if not date:
685             date = datetime.now().strftime('%Y-%m-%d')
686         jt = False
687         if journal:
688             jt = journal_obj.browse(cr, uid, journal, context=context).type
689         part = partner_obj.browse(cr, uid, partner_id, context=context)
690
691         payment_term_id = False
692         if jt and jt in ('purchase', 'purchase_refund') and part.property_supplier_payment_term:
693             payment_term_id = part.property_supplier_payment_term.id
694         elif jt and part.property_payment_term:
695             payment_term_id = part.property_payment_term.id
696         if payment_term_id:
697             res = payment_term_obj.compute(cr, uid, payment_term_id, 100, date)
698             if res:
699                 val['date_maturity'] = res[0][0]
700         if not account_id:
701             id1 = part.property_account_payable.id
702             id2 =  part.property_account_receivable.id
703             if jt:
704                 if jt in ('sale', 'purchase_refund'):
705                     val['account_id'] = fiscal_pos_obj.map_account(cr, uid, part and part.property_account_position or False, id2)
706                 elif jt in ('purchase', 'sale_refund'):
707                     val['account_id'] = fiscal_pos_obj.map_account(cr, uid, part and part.property_account_position or False, id1)
708                 elif jt in ('general', 'bank', 'cash'):
709                     if part.customer:
710                         val['account_id'] = fiscal_pos_obj.map_account(cr, uid, part and part.property_account_position or False, id2)
711                     elif part.supplier:
712                         val['account_id'] = fiscal_pos_obj.map_account(cr, uid, part and part.property_account_position or False, id1)
713                 if val.get('account_id', False):
714                     d = self.onchange_account_id(cr, uid, ids, account_id=val['account_id'], partner_id=part.id, context=context)
715                     val.update(d['value'])
716         return {'value':val}
717
718     def onchange_account_id(self, cr, uid, ids, account_id=False, partner_id=False, context=None):
719         account_obj = self.pool.get('account.account')
720         partner_obj = self.pool.get('res.partner')
721         fiscal_pos_obj = self.pool.get('account.fiscal.position')
722         val = {}
723         if account_id:
724             res = account_obj.browse(cr, uid, account_id, context=context)
725             tax_ids = res.tax_ids
726             if tax_ids and partner_id:
727                 part = partner_obj.browse(cr, uid, partner_id, context=context)
728                 tax_id = fiscal_pos_obj.map_tax(cr, uid, part and part.property_account_position or False, tax_ids)[0]
729             else:
730                 tax_id = tax_ids and tax_ids[0].id or False
731             val['account_tax_id'] = tax_id
732         return {'value': val}
733     #
734     # type: the type if reconciliation (no logic behind this field, for info)
735     #
736     # writeoff; entry generated for the difference between the lines
737     #
738     def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False):
739         if context is None:
740             context = {}
741         if context.get('fiscalyear'):
742             args.append(('period_id.fiscalyear_id', '=', context.get('fiscalyear', False)))
743         if context and context.get('next_partner_only', False):
744             if not context.get('partner_id', False):
745                 partner = self.list_partners_to_reconcile(cr, uid, context=context)
746                 if partner:
747                     partner = partner[0]
748             else:
749                 partner = context.get('partner_id', False)
750             if not partner:
751                 return []
752             args.append(('partner_id', '=', partner[0]))
753         return super(account_move_line, self).search(cr, uid, args, offset, limit, order, context, count)
754
755     def prepare_move_lines_for_reconciliation_widget(self, cr, uid, lines, target_currency=False, target_date=False, context=None):
756         """ Returns move lines formatted for the manual/bank reconciliation widget
757
758             :param target_currency: curreny you want the move line debit/credit converted into
759             :param target_date: date to use for the monetary conversion
760         """
761         if not lines:
762             return []
763         if context is None:
764             context = {}
765         ctx = context.copy()
766         currency_obj = self.pool.get('res.currency')
767         company_currency = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.currency_id
768         rml_parser = report_sxw.rml_parse(cr, uid, 'reconciliation_widget_aml', context=context)
769         reconcile_partial_ids = []  # for a partial reconciliation, take only one line
770         ret = []
771
772         for line in lines:
773             if line.reconcile_partial_id and line.reconcile_partial_id.id in reconcile_partial_ids:
774                 continue
775             partial_reconciliation_siblings_ids = []
776             if line.reconcile_partial_id:
777                 reconcile_partial_ids.append(line.reconcile_partial_id.id)
778                 partial_reconciliation_siblings_ids = self.search(cr, uid, [('reconcile_partial_id', '=', line.reconcile_partial_id.id)], context=context)
779                 partial_reconciliation_siblings_ids.remove(line.id)
780
781             ret_line = {
782                 'id': line.id,
783                 'name': line.name if line.name != '/' else line.move_id.name,
784                 'ref': line.move_id.ref,
785                 'account_code': line.account_id.code,
786                 'account_name': line.account_id.name,
787                 'account_type': line.account_id.type,
788                 'date_maturity': line.date_maturity,
789                 'date': line.date,
790                 'period_name': line.period_id.name,
791                 'journal_name': line.journal_id.name,
792                 'partner_id': line.partner_id.id,
793                 'partner_name': line.partner_id.name,
794                 'is_partially_reconciled': bool(line.reconcile_partial_id),
795                 'partial_reconciliation_siblings_ids': partial_reconciliation_siblings_ids,
796             }
797
798             # Amount residual can be negative
799             debit = line.debit
800             credit = line.credit
801             total_amount = debit-credit
802             total_amount_currency = line.amount_currency
803             amount_residual = line.amount_residual
804             amount_residual_currency = line.amount_residual_currency
805             if line.amount_residual < 0:
806                 debit, credit = credit, debit
807                 amount_residual = -amount_residual
808                 amount_residual_currency = -amount_residual_currency
809
810             # Get right debit / credit:
811             line_currency = line.currency_id or company_currency
812             amount_currency_str = ""
813             total_amount_currency_str = ""
814             if line.currency_id and line.amount_currency:
815                 amount_currency_str = rml_parser.formatLang(amount_residual_currency, currency_obj=line.currency_id)
816                 total_amount_currency_str = rml_parser.formatLang(total_amount_currency, currency_obj=line.currency_id)
817             if target_currency and line_currency == target_currency and target_currency != company_currency:
818                 debit = debit > 0 and amount_residual_currency or 0.0
819                 credit = credit > 0 and amount_residual_currency or 0.0
820                 amount_currency_str = rml_parser.formatLang(amount_residual, currency_obj=company_currency)
821                 total_amount_currency_str = rml_parser.formatLang(total_amount, currency_obj=company_currency)
822                 amount_str = rml_parser.formatLang(debit or credit, currency_obj=target_currency)
823                 total_amount_str = rml_parser.formatLang(total_amount_currency, currency_obj=target_currency)
824             else:
825                 debit = debit > 0 and amount_residual or 0.0
826                 credit = credit > 0 and amount_residual or 0.0
827                 amount_str = rml_parser.formatLang(debit or credit, currency_obj=company_currency)
828                 total_amount_str = rml_parser.formatLang(total_amount, currency_obj=company_currency)
829                 if target_currency and target_currency != company_currency:
830                     amount_currency_str = rml_parser.formatLang(debit or credit, currency_obj=line_currency)
831                     total_amount_currency_str = rml_parser.formatLang(total_amount, currency_obj=line_currency)
832                     ctx = context.copy()
833                     if target_date:
834                         ctx.update({'date': target_date})
835                     debit = currency_obj.compute(cr, uid, target_currency.id, company_currency.id, debit, context=ctx)
836                     credit = currency_obj.compute(cr, uid, target_currency.id, company_currency.id, credit, context=ctx)
837                     amount_str = rml_parser.formatLang(debit or credit, currency_obj=target_currency)
838                     total_amount = currency_obj.compute(cr, uid, target_currency.id, company_currency.id, total_amount, context=ctx)
839                     total_amount_str = rml_parser.formatLang(total_amount, currency_obj=target_currency)
840
841             ret_line['credit'] = credit
842             ret_line['debit'] = debit
843             ret_line['amount_str'] = amount_str
844             ret_line['amount_currency_str'] = amount_currency_str
845             ret_line['total_amount_str'] = total_amount_str # For partial reconciliations
846             ret_line['total_amount_currency_str'] = total_amount_currency_str
847             ret.append(ret_line)
848         return ret
849
850     def list_partners_to_reconcile(self, cr, uid, context=None):
851         cr.execute(
852              """SELECT partner_id FROM (
853                 SELECT l.partner_id, p.last_reconciliation_date, SUM(l.debit) AS debit, SUM(l.credit) AS credit, MAX(l.create_date) AS max_date
854                 FROM account_move_line l
855                 RIGHT JOIN account_account a ON (a.id = l.account_id)
856                 RIGHT JOIN res_partner p ON (l.partner_id = p.id)
857                     WHERE a.reconcile IS TRUE
858                     AND l.reconcile_id IS NULL
859                     AND l.state <> 'draft'
860                     GROUP BY l.partner_id, p.last_reconciliation_date
861                 ) AS s
862                 WHERE debit > 0 AND credit > 0 AND (last_reconciliation_date IS NULL OR max_date > last_reconciliation_date)
863                 ORDER BY last_reconciliation_date""")
864         ids = [x[0] for x in cr.fetchall()]
865         if not ids:
866             return []
867
868         # To apply the ir_rules
869         partner_obj = self.pool.get('res.partner')
870         ids = partner_obj.search(cr, uid, [('id', 'in', ids)], context=context)
871         return partner_obj.name_get(cr, uid, ids, context=context)
872
873     def reconcile_partial(self, cr, uid, ids, type='auto', context=None, writeoff_acc_id=False, writeoff_period_id=False, writeoff_journal_id=False):
874         move_rec_obj = self.pool.get('account.move.reconcile')
875         merges = []
876         unmerge = []
877         total = 0.0
878         merges_rec = []
879         company_list = []
880         if context is None:
881             context = {}
882         for line in self.browse(cr, uid, ids, context=context):
883             if company_list and not line.company_id.id in company_list:
884                 raise osv.except_osv(_('Warning!'), _('To reconcile the entries company should be the same for all entries.'))
885             company_list.append(line.company_id.id)
886
887         for line in self.browse(cr, uid, ids, context=context):
888             if line.account_id.currency_id:
889                 currency_id = line.account_id.currency_id
890             else:
891                 currency_id = line.company_id.currency_id
892             if line.reconcile_id:
893                 raise osv.except_osv(_('Warning'), _("Journal Item '%s' (id: %s), Move '%s' is already reconciled!") % (line.name, line.id, line.move_id.name))
894             if line.reconcile_partial_id:
895                 for line2 in line.reconcile_partial_id.line_partial_ids:
896                     if line2.state != 'valid':
897                         raise osv.except_osv(_('Warning'), _("Journal Item '%s' (id: %s) cannot be used in a reconciliation as it is not balanced!") % (line2.name, line2.id))
898                     if not line2.reconcile_id:
899                         if line2.id not in merges:
900                             merges.append(line2.id)
901                         if line2.account_id.currency_id:
902                             total += line2.amount_currency
903                         else:
904                             total += (line2.debit or 0.0) - (line2.credit or 0.0)
905                 merges_rec.append(line.reconcile_partial_id.id)
906             else:
907                 unmerge.append(line.id)
908                 if line.account_id.currency_id:
909                     total += line.amount_currency
910                 else:
911                     total += (line.debit or 0.0) - (line.credit or 0.0)
912         if self.pool.get('res.currency').is_zero(cr, uid, currency_id, total):
913             res = self.reconcile(cr, uid, merges+unmerge, context=context, writeoff_acc_id=writeoff_acc_id, writeoff_period_id=writeoff_period_id, writeoff_journal_id=writeoff_journal_id)
914             return res
915         # marking the lines as reconciled does not change their validity, so there is no need
916         # to revalidate their moves completely.
917         reconcile_context = dict(context, novalidate=True)
918         r_id = move_rec_obj.create(cr, uid, {
919             'type': type,
920             'line_partial_ids': map(lambda x: (4,x,False), merges+unmerge)
921         }, context=reconcile_context)
922         move_rec_obj.reconcile_partial_check(cr, uid, [r_id] + merges_rec, context=reconcile_context)
923         return r_id
924
925     def reconcile(self, cr, uid, ids, type='auto', writeoff_acc_id=False, writeoff_period_id=False, writeoff_journal_id=False, context=None):
926         account_obj = self.pool.get('account.account')
927         move_obj = self.pool.get('account.move')
928         move_rec_obj = self.pool.get('account.move.reconcile')
929         partner_obj = self.pool.get('res.partner')
930         currency_obj = self.pool.get('res.currency')
931         lines = self.browse(cr, uid, ids, context=context)
932         unrec_lines = filter(lambda x: not x['reconcile_id'], lines)
933         credit = debit = 0.0
934         currency = 0.0
935         account_id = False
936         partner_id = False
937         if context is None:
938             context = {}
939         company_list = []
940         for line in self.browse(cr, uid, ids, context=context):
941             if company_list and not line.company_id.id in company_list:
942                 raise osv.except_osv(_('Warning!'), _('To reconcile the entries company should be the same for all entries.'))
943             company_list.append(line.company_id.id)
944         for line in unrec_lines:
945             if line.state <> 'valid':
946                 raise osv.except_osv(_('Error!'),
947                         _('Entry "%s" is not valid !') % line.name)
948             credit += line['credit']
949             debit += line['debit']
950             currency += line['amount_currency'] or 0.0
951             account_id = line['account_id']['id']
952             partner_id = (line['partner_id'] and line['partner_id']['id']) or False
953         writeoff = debit - credit
954
955         # Ifdate_p in context => take this date
956         if context.has_key('date_p') and context['date_p']:
957             date=context['date_p']
958         else:
959             date = time.strftime('%Y-%m-%d')
960
961         cr.execute('SELECT account_id, reconcile_id '\
962                    'FROM account_move_line '\
963                    'WHERE id IN %s '\
964                    'GROUP BY account_id,reconcile_id',
965                    (tuple(ids), ))
966         r = cr.fetchall()
967         #TODO: move this check to a constraint in the account_move_reconcile object
968         if len(r) != 1:
969             raise osv.except_osv(_('Error'), _('Entries are not of the same account or already reconciled ! '))
970         if not unrec_lines:
971             raise osv.except_osv(_('Error!'), _('Entry is already reconciled.'))
972         account = account_obj.browse(cr, uid, account_id, context=context)
973         if not account.reconcile:
974             raise osv.except_osv(_('Error'), _('The account is not defined to be reconciled !'))
975         if r[0][1] != None:
976             raise osv.except_osv(_('Error!'), _('Some entries are already reconciled.'))
977
978         if (not currency_obj.is_zero(cr, uid, account.company_id.currency_id, writeoff)) or \
979            (account.currency_id and (not currency_obj.is_zero(cr, uid, account.currency_id, currency))):
980             if not writeoff_acc_id:
981                 raise osv.except_osv(_('Warning!'), _('You have to provide an account for the write off/exchange difference entry.'))
982             if writeoff > 0:
983                 debit = writeoff
984                 credit = 0.0
985                 self_credit = writeoff
986                 self_debit = 0.0
987             else:
988                 debit = 0.0
989                 credit = -writeoff
990                 self_credit = 0.0
991                 self_debit = -writeoff
992             # If comment exist in context, take it
993             if 'comment' in context and context['comment']:
994                 libelle = context['comment']
995             else:
996                 libelle = _('Write-Off')
997
998             cur_obj = self.pool.get('res.currency')
999             cur_id = False
1000             amount_currency_writeoff = 0.0
1001             if context.get('company_currency_id',False) != context.get('currency_id',False):
1002                 cur_id = context.get('currency_id',False)
1003                 for line in unrec_lines:
1004                     if line.currency_id and line.currency_id.id == context.get('currency_id',False):
1005                         amount_currency_writeoff += line.amount_currency
1006                     else:
1007                         tmp_amount = cur_obj.compute(cr, uid, line.account_id.company_id.currency_id.id, context.get('currency_id',False), abs(line.debit-line.credit), context={'date': line.date})
1008                         amount_currency_writeoff += (line.debit > 0) and tmp_amount or -tmp_amount
1009
1010             writeoff_lines = [
1011                 (0, 0, {
1012                     'name': libelle,
1013                     'debit': self_debit,
1014                     'credit': self_credit,
1015                     'account_id': account_id,
1016                     'date': date,
1017                     'partner_id': partner_id,
1018                     'currency_id': cur_id or (account.currency_id.id or False),
1019                     'amount_currency': amount_currency_writeoff and -1 * amount_currency_writeoff or (account.currency_id.id and -1 * currency or 0.0)
1020                 }),
1021                 (0, 0, {
1022                     'name': libelle,
1023                     'debit': debit,
1024                     'credit': credit,
1025                     'account_id': writeoff_acc_id,
1026                     'analytic_account_id': context.get('analytic_id', False),
1027                     'date': date,
1028                     'partner_id': partner_id,
1029                     'currency_id': cur_id or (account.currency_id.id or False),
1030                     'amount_currency': amount_currency_writeoff and amount_currency_writeoff or (account.currency_id.id and currency or 0.0)
1031                 })
1032             ]
1033
1034             writeoff_move_id = move_obj.create(cr, uid, {
1035                 'period_id': writeoff_period_id,
1036                 'journal_id': writeoff_journal_id,
1037                 'date':date,
1038                 'state': 'draft',
1039                 'line_id': writeoff_lines
1040             })
1041
1042             writeoff_line_ids = self.search(cr, uid, [('move_id', '=', writeoff_move_id), ('account_id', '=', account_id)])
1043             if account_id == writeoff_acc_id:
1044                 writeoff_line_ids = [writeoff_line_ids[1]]
1045             ids += writeoff_line_ids
1046
1047         # marking the lines as reconciled does not change their validity, so there is no need
1048         # to revalidate their moves completely.
1049         reconcile_context = dict(context, novalidate=True)
1050         r_id = move_rec_obj.create(cr, uid, {
1051             'type': type,
1052             'line_id': map(lambda x: (4, x, False), ids),
1053             'line_partial_ids': map(lambda x: (3, x, False), ids)
1054         }, context=reconcile_context)
1055         # the id of the move.reconcile is written in the move.line (self) by the create method above
1056         # because of the way the line_id are defined: (4, x, False)
1057         for id in ids:
1058             workflow.trg_trigger(uid, 'account.move.line', id, cr)
1059
1060         if lines and lines[0]:
1061             partner_id = lines[0].partner_id and lines[0].partner_id.id or False
1062             if partner_id and not partner_obj.has_something_to_reconcile(cr, uid, partner_id, context=context):
1063                 partner_obj.mark_as_reconciled(cr, uid, [partner_id], context=context)
1064         return r_id
1065
1066     def view_header_get(self, cr, user, view_id, view_type, context=None):
1067         if context is None:
1068             context = {}
1069         context = self.convert_to_period(cr, user, context=context)
1070         if context.get('account_id', False):
1071             cr.execute('SELECT code FROM account_account WHERE id = %s', (context['account_id'], ))
1072             res = cr.fetchone()
1073             if res:
1074                 res = _('Entries: ')+ (res[0] or '')
1075             return res
1076         if (not context.get('journal_id', False)) or (not context.get('period_id', False)):
1077             return False
1078         if context.get('search_default_journal_id', False):
1079             context['journal_id'] = context.get('search_default_journal_id')
1080         cr.execute('SELECT code FROM account_journal WHERE id = %s', (context['journal_id'], ))
1081         j = cr.fetchone()[0] or ''
1082         cr.execute('SELECT code FROM account_period WHERE id = %s', (context['period_id'], ))
1083         p = cr.fetchone()[0] or ''
1084         if j or p:
1085             return j + (p and (':' + p) or '')
1086         return False
1087
1088     def onchange_date(self, cr, user, ids, date, context=None):
1089         """
1090         Returns a dict that contains new values and context
1091         @param cr: A database cursor
1092         @param user: ID of the user currently logged in
1093         @param date: latest value from user input for field date
1094         @param args: other arguments
1095         @param context: context arguments, like lang, time zone
1096         @return: Returns a dict which contains new values, and context
1097         """
1098         res = {}
1099         if context is None:
1100             context = {}
1101         period_pool = self.pool.get('account.period')
1102         pids = period_pool.find(cr, user, date, context=context)
1103         if pids:
1104             res.update({'period_id':pids[0]})
1105             context = dict(context, period_id=pids[0])
1106         return {
1107             'value':res,
1108             'context':context,
1109         }
1110
1111     def _check_moves(self, cr, uid, context=None):
1112         # use the first move ever created for this journal and period
1113         if context is None:
1114             context = {}
1115         cr.execute('SELECT id, state, name FROM account_move WHERE journal_id = %s AND period_id = %s ORDER BY id limit 1', (context['journal_id'],context['period_id']))
1116         res = cr.fetchone()
1117         if res:
1118             if res[1] != 'draft':
1119                 raise osv.except_osv(_('User Error!'),
1120                        _('The account move (%s) for centralisation ' \
1121                                 'has been confirmed.') % res[2])
1122         return res
1123
1124     def _remove_move_reconcile(self, cr, uid, move_ids=None, opening_reconciliation=False, context=None):
1125         # Function remove move rencocile ids related with moves
1126         obj_move_line = self.pool.get('account.move.line')
1127         obj_move_rec = self.pool.get('account.move.reconcile')
1128         unlink_ids = []
1129         if not move_ids:
1130             return True
1131         recs = obj_move_line.read(cr, uid, move_ids, ['reconcile_id', 'reconcile_partial_id'])
1132         full_recs = filter(lambda x: x['reconcile_id'], recs)
1133         rec_ids = [rec['reconcile_id'][0] for rec in full_recs]
1134         part_recs = filter(lambda x: x['reconcile_partial_id'], recs)
1135         part_rec_ids = [rec['reconcile_partial_id'][0] for rec in part_recs]
1136         unlink_ids += rec_ids
1137         unlink_ids += part_rec_ids
1138         all_moves = obj_move_line.search(cr, uid, ['|',('reconcile_id', 'in', unlink_ids),('reconcile_partial_id', 'in', unlink_ids)])
1139         all_moves = list(set(all_moves) - set(move_ids))
1140         if unlink_ids:
1141             if opening_reconciliation:
1142                 raise osv.except_osv(_('Warning!'),
1143                     _('Opening Entries have already been generated.  Please run "Cancel Closing Entries" wizard to cancel those entries and then run this wizard.'))
1144                 obj_move_rec.write(cr, uid, unlink_ids, {'opening_reconciliation': False})
1145             obj_move_rec.unlink(cr, uid, unlink_ids)
1146             if len(all_moves) >= 2:
1147                 obj_move_line.reconcile_partial(cr, uid, all_moves, 'auto',context=context)
1148         return True
1149
1150     def unlink(self, cr, uid, ids, context=None, check=True):
1151         if context is None:
1152             context = {}
1153         move_obj = self.pool.get('account.move')
1154         self._update_check(cr, uid, ids, context)
1155         result = False
1156         move_ids = set()
1157         for line in self.browse(cr, uid, ids, context=context):
1158             move_ids.add(line.move_id.id)
1159             context['journal_id'] = line.journal_id.id
1160             context['period_id'] = line.period_id.id
1161             result = super(account_move_line, self).unlink(cr, uid, [line.id], context=context)
1162         move_ids = list(move_ids)
1163         if check and move_ids:
1164             move_obj.validate(cr, uid, move_ids, context=context)
1165         return result
1166
1167     def write(self, cr, uid, ids, vals, context=None, check=True, update_check=True):
1168         if context is None:
1169             context={}
1170         move_obj = self.pool.get('account.move')
1171         account_obj = self.pool.get('account.account')
1172         journal_obj = self.pool.get('account.journal')
1173         if isinstance(ids, (int, long)):
1174             ids = [ids]
1175         if vals.get('account_tax_id', False):
1176             raise osv.except_osv(_('Unable to change tax!'), _('You cannot change the tax, you should remove and recreate lines.'))
1177         if ('account_id' in vals) and not account_obj.read(cr, uid, vals['account_id'], ['active'])['active']:
1178             raise osv.except_osv(_('Bad Account!'), _('You cannot use an inactive account.'))
1179         if update_check:
1180             if ('account_id' in vals) or ('journal_id' in vals) or ('period_id' in vals) or ('move_id' in vals) or ('debit' in vals) or ('credit' in vals) or ('date' in vals):
1181                 self._update_check(cr, uid, ids, context)
1182
1183         todo_date = None
1184         if vals.get('date', False):
1185             todo_date = vals['date']
1186             del vals['date']
1187
1188         for line in self.browse(cr, uid, ids, context=context):
1189             ctx = context.copy()
1190             if not ctx.get('journal_id'):
1191                 if line.move_id:
1192                    ctx['journal_id'] = line.move_id.journal_id.id
1193                 else:
1194                     ctx['journal_id'] = line.journal_id.id
1195             if not ctx.get('period_id'):
1196                 if line.move_id:
1197                     ctx['period_id'] = line.move_id.period_id.id
1198                 else:
1199                     ctx['period_id'] = line.period_id.id
1200             #Check for centralisation
1201             journal = journal_obj.browse(cr, uid, ctx['journal_id'], context=ctx)
1202             if journal.centralisation:
1203                 self._check_moves(cr, uid, context=ctx)
1204         result = super(account_move_line, self).write(cr, uid, ids, vals, context)
1205         if check:
1206             done = []
1207             for line in self.browse(cr, uid, ids):
1208                 if line.move_id.id not in done:
1209                     done.append(line.move_id.id)
1210                     move_obj.validate(cr, uid, [line.move_id.id], context)
1211                     if todo_date:
1212                         move_obj.write(cr, uid, [line.move_id.id], {'date': todo_date}, context=context)
1213         return result
1214
1215     def _update_journal_check(self, cr, uid, journal_id, period_id, context=None):
1216         journal_obj = self.pool.get('account.journal')
1217         period_obj = self.pool.get('account.period')
1218         jour_period_obj = self.pool.get('account.journal.period')
1219         cr.execute('SELECT state FROM account_journal_period WHERE journal_id = %s AND period_id = %s', (journal_id, period_id))
1220         result = cr.fetchall()
1221         journal = journal_obj.browse(cr, uid, journal_id, context=context)
1222         period = period_obj.browse(cr, uid, period_id, context=context)
1223         for (state,) in result:
1224             if state == 'done':
1225                 raise osv.except_osv(_('Error!'), _('You can not add/modify entries in a closed period %s of journal %s.' % (period.name,journal.name)))
1226         if not result:
1227             jour_period_obj.create(cr, uid, {
1228                 'name': (journal.code or journal.name)+':'+(period.name or ''),
1229                 'journal_id': journal.id,
1230                 'period_id': period.id
1231             })
1232         return True
1233
1234     def _update_check(self, cr, uid, ids, context=None):
1235         done = {}
1236         for line in self.browse(cr, uid, ids, context=context):
1237             err_msg = _('Move name (id): %s (%s)') % (line.move_id.name, str(line.move_id.id))
1238             if line.move_id.state <> 'draft' and (not line.journal_id.entry_posted):
1239                 raise osv.except_osv(_('Error!'), _('You cannot do this modification on a confirmed entry. You can just change some non legal fields or you must unconfirm the journal entry first.\n%s.') % err_msg)
1240             if line.reconcile_id:
1241                 raise osv.except_osv(_('Error!'), _('You cannot do this modification on a reconciled entry. You can just change some non legal fields or you must unreconcile first.\n%s.') % err_msg)
1242             t = (line.journal_id.id, line.period_id.id)
1243             if t not in done:
1244                 self._update_journal_check(cr, uid, line.journal_id.id, line.period_id.id, context)
1245                 done[t] = True
1246         return True
1247
1248     def create(self, cr, uid, vals, context=None, check=True):
1249         account_obj = self.pool.get('account.account')
1250         tax_obj = self.pool.get('account.tax')
1251         move_obj = self.pool.get('account.move')
1252         cur_obj = self.pool.get('res.currency')
1253         journal_obj = self.pool.get('account.journal')
1254         context = dict(context or {})
1255         if vals.get('move_id', False):
1256             move = self.pool.get('account.move').browse(cr, uid, vals['move_id'], context=context)
1257             if move.company_id:
1258                 vals['company_id'] = move.company_id.id
1259             if move.date and not vals.get('date'):
1260                 vals['date'] = move.date
1261         if ('account_id' in vals) and not account_obj.read(cr, uid, [vals['account_id']], ['active'])[0]['active']:
1262             raise osv.except_osv(_('Bad Account!'), _('You cannot use an inactive account.'))
1263         if 'journal_id' in vals and vals['journal_id']:
1264             context['journal_id'] = vals['journal_id']
1265         if 'period_id' in vals and vals['period_id']:
1266             context['period_id'] = vals['period_id']
1267         if ('journal_id' not in context) and ('move_id' in vals) and vals['move_id']:
1268             m = move_obj.browse(cr, uid, vals['move_id'])
1269             context['journal_id'] = m.journal_id.id
1270             context['period_id'] = m.period_id.id
1271         #we need to treat the case where a value is given in the context for period_id as a string
1272         if 'period_id' in context and not isinstance(context.get('period_id', ''), (int, long)):
1273             period_candidate_ids = self.pool.get('account.period').name_search(cr, uid, name=context.get('period_id',''))
1274             if len(period_candidate_ids) != 1:
1275                 raise osv.except_osv(_('Error!'), _('No period found or more than one period found for the given date.'))
1276             context['period_id'] = period_candidate_ids[0][0]
1277         if not context.get('journal_id', False) and context.get('search_default_journal_id', False):
1278             context['journal_id'] = context.get('search_default_journal_id')
1279         self._update_journal_check(cr, uid, context['journal_id'], context['period_id'], context)
1280         move_id = vals.get('move_id', False)
1281         journal = journal_obj.browse(cr, uid, context['journal_id'], context=context)
1282         vals['journal_id'] = vals.get('journal_id') or context.get('journal_id')
1283         vals['period_id'] = vals.get('period_id') or context.get('period_id')
1284         vals['date'] = vals.get('date') or context.get('date')
1285         if not move_id:
1286             if journal.centralisation:
1287                 #Check for centralisation
1288                 res = self._check_moves(cr, uid, context)
1289                 if res:
1290                     vals['move_id'] = res[0]
1291             if not vals.get('move_id', False):
1292                 if journal.sequence_id:
1293                     #name = self.pool.get('ir.sequence').next_by_id(cr, uid, journal.sequence_id.id)
1294                     v = {
1295                         'date': vals.get('date', time.strftime('%Y-%m-%d')),
1296                         'period_id': context['period_id'],
1297                         'journal_id': context['journal_id']
1298                     }
1299                     if vals.get('ref', ''):
1300                         v.update({'ref': vals['ref']})
1301                     move_id = move_obj.create(cr, uid, v, context)
1302                     vals['move_id'] = move_id
1303                 else:
1304                     raise osv.except_osv(_('No Piece Number!'), _('Cannot create an automatic sequence for this piece.\nPut a sequence in the journal definition for automatic numbering or create a sequence manually for this piece.'))
1305         ok = not (journal.type_control_ids or journal.account_control_ids)
1306         if ('account_id' in vals):
1307             account = account_obj.browse(cr, uid, vals['account_id'], context=context)
1308             if journal.type_control_ids:
1309                 type = account.user_type
1310                 for t in journal.type_control_ids:
1311                     if type.code == t.code:
1312                         ok = True
1313                         break
1314             if journal.account_control_ids and not ok:
1315                 for a in journal.account_control_ids:
1316                     if a.id == vals['account_id']:
1317                         ok = True
1318                         break
1319             # Automatically convert in the account's secondary currency if there is one and
1320             # the provided values were not already multi-currency
1321             if account.currency_id and 'amount_currency' not in vals and account.currency_id.id != account.company_id.currency_id.id:
1322                 vals['currency_id'] = account.currency_id.id
1323                 ctx = {}
1324                 if 'date' in vals:
1325                     ctx['date'] = vals['date']
1326                 vals['amount_currency'] = cur_obj.compute(cr, uid, account.company_id.currency_id.id,
1327                     account.currency_id.id, vals.get('debit', 0.0)-vals.get('credit', 0.0), context=ctx)
1328         if not ok:
1329             raise osv.except_osv(_('Bad Account!'), _('You cannot use this general account in this journal, check the tab \'Entry Controls\' on the related journal.'))
1330
1331         result = super(account_move_line, self).create(cr, uid, vals, context=context)
1332         # CREATE Taxes
1333         if vals.get('account_tax_id', False):
1334             tax_id = tax_obj.browse(cr, uid, vals['account_tax_id'])
1335             total = vals['debit'] - vals['credit']
1336             base_code = 'base_code_id'
1337             tax_code = 'tax_code_id'
1338             account_id = 'account_collected_id'
1339             base_sign = 'base_sign'
1340             tax_sign = 'tax_sign'
1341             if journal.type in ('purchase_refund', 'sale_refund') or (journal.type in ('cash', 'bank') and total < 0):
1342                 base_code = 'ref_base_code_id'
1343                 tax_code = 'ref_tax_code_id'
1344                 account_id = 'account_paid_id'
1345                 base_sign = 'ref_base_sign'
1346                 tax_sign = 'ref_tax_sign'
1347             tmp_cnt = 0
1348             for tax in tax_obj.compute_all(cr, uid, [tax_id], total, 1.00, force_excluded=False).get('taxes'):
1349                 #create the base movement
1350                 if tmp_cnt == 0:
1351                     if tax[base_code]:
1352                         tmp_cnt += 1
1353                         if tax_id.price_include:
1354                             total = tax['price_unit']
1355                         newvals = {
1356                             'tax_code_id': tax[base_code],
1357                             'tax_amount': tax[base_sign] * abs(total),
1358                         }
1359                         if tax_id.price_include:
1360                             if tax['price_unit'] < 0:
1361                                 newvals['credit'] = abs(tax['price_unit'])
1362                             else:
1363                                 newvals['debit'] = tax['price_unit']
1364                         self.write(cr, uid, [result], newvals, context=context)
1365                 else:
1366                     data = {
1367                         'move_id': vals['move_id'],
1368                         'name': tools.ustr(vals['name'] or '') + ' ' + tools.ustr(tax['name'] or ''),
1369                         'date': vals['date'],
1370                         'partner_id': vals.get('partner_id', False),
1371                         'ref': vals.get('ref', False),
1372                         'statement_id': vals.get('statement_id', False),
1373                         'account_tax_id': False,
1374                         'tax_code_id': tax[base_code],
1375                         'tax_amount': tax[base_sign] * abs(total),
1376                         'account_id': vals['account_id'],
1377                         'credit': 0.0,
1378                         'debit': 0.0,
1379                     }
1380                     if data['tax_code_id']:
1381                         self.create(cr, uid, data, context)
1382                 #create the Tax movement
1383                 data = {
1384                     'move_id': vals['move_id'],
1385                     'name': tools.ustr(vals['name'] or '') + ' ' + tools.ustr(tax['name'] or ''),
1386                     'date': vals['date'],
1387                     'partner_id': vals.get('partner_id',False),
1388                     'ref': vals.get('ref',False),
1389                     'statement_id': vals.get('statement_id', False),
1390                     'account_tax_id': False,
1391                     'tax_code_id': tax[tax_code],
1392                     'tax_amount': tax[tax_sign] * abs(tax['amount']),
1393                     'account_id': tax[account_id] or vals['account_id'],
1394                     'credit': tax['amount']<0 and -tax['amount'] or 0.0,
1395                     'debit': tax['amount']>0 and tax['amount'] or 0.0,
1396                 }
1397                 if data['tax_code_id']:
1398                     self.create(cr, uid, data, context)
1399             del vals['account_tax_id']
1400
1401         if check and not context.get('novalidate') and (context.get('recompute', True) or journal.entry_posted):
1402             tmp = move_obj.validate(cr, uid, [vals['move_id']], context)
1403             if journal.entry_posted and tmp:
1404                 move_obj.button_validate(cr,uid, [vals['move_id']], context)
1405         return result
1406
1407     def list_periods(self, cr, uid, context=None):
1408         ids = self.pool.get('account.period').search(cr,uid,[])
1409         return self.pool.get('account.period').name_get(cr, uid, ids, context=context)
1410
1411     def list_journals(self, cr, uid, context=None):
1412         ng = dict(self.pool.get('account.journal').name_search(cr,uid,'',[]))
1413         ids = ng.keys()
1414         result = []
1415         for journal in self.pool.get('account.journal').browse(cr, uid, ids, context=context):
1416             result.append((journal.id,ng[journal.id],journal.type,
1417                 bool(journal.currency),bool(journal.analytic_journal_id)))
1418         return result
1419
1420
1421 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: