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