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
25 from openerp import workflow
26 from openerp.osv import fields, osv
27 from openerp.tools.translate import _
28 import openerp.addons.decimal_precision as dp
29 from openerp import tools
30 from openerp.report import report_sxw
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 prepare_move_lines_for_reconciliation_widget(self, cr, uid, lines, target_currency=False, target_date=False, context=None):
756 """ Returns move lines formatted for the manual/bank reconciliation widget
758 :param target_currency: curreny you want the move line debit/credit converted into
759 :param target_date: date to use for the monetary conversion
766 currency_obj = self.pool.get('res.currency')
767 company_currency = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.currency_id
768 rml_parser = report_sxw.rml_parse(cr, uid, 'reconciliation_widget_aml', context=context)
769 reconcile_partial_ids = [] # for a partial reconciliation, take only one line
773 if line.reconcile_partial_id and line.reconcile_partial_id.id in reconcile_partial_ids:
775 partial_reconciliation_siblings_ids = []
776 if line.reconcile_partial_id:
777 reconcile_partial_ids.append(line.reconcile_partial_id.id)
778 partial_reconciliation_siblings_ids = self.search(cr, uid, [('reconcile_partial_id', '=', line.reconcile_partial_id.id)], context=context)
779 partial_reconciliation_siblings_ids.remove(line.id)
783 'name': line.name if line.name != '/' else line.move_id.name,
784 'ref': line.move_id.ref,
785 'account_code': line.account_id.code,
786 'account_name': line.account_id.name,
787 'account_type': line.account_id.type,
788 'date_maturity': line.date_maturity,
790 'period_name': line.period_id.name,
791 'journal_name': line.journal_id.name,
792 'partner_id': line.partner_id.id,
793 'partner_name': line.partner_id.name,
794 'is_partially_reconciled': bool(line.reconcile_partial_id),
795 'partial_reconciliation_siblings_ids': partial_reconciliation_siblings_ids,
798 # Amount residual can be negative
801 total_amount = debit-credit
802 total_amount_currency = line.amount_currency
803 amount_residual = line.amount_residual
804 amount_residual_currency = line.amount_residual_currency
805 if line.amount_residual < 0:
806 debit, credit = credit, debit
807 amount_residual = -amount_residual
808 amount_residual_currency = -amount_residual_currency
810 # Get right debit / credit:
811 line_currency = line.currency_id or company_currency
812 amount_currency_str = ""
813 total_amount_currency_str = ""
814 if line.currency_id and line.amount_currency:
815 amount_currency_str = rml_parser.formatLang(amount_residual_currency, currency_obj=line.currency_id)
816 total_amount_currency_str = rml_parser.formatLang(total_amount_currency, currency_obj=line.currency_id)
817 if target_currency and line_currency == target_currency and target_currency != company_currency:
818 debit = debit > 0 and amount_residual_currency or 0.0
819 credit = credit > 0 and amount_residual_currency or 0.0
820 amount_currency_str = rml_parser.formatLang(amount_residual, currency_obj=company_currency)
821 total_amount_currency_str = rml_parser.formatLang(total_amount, currency_obj=company_currency)
822 amount_str = rml_parser.formatLang(debit or credit, currency_obj=target_currency)
823 total_amount_str = rml_parser.formatLang(total_amount_currency, currency_obj=target_currency)
825 debit = debit > 0 and amount_residual or 0.0
826 credit = credit > 0 and amount_residual or 0.0
827 amount_str = rml_parser.formatLang(debit or credit, currency_obj=company_currency)
828 total_amount_str = rml_parser.formatLang(total_amount, currency_obj=company_currency)
829 if target_currency and target_currency != company_currency:
830 amount_currency_str = rml_parser.formatLang(debit or credit, currency_obj=line_currency)
831 total_amount_currency_str = rml_parser.formatLang(total_amount, currency_obj=line_currency)
834 ctx.update({'date': target_date})
835 debit = currency_obj.compute(cr, uid, target_currency.id, company_currency.id, debit, context=ctx)
836 credit = currency_obj.compute(cr, uid, target_currency.id, company_currency.id, credit, context=ctx)
837 amount_str = rml_parser.formatLang(debit or credit, currency_obj=target_currency)
838 total_amount = currency_obj.compute(cr, uid, target_currency.id, company_currency.id, total_amount, context=ctx)
839 total_amount_str = rml_parser.formatLang(total_amount, currency_obj=target_currency)
841 ret_line['credit'] = credit
842 ret_line['debit'] = debit
843 ret_line['amount_str'] = amount_str
844 ret_line['amount_currency_str'] = amount_currency_str
845 ret_line['total_amount_str'] = total_amount_str # For partial reconciliations
846 ret_line['total_amount_currency_str'] = total_amount_currency_str
850 def list_partners_to_reconcile(self, cr, uid, context=None):
852 """SELECT partner_id FROM (
853 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
854 FROM account_move_line l
855 RIGHT JOIN account_account a ON (a.id = l.account_id)
856 RIGHT JOIN res_partner p ON (l.partner_id = p.id)
857 WHERE a.reconcile IS TRUE
858 AND l.reconcile_id IS NULL
859 AND l.state <> 'draft'
860 GROUP BY l.partner_id, p.last_reconciliation_date
862 WHERE debit > 0 AND credit > 0 AND (last_reconciliation_date IS NULL OR max_date > last_reconciliation_date)
863 ORDER BY last_reconciliation_date""")
864 ids = [x[0] for x in cr.fetchall()]
868 # To apply the ir_rules
869 partner_obj = self.pool.get('res.partner')
870 ids = partner_obj.search(cr, uid, [('id', 'in', ids)], context=context)
871 return partner_obj.name_get(cr, uid, ids, context=context)
873 def reconcile_partial(self, cr, uid, ids, type='auto', context=None, writeoff_acc_id=False, writeoff_period_id=False, writeoff_journal_id=False):
874 move_rec_obj = self.pool.get('account.move.reconcile')
882 for line in self.browse(cr, uid, ids, context=context):
883 if company_list and not line.company_id.id in company_list:
884 raise osv.except_osv(_('Warning!'), _('To reconcile the entries company should be the same for all entries.'))
885 company_list.append(line.company_id.id)
887 for line in self.browse(cr, uid, ids, context=context):
888 if line.account_id.currency_id:
889 currency_id = line.account_id.currency_id
891 currency_id = line.company_id.currency_id
892 if line.reconcile_id:
893 raise osv.except_osv(_('Warning'), _("Journal Item '%s' (id: %s), Move '%s' is already reconciled!") % (line.name, line.id, line.move_id.name))
894 if line.reconcile_partial_id:
895 for line2 in line.reconcile_partial_id.line_partial_ids:
896 if line2.state != 'valid':
897 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))
898 if not line2.reconcile_id:
899 if line2.id not in merges:
900 merges.append(line2.id)
901 if line2.account_id.currency_id:
902 total += line2.amount_currency
904 total += (line2.debit or 0.0) - (line2.credit or 0.0)
905 merges_rec.append(line.reconcile_partial_id.id)
907 unmerge.append(line.id)
908 if line.account_id.currency_id:
909 total += line.amount_currency
911 total += (line.debit or 0.0) - (line.credit or 0.0)
912 if self.pool.get('res.currency').is_zero(cr, uid, currency_id, total):
913 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)
915 # marking the lines as reconciled does not change their validity, so there is no need
916 # to revalidate their moves completely.
917 reconcile_context = dict(context, novalidate=True)
918 r_id = move_rec_obj.create(cr, uid, {
920 'line_partial_ids': map(lambda x: (4,x,False), merges+unmerge)
921 }, context=reconcile_context)
922 move_rec_obj.reconcile_partial_check(cr, uid, [r_id] + merges_rec, context=reconcile_context)
925 def reconcile(self, cr, uid, ids, type='auto', writeoff_acc_id=False, writeoff_period_id=False, writeoff_journal_id=False, context=None):
926 account_obj = self.pool.get('account.account')
927 move_obj = self.pool.get('account.move')
928 move_rec_obj = self.pool.get('account.move.reconcile')
929 partner_obj = self.pool.get('res.partner')
930 currency_obj = self.pool.get('res.currency')
931 lines = self.browse(cr, uid, ids, context=context)
932 unrec_lines = filter(lambda x: not x['reconcile_id'], lines)
940 for line in self.browse(cr, uid, ids, context=context):
941 if company_list and not line.company_id.id in company_list:
942 raise osv.except_osv(_('Warning!'), _('To reconcile the entries company should be the same for all entries.'))
943 company_list.append(line.company_id.id)
944 for line in unrec_lines:
945 if line.state <> 'valid':
946 raise osv.except_osv(_('Error!'),
947 _('Entry "%s" is not valid !') % line.name)
948 credit += line['credit']
949 debit += line['debit']
950 currency += line['amount_currency'] or 0.0
951 account_id = line['account_id']['id']
952 partner_id = (line['partner_id'] and line['partner_id']['id']) or False
953 writeoff = debit - credit
955 # Ifdate_p in context => take this date
956 if context.has_key('date_p') and context['date_p']:
957 date=context['date_p']
959 date = time.strftime('%Y-%m-%d')
961 cr.execute('SELECT account_id, reconcile_id '\
962 'FROM account_move_line '\
964 'GROUP BY account_id,reconcile_id',
967 #TODO: move this check to a constraint in the account_move_reconcile object
969 raise osv.except_osv(_('Error'), _('Entries are not of the same account or already reconciled ! '))
971 raise osv.except_osv(_('Error!'), _('Entry is already reconciled.'))
972 account = account_obj.browse(cr, uid, account_id, context=context)
973 if not account.reconcile:
974 raise osv.except_osv(_('Error'), _('The account is not defined to be reconciled !'))
976 raise osv.except_osv(_('Error!'), _('Some entries are already reconciled.'))
978 if (not currency_obj.is_zero(cr, uid, account.company_id.currency_id, writeoff)) or \
979 (account.currency_id and (not currency_obj.is_zero(cr, uid, account.currency_id, currency))):
980 if not writeoff_acc_id:
981 raise osv.except_osv(_('Warning!'), _('You have to provide an account for the write off/exchange difference entry.'))
985 self_credit = writeoff
991 self_debit = -writeoff
992 # If comment exist in context, take it
993 if 'comment' in context and context['comment']:
994 libelle = context['comment']
996 libelle = _('Write-Off')
998 cur_obj = self.pool.get('res.currency')
1000 amount_currency_writeoff = 0.0
1001 if context.get('company_currency_id',False) != context.get('currency_id',False):
1002 cur_id = context.get('currency_id',False)
1003 for line in unrec_lines:
1004 if line.currency_id and line.currency_id.id == context.get('currency_id',False):
1005 amount_currency_writeoff += line.amount_currency
1007 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})
1008 amount_currency_writeoff += (line.debit > 0) and tmp_amount or -tmp_amount
1013 'debit': self_debit,
1014 'credit': self_credit,
1015 'account_id': account_id,
1017 'partner_id': partner_id,
1018 'currency_id': cur_id or (account.currency_id.id or False),
1019 'amount_currency': amount_currency_writeoff and -1 * amount_currency_writeoff or (account.currency_id.id and -1 * currency or 0.0)
1025 'account_id': writeoff_acc_id,
1026 'analytic_account_id': context.get('analytic_id', False),
1028 'partner_id': partner_id,
1029 'currency_id': cur_id or (account.currency_id.id or False),
1030 'amount_currency': amount_currency_writeoff and amount_currency_writeoff or (account.currency_id.id and currency or 0.0)
1034 writeoff_move_id = move_obj.create(cr, uid, {
1035 'period_id': writeoff_period_id,
1036 'journal_id': writeoff_journal_id,
1039 'line_id': writeoff_lines
1042 writeoff_line_ids = self.search(cr, uid, [('move_id', '=', writeoff_move_id), ('account_id', '=', account_id)])
1043 if account_id == writeoff_acc_id:
1044 writeoff_line_ids = [writeoff_line_ids[1]]
1045 ids += writeoff_line_ids
1047 # marking the lines as reconciled does not change their validity, so there is no need
1048 # to revalidate their moves completely.
1049 reconcile_context = dict(context, novalidate=True)
1050 r_id = move_rec_obj.create(cr, uid, {
1052 'line_id': map(lambda x: (4, x, False), ids),
1053 'line_partial_ids': map(lambda x: (3, x, False), ids)
1054 }, context=reconcile_context)
1055 # the id of the move.reconcile is written in the move.line (self) by the create method above
1056 # because of the way the line_id are defined: (4, x, False)
1058 workflow.trg_trigger(uid, 'account.move.line', id, cr)
1060 if lines and lines[0]:
1061 partner_id = lines[0].partner_id and lines[0].partner_id.id or False
1062 if partner_id and not partner_obj.has_something_to_reconcile(cr, uid, partner_id, context=context):
1063 partner_obj.mark_as_reconciled(cr, uid, [partner_id], context=context)
1066 def view_header_get(self, cr, user, view_id, view_type, context=None):
1069 context = self.convert_to_period(cr, user, context=context)
1070 if context.get('account_id', False):
1071 cr.execute('SELECT code FROM account_account WHERE id = %s', (context['account_id'], ))
1074 res = _('Entries: ')+ (res[0] or '')
1076 if (not context.get('journal_id', False)) or (not context.get('period_id', False)):
1078 if context.get('search_default_journal_id', False):
1079 context['journal_id'] = context.get('search_default_journal_id')
1080 cr.execute('SELECT code FROM account_journal WHERE id = %s', (context['journal_id'], ))
1081 j = cr.fetchone()[0] or ''
1082 cr.execute('SELECT code FROM account_period WHERE id = %s', (context['period_id'], ))
1083 p = cr.fetchone()[0] or ''
1085 return j + (p and (':' + p) or '')
1088 def onchange_date(self, cr, user, ids, date, context=None):
1090 Returns a dict that contains new values and context
1091 @param cr: A database cursor
1092 @param user: ID of the user currently logged in
1093 @param date: latest value from user input for field date
1094 @param args: other arguments
1095 @param context: context arguments, like lang, time zone
1096 @return: Returns a dict which contains new values, and context
1101 period_pool = self.pool.get('account.period')
1102 pids = period_pool.find(cr, user, date, context=context)
1104 res.update({'period_id':pids[0]})
1105 context = dict(context, period_id=pids[0])
1111 def _check_moves(self, cr, uid, context=None):
1112 # use the first move ever created for this journal and period
1115 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']))
1118 if res[1] != 'draft':
1119 raise osv.except_osv(_('User Error!'),
1120 _('The account move (%s) for centralisation ' \
1121 'has been confirmed.') % res[2])
1124 def _remove_move_reconcile(self, cr, uid, move_ids=None, opening_reconciliation=False, context=None):
1125 # Function remove move rencocile ids related with moves
1126 obj_move_line = self.pool.get('account.move.line')
1127 obj_move_rec = self.pool.get('account.move.reconcile')
1131 recs = obj_move_line.read(cr, uid, move_ids, ['reconcile_id', 'reconcile_partial_id'])
1132 full_recs = filter(lambda x: x['reconcile_id'], recs)
1133 rec_ids = [rec['reconcile_id'][0] for rec in full_recs]
1134 part_recs = filter(lambda x: x['reconcile_partial_id'], recs)
1135 part_rec_ids = [rec['reconcile_partial_id'][0] for rec in part_recs]
1136 unlink_ids += rec_ids
1137 unlink_ids += part_rec_ids
1138 all_moves = obj_move_line.search(cr, uid, ['|',('reconcile_id', 'in', unlink_ids),('reconcile_partial_id', 'in', unlink_ids)])
1139 all_moves = list(set(all_moves) - set(move_ids))
1141 if opening_reconciliation:
1142 raise osv.except_osv(_('Warning!'),
1143 _('Opening Entries have already been generated. Please run "Cancel Closing Entries" wizard to cancel those entries and then run this wizard.'))
1144 obj_move_rec.write(cr, uid, unlink_ids, {'opening_reconciliation': False})
1145 obj_move_rec.unlink(cr, uid, unlink_ids)
1146 if len(all_moves) >= 2:
1147 obj_move_line.reconcile_partial(cr, uid, all_moves, 'auto',context=context)
1150 def unlink(self, cr, uid, ids, context=None, check=True):
1153 move_obj = self.pool.get('account.move')
1154 self._update_check(cr, uid, ids, context)
1157 for line in self.browse(cr, uid, ids, context=context):
1158 move_ids.add(line.move_id.id)
1159 context['journal_id'] = line.journal_id.id
1160 context['period_id'] = line.period_id.id
1161 result = super(account_move_line, self).unlink(cr, uid, [line.id], context=context)
1162 move_ids = list(move_ids)
1163 if check and move_ids:
1164 move_obj.validate(cr, uid, move_ids, context=context)
1167 def write(self, cr, uid, ids, vals, context=None, check=True, update_check=True):
1170 move_obj = self.pool.get('account.move')
1171 account_obj = self.pool.get('account.account')
1172 journal_obj = self.pool.get('account.journal')
1173 if isinstance(ids, (int, long)):
1175 if vals.get('account_tax_id', False):
1176 raise osv.except_osv(_('Unable to change tax!'), _('You cannot change the tax, you should remove and recreate lines.'))
1177 if ('account_id' in vals) and not account_obj.read(cr, uid, vals['account_id'], ['active'])['active']:
1178 raise osv.except_osv(_('Bad Account!'), _('You cannot use an inactive account.'))
1180 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):
1181 self._update_check(cr, uid, ids, context)
1184 if vals.get('date', False):
1185 todo_date = vals['date']
1188 for line in self.browse(cr, uid, ids, context=context):
1189 ctx = context.copy()
1190 if not ctx.get('journal_id'):
1192 ctx['journal_id'] = line.move_id.journal_id.id
1194 ctx['journal_id'] = line.journal_id.id
1195 if not ctx.get('period_id'):
1197 ctx['period_id'] = line.move_id.period_id.id
1199 ctx['period_id'] = line.period_id.id
1200 #Check for centralisation
1201 journal = journal_obj.browse(cr, uid, ctx['journal_id'], context=ctx)
1202 if journal.centralisation:
1203 self._check_moves(cr, uid, context=ctx)
1204 result = super(account_move_line, self).write(cr, uid, ids, vals, context)
1207 for line in self.browse(cr, uid, ids):
1208 if line.move_id.id not in done:
1209 done.append(line.move_id.id)
1210 move_obj.validate(cr, uid, [line.move_id.id], context)
1212 move_obj.write(cr, uid, [line.move_id.id], {'date': todo_date}, context=context)
1215 def _update_journal_check(self, cr, uid, journal_id, period_id, context=None):
1216 journal_obj = self.pool.get('account.journal')
1217 period_obj = self.pool.get('account.period')
1218 jour_period_obj = self.pool.get('account.journal.period')
1219 cr.execute('SELECT state FROM account_journal_period WHERE journal_id = %s AND period_id = %s', (journal_id, period_id))
1220 result = cr.fetchall()
1221 journal = journal_obj.browse(cr, uid, journal_id, context=context)
1222 period = period_obj.browse(cr, uid, period_id, context=context)
1223 for (state,) in result:
1225 raise osv.except_osv(_('Error!'), _('You can not add/modify entries in a closed period %s of journal %s.' % (period.name,journal.name)))
1227 jour_period_obj.create(cr, uid, {
1228 'name': (journal.code or journal.name)+':'+(period.name or ''),
1229 'journal_id': journal.id,
1230 'period_id': period.id
1234 def _update_check(self, cr, uid, ids, context=None):
1236 for line in self.browse(cr, uid, ids, context=context):
1237 err_msg = _('Move name (id): %s (%s)') % (line.move_id.name, str(line.move_id.id))
1238 if line.move_id.state <> 'draft' and (not line.journal_id.entry_posted):
1239 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)
1240 if line.reconcile_id:
1241 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)
1242 t = (line.journal_id.id, line.period_id.id)
1244 self._update_journal_check(cr, uid, line.journal_id.id, line.period_id.id, context)
1248 def create(self, cr, uid, vals, context=None, check=True):
1249 account_obj = self.pool.get('account.account')
1250 tax_obj = self.pool.get('account.tax')
1251 move_obj = self.pool.get('account.move')
1252 cur_obj = self.pool.get('res.currency')
1253 journal_obj = self.pool.get('account.journal')
1254 context = dict(context or {})
1255 if vals.get('move_id', False):
1256 move = self.pool.get('account.move').browse(cr, uid, vals['move_id'], context=context)
1258 vals['company_id'] = move.company_id.id
1259 if move.date and not vals.get('date'):
1260 vals['date'] = move.date
1261 if ('account_id' in vals) and not account_obj.read(cr, uid, [vals['account_id']], ['active'])[0]['active']:
1262 raise osv.except_osv(_('Bad Account!'), _('You cannot use an inactive account.'))
1263 if 'journal_id' in vals and vals['journal_id']:
1264 context['journal_id'] = vals['journal_id']
1265 if 'period_id' in vals and vals['period_id']:
1266 context['period_id'] = vals['period_id']
1267 if ('journal_id' not in context) and ('move_id' in vals) and vals['move_id']:
1268 m = move_obj.browse(cr, uid, vals['move_id'])
1269 context['journal_id'] = m.journal_id.id
1270 context['period_id'] = m.period_id.id
1271 #we need to treat the case where a value is given in the context for period_id as a string
1272 if 'period_id' in context and not isinstance(context.get('period_id', ''), (int, long)):
1273 period_candidate_ids = self.pool.get('account.period').name_search(cr, uid, name=context.get('period_id',''))
1274 if len(period_candidate_ids) != 1:
1275 raise osv.except_osv(_('Error!'), _('No period found or more than one period found for the given date.'))
1276 context['period_id'] = period_candidate_ids[0][0]
1277 if not context.get('journal_id', False) and context.get('search_default_journal_id', False):
1278 context['journal_id'] = context.get('search_default_journal_id')
1279 self._update_journal_check(cr, uid, context['journal_id'], context['period_id'], context)
1280 move_id = vals.get('move_id', False)
1281 journal = journal_obj.browse(cr, uid, context['journal_id'], context=context)
1282 vals['journal_id'] = vals.get('journal_id') or context.get('journal_id')
1283 vals['period_id'] = vals.get('period_id') or context.get('period_id')
1284 vals['date'] = vals.get('date') or context.get('date')
1286 if journal.centralisation:
1287 #Check for centralisation
1288 res = self._check_moves(cr, uid, context)
1290 vals['move_id'] = res[0]
1291 if not vals.get('move_id', False):
1292 if journal.sequence_id:
1293 #name = self.pool.get('ir.sequence').next_by_id(cr, uid, journal.sequence_id.id)
1295 'date': vals.get('date', time.strftime('%Y-%m-%d')),
1296 'period_id': context['period_id'],
1297 'journal_id': context['journal_id']
1299 if vals.get('ref', ''):
1300 v.update({'ref': vals['ref']})
1301 move_id = move_obj.create(cr, uid, v, context)
1302 vals['move_id'] = move_id
1304 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.'))
1305 ok = not (journal.type_control_ids or journal.account_control_ids)
1306 if ('account_id' in vals):
1307 account = account_obj.browse(cr, uid, vals['account_id'], context=context)
1308 if journal.type_control_ids:
1309 type = account.user_type
1310 for t in journal.type_control_ids:
1311 if type.code == t.code:
1314 if journal.account_control_ids and not ok:
1315 for a in journal.account_control_ids:
1316 if a.id == vals['account_id']:
1319 # Automatically convert in the account's secondary currency if there is one and
1320 # the provided values were not already multi-currency
1321 if account.currency_id and 'amount_currency' not in vals and account.currency_id.id != account.company_id.currency_id.id:
1322 vals['currency_id'] = account.currency_id.id
1325 ctx['date'] = vals['date']
1326 vals['amount_currency'] = cur_obj.compute(cr, uid, account.company_id.currency_id.id,
1327 account.currency_id.id, vals.get('debit', 0.0)-vals.get('credit', 0.0), context=ctx)
1329 raise osv.except_osv(_('Bad Account!'), _('You cannot use this general account in this journal, check the tab \'Entry Controls\' on the related journal.'))
1331 result = super(account_move_line, self).create(cr, uid, vals, context=context)
1333 if vals.get('account_tax_id', False):
1334 tax_id = tax_obj.browse(cr, uid, vals['account_tax_id'])
1335 total = vals['debit'] - vals['credit']
1336 base_code = 'base_code_id'
1337 tax_code = 'tax_code_id'
1338 account_id = 'account_collected_id'
1339 base_sign = 'base_sign'
1340 tax_sign = 'tax_sign'
1341 if journal.type in ('purchase_refund', 'sale_refund') or (journal.type in ('cash', 'bank') and total < 0):
1342 base_code = 'ref_base_code_id'
1343 tax_code = 'ref_tax_code_id'
1344 account_id = 'account_paid_id'
1345 base_sign = 'ref_base_sign'
1346 tax_sign = 'ref_tax_sign'
1348 for tax in tax_obj.compute_all(cr, uid, [tax_id], total, 1.00, force_excluded=False).get('taxes'):
1349 #create the base movement
1353 if tax_id.price_include:
1354 total = tax['price_unit']
1356 'tax_code_id': tax[base_code],
1357 'tax_amount': tax[base_sign] * abs(total),
1359 if tax_id.price_include:
1360 if tax['price_unit'] < 0:
1361 newvals['credit'] = abs(tax['price_unit'])
1363 newvals['debit'] = tax['price_unit']
1364 self.write(cr, uid, [result], newvals, context=context)
1367 'move_id': vals['move_id'],
1368 'name': tools.ustr(vals['name'] or '') + ' ' + tools.ustr(tax['name'] or ''),
1369 'date': vals['date'],
1370 'partner_id': vals.get('partner_id', False),
1371 'ref': vals.get('ref', False),
1372 'statement_id': vals.get('statement_id', False),
1373 'account_tax_id': False,
1374 'tax_code_id': tax[base_code],
1375 'tax_amount': tax[base_sign] * abs(total),
1376 'account_id': vals['account_id'],
1380 if data['tax_code_id']:
1381 self.create(cr, uid, data, context)
1382 #create the Tax movement
1384 'move_id': vals['move_id'],
1385 'name': tools.ustr(vals['name'] or '') + ' ' + tools.ustr(tax['name'] or ''),
1386 'date': vals['date'],
1387 'partner_id': vals.get('partner_id',False),
1388 'ref': vals.get('ref',False),
1389 'statement_id': vals.get('statement_id', False),
1390 'account_tax_id': False,
1391 'tax_code_id': tax[tax_code],
1392 'tax_amount': tax[tax_sign] * abs(tax['amount']),
1393 'account_id': tax[account_id] or vals['account_id'],
1394 'credit': tax['amount']<0 and -tax['amount'] or 0.0,
1395 'debit': tax['amount']>0 and tax['amount'] or 0.0,
1397 if data['tax_code_id']:
1398 self.create(cr, uid, data, context)
1399 del vals['account_tax_id']
1401 if check and not context.get('novalidate') and (context.get('recompute', True) or journal.entry_posted):
1402 tmp = move_obj.validate(cr, uid, [vals['move_id']], context)
1403 if journal.entry_posted and tmp:
1404 move_obj.button_validate(cr,uid, [vals['move_id']], context)
1407 def list_periods(self, cr, uid, context=None):
1408 ids = self.pool.get('account.period').search(cr,uid,[])
1409 return self.pool.get('account.period').name_get(cr, uid, ids, context=context)
1411 def list_journals(self, cr, uid, context=None):
1412 ng = dict(self.pool.get('account.journal').name_search(cr,uid,'',[]))
1415 for journal in self.pool.get('account.journal').browse(cr, uid, ids, context=context):
1416 result.append((journal.id,ng[journal.id],journal.type,
1417 bool(journal.currency),bool(journal.analytic_journal_id)))
1421 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: