1 # -*- encoding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2008 Tiny SPRL (<http://tiny.be>). All Rights Reserved
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.
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.
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/>.
21 ##############################################################################
25 from osv import fields, osv
26 from tools.translate import _
29 from mx.DateTime import RelativeDateTime, now, DateTime, localtime
31 class account_move_line(osv.osv):
32 _name = "account.move.line"
33 _description = "Entry lines"
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'
41 fiscalyear_clause = '%s' % context['fiscalyear']
42 state=context.get('state',False)
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+"')"
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)
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)
54 def default_get(self, cr, uid, fields, context={}):
55 data = self._default_get(cr, uid, fields, context)
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)
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,
71 'general_account_id': obj_line.account_id.id,
72 'journal_id': obj_line.journal_id.analytic_journal_id.id,
76 new_id = self.pool.get('account.analytic.line').create(cr,uid,vals_lines)
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)
83 # Starts: Manual entry from account.move form
84 if context.get('lines',[]):
87 for i in context['lines']:
88 total_new +=(i[2]['debit'] or 0.00)- (i[2]['credit'] or 0.00)
91 if context['journal']:
92 journal_obj=self.pool.get('account.journal').browse(cr,uid,context['journal'])
93 if journal_obj.type == 'purchase':
95 account = journal_obj.default_credit_account_id
97 account = journal_obj.default_debit_account_id
100 account = journal_obj.default_credit_account_id
102 account = journal_obj.default_debit_account_id
103 data['account_id'] = account.id
105 data['debit'] = s>0 and s or 0.0
106 data['credit'] = s<0 and -s or 0.0
108 # Ends: Manual entry from account.move form
110 if not 'move_id' in fields: #we are not in manual entry
113 period_obj = self.pool.get('account.period')
114 tax_obj=self.pool.get('account.tax')
116 # Compute the current move
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 \
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'))
129 move_id = (res and res[0]) or False
134 data['move_id'] = move_id
136 cr.execute('select date \
140 journal_id=%d and period_id=%d and create_uid=%d \
142 (context['journal_id'], context['period_id'], uid))
145 data['date'] = res[0]
147 period = period_obj.browse(cr, uid, context['period_id'],
149 data['date'] = period.date_start
156 move = self.pool.get('account.move').browse(cr, uid, move_id, context)
159 for l in move.line_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)
165 data.setdefault('name', l.name)
168 if 'partner_id' in fields:
169 data['partner_id'] = partner_id
171 if move.journal_id.type == 'purchase':
173 account = move.journal_id.default_credit_account_id
175 account = move.journal_id.default_debit_account_id
178 account = move.journal_id.default_credit_account_id
180 account = move.journal_id.default_debit_account_id
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
188 data['debit'] = s>0 and s or 0.0
189 data['credit'] = s<0 and -s or 0.0
191 if account.currency_id:
192 data['currency_id'] = account.currency_id.id
196 v = self.pool.get('res.currency').compute(cr, uid,
197 account.company_id.currency_id.id,
199 s, account=acc, account_invert=True)
200 data['amount_currency'] = v
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)
207 def _balance(self, cr, uid, ids, prop, unknow_none, unknow_dict):
209 # TODO group the foreach in sql
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]
217 def _invoice(self, cursor, user, ids, name, arg, context=None):
218 invoice_obj = self.pool.get('account.invoice')
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]) + ')')
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])
239 def name_get(self, cr, uid, ids, context={}):
243 for line in self.browse(cr, uid, ids, context):
245 result.append((line.id, (line.name or '')+' ('+line.ref+')'))
247 result.append((line.id, line.name))
250 def _invoice_search(self, cursor, user, obj, name, args):
253 invoice_obj = self.pool.get('account.invoice')
257 fargs = args[i][0].split('.', 1)
259 args[i] = (frags[0], 'in', invoice_obj.search(cursor, user,
260 [(fargs[1], args[i][1], args[i][2])]))
263 if isinstance(args[i][2], basestring):
264 res_ids = invoice_obj.name_search(cursor, user, args[i][2], [],
266 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
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)')
276 qu1.append('(i.id %s %s)' % (x[1], '%d'))
280 qu1.append('(i.id in (%s))' % (','.join(['%d'] * len(x[2]))))
283 qu1.append(' (False)')
285 qu1 = ' AND' + ' AND'.join(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()
293 return [('id', '=', '0')]
294 return [('id', 'in', [x[0] for x in res])]
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),
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."),
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"),
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'),
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')
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']))
347 period = period_obj.browse(cr, uid, context['period_id'],
349 dt = period.date_start
351 def _get_currency(self, cr, uid, context={}):
352 if not context.get('journal_id', False):
354 cur = self.pool.get('account.journal').browse(cr, uid, context['journal_id']).currency
355 return cur and cur.id or False
358 'blocked': lambda *a: False,
359 'centralisation': lambda *a: 'normal',
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),
367 _order = "date desc,id desc"
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 !'),
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)')
380 def _check_no_view(self, cr, uid, ids):
381 lines = self.browse(cr, uid, ids)
383 if l.account_id.type == 'view':
387 def _check_no_closed(self, cr, uid, ids):
388 lines = self.browse(cr, uid, ids)
390 if l.account_id.type == 'closed':
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']),
399 #TODO: ONCHANGE_ACCOUNT_ID: set account_tax_id
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):
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
409 v = self.pool.get('res.currency').compute(cr, uid, currency_id,acc.company_id.currency_id.id, amount, account=acc)
411 'debit': v>0 and v or 0.0,
412 'credit': v<0 and -v or 0.0
416 def onchange_partner_id(self, cr, uid, ids, move_id, partner_id, account_id=None, debit=0, credit=0, date=False, journal=False):
418 val['date_maturity'] = False
423 date = now().strftime('%Y-%m-%d')
424 part = self.pool.get('res.partner').browse(cr, uid, partner_id)
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
434 id1 = part.property_account_payable.id
435 id2 = part.property_account_receivable.id
437 jt = self.pool.get('account.journal').browse(cr, uid, journal).type
439 val['account_id'] = id2
441 val['account_id'] = id1
445 # type: the type if reconciliation (no logic behind this field, for info)
447 # writeoff; entry generated for the difference between the lines
450 def reconcile_partial(self, cr, uid, ids, type='auto', context={}):
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)
465 unmerge.append(line.id)
466 total += (line.debit or 0.0) - (line.credit or 0.0)
468 res = self.reconcile(cr, uid, merges+unmerge, context=context)
470 r_id = self.pool.get('account.move.reconcile').create(cr, uid, {
472 'line_partial_ids': map(lambda x: (4,x,False), merges+unmerge)
474 self.pool.get('account.move.reconcile').reconcile_partial_check(cr, uid, [r_id] + merges_rec, context=context)
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)
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']
503 date = time.strftime('%Y-%m-%d')
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')
510 #TODO: move this check to a constraint in the account_move_reconcile object
512 raise osv.except_osv(_('Error'), _('Entries are not of the same account or already reconciled ! '))
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 !'))
519 raise osv.except_osv(_('Error'), _('Some entries are already reconciled !'))
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 !'))
528 self_credit = writeoff
534 self_debit = -writeoff
536 # If comment exist in context, take it
537 if 'comment' in context and context['comment']:
538 libelle=context['comment']
546 'credit':self_credit,
547 'account_id':account_id,
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
557 'account_id':writeoff_acc_id,
559 'partner_id':partner_id
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)
569 writeoff_move_id = self.pool.get('account.move').create(cr, uid, {
571 'period_id': writeoff_period_id,
572 'journal_id': writeoff_journal_id,
575 'line_id': writeoff_lines
578 writeoff_line_ids = self.search(cr, uid, [('move_id', '=', writeoff_move_id), ('account_id', '=', account_id)])
579 ids += writeoff_line_ids
581 r_id = self.pool.get('account.move.reconcile').create(cr, uid, {
584 'line_id': map(lambda x: (4,x,False), ids),
585 'line_partial_ids': map(lambda x: (3,x,False), ids)
587 wf_service = netsvc.LocalService("workflow")
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)
595 wf_service.trg_trigger(uid, 'account.move.line', id, cr)
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'],))
602 res = _('Entries: ')+ (res[0] or '')
604 if (not context.get('journal_id', False)) or (not context.get('period_id', 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 ''
611 return j+(p and (':'+p) or '')
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'])
620 # if the journal view has a state field, color lines depending on
623 for field in journal.view_id.columns_id:
624 if field.field=='state':
625 state = ' colors="red:state==\'draft\'"'
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)
638 for field in journal.view_id.columns_id:
639 fields.append(field.field)
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\',\'<>\',\'view\'), (\'type\',\'<>\',\'closed\')]"')
650 attrs.append('readonly="1"')
652 attrs.append('required="1"')
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))
665 result['fields'] = self.fields_get(cr, uid, fields, context)
668 def unlink(self, cr, uid, ids, context={}, check=True):
669 self._update_check(cr, uid, ids, context)
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)
676 self.pool.get('account.move').validate(cr, uid, [line.move_id.id], context=context)
679 def write(self, cr, uid, ids, vals, context=None, check=True, update_check=True):
684 if ('debit' in vals and 'credit' in vals) and not vals['debit'] and not vals['credit']:
686 if ('debit' in vals and 'credit' not in vals) and not vals['debit']:
688 if ('credit' in vals and 'debit' not in vals) and not vals['credit']:
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!'))
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)
700 result = super(account_move_line, self).write(cr, uid, ids, vals, context)
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)
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:
715 raise osv.except_osv(_('Error !'), _('You can not add/modify entries in a closed journal.'))
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
726 def _update_check(self, cr, uid, ids, context={}):
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)
735 self._update_journal_check(cr, uid, line.journal_id.id, line.period_id.id, context)
739 def create(self, cr, uid, vals, context=None, check=True):
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
755 self._update_journal_check(cr, uid, context['journal_id'], context['period_id'], context)
757 move_id = vals.get('move_id', False)
758 journal = self.pool.get('account.journal').browse(cr, uid, context['journal_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']))
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]
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)
776 'period_id': context['period_id'],
777 'journal_id': context['journal_id']
779 move_id = self.pool.get('account.move').create(cr, uid, v, context)
780 vals['move_id'] = move_id
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.'))
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:
793 if journal.account_control_ids and not ok:
794 for a in journal.account_control_ids:
795 if a.id==vals['account_id']:
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')
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),
808 raise osv.except_osv(_('Bad account !'), _('You can not use this general account in this journal !'))
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,
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)
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'
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'
844 for tax in tax_obj.compute(cr,uid,[tax_id],total,1.00):
845 #create the base movement
849 self.write(cr, uid,[result], {
850 'tax_code_id': tax[base_code],
851 'tax_amount': tax[base_sign] * abs(total)
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'],
869 if data['tax_code_id']:
870 self.create(cr, uid, data, context)
872 #create the VAT movement
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,
888 if data['tax_code_id']:
889 self.create(cr, uid, data, context)
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'})
899 class account_bank_statement_reconcile(osv.osv):
900 _inherit = "account.bank.statement.reconcile"
902 'line_ids': fields.many2many('account.move.line', 'account_bank_statement_line_rel', 'statement_id', 'line_id', 'Entries'),
904 account_bank_statement_reconcile()
906 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: