[MERGE]: Merge with lp:openobject-trunk-dev-addons2
[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 import time
22 from datetime import datetime
23
24 import netsvc
25 from osv import fields, osv
26 from tools.translate import _
27 import decimal_precision as dp
28 import tools
29
30 class account_move_line(osv.osv):
31     _name = "account.move.line"
32     _description = "Journal Items"
33
34     def _query_get(self, cr, uid, obj='l', context={}):
35         fiscalyear_obj = self.pool.get('account.fiscalyear')
36         fiscalperiod_obj = self.pool.get('account.period')
37         fiscalyear_ids = []
38         fiscalperiod_ids = []
39         initial_bal = context.get('initial_bal', False)
40         company_clause = ""
41         if context.get('company_id', False):
42             company_clause = " AND " +obj+".company_id = %s" % context.get('company_id', False)
43         if not context.get('fiscalyear', False):
44             fiscalyear_ids = fiscalyear_obj.search(cr, uid, [('state', '=', 'draft')])
45         else:
46             if initial_bal:
47                 fiscalyear_date_start = fiscalyear_obj.read(cr, uid, context['fiscalyear'], ['date_start'])['date_start']
48                 fiscalyear_ids = fiscalyear_obj.search(cr, uid, [('date_stop', '<', fiscalyear_date_start), ('state', '=', 'draft')], context=context)
49             else:
50                 fiscalyear_ids = [context['fiscalyear']]
51
52         fiscalyear_clause = (','.join([str(x) for x in fiscalyear_ids])) or '0'
53         state = context.get('state',False)
54
55         where_move_state = ''
56         where_move_lines_by_date = ''
57
58         if context.get('date_from', False) and context.get('date_to', False):
59             if initital_bal:
60                 where_move_lines_by_date = " AND " +obj+".move_id in ( select id from account_move  where date < '"+context['date_from']+"')"
61             else:
62                 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']+"')"
63
64         if state:
65             if state.lower() not in ['all']:
66                 where_move_state= " AND "+obj+".move_id in (select id from account_move where account_move.state = '"+state+"')"
67
68         if context.get('period_from', False) and context.get('periof_from', False) and not context.get('periods', False):
69             if initial_bal:
70                 period_company_id = period_obj.browse(cr, uid, data['form']['period_from'], context=context).company_id.id
71                 first_period = self.pool.get('account.period').search(cr, uid, [('company_id', '=', period_company_id)], order='date_start', limit=1)[0]
72                 context['periods'] = period_obj.build_ctx_periods(cr, uid, first_period, data['form']['period_from'])
73             else:
74                 context['periods'] = period_obj.build_ctx_periods(cr, uid, data['form']['period_from'], data['form']['period_to'])
75
76         if context.get('periods', False):
77             ids = ','.join([str(x) for x in context['periods']])
78             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)
79         else:
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
82         if context.get('journal_ids', False):
83             query += ' AND '+obj+'.journal_id in (%s)' % ','.join(map(str, context['journal_ids']))
84
85         if context.get('chart_account_id', False):
86             child_ids = self.pool.get('account.account')._get_children_and_consol(cr, uid, [context['chart_account_id']], context=context)
87             query += ' AND '+obj+'.account_id in (%s)' % ','.join(map(str, child_ids))
88
89         query += company_clause
90
91         if context.get('period_manner','') == 'created':
92             #the query have to be build with no reference to periods but thanks to the creation date
93             if context.get('periods',False):
94                 #if one or more period are given, use them
95                 fiscalperiod_ids = fiscalperiod_obj.search(cr, uid, [('id','in',context['periods'])])
96             else:
97                 fiscalperiod_ids = self.pool.get('account.period').search(cr, uid, [('fiscalyear_id','in',fiscalyear_ids)])
98
99             #remove from the old query the clause related to the period selection
100             res = ''
101             count = 1
102             clause_list = query.split('AND')
103             ref_string = ' '+obj+'.period_id in'
104             for clause in clause_list:
105                 if count != 1 and not clause.startswith(ref_string):
106                     res += "AND"
107                 if not clause.startswith(ref_string):
108                     res += clause
109                     count += 1
110
111             #add to 'res' a new clause containing the creation date criterion
112             count = 1
113             res += " AND ("
114             periods = self.pool.get('account.period').read(cr, uid, p_ids, ['date_start','date_stop'])
115             for period in periods:
116                 if count != 1:
117                     res += " OR "
118                 #creation date criterion: the creation date of the move_line has to be
119                 # between the date_start and the date_stop of the selected periods
120                 res += "("+obj+".create_date between to_date('" + period['date_start']  + "','yyyy-mm-dd') and to_date('" + period['date_stop']  + "','yyyy-mm-dd'))"
121                 count += 1
122             res += ")"
123             return res
124
125         return query
126
127     def default_get(self, cr, uid, fields, context={}):
128         data = self._default_get(cr, uid, fields, context)
129         for f in data.keys():
130             if f not in fields:
131                 del data[f]
132         return data
133
134     def create_analytic_lines(self, cr, uid, ids, context={}):
135         for obj_line in self.browse(cr, uid, ids, context):
136             if obj_line.analytic_account_id:
137                 if not obj_line.journal_id.analytic_journal_id:
138                     raise osv.except_osv(_('No Analytic Journal !'),_("You have to define an analytic journal on the '%s' journal!") % (obj_line.journal_id.name,))
139                 amt = (obj_line.credit or  0.0) - (obj_line.debit or 0.0)
140                 vals_lines={
141                     'name': obj_line.name,
142                     'date': obj_line.date,
143                     'account_id': obj_line.analytic_account_id.id,
144                     'unit_amount':obj_line.quantity,
145                     'product_id': obj_line.product_id and obj_line.product_id.id or False,
146                     'product_uom_id': obj_line.product_uom_id and obj_line.product_uom_id.id or False,
147                     'amount': amt,
148                     'general_account_id': obj_line.account_id.id,
149                     'journal_id': obj_line.journal_id.analytic_journal_id.id,
150                     'ref': obj_line.ref,
151                     'move_id':obj_line.id,
152                     'user_id': uid
153                 }
154                 new_id = self.pool.get('account.analytic.line').create(cr,uid,vals_lines)
155         return True
156
157     def _default_get_move_form_hook(self, cursor, user, data):
158         '''Called in the end of default_get method for manual entry in account_move form'''
159         if data.has_key('analytic_account_id'):
160             del(data['analytic_account_id'])
161         if data.has_key('account_tax_id'):
162             del(data['account_tax_id'])
163         return data
164
165     def convert_to_period(self, cr, uid, context={}):
166         period_obj = self.pool.get('account.period')
167
168         #check if the period_id changed in the context from client side
169         if context.get('period_id', False):
170             period_id = context.get('period_id')
171             if type(period_id) == str:
172                 ids = period_obj.search(cr, uid, [('name','ilike',period_id)])
173                 context.update({
174                     'period_id':ids[0]
175                 })
176
177         return context
178
179     def _default_get(self, cr, uid, fields, context={}):
180
181         if not context.get('journal_id', False) and context.get('search_default_journal_id', False):
182             context['journal_id'] = context.get('search_default_journal_id')
183
184         period_obj = self.pool.get('account.period')
185
186         context = self.convert_to_period(cr, uid, context)
187
188         # Compute simple values
189         data = super(account_move_line, self).default_get(cr, uid, fields, context)
190         # Starts: Manual entry from account.move form
191         if context.get('lines',[]):
192
193             total_new=0.00
194             for i in context['lines']:
195                 if i[2]:
196                     total_new +=(i[2]['debit'] or 0.00)- (i[2]['credit'] or 0.00)
197                     for item in i[2]:
198                             data[item]=i[2][item]
199             if context['journal']:
200                 journal_obj=self.pool.get('account.journal').browse(cr, uid, context['journal'])
201                 if journal_obj.type == 'purchase':
202                     if total_new > 0:
203                         account = journal_obj.default_credit_account_id
204                     else:
205                         account = journal_obj.default_debit_account_id
206                 else:
207                     if total_new > 0:
208                         account = journal_obj.default_credit_account_id
209                     else:
210                         account = journal_obj.default_debit_account_id
211
212                 if account and ((not fields) or ('debit' in fields) or ('credit' in fields)) and 'partner_id' in data and (data['partner_id']):
213                     part = self.pool.get('res.partner').browse(cr, uid, data['partner_id'])
214                     account = self.pool.get('account.fiscal.position').map_account(cr, uid, part and part.property_account_position or False, account.id)
215                     account = self.pool.get('account.account').browse(cr, uid, account)
216                     data['account_id'] =  account.id
217
218             s = -total_new
219             data['debit'] = s>0  and s or 0.0
220             data['credit'] = s<0  and -s or 0.0
221             data = self._default_get_move_form_hook(cr, uid, data)
222             return data
223         # Ends: Manual entry from account.move form
224
225         if not 'move_id' in fields: #we are not in manual entry
226             return data
227
228         # Compute the current move
229         move_id = False
230         partner_id = False
231         if context.get('journal_id', False) and context.get('period_id', False):
232             if 'move_id' in fields:
233                 cr.execute('select move_id \
234                     from \
235                         account_move_line \
236                     where \
237                         journal_id=%s and period_id=%s and create_uid=%s and state=%s \
238                     order by id desc limit 1',
239                     (context['journal_id'], context['period_id'], uid, 'draft'))
240                 res = cr.fetchone()
241                 move_id = (res and res[0]) or False
242
243                 if not move_id:
244                     return data
245                 else:
246                     data['move_id'] = move_id
247
248             if 'date' in fields:
249                 cr.execute('select date  \
250                     from \
251                         account_move_line \
252                     where \
253                         journal_id=%s and period_id=%s and create_uid=%s \
254                     order by id desc',
255                     (context['journal_id'], context['period_id'], uid))
256                 res = cr.fetchone()
257                 if res:
258                     data['date'] = res[0]
259                 else:
260                     period = period_obj.browse(cr, uid, context['period_id'],
261                             context=context)
262                     data['date'] = period.date_start
263         if not move_id:
264             return data
265
266         total = 0
267         ref_id = False
268         move = self.pool.get('account.move').browse(cr, uid, move_id, context)
269         if 'name' in fields:
270             data.setdefault('name', move.line_id[-1].name)
271         acc1 = False
272         for l in move.line_id:
273             acc1 = l.account_id
274             partner_id = partner_id or l.partner_id.id
275             ref_id = ref_id or l.ref
276             total += (l.debit or 0.0) - (l.credit or 0.0)
277
278         if 'ref' in fields:
279             data['ref'] = ref_id
280         if 'partner_id' in fields:
281             data['partner_id'] = partner_id
282
283         if move.journal_id.type == 'purchase':
284             if total>0:
285                 account = move.journal_id.default_credit_account_id
286             else:
287                 account = move.journal_id.default_debit_account_id
288         else:
289             if total>0:
290                 account = move.journal_id.default_credit_account_id
291             else:
292                 account = move.journal_id.default_debit_account_id
293
294         part = partner_id and self.pool.get('res.partner').browse(cr, uid, partner_id) or False
295         # part = False is acceptable for fiscal position.
296         account = self.pool.get('account.fiscal.position').map_account(cr, uid, part and part.property_account_position or False, account.id)
297         if account:
298             account = self.pool.get('account.account').browse(cr, uid, account)
299
300         if account and ((not fields) or ('debit' in fields) or ('credit' in fields)):
301             data['account_id'] = account.id
302             # Propose the price VAT excluded, the VAT will be added when confirming line
303             if account.tax_ids:
304                 taxes = self.pool.get('account.fiscal.position').map_tax(cr, uid, part and part.property_account_position or False, account.tax_ids)
305                 tax = self.pool.get('account.tax').browse(cr, uid, taxes)
306                 for t in self.pool.get('account.tax').compute_inv(cr, uid, tax, total, 1):
307                     total -= t['amount']
308
309         s = -total
310         data['debit'] = s>0  and s or 0.0
311         data['credit'] = s<0  and -s or 0.0
312
313         if account and account.currency_id:
314             data['currency_id'] = account.currency_id.id
315             acc = account
316             if s>0:
317                 acc = acc1
318             v = self.pool.get('res.currency').compute(cr, uid,
319                 account.company_id.currency_id.id,
320                 data['currency_id'],
321                 s, account=acc, account_invert=True)
322             data['amount_currency'] = v
323         return data
324
325     def on_create_write(self, cr, uid, id, context={}):
326         ml = self.browse(cr, uid, id, context)
327         return map(lambda x: x.id, ml.move_id.line_id)
328
329     def _balance(self, cr, uid, ids, name, arg, context=None):
330         if context is None:
331             context = {}
332
333         c = context.copy()
334         c['initital_bal'] = True
335
336         sql = [
337             """select l2.id, sum(l1.debit-l1.credit) from account_move_line l1, account_move_line l2""",
338             """where l2.account_id=l1.account_id""",
339             """and""",
340             """l1.id<=l2.id""",
341             """and""",
342             """l2.id in %s""",
343             """and""",
344             self._query_get(cr, uid, obj='l1', context=c),
345             """ group by l2.id""",
346         ]
347
348         cr.execute('\n'.join(sql), [tuple(ids)])
349         res = dict(cr.fetchall())
350         return res
351
352     def _invoice(self, cursor, user, ids, name, arg, context=None):
353         invoice_obj = self.pool.get('account.invoice')
354         res = {}
355         for line_id in ids:
356             res[line_id] = False
357         cursor.execute('SELECT l.id, i.id ' \
358                         'FROM account_move_line l, account_invoice i ' \
359                         'WHERE l.move_id = i.move_id ' \
360                         'AND l.id IN %s',
361                         (tuple(ids),))
362         invoice_ids = []
363         for line_id, invoice_id in cursor.fetchall():
364             res[line_id] = invoice_id
365             invoice_ids.append(invoice_id)
366         invoice_names = {False: ''}
367         for invoice_id, name in invoice_obj.name_get(cursor, user,
368                 invoice_ids, context=context):
369             invoice_names[invoice_id] = name
370         for line_id in res.keys():
371             invoice_id = res[line_id]
372             res[line_id] = (invoice_id, invoice_names[invoice_id])
373         return res
374
375     def name_get(self, cr, uid, ids, context={}):
376         if not len(ids):
377             return []
378         result = []
379         for line in self.browse(cr, uid, ids, context):
380             if line.ref:
381                 result.append((line.id, (line.move_id.name or '')+' ('+line.ref+')'))
382             else:
383                 result.append((line.id, line.move_id.name))
384         return result
385
386     def _balance_search(self, cursor, user, obj, name, args, domain=None, context=None):
387         if context is None:
388             context = {}
389
390         if not len(args):
391             return []
392         where = ' and '.join(map(lambda x: '(abs(sum(debit-credit))'+x[1]+str(x[2])+')',args))
393         cursor.execute('select id, sum(debit-credit) from account_move_line \
394                      group by id, debit, credit having '+where)
395         res = cursor.fetchall()
396         if not len(res):
397             return [('id', '=', '0')]
398         return [('id', 'in', [x[0] for x in res])]
399
400     def _invoice_search(self, cursor, user, obj, name, args, context):
401         if not len(args):
402             return []
403         invoice_obj = self.pool.get('account.invoice')
404
405         i = 0
406         while i < len(args):
407             fargs = args[i][0].split('.', 1)
408             if len(fargs) > 1:
409                 args[i] = (fargs[0], 'in', invoice_obj.search(cursor, user,
410                     [(fargs[1], args[i][1], args[i][2])]))
411                 i += 1
412                 continue
413             if isinstance(args[i][2], basestring):
414                 res_ids = invoice_obj.name_search(cursor, user, args[i][2], [],
415                         args[i][1])
416                 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
417             i += 1
418         qu1, qu2 = [], []
419         for x in args:
420             if x[1] != 'in':
421                 if (x[2] is False) and (x[1] == '='):
422                     qu1.append('(i.id IS NULL)')
423                 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
424                     qu1.append('(i.id IS NOT NULL)')
425                 else:
426                     qu1.append('(i.id %s %s)' % (x[1], '%s'))
427                     qu2.append(x[2])
428             elif x[1] == 'in':
429                 if len(x[2]) > 0:
430                     qu1.append('(i.id in (%s))' % (','.join(['%s'] * len(x[2]))))
431                     qu2 += x[2]
432                 else:
433                     qu1.append(' (False)')
434         if len(qu1):
435             qu1 = ' AND' + ' AND'.join(qu1)
436         else:
437             qu1 = ''
438         cursor.execute('SELECT l.id ' \
439                 'FROM account_move_line l, account_invoice i ' \
440                 'WHERE l.move_id = i.move_id ' + qu1, qu2)
441         res = cursor.fetchall()
442         if not len(res):
443             return [('id', '=', '0')]
444         return [('id', 'in', [x[0] for x in res])]
445
446     def _get_move_lines(self, cr, uid, ids, context={}):
447         result = []
448         for move in self.pool.get('account.move').browse(cr, uid, ids, context=context):
449             for line in move.line_id:
450                 result.append(line.id)
451         return result
452
453     _columns = {
454         'name': fields.char('Name', size=64, required=True),
455         '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."),
456         'product_uom_id': fields.many2one('product.uom', 'UoM'),
457         'product_id': fields.many2one('product.product', 'Product'),
458         'debit': fields.float('Debit', digits_compute=dp.get_precision('Account')),
459         'credit': fields.float('Credit', digits_compute=dp.get_precision('Account')),
460         'account_id': fields.many2one('account.account', 'Account', required=True, ondelete="cascade", domain=[('type','<>','view'), ('type', '<>', 'closed')], select=2),
461         'move_id': fields.many2one('account.move', 'Move', ondelete="cascade", help="The move of this entry line.", select=2, required=True),
462         'narration': fields.related('move_id','narration', type='text', relation='account.move', string='Narration'),
463         'ref': fields.related('move_id', 'ref', string='Reference', type='char', size=64, store=True),
464         'statement_id': fields.many2one('account.bank.statement', 'Statement', help="The bank statement used for bank reconciliation", select=1),
465         'reconcile_id': fields.many2one('account.move.reconcile', 'Reconcile', readonly=True, ondelete='set null', select=2),
466         'reconcile_partial_id': fields.many2one('account.move.reconcile', 'Partial Reconcile', readonly=True, ondelete='set null', select=2),
467         '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')),
468         'currency_id': fields.many2one('res.currency', 'Currency', help="The optional other currency if it is a multi-currency entry."),
469
470         'period_id': fields.many2one('account.period', 'Period', required=True, select=2),
471         'journal_id': fields.many2one('account.journal', 'Journal', required=True, select=1),
472         'blocked': fields.boolean('Litigation', help="You can check this box to mark this journal item as a litigation with the associated partner"),
473
474         'partner_id': fields.many2one('res.partner', 'Partner'),
475         'date_maturity': fields.date('Due date', help="This field is used for payable and receivable journal entries. You can put the limit date for the payment of this line."),
476         'date': fields.related('move_id','date', string='Effective date', type='date', required=True,
477             store={
478                 'account.move': (_get_move_lines, ['date'], 20)
479             }),
480         'date_created': fields.date('Creation date'),
481         'analytic_lines': fields.one2many('account.analytic.line', 'move_id', 'Analytic lines'),
482         'centralisation': fields.selection([('normal','Normal'),('credit','Credit Centralisation'),('debit','Debit Centralisation')], 'Centralisation', size=6),
483         'balance': fields.function(_balance, fnct_search=_balance_search, method=True, string='Balance'),
484         'state': fields.selection([('draft','Unbalanced'), ('valid','Valid')], 'State', readonly=True,
485                                   help='When new move line is created the state will be \'Draft\'.\n* When all the payments are done it will be in \'Valid\' state.'),
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, method=True, string='Invoice',
490             type='many2one', relation='account.invoice', fnct_search=_invoice_search),
491         'account_tax_id':fields.many2one('account.tax', 'Tax'),
492         'analytic_account_id': fields.many2one('account.analytic.account', 'Analytic Account'),
493         #TODO: remove this
494         #'amount_taxed':fields.float("Taxed Amount", digits_compute=dp.get_precision('Account')),
495         'company_id': fields.related('account_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True)
496
497     }
498
499     def _get_date(self, cr, uid, context):
500         period_obj = self.pool.get('account.period')
501         dt = time.strftime('%Y-%m-%d')
502         if ('journal_id' in context) and ('period_id' in context):
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'],
512                         context=context)
513                 dt = period.date_start
514         return dt
515
516     def _get_currency(self, cr, uid, context={}):
517         if not context.get('journal_id', False):
518             return False
519         cur = self.pool.get('account.journal').browse(cr, uid, context['journal_id']).currency
520         return cur and cur.id or False
521
522     _defaults = {
523         'blocked': lambda *a: False,
524         'centralisation': lambda *a: 'normal',
525         'date': _get_date,
526         'date_created': lambda *a: time.strftime('%Y-%m-%d'),
527         'state': lambda *a: 'draft',
528         'currency_id': _get_currency,
529         'journal_id': lambda self, cr, uid, c: c.get('journal_id', False),
530         'period_id': lambda self, cr, uid, c: c.get('period_id', False),
531         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.move.line', context=c)
532     }
533     _order = "date desc,id desc"
534     _sql_constraints = [
535         ('credit_debit1', 'CHECK (credit*debit=0)',  'Wrong credit or debit value in accounting entry !'),
536         ('credit_debit2', 'CHECK (credit+debit>=0)', 'Wrong credit or debit value in accounting entry !'),
537     ]
538
539     def _auto_init(self, cr, context={}):
540         super(account_move_line, self)._auto_init(cr, context)
541         cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = \'account_move_line_journal_id_period_id_index\'')
542         if not cr.fetchone():
543             cr.execute('CREATE INDEX account_move_line_journal_id_period_id_index ON account_move_line (journal_id, period_id)')
544
545     def _check_no_view(self, cr, uid, ids):
546         lines = self.browse(cr, uid, ids)
547         for l in lines:
548             if l.account_id.type == 'view':
549                 return False
550         return True
551
552     def _check_no_closed(self, cr, uid, ids):
553         lines = self.browse(cr, uid, ids)
554         for l in lines:
555             if l.account_id.type == 'closed':
556                 return False
557         return True
558
559     def _check_company_id(self, cr, uid, ids):
560         lines = self.browse(cr, uid, ids)
561         for l in lines:
562             if l.company_id != l.account_id.company_id or l.company_id != l.period_id.company_id:
563                 return False
564         return True
565
566     _constraints = [
567         (_check_no_view, 'You can not create move line on view account.', ['account_id']),
568         (_check_no_closed, 'You can not create move line on closed account.', ['account_id']),
569         (_check_company_id,'Company must be same for its related account and period.',['company_id'] ),
570     ]
571
572     #TODO: ONCHANGE_ACCOUNT_ID: set account_tax_id
573
574     def onchange_currency(self, cr, uid, ids, account_id, amount, currency_id, date=False, journal=False):
575         if (not currency_id) or (not account_id):
576             return {}
577         result = {}
578         acc =self.pool.get('account.account').browse(cr, uid, account_id)
579         if (amount>0) and journal:
580             x = self.pool.get('account.journal').browse(cr, uid, journal).default_credit_account_id
581             if x: acc = x
582         v = self.pool.get('res.currency').compute(cr, uid, currency_id,acc.company_id.currency_id.id, amount, account=acc)
583         result['value'] = {
584             'debit': v>0 and v or 0.0,
585             'credit': v<0 and -v or 0.0
586         }
587         return result
588
589     def onchange_partner_id(self, cr, uid, ids, move_id, partner_id, account_id=None, debit=0, credit=0, date=False, journal=False):
590         val = {}
591         val['date_maturity'] = False
592
593         if not partner_id:
594             return {'value':val}
595         if not date:
596             date = datetime.now().strftime('%Y-%m-%d')
597         part = self.pool.get('res.partner').browse(cr, uid, partner_id)
598
599         if part.property_payment_term:
600             res = self.pool.get('account.payment.term').compute(cr, uid, part.property_payment_term.id, 100, date)
601             if res:
602                 val['date_maturity'] = res[0][0]
603         if not account_id:
604             id1 = part.property_account_payable.id
605             id2 =  part.property_account_receivable.id
606             if journal:
607                 jt = self.pool.get('account.journal').browse(cr, uid, journal).type
608                 #FIXME: Bank and cash journal are such a journal we can not assume a account based on this 2 journals
609                 # Bank and cash journal can have a payment or receipt transaction, and in both type partner account
610                 # will not be same id payment then payable, and if receipt then receivable
611                 #if jt in ('sale', 'purchase_refund', 'bank', 'cash'):
612                 if jt in ('sale', 'purchase_refund'):
613                     val['account_id'] = self.pool.get('account.fiscal.position').map_account(cr, uid, part and part.property_account_position or False, id2)
614                 elif jt in ('purchase', 'sale_refund', 'expense', 'bank', 'cash'):
615                     val['account_id'] = self.pool.get('account.fiscal.position').map_account(cr, uid, part and part.property_account_position or False, id1)
616
617                 if val.get('account_id', False):
618                     d = self.onchange_account_id(cr, uid, ids, val['account_id'])
619                     val.update(d['value'])
620
621         return {'value':val}
622
623     def onchange_account_id(self, cr, uid, ids, account_id=False, partner_id=False):
624         val = {}
625         if account_id:
626             res = self.pool.get('account.account').browse(cr, uid, account_id)
627             tax_ids = res.tax_ids
628             if tax_ids and partner_id:
629                 part = self.pool.get('res.partner').browse(cr, uid, partner_id)
630                 tax_id = self.pool.get('account.fiscal.position').map_tax(cr, uid, part and part.property_account_position or False, tax_ids)[0]
631             else:
632                 tax_id = tax_ids and tax_ids[0].id or False
633             val['account_tax_id'] = tax_id
634         return {'value':val}
635
636     #
637     # type: the type if reconciliation (no logic behind this field, for info)
638     #
639     # writeoff; entry generated for the difference between the lines
640     #
641
642     def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False):
643         if context is None:
644             context = {}
645         if context and context.get('next_partner_only', False):
646             if not context.get('partner_id', False):
647                 partner = self.get_next_partner_only(cr, uid, offset, context)
648             else:
649                 partner = context.get('partner_id', False)
650             if not partner:
651                 return []
652             args.append(('partner_id', '=', partner[0]))
653         return super(account_move_line, self).search(cr, uid, args, offset, limit, order, context, count)
654
655     def get_next_partner_only(self, cr, uid, offset=0, context=None):
656         cr.execute(
657              """
658              SELECT p.id
659              FROM res_partner p
660              RIGHT JOIN (
661                 SELECT l.partner_id as partner_id, SUM(l.debit) as debit, SUM(l.credit) as credit
662                 FROM account_move_line l
663                 LEFT JOIN account_account a ON (a.id = l.account_id)
664                     LEFT JOIN res_partner p ON (l.partner_id = p.id)
665                     WHERE a.reconcile IS TRUE
666                     AND l.reconcile_id IS NULL
667                     AND (p.last_reconciliation_date IS NULL OR l.date > p.last_reconciliation_date)
668                     AND l.state <> 'draft'
669                     GROUP BY l.partner_id
670                 ) AS s ON (p.id = s.partner_id)
671                 WHERE debit > 0 AND credit > 0
672                 ORDER BY p.last_reconciliation_date LIMIT 1 OFFSET %s""", (offset,)
673             )
674         return cr.fetchone()
675
676     def reconcile_partial(self, cr, uid, ids, type='auto', context=None):
677         merges = []
678         unmerge = []
679         total = 0.0
680         merges_rec = []
681
682         company_list = []
683         if context is None:
684             context = {}
685
686         for line in self.browse(cr, uid, ids, context=context):
687             if company_list and not line.company_id.id in company_list:
688                 raise osv.except_osv(_('Warning !'), _('To reconcile the entries company should be the same for all entries'))
689             company_list.append(line.company_id.id)
690
691         for line in self.browse(cr, uid, ids, context):
692             if line.reconcile_id:
693                 raise osv.except_osv(_('Warning'), _('Already Reconciled!'))
694             if line.reconcile_partial_id:
695                 for line2 in line.reconcile_partial_id.line_partial_ids:
696                     if not line2.reconcile_id:
697                         if line2.id not in merges:
698                             merges.append(line2.id)
699                         total += (line2.debit or 0.0) - (line2.credit or 0.0)
700                 merges_rec.append(line.reconcile_partial_id.id)
701             else:
702                 unmerge.append(line.id)
703                 total += (line.debit or 0.0) - (line.credit or 0.0)
704
705         if not total:
706             res = self.reconcile(cr, uid, merges+unmerge, context=context)
707             return res
708         r_id = self.pool.get('account.move.reconcile').create(cr, uid, {
709             'type': type,
710             'line_partial_ids': map(lambda x: (4,x,False), merges+unmerge)
711         })
712         self.pool.get('account.move.reconcile').reconcile_partial_check(cr, uid, [r_id] + merges_rec, context=context)
713         return True
714
715     def reconcile(self, cr, uid, ids, type='auto', writeoff_acc_id=False, writeoff_period_id=False, writeoff_journal_id=False, context=None):
716         lines = self.browse(cr, uid, ids, context=context)
717         unrec_lines = filter(lambda x: not x['reconcile_id'], lines)
718         credit = debit = 0.0
719         currency = 0.0
720         account_id = False
721         partner_id = False
722         if context is None:
723             context = {}
724
725         company_list = []
726         for line in self.browse(cr, uid, ids, context=context):
727             if company_list and not line.company_id.id in company_list:
728                 raise osv.except_osv(_('Warning !'), _('To reconcile the entries company should be the same for all entries'))
729             company_list.append(line.company_id.id)
730
731         for line in unrec_lines:
732             if line.state <> 'valid':
733                 raise osv.except_osv(_('Error'),
734                         _('Entry "%s" is not valid !') % line.name)
735             credit += line['credit']
736             debit += line['debit']
737             currency += line['amount_currency'] or 0.0
738             account_id = line['account_id']['id']
739             partner_id = (line['partner_id'] and line['partner_id']['id']) or False
740         writeoff = debit - credit
741
742         # Ifdate_p in context => take this date
743         if context.has_key('date_p') and context['date_p']:
744             date=context['date_p']
745         else:
746             date = time.strftime('%Y-%m-%d')
747
748         cr.execute('SELECT account_id, reconcile_id '\
749                    'FROM account_move_line '\
750                    'WHERE id IN %s '\
751                    'GROUP BY account_id,reconcile_id',
752                    (tuple(ids),))
753         r = cr.fetchall()
754         #TODO: move this check to a constraint in the account_move_reconcile object
755         if (len(r) != 1) and not context.get('fy_closing', False):
756             raise osv.except_osv(_('Error'), _('Entries are not of the same account or already reconciled ! '))
757         if not unrec_lines:
758             raise osv.except_osv(_('Error'), _('Entry is already reconciled'))
759         account = self.pool.get('account.account').browse(cr, uid, account_id, context=context)
760         if not context.get('fy_closing', False) and not account.reconcile:
761             raise osv.except_osv(_('Error'), _('The account is not defined to be reconciled !'))
762         if r[0][1] != None:
763             raise osv.except_osv(_('Error'), _('Some entries are already reconciled !'))
764
765         if (not self.pool.get('res.currency').is_zero(cr, uid, account.company_id.currency_id, writeoff)) or \
766            (account.currency_id and (not self.pool.get('res.currency').is_zero(cr, uid, account.currency_id, currency))):
767             if not writeoff_acc_id:
768                 raise osv.except_osv(_('Warning'), _('You have to provide an account for the write off entry !'))
769             if writeoff > 0:
770                 debit = writeoff
771                 credit = 0.0
772                 self_credit = writeoff
773                 self_debit = 0.0
774             else:
775                 debit = 0.0
776                 credit = -writeoff
777                 self_credit = 0.0
778                 self_debit = -writeoff
779
780             # If comment exist in context, take it
781             if 'comment' in context and context['comment']:
782                 libelle=context['comment']
783             else:
784                 libelle='Write-Off'
785
786             writeoff_lines = [
787                 (0, 0, {
788                     'name':libelle,
789                     'debit':self_debit,
790                     'credit':self_credit,
791                     'account_id':account_id,
792                     'date':date,
793                     'partner_id':partner_id,
794                     'currency_id': account.currency_id.id or False,
795                     'amount_currency': account.currency_id.id and -currency or 0.0
796                 }),
797                 (0, 0, {
798                     'name':libelle,
799                     'debit':debit,
800                     'credit':credit,
801                     'account_id':writeoff_acc_id,
802                     'analytic_account_id': context.get('analytic_id', False),
803                     'date':date,
804                     'partner_id':partner_id
805                 })
806             ]
807
808             writeoff_move_id = self.pool.get('account.move').create(cr, uid, {
809                 'period_id': writeoff_period_id,
810                 'journal_id': writeoff_journal_id,
811                 'date':date,
812                 'state': 'draft',
813                 'line_id': writeoff_lines
814             })
815
816             writeoff_line_ids = self.search(cr, uid, [('move_id', '=', writeoff_move_id), ('account_id', '=', account_id)])
817             ids += writeoff_line_ids
818
819         r_id = self.pool.get('account.move.reconcile').create(cr, uid, {
820             #'name': date,
821             'type': type,
822             'line_id': map(lambda x: (4,x,False), ids),
823             'line_partial_ids': map(lambda x: (3,x,False), ids)
824         })
825         wf_service = netsvc.LocalService("workflow")
826         # the id of the move.reconcile is written in the move.line (self) by the create method above
827         # because of the way the line_id are defined: (4, x, False)
828         for id in ids:
829             wf_service.trg_trigger(uid, 'account.move.line', id, cr)
830
831         if lines and lines[0]:
832             partner_id = lines[0].partner_id and lines[0].partner_id.id or False
833             if partner_id and context and context.get('stop_reconcile', False):
834                 self.pool.get('res.partner').write(cr, uid, [partner_id], {'last_reconciliation_date': time.strftime('%Y-%m-%d %H:%M:%S')})
835         return r_id
836
837     def view_header_get(self, cr, user, view_id, view_type, context):
838         context = self.convert_to_period(cr, user, context)
839         if context.get('account_id', False):
840             cr.execute('select code from account_account where id=%s', (context['account_id'],))
841             res = cr.fetchone()
842             res = _('Entries: ')+ (res[0] or '')
843             return res
844         if (not context.get('journal_id', False)) or (not context.get('period_id', False)):
845             return False
846         cr.execute('select code from account_journal where id=%s', (context['journal_id'],))
847         j = cr.fetchone()[0] or ''
848         cr.execute('select code from account_period where id=%s', (context['period_id'],))
849         p = cr.fetchone()[0] or ''
850         if j or p:
851             return j+(p and (':'+p) or '')
852         return False
853
854     def onchange_date(self, cr, user, ids, date, context={}):
855         """
856         Returns a dict that contains new values and context
857         @param cr: A database cursor
858         @param user: ID of the user currently logged in
859         @param date: latest value from user input for field date
860         @param args: other arguments
861         @param context: context arguments, like lang, time zone
862         @return: Returns a dict which contains new values, and context
863         """
864         res = {}
865         period_pool = self.pool.get('account.period')
866         pids = period_pool.search(cr, user, [('date_start','<=',date), ('date_stop','>=',date)])
867         if pids:
868             res.update({
869                 'period_id':pids[0]
870             })
871             context.update({
872                 'period_id':pids[0]
873             })
874         return {
875             'value':res,
876             'context':context,
877         }
878
879     def fields_view_get(self, cr, uid, view_id=None, view_type='form', context={}, toolbar=False, submenu=False):
880         journal_pool = self.pool.get('account.journal')
881
882         result = super(osv.osv, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar=toolbar, submenu=submenu)
883         if view_type != 'tree':
884             #Remove the toolbar from the form view
885             if view_type == 'form':
886                 if result.get('toolbar', False):
887                     result['toolbar']['action'] = []
888
889             #Restrict the list of journal view in search view
890             if view_type == 'search':
891                 journal_list = journal_pool.name_search(cr, uid, '', [], context=context)
892                 result['fields']['journal_id']['selection'] = journal_list
893             return result
894
895         if context.get('view_mode', False):
896             return result
897
898         fld = []
899         fields = {}
900         flds = []
901         title = "Accounting Entries" #self.view_header_get(cr, uid, view_id, view_type, context)
902         xml = '''<?xml version="1.0"?>\n<tree string="%s" editable="top" refresh="5" on_write="on_create_write" colors="red:state==\'draft\';black:state==\'valid\'">\n\t''' % (title)
903
904         ids = journal_pool.search(cr, uid, [])
905         journals = journal_pool.browse(cr, uid, ids)
906         all_journal = [None]
907         common_fields = {}
908         total = len(journals)
909         for journal in journals:
910             all_journal.append(journal.id)
911             for field in journal.view_id.columns_id:
912                 if not field.field in fields:
913                     fields[field.field] = [journal.id]
914                     fld.append((field.field, field.sequence))
915                     flds.append(field.field)
916                     common_fields[field.field] = 1
917                 else:
918                     fields.get(field.field).append(journal.id)
919                     common_fields[field.field] = common_fields[field.field] + 1
920         fld.append(('period_id', 3))
921         fld.append(('journal_id', 10))
922         flds.append('period_id')
923         flds.append('journal_id')
924         fields['period_id'] = all_journal
925         fields['journal_id'] = all_journal
926         from operator import itemgetter
927         fld = sorted(fld, key=itemgetter(1))
928
929         widths = {
930             'ref': 50,
931             'statement_id': 50,
932             'state': 60,
933             'tax_code_id': 50,
934             'move_id': 40,
935         }
936
937         for field_it in fld:
938             field = field_it[0]
939             if common_fields.get(field) == total:
940                 fields.get(field).append(None)
941
942 #            if field=='state':
943 #                state = 'colors="red:state==\'draft\'"'
944
945             attrs = []
946             if field == 'debit':
947                 attrs.append('sum="Total debit"')
948
949             elif field == 'credit':
950                 attrs.append('sum="Total credit"')
951
952             elif field == 'move_id':
953                 attrs.append('required="False"')
954
955             elif field == 'account_tax_id':
956                 attrs.append('domain="[(\'parent_id\',\'=\',False)]"')
957                 attrs.append("context=\"{'journal_id':journal_id}\"")
958
959             elif field == 'account_id' and journal.id:
960                 attrs.append('domain="[(\'journal_id\', \'=\', '+str(journal.id)+'),(\'type\',\'&lt;&gt;\',\'view\'), (\'type\',\'&lt;&gt;\',\'closed\')]" on_change="onchange_account_id(account_id, partner_id)"')
961
962             elif field == 'partner_id':
963                 attrs.append('on_change="onchange_partner_id(move_id, partner_id, account_id, debit, credit, date, journal_id)"')
964
965             elif field == 'journal_id':
966                 attrs.append("context=\"{'journal_id':journal_id}\"")
967
968             elif field == 'statement_id':
969                 attrs.append("domain=\"[('state','!=','confirm'),('journal_id.type','=','bank')]\"")
970
971             elif field == 'date':
972                 attrs.append('on_change="onchange_date(date)"')
973
974             if field in ('amount_currency', 'currency_id'):
975                 attrs.append('on_change="onchange_currency(account_id, amount_currency,currency_id, date, journal_id)"')
976                 attrs.append('''attrs="{'readonly':[('state','=','valid')]}"''')
977
978             if field in widths:
979                 attrs.append('width="'+str(widths[field])+'"')
980             attrs.append("invisible=\"context.get('visible_id') not in %s\"" % (fields.get(field)))
981             xml += '''<field name="%s" %s/>\n''' % (field,' '.join(attrs))
982
983         xml += '''</tree>'''
984         result['arch'] = xml
985         result['fields'] = self.fields_get(cr, uid, flds, context)
986         return result
987
988     def _check_moves(self, cr, uid, context):
989         # use the first move ever created for this journal and period
990         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']))
991         res = cr.fetchone()
992         if res:
993             if res[1] != 'draft':
994                 raise osv.except_osv(_('UserError'),
995                        _('The account move (%s) for centralisation ' \
996                                 'has been confirmed!') % res[2])
997         return res
998
999     def _remove_move_reconcile(self, cr, uid, move_ids=[], context=None):
1000         # Function remove move rencocile ids related with moves
1001         obj_move_line = self.pool.get('account.move.line')
1002         obj_move_rec = self.pool.get('account.move.reconcile')
1003         unlink_ids = []
1004         if not move_ids:
1005             return True
1006         recs = obj_move_line.read(cr, uid, move_ids, ['reconcile_id','reconcile_partial_id'])
1007         full_recs = filter(lambda x: x['reconcile_id'], recs)
1008         rec_ids = [rec['reconcile_id'][0] for rec in full_recs]
1009         part_recs = filter(lambda x: x['reconcile_partial_id'], recs)
1010         part_rec_ids = [rec['reconcile_partial_id'][0] for rec in part_recs]
1011         unlink_ids += rec_ids
1012         unlink_ids += part_rec_ids
1013         if len(unlink_ids):
1014             obj_move_rec.unlink(cr, uid, unlink_ids)
1015         return True
1016
1017     def unlink(self, cr, uid, ids, context={}, check=True):
1018         self._update_check(cr, uid, ids, context)
1019         result = False
1020         for line in self.browse(cr, uid, ids, context):
1021             context['journal_id']=line.journal_id.id
1022             context['period_id']=line.period_id.id
1023             result = super(account_move_line, self).unlink(cr, uid, [line.id], context=context)
1024             if check:
1025                 self.pool.get('account.move').validate(cr, uid, [line.move_id.id], context=context)
1026         return result
1027
1028     def _check_date(self, cr, uid, vals, context=None, check=True):
1029         if context is None:
1030             context = {}
1031         journal_id = False
1032         if 'date' in vals.keys():
1033             if 'journal_id' in vals and 'journal_id' not in context:
1034                 journal_id = vals['journal_id']
1035             if 'period_id' in vals and 'period_id' not in context:
1036                 period_id = vals['period_id']
1037             elif 'journal_id' not in context and 'move_id' in vals:
1038                 if vals.get('move_id', False):
1039                     m = self.pool.get('account.move').browse(cr, uid, vals['move_id'])
1040                     journal_id = m.journal_id.id
1041                     period_id = m.period_id.id
1042             else:
1043                 journal_id = context.get('journal_id',False)
1044                 period_id = context.get('period_id',False)
1045             if journal_id:
1046                 journal = self.pool.get('account.journal').browse(cr, uid, [journal_id])[0]
1047                 if journal.allow_date and period_id:
1048                     period = self.pool.get('account.period').browse(cr, uid, [period_id])[0]
1049                     if not time.strptime(vals['date'][:10],'%Y-%m-%d')>=time.strptime(period.date_start,'%Y-%m-%d') or not time.strptime(vals['date'][:10],'%Y-%m-%d')<=time.strptime(period.date_stop,'%Y-%m-%d'):
1050                         raise osv.except_osv(_('Error'),_('The date of your Journal Entry is not in the defined period!'))
1051         else:
1052             return True
1053
1054     def write(self, cr, uid, ids, vals, context=None, check=True, update_check=True):
1055         if context is None:
1056             context={}
1057         if vals.get('account_tax_id', False):
1058             raise osv.except_osv(_('Unable to change tax !'), _('You can not change the tax, you should remove and recreate lines !'))
1059         self._check_date(cr, uid, vals, context, check)
1060         account_obj = self.pool.get('account.account')
1061         if ('account_id' in vals) and not account_obj.read(cr, uid, vals['account_id'], ['active'])['active']:
1062             raise osv.except_osv(_('Bad account!'), _('You can not use an inactive account!'))
1063         if update_check:
1064             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):
1065                 self._update_check(cr, uid, ids, context)
1066
1067         todo_date = None
1068         if vals.get('date', False):
1069             todo_date = vals['date']
1070             del vals['date']
1071
1072         for line in self.browse(cr, uid, ids,context=context):
1073             ctx = context.copy()
1074             if ('journal_id' not in ctx):
1075                 if line.move_id:
1076                    ctx['journal_id'] = line.move_id.journal_id.id
1077                 else:
1078                     ctx['journal_id'] = line.journal_id.id
1079             if ('period_id' not in ctx):
1080                 if line.move_id:
1081                     ctx['period_id'] = line.move_id.period_id.id
1082                 else:
1083                     ctx['period_id'] = line.period_id.id
1084             #Check for centralisation
1085             journal = self.pool.get('account.journal').browse(cr, uid, ctx['journal_id'], context=ctx)
1086             if journal.centralisation:
1087                 self._check_moves(cr, uid, context=ctx)
1088
1089         result = super(account_move_line, self).write(cr, uid, ids, vals, context)
1090
1091         if check:
1092             done = []
1093             for line in self.browse(cr, uid, ids):
1094                 if line.move_id.id not in done:
1095                     done.append(line.move_id.id)
1096                     self.pool.get('account.move').validate(cr, uid, [line.move_id.id], context)
1097                     if todo_date:
1098                         self.pool.get('account.move').write(cr, uid, [line.move_id.id], {'date': todo_date}, context=context)
1099         return result
1100
1101     def _update_journal_check(self, cr, uid, journal_id, period_id, context={}):
1102         cr.execute('select state from account_journal_period where journal_id=%s and period_id=%s', (journal_id, period_id))
1103         result = cr.fetchall()
1104         for (state,) in result:
1105             if state=='done':
1106                 raise osv.except_osv(_('Error !'), _('You can not add/modify entries in a closed journal.'))
1107         if not result:
1108             journal = self.pool.get('account.journal').browse(cr, uid, journal_id, context)
1109             period = self.pool.get('account.period').browse(cr, uid, period_id, context)
1110             self.pool.get('account.journal.period').create(cr, uid, {
1111                 'name': (journal.code or journal.name)+':'+(period.name or ''),
1112                 'journal_id': journal.id,
1113                 'period_id': period.id
1114             })
1115         return True
1116
1117     def _update_check(self, cr, uid, ids, context={}):
1118         done = {}
1119         for line in self.browse(cr, uid, ids, context):
1120             if line.move_id.state<>'draft':
1121                 raise osv.except_osv(_('Error !'), _('You can not do this modification on a confirmed entry ! Please note that you can just change some non important fields !'))
1122             if line.reconcile_id:
1123                 raise osv.except_osv(_('Error !'), _('You can not do this modification on a reconciled entry ! Please note that you can just change some non important fields !'))
1124             t = (line.journal_id.id, line.period_id.id)
1125             if t not in done:
1126                 self._update_journal_check(cr, uid, line.journal_id.id, line.period_id.id, context)
1127                 done[t] = True
1128         return True
1129
1130     def create(self, cr, uid, vals, context=None, check=True):
1131         account_obj = self.pool.get('account.account')
1132         tax_obj=self.pool.get('account.tax')
1133         if context is None:
1134             context = {}
1135         self._check_date(cr, uid, vals, context, check)
1136         if ('account_id' in vals) and not account_obj.read(cr, uid, vals['account_id'], ['active'])['active']:
1137             raise osv.except_osv(_('Bad account!'), _('You can not use an inactive account!'))
1138         if 'journal_id' in vals:
1139             context['journal_id'] = vals['journal_id']
1140         if 'period_id' in vals:
1141             context['period_id'] = vals['period_id']
1142         if ('journal_id' not in context) and ('move_id' in vals) and vals['move_id']:
1143             m = self.pool.get('account.move').browse(cr, uid, vals['move_id'])
1144             context['journal_id'] = m.journal_id.id
1145             context['period_id'] = m.period_id.id
1146
1147         self._update_journal_check(cr, uid, context['journal_id'], context['period_id'], context)
1148         move_id = vals.get('move_id', False)
1149         journal = self.pool.get('account.journal').browse(cr, uid, context['journal_id'])
1150         is_new_move = False
1151         if not move_id:
1152             if journal.centralisation:
1153                 #Check for centralisation
1154                 res = self._check_moves(cr, uid, context)
1155                 if res:
1156                     vals['move_id'] = res[0]
1157
1158             if not vals.get('move_id', False):
1159                 if journal.sequence_id:
1160                     #name = self.pool.get('ir.sequence').get_id(cr, uid, journal.sequence_id.id)
1161                     v = {
1162                         'date': vals.get('date', time.strftime('%Y-%m-%d')),
1163                         'period_id': context['period_id'],
1164                         'journal_id': context['journal_id']
1165                     }
1166                     move_id = self.pool.get('account.move').create(cr, uid, v, context)
1167                     vals['move_id'] = move_id
1168                 else:
1169                     raise osv.except_osv(_('No piece number !'), _('Can not create an automatic sequence for this piece !\n\nPut a sequence in the journal definition for automatic numbering or create a sequence manually for this piece.'))
1170             is_new_move = True
1171
1172         ok = not (journal.type_control_ids or journal.account_control_ids)
1173         if ('account_id' in vals):
1174             account = account_obj.browse(cr, uid, vals['account_id'])
1175             if journal.type_control_ids:
1176                 type = account.user_type
1177                 for t in journal.type_control_ids:
1178                     if type.code == t.code:
1179                         ok = True
1180                         break
1181             if journal.account_control_ids and not ok:
1182                 for a in journal.account_control_ids:
1183                     if a.id == vals['account_id']:
1184                         ok = True
1185                         break
1186
1187             # Automatically convert in the account's secondary currency if there is one and
1188             # the provided values were not already multi-currency
1189             if account.currency_id and 'amount_currency' not in vals and account.currency_id.id != account.company_id.currency_id.id:
1190                 vals['currency_id'] = account.currency_id.id
1191                 cur_obj = self.pool.get('res.currency')
1192                 ctx = {}
1193                 if 'date' in vals:
1194                     ctx['date'] = vals['date']
1195                 vals['amount_currency'] = cur_obj.compute(cr, uid, account.company_id.currency_id.id,
1196                     account.currency_id.id, vals.get('debit', 0.0)-vals.get('credit', 0.0),
1197                     context=ctx)
1198         if not ok:
1199             raise osv.except_osv(_('Bad account !'), _('You can not use this general account in this journal !'))
1200
1201         if vals.get('analytic_account_id',False):
1202             if journal.analytic_journal_id:
1203                 vals['analytic_lines'] = [(0,0, {
1204                         'name': vals['name'],
1205                         'date': vals.get('date', time.strftime('%Y-%m-%d')),
1206                         'account_id': vals.get('analytic_account_id', False),
1207                         'unit_amount': vals.get('quantity', 1.0),
1208                         'amount': vals.get('debit', 0.0) or vals.get('credit', 0.0),
1209                         'general_account_id': vals.get('account_id', False),
1210                         'journal_id': journal.analytic_journal_id.id,
1211                         'ref': vals.get('ref', False),
1212                         'user_id': uid
1213                     })]
1214
1215         result = super(osv.osv, self).create(cr, uid, vals, context)
1216         # CREATE Taxes
1217         if vals.get('account_tax_id', False):
1218             tax_id = tax_obj.browse(cr, uid, vals['account_tax_id'])
1219             total = vals['debit'] - vals['credit']
1220             if journal.refund_journal:
1221                 base_code = 'ref_base_code_id'
1222                 tax_code = 'ref_tax_code_id'
1223                 account_id = 'account_paid_id'
1224                 base_sign = 'ref_base_sign'
1225                 tax_sign = 'ref_tax_sign'
1226             else:
1227                 base_code = 'base_code_id'
1228                 tax_code = 'tax_code_id'
1229                 account_id = 'account_collected_id'
1230                 base_sign = 'base_sign'
1231                 tax_sign = 'tax_sign'
1232
1233             tmp_cnt = 0
1234             for tax in tax_obj.compute_all(cr, uid, [tax_id], total, 1.00).get('taxes'):
1235                 #create the base movement
1236                 if tmp_cnt == 0:
1237                     if tax[base_code]:
1238                         tmp_cnt += 1
1239                         self.write(cr, uid,[result], {
1240                             'tax_code_id': tax[base_code],
1241                             'tax_amount': tax[base_sign] * abs(total)
1242                         })
1243                 else:
1244                     data = {
1245                         'move_id': vals['move_id'],
1246                         'journal_id': vals['journal_id'],
1247                         'period_id': vals['period_id'],
1248                         'name': tools.ustr(vals['name'] or '') + ' ' + tools.ustr(tax['name'] or ''),
1249                         'date': vals['date'],
1250                         'partner_id': vals.get('partner_id',False),
1251                         'ref': vals.get('ref',False),
1252                         'account_tax_id': False,
1253                         'tax_code_id': tax[base_code],
1254                         'tax_amount': tax[base_sign] * abs(total),
1255                         'account_id': vals['account_id'],
1256                         'credit': 0.0,
1257                         'debit': 0.0,
1258                     }
1259                     if data['tax_code_id']:
1260                         self.create(cr, uid, data, context)
1261
1262                 #create the VAT movement
1263                 data = {
1264                     'move_id': vals['move_id'],
1265                     'journal_id': vals['journal_id'],
1266                     'period_id': vals['period_id'],
1267                     'name': tools.ustr(vals['name'] or '') + ' ' + tools.ustr(tax['name'] or ''),
1268                     'date': vals['date'],
1269                     'partner_id': vals.get('partner_id',False),
1270                     'ref': vals.get('ref',False),
1271                     'account_tax_id': False,
1272                     'tax_code_id': tax[tax_code],
1273                     'tax_amount': tax[tax_sign] * abs(tax['amount']),
1274                     'account_id': tax[account_id] or vals['account_id'],
1275                     'credit': tax['amount']<0 and -tax['amount'] or 0.0,
1276                     'debit': tax['amount']>0 and tax['amount'] or 0.0,
1277                 }
1278                 if data['tax_code_id']:
1279                     self.create(cr, uid, data, context)
1280             del vals['account_tax_id']
1281
1282         if check and ((not context.get('no_store_function')) or journal.entry_posted):
1283             tmp = self.pool.get('account.move').validate(cr, uid, [vals['move_id']], context)
1284             if journal.entry_posted and tmp:
1285                 rs = self.pool.get('account.move').button_validate(cr,uid, [vals['move_id']],context)
1286         return result
1287 account_move_line()
1288
1289 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
1290