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