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