1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 ##############################################################################
22 from datetime import datetime
25 from osv import fields, osv
26 from tools.translate import _
27 import decimal_precision as dp
30 class account_move_line(osv.osv):
31 _name = "account.move.line"
32 _description = "Journal Items"
34 def _query_get(self, cr, uid, obj='l', context={}):
35 fiscalyear_obj = self.pool.get('account.fiscalyear')
36 fiscalperiod_obj = self.pool.get('account.period')
39 initial_bal = context.get('initial_bal', False)
41 if context.get('company_id', False):
42 company_clause = " AND " +obj+".company_id = %s" % context.get('company_id', False)
43 if not context.get('fiscalyear', False):
44 fiscalyear_ids = fiscalyear_obj.search(cr, uid, [('state', '=', 'draft')])
47 fiscalyear_date_start = fiscalyear_obj.read(cr, uid, context['fiscalyear'], ['date_start'])['date_start']
48 fiscalyear_ids = fiscalyear_obj.search(cr, uid, [('date_stop', '<', fiscalyear_date_start), ('state', '=', 'draft')], context=context)
50 fiscalyear_ids = [context['fiscalyear']]
52 fiscalyear_clause = (','.join([str(x) for x in fiscalyear_ids])) or '0'
53 state = context.get('state',False)
56 where_move_lines_by_date = ''
58 if context.get('date_from', False) and context.get('date_to', False):
60 where_move_lines_by_date = " AND " +obj+".move_id in ( select id from account_move where date < '"+context['date_from']+"')"
62 where_move_lines_by_date = " AND " +obj+".move_id in ( select id from account_move where date >= '" +context['date_from']+"' AND date <= '"+context['date_to']+"')"
65 if state.lower() not in ['all']:
66 where_move_state= " AND "+obj+".move_id in (select id from account_move where account_move.state = '"+state+"')"
68 if context.get('period_from', False) and context.get('periof_from', False) and not context.get('periods', False):
70 period_company_id = period_obj.browse(cr, uid, data['form']['period_from'], context=context).company_id.id
71 first_period = self.pool.get('account.period').search(cr, uid, [('company_id', '=', period_company_id)], order='date_start', limit=1)[0]
72 context['periods'] = period_obj.build_ctx_periods(cr, uid, first_period, data['form']['period_from'])
74 context['periods'] = period_obj.build_ctx_periods(cr, uid, data['form']['period_from'], data['form']['period_to'])
76 if context.get('periods', False):
77 ids = ','.join([str(x) for x in context['periods']])
78 query = obj+".state<>'draft' AND "+obj+".period_id in (SELECT id from account_period WHERE fiscalyear_id in (%s) AND id in (%s)) %s %s" % (fiscalyear_clause, ids, where_move_state, where_move_lines_by_date)
80 query = obj+".state<>'draft' AND "+obj+".period_id in (SELECT id from account_period WHERE fiscalyear_id in (%s) %s %s)" % (fiscalyear_clause,where_move_state,where_move_lines_by_date)
82 if context.get('journal_ids', False):
83 query += ' AND '+obj+'.journal_id in (%s)' % ','.join(map(str, context['journal_ids']))
85 if context.get('chart_account_id', False):
86 child_ids = self.pool.get('account.account')._get_children_and_consol(cr, uid, [context['chart_account_id']], context=context)
87 query += ' AND '+obj+'.account_id in (%s)' % ','.join(map(str, child_ids))
89 query += company_clause
91 if context.get('period_manner','') == 'created':
92 #the query have to be build with no reference to periods but thanks to the creation date
93 if context.get('periods',False):
94 #if one or more period are given, use them
95 fiscalperiod_ids = fiscalperiod_obj.search(cr, uid, [('id','in',context['periods'])])
97 fiscalperiod_ids = self.pool.get('account.period').search(cr, uid, [('fiscalyear_id','in',fiscalyear_ids)])
99 #remove from the old query the clause related to the period selection
102 clause_list = query.split('AND')
103 ref_string = ' '+obj+'.period_id in'
104 for clause in clause_list:
105 if count != 1 and not clause.startswith(ref_string):
107 if not clause.startswith(ref_string):
111 #add to 'res' a new clause containing the creation date criterion
114 periods = self.pool.get('account.period').read(cr, uid, p_ids, ['date_start','date_stop'])
115 for period in periods:
118 #creation date criterion: the creation date of the move_line has to be
119 # between the date_start and the date_stop of the selected periods
120 res += "("+obj+".create_date between to_date('" + period['date_start'] + "','yyyy-mm-dd') and to_date('" + period['date_stop'] + "','yyyy-mm-dd'))"
127 def default_get(self, cr, uid, fields, context={}):
128 data = self._default_get(cr, uid, fields, context)
129 for f in data.keys():
134 def create_analytic_lines(self, cr, uid, ids, context={}):
135 for obj_line in self.browse(cr, uid, ids, context):
136 if obj_line.analytic_account_id:
137 if not obj_line.journal_id.analytic_journal_id:
138 raise osv.except_osv(_('No Analytic Journal !'),_("You have to define an analytic journal on the '%s' journal!") % (obj_line.journal_id.name,))
139 amt = (obj_line.credit or 0.0) - (obj_line.debit or 0.0)
141 'name': obj_line.name,
142 'date': obj_line.date,
143 'account_id': obj_line.analytic_account_id.id,
144 'unit_amount':obj_line.quantity,
145 'product_id': obj_line.product_id and obj_line.product_id.id or False,
146 'product_uom_id': obj_line.product_uom_id and obj_line.product_uom_id.id or False,
148 'general_account_id': obj_line.account_id.id,
149 'journal_id': obj_line.journal_id.analytic_journal_id.id,
151 'move_id':obj_line.id,
154 new_id = self.pool.get('account.analytic.line').create(cr,uid,vals_lines)
157 def _default_get_move_form_hook(self, cursor, user, data):
158 '''Called in the end of default_get method for manual entry in account_move form'''
159 if data.has_key('analytic_account_id'):
160 del(data['analytic_account_id'])
161 if data.has_key('account_tax_id'):
162 del(data['account_tax_id'])
165 def convert_to_period(self, cr, uid, context={}):
166 period_obj = self.pool.get('account.period')
168 #check if the period_id changed in the context from client side
169 if context.get('period_id', False):
170 period_id = context.get('period_id')
171 if type(period_id) == str:
172 ids = period_obj.search(cr, uid, [('name','ilike',period_id)])
179 def _default_get(self, cr, uid, fields, context={}):
181 if not context.get('journal_id', False) and context.get('search_default_journal_id', False):
182 context['journal_id'] = context.get('search_default_journal_id')
184 period_obj = self.pool.get('account.period')
186 context = self.convert_to_period(cr, uid, context)
188 # Compute simple values
189 data = super(account_move_line, self).default_get(cr, uid, fields, context)
190 # Starts: Manual entry from account.move form
191 if context.get('lines',[]):
194 for i in context['lines']:
196 total_new +=(i[2]['debit'] or 0.00)- (i[2]['credit'] or 0.00)
198 data[item]=i[2][item]
199 if context['journal']:
200 journal_obj=self.pool.get('account.journal').browse(cr, uid, context['journal'])
201 if journal_obj.type == 'purchase':
203 account = journal_obj.default_credit_account_id
205 account = journal_obj.default_debit_account_id
208 account = journal_obj.default_credit_account_id
210 account = journal_obj.default_debit_account_id
212 if account and ((not fields) or ('debit' in fields) or ('credit' in fields)) and 'partner_id' in data and (data['partner_id']):
213 part = self.pool.get('res.partner').browse(cr, uid, data['partner_id'])
214 account = self.pool.get('account.fiscal.position').map_account(cr, uid, part and part.property_account_position or False, account.id)
215 account = self.pool.get('account.account').browse(cr, uid, account)
216 data['account_id'] = account.id
219 data['debit'] = s>0 and s or 0.0
220 data['credit'] = s<0 and -s or 0.0
221 data = self._default_get_move_form_hook(cr, uid, data)
223 # Ends: Manual entry from account.move form
225 if not 'move_id' in fields: #we are not in manual entry
228 # Compute the current move
231 if context.get('journal_id', False) and context.get('period_id', False):
232 if 'move_id' in fields:
233 cr.execute('select move_id \
237 journal_id=%s and period_id=%s and create_uid=%s and state=%s \
238 order by id desc limit 1',
239 (context['journal_id'], context['period_id'], uid, 'draft'))
241 move_id = (res and res[0]) or False
246 data['move_id'] = move_id
249 cr.execute('select date \
253 journal_id=%s and period_id=%s and create_uid=%s \
255 (context['journal_id'], context['period_id'], uid))
258 data['date'] = res[0]
260 period = period_obj.browse(cr, uid, context['period_id'],
262 data['date'] = period.date_start
268 move = self.pool.get('account.move').browse(cr, uid, move_id, context)
270 data.setdefault('name', move.line_id[-1].name)
272 for l in move.line_id:
274 partner_id = partner_id or l.partner_id.id
275 ref_id = ref_id or l.ref
276 total += (l.debit or 0.0) - (l.credit or 0.0)
280 if 'partner_id' in fields:
281 data['partner_id'] = partner_id
283 if move.journal_id.type == 'purchase':
285 account = move.journal_id.default_credit_account_id
287 account = move.journal_id.default_debit_account_id
290 account = move.journal_id.default_credit_account_id
292 account = move.journal_id.default_debit_account_id
294 part = partner_id and self.pool.get('res.partner').browse(cr, uid, partner_id) or False
295 # part = False is acceptable for fiscal position.
296 account = self.pool.get('account.fiscal.position').map_account(cr, uid, part and part.property_account_position or False, account.id)
298 account = self.pool.get('account.account').browse(cr, uid, account)
300 if account and ((not fields) or ('debit' in fields) or ('credit' in fields)):
301 data['account_id'] = account.id
302 # Propose the price VAT excluded, the VAT will be added when confirming line
304 taxes = self.pool.get('account.fiscal.position').map_tax(cr, uid, part and part.property_account_position or False, account.tax_ids)
305 tax = self.pool.get('account.tax').browse(cr, uid, taxes)
306 for t in self.pool.get('account.tax').compute_inv(cr, uid, tax, total, 1):
310 data['debit'] = s>0 and s or 0.0
311 data['credit'] = s<0 and -s or 0.0
313 if account and account.currency_id:
314 data['currency_id'] = account.currency_id.id
318 v = self.pool.get('res.currency').compute(cr, uid,
319 account.company_id.currency_id.id,
321 s, account=acc, account_invert=True)
322 data['amount_currency'] = v
325 def on_create_write(self, cr, uid, id, context={}):
326 ml = self.browse(cr, uid, id, context)
327 return map(lambda x: x.id, ml.move_id.line_id)
329 def _balance(self, cr, uid, ids, name, arg, context=None):
334 c['initital_bal'] = True
337 """select l2.id, sum(l1.debit-l1.credit) from account_move_line l1, account_move_line l2""",
338 """where l2.account_id=l1.account_id""",
344 self._query_get(cr, uid, obj='l1', context=c),
345 """ group by l2.id""",
348 cr.execute('\n'.join(sql), [tuple(ids)])
349 res = dict(cr.fetchall())
352 def _invoice(self, cursor, user, ids, name, arg, context=None):
353 invoice_obj = self.pool.get('account.invoice')
357 cursor.execute('SELECT l.id, i.id ' \
358 'FROM account_move_line l, account_invoice i ' \
359 'WHERE l.move_id = i.move_id ' \
363 for line_id, invoice_id in cursor.fetchall():
364 res[line_id] = invoice_id
365 invoice_ids.append(invoice_id)
366 invoice_names = {False: ''}
367 for invoice_id, name in invoice_obj.name_get(cursor, user,
368 invoice_ids, context=context):
369 invoice_names[invoice_id] = name
370 for line_id in res.keys():
371 invoice_id = res[line_id]
372 res[line_id] = (invoice_id, invoice_names[invoice_id])
375 def name_get(self, cr, uid, ids, context={}):
379 for line in self.browse(cr, uid, ids, context):
381 result.append((line.id, (line.move_id.name or '')+' ('+line.ref+')'))
383 result.append((line.id, line.move_id.name))
386 def _balance_search(self, cursor, user, obj, name, args, domain=None, context=None):
392 where = ' and '.join(map(lambda x: '(abs(sum(debit-credit))'+x[1]+str(x[2])+')',args))
393 cursor.execute('select id, sum(debit-credit) from account_move_line \
394 group by id, debit, credit having '+where)
395 res = cursor.fetchall()
397 return [('id', '=', '0')]
398 return [('id', 'in', [x[0] for x in res])]
400 def _invoice_search(self, cursor, user, obj, name, args, context):
403 invoice_obj = self.pool.get('account.invoice')
407 fargs = args[i][0].split('.', 1)
409 args[i] = (fargs[0], 'in', invoice_obj.search(cursor, user,
410 [(fargs[1], args[i][1], args[i][2])]))
413 if isinstance(args[i][2], basestring):
414 res_ids = invoice_obj.name_search(cursor, user, args[i][2], [],
416 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
421 if (x[2] is False) and (x[1] == '='):
422 qu1.append('(i.id IS NULL)')
423 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
424 qu1.append('(i.id IS NOT NULL)')
426 qu1.append('(i.id %s %s)' % (x[1], '%s'))
430 qu1.append('(i.id in (%s))' % (','.join(['%s'] * len(x[2]))))
433 qu1.append(' (False)')
435 qu1 = ' AND' + ' AND'.join(qu1)
438 cursor.execute('SELECT l.id ' \
439 'FROM account_move_line l, account_invoice i ' \
440 'WHERE l.move_id = i.move_id ' + qu1, qu2)
441 res = cursor.fetchall()
443 return [('id', '=', '0')]
444 return [('id', 'in', [x[0] for x in res])]
446 def _get_move_lines(self, cr, uid, ids, context={}):
448 for move in self.pool.get('account.move').browse(cr, uid, ids, context=context):
449 for line in move.line_id:
450 result.append(line.id)
454 'name': fields.char('Name', size=64, required=True),
455 '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 useful for some reports."),
456 'product_uom_id': fields.many2one('product.uom', 'UoM'),
457 'product_id': fields.many2one('product.product', 'Product'),
458 'debit': fields.float('Debit', digits_compute=dp.get_precision('Account')),
459 'credit': fields.float('Credit', digits_compute=dp.get_precision('Account')),
460 'account_id': fields.many2one('account.account', 'Account', required=True, ondelete="cascade", domain=[('type','<>','view'), ('type', '<>', 'closed')], select=2),
461 'move_id': fields.many2one('account.move', 'Move', ondelete="cascade", help="The move of this entry line.", select=2, required=True),
462 'narration': fields.related('move_id','narration', type='text', relation='account.move', string='Narration'),
463 'ref': fields.related('move_id', 'ref', string='Reference', type='char', size=64, store=True),
464 'statement_id': fields.many2one('account.bank.statement', 'Statement', help="The bank statement used for bank reconciliation", select=1),
465 'reconcile_id': fields.many2one('account.move.reconcile', 'Reconcile', readonly=True, ondelete='set null', select=2),
466 'reconcile_partial_id': fields.many2one('account.move.reconcile', 'Partial Reconcile', readonly=True, ondelete='set null', select=2),
467 'amount_currency': fields.float('Amount Currency', help="The amount expressed in an optional other currency if it is a multi-currency entry.", digits_compute=dp.get_precision('Account')),
468 'currency_id': fields.many2one('res.currency', 'Currency', help="The optional other currency if it is a multi-currency entry."),
470 'period_id': fields.many2one('account.period', 'Period', required=True, select=2),
471 'journal_id': fields.many2one('account.journal', 'Journal', required=True, select=1),
472 'blocked': fields.boolean('Litigation', help="You can check this box to mark this journal item as a litigation with the associated partner"),
474 'partner_id': fields.many2one('res.partner', 'Partner'),
475 'date_maturity': fields.date('Due date', help="This field is used for payable and receivable journal entries. You can put the limit date for the payment of this line."),
476 'date': fields.related('move_id','date', string='Effective date', type='date', required=True,
478 'account.move': (_get_move_lines, ['date'], 20)
480 'date_created': fields.date('Creation date'),
481 'analytic_lines': fields.one2many('account.analytic.line', 'move_id', 'Analytic lines'),
482 'centralisation': fields.selection([('normal','Normal'),('credit','Credit Centralisation'),('debit','Debit Centralisation')], 'Centralisation', size=6),
483 'balance': fields.function(_balance, fnct_search=_balance_search, method=True, string='Balance'),
484 'state': fields.selection([('draft','Unbalanced'), ('valid','Valid')], 'State', readonly=True,
485 help='When new move line is created the state will be \'Draft\'.\n* When all the payments are done it will be in \'Valid\' state.'),
486 'tax_code_id': fields.many2one('account.tax.code', 'Tax Account', help="The Account can either be a base tax code or a tax code account."),
487 'tax_amount': fields.float('Tax/Base Amount', digits_compute=dp.get_precision('Account'), select=True, help="If the Tax account is a tax code account, this field will contain the taxed amount.If the tax account is base tax code, "\
488 "this field will contain the basic amount(without tax)."),
489 'invoice': fields.function(_invoice, method=True, string='Invoice',
490 type='many2one', relation='account.invoice', fnct_search=_invoice_search),
491 'account_tax_id':fields.many2one('account.tax', 'Tax'),
492 'analytic_account_id': fields.many2one('account.analytic.account', 'Analytic Account'),
494 #'amount_taxed':fields.float("Taxed Amount", digits_compute=dp.get_precision('Account')),
495 'company_id': fields.related('account_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True)
499 def _get_date(self, cr, uid, context):
500 period_obj = self.pool.get('account.period')
501 dt = time.strftime('%Y-%m-%d')
502 if ('journal_id' in context) and ('period_id' in context):
503 cr.execute('select date from account_move_line ' \
504 'where journal_id=%s and period_id=%s ' \
505 'order by id desc limit 1',
506 (context['journal_id'], context['period_id']))
511 period = period_obj.browse(cr, uid, context['period_id'],
513 dt = period.date_start
516 def _get_currency(self, cr, uid, context={}):
517 if not context.get('journal_id', False):
519 cur = self.pool.get('account.journal').browse(cr, uid, context['journal_id']).currency
520 return cur and cur.id or False
523 'blocked': lambda *a: False,
524 'centralisation': lambda *a: 'normal',
526 'date_created': lambda *a: time.strftime('%Y-%m-%d'),
527 'state': lambda *a: 'draft',
528 'currency_id': _get_currency,
529 'journal_id': lambda self, cr, uid, c: c.get('journal_id', False),
530 'period_id': lambda self, cr, uid, c: c.get('period_id', False),
531 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.move.line', context=c)
533 _order = "date desc,id desc"
535 ('credit_debit1', 'CHECK (credit*debit=0)', 'Wrong credit or debit value in accounting entry !'),
536 ('credit_debit2', 'CHECK (credit+debit>=0)', 'Wrong credit or debit value in accounting entry !'),
539 def _auto_init(self, cr, context={}):
540 super(account_move_line, self)._auto_init(cr, context)
541 cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = \'account_move_line_journal_id_period_id_index\'')
542 if not cr.fetchone():
543 cr.execute('CREATE INDEX account_move_line_journal_id_period_id_index ON account_move_line (journal_id, period_id)')
545 def _check_no_view(self, cr, uid, ids):
546 lines = self.browse(cr, uid, ids)
548 if l.account_id.type == 'view':
552 def _check_no_closed(self, cr, uid, ids):
553 lines = self.browse(cr, uid, ids)
555 if l.account_id.type == 'closed':
559 def _check_company_id(self, cr, uid, ids):
560 lines = self.browse(cr, uid, ids)
562 if l.company_id != l.account_id.company_id or l.company_id != l.period_id.company_id:
567 (_check_no_view, 'You can not create move line on view account.', ['account_id']),
568 (_check_no_closed, 'You can not create move line on closed account.', ['account_id']),
569 (_check_company_id,'Company must be same for its related account and period.',['company_id'] ),
572 #TODO: ONCHANGE_ACCOUNT_ID: set account_tax_id
574 def onchange_currency(self, cr, uid, ids, account_id, amount, currency_id, date=False, journal=False):
575 if (not currency_id) or (not account_id):
578 acc =self.pool.get('account.account').browse(cr, uid, account_id)
579 if (amount>0) and journal:
580 x = self.pool.get('account.journal').browse(cr, uid, journal).default_credit_account_id
582 v = self.pool.get('res.currency').compute(cr, uid, currency_id,acc.company_id.currency_id.id, amount, account=acc)
584 'debit': v>0 and v or 0.0,
585 'credit': v<0 and -v or 0.0
589 def onchange_partner_id(self, cr, uid, ids, move_id, partner_id, account_id=None, debit=0, credit=0, date=False, journal=False):
591 val['date_maturity'] = False
596 date = datetime.now().strftime('%Y-%m-%d')
597 part = self.pool.get('res.partner').browse(cr, uid, partner_id)
599 if part.property_payment_term:
600 res = self.pool.get('account.payment.term').compute(cr, uid, part.property_payment_term.id, 100, date)
602 val['date_maturity'] = res[0][0]
604 id1 = part.property_account_payable.id
605 id2 = part.property_account_receivable.id
607 jt = self.pool.get('account.journal').browse(cr, uid, journal).type
608 #FIXME: Bank and cash journal are such a journal we can not assume a account based on this 2 journals
609 # Bank and cash journal can have a payment or receipt transaction, and in both type partner account
610 # will not be same id payment then payable, and if receipt then receivable
611 #if jt in ('sale', 'purchase_refund', 'bank', 'cash'):
612 if jt in ('sale', 'purchase_refund'):
613 val['account_id'] = self.pool.get('account.fiscal.position').map_account(cr, uid, part and part.property_account_position or False, id2)
614 elif jt in ('purchase', 'sale_refund', 'expense', 'bank', 'cash'):
615 val['account_id'] = self.pool.get('account.fiscal.position').map_account(cr, uid, part and part.property_account_position or False, id1)
617 if val.get('account_id', False):
618 d = self.onchange_account_id(cr, uid, ids, val['account_id'])
619 val.update(d['value'])
623 def onchange_account_id(self, cr, uid, ids, account_id=False, partner_id=False):
626 res = self.pool.get('account.account').browse(cr, uid, account_id)
627 tax_ids = res.tax_ids
628 if tax_ids and partner_id:
629 part = self.pool.get('res.partner').browse(cr, uid, partner_id)
630 tax_id = self.pool.get('account.fiscal.position').map_tax(cr, uid, part and part.property_account_position or False, tax_ids)[0]
632 tax_id = tax_ids and tax_ids[0].id or False
633 val['account_tax_id'] = tax_id
637 # type: the type if reconciliation (no logic behind this field, for info)
639 # writeoff; entry generated for the difference between the lines
642 def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False):
645 if context and context.get('next_partner_only', False):
646 if not context.get('partner_id', False):
647 partner = self.get_next_partner_only(cr, uid, offset, context)
649 partner = context.get('partner_id', False)
652 args.append(('partner_id', '=', partner[0]))
653 return super(account_move_line, self).search(cr, uid, args, offset, limit, order, context, count)
655 def get_next_partner_only(self, cr, uid, offset=0, context=None):
661 SELECT l.partner_id as partner_id, SUM(l.debit) as debit, SUM(l.credit) as credit
662 FROM account_move_line l
663 LEFT JOIN account_account a ON (a.id = l.account_id)
664 LEFT JOIN res_partner p ON (l.partner_id = p.id)
665 WHERE a.reconcile IS TRUE
666 AND l.reconcile_id IS NULL
667 AND (p.last_reconciliation_date IS NULL OR l.date > p.last_reconciliation_date)
668 AND l.state <> 'draft'
669 GROUP BY l.partner_id
670 ) AS s ON (p.id = s.partner_id)
671 WHERE debit > 0 AND credit > 0
672 ORDER BY p.last_reconciliation_date LIMIT 1 OFFSET %s""", (offset,)
676 def reconcile_partial(self, cr, uid, ids, type='auto', context=None):
686 for line in self.browse(cr, uid, ids, context=context):
687 if company_list and not line.company_id.id in company_list:
688 raise osv.except_osv(_('Warning !'), _('To reconcile the entries company should be the same for all entries'))
689 company_list.append(line.company_id.id)
691 for line in self.browse(cr, uid, ids, context):
692 if line.reconcile_id:
693 raise osv.except_osv(_('Warning'), _('Already Reconciled!'))
694 if line.reconcile_partial_id:
695 for line2 in line.reconcile_partial_id.line_partial_ids:
696 if not line2.reconcile_id:
697 if line2.id not in merges:
698 merges.append(line2.id)
699 total += (line2.debit or 0.0) - (line2.credit or 0.0)
700 merges_rec.append(line.reconcile_partial_id.id)
702 unmerge.append(line.id)
703 total += (line.debit or 0.0) - (line.credit or 0.0)
706 res = self.reconcile(cr, uid, merges+unmerge, context=context)
708 r_id = self.pool.get('account.move.reconcile').create(cr, uid, {
710 'line_partial_ids': map(lambda x: (4,x,False), merges+unmerge)
712 self.pool.get('account.move.reconcile').reconcile_partial_check(cr, uid, [r_id] + merges_rec, context=context)
715 def reconcile(self, cr, uid, ids, type='auto', writeoff_acc_id=False, writeoff_period_id=False, writeoff_journal_id=False, context=None):
716 lines = self.browse(cr, uid, ids, context=context)
717 unrec_lines = filter(lambda x: not x['reconcile_id'], lines)
726 for line in self.browse(cr, uid, ids, context=context):
727 if company_list and not line.company_id.id in company_list:
728 raise osv.except_osv(_('Warning !'), _('To reconcile the entries company should be the same for all entries'))
729 company_list.append(line.company_id.id)
731 for line in unrec_lines:
732 if line.state <> 'valid':
733 raise osv.except_osv(_('Error'),
734 _('Entry "%s" is not valid !') % line.name)
735 credit += line['credit']
736 debit += line['debit']
737 currency += line['amount_currency'] or 0.0
738 account_id = line['account_id']['id']
739 partner_id = (line['partner_id'] and line['partner_id']['id']) or False
740 writeoff = debit - credit
742 # Ifdate_p in context => take this date
743 if context.has_key('date_p') and context['date_p']:
744 date=context['date_p']
746 date = time.strftime('%Y-%m-%d')
748 cr.execute('SELECT account_id, reconcile_id '\
749 'FROM account_move_line '\
751 'GROUP BY account_id,reconcile_id',
754 #TODO: move this check to a constraint in the account_move_reconcile object
755 if (len(r) != 1) and not context.get('fy_closing', False):
756 raise osv.except_osv(_('Error'), _('Entries are not of the same account or already reconciled ! '))
758 raise osv.except_osv(_('Error'), _('Entry is already reconciled'))
759 account = self.pool.get('account.account').browse(cr, uid, account_id, context=context)
760 if not context.get('fy_closing', False) and not account.reconcile:
761 raise osv.except_osv(_('Error'), _('The account is not defined to be reconciled !'))
763 raise osv.except_osv(_('Error'), _('Some entries are already reconciled !'))
765 if (not self.pool.get('res.currency').is_zero(cr, uid, account.company_id.currency_id, writeoff)) or \
766 (account.currency_id and (not self.pool.get('res.currency').is_zero(cr, uid, account.currency_id, currency))):
767 if not writeoff_acc_id:
768 raise osv.except_osv(_('Warning'), _('You have to provide an account for the write off entry !'))
772 self_credit = writeoff
778 self_debit = -writeoff
780 # If comment exist in context, take it
781 if 'comment' in context and context['comment']:
782 libelle=context['comment']
790 'credit':self_credit,
791 'account_id':account_id,
793 'partner_id':partner_id,
794 'currency_id': account.currency_id.id or False,
795 'amount_currency': account.currency_id.id and -currency or 0.0
801 'account_id':writeoff_acc_id,
802 'analytic_account_id': context.get('analytic_id', False),
804 'partner_id':partner_id
808 writeoff_move_id = self.pool.get('account.move').create(cr, uid, {
809 'period_id': writeoff_period_id,
810 'journal_id': writeoff_journal_id,
813 'line_id': writeoff_lines
816 writeoff_line_ids = self.search(cr, uid, [('move_id', '=', writeoff_move_id), ('account_id', '=', account_id)])
817 ids += writeoff_line_ids
819 r_id = self.pool.get('account.move.reconcile').create(cr, uid, {
822 'line_id': map(lambda x: (4,x,False), ids),
823 'line_partial_ids': map(lambda x: (3,x,False), ids)
825 wf_service = netsvc.LocalService("workflow")
826 # the id of the move.reconcile is written in the move.line (self) by the create method above
827 # because of the way the line_id are defined: (4, x, False)
829 wf_service.trg_trigger(uid, 'account.move.line', id, cr)
831 if lines and lines[0]:
832 partner_id = lines[0].partner_id and lines[0].partner_id.id or False
833 if partner_id and context and context.get('stop_reconcile', False):
834 self.pool.get('res.partner').write(cr, uid, [partner_id], {'last_reconciliation_date': time.strftime('%Y-%m-%d %H:%M:%S')})
837 def view_header_get(self, cr, user, view_id, view_type, context):
838 context = self.convert_to_period(cr, user, context)
839 if context.get('account_id', False):
840 cr.execute('select code from account_account where id=%s', (context['account_id'],))
842 res = _('Entries: ')+ (res[0] or '')
844 if (not context.get('journal_id', False)) or (not context.get('period_id', False)):
846 cr.execute('select code from account_journal where id=%s', (context['journal_id'],))
847 j = cr.fetchone()[0] or ''
848 cr.execute('select code from account_period where id=%s', (context['period_id'],))
849 p = cr.fetchone()[0] or ''
851 return j+(p and (':'+p) or '')
854 def onchange_date(self, cr, user, ids, date, context={}):
856 Returns a dict that contains new values and context
857 @param cr: A database cursor
858 @param user: ID of the user currently logged in
859 @param date: latest value from user input for field date
860 @param args: other arguments
861 @param context: context arguments, like lang, time zone
862 @return: Returns a dict which contains new values, and context
865 period_pool = self.pool.get('account.period')
866 pids = period_pool.search(cr, user, [('date_start','<=',date), ('date_stop','>=',date)])
879 def fields_view_get(self, cr, uid, view_id=None, view_type='form', context={}, toolbar=False, submenu=False):
880 journal_pool = self.pool.get('account.journal')
882 result = super(osv.osv, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar=toolbar, submenu=submenu)
883 if view_type != 'tree':
884 #Remove the toolbar from the form view
885 if view_type == 'form':
886 if result.get('toolbar', False):
887 result['toolbar']['action'] = []
889 #Restrict the list of journal view in search view
890 if view_type == 'search':
891 journal_list = journal_pool.name_search(cr, uid, '', [], context=context)
892 result['fields']['journal_id']['selection'] = journal_list
895 if context.get('view_mode', False):
901 title = "Accounting Entries" #self.view_header_get(cr, uid, view_id, view_type, context)
902 xml = '''<?xml version="1.0"?>\n<tree string="%s" editable="top" refresh="5" on_write="on_create_write" colors="red:state==\'draft\';black:state==\'valid\'">\n\t''' % (title)
904 ids = journal_pool.search(cr, uid, [])
905 journals = journal_pool.browse(cr, uid, ids)
908 total = len(journals)
909 for journal in journals:
910 all_journal.append(journal.id)
911 for field in journal.view_id.columns_id:
912 if not field.field in fields:
913 fields[field.field] = [journal.id]
914 fld.append((field.field, field.sequence))
915 flds.append(field.field)
916 common_fields[field.field] = 1
918 fields.get(field.field).append(journal.id)
919 common_fields[field.field] = common_fields[field.field] + 1
921 fld.append(('period_id', 3))
922 fld.append(('journal_id', 10))
923 flds.append('period_id')
924 flds.append('journal_id')
925 fields['period_id'] = all_journal
926 fields['journal_id'] = all_journal
928 from operator import itemgetter
929 fld = sorted(fld, key=itemgetter(1))
942 if common_fields.get(field) == total:
943 fields.get(field).append(None)
946 # state = 'colors="red:state==\'draft\'"'
950 attrs.append('sum="Total debit"')
952 elif field == 'credit':
953 attrs.append('sum="Total credit"')
955 elif field == 'move_id':
956 attrs.append('required="False"')
958 elif field == 'account_tax_id':
959 attrs.append('domain="[(\'parent_id\',\'=\',False)]"')
960 attrs.append("context=\"{'journal_id':journal_id}\"")
962 elif field == 'account_id' and journal.id:
963 attrs.append('domain="[(\'journal_id\', \'=\', '+str(journal.id)+'),(\'type\',\'<>\',\'view\'), (\'type\',\'<>\',\'closed\')]" on_change="onchange_account_id(account_id, partner_id)"')
965 elif field == 'partner_id':
966 attrs.append('on_change="onchange_partner_id(move_id, partner_id, account_id, debit, credit, date, journal_id)"')
968 elif field == 'journal_id':
969 attrs.append("context=\"{'journal_id':journal_id}\"")
971 elif field == 'statement_id':
972 attrs.append("domain=\"[('state','!=','confirm'),('journal_id.type','=','bank')]\"")
974 elif field == 'date':
975 attrs.append('on_change="onchange_date(date)"')
977 if field in ('amount_currency', 'currency_id'):
978 attrs.append('on_change="onchange_currency(account_id, amount_currency,currency_id, date, journal_id)"')
979 attrs.append('''attrs="{'readonly':[('state','=','valid')]}"''')
982 attrs.append('width="'+str(widths[field])+'"')
984 attrs.append("invisible=\"context.get('visible_id') not in %s\"" % (fields.get(field)))
985 xml += '''<field name="%s" %s/>\n''' % (field,' '.join(attrs))
989 result['fields'] = self.fields_get(cr, uid, flds, context)
992 def _check_moves(self, cr, uid, context):
993 # use the first move ever created for this journal and period
994 cr.execute('select id, state, name from account_move where journal_id=%s and period_id=%s order by id limit 1', (context['journal_id'],context['period_id']))
997 if res[1] != 'draft':
998 raise osv.except_osv(_('UserError'),
999 _('The account move (%s) for centralisation ' \
1000 'has been confirmed!') % res[2])
1003 def _remove_move_reconcile(self, cr, uid, move_ids=[], context=None):
1004 # Function remove move rencocile ids related with moves
1005 obj_move_line = self.pool.get('account.move.line')
1006 obj_move_rec = self.pool.get('account.move.reconcile')
1010 recs = obj_move_line.read(cr, uid, move_ids, ['reconcile_id','reconcile_partial_id'])
1011 full_recs = filter(lambda x: x['reconcile_id'], recs)
1012 rec_ids = [rec['reconcile_id'][0] for rec in full_recs]
1013 part_recs = filter(lambda x: x['reconcile_partial_id'], recs)
1014 part_rec_ids = [rec['reconcile_partial_id'][0] for rec in part_recs]
1015 unlink_ids += rec_ids
1016 unlink_ids += part_rec_ids
1018 obj_move_rec.unlink(cr, uid, unlink_ids)
1021 def unlink(self, cr, uid, ids, context={}, check=True):
1022 self._update_check(cr, uid, ids, context)
1024 for line in self.browse(cr, uid, ids, context):
1025 context['journal_id']=line.journal_id.id
1026 context['period_id']=line.period_id.id
1027 result = super(account_move_line, self).unlink(cr, uid, [line.id], context=context)
1029 self.pool.get('account.move').validate(cr, uid, [line.move_id.id], context=context)
1032 def _check_date(self, cr, uid, vals, context=None, check=True):
1036 if 'date' in vals.keys():
1037 if 'journal_id' in vals and 'journal_id' not in context:
1038 journal_id = vals['journal_id']
1039 if 'period_id' in vals and 'period_id' not in context:
1040 period_id = vals['period_id']
1041 elif 'journal_id' not in context and 'move_id' in vals:
1042 if vals.get('move_id', False):
1043 m = self.pool.get('account.move').browse(cr, uid, vals['move_id'])
1044 journal_id = m.journal_id.id
1045 period_id = m.period_id.id
1047 journal_id = context.get('journal_id',False)
1048 period_id = context.get('period_id',False)
1050 journal = self.pool.get('account.journal').browse(cr, uid, [journal_id])[0]
1051 if journal.allow_date and period_id:
1052 period = self.pool.get('account.period').browse(cr, uid, [period_id])[0]
1053 if not time.strptime(vals['date'][:10],'%Y-%m-%d')>=time.strptime(period.date_start,'%Y-%m-%d') or not time.strptime(vals['date'][:10],'%Y-%m-%d')<=time.strptime(period.date_stop,'%Y-%m-%d'):
1054 raise osv.except_osv(_('Error'),_('The date of your Journal Entry is not in the defined period!'))
1058 def write(self, cr, uid, ids, vals, context=None, check=True, update_check=True):
1061 if vals.get('account_tax_id', False):
1062 raise osv.except_osv(_('Unable to change tax !'), _('You can not change the tax, you should remove and recreate lines !'))
1063 self._check_date(cr, uid, vals, context, check)
1064 account_obj = self.pool.get('account.account')
1065 if ('account_id' in vals) and not account_obj.read(cr, uid, vals['account_id'], ['active'])['active']:
1066 raise osv.except_osv(_('Bad account!'), _('You can not use an inactive account!'))
1068 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):
1069 self._update_check(cr, uid, ids, context)
1072 if vals.get('date', False):
1073 todo_date = vals['date']
1076 for line in self.browse(cr, uid, ids,context=context):
1077 ctx = context.copy()
1078 if ('journal_id' not in ctx):
1080 ctx['journal_id'] = line.move_id.journal_id.id
1082 ctx['journal_id'] = line.journal_id.id
1083 if ('period_id' not in ctx):
1085 ctx['period_id'] = line.move_id.period_id.id
1087 ctx['period_id'] = line.period_id.id
1088 #Check for centralisation
1089 journal = self.pool.get('account.journal').browse(cr, uid, ctx['journal_id'], context=ctx)
1090 if journal.centralisation:
1091 self._check_moves(cr, uid, context=ctx)
1093 result = super(account_move_line, self).write(cr, uid, ids, vals, context)
1097 for line in self.browse(cr, uid, ids):
1098 if line.move_id.id not in done:
1099 done.append(line.move_id.id)
1100 self.pool.get('account.move').validate(cr, uid, [line.move_id.id], context)
1102 self.pool.get('account.move').write(cr, uid, [line.move_id.id], {'date': todo_date}, context=context)
1105 def _update_journal_check(self, cr, uid, journal_id, period_id, context={}):
1106 cr.execute('select state from account_journal_period where journal_id=%s and period_id=%s', (journal_id, period_id))
1107 result = cr.fetchall()
1108 for (state,) in result:
1110 raise osv.except_osv(_('Error !'), _('You can not add/modify entries in a closed journal.'))
1112 journal = self.pool.get('account.journal').browse(cr, uid, journal_id, context)
1113 period = self.pool.get('account.period').browse(cr, uid, period_id, context)
1114 self.pool.get('account.journal.period').create(cr, uid, {
1115 'name': (journal.code or journal.name)+':'+(period.name or ''),
1116 'journal_id': journal.id,
1117 'period_id': period.id
1121 def _update_check(self, cr, uid, ids, context={}):
1123 for line in self.browse(cr, uid, ids, context):
1124 if line.move_id.state<>'draft':
1125 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 !'))
1126 if line.reconcile_id:
1127 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 !'))
1128 t = (line.journal_id.id, line.period_id.id)
1130 self._update_journal_check(cr, uid, line.journal_id.id, line.period_id.id, context)
1134 def create(self, cr, uid, vals, context=None, check=True):
1135 account_obj = self.pool.get('account.account')
1136 tax_obj=self.pool.get('account.tax')
1139 self._check_date(cr, uid, vals, context, check)
1140 if ('account_id' in vals) and not account_obj.read(cr, uid, vals['account_id'], ['active'])['active']:
1141 raise osv.except_osv(_('Bad account!'), _('You can not use an inactive account!'))
1142 if 'journal_id' in vals:
1143 context['journal_id'] = vals['journal_id']
1144 if 'period_id' in vals:
1145 context['period_id'] = vals['period_id']
1146 if ('journal_id' not in context) and ('move_id' in vals) and vals['move_id']:
1147 m = self.pool.get('account.move').browse(cr, uid, vals['move_id'])
1148 context['journal_id'] = m.journal_id.id
1149 context['period_id'] = m.period_id.id
1151 self._update_journal_check(cr, uid, context['journal_id'], context['period_id'], context)
1152 move_id = vals.get('move_id', False)
1153 journal = self.pool.get('account.journal').browse(cr, uid, context['journal_id'])
1156 if journal.centralisation:
1157 #Check for centralisation
1158 res = self._check_moves(cr, uid, context)
1160 vals['move_id'] = res[0]
1162 if not vals.get('move_id', False):
1163 if journal.sequence_id:
1164 #name = self.pool.get('ir.sequence').get_id(cr, uid, journal.sequence_id.id)
1166 'date': vals.get('date', time.strftime('%Y-%m-%d')),
1167 'period_id': context['period_id'],
1168 'journal_id': context['journal_id']
1170 move_id = self.pool.get('account.move').create(cr, uid, v, context)
1171 vals['move_id'] = move_id
1173 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.'))
1176 ok = not (journal.type_control_ids or journal.account_control_ids)
1177 if ('account_id' in vals):
1178 account = account_obj.browse(cr, uid, vals['account_id'])
1179 if journal.type_control_ids:
1180 type = account.user_type
1181 for t in journal.type_control_ids:
1182 if type.code == t.code:
1185 if journal.account_control_ids and not ok:
1186 for a in journal.account_control_ids:
1187 if a.id == vals['account_id']:
1191 # Automatically convert in the account's secondary currency if there is one and
1192 # the provided values were not already multi-currency
1193 if account.currency_id and 'amount_currency' not in vals and account.currency_id.id != account.company_id.currency_id.id:
1194 vals['currency_id'] = account.currency_id.id
1195 cur_obj = self.pool.get('res.currency')
1198 ctx['date'] = vals['date']
1199 vals['amount_currency'] = cur_obj.compute(cr, uid, account.company_id.currency_id.id,
1200 account.currency_id.id, vals.get('debit', 0.0)-vals.get('credit', 0.0),
1203 raise osv.except_osv(_('Bad account !'), _('You can not use this general account in this journal !'))
1205 if vals.get('analytic_account_id',False):
1206 if journal.analytic_journal_id:
1207 vals['analytic_lines'] = [(0,0, {
1208 'name': vals['name'],
1209 'date': vals.get('date', time.strftime('%Y-%m-%d')),
1210 'account_id': vals.get('analytic_account_id', False),
1211 'unit_amount': vals.get('quantity', 1.0),
1212 'amount': vals.get('debit', 0.0) or vals.get('credit', 0.0),
1213 'general_account_id': vals.get('account_id', False),
1214 'journal_id': journal.analytic_journal_id.id,
1215 'ref': vals.get('ref', False),
1219 result = super(osv.osv, self).create(cr, uid, vals, context)
1221 if vals.get('account_tax_id', False):
1222 tax_id = tax_obj.browse(cr, uid, vals['account_tax_id'])
1223 total = vals['debit'] - vals['credit']
1224 if journal.refund_journal:
1225 base_code = 'ref_base_code_id'
1226 tax_code = 'ref_tax_code_id'
1227 account_id = 'account_paid_id'
1228 base_sign = 'ref_base_sign'
1229 tax_sign = 'ref_tax_sign'
1231 base_code = 'base_code_id'
1232 tax_code = 'tax_code_id'
1233 account_id = 'account_collected_id'
1234 base_sign = 'base_sign'
1235 tax_sign = 'tax_sign'
1238 for tax in tax_obj.compute_all(cr, uid, [tax_id], total, 1.00).get('taxes'):
1239 #create the base movement
1243 self.write(cr, uid,[result], {
1244 'tax_code_id': tax[base_code],
1245 'tax_amount': tax[base_sign] * abs(total)
1249 'move_id': vals['move_id'],
1250 'journal_id': vals['journal_id'],
1251 'period_id': vals['period_id'],
1252 'name': tools.ustr(vals['name'] or '') + ' ' + tools.ustr(tax['name'] or ''),
1253 'date': vals['date'],
1254 'partner_id': vals.get('partner_id',False),
1255 'ref': vals.get('ref',False),
1256 'account_tax_id': False,
1257 'tax_code_id': tax[base_code],
1258 'tax_amount': tax[base_sign] * abs(total),
1259 'account_id': vals['account_id'],
1263 if data['tax_code_id']:
1264 self.create(cr, uid, data, context)
1266 #create the VAT movement
1268 'move_id': vals['move_id'],
1269 'journal_id': vals['journal_id'],
1270 'period_id': vals['period_id'],
1271 'name': tools.ustr(vals['name'] or '') + ' ' + tools.ustr(tax['name'] or ''),
1272 'date': vals['date'],
1273 'partner_id': vals.get('partner_id',False),
1274 'ref': vals.get('ref',False),
1275 'account_tax_id': False,
1276 'tax_code_id': tax[tax_code],
1277 'tax_amount': tax[tax_sign] * abs(tax['amount']),
1278 'account_id': tax[account_id] or vals['account_id'],
1279 'credit': tax['amount']<0 and -tax['amount'] or 0.0,
1280 'debit': tax['amount']>0 and tax['amount'] or 0.0,
1282 if data['tax_code_id']:
1283 self.create(cr, uid, data, context)
1284 del vals['account_tax_id']
1286 if check and ((not context.get('no_store_function')) or journal.entry_posted):
1287 tmp = self.pool.get('account.move').validate(cr, uid, [vals['move_id']], context)
1288 if journal.entry_posted and tmp:
1289 rs = self.pool.get('account.move').button_validate(cr,uid, [vals['move_id']],context)
1293 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: