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 ##############################################################################
23 from datetime import datetime
26 from openerp import workflow
27 from openerp.osv import fields, osv
28 from openerp.tools.translate import _
29 import openerp.addons.decimal_precision as dp
30 from openerp import tools
33 class account_move_line(osv.osv):
34 _name = "account.move.line"
35 _description = "Journal Items"
37 def _query_get(self, cr, uid, obj='l', context=None):
38 fiscalyear_obj = self.pool.get('account.fiscalyear')
39 fiscalperiod_obj = self.pool.get('account.period')
40 account_obj = self.pool.get('account.account')
42 context = dict(context or {})
43 initial_bal = context.get('initial_bal', False)
45 if context.get('company_id', False):
46 company_clause = " AND " +obj+".company_id = %s" % context.get('company_id', False)
47 if not context.get('fiscalyear', False):
48 if context.get('all_fiscalyear', False):
49 #this option is needed by the aged balance report because otherwise, if we search only the draft ones, an open invoice of a closed fiscalyear won't be displayed
50 fiscalyear_ids = fiscalyear_obj.search(cr, uid, [])
52 fiscalyear_ids = fiscalyear_obj.search(cr, uid, [('state', '=', 'draft')])
54 #for initial balance as well as for normal query, we check only the selected FY because the best practice is to generate the FY opening entries
55 fiscalyear_ids = [context['fiscalyear']]
57 fiscalyear_clause = (','.join([str(x) for x in fiscalyear_ids])) or '0'
58 state = context.get('state', False)
60 where_move_lines_by_date = ''
62 if context.get('date_from', False) and context.get('date_to', False):
64 where_move_lines_by_date = " AND " +obj+".move_id IN (SELECT id FROM account_move WHERE date < '" +context['date_from']+"')"
66 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']+"')"
69 if state.lower() not in ['all']:
70 where_move_state= " AND "+obj+".move_id IN (SELECT id FROM account_move WHERE account_move.state = '"+state+"')"
71 if context.get('period_from', False) and context.get('period_to', False) and not context.get('periods', False):
73 period_company_id = fiscalperiod_obj.browse(cr, uid, context['period_from'], context=context).company_id.id
74 first_period = fiscalperiod_obj.search(cr, uid, [('company_id', '=', period_company_id)], order='date_start', limit=1)[0]
75 context['periods'] = fiscalperiod_obj.build_ctx_periods(cr, uid, first_period, context['period_from'])
77 context['periods'] = fiscalperiod_obj.build_ctx_periods(cr, uid, context['period_from'], context['period_to'])
78 if context.get('periods', False):
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)
81 period_ids = fiscalperiod_obj.search(cr, uid, [('id', 'in', context['periods'])], order='date_start', limit=1)
82 if period_ids and period_ids[0]:
83 first_period = fiscalperiod_obj.browse(cr, uid, period_ids[0], context=context)
84 ids = ','.join([str(x) for x in context['periods']])
85 query = obj+".state <> 'draft' AND "+obj+".period_id IN (SELECT id FROM account_period WHERE fiscalyear_id IN (%s) AND date_start <= '%s' AND id NOT IN (%s)) %s %s" % (fiscalyear_clause, first_period.date_start, ids, where_move_state, where_move_lines_by_date)
87 ids = ','.join([str(x) for x in context['periods']])
88 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)
90 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)
92 if initial_bal and not context.get('periods', False) and not where_move_lines_by_date:
93 #we didn't pass any filter in the context, and the initial balance can't be computed using only the fiscalyear otherwise entries will be summed twice
94 #so we have to invalidate this query
95 raise osv.except_osv(_('Warning!'),_("You have not supplied enough arguments to compute the initial balance, please select a period and a journal in the context."))
98 if context.get('journal_ids', False):
99 query += ' AND '+obj+'.journal_id IN (%s)' % ','.join(map(str, context['journal_ids']))
101 if context.get('chart_account_id', False):
102 child_ids = account_obj._get_children_and_consol(cr, uid, [context['chart_account_id']], context=context)
103 query += ' AND '+obj+'.account_id IN (%s)' % ','.join(map(str, child_ids))
105 query += company_clause
108 def _amount_residual(self, cr, uid, ids, field_names, args, context=None):
110 This function returns the residual amount on a receivable or payable account.move.line.
111 By default, it returns an amount in the currency of this journal entry (maybe different
112 of the company currency), but if you pass 'residual_in_company_currency' = True in the
113 context then the returned amount will be in company currency.
118 cur_obj = self.pool.get('res.currency')
119 for move_line in self.browse(cr, uid, ids, context=context):
120 res[move_line.id] = {
121 'amount_residual': 0.0,
122 'amount_residual_currency': 0.0,
125 if move_line.reconcile_id:
127 if not move_line.account_id.reconcile:
128 #this function does not suport to be used on move lines not related to a reconcilable account
131 if move_line.currency_id:
132 move_line_total = move_line.amount_currency
133 sign = move_line.amount_currency < 0 and -1 or 1
135 move_line_total = move_line.debit - move_line.credit
136 sign = (move_line.debit - move_line.credit) < 0 and -1 or 1
137 line_total_in_company_currency = move_line.debit - move_line.credit
138 context_unreconciled = context.copy()
139 if move_line.reconcile_partial_id:
140 for payment_line in move_line.reconcile_partial_id.line_partial_ids:
141 if payment_line.id == move_line.id:
143 if payment_line.currency_id and move_line.currency_id and payment_line.currency_id.id == move_line.currency_id.id:
144 move_line_total += payment_line.amount_currency
146 if move_line.currency_id:
147 context_unreconciled.update({'date': payment_line.date})
148 amount_in_foreign_currency = cur_obj.compute(cr, uid, move_line.company_id.currency_id.id, move_line.currency_id.id, (payment_line.debit - payment_line.credit), round=False, context=context_unreconciled)
149 move_line_total += amount_in_foreign_currency
151 move_line_total += (payment_line.debit - payment_line.credit)
152 line_total_in_company_currency += (payment_line.debit - payment_line.credit)
154 result = move_line_total
155 res[move_line.id]['amount_residual_currency'] = sign * (move_line.currency_id and self.pool.get('res.currency').round(cr, uid, move_line.currency_id, result) or result)
156 res[move_line.id]['amount_residual'] = sign * line_total_in_company_currency
159 def default_get(self, cr, uid, fields, context=None):
160 data = self._default_get(cr, uid, fields, context=context)
161 for f in data.keys():
166 def _prepare_analytic_line(self, cr, uid, obj_line, context=None):
168 Prepare the values given at the create() of account.analytic.line upon the validation of a journal item having
169 an analytic account. This method is intended to be extended in other modules.
171 :param obj_line: browse record of the account.move.line that triggered the analytic line creation
173 return {'name': obj_line.name,
174 'date': obj_line.date,
175 'account_id': obj_line.analytic_account_id.id,
176 'unit_amount': obj_line.quantity,
177 'product_id': obj_line.product_id and obj_line.product_id.id or False,
178 'product_uom_id': obj_line.product_uom_id and obj_line.product_uom_id.id or False,
179 'amount': (obj_line.credit or 0.0) - (obj_line.debit or 0.0),
180 'general_account_id': obj_line.account_id.id,
181 'journal_id': obj_line.journal_id.analytic_journal_id.id,
183 'move_id': obj_line.id,
187 def create_analytic_lines(self, cr, uid, ids, context=None):
188 acc_ana_line_obj = self.pool.get('account.analytic.line')
189 for obj_line in self.browse(cr, uid, ids, context=context):
190 if obj_line.analytic_account_id:
191 if not obj_line.journal_id.analytic_journal_id:
192 raise osv.except_osv(_('No Analytic Journal!'),_("You have to define an analytic journal on the '%s' journal!") % (obj_line.journal_id.name, ))
193 if obj_line.analytic_lines:
194 acc_ana_line_obj.unlink(cr,uid,[obj.id for obj in obj_line.analytic_lines])
195 vals_line = self._prepare_analytic_line(cr, uid, obj_line, context=context)
196 acc_ana_line_obj.create(cr, uid, vals_line)
199 def _default_get_move_form_hook(self, cursor, user, data):
200 '''Called in the end of default_get method for manual entry in account_move form'''
201 if data.has_key('analytic_account_id'):
202 del(data['analytic_account_id'])
203 if data.has_key('account_tax_id'):
204 del(data['account_tax_id'])
207 def convert_to_period(self, cr, uid, context=None):
210 period_obj = self.pool.get('account.period')
211 #check if the period_id changed in the context from client side
212 if context.get('period_id', False):
213 period_id = context.get('period_id')
214 if type(period_id) == str:
215 ids = period_obj.search(cr, uid, [('name', 'ilike', period_id)])
216 context = dict(context, period_id=ids and ids[0] or False)
219 def _default_get(self, cr, uid, fields, context=None):
220 #default_get should only do the following:
221 # -propose the next amount in debit/credit in order to balance the move
222 # -propose the next account from the journal (default debit/credit account) accordingly
223 context = dict(context or {})
224 account_obj = self.pool.get('account.account')
225 period_obj = self.pool.get('account.period')
226 journal_obj = self.pool.get('account.journal')
227 move_obj = self.pool.get('account.move')
228 tax_obj = self.pool.get('account.tax')
229 fiscal_pos_obj = self.pool.get('account.fiscal.position')
230 partner_obj = self.pool.get('res.partner')
231 currency_obj = self.pool.get('res.currency')
233 if not context.get('journal_id', False):
234 context['journal_id'] = context.get('search_default_journal_id', False)
235 if not context.get('period_id', False):
236 context['period_id'] = context.get('search_default_period_id', False)
237 context = self.convert_to_period(cr, uid, context)
239 # Compute simple values
240 data = super(account_move_line, self).default_get(cr, uid, fields, context=context)
241 if context.get('journal_id'):
243 #in account.move form view, it is not possible to compute total debit and credit using
244 #a browse record. So we must use the context to pass the whole one2many field and compute the total
245 if context.get('line_id'):
246 for move_line_dict in move_obj.resolve_2many_commands(cr, uid, 'line_id', context.get('line_id'), context=context):
247 data['name'] = data.get('name') or move_line_dict.get('name')
248 data['partner_id'] = data.get('partner_id') or move_line_dict.get('partner_id')
249 total += move_line_dict.get('debit', 0.0) - move_line_dict.get('credit', 0.0)
250 elif context.get('period_id'):
251 #find the date and the ID of the last unbalanced account.move encoded by the current user in that journal and period
253 cr.execute('''SELECT move_id, date FROM account_move_line
254 WHERE journal_id = %s AND period_id = %s AND create_uid = %s AND state = %s
255 ORDER BY id DESC limit 1''', (context['journal_id'], context['period_id'], uid, 'draft'))
257 move_id = res and res[0] or False
258 data['date'] = res and res[1] or period_obj.browse(cr, uid, context['period_id'], context=context).date_start
259 data['move_id'] = move_id
261 #if there exist some unbalanced accounting entries that match the journal and the period,
262 #we propose to continue the same move by copying the ref, the name, the partner...
263 move = move_obj.browse(cr, uid, move_id, context=context)
264 data.setdefault('name', move.line_id[-1].name)
265 for l in move.line_id:
266 data['partner_id'] = data.get('partner_id') or l.partner_id.id
267 data['ref'] = data.get('ref') or l.ref
268 total += (l.debit or 0.0) - (l.credit or 0.0)
270 #compute the total of current move
271 data['debit'] = total < 0 and -total or 0.0
272 data['credit'] = total > 0 and total or 0.0
273 #pick the good account on the journal accordingly if the next proposed line will be a debit or a credit
274 journal_data = journal_obj.browse(cr, uid, context['journal_id'], context=context)
275 account = total > 0 and journal_data.default_credit_account_id or journal_data.default_debit_account_id
276 #map the account using the fiscal position of the partner, if needed
277 part = data.get('partner_id') and partner_obj.browse(cr, uid, data['partner_id'], context=context) or False
278 if account and data.get('partner_id'):
279 account = fiscal_pos_obj.map_account(cr, uid, part and part.property_account_position or False, account.id)
280 account = account_obj.browse(cr, uid, account, context=context)
281 data['account_id'] = account and account.id or False
282 #compute the amount in secondary currency of the account, if needed
283 if account and account.currency_id:
284 data['currency_id'] = account.currency_id.id
285 #set the context for the multi currency change
286 compute_ctx = context.copy()
288 #the following 2 parameters are used to choose the currency rate, in case where the account
289 #doesn't work with an outgoing currency rate method 'at date' but 'average'
290 'res.currency.compute.account': account,
291 'res.currency.compute.account_invert': True,
294 compute_ctx.update({'date': data['date']})
295 data['amount_currency'] = currency_obj.compute(cr, uid, account.company_id.currency_id.id, data['currency_id'], -total, context=compute_ctx)
296 data = self._default_get_move_form_hook(cr, uid, data)
299 def on_create_write(self, cr, uid, id, context=None):
302 ml = self.browse(cr, uid, id, context=context)
303 return map(lambda x: x.id, ml.move_id.line_id)
305 def _balance(self, cr, uid, ids, name, arg, context=None):
309 c['initital_bal'] = True
310 sql = """SELECT l1.id, COALESCE(SUM(l2.debit-l2.credit), 0)
311 FROM account_move_line l1 LEFT JOIN account_move_line l2
312 ON (l1.account_id = l2.account_id
315 self._query_get(cr, uid, obj='l2', context=c) + \
316 ") WHERE l1.id IN %s GROUP BY l1.id"
318 cr.execute(sql, [tuple(ids)])
319 return dict(cr.fetchall())
321 def _invoice(self, cursor, user, ids, name, arg, context=None):
322 invoice_obj = self.pool.get('account.invoice')
326 cursor.execute('SELECT l.id, i.id ' \
327 'FROM account_move_line l, account_invoice i ' \
328 'WHERE l.move_id = i.move_id ' \
332 for line_id, invoice_id in cursor.fetchall():
333 res[line_id] = invoice_id
334 invoice_ids.append(invoice_id)
335 invoice_names = {False: ''}
336 for invoice_id, name in invoice_obj.name_get(cursor, user, invoice_ids, context=context):
337 invoice_names[invoice_id] = name
338 for line_id in res.keys():
339 invoice_id = res[line_id]
340 res[line_id] = (invoice_id, invoice_names[invoice_id])
343 def name_get(self, cr, uid, ids, context=None):
347 for line in self.browse(cr, uid, ids, context=context):
349 result.append((line.id, (line.move_id.name or '')+' ('+line.ref+')'))
351 result.append((line.id, line.move_id.name))
354 def _balance_search(self, cursor, user, obj, name, args, domain=None, context=None):
359 where = ' AND '.join(map(lambda x: '(abs(sum(debit-credit))'+x[1]+str(x[2])+')',args))
360 cursor.execute('SELECT id, SUM(debit-credit) FROM account_move_line \
361 GROUP BY id, debit, credit having '+where)
362 res = cursor.fetchall()
364 return [('id', '=', '0')]
365 return [('id', 'in', [x[0] for x in res])]
367 def _invoice_search(self, cursor, user, obj, name, args, context=None):
370 invoice_obj = self.pool.get('account.invoice')
373 fargs = args[i][0].split('.', 1)
375 args[i] = (fargs[0], 'in', invoice_obj.search(cursor, user,
376 [(fargs[1], args[i][1], args[i][2])]))
379 if isinstance(args[i][2], basestring):
380 res_ids = invoice_obj.name_search(cursor, user, args[i][2], [],
382 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
387 if (x[2] is False) and (x[1] == '='):
388 qu1.append('(i.id IS NULL)')
389 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
390 qu1.append('(i.id IS NOT NULL)')
392 qu1.append('(i.id %s %s)' % (x[1], '%s'))
396 qu1.append('(i.id IN (%s))' % (','.join(['%s'] * len(x[2]))))
399 qu1.append(' (False)')
401 qu1 = ' AND' + ' AND'.join(qu1)
404 cursor.execute('SELECT l.id ' \
405 'FROM account_move_line l, account_invoice i ' \
406 'WHERE l.move_id = i.move_id ' + qu1, qu2)
407 res = cursor.fetchall()
409 return [('id', '=', '0')]
410 return [('id', 'in', [x[0] for x in res])]
412 def _get_move_lines(self, cr, uid, ids, context=None):
414 for move in self.pool.get('account.move').browse(cr, uid, ids, context=context):
415 for line in move.line_id:
416 result.append(line.id)
419 def _get_reconcile(self, cr, uid, ids,name, unknow_none, context=None):
420 res = dict.fromkeys(ids, False)
421 for line in self.browse(cr, uid, ids, context=context):
422 if line.reconcile_id:
423 res[line.id] = str(line.reconcile_id.name)
424 elif line.reconcile_partial_id:
425 res[line.id] = str(line.reconcile_partial_id.name)
428 def _get_move_from_reconcile(self, cr, uid, ids, context=None):
430 for r in self.pool.get('account.move.reconcile').browse(cr, uid, ids, context=context):
431 for line in r.line_partial_ids:
432 move[line.move_id.id] = True
433 for line in r.line_id:
434 move[line.move_id.id] = True
437 move_line_ids = self.pool.get('account.move.line').search(cr, uid, [('journal_id','in',move.keys())], context=context)
442 'name': fields.char('Name', required=True),
443 '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."),
444 'product_uom_id': fields.many2one('product.uom', 'Unit of Measure'),
445 'product_id': fields.many2one('product.product', 'Product'),
446 'debit': fields.float('Debit', digits_compute=dp.get_precision('Account')),
447 'credit': fields.float('Credit', digits_compute=dp.get_precision('Account')),
448 'account_id': fields.many2one('account.account', 'Account', required=True, ondelete="cascade", domain=[('type','<>','view'), ('type', '<>', 'closed')], select=2),
449 'move_id': fields.many2one('account.move', 'Journal Entry', ondelete="cascade", help="The move of this entry line.", select=2, required=True),
450 'narration': fields.related('move_id','narration', type='text', relation='account.move', string='Internal Note'),
451 'ref': fields.related('move_id', 'ref', string='Reference', type='char', store=True),
452 'statement_id': fields.many2one('account.bank.statement', 'Statement', help="The bank statement used for bank reconciliation", select=1, copy=False),
453 'reconcile_id': fields.many2one('account.move.reconcile', 'Reconcile', readonly=True, ondelete='set null', select=2, copy=False),
454 'reconcile_partial_id': fields.many2one('account.move.reconcile', 'Partial Reconcile', readonly=True, ondelete='set null', select=2, copy=False),
455 'reconcile_ref': fields.function(_get_reconcile, type='char', string='Reconcile Ref', oldname='reconcile', store={
456 'account.move.line': (lambda self, cr, uid, ids, c={}: ids, ['reconcile_id','reconcile_partial_id'], 50),'account.move.reconcile': (_get_move_from_reconcile, None, 50)}),
457 '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')),
458 'amount_residual_currency': fields.function(_amount_residual, string='Residual Amount in Currency', multi="residual", help="The residual amount on a receivable or payable of a journal entry expressed in its currency (maybe different of the company currency)."),
459 'amount_residual': fields.function(_amount_residual, string='Residual Amount', multi="residual", help="The residual amount on a receivable or payable of a journal entry expressed in the company currency."),
460 'currency_id': fields.many2one('res.currency', 'Currency', help="The optional other currency if it is a multi-currency entry."),
461 'journal_id': fields.related('move_id', 'journal_id', string='Journal', type='many2one', relation='account.journal', required=True, select=True,
463 'account.move': (_get_move_lines, ['journal_id'], 20)
465 'period_id': fields.related('move_id', 'period_id', string='Period', type='many2one', relation='account.period', required=True, select=True,
467 'account.move': (_get_move_lines, ['period_id'], 20)
469 'blocked': fields.boolean('No Follow-up', help="You can check this box to mark this journal item as a litigation with the associated partner"),
470 'partner_id': fields.many2one('res.partner', 'Partner', select=1, ondelete='restrict'),
471 'date_maturity': fields.date('Due date', select=True ,help="This field is used for payable and receivable journal entries. You can put the limit date for the payment of this line."),
472 'date': fields.related('move_id','date', string='Effective date', type='date', required=True, select=True,
474 'account.move': (_get_move_lines, ['date'], 20)
476 'date_created': fields.date('Creation date', select=True),
477 'analytic_lines': fields.one2many('account.analytic.line', 'move_id', 'Analytic lines'),
478 'centralisation': fields.selection([('normal','Normal'),('credit','Credit Centralisation'),('debit','Debit Centralisation'),('currency','Currency Adjustment')], 'Centralisation', size=8),
479 'balance': fields.function(_balance, fnct_search=_balance_search, string='Balance'),
480 'state': fields.selection([('draft','Unbalanced'), ('valid','Balanced')], 'Status', readonly=True, copy=False),
481 '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."),
482 '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, "\
483 "this field will contain the basic amount(without tax)."),
484 'invoice': fields.function(_invoice, string='Invoice',
485 type='many2one', relation='account.invoice', fnct_search=_invoice_search),
486 'account_tax_id':fields.many2one('account.tax', 'Tax', copy=False),
487 'analytic_account_id': fields.many2one('account.analytic.account', 'Analytic Account'),
488 'company_id': fields.related('account_id', 'company_id', type='many2one', relation='res.company',
489 string='Company', store=True, readonly=True)
492 def _get_date(self, cr, uid, context=None):
495 period_obj = self.pool.get('account.period')
496 dt = time.strftime('%Y-%m-%d')
497 if context.get('journal_id') and context.get('period_id'):
498 cr.execute('SELECT date FROM account_move_line ' \
499 'WHERE journal_id = %s AND period_id = %s ' \
500 'ORDER BY id DESC limit 1',
501 (context['journal_id'], context['period_id']))
506 period = period_obj.browse(cr, uid, context['period_id'], context=context)
507 dt = period.date_start
510 def _get_currency(self, cr, uid, context=None):
513 if not context.get('journal_id', False):
515 cur = self.pool.get('account.journal').browse(cr, uid, context['journal_id']).currency
516 return cur and cur.id or False
518 def _get_period(self, cr, uid, context=None):
520 Return default account period value
522 context = context or {}
523 if context.get('period_id', False):
524 return context['period_id']
525 account_period_obj = self.pool.get('account.period')
526 ids = account_period_obj.find(cr, uid, context=context)
532 def _get_journal(self, cr, uid, context=None):
534 Return journal based on the journal type
536 context = context or {}
537 if context.get('journal_id', False):
538 return context['journal_id']
541 journal_pool = self.pool.get('account.journal')
542 if context.get('journal_type', False):
543 jids = journal_pool.search(cr, uid, [('type','=', context.get('journal_type'))])
545 model, action_id = self.pool['ir.model.data'].get_object_reference(cr, uid, 'account', 'action_account_journal_form')
546 msg = _("""Cannot find any account journal of "%s" type for this company, You should create one.\n Please go to Journal Configuration""") % context.get('journal_type').replace('_', ' ').title()
547 raise openerp.exceptions.RedirectWarning(msg, action_id, _('Go to the configuration panel'))
554 'centralisation': 'normal',
556 'date_created': fields.date.context_today,
558 'currency_id': _get_currency,
559 'journal_id': _get_journal,
562 'amount_currency': 0.0,
563 'account_id': lambda self, cr, uid, c: c.get('account_id', False),
564 'period_id': _get_period,
565 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.move.line', context=c)
567 _order = "date desc, id desc"
569 ('credit_debit1', 'CHECK (credit*debit=0)', 'Wrong credit or debit value in accounting entry !'),
570 ('credit_debit2', 'CHECK (credit+debit>=0)', 'Wrong credit or debit value in accounting entry !'),
573 def _auto_init(self, cr, context=None):
574 res = super(account_move_line, self)._auto_init(cr, context=context)
575 cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = \'account_move_line_journal_id_period_id_index\'')
576 if not cr.fetchone():
577 cr.execute('CREATE INDEX account_move_line_journal_id_period_id_index ON account_move_line (journal_id, period_id)')
578 cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = %s', ('account_move_line_date_id_index',))
579 if not cr.fetchone():
580 cr.execute('CREATE INDEX account_move_line_date_id_index ON account_move_line (date DESC, id desc)')
583 def _check_no_view(self, cr, uid, ids, context=None):
584 lines = self.browse(cr, uid, ids, context=context)
586 if l.account_id.type in ('view', 'consolidation'):
590 def _check_no_closed(self, cr, uid, ids, context=None):
591 lines = self.browse(cr, uid, ids, context=context)
593 if l.account_id.type == 'closed':
594 raise osv.except_osv(_('Error!'), _('You cannot create journal items on a closed account %s %s.') % (l.account_id.code, l.account_id.name))
597 def _check_company_id(self, cr, uid, ids, context=None):
598 lines = self.browse(cr, uid, ids, context=context)
600 if l.company_id != l.account_id.company_id or l.company_id != l.period_id.company_id:
604 def _check_date(self, cr, uid, ids, context=None):
605 for l in self.browse(cr, uid, ids, context=context):
606 if l.journal_id.allow_date:
607 if not time.strptime(l.date[:10],'%Y-%m-%d') >= time.strptime(l.period_id.date_start, '%Y-%m-%d') or not time.strptime(l.date[:10], '%Y-%m-%d') <= time.strptime(l.period_id.date_stop, '%Y-%m-%d'):
611 def _check_currency(self, cr, uid, ids, context=None):
612 for l in self.browse(cr, uid, ids, context=context):
613 if l.account_id.currency_id:
614 if not l.currency_id or not l.currency_id.id == l.account_id.currency_id.id:
618 def _check_currency_and_amount(self, cr, uid, ids, context=None):
619 for l in self.browse(cr, uid, ids, context=context):
620 if (l.amount_currency and not l.currency_id):
624 def _check_currency_amount(self, cr, uid, ids, context=None):
625 for l in self.browse(cr, uid, ids, context=context):
626 if l.amount_currency:
627 if (l.amount_currency > 0.0 and l.credit > 0.0) or (l.amount_currency < 0.0 and l.debit > 0.0):
631 def _check_currency_company(self, cr, uid, ids, context=None):
632 for l in self.browse(cr, uid, ids, context=context):
633 if l.currency_id.id == l.company_id.currency_id.id:
638 (_check_no_view, 'You cannot create journal items on an account of type view or consolidation.', ['account_id']),
639 (_check_no_closed, 'You cannot create journal items on closed account.', ['account_id']),
640 (_check_company_id, 'Account and Period must belong to the same company.', ['company_id']),
641 (_check_date, 'The date of your Journal Entry is not in the defined period! You should change the date or remove this constraint from the journal.', ['date']),
642 (_check_currency, 'The selected account of your Journal Entry forces to provide a secondary currency. You should remove the secondary currency on the account or select a multi-currency view on the journal.', ['currency_id']),
643 (_check_currency_and_amount, "You cannot create journal items with a secondary currency without recording both 'currency' and 'amount currency' field.", ['currency_id','amount_currency']),
644 (_check_currency_amount, 'The amount expressed in the secondary currency must be positive when account is debited and negative when account is credited.', ['amount_currency']),
645 (_check_currency_company, "You cannot provide a secondary currency if it is the same than the company one." , ['currency_id']),
648 #TODO: ONCHANGE_ACCOUNT_ID: set account_tax_id
649 def onchange_currency(self, cr, uid, ids, account_id, amount, currency_id, date=False, journal=False, context=None):
652 account_obj = self.pool.get('account.account')
653 journal_obj = self.pool.get('account.journal')
654 currency_obj = self.pool.get('res.currency')
655 if (not currency_id) or (not account_id):
658 acc = account_obj.browse(cr, uid, account_id, context=context)
659 if (amount>0) and journal:
660 x = journal_obj.browse(cr, uid, journal).default_credit_account_id
662 context = dict(context)
665 'res.currency.compute.account': acc,
667 v = currency_obj.compute(cr, uid, currency_id, acc.company_id.currency_id.id, amount, context=context)
669 'debit': v > 0 and v or 0.0,
670 'credit': v < 0 and -v or 0.0
674 def onchange_partner_id(self, cr, uid, ids, move_id, partner_id, account_id=None, debit=0, credit=0, date=False, journal=False, context=None):
675 partner_obj = self.pool.get('res.partner')
676 payment_term_obj = self.pool.get('account.payment.term')
677 journal_obj = self.pool.get('account.journal')
678 fiscal_pos_obj = self.pool.get('account.fiscal.position')
680 val['date_maturity'] = False
685 date = datetime.now().strftime('%Y-%m-%d')
688 jt = journal_obj.browse(cr, uid, journal, context=context).type
689 part = partner_obj.browse(cr, uid, partner_id, context=context)
691 payment_term_id = False
692 if jt and jt in ('purchase', 'purchase_refund') and part.property_supplier_payment_term:
693 payment_term_id = part.property_supplier_payment_term.id
694 elif jt and part.property_payment_term:
695 payment_term_id = part.property_payment_term.id
697 res = payment_term_obj.compute(cr, uid, payment_term_id, 100, date)
699 val['date_maturity'] = res[0][0]
701 id1 = part.property_account_payable.id
702 id2 = part.property_account_receivable.id
704 if jt in ('sale', 'purchase_refund'):
705 val['account_id'] = fiscal_pos_obj.map_account(cr, uid, part and part.property_account_position or False, id2)
706 elif jt in ('purchase', 'sale_refund'):
707 val['account_id'] = fiscal_pos_obj.map_account(cr, uid, part and part.property_account_position or False, id1)
708 elif jt in ('general', 'bank', 'cash'):
710 val['account_id'] = fiscal_pos_obj.map_account(cr, uid, part and part.property_account_position or False, id2)
712 val['account_id'] = fiscal_pos_obj.map_account(cr, uid, part and part.property_account_position or False, id1)
713 if val.get('account_id', False):
714 d = self.onchange_account_id(cr, uid, ids, account_id=val['account_id'], partner_id=part.id, context=context)
715 val.update(d['value'])
718 def onchange_account_id(self, cr, uid, ids, account_id=False, partner_id=False, context=None):
719 account_obj = self.pool.get('account.account')
720 partner_obj = self.pool.get('res.partner')
721 fiscal_pos_obj = self.pool.get('account.fiscal.position')
724 res = account_obj.browse(cr, uid, account_id, context=context)
725 tax_ids = res.tax_ids
726 if tax_ids and partner_id:
727 part = partner_obj.browse(cr, uid, partner_id, context=context)
728 tax_id = fiscal_pos_obj.map_tax(cr, uid, part and part.property_account_position or False, tax_ids)[0]
730 tax_id = tax_ids and tax_ids[0].id or False
731 val['account_tax_id'] = tax_id
732 return {'value': val}
734 # type: the type if reconciliation (no logic behind this field, for info)
736 # writeoff; entry generated for the difference between the lines
738 def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False):
741 if context.get('fiscalyear'):
742 args.append(('period_id.fiscalyear_id', '=', context.get('fiscalyear', False)))
743 if context and context.get('next_partner_only', False):
744 if not context.get('partner_id', False):
745 partner = self.list_partners_to_reconcile(cr, uid, context=context)
749 partner = context.get('partner_id', False)
752 args.append(('partner_id', '=', partner[0]))
753 return super(account_move_line, self).search(cr, uid, args, offset, limit, order, context, count)
755 def list_partners_to_reconcile(self, cr, uid, context=None):
757 """SELECT partner_id FROM (
758 SELECT l.partner_id, p.last_reconciliation_date, SUM(l.debit) AS debit, SUM(l.credit) AS credit, MAX(l.create_date) AS max_date
759 FROM account_move_line l
760 RIGHT JOIN account_account a ON (a.id = l.account_id)
761 RIGHT JOIN res_partner p ON (l.partner_id = p.id)
762 WHERE a.reconcile IS TRUE
763 AND l.reconcile_id IS NULL
764 AND l.state <> 'draft'
765 GROUP BY l.partner_id, p.last_reconciliation_date
767 WHERE debit > 0 AND credit > 0 AND (last_reconciliation_date IS NULL OR max_date > last_reconciliation_date)
768 ORDER BY last_reconciliation_date""")
769 ids = [x[0] for x in cr.fetchall()]
773 # To apply the ir_rules
774 partner_obj = self.pool.get('res.partner')
775 ids = partner_obj.search(cr, uid, [('id', 'in', ids)], context=context)
776 return partner_obj.name_get(cr, uid, ids, context=context)
778 def reconcile_partial(self, cr, uid, ids, type='auto', context=None, writeoff_acc_id=False, writeoff_period_id=False, writeoff_journal_id=False):
779 move_rec_obj = self.pool.get('account.move.reconcile')
787 for line in self.browse(cr, uid, ids, context=context):
788 if company_list and not line.company_id.id in company_list:
789 raise osv.except_osv(_('Warning!'), _('To reconcile the entries company should be the same for all entries.'))
790 company_list.append(line.company_id.id)
792 for line in self.browse(cr, uid, ids, context=context):
793 if line.account_id.currency_id:
794 currency_id = line.account_id.currency_id
796 currency_id = line.company_id.currency_id
797 if line.reconcile_id:
798 raise osv.except_osv(_('Warning'), _("Journal Item '%s' (id: %s), Move '%s' is already reconciled!") % (line.name, line.id, line.move_id.name))
799 if line.reconcile_partial_id:
800 for line2 in line.reconcile_partial_id.line_partial_ids:
801 if line2.state != 'valid':
802 raise osv.except_osv(_('Warning'), _("Journal Item '%s' (id: %s) cannot be used in a reconciliation as it is not balanced!") % (line2.name, line2.id))
803 if not line2.reconcile_id:
804 if line2.id not in merges:
805 merges.append(line2.id)
806 if line2.account_id.currency_id:
807 total += line2.amount_currency
809 total += (line2.debit or 0.0) - (line2.credit or 0.0)
810 merges_rec.append(line.reconcile_partial_id.id)
812 unmerge.append(line.id)
813 if line.account_id.currency_id:
814 total += line.amount_currency
816 total += (line.debit or 0.0) - (line.credit or 0.0)
817 if self.pool.get('res.currency').is_zero(cr, uid, currency_id, total):
818 res = self.reconcile(cr, uid, merges+unmerge, context=context, writeoff_acc_id=writeoff_acc_id, writeoff_period_id=writeoff_period_id, writeoff_journal_id=writeoff_journal_id)
820 r_id = move_rec_obj.create(cr, uid, {
822 'line_partial_ids': map(lambda x: (4,x,False), merges+unmerge)
824 move_rec_obj.reconcile_partial_check(cr, uid, [r_id] + merges_rec, context=context)
827 def reconcile(self, cr, uid, ids, type='auto', writeoff_acc_id=False, writeoff_period_id=False, writeoff_journal_id=False, context=None):
828 account_obj = self.pool.get('account.account')
829 move_obj = self.pool.get('account.move')
830 move_rec_obj = self.pool.get('account.move.reconcile')
831 partner_obj = self.pool.get('res.partner')
832 currency_obj = self.pool.get('res.currency')
833 lines = self.browse(cr, uid, ids, context=context)
834 unrec_lines = filter(lambda x: not x['reconcile_id'], lines)
842 for line in self.browse(cr, uid, ids, context=context):
843 if company_list and not line.company_id.id in company_list:
844 raise osv.except_osv(_('Warning!'), _('To reconcile the entries company should be the same for all entries.'))
845 company_list.append(line.company_id.id)
846 for line in unrec_lines:
847 if line.state <> 'valid':
848 raise osv.except_osv(_('Error!'),
849 _('Entry "%s" is not valid !') % line.name)
850 credit += line['credit']
851 debit += line['debit']
852 currency += line['amount_currency'] or 0.0
853 account_id = line['account_id']['id']
854 partner_id = (line['partner_id'] and line['partner_id']['id']) or False
855 writeoff = debit - credit
857 # Ifdate_p in context => take this date
858 if context.has_key('date_p') and context['date_p']:
859 date=context['date_p']
861 date = time.strftime('%Y-%m-%d')
863 cr.execute('SELECT account_id, reconcile_id '\
864 'FROM account_move_line '\
866 'GROUP BY account_id,reconcile_id',
869 #TODO: move this check to a constraint in the account_move_reconcile object
871 raise osv.except_osv(_('Error'), _('Entries are not of the same account or already reconciled ! '))
873 raise osv.except_osv(_('Error!'), _('Entry is already reconciled.'))
874 account = account_obj.browse(cr, uid, account_id, context=context)
875 if not account.reconcile:
876 raise osv.except_osv(_('Error'), _('The account is not defined to be reconciled !'))
878 raise osv.except_osv(_('Error!'), _('Some entries are already reconciled.'))
880 if (not currency_obj.is_zero(cr, uid, account.company_id.currency_id, writeoff)) or \
881 (account.currency_id and (not currency_obj.is_zero(cr, uid, account.currency_id, currency))):
882 if not writeoff_acc_id:
883 raise osv.except_osv(_('Warning!'), _('You have to provide an account for the write off/exchange difference entry.'))
887 self_credit = writeoff
893 self_debit = -writeoff
894 # If comment exist in context, take it
895 if 'comment' in context and context['comment']:
896 libelle = context['comment']
898 libelle = _('Write-Off')
900 cur_obj = self.pool.get('res.currency')
902 amount_currency_writeoff = 0.0
903 if context.get('company_currency_id',False) != context.get('currency_id',False):
904 cur_id = context.get('currency_id',False)
905 for line in unrec_lines:
906 if line.currency_id and line.currency_id.id == context.get('currency_id',False):
907 amount_currency_writeoff += line.amount_currency
909 tmp_amount = cur_obj.compute(cr, uid, line.account_id.company_id.currency_id.id, context.get('currency_id',False), abs(line.debit-line.credit), context={'date': line.date})
910 amount_currency_writeoff += (line.debit > 0) and tmp_amount or -tmp_amount
916 'credit': self_credit,
917 'account_id': account_id,
919 'partner_id': partner_id,
920 'currency_id': cur_id or (account.currency_id.id or False),
921 'amount_currency': amount_currency_writeoff and -1 * amount_currency_writeoff or (account.currency_id.id and -1 * currency or 0.0)
927 'account_id': writeoff_acc_id,
928 'analytic_account_id': context.get('analytic_id', False),
930 'partner_id': partner_id,
931 'currency_id': cur_id or (account.currency_id.id or False),
932 'amount_currency': amount_currency_writeoff and amount_currency_writeoff or (account.currency_id.id and currency or 0.0)
936 writeoff_move_id = move_obj.create(cr, uid, {
937 'period_id': writeoff_period_id,
938 'journal_id': writeoff_journal_id,
941 'line_id': writeoff_lines
944 writeoff_line_ids = self.search(cr, uid, [('move_id', '=', writeoff_move_id), ('account_id', '=', account_id)])
945 if account_id == writeoff_acc_id:
946 writeoff_line_ids = [writeoff_line_ids[1]]
947 ids += writeoff_line_ids
949 r_id = move_rec_obj.create(cr, uid, {
951 'line_id': map(lambda x: (4, x, False), ids),
952 'line_partial_ids': map(lambda x: (3, x, False), ids)
954 # the id of the move.reconcile is written in the move.line (self) by the create method above
955 # because of the way the line_id are defined: (4, x, False)
957 workflow.trg_trigger(uid, 'account.move.line', id, cr)
959 if lines and lines[0]:
960 partner_id = lines[0].partner_id and lines[0].partner_id.id or False
961 if partner_id and not partner_obj.has_something_to_reconcile(cr, uid, partner_id, context=context):
962 partner_obj.mark_as_reconciled(cr, uid, [partner_id], context=context)
965 def view_header_get(self, cr, user, view_id, view_type, context=None):
968 context = self.convert_to_period(cr, user, context=context)
969 if context.get('account_id', False):
970 cr.execute('SELECT code FROM account_account WHERE id = %s', (context['account_id'], ))
973 res = _('Entries: ')+ (res[0] or '')
975 if (not context.get('journal_id', False)) or (not context.get('period_id', False)):
977 if context.get('search_default_journal_id', False):
978 context['journal_id'] = context.get('search_default_journal_id')
979 cr.execute('SELECT code FROM account_journal WHERE id = %s', (context['journal_id'], ))
980 j = cr.fetchone()[0] or ''
981 cr.execute('SELECT code FROM account_period WHERE id = %s', (context['period_id'], ))
982 p = cr.fetchone()[0] or ''
984 return j + (p and (':' + p) or '')
987 def onchange_date(self, cr, user, ids, date, context=None):
989 Returns a dict that contains new values and context
990 @param cr: A database cursor
991 @param user: ID of the user currently logged in
992 @param date: latest value from user input for field date
993 @param args: other arguments
994 @param context: context arguments, like lang, time zone
995 @return: Returns a dict which contains new values, and context
1000 period_pool = self.pool.get('account.period')
1001 pids = period_pool.find(cr, user, date, context=context)
1003 res.update({'period_id':pids[0]})
1004 context = dict(context, period_id=pids[0])
1010 def _check_moves(self, cr, uid, context=None):
1011 # use the first move ever created for this journal and period
1014 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']))
1017 if res[1] != 'draft':
1018 raise osv.except_osv(_('User Error!'),
1019 _('The account move (%s) for centralisation ' \
1020 'has been confirmed.') % res[2])
1023 def _remove_move_reconcile(self, cr, uid, move_ids=None, opening_reconciliation=False, context=None):
1024 # Function remove move rencocile ids related with moves
1025 obj_move_line = self.pool.get('account.move.line')
1026 obj_move_rec = self.pool.get('account.move.reconcile')
1030 recs = obj_move_line.read(cr, uid, move_ids, ['reconcile_id', 'reconcile_partial_id'])
1031 full_recs = filter(lambda x: x['reconcile_id'], recs)
1032 rec_ids = [rec['reconcile_id'][0] for rec in full_recs]
1033 part_recs = filter(lambda x: x['reconcile_partial_id'], recs)
1034 part_rec_ids = [rec['reconcile_partial_id'][0] for rec in part_recs]
1035 unlink_ids += rec_ids
1036 unlink_ids += part_rec_ids
1037 all_moves = obj_move_line.search(cr, uid, ['|',('reconcile_id', 'in', unlink_ids),('reconcile_partial_id', 'in', unlink_ids)])
1038 all_moves = list(set(all_moves) - set(move_ids))
1040 if opening_reconciliation:
1041 raise osv.except_osv(_('Warning!'),
1042 _('Opening Entries have already been generated. Please run "Cancel Closing Entries" wizard to cancel those entries and then run this wizard.'))
1043 obj_move_rec.write(cr, uid, unlink_ids, {'opening_reconciliation': False})
1044 obj_move_rec.unlink(cr, uid, unlink_ids)
1045 if len(all_moves) >= 2:
1046 obj_move_line.reconcile_partial(cr, uid, all_moves, 'auto',context=context)
1049 def unlink(self, cr, uid, ids, context=None, check=True):
1052 move_obj = self.pool.get('account.move')
1053 self._update_check(cr, uid, ids, context)
1056 for line in self.browse(cr, uid, ids, context=context):
1057 move_ids.add(line.move_id.id)
1058 context['journal_id'] = line.journal_id.id
1059 context['period_id'] = line.period_id.id
1060 result = super(account_move_line, self).unlink(cr, uid, [line.id], context=context)
1061 move_ids = list(move_ids)
1062 if check and move_ids:
1063 move_obj.validate(cr, uid, move_ids, context=context)
1066 def write(self, cr, uid, ids, vals, context=None, check=True, update_check=True):
1069 move_obj = self.pool.get('account.move')
1070 account_obj = self.pool.get('account.account')
1071 journal_obj = self.pool.get('account.journal')
1072 if isinstance(ids, (int, long)):
1074 if vals.get('account_tax_id', False):
1075 raise osv.except_osv(_('Unable to change tax!'), _('You cannot change the tax, you should remove and recreate lines.'))
1076 if ('account_id' in vals) and not account_obj.read(cr, uid, vals['account_id'], ['active'])['active']:
1077 raise osv.except_osv(_('Bad Account!'), _('You cannot use an inactive account.'))
1079 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):
1080 self._update_check(cr, uid, ids, context)
1083 if vals.get('date', False):
1084 todo_date = vals['date']
1087 for line in self.browse(cr, uid, ids, context=context):
1088 ctx = context.copy()
1089 if not ctx.get('journal_id'):
1091 ctx['journal_id'] = line.move_id.journal_id.id
1093 ctx['journal_id'] = line.journal_id.id
1094 if not ctx.get('period_id'):
1096 ctx['period_id'] = line.move_id.period_id.id
1098 ctx['period_id'] = line.period_id.id
1099 #Check for centralisation
1100 journal = journal_obj.browse(cr, uid, ctx['journal_id'], context=ctx)
1101 if journal.centralisation:
1102 self._check_moves(cr, uid, context=ctx)
1103 result = super(account_move_line, self).write(cr, uid, ids, vals, context)
1106 for line in self.browse(cr, uid, ids):
1107 if line.move_id.id not in done:
1108 done.append(line.move_id.id)
1109 move_obj.validate(cr, uid, [line.move_id.id], context)
1111 move_obj.write(cr, uid, [line.move_id.id], {'date': todo_date}, context=context)
1114 def _update_journal_check(self, cr, uid, journal_id, period_id, context=None):
1115 journal_obj = self.pool.get('account.journal')
1116 period_obj = self.pool.get('account.period')
1117 jour_period_obj = self.pool.get('account.journal.period')
1118 cr.execute('SELECT state FROM account_journal_period WHERE journal_id = %s AND period_id = %s', (journal_id, period_id))
1119 result = cr.fetchall()
1120 journal = journal_obj.browse(cr, uid, journal_id, context=context)
1121 period = period_obj.browse(cr, uid, period_id, context=context)
1122 for (state,) in result:
1124 raise osv.except_osv(_('Error!'), _('You can not add/modify entries in a closed period %s of journal %s.' % (period.name,journal.name)))
1126 jour_period_obj.create(cr, uid, {
1127 'name': (journal.code or journal.name)+':'+(period.name or ''),
1128 'journal_id': journal.id,
1129 'period_id': period.id
1133 def _update_check(self, cr, uid, ids, context=None):
1135 for line in self.browse(cr, uid, ids, context=context):
1136 err_msg = _('Move name (id): %s (%s)') % (line.move_id.name, str(line.move_id.id))
1137 if line.move_id.state <> 'draft' and (not line.journal_id.entry_posted):
1138 raise osv.except_osv(_('Error!'), _('You cannot do this modification on a confirmed entry. You can just change some non legal fields or you must unconfirm the journal entry first.\n%s.') % err_msg)
1139 if line.reconcile_id:
1140 raise osv.except_osv(_('Error!'), _('You cannot do this modification on a reconciled entry. You can just change some non legal fields or you must unreconcile first.\n%s.') % err_msg)
1141 t = (line.journal_id.id, line.period_id.id)
1143 self._update_journal_check(cr, uid, line.journal_id.id, line.period_id.id, context)
1147 def create(self, cr, uid, vals, context=None, check=True):
1148 account_obj = self.pool.get('account.account')
1149 tax_obj = self.pool.get('account.tax')
1150 move_obj = self.pool.get('account.move')
1151 cur_obj = self.pool.get('res.currency')
1152 journal_obj = self.pool.get('account.journal')
1153 context = dict(context or {})
1154 if vals.get('move_id', False):
1155 move = self.pool.get('account.move').browse(cr, uid, vals['move_id'], context=context)
1157 vals['company_id'] = move.company_id.id
1158 if move.date and not vals.get('date'):
1159 vals['date'] = move.date
1160 if ('account_id' in vals) and not account_obj.read(cr, uid, [vals['account_id']], ['active'])[0]['active']:
1161 raise osv.except_osv(_('Bad Account!'), _('You cannot use an inactive account.'))
1162 if 'journal_id' in vals and vals['journal_id']:
1163 context['journal_id'] = vals['journal_id']
1164 if 'period_id' in vals and vals['period_id']:
1165 context['period_id'] = vals['period_id']
1166 if ('journal_id' not in context) and ('move_id' in vals) and vals['move_id']:
1167 m = move_obj.browse(cr, uid, vals['move_id'])
1168 context['journal_id'] = m.journal_id.id
1169 context['period_id'] = m.period_id.id
1170 #we need to treat the case where a value is given in the context for period_id as a string
1171 if 'period_id' in context and not isinstance(context.get('period_id', ''), (int, long)):
1172 period_candidate_ids = self.pool.get('account.period').name_search(cr, uid, name=context.get('period_id',''))
1173 if len(period_candidate_ids) != 1:
1174 raise osv.except_osv(_('Error!'), _('No period found or more than one period found for the given date.'))
1175 context['period_id'] = period_candidate_ids[0][0]
1176 if not context.get('journal_id', False) and context.get('search_default_journal_id', False):
1177 context['journal_id'] = context.get('search_default_journal_id')
1178 self._update_journal_check(cr, uid, context['journal_id'], context['period_id'], context)
1179 move_id = vals.get('move_id', False)
1180 journal = journal_obj.browse(cr, uid, context['journal_id'], context=context)
1181 vals['journal_id'] = vals.get('journal_id') or context.get('journal_id')
1182 vals['period_id'] = vals.get('period_id') or context.get('period_id')
1183 vals['date'] = vals.get('date') or context.get('date')
1185 if journal.centralisation:
1186 #Check for centralisation
1187 res = self._check_moves(cr, uid, context)
1189 vals['move_id'] = res[0]
1190 if not vals.get('move_id', False):
1191 if journal.sequence_id:
1192 #name = self.pool.get('ir.sequence').next_by_id(cr, uid, journal.sequence_id.id)
1194 'date': vals.get('date', time.strftime('%Y-%m-%d')),
1195 'period_id': context['period_id'],
1196 'journal_id': context['journal_id']
1198 if vals.get('ref', ''):
1199 v.update({'ref': vals['ref']})
1200 move_id = move_obj.create(cr, uid, v, context)
1201 vals['move_id'] = move_id
1203 raise osv.except_osv(_('No Piece Number!'), _('Cannot create an automatic sequence for this piece.\nPut a sequence in the journal definition for automatic numbering or create a sequence manually for this piece.'))
1204 ok = not (journal.type_control_ids or journal.account_control_ids)
1205 if ('account_id' in vals):
1206 account = account_obj.browse(cr, uid, vals['account_id'], context=context)
1207 if journal.type_control_ids:
1208 type = account.user_type
1209 for t in journal.type_control_ids:
1210 if type.code == t.code:
1213 if journal.account_control_ids and not ok:
1214 for a in journal.account_control_ids:
1215 if a.id == vals['account_id']:
1218 # Automatically convert in the account's secondary currency if there is one and
1219 # the provided values were not already multi-currency
1220 if account.currency_id and 'amount_currency' not in vals and account.currency_id.id != account.company_id.currency_id.id:
1221 vals['currency_id'] = account.currency_id.id
1224 ctx['date'] = vals['date']
1225 vals['amount_currency'] = cur_obj.compute(cr, uid, account.company_id.currency_id.id,
1226 account.currency_id.id, vals.get('debit', 0.0)-vals.get('credit', 0.0), context=ctx)
1228 raise osv.except_osv(_('Bad Account!'), _('You cannot use this general account in this journal, check the tab \'Entry Controls\' on the related journal.'))
1230 result = super(account_move_line, self).create(cr, uid, vals, context=context)
1232 if vals.get('account_tax_id', False):
1233 tax_id = tax_obj.browse(cr, uid, vals['account_tax_id'])
1234 total = vals['debit'] - vals['credit']
1235 base_code = 'base_code_id'
1236 tax_code = 'tax_code_id'
1237 account_id = 'account_collected_id'
1238 base_sign = 'base_sign'
1239 tax_sign = 'tax_sign'
1240 if journal.type in ('purchase_refund', 'sale_refund') or (journal.type in ('cash', 'bank') and total < 0):
1241 base_code = 'ref_base_code_id'
1242 tax_code = 'ref_tax_code_id'
1243 account_id = 'account_paid_id'
1244 base_sign = 'ref_base_sign'
1245 tax_sign = 'ref_tax_sign'
1247 for tax in tax_obj.compute_all(cr, uid, [tax_id], total, 1.00, force_excluded=False).get('taxes'):
1248 #create the base movement
1252 if tax_id.price_include:
1253 total = tax['price_unit']
1255 'tax_code_id': tax[base_code],
1256 'tax_amount': tax[base_sign] * abs(total),
1258 if tax_id.price_include:
1259 if tax['price_unit'] < 0:
1260 newvals['credit'] = abs(tax['price_unit'])
1262 newvals['debit'] = tax['price_unit']
1263 self.write(cr, uid, [result], newvals, context=context)
1266 'move_id': vals['move_id'],
1267 'name': tools.ustr(vals['name'] or '') + ' ' + tools.ustr(tax['name'] or ''),
1268 'date': vals['date'],
1269 'partner_id': vals.get('partner_id', False),
1270 'ref': vals.get('ref', False),
1271 'statement_id': vals.get('statement_id', False),
1272 'account_tax_id': False,
1273 'tax_code_id': tax[base_code],
1274 'tax_amount': tax[base_sign] * abs(total),
1275 'account_id': vals['account_id'],
1279 if data['tax_code_id']:
1280 self.create(cr, uid, data, context)
1281 #create the Tax movement
1283 'move_id': vals['move_id'],
1284 'name': tools.ustr(vals['name'] or '') + ' ' + tools.ustr(tax['name'] or ''),
1285 'date': vals['date'],
1286 'partner_id': vals.get('partner_id',False),
1287 'ref': vals.get('ref',False),
1288 'statement_id': vals.get('statement_id', False),
1289 'account_tax_id': False,
1290 'tax_code_id': tax[tax_code],
1291 'tax_amount': tax[tax_sign] * abs(tax['amount']),
1292 'account_id': tax[account_id] or vals['account_id'],
1293 'credit': tax['amount']<0 and -tax['amount'] or 0.0,
1294 'debit': tax['amount']>0 and tax['amount'] or 0.0,
1296 if data['tax_code_id']:
1297 self.create(cr, uid, data, context)
1298 del vals['account_tax_id']
1300 if check and not context.get('novalidate') and ((not context.get('no_store_function')) or journal.entry_posted):
1301 tmp = move_obj.validate(cr, uid, [vals['move_id']], context)
1302 if journal.entry_posted and tmp:
1303 move_obj.button_validate(cr,uid, [vals['move_id']], context)
1306 def list_periods(self, cr, uid, context=None):
1307 ids = self.pool.get('account.period').search(cr,uid,[])
1308 return self.pool.get('account.period').name_get(cr, uid, ids, context=context)
1310 def list_journals(self, cr, uid, context=None):
1311 ng = dict(self.pool.get('account.journal').name_search(cr,uid,'',[]))
1314 for journal in self.pool.get('account.journal').browse(cr, uid, ids, context=context):
1315 result.append((journal.id,ng[journal.id],journal.type,
1316 bool(journal.currency),bool(journal.analytic_journal_id)))
1320 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: