Forward port of branch saas-3 up to fc9fc3e
[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             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 = {}
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 and (invoice_id, invoice_names[invoice_id]) or False
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         ret = []
770
771         for line in lines:
772             partial_reconciliation_siblings_ids = []
773             if line.reconcile_partial_id:
774                 partial_reconciliation_siblings_ids = self.search(cr, uid, [('reconcile_partial_id', '=', line.reconcile_partial_id.id)], context=context)
775                 partial_reconciliation_siblings_ids.remove(line.id)
776
777             ret_line = {
778                 'id': line.id,
779                 'name': line.name != '/' and line.move_id.name + ': ' + line.name or line.move_id.name,
780                 'ref': line.move_id.ref,
781                 'account_code': line.account_id.code,
782                 'account_name': line.account_id.name,
783                 'account_type': line.account_id.type,
784                 'date_maturity': line.date_maturity,
785                 'date': line.date,
786                 'period_name': line.period_id.name,
787                 'journal_name': line.journal_id.name,
788                 'partner_id': line.partner_id.id,
789                 'partner_name': line.partner_id.name,
790                 'is_partially_reconciled': bool(line.reconcile_partial_id),
791                 'partial_reconciliation_siblings_ids': partial_reconciliation_siblings_ids,
792             }
793
794             # Amount residual can be negative
795             debit = line.debit
796             credit = line.credit
797             total_amount = abs(debit - credit)
798             total_amount_currency = line.amount_currency
799             amount_residual = line.amount_residual
800             amount_residual_currency = line.amount_residual_currency
801             if line.amount_residual < 0:
802                 debit, credit = credit, debit
803                 amount_residual = -amount_residual
804                 amount_residual_currency = -amount_residual_currency
805
806             # Get right debit / credit:
807             line_currency = line.currency_id or company_currency
808             amount_currency_str = ""
809             total_amount_currency_str = ""
810             if line.currency_id and line.amount_currency:
811                 amount_currency_str = rml_parser.formatLang(amount_residual_currency, currency_obj=line.currency_id)
812                 total_amount_currency_str = rml_parser.formatLang(total_amount_currency, currency_obj=line.currency_id)
813             if target_currency and line_currency == target_currency and target_currency != company_currency:
814                 debit = debit > 0 and amount_residual_currency or 0.0
815                 credit = credit > 0 and amount_residual_currency or 0.0
816                 amount_currency_str = rml_parser.formatLang(amount_residual, currency_obj=company_currency)
817                 total_amount_currency_str = rml_parser.formatLang(total_amount, currency_obj=company_currency)
818                 amount_str = rml_parser.formatLang(debit or credit, currency_obj=target_currency)
819                 total_amount_str = rml_parser.formatLang(total_amount_currency, currency_obj=target_currency)
820             else:
821                 debit = debit > 0 and amount_residual or 0.0
822                 credit = credit > 0 and amount_residual or 0.0
823                 amount_str = rml_parser.formatLang(debit or credit, currency_obj=company_currency)
824                 total_amount_str = rml_parser.formatLang(total_amount, currency_obj=company_currency)
825                 if target_currency and target_currency != company_currency:
826                     amount_currency_str = rml_parser.formatLang(debit or credit, currency_obj=line_currency)
827                     total_amount_currency_str = rml_parser.formatLang(total_amount, currency_obj=line_currency)
828                     ctx = context.copy()
829                     if target_date:
830                         ctx.update({'date': target_date})
831                     debit = currency_obj.compute(cr, uid, company_currency.id, target_currency.id, debit, context=ctx)
832                     credit = currency_obj.compute(cr, uid, company_currency.id, target_currency.id, credit, context=ctx)
833                     amount_str = rml_parser.formatLang(debit or credit, currency_obj=target_currency)
834                     total_amount = currency_obj.compute(cr, uid, company_currency.id, target_currency.id, total_amount, context=ctx)
835                     total_amount_str = rml_parser.formatLang(total_amount, currency_obj=target_currency)
836
837             ret_line['credit'] = credit
838             ret_line['debit'] = debit
839             ret_line['amount_str'] = amount_str
840             ret_line['amount_currency_str'] = amount_currency_str
841             ret_line['total_amount_str'] = total_amount_str # For partial reconciliations
842             ret_line['total_amount_currency_str'] = total_amount_currency_str
843             ret.append(ret_line)
844         return ret
845
846     def list_partners_to_reconcile(self, cr, uid, context=None):
847         cr.execute(
848              """SELECT partner_id FROM (
849                 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
850                 FROM account_move_line l
851                 RIGHT JOIN account_account a ON (a.id = l.account_id)
852                 RIGHT JOIN res_partner p ON (l.partner_id = p.id)
853                     WHERE a.reconcile IS TRUE
854                     AND l.reconcile_id IS NULL
855                     AND l.state <> 'draft'
856                     GROUP BY l.partner_id, p.last_reconciliation_date
857                 ) AS s
858                 WHERE debit > 0 AND credit > 0 AND (last_reconciliation_date IS NULL OR max_date > last_reconciliation_date)
859                 ORDER BY last_reconciliation_date""")
860         ids = [x[0] for x in cr.fetchall()]
861         if not ids:
862             return []
863
864         # To apply the ir_rules
865         partner_obj = self.pool.get('res.partner')
866         ids = partner_obj.search(cr, uid, [('id', 'in', ids)], context=context)
867         return partner_obj.name_get(cr, uid, ids, context=context)
868
869     def reconcile_partial(self, cr, uid, ids, type='auto', context=None, writeoff_acc_id=False, writeoff_period_id=False, writeoff_journal_id=False):
870         move_rec_obj = self.pool.get('account.move.reconcile')
871         merges = []
872         unmerge = []
873         total = 0.0
874         merges_rec = []
875         company_list = []
876         if context is None:
877             context = {}
878         for line in self.browse(cr, uid, ids, context=context):
879             if company_list and not line.company_id.id in company_list:
880                 raise osv.except_osv(_('Warning!'), _('To reconcile the entries company should be the same for all entries.'))
881             company_list.append(line.company_id.id)
882
883         for line in self.browse(cr, uid, ids, context=context):
884             if line.account_id.currency_id:
885                 currency_id = line.account_id.currency_id
886             else:
887                 currency_id = line.company_id.currency_id
888             if line.reconcile_id:
889                 raise osv.except_osv(_('Warning'), _("Journal Item '%s' (id: %s), Move '%s' is already reconciled!") % (line.name, line.id, line.move_id.name))
890             if line.reconcile_partial_id:
891                 for line2 in line.reconcile_partial_id.line_partial_ids:
892                     if line2.state != 'valid':
893                         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))
894                     if not line2.reconcile_id:
895                         if line2.id not in merges:
896                             merges.append(line2.id)
897                         if line2.account_id.currency_id:
898                             total += line2.amount_currency
899                         else:
900                             total += (line2.debit or 0.0) - (line2.credit or 0.0)
901                 merges_rec.append(line.reconcile_partial_id.id)
902             else:
903                 unmerge.append(line.id)
904                 if line.account_id.currency_id:
905                     total += line.amount_currency
906                 else:
907                     total += (line.debit or 0.0) - (line.credit or 0.0)
908         if self.pool.get('res.currency').is_zero(cr, uid, currency_id, total):
909             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)
910             return res
911         # marking the lines as reconciled does not change their validity, so there is no need
912         # to revalidate their moves completely.
913         reconcile_context = dict(context, novalidate=True)
914         r_id = move_rec_obj.create(cr, uid, {
915             'type': type,
916             'line_partial_ids': map(lambda x: (4,x,False), merges+unmerge)
917         }, context=reconcile_context)
918         move_rec_obj.reconcile_partial_check(cr, uid, [r_id] + merges_rec, context=reconcile_context)
919         return r_id
920
921     def reconcile(self, cr, uid, ids, type='auto', writeoff_acc_id=False, writeoff_period_id=False, writeoff_journal_id=False, context=None):
922         account_obj = self.pool.get('account.account')
923         move_obj = self.pool.get('account.move')
924         move_rec_obj = self.pool.get('account.move.reconcile')
925         partner_obj = self.pool.get('res.partner')
926         currency_obj = self.pool.get('res.currency')
927         lines = self.browse(cr, uid, ids, context=context)
928         unrec_lines = filter(lambda x: not x['reconcile_id'], lines)
929         credit = debit = 0.0
930         currency = 0.0
931         account_id = False
932         partner_id = False
933         if context is None:
934             context = {}
935         company_list = []
936         for line in self.browse(cr, uid, ids, context=context):
937             if company_list and not line.company_id.id in company_list:
938                 raise osv.except_osv(_('Warning!'), _('To reconcile the entries company should be the same for all entries.'))
939             company_list.append(line.company_id.id)
940         for line in unrec_lines:
941             if line.state <> 'valid':
942                 raise osv.except_osv(_('Error!'),
943                         _('Entry "%s" is not valid !') % line.name)
944             credit += line['credit']
945             debit += line['debit']
946             currency += line['amount_currency'] or 0.0
947             account_id = line['account_id']['id']
948             partner_id = (line['partner_id'] and line['partner_id']['id']) or False
949         writeoff = debit - credit
950
951         # Ifdate_p in context => take this date
952         if context.has_key('date_p') and context['date_p']:
953             date=context['date_p']
954         else:
955             date = time.strftime('%Y-%m-%d')
956
957         cr.execute('SELECT account_id, reconcile_id '\
958                    'FROM account_move_line '\
959                    'WHERE id IN %s '\
960                    'GROUP BY account_id,reconcile_id',
961                    (tuple(ids), ))
962         r = cr.fetchall()
963         #TODO: move this check to a constraint in the account_move_reconcile object
964         if len(r) != 1:
965             raise osv.except_osv(_('Error'), _('Entries are not of the same account or already reconciled ! '))
966         if not unrec_lines:
967             raise osv.except_osv(_('Error!'), _('Entry is already reconciled.'))
968         account = account_obj.browse(cr, uid, account_id, context=context)
969         if not account.reconcile:
970             raise osv.except_osv(_('Error'), _('The account is not defined to be reconciled !'))
971         if r[0][1] != None:
972             raise osv.except_osv(_('Error!'), _('Some entries are already reconciled.'))
973
974         if (not currency_obj.is_zero(cr, uid, account.company_id.currency_id, writeoff)) or \
975            (account.currency_id and (not currency_obj.is_zero(cr, uid, account.currency_id, currency))):
976             if not writeoff_acc_id:
977                 raise osv.except_osv(_('Warning!'), _('You have to provide an account for the write off/exchange difference entry.'))
978             if writeoff > 0:
979                 debit = writeoff
980                 credit = 0.0
981                 self_credit = writeoff
982                 self_debit = 0.0
983             else:
984                 debit = 0.0
985                 credit = -writeoff
986                 self_credit = 0.0
987                 self_debit = -writeoff
988             # If comment exist in context, take it
989             if 'comment' in context and context['comment']:
990                 libelle = context['comment']
991             else:
992                 libelle = _('Write-Off')
993
994             cur_obj = self.pool.get('res.currency')
995             cur_id = False
996             amount_currency_writeoff = 0.0
997             if context.get('company_currency_id',False) != context.get('currency_id',False):
998                 cur_id = context.get('currency_id',False)
999                 for line in unrec_lines:
1000                     if line.currency_id and line.currency_id.id == context.get('currency_id',False):
1001                         amount_currency_writeoff += line.amount_currency
1002                     else:
1003                         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})
1004                         amount_currency_writeoff += (line.debit > 0) and tmp_amount or -tmp_amount
1005
1006             writeoff_lines = [
1007                 (0, 0, {
1008                     'name': libelle,
1009                     'debit': self_debit,
1010                     'credit': self_credit,
1011                     'account_id': account_id,
1012                     'date': date,
1013                     'partner_id': partner_id,
1014                     'currency_id': cur_id or (account.currency_id.id or False),
1015                     'amount_currency': amount_currency_writeoff and -1 * amount_currency_writeoff or (account.currency_id.id and -1 * currency or 0.0)
1016                 }),
1017                 (0, 0, {
1018                     'name': libelle,
1019                     'debit': debit,
1020                     'credit': credit,
1021                     'account_id': writeoff_acc_id,
1022                     'analytic_account_id': context.get('analytic_id', False),
1023                     'date': date,
1024                     'partner_id': partner_id,
1025                     'currency_id': cur_id or (account.currency_id.id or False),
1026                     'amount_currency': amount_currency_writeoff and amount_currency_writeoff or (account.currency_id.id and currency or 0.0)
1027                 })
1028             ]
1029
1030             writeoff_move_id = move_obj.create(cr, uid, {
1031                 'period_id': writeoff_period_id,
1032                 'journal_id': writeoff_journal_id,
1033                 'date':date,
1034                 'state': 'draft',
1035                 'line_id': writeoff_lines
1036             })
1037
1038             writeoff_line_ids = self.search(cr, uid, [('move_id', '=', writeoff_move_id), ('account_id', '=', account_id)])
1039             if account_id == writeoff_acc_id:
1040                 writeoff_line_ids = [writeoff_line_ids[1]]
1041             ids += writeoff_line_ids
1042
1043         # marking the lines as reconciled does not change their validity, so there is no need
1044         # to revalidate their moves completely.
1045         reconcile_context = dict(context, novalidate=True)
1046         r_id = move_rec_obj.create(cr, uid, {
1047             'type': type,
1048             'line_id': map(lambda x: (4, x, False), ids),
1049             'line_partial_ids': map(lambda x: (3, x, False), ids)
1050         }, context=reconcile_context)
1051         # the id of the move.reconcile is written in the move.line (self) by the create method above
1052         # because of the way the line_id are defined: (4, x, False)
1053         for id in ids:
1054             workflow.trg_trigger(uid, 'account.move.line', id, cr)
1055
1056         if lines and lines[0]:
1057             partner_id = lines[0].partner_id and lines[0].partner_id.id or False
1058             if partner_id and not partner_obj.has_something_to_reconcile(cr, uid, partner_id, context=context):
1059                 partner_obj.mark_as_reconciled(cr, uid, [partner_id], context=context)
1060         return r_id
1061
1062     def view_header_get(self, cr, user, view_id, view_type, context=None):
1063         if context is None:
1064             context = {}
1065         context = self.convert_to_period(cr, user, context=context)
1066         if context.get('account_id', False):
1067             cr.execute('SELECT code FROM account_account WHERE id = %s', (context['account_id'], ))
1068             res = cr.fetchone()
1069             if res:
1070                 res = _('Entries: ')+ (res[0] or '')
1071             return res
1072         if (not context.get('journal_id', False)) or (not context.get('period_id', False)):
1073             return False
1074         if context.get('search_default_journal_id', False):
1075             context['journal_id'] = context.get('search_default_journal_id')
1076         cr.execute('SELECT code FROM account_journal WHERE id = %s', (context['journal_id'], ))
1077         j = cr.fetchone()[0] or ''
1078         cr.execute('SELECT code FROM account_period WHERE id = %s', (context['period_id'], ))
1079         p = cr.fetchone()[0] or ''
1080         if j or p:
1081             return j + (p and (':' + p) or '')
1082         return False
1083
1084     def onchange_date(self, cr, user, ids, date, context=None):
1085         """
1086         Returns a dict that contains new values and context
1087         @param cr: A database cursor
1088         @param user: ID of the user currently logged in
1089         @param date: latest value from user input for field date
1090         @param args: other arguments
1091         @param context: context arguments, like lang, time zone
1092         @return: Returns a dict which contains new values, and context
1093         """
1094         res = {}
1095         if context is None:
1096             context = {}
1097         period_pool = self.pool.get('account.period')
1098         pids = period_pool.find(cr, user, date, context=context)
1099         if pids:
1100             res.update({'period_id':pids[0]})
1101             context = dict(context, period_id=pids[0])
1102         return {
1103             'value':res,
1104             'context':context,
1105         }
1106
1107     def _check_moves(self, cr, uid, context=None):
1108         # use the first move ever created for this journal and period
1109         if context is None:
1110             context = {}
1111         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']))
1112         res = cr.fetchone()
1113         if res:
1114             if res[1] != 'draft':
1115                 raise osv.except_osv(_('User Error!'),
1116                        _('The account move (%s) for centralisation ' \
1117                                 'has been confirmed.') % res[2])
1118         return res
1119
1120     def _remove_move_reconcile(self, cr, uid, move_ids=None, opening_reconciliation=False, context=None):
1121         # Function remove move rencocile ids related with moves
1122         obj_move_line = self.pool.get('account.move.line')
1123         obj_move_rec = self.pool.get('account.move.reconcile')
1124         unlink_ids = []
1125         if not move_ids:
1126             return True
1127         recs = obj_move_line.read(cr, uid, move_ids, ['reconcile_id', 'reconcile_partial_id'])
1128         full_recs = filter(lambda x: x['reconcile_id'], recs)
1129         rec_ids = [rec['reconcile_id'][0] for rec in full_recs]
1130         part_recs = filter(lambda x: x['reconcile_partial_id'], recs)
1131         part_rec_ids = [rec['reconcile_partial_id'][0] for rec in part_recs]
1132         unlink_ids += rec_ids
1133         unlink_ids += part_rec_ids
1134         all_moves = obj_move_line.search(cr, uid, ['|',('reconcile_id', 'in', unlink_ids),('reconcile_partial_id', 'in', unlink_ids)])
1135         all_moves = list(set(all_moves) - set(move_ids))
1136         if unlink_ids:
1137             if opening_reconciliation:
1138                 raise osv.except_osv(_('Warning!'),
1139                     _('Opening Entries have already been generated.  Please run "Cancel Closing Entries" wizard to cancel those entries and then run this wizard.'))
1140                 obj_move_rec.write(cr, uid, unlink_ids, {'opening_reconciliation': False})
1141             obj_move_rec.unlink(cr, uid, unlink_ids)
1142             if len(all_moves) >= 2:
1143                 obj_move_line.reconcile_partial(cr, uid, all_moves, 'auto',context=context)
1144         return True
1145
1146     def unlink(self, cr, uid, ids, context=None, check=True):
1147         if context is None:
1148             context = {}
1149         move_obj = self.pool.get('account.move')
1150         self._update_check(cr, uid, ids, context)
1151         result = False
1152         move_ids = set()
1153         for line in self.browse(cr, uid, ids, context=context):
1154             move_ids.add(line.move_id.id)
1155             context['journal_id'] = line.journal_id.id
1156             context['period_id'] = line.period_id.id
1157             result = super(account_move_line, self).unlink(cr, uid, [line.id], context=context)
1158         move_ids = list(move_ids)
1159         if check and move_ids:
1160             move_obj.validate(cr, uid, move_ids, context=context)
1161         return result
1162
1163     def write(self, cr, uid, ids, vals, context=None, check=True, update_check=True):
1164         if context is None:
1165             context={}
1166         move_obj = self.pool.get('account.move')
1167         account_obj = self.pool.get('account.account')
1168         journal_obj = self.pool.get('account.journal')
1169         if isinstance(ids, (int, long)):
1170             ids = [ids]
1171         if vals.get('account_tax_id', False):
1172             raise osv.except_osv(_('Unable to change tax!'), _('You cannot change the tax, you should remove and recreate lines.'))
1173         if ('account_id' in vals) and not account_obj.read(cr, uid, vals['account_id'], ['active'])['active']:
1174             raise osv.except_osv(_('Bad Account!'), _('You cannot use an inactive account.'))
1175         if update_check:
1176             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):
1177                 self._update_check(cr, uid, ids, context)
1178
1179         todo_date = None
1180         if vals.get('date', False):
1181             todo_date = vals['date']
1182             del vals['date']
1183
1184         for line in self.browse(cr, uid, ids, context=context):
1185             ctx = context.copy()
1186             if not ctx.get('journal_id'):
1187                 if line.move_id:
1188                    ctx['journal_id'] = line.move_id.journal_id.id
1189                 else:
1190                     ctx['journal_id'] = line.journal_id.id
1191             if not ctx.get('period_id'):
1192                 if line.move_id:
1193                     ctx['period_id'] = line.move_id.period_id.id
1194                 else:
1195                     ctx['period_id'] = line.period_id.id
1196             #Check for centralisation
1197             journal = journal_obj.browse(cr, uid, ctx['journal_id'], context=ctx)
1198             if journal.centralisation:
1199                 self._check_moves(cr, uid, context=ctx)
1200         result = super(account_move_line, self).write(cr, uid, ids, vals, context)
1201         if check:
1202             done = []
1203             for line in self.browse(cr, uid, ids):
1204                 if line.move_id.id not in done:
1205                     done.append(line.move_id.id)
1206                     move_obj.validate(cr, uid, [line.move_id.id], context)
1207                     if todo_date:
1208                         move_obj.write(cr, uid, [line.move_id.id], {'date': todo_date}, context=context)
1209         return result
1210
1211     def _update_journal_check(self, cr, uid, journal_id, period_id, context=None):
1212         journal_obj = self.pool.get('account.journal')
1213         period_obj = self.pool.get('account.period')
1214         jour_period_obj = self.pool.get('account.journal.period')
1215         cr.execute('SELECT state FROM account_journal_period WHERE journal_id = %s AND period_id = %s', (journal_id, period_id))
1216         result = cr.fetchall()
1217         journal = journal_obj.browse(cr, uid, journal_id, context=context)
1218         period = period_obj.browse(cr, uid, period_id, context=context)
1219         for (state,) in result:
1220             if state == 'done':
1221                 raise osv.except_osv(_('Error!'), _('You can not add/modify entries in a closed period %s of journal %s.' % (period.name,journal.name)))
1222         if not result:
1223             jour_period_obj.create(cr, uid, {
1224                 'name': (journal.code or journal.name)+':'+(period.name or ''),
1225                 'journal_id': journal.id,
1226                 'period_id': period.id
1227             })
1228         return True
1229
1230     def _update_check(self, cr, uid, ids, context=None):
1231         done = {}
1232         for line in self.browse(cr, uid, ids, context=context):
1233             err_msg = _('Move name (id): %s (%s)') % (line.move_id.name, str(line.move_id.id))
1234             if line.move_id.state <> 'draft' and (not line.journal_id.entry_posted):
1235                 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)
1236             if line.reconcile_id:
1237                 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)
1238             t = (line.journal_id.id, line.period_id.id)
1239             if t not in done:
1240                 self._update_journal_check(cr, uid, line.journal_id.id, line.period_id.id, context)
1241                 done[t] = True
1242         return True
1243
1244     def create(self, cr, uid, vals, context=None, check=True):
1245         account_obj = self.pool.get('account.account')
1246         tax_obj = self.pool.get('account.tax')
1247         move_obj = self.pool.get('account.move')
1248         cur_obj = self.pool.get('res.currency')
1249         journal_obj = self.pool.get('account.journal')
1250         context = dict(context or {})
1251         if vals.get('move_id', False):
1252             move = self.pool.get('account.move').browse(cr, uid, vals['move_id'], context=context)
1253             if move.company_id:
1254                 vals['company_id'] = move.company_id.id
1255             if move.date and not vals.get('date'):
1256                 vals['date'] = move.date
1257         if ('account_id' in vals) and not account_obj.read(cr, uid, [vals['account_id']], ['active'])[0]['active']:
1258             raise osv.except_osv(_('Bad Account!'), _('You cannot use an inactive account.'))
1259         if 'journal_id' in vals and vals['journal_id']:
1260             context['journal_id'] = vals['journal_id']
1261         if 'period_id' in vals and vals['period_id']:
1262             context['period_id'] = vals['period_id']
1263         if ('journal_id' not in context) and ('move_id' in vals) and vals['move_id']:
1264             m = move_obj.browse(cr, uid, vals['move_id'])
1265             context['journal_id'] = m.journal_id.id
1266             context['period_id'] = m.period_id.id
1267         #we need to treat the case where a value is given in the context for period_id as a string
1268         if 'period_id' in context and not isinstance(context.get('period_id', ''), (int, long)):
1269             period_candidate_ids = self.pool.get('account.period').name_search(cr, uid, name=context.get('period_id',''))
1270             if len(period_candidate_ids) != 1:
1271                 raise osv.except_osv(_('Error!'), _('No period found or more than one period found for the given date.'))
1272             context['period_id'] = period_candidate_ids[0][0]
1273         if not context.get('journal_id', False) and context.get('search_default_journal_id', False):
1274             context['journal_id'] = context.get('search_default_journal_id')
1275         self._update_journal_check(cr, uid, context['journal_id'], context['period_id'], context)
1276         move_id = vals.get('move_id', False)
1277         journal = journal_obj.browse(cr, uid, context['journal_id'], context=context)
1278         vals['journal_id'] = vals.get('journal_id') or context.get('journal_id')
1279         vals['period_id'] = vals.get('period_id') or context.get('period_id')
1280         vals['date'] = vals.get('date') or context.get('date')
1281         if not move_id:
1282             if journal.centralisation:
1283                 #Check for centralisation
1284                 res = self._check_moves(cr, uid, context)
1285                 if res:
1286                     vals['move_id'] = res[0]
1287             if not vals.get('move_id', False):
1288                 if journal.sequence_id:
1289                     #name = self.pool.get('ir.sequence').next_by_id(cr, uid, journal.sequence_id.id)
1290                     v = {
1291                         'date': vals.get('date', time.strftime('%Y-%m-%d')),
1292                         'period_id': context['period_id'],
1293                         'journal_id': context['journal_id']
1294                     }
1295                     if vals.get('ref', ''):
1296                         v.update({'ref': vals['ref']})
1297                     move_id = move_obj.create(cr, uid, v, context)
1298                     vals['move_id'] = move_id
1299                 else:
1300                     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.'))
1301         ok = not (journal.type_control_ids or journal.account_control_ids)
1302         if ('account_id' in vals):
1303             account = account_obj.browse(cr, uid, vals['account_id'], context=context)
1304             if journal.type_control_ids:
1305                 type = account.user_type
1306                 for t in journal.type_control_ids:
1307                     if type.code == t.code:
1308                         ok = True
1309                         break
1310             if journal.account_control_ids and not ok:
1311                 for a in journal.account_control_ids:
1312                     if a.id == vals['account_id']:
1313                         ok = True
1314                         break
1315             # Automatically convert in the account's secondary currency if there is one and
1316             # the provided values were not already multi-currency
1317             if account.currency_id and 'amount_currency' not in vals and account.currency_id.id != account.company_id.currency_id.id:
1318                 vals['currency_id'] = account.currency_id.id
1319                 ctx = {}
1320                 if 'date' in vals:
1321                     ctx['date'] = vals['date']
1322                 vals['amount_currency'] = cur_obj.compute(cr, uid, account.company_id.currency_id.id,
1323                     account.currency_id.id, vals.get('debit', 0.0)-vals.get('credit', 0.0), context=ctx)
1324         if not ok:
1325             raise osv.except_osv(_('Bad Account!'), _('You cannot use this general account in this journal, check the tab \'Entry Controls\' on the related journal.'))
1326
1327         result = super(account_move_line, self).create(cr, uid, vals, context=context)
1328         # CREATE Taxes
1329         if vals.get('account_tax_id', False):
1330             tax_id = tax_obj.browse(cr, uid, vals['account_tax_id'])
1331             total = vals['debit'] - vals['credit']
1332             base_code = 'base_code_id'
1333             tax_code = 'tax_code_id'
1334             account_id = 'account_collected_id'
1335             base_sign = 'base_sign'
1336             tax_sign = 'tax_sign'
1337             if journal.type in ('purchase_refund', 'sale_refund') or (journal.type in ('cash', 'bank') and total < 0):
1338                 base_code = 'ref_base_code_id'
1339                 tax_code = 'ref_tax_code_id'
1340                 account_id = 'account_paid_id'
1341                 base_sign = 'ref_base_sign'
1342                 tax_sign = 'ref_tax_sign'
1343             tmp_cnt = 0
1344             for tax in tax_obj.compute_all(cr, uid, [tax_id], total, 1.00, force_excluded=False).get('taxes'):
1345                 #create the base movement
1346                 if tmp_cnt == 0:
1347                     if tax[base_code]:
1348                         tmp_cnt += 1
1349                         if tax_id.price_include:
1350                             total = tax['price_unit']
1351                         newvals = {
1352                             'tax_code_id': tax[base_code],
1353                             'tax_amount': tax[base_sign] * abs(total),
1354                         }
1355                         if tax_id.price_include:
1356                             if tax['price_unit'] < 0:
1357                                 newvals['credit'] = abs(tax['price_unit'])
1358                             else:
1359                                 newvals['debit'] = tax['price_unit']
1360                         self.write(cr, uid, [result], newvals, context=context)
1361                 else:
1362                     data = {
1363                         'move_id': vals['move_id'],
1364                         'name': tools.ustr(vals['name'] or '') + ' ' + tools.ustr(tax['name'] or ''),
1365                         'date': vals['date'],
1366                         'partner_id': vals.get('partner_id', False),
1367                         'ref': vals.get('ref', False),
1368                         'statement_id': vals.get('statement_id', False),
1369                         'account_tax_id': False,
1370                         'tax_code_id': tax[base_code],
1371                         'tax_amount': tax[base_sign] * abs(total),
1372                         'account_id': vals['account_id'],
1373                         'credit': 0.0,
1374                         'debit': 0.0,
1375                     }
1376                     if data['tax_code_id']:
1377                         self.create(cr, uid, data, context)
1378                 #create the Tax movement
1379                 data = {
1380                     'move_id': vals['move_id'],
1381                     'name': tools.ustr(vals['name'] or '') + ' ' + tools.ustr(tax['name'] or ''),
1382                     'date': vals['date'],
1383                     'partner_id': vals.get('partner_id',False),
1384                     'ref': vals.get('ref',False),
1385                     'statement_id': vals.get('statement_id', False),
1386                     'account_tax_id': False,
1387                     'tax_code_id': tax[tax_code],
1388                     'tax_amount': tax[tax_sign] * abs(tax['amount']),
1389                     'account_id': tax[account_id] or vals['account_id'],
1390                     'credit': tax['amount']<0 and -tax['amount'] or 0.0,
1391                     'debit': tax['amount']>0 and tax['amount'] or 0.0,
1392                 }
1393                 if data['tax_code_id']:
1394                     self.create(cr, uid, data, context)
1395             del vals['account_tax_id']
1396
1397         if check and not context.get('novalidate') and (context.get('recompute', True) or journal.entry_posted):
1398             tmp = move_obj.validate(cr, uid, [vals['move_id']], context)
1399             if journal.entry_posted and tmp:
1400                 move_obj.button_validate(cr,uid, [vals['move_id']], context)
1401         return result
1402
1403     def list_periods(self, cr, uid, context=None):
1404         ids = self.pool.get('account.period').search(cr,uid,[])
1405         return self.pool.get('account.period').name_get(cr, uid, ids, context=context)
1406
1407     def list_journals(self, cr, uid, context=None):
1408         ng = dict(self.pool.get('account.journal').name_search(cr,uid,'',[]))
1409         ids = ng.keys()
1410         result = []
1411         for journal in self.pool.get('account.journal').browse(cr, uid, ids, context=context):
1412             result.append((journal.id,ng[journal.id],journal.type,
1413                 bool(journal.currency),bool(journal.analytic_journal_id)))
1414         return result
1415
1416
1417 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: