Modifs
[odoo/odoo.git] / addons / account / account_move_line.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 # Copyright (c) 2004-2008 TINY SPRL. (http://tiny.be) All Rights Reserved.
5 #
6 # $Id$
7 #
8 # WARNING: This program as such is intended to be used by professional
9 # programmers who take the whole responsability of assessing all potential
10 # consequences resulting from its eventual inadequacies and bugs
11 # End users who are looking for a ready-to-use solution with commercial
12 # garantees and support are strongly adviced to contract a Free Software
13 # Service Company
14 #
15 # This program is Free Software; you can redistribute it and/or
16 # modify it under the terms of the GNU General Public License
17 # as published by the Free Software Foundation; either version 2
18 # of the License, or (at your option) any later version.
19 #
20 # This program is distributed in the hope that it will be useful,
21 # but WITHOUT ANY WARRANTY; without even the implied warranty of
22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 # GNU General Public License for more details.
24 #
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
28 #
29 ##############################################################################
30
31 import time
32 import netsvc
33 from osv import fields, osv
34 from tools.translate import _
35
36 class account_move_line(osv.osv):
37     _name = "account.move.line"
38     _description = "Entry lines"
39
40     def _query_get(self, cr, uid, obj='l', context={}):
41         fiscalyear_obj = self.pool.get('account.fiscalyear')
42         if not context.get('fiscalyear', False):
43             fiscalyear_ids = fiscalyear_obj.search(cr, uid, [('state', '=', 'draft')])
44             fiscalyear_clause = (','.join([str(x) for x in fiscalyear_ids])) or '0'
45         else:
46             fiscalyear_clause = '%s' % context['fiscalyear']
47         state=context.get('state',False)
48         where_move_state=''
49         if state:
50             if state.lower() not in ['all']:
51                 where_move_state= " AND "+obj+".move_id in (select id from account_move where account_move.state = '"+state+"')"
52
53         if context.get('periods', False):
54             ids = ','.join([str(x) for x in context['periods']])
55             return obj+".active AND "+obj+".state<>'draft' AND "+obj+".period_id in (SELECT id from account_period WHERE fiscalyear_id in (%s) AND id in (%s)) %s" % (fiscalyear_clause, ids,where_move_state)
56         else:
57             return obj+".active AND "+obj+".state<>'draft' AND "+obj+".period_id in (SELECT id from account_period WHERE fiscalyear_id in (%s) %s)" % (fiscalyear_clause,where_move_state)
58
59     def default_get(self, cr, uid, fields, context={}):
60         data = self._default_get(cr, uid, fields, context)
61         for f in data.keys():
62             if f not in fields:
63                 del data[f]
64         return data
65
66     def _default_get(self, cr, uid, fields, context={}):
67         # Compute simple values
68         data = super(account_move_line, self).default_get(cr, uid, fields, context)
69
70         if not 'move_id' in fields: #we are not in manual entry
71             return data
72
73         period_obj = self.pool.get('account.period')
74         tax_obj=self.pool.get('account.tax')
75
76         # Compute the current move
77         move_id = False
78         partner_id = False
79         if context.get('journal_id',False) and context.get('period_id',False):
80             if 'move_id' in fields:
81                 cr.execute('select move_id \
82                     from \
83                         account_move_line \
84                     where \
85                         journal_id=%d and period_id=%d and create_uid=%d and state=%s \
86                     order by id desc limit 1',
87                     (context['journal_id'], context['period_id'], uid, 'draft'))
88                 res = cr.fetchone()
89                 move_id = (res and res[0]) or False
90
91                 if not move_id:
92                     return data
93                 else:
94                     data['move_id'] = move_id
95             if 'date' in fields:
96                 cr.execute('select date  \
97                     from \
98                         account_move_line \
99                     where \
100                         journal_id=%d and period_id=%d and create_uid=%d \
101                     order by id desc',
102                     (context['journal_id'], context['period_id'], uid))
103                 res = cr.fetchone()
104                 if res:
105                     data['date'] = res[0]
106                 else:
107                     period = period_obj.browse(cr, uid, context['period_id'],
108                             context=context)
109                     data['date'] = period.date_start
110
111         if not move_id:
112             return data
113
114         total = 0
115         ref_id = False
116         move = self.pool.get('account.move').browse(cr, uid, move_id, context)
117
118         for l in move.line_id:
119             partner_id = partner_id or l.partner_id.id
120             ref_id = ref_id or l.ref
121             total += (l.debit or 0.0) - (l.credit or 0.0)
122             if 'name' in fields:
123                data.setdefault('name', l.name)
124         if 'ref' in fields:
125             data['ref'] = ref_id
126         if 'partner_id' in fields:
127             data['partner_id'] = partner_id
128
129         if move.journal_id.type == 'purchase':
130             if total>0:
131                 account = move.journal_id.default_credit_account_id
132             else:
133                 account = move.journal_id.default_debit_account_id
134         else:
135             if total>0:
136                 account = move.journal_id.default_credit_account_id
137             else:
138                 account = move.journal_id.default_debit_account_id
139
140         data['account_id'] = account.id
141         if account and account.tax_ids:
142             for tax in self.pool.get('account.tax').compute_inv(cr,uid,[account.tax_ids[0]],total,1.00):
143                 total -= tax['amount']
144             data['account_tax_id'] = account.tax_ids[0].id
145         s = -total
146         data['debit'] = s>0  and s or 0.0
147         data['credit'] = s<0  and -s or 0.0
148         return data
149
150     def _on_create_write(self, cr, uid, id, context={}):
151         ml = self.browse(cr, uid, id, context)
152         return map(lambda x: x.id, ml.move_id.line_id)
153
154     def _balance(self, cr, uid, ids, prop, unknow_none, unknow_dict):
155         res={}
156         # TODO group the foreach in sql
157         for id in ids:
158             cr.execute('SELECT date,account_id FROM account_move_line WHERE id=%d', (id,))
159             dt, acc = cr.fetchone()
160             cr.execute('SELECT SUM(debit-credit) FROM account_move_line WHERE account_id=%d AND (date<%s OR (date=%s AND id<=%d)) and active', (acc,dt,dt,id))
161             res[id] = cr.fetchone()[0]
162         return res
163
164     def _invoice(self, cursor, user, ids, name, arg, context=None):
165         invoice_obj = self.pool.get('account.invoice')
166         res = {}
167         for line_id in ids:
168             res[line_id] = False
169         cursor.execute('SELECT l.id, i.id ' \
170                 'FROM account_move_line l, account_invoice i ' \
171                 'WHERE l.move_id = i.move_id ' \
172                     'AND l.id in (' + ','.join([str(x) for x in ids]) + ')')
173         invoice_ids = []
174         for line_id, invoice_id in cursor.fetchall():
175             res[line_id] = invoice_id
176             invoice_ids.append(invoice_id)
177         invoice_names = {False: ''}
178         for invoice_id, name in invoice_obj.name_get(cursor, user,
179                 invoice_ids, context=context):
180             invoice_names[invoice_id] = name
181         for line_id in res.keys():
182             invoice_id = res[line_id]
183             res[line_id] = (invoice_id, invoice_names[invoice_id])
184         return res
185
186     def name_get(self, cr, uid, ids, context={}):
187         if not len(ids):
188             return []
189         result = []
190         for line in self.browse(cr, uid, ids, context):
191             if line.ref:
192                 result.append((line.id, (line.name or '')+' ('+line.ref+')'))
193             else:
194                 result.append((line.id, line.name))
195         return result
196
197     def _invoice_search(self, cursor, user, obj, name, args):
198         if not len(args):
199             return []
200         invoice_obj = self.pool.get('account.invoice')
201
202         i = 0
203         while i < len(args):
204             fargs = args[i][0].split('.', 1)
205             if len(fargs) > 1:
206                 args[i] = (frags[0], 'in', invoice_obj.search(cursor, user,
207                     [(fargs[1], args[i][1], args[i][2])]))
208                 i += 1
209                 continue
210             if isinstance(args[i][2], basestring):
211                 res_ids = invoice_obj.name_search(cursor, user, args[i][2], [],
212                         args[i][1])
213                 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
214             i += 1
215         qu1, qu2 = [], []
216         for x in args:
217             if x[1] != 'in':
218                 if (x[2] is False) and (x[1] == '='):
219                     qu1.append('(i.id IS NULL)')
220                 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
221                     qu1.append('(i.id IS NOT NULL)')
222                 else:
223                     qu1.append('(i.id %s %s)' % (x[1], '%d'))
224                     qu2.append(x[2])
225             elif x[1] == 'in':
226                 if len(x[2]) > 0:
227                     qu1.append('(i.id in (%s))' % (','.join(['%d'] * len(x[2]))))
228                     qu2 += x[2]
229                 else:
230                     qu1.append(' (False)')
231         if len(qu1):
232             qu1 = ' AND' + ' AND'.join(qu1)
233         else:
234             qu1 = ''
235         cursor.execute('SELECT l.id ' \
236                 'FROM account_move_line l, account_invoice i ' \
237                 'WHERE l.move_id = i.move_id ' + qu1, qu2)
238         res = cursor.fetchall()
239         if not len(res):
240             return [('id', '=', '0')]
241         return [('id', 'in', [x[0] for x in res])]
242
243     _columns = {
244         'name': fields.char('Name', size=64, required=True),
245         'quantity': fields.float('Quantity', digits=(16,2), help="The optionnal quantity expressed by this line, eg: number of product sold. The quantity is not a legal requirement but is very usefull for some reports."),
246         'debit': fields.float('Debit', digits=(16,2)),
247         'credit': fields.float('Credit', digits=(16,2)),
248         'account_id': fields.many2one('account.account', 'Account', required=True, ondelete="cascade", domain=[('type','<>','view'), ('type', '<>', 'closed')], select=2),
249         'move_id': fields.many2one('account.move', 'Move', ondelete="cascade", states={'valid':[('readonly',True)]}, help="The move of this entry line.", select=2),
250
251         'ref': fields.char('Ref.', size=32),
252         'statement_id': fields.many2one('account.bank.statement', 'Statement', help="The bank statement used for bank reconciliation", select=1),
253         'reconcile_id': fields.many2one('account.move.reconcile', 'Reconcile', readonly=True, ondelete='set null', select=2),
254         'reconcile_partial_id': fields.many2one('account.move.reconcile', 'Partial Reconcile', readonly=True, ondelete='set null', select=2),
255         'amount_currency': fields.float('Amount Currency', help="The amount expressed in an optionnal other currency if it is a multi-currency entry."),
256         'currency_id': fields.many2one('res.currency', 'Currency', help="The optionnal other currency if it is a multi-currency entry."),
257
258         'period_id': fields.many2one('account.period', 'Period', required=True, select=2),
259         'journal_id': fields.many2one('account.journal', 'Journal', required=True, select=1),
260         'blocked': fields.boolean('Litigation', help="You can check this box to mark the entry line as a litigation with the associated partner"),
261
262         'partner_id': fields.many2one('res.partner', 'Partner Ref.'),
263         'date_maturity': fields.date('Maturity date', help="This field is used for payable and receivable entries. You can put the limit date for the payment of this entry line."),
264         'date': fields.date('Effective date', required=True),
265         'date_created': fields.date('Creation date'),
266         'analytic_lines': fields.one2many('account.analytic.line', 'move_id', 'Analytic lines'),
267         'centralisation': fields.selection([('normal','Normal'),('credit','Credit Centralisation'),('debit','Debit Centralisation')], 'Centralisation', size=6),
268         'balance': fields.function(_balance, method=True, string='Balance'),
269         'active': fields.boolean('Active'),
270         'state': fields.selection([('draft','Draft'), ('valid','Valid')], 'Status', readonly=True),
271         'tax_code_id': fields.many2one('account.tax.code', 'Tax Account'),
272         'tax_amount': fields.float('Tax/Base Amount', digits=(16,2), select=True),
273         'invoice': fields.function(_invoice, method=True, string='Invoice',
274             type='many2one', relation='account.invoice', fnct_search=_invoice_search),
275         'account_tax_id':fields.many2one('account.tax', 'Tax'),
276         'analytic_account_id' : fields.many2one('account.analytic.account', 'Analytic Account'),
277 #TODO: remove this
278         'amount_taxed':fields.float("Taxed Amount",digits=(16,2)),
279     }
280
281     def _get_date(self, cr, uid, context):
282         period_obj = self.pool.get('account.period')
283         dt = time.strftime('%Y-%m-%d')
284         if ('journal_id' in context) and ('period_id' in context):
285             cr.execute('select date from account_move_line ' \
286                     'where journal_id=%d and period_id=%d ' \
287                     'order by id desc limit 1',
288                     (context['journal_id'], context['period_id']))
289             res = cr.fetchone()
290             if res:
291                 dt = res[0]
292             else:
293                 period = period_obj.browse(cr, uid, context['period_id'],
294                         context=context)
295                 dt = period.date_start
296         return dt
297     _defaults = {
298         'blocked': lambda *a: False,
299         'active': lambda *a: True,
300         'centralisation': lambda *a: 'normal',
301         'date': _get_date,
302         'date_created': lambda *a: time.strftime('%Y-%m-%d'),
303         'state': lambda *a: 'draft',
304         'journal_id': lambda self, cr, uid, c: c.get('journal_id', False),
305         'period_id': lambda self, cr, uid, c: c.get('period_id', False),
306     }
307     _order = "date desc,id desc"
308     _sql_constraints = [
309         ('credit_debit1', 'CHECK (credit*debit=0)',  'Wrong credit or debit value in accounting entry !'),
310         ('credit_debit2', 'CHECK (credit+debit>=0)', 'Wrong credit or debit value in accounting entry !'),
311     ]
312
313     def _auto_init(self, cr, context={}):
314         super(account_move_line, self)._auto_init(cr, context)
315         cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = \'account_move_line_journal_id_period_id_index\'')
316         if not cr.fetchone():
317             cr.execute('CREATE INDEX account_move_line_journal_id_period_id_index ON account_move_line (journal_id, period_id)')
318             cr.commit()
319
320     def _check_no_view(self, cr, uid, ids):
321         lines = self.browse(cr, uid, ids)
322         for l in lines:
323             if l.account_id.type == 'view':
324                 return False
325         return True
326
327     def _check_no_closed(self, cr, uid, ids):
328         lines = self.browse(cr, uid, ids)
329         for l in lines:
330             if l.account_id.type == 'closed':
331                 return False
332         return True
333
334     _constraints = [
335         (_check_no_view, 'You can not create move line on view account.', ['account_id']),
336         (_check_no_closed, 'You can not create move line on closed account.', ['account_id']),
337     ]
338
339     #TODO: ONCHANGE_ACCOUNT_ID: set account_tax_id
340
341     def onchange_partner_id(self, cr, uid, ids, move_id, partner_id, account_id=None, debit=0, credit=0, journal=False):
342         if (not partner_id) or account_id:
343             return {}
344         part = self.pool.get('res.partner').browse(cr, uid, partner_id)
345         id1 = part.property_account_payable.id
346         id2 =  part.property_account_receivable.id
347         val = {}
348         if journal:
349             jt = self.pool.get('account.journal').browse(cr, uid, journal).type
350             if jt=='sale':
351                 val['account_id'] =  id2
352             elif jt=='purchase':
353                 val['account_id'] =  id1
354         # Compute Maturity Date in val !
355         return {'value':val}
356
357     #
358     # type: the type if reconciliation (no logic behind this field, for info)
359     #
360     # writeoff; entry generated for the difference between the lines
361     #
362
363     def reconcile_partial(self, cr, uid, ids, type='auto', context={}):
364         merges = []
365         unmerge = []
366         total = 0.0
367         merges_rec = []
368         for line in self.browse(cr, uid, ids, context):
369             if line.reconcile_id:
370                 raise _('Already Reconciled')
371             if line.reconcile_partial_id:
372                 for line2 in line.reconcile_partial_id.line_partial_ids:
373                     if not line2.reconcile_id:
374                         merges.append(line2.id)
375                         total += (line2.debit or 0.0) - (line2.credit or 0.0)
376                 merges_rec.append(line.reconcile_partial_id.id)
377             else:
378                 unmerge.append(line.id)
379                 total += (line.debit or 0.0) - (line.credit or 0.0)
380         if not total:
381             res = self.reconcile(cr, uid, merges+unmerge, context=context)
382             return res
383         r_id = self.pool.get('account.move.reconcile').create(cr, uid, {
384             'type': type,
385             'line_partial_ids': map(lambda x: (4,x,False), merges+unmerge)
386         })
387         self.pool.get('account.move.reconcile').reconcile_partial_check(cr, uid, [r_id] + merges_rec, context=context)
388         return True
389
390     def reconcile(self, cr, uid, ids, type='auto', writeoff_acc_id=False, writeoff_period_id=False, writeoff_journal_id=False, context={}):
391         id_set = ','.join(map(str, ids))
392         lines = self.browse(cr, uid, ids, context=context)
393         unrec_lines = filter(lambda x: not x['reconcile_id'], lines)
394         credit = debit = 0.0
395         currency = 0.0
396         account_id = False
397         partner_id = False
398         for line in unrec_lines:
399             if line.state <> 'valid':
400                 raise osv.except_osv(_('Error'),
401                         _('Entry "%s" is not valid !') % line.name)
402             credit += line['credit']
403             debit += line['debit']
404             currency += line['amount_currency'] or 0.0
405             account_id = line['account_id']['id']
406             partner_id = (line['partner_id'] and line['partner_id']['id']) or False
407         writeoff = debit - credit
408         # Ifdate_p in context => take this date
409         if context.has_key('date_p') and context['date_p']:
410             date=context['date_p']
411         else:
412             date = time.strftime('%Y-%m-%d')
413
414         cr.execute('SELECT account_id, reconcile_id \
415                 FROM account_move_line \
416                 WHERE id IN ('+id_set+') \
417                 GROUP BY account_id,reconcile_id')
418         r = cr.fetchall()
419 #TODO: move this check to a constraint in the account_move_reconcile object
420         if len(r) != 1:
421             raise osv.except_osv(_('Error'), _('Entries are not of the same account or already reconciled ! '))
422         account = self.pool.get('account.account').browse(cr, uid, account_id, context=context)
423         if not account.reconcile:
424             raise osv.except_osv(_('Error'), _('The account is not defined to be reconcile !'))
425         if r[0][1] != None:
426             raise osv.except_osv(_('Error'), _('Some entries are already reconciled !'))
427
428         if (not self.pool.get('res.currency').is_zero(cr, uid, account.company_id.currency_id, writeoff)) or \
429            (account.currency_id and (not self.pool.get('res.currency').is_zero(cr, uid, account.currency_id, currency))):
430             if not writeoff_acc_id:
431                 raise osv.except_osv(_('Warning'), _('You have to provide an account for the write off entry !'))
432             if writeoff > 0:
433                 debit = writeoff
434                 credit = 0.0
435                 self_credit = writeoff
436                 self_debit = 0.0
437             else:
438                 debit = 0.0
439                 credit = -writeoff
440                 self_credit = 0.0
441                 self_debit = -writeoff
442
443             # If comment exist in context, take it
444             if context['comment']:
445                 libelle=context['comment']
446             else:
447                 libelle='Write-Off'
448
449             writeoff_lines = [
450                 (0, 0, {
451                     'name':libelle,
452                     'debit':self_debit,
453                     'credit':self_credit,
454                     'account_id':account_id,
455                     'date':date,
456                     'partner_id':partner_id,
457                     'currency_id': account.currency_id.id or False,
458                     'amount_currency': account.currency_id.id and -currency or 0.0
459                 }),
460                 (0, 0, {
461                     'name':libelle,
462                     'debit':debit,
463                     'credit':credit,
464                     'account_id':writeoff_acc_id,
465                     'date':date,
466                     'partner_id':partner_id
467                 })
468             ]
469
470             name = 'Write-Off'
471             if writeoff_journal_id:
472                 journal = self.pool.get('account.journal').browse(cr, uid, writeoff_journal_id)
473                 if journal.sequence_id:
474                     name = self.pool.get('ir.sequence').get_id(cr, uid, journal.sequence_id.id)
475
476             writeoff_move_id = self.pool.get('account.move').create(cr, uid, {
477                 'name': name,
478                 'period_id': writeoff_period_id,
479                 'journal_id': writeoff_journal_id,
480
481                 'state': 'draft',
482                 'line_id': writeoff_lines
483             })
484
485             writeoff_line_ids = self.search(cr, uid, [('move_id', '=', writeoff_move_id), ('account_id', '=', account_id)])
486             ids += writeoff_line_ids
487
488         r_id = self.pool.get('account.move.reconcile').create(cr, uid, {
489             #'name': date,
490             'type': type,
491             'line_id': map(lambda x: (4,x,False), ids),
492             'line_partial_ids': map(lambda x: (3,x,False), ids)
493         })
494         # the id of the move.reconcile is written in the move.line (self) by the create method above
495         # because of the way the line_id are defined: (4, x, False)
496         wf_service = netsvc.LocalService("workflow")
497         for id in ids:
498             wf_service.trg_trigger(uid, 'account.move.line', id, cr)
499         return r_id
500
501     def view_header_get(self, cr, user, view_id, view_type, context):
502         if context.get('account_id', False):
503             cr.execute('select code from account_account where id=%d', (context['account_id'],))
504             res = cr.fetchone()
505             res = _('Entries: ')+ (res[0] or '')
506             return res
507         if (not context.get('journal_id', False)) or (not context.get('period_id', False)):
508             return False
509         cr.execute('select code from account_journal where id=%d', (context['journal_id'],))
510         j = cr.fetchone()[0] or ''
511         cr.execute('select code from account_period where id=%d', (context['period_id'],))
512         p = cr.fetchone()[0] or ''
513         if j or p:
514             return j+(p and (':'+p) or '')
515         return False
516
517     def fields_view_get(self, cr, uid, view_id=None, view_type='form', context={}, toolbar=False):
518         result = super(osv.osv, self).fields_view_get(cr, uid, view_id,view_type,context)
519         if view_type=='tree' and 'journal_id' in context:
520             title = self.view_header_get(cr, uid, view_id, view_type, context)
521             journal = self.pool.get('account.journal').browse(cr, uid, context['journal_id'])
522
523             # if the journal view has a state field, color lines depending on
524             # its value
525             state = ''
526             for field in journal.view_id.columns_id:
527                 if field.field=='state':
528                     state = ' colors="red:state==\'draft\'"'
529
530             #xml = '''<?xml version="1.0"?>\n<tree string="%s" editable="top" refresh="5"%s>\n\t''' % (title, state)
531             xml = '''<?xml version="1.0"?>\n<tree string="%s" editable="top" refresh="5" on_write="_on_create_write"%s>\n\t''' % (title, state)
532             fields = []
533
534             widths = {
535                 'ref': 50,
536                 'statement_id': 50,
537                 'state': 60,
538                 'tax_code_id': 50,
539                 'move_id': 40,
540             }
541             for field in journal.view_id.columns_id:
542                 fields.append(field.field)
543                 attrs = []
544                 if field.field=='debit':
545                     attrs.append('sum="Total debit"')
546                 elif field.field=='credit':
547                     attrs.append('sum="Total credit"')
548                 elif field.field=='account_id' and journal.id:
549                     attrs.append('domain="[(\'journal_id\', \'=\', '+str(journal.id)+'),(\'type\',\'&lt;&gt;\',\'view\'), (\'type\',\'&lt;&gt;\',\'closed\')]"')
550                 if field.readonly:
551                     attrs.append('readonly="1"')
552                 if field.required:
553                     attrs.append('required="1"')
554                 else:
555                     attrs.append('required="0"')
556                 if field.field == 'partner_id':
557                     attrs.append('on_change="onchange_partner_id(move_id,partner_id,account_id,debit,credit,((\'journal_id\' in context) and context[\'journal_id\']) or {})"')
558                 if field.field in widths:
559                     attrs.append('width="'+str(widths[field.field])+'"')
560                 xml += '''<field name="%s" %s/>\n''' % (field.field,' '.join(attrs))
561
562             xml += '''</tree>'''
563             result['arch'] = xml
564             result['fields'] = self.fields_get(cr, uid, fields, context)
565         return result
566
567     def unlink(self, cr, uid, ids, context={}, check=True):
568         self._update_check(cr, uid, ids, context)
569         result = False
570         for line in self.browse(cr, uid, ids, context):
571             context['journal_id']=line.journal_id.id
572             context['period_id']=line.period_id.id
573             result = super(account_move_line, self).unlink(cr, uid, [line.id], context=context)
574             if check:
575                 self.pool.get('account.move').validate(cr, uid, [line.move_id.id], context=context)
576         return result
577
578     def write(self, cr, uid, ids, vals, context=None, check=True, update_check=True):
579         if not context:
580             context={}
581         raise_ex=False
582
583         if ('debit' in vals and 'credit' in vals)  and not vals['debit'] and not vals['credit']:
584             raise_ex=True
585         if ('debit' in vals and 'credit' not in vals) and  not vals['debit']:
586             raise_ex=True
587         if ('credit' in vals and 'debit' not in vals) and  not vals['credit']:
588             raise_ex=True
589
590         if raise_ex:
591             raise osv.except_osv(_('Wrong Accounting Entry!'), _('Both Credit and Debit cannot be zero!'))
592
593         if ('account_id' in vals) and not account_obj.read(cr, uid, vals['account_id'], ['active'])['active']:
594             raise osv.except_osv(_('Bad account!'), _('You can not use an inactive account!'))
595         if update_check:
596             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):
597                 self._update_check(cr, uid, ids, context)
598         result = super(osv.osv, self).write(cr, uid, ids, vals, context)
599         if check:
600             done = []
601             for line in self.browse(cr, uid, ids):
602                 if line.move_id.id not in done:
603                     done.append(line.move_id.id)
604                     self.pool.get('account.move').validate(cr, uid, [line.move_id.id], context)
605         return result
606
607     def _update_journal_check(self, cr, uid, journal_id, period_id, context={}):
608         cr.execute('select state from account_journal_period where journal_id=%d and period_id=%d', (journal_id, period_id))
609         result = cr.fetchall()
610         for (state,) in result:
611             if state=='done':
612                 raise osv.except_osv(_('Error !'), _('You can not add/modify entries in a closed journal.'))
613         if not result:
614             journal = self.pool.get('account.journal').browse(cr, uid, journal_id, context)
615             period = self.pool.get('account.period').browse(cr, uid, period_id, context)
616             self.pool.get('account.journal.period').create(cr, uid, {
617                 'name': (journal.code or journal.name)+':'+(period.name or ''),
618                 'journal_id': journal.id,
619                 'period_id': period.id
620             })
621         return True
622
623     def _update_check(self, cr, uid, ids, context={}):
624         done = {}
625         for line in self.browse(cr, uid, ids, context):
626             if line.move_id.state<>'draft':
627                 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 !'))
628             if line.reconcile_id:
629                 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 !'))
630             t = (line.journal_id.id, line.period_id.id)
631             if t not in done:
632                 self._update_journal_check(cr, uid, line.journal_id.id, line.period_id.id, context)
633                 done[t] = True
634         return True
635
636     def create(self, cr, uid, vals, context=None, check=True):
637         if not context:
638             context={}
639
640         account_obj = self.pool.get('account.account')
641         tax_obj=self.pool.get('account.tax')
642
643         if ('account_id' in vals) and not account_obj.read(cr, uid, vals['account_id'], ['active'])['active']:
644             raise osv.except_osv(_('Bad account!'), _('You can not use an inactive account!'))
645         if 'journal_id' in vals and 'journal_id' not in context:
646             context['journal_id'] = vals['journal_id']
647         if 'period_id' in vals and 'period_id' not in context:
648             context['period_id'] = vals['period_id']
649         if 'journal_id' not in context and 'move_id' in vals:
650             m = self.pool.get('account.move').browse(cr, uid, vals['move_id'])
651             context['journal_id'] = m.journal_id.id
652             context['period_id'] = m.period_id.id
653
654         self._update_journal_check(cr, uid, context['journal_id'], context['period_id'], context)
655
656         move_id = vals.get('move_id', False)
657         journal = self.pool.get('account.journal').browse(cr, uid, context['journal_id'])
658         if not move_id:
659             if journal.centralisation:
660                 # use the first move ever created for this journal and period
661                 cr.execute('select id, state, name from account_move where journal_id=%d and period_id=%d order by id limit 1', (context['journal_id'],context['period_id']))
662                 res = cr.fetchone()
663                 if res:
664                     if res[1] != 'draft':
665                         raise osv.except_osv(_('UserError'),
666                                 _('The account move (%s) for centralisation ' \
667                                         'has been confirmed!') % res[2])
668                     vals['move_id'] = res[0]
669
670             if not vals.get('move_id', False):
671                 if journal.sequence_id:
672                     name = self.pool.get('ir.sequence').get_id(cr, uid, journal.sequence_id.id)
673                     v = {
674                         'name': name,
675                         'period_id': context['period_id'],
676                         'journal_id': context['journal_id']
677                     }
678                     move_id = self.pool.get('account.move').create(cr, uid, v, context)
679                     vals['move_id'] = move_id
680                 else:
681                     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.'))
682
683         ok = not (journal.type_control_ids or journal.account_control_ids)
684         if ('account_id' in vals):
685             account = account_obj.browse(cr, uid, vals['account_id'])
686             if journal.type_control_ids:
687                 type = account.type
688                 for t in journal.type_control_ids:
689                     if type==t.code:
690                         ok = True
691                         break
692             if journal.account_control_ids and not ok:
693                 for a in journal.account_control_ids:
694                     if a.id==vals['account_id']:
695                         ok = True
696                         break
697             if (account.currency_id) and 'amount_currency' not in vals:
698                 vals['currency_id'] = account.currency_id.id
699                 cur_obj = self.pool.get('res.currency')
700                 ctx = {}
701                 if 'date' in vals:
702                     ctx['date'] = vals['date']
703                 vals['amount_currency'] = cur_obj.compute(cr, uid, account.company_id.currency_id.id, account.currency_id.id, vals.get('debit', 0.0)-vals.get('credit', 0.0), context=ctx)
704         if not ok:
705             raise osv.except_osv(_('Bad account !'), _('You can not use this general account in this journal !'))
706
707         result = super(osv.osv, self).create(cr, uid, vals, context)
708         if 'analytic_account_id' in vals and vals['analytic_account_id']:
709             if journal.analytic_journal_id:
710                 vals['analytic_lines'] = [(0,0, {
711                         'name': vals['name'],
712                         'date': vals['date'],
713                         'account_id': vals['analytic_account_id'],
714                         'unit_amount': vals['quantity'],
715                         'amount': vals['debit'] or vals['credit'],
716                         'general_account_id': vals['account_id'],
717                         'journal_id': journal.analytic_journal_id.id,
718                         'ref': vals['ref'],
719                     })]
720
721         # CREATE Taxes
722         if 'account_tax_id' in vals and vals['account_tax_id']:
723             tax_id=tax_obj.browse(cr,uid,vals['account_tax_id'])
724             total = vals['credit'] or (-vals['debit'])
725             for tax in tax_obj.compute(cr,uid,[tax_id],total,1.00):
726                 self.write(cr, uid,[result], {
727                     'tax_code_id': tax['base_code_id'],
728                     'tax_amount': tax['base_sign'] * total
729                 })
730                 data = {
731                     'move_id': vals['move_id'],
732                     'journal_id': vals['journal_id'],
733                     'period_id': vals['period_id'],
734                     'name': vals['name']+' '+tax['name'],
735                     'date': vals['date'],
736                     'partner_id': vals.get('partner_id',False),
737                     'ref': vals.get('ref',False),
738                     'account_tax_id': False,
739                     'tax_code_id': tax['tax_code_id'],
740                     'tax_amount': tax['tax_sign'] * tax['amount'],
741                     'account_id': tax['account_paid_id'], # or collected ?
742                     'credit': tax['amount']>0 and tax['amount'] or 0.0,
743                     'debit': tax['amount']<0 and -tax['amount'] or 0.0,
744                 }
745                 self.create(cr, uid, data, context)
746         if check:
747             tmp = self.pool.get('account.move').validate(cr, uid, [vals['move_id']], context)
748             if journal.entry_posted and tmp:
749                 self.pool.get('account.move').write(cr,uid, [vals['move_id']],{'state':'posted'})
750         return result
751 account_move_line()
752
753
754 class account_bank_statement_reconcile(osv.osv):
755     _inherit = "account.bank.statement.reconcile"
756     _columns = {
757         'line_ids': fields.many2many('account.move.line', 'account_bank_statement_line_rel', 'statement_id', 'line_id', 'Entries'),
758     }
759 account_bank_statement_reconcile()
760
761 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
762