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 _default_get(self, cr, uid, fields, context={}):
62 # Compute simple values
63 data = super(account_move_line, self).default_get(cr, uid, fields, context)
65 # Starts: Manual entry from account.move form
66 if context.get('lines',[]):
69 for i in context['lines']:
70 total_new +=(i[2]['debit'] or 0.00)- (i[2]['credit'] or 0.00)
73 if context['journal']:
74 journal_obj=self.pool.get('account.journal').browse(cr,uid,context['journal'])
75 if journal_obj.type == 'purchase':
77 account = journal_obj.default_credit_account_id
79 account = journal_obj.default_debit_account_id
82 account = journal_obj.default_credit_account_id
84 account = journal_obj.default_debit_account_id
85 data['account_id'] = account.id
87 data['debit'] = s>0 and s or 0.0
88 data['credit'] = s<0 and -s or 0.0
90 # Ends: Manual entry from account.move form
92 if not 'move_id' in fields: #we are not in manual entry
95 period_obj = self.pool.get('account.period')
96 tax_obj=self.pool.get('account.tax')
98 # Compute the current move
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 \
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'))
111 move_id = (res and res[0]) or False
116 data['move_id'] = move_id
118 cr.execute('select date \
122 journal_id=%d and period_id=%d and create_uid=%d \
124 (context['journal_id'], context['period_id'], uid))
127 data['date'] = res[0]
129 period = period_obj.browse(cr, uid, context['period_id'],
131 data['date'] = period.date_start
138 move = self.pool.get('account.move').browse(cr, uid, move_id, context)
141 for l in move.line_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)
147 data.setdefault('name', l.name)
150 if 'partner_id' in fields:
151 data['partner_id'] = partner_id
153 if move.journal_id.type == 'purchase':
155 account = move.journal_id.default_credit_account_id
157 account = move.journal_id.default_debit_account_id
160 account = move.journal_id.default_credit_account_id
162 account = move.journal_id.default_debit_account_id
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
170 data['debit'] = s>0 and s or 0.0
171 data['credit'] = s<0 and -s or 0.0
173 if account.currency_id:
174 data['currency_id'] = account.currency_id.id
178 v = self.pool.get('res.currency').compute(cr, uid,
179 account.company_id.currency_id.id,
181 s, account=acc, account_invert=True)
182 data['amount_currency'] = v
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)
189 def _balance(self, cr, uid, ids, prop, unknow_none, unknow_dict):
191 # TODO group the foreach in sql
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]
199 def _invoice(self, cursor, user, ids, name, arg, context=None):
200 invoice_obj = self.pool.get('account.invoice')
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]) + ')')
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])
221 def name_get(self, cr, uid, ids, context={}):
225 for line in self.browse(cr, uid, ids, context):
227 result.append((line.id, (line.name or '')+' ('+line.ref+')'))
229 result.append((line.id, line.name))
232 def _invoice_search(self, cursor, user, obj, name, args):
235 invoice_obj = self.pool.get('account.invoice')
239 fargs = args[i][0].split('.', 1)
241 args[i] = (frags[0], 'in', invoice_obj.search(cursor, user,
242 [(fargs[1], args[i][1], args[i][2])]))
245 if isinstance(args[i][2], basestring):
246 res_ids = invoice_obj.name_search(cursor, user, args[i][2], [],
248 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
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)')
258 qu1.append('(i.id %s %s)' % (x[1], '%d'))
262 qu1.append('(i.id in (%s))' % (','.join(['%d'] * len(x[2]))))
265 qu1.append(' (False)')
267 qu1 = ' AND' + ' AND'.join(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()
275 return [('id', '=', '0')]
276 return [('id', 'in', [x[0] for x in res])]
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),
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."),
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"),
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'),
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')
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']))
329 period = period_obj.browse(cr, uid, context['period_id'],
331 dt = period.date_start
333 def _get_currency(self, cr, uid, context={}):
334 if not context.get('journal_id', False):
336 cur = self.pool.get('account.journal').browse(cr, uid, context['journal_id']).currency
337 return cur and cur.id or False
340 'blocked': lambda *a: False,
341 'centralisation': lambda *a: 'normal',
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),
349 _order = "date desc,id desc"
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 !'),
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)')
362 def _check_no_view(self, cr, uid, ids):
363 lines = self.browse(cr, uid, ids)
365 if l.account_id.type == 'view':
369 def _check_no_closed(self, cr, uid, ids):
370 lines = self.browse(cr, uid, ids)
372 if l.account_id.type == 'closed':
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']),
381 #TODO: ONCHANGE_ACCOUNT_ID: set account_tax_id
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):
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
391 v = self.pool.get('res.currency').compute(cr, uid, currency_id,acc.company_id.currency_id.id, amount, account=acc)
393 'debit': v>0 and v or 0.0,
394 'credit': v<0 and -v or 0.0
398 def onchange_partner_id(self, cr, uid, ids, move_id, partner_id, account_id=None, debit=0, credit=0, date=False, journal=False):
400 val['date_maturity'] = False
405 date = now().strftime('%Y-%m-%d')
406 part = self.pool.get('res.partner').browse(cr, uid, partner_id)
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
416 id1 = part.property_account_payable.id
417 id2 = part.property_account_receivable.id
419 jt = self.pool.get('account.journal').browse(cr, uid, journal).type
421 val['account_id'] = id2
423 val['account_id'] = id1
427 # type: the type if reconciliation (no logic behind this field, for info)
429 # writeoff; entry generated for the difference between the lines
432 def reconcile_partial(self, cr, uid, ids, type='auto', context={}):
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)
447 unmerge.append(line.id)
448 total += (line.debit or 0.0) - (line.credit or 0.0)
450 res = self.reconcile(cr, uid, merges+unmerge, context=context)
452 r_id = self.pool.get('account.move.reconcile').create(cr, uid, {
454 'line_partial_ids': map(lambda x: (4,x,False), merges+unmerge)
456 self.pool.get('account.move.reconcile').reconcile_partial_check(cr, uid, [r_id] + merges_rec, context=context)
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)
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']
485 date = time.strftime('%Y-%m-%d')
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')
492 #TODO: move this check to a constraint in the account_move_reconcile object
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 !'))
499 raise osv.except_osv(_('Error'), _('Some entries are already reconciled !'))
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 !'))
508 self_credit = writeoff
514 self_debit = -writeoff
516 # If comment exist in context, take it
517 if 'comment' in context and context['comment']:
518 libelle=context['comment']
526 'credit':self_credit,
527 'account_id':account_id,
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
537 'account_id':writeoff_acc_id,
539 'partner_id':partner_id
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)
549 writeoff_move_id = self.pool.get('account.move').create(cr, uid, {
551 'period_id': writeoff_period_id,
552 'journal_id': writeoff_journal_id,
555 'line_id': writeoff_lines
558 writeoff_line_ids = self.search(cr, uid, [('move_id', '=', writeoff_move_id), ('account_id', '=', account_id)])
559 ids += writeoff_line_ids
561 r_id = self.pool.get('account.move.reconcile').create(cr, uid, {
564 'line_id': map(lambda x: (4,x,False), ids),
565 'line_partial_ids': map(lambda x: (3,x,False), ids)
567 wf_service = netsvc.LocalService("workflow")
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)
575 wf_service.trg_trigger(uid, 'account.move.line', id, cr)
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'],))
582 res = _('Entries: ')+ (res[0] or '')
584 if (not context.get('journal_id', False)) or (not context.get('period_id', 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 ''
591 return j+(p and (':'+p) or '')
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'])
600 # if the journal view has a state field, color lines depending on
603 for field in journal.view_id.columns_id:
604 if field.field=='state':
605 state = ' colors="red:state==\'draft\'"'
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)
618 for field in journal.view_id.columns_id:
619 fields.append(field.field)
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\',\'<>\',\'view\'), (\'type\',\'<>\',\'closed\')]"')
628 attrs.append('readonly="1"')
630 attrs.append('required="1"')
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))
643 result['fields'] = self.fields_get(cr, uid, fields, context)
646 def unlink(self, cr, uid, ids, context={}, check=True):
647 self._update_check(cr, uid, ids, context)
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)
654 self.pool.get('account.move').validate(cr, uid, [line.move_id.id], context=context)
657 def write(self, cr, uid, ids, vals, context=None, check=True, update_check=True):
662 if ('debit' in vals and 'credit' in vals) and not vals['debit'] and not vals['credit']:
664 if ('debit' in vals and 'credit' not in vals) and not vals['debit']:
666 if ('credit' in vals and 'debit' not in vals) and not vals['credit']:
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!'))
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)
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)
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:
691 raise osv.except_osv(_('Error !'), _('You can not add/modify entries in a closed journal.'))
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
702 def _update_check(self, cr, uid, ids, context={}):
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)
711 self._update_journal_check(cr, uid, line.journal_id.id, line.period_id.id, context)
715 def create(self, cr, uid, vals, context=None, check=True):
718 account_obj = self.pool.get('account.account')
719 tax_obj=self.pool.get('account.tax')
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
732 self._update_journal_check(cr, uid, context['journal_id'], context['period_id'], context)
734 move_id = vals.get('move_id', False)
735 journal = self.pool.get('account.journal').browse(cr, uid, context['journal_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']))
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]
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)
753 'period_id': context['period_id'],
754 'journal_id': context['journal_id']
756 move_id = self.pool.get('account.move').create(cr, uid, v, context)
757 vals['move_id'] = move_id
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.'))
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:
770 if journal.account_control_ids and not ok:
771 for a in journal.account_control_ids:
772 if a.id==vals['account_id']:
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')
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),
785 raise osv.except_osv(_('Bad account !'), _('You can not use this general account in this journal !'))
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,
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
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,
825 self.create(cr, uid, data, context)
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'})
834 class account_bank_statement_reconcile(osv.osv):
835 _inherit = "account.bank.statement.reconcile"
837 'line_ids': fields.many2many('account.move.line', 'account_bank_statement_line_rel', 'statement_id', 'line_id', 'Entries'),
839 account_bank_statement_reconcile()
841 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: