[IMP] Cleanup and refactoring of exception handling

Unify and refactor exception handling in framework and addons.

The generic `except_osv` is now deprecated, and replaced by more specialized exception subtypes:
 - `UserError` (renamed from Warning, as it conflicts with the built-in `Warning`) raised when a non-technical error occurs during a business operation. It could be a missing information in the data provided by the user, or a misconfiguration.
 - `AccessError`: raised when any operation is denied because the user conducting it does not have the required access rights.
 - `AccessDenied`: raised when an operation that requires authenticated access is attempted via an unauthenticated request.
 - `MissingError`: raised when an operation is attempted on a record that does not exist.
 - `ValidationError`: raised when an operation violates a SQL or Python constraint.
 - All other exceptions are internal errors due to a system problem or bug, and raised untouched to the client-side, which should display a traceback.

All exceptions take a single message argument.

The `test_exceptions` module has been updated to showcase both new and old (deprecated) exceptions.

A great many old `except_osv` had a useless title with "Error!" or "Warning", those have been removed, as this is handled by the client-side widget that displays the messages.

This commit introduces a more consistent policy for logging errors and warnings:
 - All messages that do not require administrator attention should be logged at INFO level or lower. This includes all errors that are notified to the user in a friendly manner, even for access right problems or validation errors during business operations.
 - All messages that indicate a likely misconfiguration or malicious use by the users should be logged at WARNING level, as they typically require administrator attention.
 - All other unhandled internal errors cannot typically be handled by the user and should be logged at ERROR or higher level, as they require immediate administrator attention.
This commit is contained in:
Goffin Simon
2015-01-16 17:15:18 +01:00
committed by Christophe Simonis
parent eeb8ed165d
commit 0fd773a486
236 changed files with 1264 additions and 1107 deletions
+36 -45
View File
@@ -31,6 +31,7 @@ from openerp import tools
from openerp.osv import fields, osv, expression
from openerp.tools.translate import _
from openerp.tools.float_utils import float_round as round
from openerp.exceptions import UserError
import openerp.addons.decimal_precision as dp
@@ -419,12 +420,12 @@ class account_account(osv.osv):
journal_obj = self.pool.get('account.journal')
jids = journal_obj.search(cr, uid, [('type','=','situation'),('centralisation','=',1),('company_id','=',account.company_id.id)], context=context)
if not jids:
raise osv.except_osv(_('Error!'),_("You need an Opening journal with centralisation checked to set the initial balance."))
raise UserError(_("You need an Opening journal with centralisation checked to set the initial balance."))
period_obj = self.pool.get('account.period')
pids = period_obj.search(cr, uid, [('special','=',True),('company_id','=',account.company_id.id)], context=context)
if not pids:
raise osv.except_osv(_('Error!'),_("There is no opening/closing period defined, please create one to set the initial balance."))
raise UserError(_("There is no opening/closing period defined, please create one to set the initial balance."))
move_obj = self.pool.get('account.move.line')
move_id = move_obj.search(cr, uid, [
@@ -441,7 +442,7 @@ class account_account(osv.osv):
}, context=context)
else:
if diff<0.0:
raise osv.except_osv(_('Error!'),_("Unable to adapt the initial balance (negative value)."))
raise UserError(_("Unable to adapt the initial balance (negative value)."))
nameinv = (name=='credit' and 'debit') or 'credit'
move_id = move_obj.create(cr, uid, {
'name': _('Opening Balance'),
@@ -654,14 +655,14 @@ class account_account(osv.osv):
if line_obj.search(cr, uid, [('account_id', 'in', account_ids)], context=context):
if method == 'write':
raise osv.except_osv(_('Error!'), _('You cannot deactivate an account that contains journal items.'))
raise UserError(_('You cannot deactivate an account that contains journal items.'))
elif method == 'unlink':
raise osv.except_osv(_('Error!'), _('You cannot remove an account that contains journal items.'))
raise UserError(_('You cannot remove an account that contains journal items.'))
#Checking whether the account is set as a property to any Partner or not
values = ['account.account,%s' % (account_id,) for account_id in ids]
partner_prop_acc = self.pool.get('ir.property').search(cr, uid, [('value_reference','in', values)], context=context)
if partner_prop_acc:
raise osv.except_osv(_('Warning!'), _('You cannot remove/deactivate an account which is set on a customer or supplier.'))
raise UserError(_('You cannot remove/deactivate an account which is set on a customer or supplier.'))
return True
def _check_allow_type_change(self, cr, uid, ids, new_type, context=None):
@@ -673,10 +674,10 @@ class account_account(osv.osv):
if line_obj.search(cr, uid, [('account_id', 'in', account_ids)]):
#Check for 'Closed' type
if old_type == 'closed' and new_type !='closed':
raise osv.except_osv(_('Warning!'), _("You cannot change the type of account from 'Closed' to any other type as it contains journal items!"))
raise UserError(_("You cannot change the type of account from 'Closed' to any other type as it contains journal items!"))
# Forbid to change an account type for restricted_groups as it contains journal items (or if one of its children does)
if (new_type in restricted_groups):
raise osv.except_osv(_('Warning!'), _("You cannot change the type of account to '%s' type as it contains journal items!") % (new_type,))
raise UserError(_("You cannot change the type of account to '%s' type as it contains journal items!") % (new_type,))
return True
@@ -688,7 +689,7 @@ class account_account(osv.osv):
for account in self.browse(cr, uid, ids, context=context):
account_ids = self.search(cr, uid, [('id', 'child_of', [account.id])], context=context)
if line_obj.search(cr, uid, [('account_id', 'in', account_ids)], context=context):
raise osv.except_osv(_('Warning !'), _("You cannot change the code of account which contains journal items!"))
raise UserError(_("You cannot change the code of account which contains journal items!"))
return True
def write(self, cr, uid, ids, vals, context=None):
@@ -706,7 +707,7 @@ class account_account(osv.osv):
# Allow the write if the value is the same
for i in [i['company_id'][0] for i in self.read(cr,uid,ids,['company_id'], context=context)]:
if vals['company_id']!=i:
raise osv.except_osv(_('Warning!'), _('You cannot change the owner company of an account that already contains journal items.'))
raise UserError(_('You cannot change the owner company of an account that already contains journal items.'))
if 'active' in vals and not vals['active']:
self._check_moves(cr, uid, ids, "write", context=context)
if 'type' in vals.keys():
@@ -798,7 +799,7 @@ class account_journal(osv.osv):
if 'company_id' in vals and journal.company_id.id != vals['company_id']:
move_lines = self.pool.get('account.move.line').search(cr, uid, [('journal_id', 'in', ids)])
if move_lines:
raise osv.except_osv(_('Warning!'), _('This journal already contains items, therefore you cannot modify its company field.'))
raise UserError(_('This journal already contains items, therefore you cannot modify its company field.'))
return super(account_journal, self).write(cr, uid, ids, vals, context=context)
def create_sequence(self, cr, uid, vals, context=None):
@@ -1047,7 +1048,7 @@ class account_period(osv.osv):
mode = 'draft'
for period in self.browse(cr, uid, ids):
if period.fiscalyear_id.state == 'done':
raise osv.except_osv(_('Warning!'), _('You can not re-open a period which belongs to closed fiscal year'))
raise UserError(_('You can not re-open a period which belongs to closed fiscal year'))
cr.execute('update account_journal_period set state=%s where period_id in %s', (mode, tuple(ids),))
cr.execute('update account_period set state=%s where id in %s', (mode, tuple(ids),))
self.invalidate_cache(cr, uid, context=context)
@@ -1067,7 +1068,7 @@ class account_period(osv.osv):
if 'company_id' in vals:
move_lines = self.pool.get('account.move.line').search(cr, uid, [('period_id', 'in', ids)])
if move_lines:
raise osv.except_osv(_('Warning!'), _('This journal already contains items for this period, therefore you cannot modify its company field.'))
raise UserError(_('This journal already contains items for this period, therefore you cannot modify its company field.'))
return super(account_period, self).write(cr, uid, ids, vals, context=context)
def build_ctx_periods(self, cr, uid, period_from_id, period_to_id):
@@ -1080,9 +1081,9 @@ class account_period(osv.osv):
period_date_stop = period_to.date_stop
company2_id = period_to.company_id.id
if company1_id != company2_id:
raise osv.except_osv(_('Error!'), _('You should choose the periods that belong to the same company.'))
raise UserError(_('You should choose the periods that belong to the same company.'))
if period_date_start > period_date_stop:
raise osv.except_osv(_('Error!'), _('Start period should precede then end period.'))
raise UserError(_('Start period should precede then end period.'))
# /!\ We do not include a criterion on the company_id field below, to allow producing consolidated reports
# on multiple companies. It will only work when start/end periods are selected and no fiscal year is chosen.
@@ -1124,7 +1125,7 @@ class account_journal_period(osv.osv):
cr.execute('select * from account_move_line where journal_id=%s and period_id=%s limit 1', (obj.journal_id.id, obj.period_id.id))
res = cr.fetchall()
if res:
raise osv.except_osv(_('Error!'), _('You cannot modify/delete a journal with entries for this period.'))
raise UserError(_('You cannot modify/delete a journal with entries for this period.'))
return True
def write(self, cr, uid, ids, vals, context=None):
@@ -1308,7 +1309,7 @@ class account_move(osv.osv):
valid_moves = self.validate(cr, uid, ids, context)
if not valid_moves:
raise osv.except_osv(_('Error!'), _('You cannot validate a non-balanced entry.\nMake sure you have configured payment terms properly.\nThe latest payment term line should be of the "Balance" type.'))
raise UserError(_('You cannot validate a non-balanced entry.\nMake sure you have configured payment terms properly.\nThe latest payment term line should be of the "Balance" type.'))
obj_sequence = self.pool.get('ir.sequence')
for move in self.browse(cr, uid, valid_moves, context=context):
if move.name =='/':
@@ -1322,7 +1323,7 @@ class account_move(osv.osv):
c = {'fiscalyear_id': move.period_id.fiscalyear_id.id}
new_name = obj_sequence.next_by_id(cr, uid, journal.sequence_id.id, c)
else:
raise osv.except_osv(_('Error!'), _('Please define a sequence on the journal.'))
raise UserError(_('Please define a sequence on the journal.'))
if new_name:
self.write(cr, uid, [move.id], {'name':new_name})
@@ -1346,14 +1347,13 @@ class account_move(osv.osv):
if not top_common:
top_common = top_account
elif top_account.id != top_common.id:
raise osv.except_osv(_('Error!'),
_('You cannot validate this journal entry because account "%s" does not belong to chart of accounts "%s".') % (account.name, top_common.name))
raise UserError(_('You cannot validate this journal entry because account "%s" does not belong to chart of accounts "%s".') % (account.name, top_common.name))
return self.post(cursor, user, ids, context=context)
def button_cancel(self, cr, uid, ids, context=None):
for line in self.browse(cr, uid, ids, context=context):
if not line.journal_id.update_posted:
raise osv.except_osv(_('Error!'), _('You cannot modify a posted entry of this journal.\nFirst you should set the journal to allow cancelling entries.'))
raise UserError(_('You cannot modify a posted entry of this journal.\nFirst you should set the journal to allow cancelling entries.'))
if ids:
cr.execute('UPDATE account_move '\
'SET state=%s '\
@@ -1415,14 +1415,10 @@ class account_move(osv.osv):
obj_move_line = self.pool.get('account.move.line')
for move in self.browse(cr, uid, ids, context=context):
if move['state'] != 'draft':
raise osv.except_osv(_('User Error!'),
_('You cannot delete a posted journal entry "%s".') % \
move['name'])
raise UserError(_('You cannot delete a posted journal entry "%s".') % move['name'])
for line in move.line_id:
if line.invoice:
raise osv.except_osv(_('User Error!'),
_("Move cannot be deleted if linked to an invoice. (Invoice: %s - Move ID:%s)") % \
(line.invoice.number,move.name))
raise UserError(_("Move cannot be deleted if linked to an invoice. (Invoice: %s - Move ID:%s)") % (line.invoice.number,move.name))
line_ids = map(lambda x: x.id, move.line_id)
context['journal_id'] = move.journal_id.id
context['period_id'] = move.period_id.id
@@ -1449,16 +1445,12 @@ class account_move(osv.osv):
account_id = move.journal_id.default_debit_account_id.id
mode2 = 'debit'
if not account_id:
raise osv.except_osv(_('User Error!'),
_('There is no default debit account defined \n' \
'on journal "%s".') % move.journal_id.name)
raise UserError(_('There is no default debit account defined \non journal "%s".') % move.journal_id.name)
else:
account_id = move.journal_id.default_credit_account_id.id
mode2 = 'credit'
if not account_id:
raise osv.except_osv(_('User Error!'),
_('There is no default credit account defined \n' \
'on journal "%s".') % move.journal_id.name)
raise UserError(_('There is no default credit account defined \non journal "%s".') % move.journal_id.name)
# find the first line of this move with the current mode
# or create it if it doesn't exist
@@ -1551,11 +1543,11 @@ class account_move(osv.osv):
if not company_id:
company_id = line.account_id.company_id.id
if not company_id == line.account_id.company_id.id:
raise osv.except_osv(_('Error!'), _("Cannot create moves for different companies."))
raise UserError(_("Cannot create moves for different companies."))
if line.account_id.currency_id and line.currency_id:
if line.account_id.currency_id.id != line.currency_id.id and (line.account_id.currency_id.id != line.account_id.company_id.currency_id.id):
raise osv.except_osv(_('Error!'), _("""Cannot create move with currency different from ..""") % (line.account_id.code, line.account_id.name))
raise UserError(_("""Cannot create move with currency different from ..""") % (line.account_id.code, line.account_id.name))
if abs(amount) < 10 ** -4:
# If the move is balanced
@@ -1642,8 +1634,7 @@ class account_move_reconcile(osv.osv):
def unlink(self, cr, uid, ids, context=None):
for move_rec in self.browse(cr, uid, ids, context=context):
if move_rec.opening_reconciliation:
raise osv.except_osv(_('Error!'), _('You cannot unreconcile journal items if they has been generated by the \
opening/closing fiscal year process.'))
raise UserError(_('You cannot unreconcile journal items if they has been generated by the opening/closing fiscal year process.'))
return super(account_move_reconcile, self).unlink(cr, uid, ids, context=context)
# Look in the line_id and line_partial_ids to ensure the partner is the same or empty
@@ -2137,7 +2128,7 @@ class account_tax(osv.osv):
product=product, partner=partner, force_excluded=force_excluded)
def compute(self, cr, uid, taxes, price_unit, quantity, product=None, partner=None):
_logger.warning("Deprecated, use compute_all(...)['taxes'] instead of compute(...) to manage prices with tax included.")
_logger.info("Deprecated, use compute_all(...)['taxes'] instead of compute(...) to manage prices with tax included.")
return self._compute(cr, uid, taxes, price_unit, quantity, product, partner)
def _compute(self, cr, uid, taxes, price_unit, quantity, product=None, partner=None, precision=None):
@@ -2305,7 +2296,7 @@ class account_model(osv.osv):
try:
entry['name'] = model.name%{'year': move_date.strftime('%Y'), 'month': move_date.strftime('%m'), 'date': move_date.strftime('%Y-%m')}
except:
raise osv.except_osv(_('Wrong Model!'), _('You have a wrong expression "%(...)s" in your model!'))
raise UserError(_('You have a wrong expression "%(...)s" in your model!'))
move_id = account_move_obj.create(cr, uid, {
'ref': entry['name'],
'period_id': period_id,
@@ -2317,7 +2308,7 @@ class account_model(osv.osv):
analytic_account_id = False
if line.analytic_account_id:
if not model.journal_id.analytic_journal_id:
raise osv.except_osv(_('No Analytic Journal!'),_("You have to define an analytic journal on the '%s' journal!") % (model.journal_id.name,))
raise UserError(_("You have to define an analytic journal on the '%s' journal!") % (model.journal_id.name,))
analytic_account_id = line.analytic_account_id.id
val = {
'move_id': move_id,
@@ -2329,7 +2320,7 @@ class account_model(osv.osv):
date_maturity = context.get('date',time.strftime('%Y-%m-%d'))
if line.date_maturity == 'partner':
if not line.partner_id:
raise osv.except_osv(_('Error!'), _("Maturity date of entry line generated by model line '%s' of model '%s' is based on partner payment term!" \
raise UserError(_("Maturity date of entry line generated by model line '%s' of model '%s' is based on partner payment term!" \
"\nPlease define partner on it!")%(line.name, model.name))
payment_term_id = False
@@ -2643,7 +2634,7 @@ class account_add_tmpl_wizard(osv.osv_memory):
ptids = tmpl_obj.read(cr, uid, [tids[0]['parent_id'][0]], ['code'])
res = None
if not ptids or not ptids[0]['code']:
raise osv.except_osv(_('Error!'), _('There is no parent code for the template account.'))
raise UserError(_('There is no parent code for the template account.'))
res = acc_obj.search(cr, uid, [('code','=',ptids[0]['code'])])
return res and res[0] or False
@@ -3450,7 +3441,7 @@ class wizard_multi_charts_accounts(osv.osv_memory):
if not ids:
break
else:
raise osv.except_osv(_('Error!'), _('Cannot generate an unused journal code.'))
raise UserError(_('Cannot generate an unused journal code.'))
return {
'name': line['acc_name'],
@@ -3489,7 +3480,7 @@ class wizard_multi_charts_accounts(osv.osv_memory):
if not ids:
break
else:
raise osv.except_osv(_('Error!'), _('Cannot generate an unused account code.'))
raise UserError(_('Cannot generate an unused account code.'))
# Get the id of the user types fr-or cash and bank
tmp = obj_data.get_object_reference(cr, uid, 'account', 'data_account_type_cash')
@@ -3543,7 +3534,7 @@ class wizard_multi_charts_accounts(osv.osv_memory):
ref_acc_bank = obj_wizard.chart_template_id.bank_account_view_id
if journal_data and not ref_acc_bank.code:
raise osv.except_osv(_('Configuration Error!'), _('You have to set a code for the bank account defined on the selected chart of accounts.'))
raise UserError(_('You have to set a code for the bank account defined on the selected chart of accounts.'))
self.pool.get('res.company').write(cr, uid, [company.id], {'bank_account_code_char': ref_acc_bank.code}, context=context)
for line in journal_data:
+3 -2
View File
@@ -22,6 +22,7 @@
from openerp.osv import fields
from openerp.osv import osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class account_analytic_line(osv.osv):
_inherit = 'account.analytic.line'
@@ -93,7 +94,7 @@ class account_analytic_line(osv.osv):
if not a:
a = prod.categ_id.property_account_expense_categ.id
if not a:
raise osv.except_osv(_('Error!'),
raise UserError(
_('There is no expense account defined ' \
'for this product: "%s" (id:%d).') % \
(prod.name, prod.id,))
@@ -102,7 +103,7 @@ class account_analytic_line(osv.osv):
if not a:
a = prod.categ_id.property_account_income_categ.id
if not a:
raise osv.except_osv(_('Error!'),
raise UserError(
_('There is no income account defined ' \
'for this product: "%s" (id:%d).') % \
(prod.name, prod_id,))
+12 -18
View File
@@ -24,6 +24,7 @@ from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
from openerp.report import report_sxw
from openerp.tools import float_compare, float_round
from openerp.exceptions import UserError
from operator import add
import time
@@ -319,8 +320,7 @@ class account_bank_statement(osv.osv):
def balance_check(self, cr, uid, st_id, journal_type='bank', context=None):
st = self.browse(cr, uid, st_id, context=context)
if not ((abs((st.balance_end or 0.0) - st.balance_end_real) < 0.0001) or (abs((st.balance_end or 0.0) - st.balance_end_real) < 0.0001)):
raise osv.except_osv(_('Error!'),
_('The statement balance is incorrect !\nThe expected balance (%.2f) is different than the computed one. (%.2f)') % (st.balance_end_real, st.balance_end))
raise UserError(_('The statement balance is incorrect !\nThe expected balance (%.2f) is different than the computed one. (%.2f)') % (st.balance_end_real, st.balance_end))
return True
def statement_close(self, cr, uid, ids, journal_type='bank', context=None):
@@ -341,10 +341,10 @@ class account_bank_statement(osv.osv):
self.balance_check(cr, uid, st.id, journal_type=j_type, context=context)
if (not st.journal_id.default_credit_account_id) \
or (not st.journal_id.default_debit_account_id):
raise osv.except_osv(_('Configuration Error!'), _('Please verify that an account is defined in the journal.'))
raise UserError(_('Please verify that an account is defined in the journal.'))
for line in st.move_line_ids:
if line.state != 'valid':
raise osv.except_osv(_('Error!'), _('The account entries lines are not in valid state.'))
raise UserError(_('The account entries lines are not in valid state.'))
move_ids = []
for st_line in st.line_ids:
if not st_line.amount:
@@ -359,7 +359,7 @@ class account_bank_statement(osv.osv):
}
self.pool.get('account.bank.statement.line').process_reconciliation(cr, uid, st_line.id, [vals], context=context)
elif not st_line.journal_entry_ids.ids:
raise osv.except_osv(_('Error!'), _('All the account entries lines must be processed in order to close the statement.'))
raise UserError(_('All the account entries lines must be processed in order to close the statement.'))
move_ids += st_line.journal_entry_ids.ids
if move_ids:
self.pool.get('account.move').post(cr, uid, move_ids, context=context)
@@ -401,10 +401,7 @@ class account_bank_statement(osv.osv):
statement_line_obj = self.pool['account.bank.statement.line']
for item in self.browse(cr, uid, ids, context=context):
if item.state != 'draft':
raise osv.except_osv(
_('Invalid Action!'),
_('In order to delete a bank statement, you must first cancel it to delete related journal items.')
)
raise UserError(_('In order to delete a bank statement, you must first cancel it to delete related journal items.'))
# Explicitly unlink bank statement lines
# so it will check that the related journal entries have
# been deleted first
@@ -439,16 +436,13 @@ class account_bank_statement_line(osv.osv):
def create(self, cr, uid, vals, context=None):
if vals.get('amount_currency', 0) and not vals.get('amount', 0):
raise osv.except_osv(_('Error!'), _('If "Amount Currency" is specified, then "Amount" must be as well.'))
raise UserError(_('If "Amount Currency" is specified, then "Amount" must be as well.'))
return super(account_bank_statement_line, self).create(cr, uid, vals, context=context)
def unlink(self, cr, uid, ids, context=None):
for item in self.browse(cr, uid, ids, context=context):
if item.journal_entry_ids:
raise osv.except_osv(
_('Invalid Action!'),
_('In order to delete a bank statement line, you must first cancel it to delete related journal items.')
)
raise UserError(_("""In order to delete a bank statement line, you must first cancel it to delete related journal items."""))
return super(account_bank_statement_line, self).unlink(cr, uid, ids, context=context)
def cancel(self, cr, uid, ids, context=None):
@@ -706,11 +700,11 @@ class account_bank_statement_line(osv.osv):
if currency_diff < 0:
account_id = st_line.company_id.expense_currency_exchange_account_id.id
if not account_id:
raise osv.except_osv(_('Insufficient Configuration!'), _("You should configure the 'Loss Exchange Rate Account' in the accounting settings, to manage automatically the booking of accounting entries related to differences between exchange rates."))
raise UserError(_("You should configure the 'Loss Exchange Rate Account' in the accounting settings, to manage automatically the booking of accounting entries related to differences between exchange rates."))
else:
account_id = st_line.company_id.income_currency_exchange_account_id.id
if not account_id:
raise osv.except_osv(_('Insufficient Configuration!'), _("You should configure the 'Gain Exchange Rate Account' in the accounting settings, to manage automatically the booking of accounting entries related to differences between exchange rates."))
raise UserError(_("You should configure the 'Gain Exchange Rate Account' in the accounting settings, to manage automatically the booking of accounting entries related to differences between exchange rates."))
return {
'move_id': move_id,
'name': _('change') + ': ' + (st_line.name or '/'),
@@ -749,7 +743,7 @@ class account_bank_statement_line(osv.osv):
# Checks
if st_line.journal_entry_ids.ids:
raise osv.except_osv(_('Error!'), _('The bank statement line was already reconciled.'))
raise UserError(_('The bank statement line was already reconciled.'))
for mv_line_dict in mv_line_dicts:
for field in ['debit', 'credit', 'amount_currency']:
if field not in mv_line_dict:
@@ -757,7 +751,7 @@ class account_bank_statement_line(osv.osv):
if mv_line_dict.get('counterpart_move_line_id'):
mv_line = aml_obj.browse(cr, uid, mv_line_dict.get('counterpart_move_line_id'), context=context)
if mv_line.reconcile_id:
raise osv.except_osv(_('Error!'), _('A selected move line was already reconciled.'))
raise UserError(_('A selected move line was already reconciled.'))
# When the move line is already paid (fully reconciled move), we just link them to the bank statement
to_reconcile_mv_line_ids = [x['counterpart_move_line_id'] for x in mv_line_dicts if x.get('already_paid', False)]
+4 -3
View File
@@ -26,6 +26,7 @@ from openerp.osv import fields, osv
from openerp.tools import float_compare
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
from openerp.exceptions import UserError, AccessError
class account_cashbox_line(osv.osv):
@@ -268,7 +269,7 @@ class account_cash_statement(osv.osv):
for statement in statement_pool.browse(cr, uid, ids, context=context):
vals = {}
if not self._user_allow(cr, uid, statement.id, context=context):
raise osv.except_osv(_('Error!'), (_('You do not have rights to open this %s journal!') % (statement.journal_id.name, )))
raise AccessError((_('You do not have rights to open this %s journal!') % (statement.journal_id.name, )))
if statement.name and statement.name == '/':
c = {'fiscalyear_id': statement.period_id.fiscalyear_id.id}
@@ -312,12 +313,12 @@ class account_cash_statement(osv.osv):
account = obj.journal_id.loss_account_id
name = _('Loss')
if not obj.journal_id.loss_account_id:
raise osv.except_osv(_('Error!'), _('There is no Loss Account on the journal %s.') % (obj.journal_id.name,))
raise UserError(_('There is no Loss Account on the journal %s.') % (obj.journal_id.name,))
else: # obj.difference > 0.0
account = obj.journal_id.profit_account_id
name = _('Profit')
if not obj.journal_id.profit_account_id:
raise osv.except_osv(_('Error!'), _('There is no Profit Account on the journal %s.') % (obj.journal_id.name,))
raise UserError(_('There is no Profit Account on the journal %s.') % (obj.journal_id.name,))
values = {
'statement_id' : obj.id,
+17 -24
View File
@@ -23,7 +23,7 @@ import itertools
from lxml import etree
from openerp import models, fields, api, _
from openerp.exceptions import except_orm, Warning, RedirectWarning
from openerp.exceptions import UserError, RedirectWarning
from openerp.tools import float_compare
import openerp.addons.decimal_precision as dp
@@ -91,8 +91,7 @@ class account_invoice(models.Model):
journal_type = type2journal.get(inv_type, 'sale')
journal = self.env['account.analytic.journal'].search([('type', '=', journal_type)], limit=1)
if not journal:
raise except_orm(_('No Analytic Journal!'),
_("You must define an analytic journal of type '%s'!") % (journal_type,))
raise UserError(_("You must define an analytic journal of type '%s'!") % (journal_type,))
return journal[0]
@api.one
@@ -418,9 +417,9 @@ class account_invoice(models.Model):
def unlink(self):
for invoice in self:
if invoice.state not in ('draft', 'cancel'):
raise Warning(_('You cannot delete an invoice which is not draft or cancelled. You should refund it instead.'))
raise UserError(_('You cannot delete an invoice which is not draft or cancelled. You should refund it instead.'))
elif invoice.internal_number:
raise Warning(_('You cannot delete an invoice after it has been validated (and received a number). You can set it back to "Draft" state and modify its content, then re-confirm it.'))
raise UserError(_('You cannot delete an invoice after it has been validated (and received a number). You can set it back to "Draft" state and modify its content, then re-confirm it.'))
return super(account_invoice, self).unlink()
@api.multi
@@ -509,8 +508,7 @@ class account_invoice(models.Model):
if pterm_list:
return {'value': {'date_due': max(line[0] for line in pterm_list)}}
else:
raise except_orm(_('Insufficient Data!'),
_('The payment term of supplier does not have a payment term line.'))
raise UserError(_('The payment term of supplier does not have a payment term line.'))
@api.multi
def onchange_invoice_line(self, lines):
@@ -571,10 +569,7 @@ class account_invoice(models.Model):
if len(line_cmd) >= 3 and isinstance(line_cmd[2], dict):
line = self.env['account.account'].browse(line_cmd[2]['account_id'])
if line.company_id.id != company_id:
raise except_orm(
_('Configuration Error!'),
_("Invoice line account's company and invoice's company does not match.")
)
raise UserError(_("""Configuration Error!\nInvoice line account's company and invoice's company does not match."""))
if company_id and type:
journal_type = TYPE2JOURNAL[type]
@@ -670,8 +665,7 @@ class account_invoice(models.Model):
else:
ref = self.number
if not self.journal_id.analytic_journal_id:
raise except_orm(_('No Analytic Journal!'),
_("You have to define an analytic journal on the '%s' journal!") % (self.journal_id.name,))
raise UserError(_("You have to define an analytic journal on the '%s' journal!") % (self.journal_id.name,))
currency = self.currency_id.with_context(date=self.date_invoice)
il['analytic_lines'] = [(0,0, {
'name': il['name'],
@@ -723,13 +717,13 @@ class account_invoice(models.Model):
key = (tax.tax_code_id.id, tax.base_code_id.id, tax.account_id.id)
tax_key.append(key)
if key not in compute_taxes:
raise except_orm(_('Warning!'), _('Global taxes defined, but they are not in invoice lines !'))
raise UserError(_('Global taxes defined, but they are not in invoice lines !'))
base = compute_taxes[key]['base']
if float_compare(abs(base - tax.base), company_currency.rounding, precision_digits=precision) == 1:
raise except_orm(_('Warning!'), _('Tax base different!\nClick on compute to update the tax base.'))
raise UserError(_('Tax base different!\nClick on compute to update the tax base.'))
for key in compute_taxes:
if key not in tax_key:
raise except_orm(_('Warning!'), _('Taxes are missing!\nClick on compute button.'))
raise UserError(_('Taxes are missing!\nClick on compute button.'))
@api.multi
def compute_invoice_totals(self, company_currency, ref, invoice_move_lines):
@@ -794,9 +788,9 @@ class account_invoice(models.Model):
for inv in self:
if not inv.journal_id.sequence_id:
raise except_orm(_('Error!'), _('Please define sequence on the journal related to this invoice.'))
raise UserError(_('Please define sequence on the journal related to this invoice.'))
if not inv.invoice_line:
raise except_orm(_('No Invoice Lines!'), _('Please create some invoice lines.'))
raise UserError(_('Please create some invoice lines.'))
if inv.move_id:
continue
@@ -816,7 +810,7 @@ class account_invoice(models.Model):
# I disabled the check_total feature
if self.env['res.users'].has_group('account.group_supplier_inv_check_total'):
if inv.type in ('in_invoice', 'in_refund') and abs(inv.check_total - inv.amount_total) >= (inv.currency_id.rounding / 2.0):
raise except_orm(_('Bad Total!'), _('Please verify the price of the invoice!\nThe encoded total does not match the computed total.'))
raise UserError(_('Please verify the price of the invoice!\nThe encoded total does not match the computed total.'))
if inv.payment_term:
total_fixed = total_percent = 0
@@ -827,7 +821,7 @@ class account_invoice(models.Model):
total_percent += (line.value_amount/100.0)
total_fixed = (total_fixed * 100) / (inv.amount_total or 1.0)
if (total_fixed + total_percent) > 100:
raise except_orm(_('Error!'), _("Cannot create the invoice.\nThe related payment term is probably misconfigured as it gives a computed amount greater than the total invoiced amount. In order to avoid rounding issues, the latest line of your payment term must be of type 'balance'."))
raise UserError(_("Cannot create the invoice.\nThe related payment term is probably misconfigured as it gives a computed amount greater than the total invoiced amount. In order to avoid rounding issues, the latest line of your payment term must be of type 'balance'."))
# one move line per tax line
iml += account_invoice_tax.move_line_get(inv.id)
@@ -890,8 +884,7 @@ class account_invoice(models.Model):
journal = inv.journal_id.with_context(ctx)
if journal.centralisation:
raise except_orm(_('User Error!'),
_('You cannot create an invoice on a centralized journal. Uncheck the centralized counterpart box in the related journal from the configuration menu.'))
raise UserError(_('You cannot create an invoice on a centralized journal. Uncheck the centralized counterpart box in the related journal from the configuration menu.'))
line = inv.finalize_invoice_move_lines(line)
@@ -993,7 +986,7 @@ class account_invoice(models.Model):
if inv.payment_ids:
for move_line in inv.payment_ids:
if move_line.reconcile_partial_id.line_partial_ids:
raise except_orm(_('Error!'), _('You cannot cancel an invoice which is partially paid. You need to unreconcile related payment entries first.'))
raise UserError(_('You cannot cancel an invoice which is partially paid. You need to unreconcile related payment entries first.'))
# First, set the invoices as cancelled and detach the move ids
self.write({'state': 'cancel', 'move_id': False})
@@ -1308,7 +1301,7 @@ class account_invoice_line(models.Model):
self = self.with_context(company_id=company_id, force_company=company_id)
if not partner_id:
raise except_orm(_('No Partner Defined!'), _("You must first select a partner!"))
raise UserError(_("You must first select a partner!"))
if not product:
if type in ('in_invoice', 'in_refund'):
return {'value': {}, 'domain': {'product_uom': []}}
+25 -28
View File
@@ -29,6 +29,7 @@ import openerp.addons.decimal_precision as dp
from openerp import tools
from openerp.report import report_sxw
import openerp
from openerp.exceptions import UserError
class account_move_line(osv.osv):
_name = "account.move.line"
@@ -92,7 +93,7 @@ class account_move_line(osv.osv):
if initial_bal and not context.get('periods', False) and not where_move_lines_by_date:
#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
#so we have to invalidate this query
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."))
raise UserError(("You have not supplied enough arguments to compute the initial balance, please select a period and a journal in the context."))
if context.get('journal_ids', False):
@@ -191,7 +192,7 @@ class account_move_line(osv.osv):
acc_ana_line_obj.unlink(cr,uid,[obj.id for obj in obj_line.analytic_lines])
if obj_line.analytic_account_id:
if not obj_line.journal_id.analytic_journal_id:
raise osv.except_osv(_('No Analytic Journal!'),_("You have to define an analytic journal on the '%s' journal!") % (obj_line.journal_id.name, ))
raise UserError(("You have to define an analytic journal on the '%s' journal!") % (obj_line.journal_id.name, ))
vals_line = self._prepare_analytic_line(cr, uid, obj_line, context=context)
acc_ana_line_obj.create(cr, uid, vals_line)
return True
@@ -596,7 +597,7 @@ class account_move_line(osv.osv):
lines = self.browse(cr, uid, ids, context=context)
for l in lines:
if l.account_id.type == 'closed':
raise osv.except_osv(_('Error!'), _('You cannot create journal items on a closed account %s %s.') % (l.account_id.code, l.account_id.name))
raise UserError(('You cannot create journal items on a closed account %s %s.') % (l.account_id.code, l.account_id.name))
return True
def _check_company_id(self, cr, uid, ids, context=None):
@@ -883,7 +884,7 @@ class account_move_line(osv.osv):
context = {}
for line in self.browse(cr, uid, ids, context=context):
if company_list and not line.company_id.id in company_list:
raise osv.except_osv(_('Warning!'), _('To reconcile the entries company should be the same for all entries.'))
raise UserError(_('To reconcile the entries company should be the same for all entries.'))
company_list.append(line.company_id.id)
for line in self.browse(cr, uid, ids, context=context):
@@ -892,11 +893,11 @@ class account_move_line(osv.osv):
else:
currency_id = line.company_id.currency_id
if line.reconcile_id:
raise osv.except_osv(_('Warning'), _("Journal Item '%s' (id: %s), Move '%s' is already reconciled!") % (line.name, line.id, line.move_id.name))
raise UserError(_("Journal Item '%s' (id: %s), Move '%s' is already reconciled!") % (line.name, line.id, line.move_id.name))
if line.reconcile_partial_id:
for line2 in line.reconcile_partial_id.line_partial_ids:
if line2.state != 'valid':
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))
raise UserError(_("Journal Item '%s' (id: %s) cannot be used in a reconciliation as it is not balanced!") % (line2.name, line2.id))
if not line2.reconcile_id:
if line2.id not in merges:
merges.append(line2.id)
@@ -941,12 +942,11 @@ class account_move_line(osv.osv):
company_list = []
for line in self.browse(cr, uid, ids, context=context):
if company_list and not line.company_id.id in company_list:
raise osv.except_osv(_('Warning!'), _('To reconcile the entries company should be the same for all entries.'))
raise UserError(_('To reconcile the entries company should be the same for all entries.'))
company_list.append(line.company_id.id)
for line in unrec_lines:
if line.state <> 'valid':
raise osv.except_osv(_('Error!'),
_('Entry "%s" is not valid !') % line.name)
raise UserError(_('Entry "%s" is not valid !') % line.name)
credit += line['credit']
debit += line['debit']
currency += line['amount_currency'] or 0.0
@@ -968,19 +968,19 @@ class account_move_line(osv.osv):
r = cr.fetchall()
#TODO: move this check to a constraint in the account_move_reconcile object
if len(r) != 1:
raise osv.except_osv(_('Error'), _('Entries are not of the same account or already reconciled ! '))
raise UserError(_('Entries are not of the same account or already reconciled ! '))
if not unrec_lines:
raise osv.except_osv(_('Error!'), _('Entry is already reconciled.'))
raise UserError(_('Entry is already reconciled.'))
account = account_obj.browse(cr, uid, account_id, context=context)
if not account.reconcile:
raise osv.except_osv(_('Error'), _('The account is not defined to be reconciled !'))
raise UserError(_('The account is not defined to be reconciled !'))
if r[0][1] != None:
raise osv.except_osv(_('Error!'), _('Some entries are already reconciled.'))
raise UserError(_('Some entries are already reconciled.'))
if (not currency_obj.is_zero(cr, uid, account.company_id.currency_id, writeoff)) or \
(account.currency_id and (not currency_obj.is_zero(cr, uid, account.currency_id, currency))):
if not writeoff_acc_id:
raise osv.except_osv(_('Warning!'), _('You have to provide an account for the write off/exchange difference entry.'))
raise UserError(_('You have to provide an account for the write off/exchange difference entry.'))
if writeoff > 0:
debit = writeoff
credit = 0.0
@@ -1118,9 +1118,7 @@ class account_move_line(osv.osv):
res = cr.fetchone()
if res:
if res[1] != 'draft':
raise osv.except_osv(_('User Error!'),
_('The account move (%s) for centralisation ' \
'has been confirmed.') % res[2])
raise UserError(_('The account move (%s) for centralisation has been confirmed.') % res[2])
return res
def _remove_move_reconcile(self, cr, uid, move_ids=None, opening_reconciliation=False, context=None):
@@ -1141,8 +1139,7 @@ class account_move_line(osv.osv):
all_moves = list(set(all_moves) - set(move_ids))
if unlink_ids:
if opening_reconciliation:
raise osv.except_osv(_('Warning!'),
_('Opening Entries have already been generated. Please run "Cancel Closing Entries" wizard to cancel those entries and then run this wizard.'))
raise UserError(_('Opening Entries have already been generated. Please run "Cancel Closing Entries" wizard to cancel those entries and then run this wizard.'))
obj_move_rec.write(cr, uid, unlink_ids, {'opening_reconciliation': False})
obj_move_rec.unlink(cr, uid, unlink_ids)
if len(all_moves) >= 2:
@@ -1175,9 +1172,9 @@ class account_move_line(osv.osv):
if isinstance(ids, (int, long)):
ids = [ids]
if vals.get('account_tax_id', False):
raise osv.except_osv(_('Unable to change tax!'), _('You cannot change the tax, you should remove and recreate lines.'))
raise UserError(_('You cannot change the tax, you should remove and recreate lines.'))
if ('account_id' in vals) and not account_obj.read(cr, uid, vals['account_id'], ['active'])['active']:
raise osv.except_osv(_('Bad Account!'), _('You cannot use an inactive account.'))
raise UserError(_('You cannot use an inactive account.'))
if update_check:
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):
self._update_check(cr, uid, ids, context)
@@ -1224,7 +1221,7 @@ class account_move_line(osv.osv):
period = period_obj.browse(cr, uid, period_id, context=context)
for (state,) in result:
if state == 'done':
raise osv.except_osv(_('Error!'), _('You can not add/modify entries in a closed period %s of journal %s.' % (period.name,journal.name)))
raise UserError(_('You can not add/modify entries in a closed period %s of journal %s.' % (period.name,journal.name)))
if not result:
jour_period_obj.create(cr, uid, {
'name': (journal.code or journal.name)+':'+(period.name or ''),
@@ -1238,9 +1235,9 @@ class account_move_line(osv.osv):
for line in self.browse(cr, uid, ids, context=context):
err_msg = _('Move name (id): %s (%s)') % (line.move_id.name, str(line.move_id.id))
if line.move_id.state <> 'draft' and (not line.journal_id.entry_posted):
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)
raise UserError(_('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)
if line.reconcile_id:
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)
raise UserError(_('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)
t = (line.journal_id.id, line.period_id.id)
if t not in done:
self._update_journal_check(cr, uid, line.journal_id.id, line.period_id.id, context)
@@ -1261,7 +1258,7 @@ class account_move_line(osv.osv):
if move.date and not vals.get('date'):
vals['date'] = move.date
if ('account_id' in vals) and not account_obj.read(cr, uid, [vals['account_id']], ['active'])[0]['active']:
raise osv.except_osv(_('Bad Account!'), _('You cannot use an inactive account.'))
raise UserError(_('You cannot use an inactive account.'))
if 'journal_id' in vals and vals['journal_id']:
context['journal_id'] = vals['journal_id']
if 'period_id' in vals and vals['period_id']:
@@ -1274,7 +1271,7 @@ class account_move_line(osv.osv):
if 'period_id' in context and not isinstance(context.get('period_id', ''), (int, long)):
period_candidate_ids = self.pool.get('account.period').name_search(cr, uid, name=context.get('period_id',''))
if len(period_candidate_ids) != 1:
raise osv.except_osv(_('Error!'), _('No period found or more than one period found for the given date.'))
raise UserError(_('No period found or more than one period found for the given date.'))
context['period_id'] = period_candidate_ids[0][0]
if not context.get('journal_id', False) and context.get('search_default_journal_id', False):
context['journal_id'] = context.get('search_default_journal_id')
@@ -1303,7 +1300,7 @@ class account_move_line(osv.osv):
move_id = move_obj.create(cr, uid, v, context)
vals['move_id'] = move_id
else:
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.'))
raise UserError(_('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.'))
ok = not (journal.type_control_ids or journal.account_control_ids)
if ('account_id' in vals):
account = account_obj.browse(cr, uid, vals['account_id'], context=context)
@@ -1328,7 +1325,7 @@ class account_move_line(osv.osv):
vals['amount_currency'] = cur_obj.compute(cr, uid, account.company_id.currency_id.id,
account.currency_id.id, vals.get('debit', 0.0)-vals.get('credit', 0.0), context=ctx)
if not ok:
raise osv.except_osv(_('Bad Account!'), _('You cannot use this general account in this journal, check the tab \'Entry Controls\' on the related journal.'))
raise UserError(_('You cannot use this general account in this journal, check the tab \'Entry Controls\' on the related journal.'))
result = super(account_move_line, self).create(cr, uid, vals, context=context)
# CREATE Taxes
+2 -1
View File
@@ -35,6 +35,7 @@ except ImportError:
from openerp.release import serie
from openerp.tools.translate import _
from openerp.osv import fields, osv
from openerp.exceptions import UserError
_logger = logging.getLogger(__name__)
@@ -111,7 +112,7 @@ class account_installer(osv.osv_memory):
def check_unconfigured_cmp(self, cr, uid, context=None):
""" check if there are still unconfigured companies """
if not self.get_unconfigured_cmp(cr, uid, context=context):
raise osv.except_osv(_('No Unconfigured Company!'), _("There is currently no company without chart of account. The wizard will therefore not be executed."))
raise UserError(_("There is currently no company without chart of account. The wizard will therefore not be executed."))
def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
if context is None: context = {}
+3 -1
View File
@@ -21,6 +21,7 @@
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class product_category(osv.osv):
_inherit = "product.category"
@@ -66,5 +67,6 @@ class product_template(osv.osv):
if 'uom_po_id' in vals:
product_ids = self.pool.get('product.product').search(cr, uid, [('product_tmpl_id', 'in', ids)], context=context)
if self.pool.get('account.move.line').search(cr, uid, [('product_id', 'in', product_ids)], context=context, limit=1):
raise osv.except_osv(_('Error!'), _("You can not change the unit of measure of a product that has been already used in an account journal item. If you need to change the unit of measure, you may deactivate this product.") % ())
raise UserError(_("You can not change the unit of measure of a product that has been already used in an \
account journal item. If you need to change the unit of measure, you may deactivate this product."))
return super(product_template, self).write(cr, uid, ids, vals, context=context)
@@ -23,6 +23,7 @@ import time
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class account_automatic_reconcile(osv.osv_memory):
_name = 'account.automatic.reconcile'
@@ -151,7 +152,7 @@ class account_automatic_reconcile(osv.osv_memory):
allow_write_off = form.allow_write_off
reconciled = unreconciled = 0
if not form.account_ids:
raise osv.except_osv(_('User Error!'), _('You must select accounts to reconcile.'))
raise UserError(_('You must select accounts to reconcile.'))
for account_id in form.account_ids:
params = (account_id.id,)
if not allow_write_off:
@@ -21,6 +21,7 @@
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class account_change_currency(osv.osv_memory):
_name = 'account.change.currency'
@@ -35,7 +36,7 @@ class account_change_currency(osv.osv_memory):
context = {}
if context.get('active_id',False):
if obj_inv.browse(cr, uid, context['active_id']).state != 'draft':
raise osv.except_osv(_('Error!'), _('You can only change currency for Draft Invoice.'))
raise UserError(_('You can only change currency for Draft Invoice.'))
pass
def change_currency(self, cr, uid, ids, context=None):
@@ -56,18 +57,18 @@ class account_change_currency(osv.osv_memory):
if invoice.company_id.currency_id.id == invoice.currency_id.id:
new_price = line.price_unit * rate
if new_price <= 0:
raise osv.except_osv(_('Error!'), _('New currency is not configured properly.'))
raise UserError(_('New currency is not configured properly.'))
if invoice.company_id.currency_id.id != invoice.currency_id.id and invoice.company_id.currency_id.id == new_currency:
old_rate = invoice.currency_id.rate
if old_rate <= 0:
raise osv.except_osv(_('Error!'), _('Current currency is not configured properly.'))
raise UserError(_('Current currency is not configured properly.'))
new_price = line.price_unit / old_rate
if invoice.company_id.currency_id.id != invoice.currency_id.id and invoice.company_id.currency_id.id != new_currency:
old_rate = invoice.currency_id.rate
if old_rate <= 0:
raise osv.except_osv(_('Error!'), _('Current currency is not configured properly.'))
raise UserError(_('Current currency is not configured properly.'))
new_price = (line.price_unit / old_rate ) * rate
obj_inv_line.write(cr, uid, [line.id], {'price_unit': new_price})
obj_inv.write(cr, uid, [invoice.id], {'currency_id': new_currency}, context=context)
@@ -20,6 +20,7 @@
##############################################################################
from openerp.osv import fields, osv
from openerp.exceptions import UserError
class accounting_report(osv.osv_memory):
@@ -69,7 +70,7 @@ class accounting_report(osv.osv_memory):
result['date_to'] = data['form']['date_to_cmp']
elif data['form']['filter_cmp'] == 'filter_period':
if not data['form']['period_from_cmp'] or not data['form']['period_to_cmp']:
raise osv.except_osv(_('Error!'),_('Select a starting and an ending period'))
raise UserError(_('Select a starting and an ending period'))
result['period_from'] = data['form']['period_from_cmp']
result['period_to'] = data['form']['period_to_cmp']
return result
@@ -21,6 +21,7 @@
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class account_fiscalyear_close(osv.osv_memory):
"""
@@ -59,7 +60,7 @@ class account_fiscalyear_close(osv.osv_memory):
#check that the reconcilation concern journal entries from only one company
cr.execute('select distinct(company_id) from account_move_line where id in %s',(tuple(ids),))
if len(cr.fetchall()) > 1:
raise osv.except_osv(_('Warning!'), _('The entries to reconcile should belong to the same company.'))
raise UserError(_('The entries to reconcile should belong to the same company.'))
r_id = self.pool.get('account.move.reconcile').create(cr, uid, {'type': 'auto', 'opening_reconciliation': True})
cr.execute('update account_move_line set reconcile_id = %s where id in %s',(r_id, tuple(ids),))
obj_acc_move_line.invalidate_cache(cr, uid, ['reconcile_id'], ids, context=context)
@@ -86,7 +87,7 @@ class account_fiscalyear_close(osv.osv_memory):
fy2_period_set = ','.join(map(lambda id: str(id[0]), cr.fetchall()))
if not fy_period_set or not fy2_period_set:
raise osv.except_osv(_('User Error!'), _('The periods to generate opening entries cannot be found.'))
raise UserError(_('The periods to generate opening entries cannot be found.'))
period = obj_acc_period.browse(cr, uid, data[0].period_id.id, context=context)
new_fyear = obj_acc_fiscalyear.browse(cr, uid, data[0].fy2_id.id, context=context)
@@ -97,11 +98,9 @@ class account_fiscalyear_close(osv.osv_memory):
company_id = new_journal.company_id.id
if not new_journal.default_credit_account_id or not new_journal.default_debit_account_id:
raise osv.except_osv(_('User Error!'),
_('The journal must have default credit and debit account.'))
raise UserError(_('The journal must have default credit and debit account.'))
if (not new_journal.centralisation) or new_journal.entry_posted:
raise osv.except_osv(_('User Error!'),
_('The journal must have centralized counterpart without the Skipping draft state option checked.'))
raise UserError(_('The journal must have centralized counterpart without the Skipping draft state option checked.'))
#delete existing move and move lines if any
move_ids = obj_acc_move.search(cr, uid, [
@@ -21,6 +21,7 @@
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class account_fiscalyear_close_state(osv.osv_memory):
"""
@@ -51,7 +52,7 @@ class account_fiscalyear_close_state(osv.osv_memory):
account_move_ids = account_move_obj.search(cr, uid, [('period_id.fiscalyear_id', '=', fy_id), ('state', '=', "draft")], context=context)
if account_move_ids:
raise osv.except_osv(_('Invalid Action!'), _('In order to close a fiscalyear, you must first post related journal entries.'))
raise UserError(_('In order to close a fiscalyear, you must first post related journal entries.'))
cr.execute('UPDATE account_journal_period ' \
'SET state = %s ' \
@@ -23,6 +23,7 @@ import time
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class account_invoice_refund(osv.osv_memory):
@@ -113,9 +114,9 @@ class account_invoice_refund(osv.osv_memory):
journal_id = form.journal_id.id
for inv in inv_obj.browse(cr, uid, context.get('active_ids'), context=context):
if inv.state in ['draft', 'proforma2', 'cancel']:
raise osv.except_osv(_('Error!'), _('Cannot %s draft/proforma/cancel invoice.') % (mode))
raise UserError(_('Cannot operate on draft/proforma/cancel invoices.'))
if inv.reconciled and mode in ('cancel', 'modify'):
raise osv.except_osv(_('Error!'), _('Cannot %s invoice which is already reconciled, invoice should be unreconciled first. You can only refund this invoice.') % (mode))
raise UserError(_('Cannot operate on cancel/modified invoice which is already reconciled, invoice should be unreconciled first. You can only refund this invoice.'))
if form.period.id:
period = form.period.id
else:
@@ -150,8 +151,7 @@ class account_invoice_refund(osv.osv_memory):
description = inv.name
if not period:
raise osv.except_osv(_('Insufficient Data!'), \
_('No period found on the invoice.'))
raise UserError(_('No period found on the invoice.'))
refund_id = inv_obj.refund(cr, uid, [inv.id], date, period, description, journal_id, context=context)
refund = inv_obj.browse(cr, uid, refund_id[0], context=context)
@@ -21,6 +21,7 @@
from openerp.osv import osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class account_invoice_confirm(osv.osv_memory):
"""
@@ -38,7 +39,7 @@ class account_invoice_confirm(osv.osv_memory):
proxy = self.pool['account.invoice']
for record in proxy.browse(cr, uid, active_ids, context=context):
if record.state not in ('draft', 'proforma', 'proforma2'):
raise osv.except_osv(_('Warning!'), _("Selected invoice(s) cannot be confirmed as they are not in 'Draft' or 'Pro-Forma' state."))
raise UserError(_("Selected invoice(s) cannot be confirmed as they are not in 'Draft' or 'Pro-Forma' state."))
record.signal_workflow('invoice_open')
return {'type': 'ir.actions.act_window_close'}
@@ -61,6 +62,6 @@ class account_invoice_cancel(osv.osv_memory):
for record in proxy.browse(cr, uid, active_ids, context=context):
if record.state in ('cancel','paid'):
raise osv.except_osv(_('Warning!'), _("Selected invoice(s) cannot be cancelled as they are already in 'Cancelled' or 'Done' state."))
raise UserError(_("Selected invoice(s) cannot be cancelled as they are already in 'Cancelled' or 'Done' state."))
record.signal_workflow('invoice_cancel')
return {'type': 'ir.actions.act_window_close'}
@@ -21,6 +21,7 @@
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class account_move_bank_reconcile(osv.osv_memory):
"""
@@ -46,8 +47,7 @@ class account_move_bank_reconcile(osv.osv_memory):
from account_journal where id=%s', (data['journal_id'],))
account_id = cr.fetchone()[0]
if not account_id:
raise osv.except_osv(_('Error!'), _('You have to define \
the bank account\nin the journal definition for reconciliation.'))
raise UserError(_('You have to define the bank account\nin the journal definition for reconciliation.'))
return {
'domain': "[('journal_id','=',%d), ('account_id','=',%d), ('state','<>','draft')]" % (data['journal_id'], account_id),
'name': _('Standard Encoding'),
@@ -21,6 +21,7 @@
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class account_open_closed_fiscalyear(osv.osv_memory):
_name = "account.open.closed.fiscalyear"
@@ -36,7 +37,7 @@ class account_open_closed_fiscalyear(osv.osv_memory):
data = self.browse(cr, uid, ids, context=context)[0]
period_journal = data.fyear_id.end_journal_period_id or False
if not period_journal:
raise osv.except_osv(_('Error!'), _("You have to set the 'End of Year Entries Journal' for this Fiscal Year which is set after generating opening entries from 'Generate Opening Entries'."))
raise UserError(_("You have to set the 'End of Year Entries Journal' for this Fiscal Year which is set after generating opening entries from 'Generate Opening Entries'."))
ids_move = move_obj.search(cr, uid, [('journal_id','=',period_journal.journal_id.id),('period_id','=',period_journal.period_id.id)])
if ids_move:
@@ -21,6 +21,7 @@
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class account_period_close(osv.osv_memory):
"""
@@ -49,7 +50,7 @@ class account_period_close(osv.osv_memory):
for id in context['active_ids']:
account_move_ids = account_move_obj.search(cr, uid, [('period_id', '=', id), ('state', '=', "draft")], context=context)
if account_move_ids:
raise osv.except_osv(_('Invalid Action!'), _('In order to close a period, you must first post related journal entries.'))
raise UserError(_('In order to close a period, you must first post related journal entries.'))
cr.execute('update account_journal_period set state=%s where period_id=%s', (mode, id))
cr.execute('update account_period set state=%s where id=%s', (mode, id))
@@ -24,6 +24,7 @@ from datetime import datetime
from dateutil.relativedelta import relativedelta
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class account_aged_trial_balance(osv.osv_memory):
@@ -54,9 +55,9 @@ class account_aged_trial_balance(osv.osv_memory):
period_length = data['form']['period_length']
if period_length<=0:
raise osv.except_osv(_('User Error!'), _('You must set a period length greater than 0.'))
raise UserError(_('You must set a period length greater than 0.'))
if not data['form']['date_from']:
raise osv.except_osv(_('User Error!'), _('You must set a start date.'))
raise UserError(_('You must set a start date.'))
start = datetime.strptime(data['form']['date_from'], "%Y-%m-%d")
@@ -25,6 +25,7 @@ from lxml import etree
from openerp.osv import fields, osv
from openerp.osv.orm import setup_modifiers
from openerp.tools.translate import _
from openerp.exceptions import UserError
class account_common_report(osv.osv_memory):
_name = "account.common.report"
@@ -160,7 +161,7 @@ class account_common_report(osv.osv_memory):
result['date_to'] = data['form']['date_to']
elif data['form']['filter'] == 'filter_period':
if not data['form']['period_from'] or not data['form']['period_to']:
raise osv.except_osv(_('Error!'),_('Select a starting and an ending period.'))
raise UserError(_('Select a starting and an ending period.'))
result['period_from'] = data['form']['period_from']
result['period_to'] = data['form']['period_to']
return result
+2 -1
View File
@@ -21,6 +21,7 @@
from openerp.osv import osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class account_state_open(osv.osv_memory):
_name = 'account.state.open'
@@ -35,6 +36,6 @@ class account_state_open(osv.osv_memory):
if isinstance(active_ids, list):
invoice = proxy.browse(cr, uid, active_ids[0], context=context)
if invoice.reconciled:
raise osv.except_osv(_('Warning!'), _('Invoice is already reconciled.'))
raise UserError(_('Invoice is already reconciled.'))
invoice.signal_workflow('open_test')
return {'type': 'ir.actions.act_window_close'}
+2 -1
View File
@@ -22,6 +22,7 @@ import time
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class account_use_model(osv.osv_memory):
@@ -41,7 +42,7 @@ class account_use_model(osv.osv_memory):
for line in model.lines_id:
if line.date_maturity == 'partner':
if not line.partner_id:
raise osv.except_osv(_('Error!'), _("Maturity date of entry line generated by model line '%s' is based on partner payment term!"\
raise UserError(_("Maturity date of entry line generated by model line '%s' is based on partner payment term!"\
"\nPlease define partner on it!")%line.name)
pass
@@ -20,6 +20,7 @@
##############################################################################
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class validate_account_move(osv.osv_memory):
_name = "validate.account.move"
@@ -36,7 +37,7 @@ class validate_account_move(osv.osv_memory):
data = self.read(cr, uid, ids[0], context=context)
ids_move = obj_move.search(cr, uid, [('state','=','draft'),('journal_id','in',tuple(data['journal_ids'])),('period_id','in',tuple(data['period_ids']))], order='date')
if not ids_move:
raise osv.except_osv(_('Warning!'), _('Specified journals do not have any account move entries in draft state for the specified periods.'))
raise UserError(_('Specified journals do not have any account move entries in draft state for the specified periods.'))
obj_move.button_validate(cr, uid, ids_move, context=context)
return {'type': 'ir.actions.act_window_close'}
@@ -57,6 +58,6 @@ class validate_account_move_lines(osv.osv_memory):
move_ids.append(line.move_id.id)
move_ids = list(set(move_ids))
if not move_ids:
raise osv.except_osv(_('Warning!'), _('Selected Entry Lines does not have any account move entries in draft state.'))
raise UserError(_('Selected Entry Lines does not have any account move entries in draft state.'))
obj_move.button_validate(cr, uid, move_ids, context)
return {'type': 'ir.actions.act_window_close'}
+5 -6
View File
@@ -1,6 +1,7 @@
from openerp.osv import fields, osv
import openerp.addons.decimal_precision as dp
from openerp.tools.translate import _
from openerp.exceptions import UserError
class CashBox(osv.osv_memory):
_register = False
@@ -28,12 +29,10 @@ class CashBox(osv.osv_memory):
for box in self.browse(cr, uid, ids, context=context):
for record in records:
if not record.journal_id:
raise osv.except_osv(_('Error!'),
_("Please check that the field 'Journal' is set on the Bank Statement"))
raise UserError(_("Please check that the field 'Journal' is set on the Bank Statement"))
if not record.journal_id.internal_account_id:
raise osv.except_osv(_('Error!'),
_("Please check that the field 'Internal Transfers Account' is set on the payment method '%s'.") % (record.journal_id.name,))
raise UserError(_("Please check that the field 'Internal Transfers Account' is set on the payment method '%s'.") % (record.journal_id.name,))
self._create_bank_statement_line(cr, uid, box, record, context=context)
@@ -54,7 +53,7 @@ class CashBoxIn(CashBox):
def _compute_values_for_statement_line(self, cr, uid, box, record, context=None):
if not record.journal_id.internal_account_id.id:
raise osv.except_osv(_('Configuration Error'), _("You should have defined an 'Internal Transfer Account' in your cash register's journal!"))
raise UserError(_("You should have defined an 'Internal Transfer Account' in your cash register's journal!"))
return {
'statement_id': record.id,
'journal_id': record.journal_id.id,
@@ -72,7 +71,7 @@ class CashBoxOut(CashBox):
def _compute_values_for_statement_line(self, cr, uid, box, record, context=None):
if not record.journal_id.internal_account_id.id:
raise osv.except_osv(_('Configuration Error'), _("You should have defined an 'Internal Transfer Account' in your cash register's journal!"))
raise UserError(_("You should have defined an 'Internal Transfer Account' in your cash register's journal!"))
amount = box.amount or 0.0
return {
'statement_id': record.id,
@@ -26,6 +26,7 @@ import time
from openerp.osv import osv, fields
import openerp.tools
from openerp.tools.translate import _
from openerp.exceptions import UserError
from openerp.addons.decimal_precision import decimal_precision as dp
@@ -660,13 +661,12 @@ class account_analytic_account(osv.osv):
journal_obj = self.pool.get('account.journal')
if not contract.partner_id:
raise osv.except_osv(_('No Customer Defined!'),_("You must first select a Customer for Contract %s!") % contract.name )
raise UserError(_("You must first select a Customer for Contract %s!") % contract.name )
fpos = contract.partner_id.property_account_position or False
journal_ids = journal_obj.search(cr, uid, [('type', '=','sale'),('company_id', '=', contract.company_id.id or False)], limit=1)
if not journal_ids:
raise osv.except_osv(_('Error!'),
_('Please define a sale journal for the company "%s".') % (contract.company_id.name or '', ))
raise UserError(_('Please define a sale journal for the company "%s".') % (contract.company_id.name or '', ))
partner_payment_term = contract.partner_id.property_payment_term and contract.partner_id.property_payment_term.id or False
@@ -21,6 +21,7 @@
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class sale_configuration(osv.osv_memory):
_inherit = 'sale.config.settings'
@@ -54,7 +55,8 @@ class sale_configuration(osv.osv_memory):
if product and product.exists():
product.write({'uom_id': wizard.time_unit.id, 'uom_po_id': wizard.time_unit.id})
else:
_logger.warning("Product with xml_id 'product.product_product_consultant' not found, UoMs not updated!")
_logger.info("Product with xml_id 'product.product_product_consultant' not found, UoMs not updated!")
raise UserError(_("Product with xml_id 'product.product_product_consultant' not found, UoMs not updated!"))
if wizard.module_project and wizard.time_unit:
user = self.pool.get('res.users').browse(cr, uid, uid, context)
@@ -25,6 +25,7 @@ from lxml import etree
from openerp.osv import fields, osv
from openerp import tools
from openerp.tools.translate import _
from openerp.exceptions import UserError
class one2many_mod2(fields.one2many):
def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
@@ -215,7 +216,7 @@ class account_analytic_plan_instance(osv.osv):
pids = ana_plan_instance_obj.search(cr, uid, [('name','=',vals['name']), ('code','=',vals['code']), ('plan_id','<>',False)], context=context)
if pids:
raise osv.except_osv(_('Error!'), _('A model with this name and code already exists.'))
raise UserError(_('A model with this name and code already exists.'))
res = acct_anal_plan_line_obj.search(cr, uid, [('plan_id','=',journal.plan_id.id)], context=context)
for i in res:
@@ -228,7 +229,7 @@ class account_analytic_plan_instance(osv.osv):
if acct_anal_acct.search(cr, uid, [('parent_id', 'child_of', [item.root_analytic_id.id]), ('id', '=', tempo[2]['analytic_account_id'])], context=context):
total_per_plan += tempo[2]['rate']
if total_per_plan < item.min_required or total_per_plan > item.max_required:
raise osv.except_osv(_('Error!'),_('The total should be between %s and %s.') % (str(item.min_required), str(item.max_required)))
raise UserError(_('The total should be between %s and %s.') % (str(item.min_required), str(item.max_required)))
return super(account_analytic_plan_instance, self).create(cr, uid, vals, context=context)
@@ -332,7 +333,7 @@ class account_move_line(osv.osv):
for line in self.browse(cr, uid, ids, context=context):
if line.analytics_id:
if not line.journal_id.analytic_journal_id:
raise osv.except_osv(_('No Analytic Journal!'),_("You have to define an analytic journal on the '%s' journal.") % (line.journal_id.name,))
raise UserError(_("You have to define an analytic journal on the '%s' journal.") % (line.journal_id.name,))
toremove = analytic_line_obj.search(cr, uid, [('move_id','=',line.id)], context=context)
if toremove:
@@ -468,7 +469,7 @@ class account_bank_statement(osv.osv):
for st_line in st.line_ids:
if st_line.analytics_id:
if not st.journal_id.analytic_journal_id:
raise osv.except_osv(_('No Analytic Journal!'),_("You have to define an analytic journal on the '%s' journal.") % (st.journal_id.name,))
raise UserError(_("You have to define an analytic journal on the '%s' journal.") % (st.journal_id.name,))
if not st_line.amount:
continue
return True
@@ -23,6 +23,7 @@ import time
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class account_crossovered_analytic(osv.osv_memory):
@@ -59,7 +60,7 @@ class account_crossovered_analytic(osv.osv_memory):
flag = False
break
if flag:
raise osv.except_osv(_('User Error!'),_('There are no analytic lines related to account %s.' % name))
raise UserError(_('There are no analytic lines related to account %s.' % name))
datas = {
'ids': [],
@@ -21,6 +21,7 @@
from openerp.osv import osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class analytic_plan_create_model(osv.osv_memory):
_name = "analytic.plan.create.model"
@@ -35,10 +36,10 @@ class analytic_plan_create_model(osv.osv_memory):
if 'active_id' in context and context['active_id']:
plan = plan_obj.browse(cr, uid, context['active_id'], context=context)
if (not plan.name) or (not plan.code):
raise osv.except_osv(_('Error!'), _('Please put a name and a code before saving the model.'))
raise UserError(_('Please put a name and a code before saving the model.'))
pids = anlytic_plan_obj.search(cr, uid, [], context=context)
if not pids:
raise osv.except_osv(_('Error!'), _('There is no analytic plan defined.'))
raise UserError(_('There is no analytic plan defined.'))
plan_obj.write(cr, uid, [context['active_id']], {'plan_id':pids[0]}, context=context)
model_data_ids = mod_obj.search(cr, uid, [('model', '=', 'ir.ui.view'),('name', '=', 'view_analytic_plan_create_model')], context=context)
+2 -1
View File
@@ -26,6 +26,7 @@ from dateutil.relativedelta import relativedelta
from openerp.osv import fields, osv
import openerp.addons.decimal_precision as dp
from openerp.tools.translate import _
from openerp.exceptions import UserError
class account_asset_category(osv.osv):
_name = 'account.asset.category'
@@ -78,7 +79,7 @@ class account_asset_asset(osv.osv):
def unlink(self, cr, uid, ids, context=None):
for asset in self.browse(cr, uid, ids, context=context):
if asset.account_move_line_ids:
raise osv.except_osv(_('Error!'), _('You cannot delete an asset that contains posted depreciation lines.'))
raise UserError(_('You cannot delete an asset that contains posted depreciation lines.'))
return super(account_asset_asset, self).unlink(cr, uid, ids, context=context)
def _get_period(self, cr, uid, context=None):
@@ -24,6 +24,7 @@ import time
from openerp.osv import fields, osv
import openerp.addons.decimal_precision as dp
from openerp.tools.translate import _
from openerp.exceptions import UserError
class account_bank_statement(osv.osv):
_inherit = 'account.bank.statement'
@@ -130,6 +131,5 @@ class account_bank_statement_line(osv.osv):
if context is None:
context = {}
if context.get('block_statement_line_delete', False):
raise osv.except_osv(_('Warning!'), _('Delete operation not allowed. \
Please go to the associated bank statement in order to delete and/or modify bank statement line.'))
raise UserError(_('Delete operation not allowed. Please go to the associated bank statement in order to delete and/or modify bank statement line.'))
return super(account_bank_statement_line, self).unlink(cr, uid, ids, context=context)
@@ -5,6 +5,7 @@ import base64
from openerp import SUPERUSER_ID
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
import logging
_logger = logging.getLogger(__name__)
@@ -93,12 +94,12 @@ class account_bank_statement_import(osv.TransientModel):
-o 'partner_name': string
-o 'ref': string
"""
raise osv.except_osv(_('Error'), _('Could not make sense of the given file.\nDid you install the module to support this type of file ?'))
raise UserError(_('Could not make sense of the given file.\nDid you install the module to support this type of file ?'))
def _check_parsed_data(self, cr, uid, stmts_vals, context=None):
""" Basic and structural verifications """
if len(stmts_vals) == 0:
raise osv.except_osv(_('Error'), _('This file doesn\'t contain any statement.'))
raise UserError(_('This file doesn\'t contain any statement.'))
no_st_line = True
for vals in stmts_vals:
@@ -106,7 +107,7 @@ class account_bank_statement_import(osv.TransientModel):
no_st_line = False
break
if no_st_line:
raise osv.except_osv(_('Error'), _('This file doesn\'t contain any transaction.'))
raise UserError(_('This file doesn\'t contain any transaction.'))
def _find_additional_data(self, cr, uid, currency_code, account_number, context=None):
""" Get the res.currency ID and the res.partner.bank ID """
@@ -139,7 +140,7 @@ class account_bank_statement_import(osv.TransientModel):
bank_account = bank_pool.browse(cr, uid, bank_account_id, context=context)
if journal_id:
if bank_account.journal_id.id and bank_account.journal_id.id != journal_id:
raise osv.except_osv(_('Error'), _('The account of this statement is linked to another journal.'))
raise UserError(_('The account of this statement is linked to another journal.'))
if not bank_account.journal_id.id:
bank_pool.write(cr, uid, [bank_account_id], {'journal_id': journal_id}, context=context)
else:
@@ -150,7 +151,7 @@ class account_bank_statement_import(osv.TransientModel):
if journal_id:
journal_currency_id = self.pool.get('account.journal').browse(cr, uid, journal_id, context=context).currency.id
if currency_id and currency_id != journal_currency_id:
raise osv.except_osv(_('Error'), _('The currency of the bank statement is not the same as the currency of the journal !'))
raise UserError(_('The currency of the bank statement is not the same as the currency of the journal !'))
# If there is no journal, create one (and its account)
if not journal_id and account_number:
@@ -160,7 +161,7 @@ class account_bank_statement_import(osv.TransientModel):
# If we couldn't find/create a journal, everything is lost
if not journal_id:
raise osv.except_osv(_('Error'), _('Cannot find in which journal import this statement. Please manually select a journal.'))
raise UserError(_('Cannot find in which journal import this statement. Please manually select a journal.'))
return journal_id
@@ -252,7 +253,7 @@ class account_bank_statement_import(osv.TransientModel):
st_vals['line_ids'] = [[0, False, line] for line in filtered_st_lines]
statement_ids.append(bs_obj.create(cr, uid, st_vals, context=context))
if len(statement_ids) == 0:
raise osv.except_osv(_('Error'), _('You have already imported that file.'))
raise UserError(_('You have already imported that file.'))
# Prepare import feedback
notifications = []
@@ -269,3 +270,4 @@ class account_bank_statement_import(osv.TransientModel):
}]
return statement_ids, notifications
@@ -5,6 +5,7 @@ import os
from openerp.osv import osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
_logger = logging.getLogger(__name__)
@@ -35,7 +36,7 @@ class account_bank_statement_import(osv.TransientModel):
pathname = os.path.dirname('temp.ofx')
path = os.path.join(os.path.abspath(pathname), 'temp.ofx')
except:
raise osv.except_osv(_('Import Error!'), _('File handling error.'))
raise UserError(_('File handling error.'))
ofx = self._check_ofx(cr, uid, file(path), context=context)
if not ofx:
@@ -65,7 +66,7 @@ class account_bank_statement_import(osv.TransientModel):
transactions.append(vals_line)
except Exception, e:
os.remove(path)
raise osv.except_osv(_('Error!'), _("The following problem occurred during import. The file might not be valid.\n\n %s" % e.message))
raise UserError(_("The following problem occurred during import. The file might not be valid.\n\n %s" % e.message))
vals_bank_statement = {
'name': ofx.account.routing_number,
@@ -5,6 +5,7 @@ from tempfile import TemporaryFile
from openerp.tools.translate import _
from openerp.osv import osv, fields
from openerp.exceptions import UserError
class account_bank_statement_import(osv.TransientModel):
_inherit = "account.bank.statement.import"
@@ -54,7 +55,7 @@ class account_bank_statement_import(osv.TransientModel):
header = data_list[0].strip()
header = header.split(":")[1]
except:
raise osv.except_osv(_('Import Error!'), _('Could not decipher the QIF file.'))
raise UserError(_('Could not decipher the QIF file.'))
transactions = []
vals_line = {}
total = 0
@@ -89,10 +90,11 @@ class account_bank_statement_import(osv.TransientModel):
else:
pass
else:
raise osv.except_osv(_('Error!'), _('This file is either not a bank statement or is not correctly formed.'))
raise UserError(_('This file is either not a bank statement or is not correctly formed.'))
vals_bank_statement.update({
'balance_end_real': total,
'transactions': transactions
})
return None, None, [vals_bank_statement]
+2 -1
View File
@@ -24,6 +24,7 @@ from datetime import date, datetime
from openerp.osv import fields, osv
from openerp.tools import ustr, DEFAULT_SERVER_DATE_FORMAT
from openerp.tools.translate import _
from openerp.exceptions import UserError
import openerp.addons.decimal_precision as dp
@@ -121,7 +122,7 @@ class crossovered_budget_lines(osv.osv):
for line in self.browse(cr, uid, ids, context=context):
acc_ids = [x.id for x in line.general_budget_id.account_ids]
if not acc_ids:
raise osv.except_osv(_('Error!'),_("The Budget '%s' has no accounts!") % ustr(line.general_budget_id.name))
raise UserError(_("The Budget '%s' has no accounts!") % ustr(line.general_budget_id.name))
date_to = line.date_to
date_from = line.date_from
if line.analytic_account_id.id:
@@ -23,6 +23,7 @@ from openerp.osv import osv,fields
from openerp.tools.translate import _
from openerp.tools.amount_to_text_en import amount_to_text
from lxml import etree
from openerp.exceptions import UserError
class account_voucher(osv.osv):
_inherit = 'account.voucher'
@@ -74,7 +75,7 @@ class account_voucher(osv.osv):
def print_check(self, cr, uid, ids, context=None):
if not ids:
raise osv.except_osv(_('Printing error'), _('No check selected '))
raise UserError(_('No check selected '))
data = {
'id': ids and ids[0],
@@ -21,6 +21,7 @@
from openerp.tools.translate import _
from openerp.osv import fields, osv
from openerp.exceptions import UserError
class account_check_write(osv.osv_memory):
@@ -56,7 +57,7 @@ class account_check_write(osv.osv_memory):
for check in voucher_obj.browse(cr, uid, voucher_ids, context=context):
new_value += increment
if check.number:
raise osv.except_osv(_('Error!'),_("One of the printed check already got a number."))
raise UserError(_("One of the printed check already got a number."))
voucher_obj.proforma_voucher(cr, uid, voucher_ids, context=context)
#update the sequence again (because the assignation using next_val was made during the same transaction of
+3 -2
View File
@@ -23,6 +23,7 @@ from openerp import api
from openerp.osv import fields, osv
from lxml import etree
from openerp.tools.translate import _
from openerp.exceptions import UserError
class followup(osv.osv):
_name = 'account_followup.followup'
@@ -310,13 +311,13 @@ class res_partner(osv.osv):
('state', '!=', 'draft'),
('company_id', '=', company_id),
], context=context):
raise osv.except_osv(_('Error!'),_("The partner does not have any accounting entries to print in the overdue report for the current company."))
raise UserError(_("The partner does not have any accounting entries to print in the overdue report for the current company."))
self.message_post(cr, uid, [ids[0]], body=_('Printed overdue payments report'), context=context)
#build the id of this partner in the psql view. Could be replaced by a search with [('company_id', '=', company_id),('partner_id', '=', ids[0])]
wizard_partner_ids = [ids[0] * 10000 + company_id]
followup_ids = self.pool.get('account_followup.followup').search(cr, uid, [('company_id', '=', company_id)], context=context)
if not followup_ids:
raise osv.except_osv(_('Error!'),_("There is no followup plan defined for the current company."))
raise UserError(_("There is no followup plan defined for the current company."))
data = {
'date': fields.date.today(),
'followup_id': followup_ids[0],
@@ -23,6 +23,7 @@ import time
from collections import defaultdict
from openerp.osv import osv
from openerp.report import report_sxw
from openerp.exceptions import UserError
class report_rappel(report_sxw.rml_parse):
@@ -79,7 +80,7 @@ class report_rappel(report_sxw.rml_parse):
fp_obj = self.pool['account_followup.followup']
fp_line = fp_obj.browse(self.cr, self.uid, followup_id, context=context).followup_line
if not fp_line:
raise osv.except_osv(_('Error!'),_("The followup plan defined for the current company does not have any followup action."))
raise UserError(_("The followup plan defined for the current company does not have any followup action."))
#the default text will be the first fp_line in the sequence with a description.
default_text = ''
li_delay = []
+2 -1
View File
@@ -21,6 +21,7 @@
from openerp.tools.translate import _
from openerp.osv import osv
from openerp.exceptions import UserError
class Invoice(osv.osv):
_inherit = 'account.invoice'
@@ -39,5 +40,5 @@ class Invoice(osv.osv):
if pl_line_ids:
pay_line = payment_line_obj.browse(cr, uid, pl_line_ids, context=context)
payment_order_name = ','.join(map(lambda x: x.order_id.reference, pay_line))
raise osv.except_osv(_('Error!'), _("You cannot cancel an invoice which has already been imported in a payment order. Remove it from the following payment order : %s."%(payment_order_name)))
raise UserError(_("You cannot cancel an invoice which has already been imported in a payment order. Remove it from the following payment order : %s."%(payment_order_name)))
return super(Invoice, self).action_cancel(cr, uid, ids, context=context)
+2 -1
View File
@@ -21,6 +21,7 @@
from openerp.osv import osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class account_move_line(osv.osv):
_inherit = "account.move.line"
@@ -54,5 +55,5 @@ class account_move_line(osv.osv):
if not line2bank.get(line.id) and line.partner_id.bank_ids:
line2bank[line.id] = line.partner_id.bank_ids[0].id
else:
raise osv.except_osv(_('Error!'), _('There is no partner defined on the entry line.'))
raise UserError(_('There is no partner defined on the entry line.'))
return line2bank
+7 -8
View File
@@ -28,6 +28,7 @@ from openerp.tools.translate import _
from openerp.tools import float_compare
from openerp.report import report_sxw
import openerp
from openerp.exceptions import UserError
class res_currency(osv.osv):
_inherit = "res.currency"
@@ -515,7 +516,7 @@ class account_voucher(osv.osv):
tr_type = 'purchase'
else:
if not journal.default_credit_account_id or not journal.default_debit_account_id:
raise osv.except_osv(_('Error!'), _('Please define default credit/debit accounts on the journal "%s".') % (journal.name))
raise UserError(_('Please define default credit/debit accounts on the journal "%s".') % (journal.name))
account_id = journal.default_credit_account_id.id or journal.default_debit_account_id.id
tr_type = 'receipt'
@@ -956,7 +957,7 @@ class account_voucher(osv.osv):
def unlink(self, cr, uid, ids, context=None):
for t in self.read(cr, uid, ids, ['state'], context=context):
if t['state'] not in ('draft', 'cancel'):
raise osv.except_osv(_('Invalid Action!'), _('Cannot delete voucher(s) which are already opened or paid.'))
raise UserError(_('Cannot delete voucher(s) which are already opened or paid.'))
return super(account_voucher, self).unlink(cr, uid, ids, context=context)
def onchange_payment(self, cr, uid, ids, pay_now, journal_id, partner_id, ttype='sale'):
@@ -1054,14 +1055,12 @@ class account_voucher(osv.osv):
name = voucher.number
elif voucher.journal_id.sequence_id:
if not voucher.journal_id.sequence_id.active:
raise osv.except_osv(_('Configuration Error !'),
_('Please activate the sequence of selected journal !'))
raise UserError(_('Please activate the sequence of selected journal !'))
c = dict(context)
c.update({'fiscalyear_id': voucher.period_id.fiscalyear_id.id})
name = seq_obj.next_by_id(cr, uid, voucher.journal_id.sequence_id.id, context=c)
else:
raise osv.except_osv(_('Error!'),
_('Please define a sequence on the journal.'))
raise UserError(_('Please define a sequence on the journal.'))
ref = voucher.reference or name
move = {
@@ -1196,7 +1195,7 @@ class account_voucher(osv.osv):
# currency rate difference
if line.amount == line.amount_unreconciled:
if not line.move_line_id:
raise osv.except_osv(_('Wrong voucher line'),_("The invoice you are willing to pay is not valid anymore."))
raise UserError(_("The invoice you are willing to pay is not valid anymore."))
sign = line.type =='dr' and -1 or 1
currency_rate_difference = sign * (line.move_line_id.amount_residual - amount)
else:
@@ -1237,7 +1236,7 @@ class account_voucher(osv.osv):
if move_line.get('account_tax_id', False):
tax_data = tax_obj.browse(cr, uid, [move_line['account_tax_id']], context=context)[0]
if not (tax_data.base_code_id and tax_data.tax_code_id):
raise osv.except_osv(_('No Account Base Code and Account Tax Code!'),_("You have to configure account base code and account tax code on the '%s' tax!") % (tax_data.name))
raise UserError(_("You have to configure account base code and account tax code on the '%s' tax!") % (tax_data.name))
# compute the amount in foreign currency
foreign_currency_diff = 0.0
+3 -2
View File
@@ -26,6 +26,7 @@ from openerp.osv import fields, osv
from openerp import tools
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
from openerp.exceptions import UserError
class account_analytic_account(osv.osv):
_name = 'account.analytic.account'
@@ -157,7 +158,7 @@ class account_analytic_account(osv.osv):
for account in self.browse(cr, uid, ids, context=context):
if account.company_id:
if account.company_id.currency_id.id != value:
raise osv.except_osv(_('Error!'), _("If you set a company, the currency selected has to be the same as it's currency. \nYou can remove the company belonging, and thus change the currency, only on analytic account of type 'view'. This can be really useful for consolidation purposes of several companies charts with different currencies, for example."))
raise UserError(_("If you set a company, the currency selected has to be the same as it's currency. \nYou can remove the company belonging, and thus change the currency, only on analytic account of type 'view'. This can be really useful for consolidation purposes of several companies charts with different currencies, for example."))
if value:
cr.execute("""update account_analytic_account set currency_id=%s where id=%s""", (value, account.id))
self.invalidate_cache(cr, uid, ['currency_id'], [account.id], context=context)
@@ -269,7 +270,7 @@ class account_analytic_account(osv.osv):
]
def name_create(self, cr, uid, name, context=None):
raise osv.except_osv(_('Warning'), _("Quick account creation disallowed."))
raise UserError(_("Quick account creation disallowed."))
def copy(self, cr, uid, id, default=None, context=None):
if not default:
+1 -1
View File
@@ -1 +1 @@
id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
1 id name model_id:id group_id:id perm_read perm_write perm_create perm_unlink
@@ -22,6 +22,7 @@
from openerp.osv import fields,osv
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
from openerp.exceptions import UserError
class analytic_user_funct_grid(osv.osv):
_name="analytic.user.funct.grid"
@@ -105,10 +106,7 @@ class hr_analytic_timesheet(osv.osv):
if not a:
a = r.product_id.categ_id.property_account_expense_categ.id
if not a:
raise osv.except_osv(_('Error!'),
_('There is no expense account defined ' \
'for this product: "%s" (id:%d)') % \
(r.product_id.name, r.product_id.id,))
raise UserError(_('There is no expense account defined for this product: "%s" (id:%d)') % (r.product_id.name, r.product_id.id,))
# Compute based on pricetype
if unit_amount:
amount_unit = self.on_change_unit_amount(cr, uid, ids,
@@ -134,7 +132,7 @@ class hr_analytic_timesheet(osv.osv):
if not a:
a = r.product_id.categ_id.property_account_expense_categ.id
if not a:
raise osv.except_osv(_('Error!'),
raise UserError(
_('There is no expense account defined ' \
'for this product: "%s" (id:%d)') % \
(r.product_id.name, r.product_id.id,))
+7 -6
View File
@@ -34,6 +34,7 @@ from openerp.tools.translate import _
from itertools import groupby
from operator import itemgetter
from openerp.exceptions import UserError
FIELD_STATES = [('clear', 'Clear'), ('anonymized', 'Anonymized'), ('not_existing', 'Not Existing'), ('new', 'New')]
@@ -86,11 +87,11 @@ class ir_model_fields_anonymization(osv.osv):
if context.get('manual'):
global_state = self._get_global_state(cr, uid, context=context)
if global_state == 'anonymized':
raise osv.except_osv('Error!', "The database is currently anonymized, you cannot create, modify or delete fields.")
raise UserError(_("The database is currently anonymized, you cannot create, modify or delete fields."))
elif global_state == 'unstable':
msg = _("The database anonymization is currently in an unstable state. Some fields are anonymized," + \
" while some fields are not anonymized. You should try to solve this problem before trying to create, write or delete fields.")
raise osv.except_osv('Error!', msg)
raise UserError(msg)
return True
@@ -357,7 +358,7 @@ class ir_model_fields_anonymize_wizard(osv.osv_memory):
else:
msg = _("The database anonymization is currently in an unstable state. Some fields are anonymized," + \
" while some fields are not anonymized. You should try to solve this problem before trying to do anything else.")
raise osv.except_osv('Error!', msg)
raise UserError(msg)
res['arch'] = etree.tostring(eview)
@@ -368,7 +369,7 @@ class ir_model_fields_anonymize_wizard(osv.osv_memory):
'state': 'in_exception',
'msg': error_msg,
})
raise osv.except_osv(error_type, error_msg)
raise UserError('%s: %s' % (error_type, error_msg))
def anonymize_database(self, cr, uid, ids, context=None):
"""Sets the 'anonymized' state to defined fields"""
@@ -521,11 +522,11 @@ class ir_model_fields_anonymize_wizard(osv.osv_memory):
# check that all the defined fields are in the 'anonymized' state
state = ir_model_fields_anonymization_model._get_global_state(cr, uid, context=context)
if state == 'clear':
raise osv.except_osv_('Error!', "The database is not currently anonymized, you cannot reverse the anonymization.")
raise UserError(_("The database is not currently anonymized, you cannot reverse the anonymization."))
elif state == 'unstable':
msg = _("The database anonymization is currently in an unstable state. Some fields are anonymized," + \
" while some fields are not anonymized. You should try to solve this problem before trying to do anything.")
raise osv.except_osv('Error!', msg)
raise UserError(msg)
wizards = self.browse(cr, uid, ids, context=context)
for wizard in wizards:
+2 -1
View File
@@ -28,6 +28,7 @@ from openerp.osv import osv, fields
from openerp.tools.misc import DEFAULT_SERVER_DATETIME_FORMAT, ustr
from ast import literal_eval
from openerp.tools.translate import _
from openerp.exceptions import UserError
class SignupError(Exception):
pass
@@ -291,7 +292,7 @@ class res_users(osv.Model):
for user in self.browse(cr, uid, ids, context):
if not user.email:
raise osv.except_osv(_("Cannot send email: user has no email address."), user.name)
raise UserError(_("Cannot send email: user %s has no email address.") % user.name)
self.pool.get('mail.template').send_mail(cr, uid, template.id, user.id, force_send=True, raise_exception=True, context=context)
def create(self, cr, uid, values, context=None):
+2 -1
View File
@@ -21,6 +21,7 @@
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
LANG_CODE_MAPPING = {
'ar_SY': ('ar', 'Arabic'),
@@ -73,7 +74,7 @@ class ir_translation(osv.Model):
def _get_all_supported_languages(self, cr, uid, context=None):
flag, gengo = self.pool.get('base.gengo.translations').gengo_authentication(cr, uid, context=context)
if not flag:
raise osv.except_osv(_('Gengo Authentication Error'), gengo)
raise UserError(gengo)
supported_langs = {}
lang_pair = gengo.getServiceLanguagePairs(lc_src='en')
if lang_pair['opstat'] == 'ok':
@@ -27,6 +27,7 @@ import time
from openerp.osv import osv, fields
from openerp import tools, SUPERUSER_ID
from openerp.tools.translate import _
from openerp.exceptions import UserError
_logger = logging.getLogger(__name__)
@@ -99,17 +100,17 @@ class base_gengo_translations(osv.osv_memory):
flag, gengo = self.gengo_authentication(cr, uid, context=context)
if not flag:
raise osv.except_osv(_('Gengo Authentication Error'), gengo)
raise UserError(gengo)
for wizard in self.browse(cr, uid, ids, context=context):
supported_langs = self.pool.get('ir.translation')._get_all_supported_languages(cr, uid, context=context)
language = self.pool.get('ir.translation')._get_gengo_corresponding_language(wizard.lang_id.code)
if language not in supported_langs:
raise osv.except_osv(_("Warning"), _('This language is not supported by the Gengo translation services.'))
raise UserError(_('This language is not supported by the Gengo translation services.'))
ctx = context.copy()
ctx['gengo_language'] = wizard.lang_id.id
if wizard.sync_limit > 200 or wizard.sync_limit < 1:
raise osv.except_osv(_("Warning"), _('Sync limit should between 1 to 200 for Gengo translation services.'))
raise UserError(_('Sync limit should between 1 to 200 for Gengo translation services.'))
if wizard.sync_type in ['send', 'both']:
self._sync_request(cr, uid, wizard.sync_limit, context=ctx)
if wizard.sync_type in ['receive', 'both']:
@@ -28,6 +28,7 @@ import urllib
from openerp.osv import osv, fields
from openerp import tools
from openerp.tools.translate import _
from openerp.exceptions import UserError
def geo_find(addr):
@@ -37,8 +38,7 @@ def geo_find(addr):
try:
result = json.load(urllib.urlopen(url))
except Exception, e:
raise osv.except_osv(_('Network error'),
_('Cannot contact geolocation servers. Please make sure that your internet connection is up and running (%s).') % e)
raise UserError(_('Cannot contact geolocation servers. Please make sure that your internet connection is up and running (%s).') % e)
if result['status'] != 'OK':
return None
@@ -8,6 +8,7 @@ import openerp
from openerp.osv import osv
from openerp.tools import convert_file
from openerp.tools.translate import _
from openerp.exceptions import UserError
_logger = logging.getLogger(__name__)
@@ -27,7 +28,7 @@ class view(osv.osv):
unmet_dependencies = set(terp['depends']).difference(installed_mods)
if unmet_dependencies:
msg = _("Unmet module dependencies: %s")
raise osv.except_osv(_('Error !'), msg % ', '.join(unmet_dependencies))
raise UserError(msg % ', '.join(unmet_dependencies))
mod = known_mods_names.get(module)
if mod:
@@ -79,7 +80,7 @@ class view(osv.osv):
if not module_file:
raise Exception("No file sent.")
if not zipfile.is_zipfile(module_file):
raise osv.except_osv(_('Error !'), _('File is not a zip file!'))
raise UserError(_('File is not a zip file!'))
success = []
errors = dict()
@@ -88,7 +89,7 @@ class view(osv.osv):
for zf in z.filelist:
if zf.file_size > MAX_FILE_SIZE:
msg = _("File '%s' exceed maximum allowed file size")
raise osv.except_osv(_('Error !'), msg % zf.filename)
raise UserError(msg % zf.filename)
with openerp.tools.osutil.tempdir() as module_dir:
z.extractall(module_dir)
+2 -1
View File
@@ -35,6 +35,7 @@ except ImportError:
from openerp.osv import fields, osv
from openerp.tools.misc import ustr
from openerp.tools.translate import _
from openerp.exceptions import UserError
_ref_vat = {
'at': 'ATU12345675',
@@ -111,7 +112,7 @@ class res_partner(osv.osv):
def button_check_vat(self, cr, uid, ids, context=None):
if not self.check_vat(cr, uid, ids, context=context):
msg = self._construct_constraint_msg(cr, uid, ids, context=context)
raise osv.except_osv(_('Error!'), msg)
raise UserError(msg)
return True
def check_vat(self, cr, uid, ids, context=None):
+9 -8
View File
@@ -19,6 +19,7 @@ from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FO
from openerp.tools.translate import _
from openerp.http import request
from operator import itemgetter
from openerp.exceptions import UserError
import logging
_logger = logging.getLogger(__name__)
@@ -101,7 +102,7 @@ class calendar_attendee(osv.Model):
}
def copy(self, cr, uid, id, default=None, context=None):
raise osv.except_osv(_('Warning!'), _('You cannot duplicate a calendar attendee.'))
raise UserError(_('You cannot duplicate a calendar attendee.'))
def onchange_partner_id(self, cr, uid, ids, partner_id, context=None):
"""
@@ -138,7 +139,7 @@ class calendar_attendee(osv.Model):
cal = vobject.iCalendar()
event = cal.add('vevent')
if not event_obj.start or not event_obj.stop:
raise osv.except_osv(_('Warning!'), _("First you have to specify the date of the invitation."))
raise UserError(_("First you have to specify the date of the invitation."))
event.add('created').value = ics_datetime(time.strftime(DEFAULT_SERVER_DATETIME_FORMAT))
event.add('dtstart').value = ics_datetime(event_obj.start, event_obj.allday)
event.add('dtend').value = ics_datetime(event_obj.stop, event_obj.allday)
@@ -857,8 +858,8 @@ class calendar_event(osv.Model):
allday = self.read(cr, uid, [id], ['allday'], context=context)[0].get('allday')
else:
allday = False
_logger.warning("Calendar - All day is not specified, arbitrarily set to False")
#raise osv.except_osv(_('Error!'), ("Need to know if it's an allday or not..."))
_logger.debug("Calendar - All day is not specified, arbitrarily set to False")
#raise UserError(_("Need to know if it's an allday or not..."))
key = "date" if allday else "datetime"
notkey = "datetime" if allday else "date"
@@ -1233,9 +1234,9 @@ class calendar_event(osv.Model):
@return: string containing recurring rule (empty if no rule)
"""
if data['interval'] and data['interval'] < 0:
raise osv.except_osv(_('warning!'), _('interval cannot be negative.'))
raise UserError(_('interval cannot be negative.'))
if data['count'] and data['count'] <= 0:
raise osv.except_osv(_('warning!'), _('count cannot be negative or 0.'))
raise UserError(_('Event recurrence interval cannot be negative.'))
def get_week_string(freq, data):
weekdays = ['mo', 'tu', 'we', 'th', 'fr', 'sa', 'su']
@@ -1248,7 +1249,7 @@ class calendar_event(osv.Model):
def get_month_string(freq, data):
if freq == 'monthly':
if data.get('month_by') == 'date' and (data.get('day') < 1 or data.get('day') > 31):
raise osv.except_osv(_('Error!'), ("Please select a proper day of the month."))
raise UserError(_("Please select a proper day of the month."))
if data.get('month_by') == 'day': # Eg : Second Monday of the month
return ';BYDAY=' + data.get('byday') + data.get('week_list')
@@ -1604,7 +1605,7 @@ class calendar_event(osv.Model):
context = dict(context or {})
if 'date' in groupby:
raise osv.except_osv(_('Warning!'), _('Group by date is not supported, use the calendar view instead.'))
raise UserError(_('Group by date is not supported, use the calendar view instead.'))
virtual_id = context.get('virtual_id', True)
context.update({'virtual_id': False})
res = super(calendar_event, self).read_group(cr, uid, domain, fields, groupby, offset=offset, limit=limit, context=context, orderby=orderby, lazy=lazy)
+6 -6
View File
@@ -19,6 +19,7 @@ from openerp.osv import osv, orm
from openerp.osv import fields
from openerp.osv.orm import browse_record
from openerp.tools.translate import _
from openerp.exceptions import UserError
pattern = re.compile("&(\w+?);")
@@ -286,7 +287,7 @@ class MergePartnerAutomatic(osv.TransientModel):
if parent_id and parent_id != dst_partner.id:
try:
dst_partner.write({'parent_id': parent_id})
except (osv.except_osv, orm.except_orm):
except ValidationError:
_logger.info('Skip recursive partner hierarchies for parent_id %s of partner: %s', parent_id, dst_partner.id)
@mute_logger('openerp.osv.expression', 'openerp.models')
@@ -298,10 +299,10 @@ class MergePartnerAutomatic(osv.TransientModel):
return
if len(partner_ids) > 3:
raise osv.except_osv(_('Error'), _("For safety reasons, you cannot merge more than 3 contacts together. You can re-open the wizard several times if needed."))
raise UserError(_("For safety reasons, you cannot merge more than 3 contacts together. You can re-open the wizard several times if needed."))
if openerp.SUPERUSER_ID != uid and len(set(partner.email for partner in proxy.browse(cr, uid, partner_ids, context=context))) > 1:
raise osv.except_osv(_('Error'), _("All contacts must have the same email. Only the Administrator can merge contacts with different emails."))
raise UserError(_("All contacts must have the same email. Only the Administrator can merge contacts with different emails."))
if dst_partner and dst_partner.id in partner_ids:
src_partners = proxy.browse(cr, uid, [id for id in partner_ids if id != dst_partner.id], context=context)
@@ -313,7 +314,7 @@ class MergePartnerAutomatic(osv.TransientModel):
if openerp.SUPERUSER_ID != uid and self._model_is_installed(cr, uid, 'account.move.line', context=context) and \
self.pool.get('account.move.line').search(cr, openerp.SUPERUSER_ID, [('partner_id', 'in', [partner.id for partner in src_partners])], context=context):
raise osv.except_osv(_('Error'), _("Only the destination contact may be linked to existing Journal Items. Please ask the Administrator if you need to merge several contacts linked to existing Journal Items."))
raise UserError(_("Only the destination contact may be linked to existing Journal Items. Please ask the Administrator if you need to merge several contacts linked to existing Journal Items."))
call_it = lambda function: function(cr, uid, src_partners, dst_partner,
context=context)
@@ -442,8 +443,7 @@ class MergePartnerAutomatic(osv.TransientModel):
]
if not groups:
raise osv.except_osv(_('Error'),
_("You have to specify a filter for your selection"))
raise UserError(_("You have to specify a filter for your selection"))
return groups
+11 -15
View File
@@ -30,6 +30,7 @@ from openerp.addons.base.res.res_partner import format_address
from openerp.osv import fields, osv, orm
from openerp.tools.translate import _
from openerp.tools import email_re, email_split
from openerp.exceptions import UserError, AccessError
CRM_LEAD_FIELDS_TO_MERGE = ['name',
@@ -390,10 +391,9 @@ class crm_lead(format_address, osv.osv):
else:
stages_leads[stage_id] = [lead.id]
else:
raise osv.except_osv(_('Warning!'),
_('To relieve your sales pipe and group all Lost opportunities, configure one of your sales stage as follow:\n'
'probability = 0 %, select "Change Probability Automatically".\n'
'Create a specific stage or edit an existing one by editing columns of your opportunity pipe.'))
raise UserError(_('To relieve your sales pipe and group all Lost opportunities, configure one of your sales stage as follow:\n'
'probability = 0 %, select "Change Probability Automatically".\n'
'Create a specific stage or edit an existing one by editing columns of your opportunity pipe.'))
for stage_id, lead_ids in stages_leads.items():
self.write(cr, uid, lead_ids, {'stage_id': stage_id}, context=context)
return True
@@ -410,10 +410,9 @@ class crm_lead(format_address, osv.osv):
else:
stages_leads[stage_id] = [lead.id]
else:
raise osv.except_osv(_('Warning!'),
_('To relieve your sales pipe and group all Won opportunities, configure one of your sales stage as follow:\n'
'probability = 100 % and select "Change Probability Automatically".\n'
'Create a specific stage or edit an existing one by editing columns of your opportunity pipe.'))
raise UserError(_('To relieve your sales pipe and group all Won opportunities, configure one of your sales stage as follow:\n'
'probability = 100 % and select "Change Probability Automatically".\n'
'Create a specific stage or edit an existing one by editing columns of your opportunity pipe.'))
for stage_id, lead_ids in stages_leads.items():
self.write(cr, uid, lead_ids, {'stage_id': stage_id}, context=context)
return True
@@ -428,7 +427,7 @@ class crm_lead(format_address, osv.osv):
if case.team_id.parent_id.user_id:
data['user_id'] = case.team_id.parent_id.user_id.id
else:
raise osv.except_osv(_('Error!'), _("You are already at the top level of your sales-team category.\nTherefore you cannot escalate furthermore."))
raise UserError(_("You are already at the top level of your sales-team category.\nTherefore you cannot escalate furthermore."))
self.write(cr, uid, [case.id], data, context=context)
return True
@@ -637,7 +636,7 @@ class crm_lead(format_address, osv.osv):
context = {}
if len(ids) <= 1:
raise osv.except_osv(_('Warning!'), _('Please select more than one element (lead or opportunity) from the list view.'))
raise UserError(_('Please select more than one element (lead or opportunity) from the list view.'))
opportunities = self.browse(cr, uid, ids, context=context)
sequenced_opps = []
@@ -763,10 +762,7 @@ class crm_lead(format_address, osv.osv):
contact_name = self.pool.get('res.partner')._parse_partner_name(lead.email_from, context=context)[0]
partner_id = self._lead_create_contact(cr, uid, lead, contact_name, False, context=context)
else:
raise osv.except_osv(
_('Warning!'),
_('No customer name defined. Please fill one of the following fields: Company Name, Contact Name or Email ("Name <email@address>")')
)
raise UserError(_('No customer name defined. Please fill one of the following fields: Company Name, Contact Name or Email ("Name <email@address>")'))
return partner_id
def handle_partner_assignation(self, cr, uid, ids, action='create', partner_id=False, context=None):
@@ -996,7 +992,7 @@ class crm_lead(format_address, osv.osv):
self._message_add_suggested_recipient(cr, uid, recipients, lead, partner=lead.partner_id, reason=_('Customer'))
elif lead.email_from:
self._message_add_suggested_recipient(cr, uid, recipients, lead, email=lead.email_from, reason=_('Customer Email'))
except (osv.except_osv, orm.except_orm): # no read access rights -> just ignore suggested recipients because this imply modifying followers
except AccessError: # no read access rights -> just ignore suggested recipients because this imply modifying followers
pass
return recipients
+2 -1
View File
@@ -24,6 +24,7 @@ from datetime import datetime
from openerp.osv import fields, osv
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
from openerp.tools.translate import _
from openerp.exceptions import UserError
class crm_phonecall(osv.osv):
""" Model for CRM phonecalls """
@@ -286,7 +287,7 @@ class crm_phonecall(osv.osv):
:return dict: containing view information
"""
if len(ids) != 1:
raise osv.except_osv(_('Warning!'),_('It\'s only possible to convert one phonecall at a time.'))
raise UserError(_('It\'s only possible to convert one phonecall at a time.'))
opportunity_dict = self.convert_opportunity(cr, uid, ids, context=context)
return self.pool.get('crm.lead').redirect_opportunity_view(cr, uid, opportunity_dict[ids[0]], context)
+2 -1
View File
@@ -22,6 +22,7 @@
from openerp.osv import fields, osv
from openerp.tools.translate import _
import re
from openerp.exceptions import UserError
class crm_lead2opportunity_partner(osv.osv_memory):
_name = 'crm.lead2opportunity.partner'
@@ -102,7 +103,7 @@ class crm_lead2opportunity_partner(osv.osv_memory):
lead_obj = self.pool.get('crm.lead')
for lead in lead_obj.browse(cr, uid, context.get('active_ids', []), context=context):
if lead.probability == 100:
raise osv.except_osv(_("Warning!"), _("Closed/Dead leads cannot be converted into opportunities."))
raise UserError(_("Closed/Dead leads cannot be converted into opportunities."))
return False
def _convert_opportunity(self, cr, uid, ids, vals, context=None):
+2 -1
View File
@@ -25,6 +25,7 @@ from openerp.osv import fields, osv
from openerp import tools
from openerp.tools.translate import _
from openerp.tools import html2plaintext
from openerp.exceptions import UserError
class crm_helpdesk(osv.osv):
@@ -112,7 +113,7 @@ class crm_helpdesk(osv.osv):
if parent_id.change_responsible and parent_id.user_id:
data['user_id'] = parent_id.user_id.id
else:
raise osv.except_osv(_('Error!'), _('You can not escalate, you are already at the top level regarding your sales-team category.'))
raise UserError(_('You can not escalate, you are already at the top level regarding your sales-team category.'))
self.write(cr, uid, [case.id], data, context=context)
return True
+2 -1
View File
@@ -21,6 +21,7 @@
from openerp.osv import osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class crm_lead(osv.osv):
@@ -30,7 +31,7 @@ class crm_lead(osv.osv):
try:
model, action_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'crm_partner_assign', 'crm_lead_channel_interested_act')
except ValueError:
raise osv.except_osv(_('Error!'), _("The CRM Channel Interested Action is missing"))
raise UserError(_("The CRM Channel Interested Action is missing"))
action = self.pool[model].read(cr, uid, [action_id], context=context)[0]
action_context = eval(action['context'])
action_context['interested'] = interested
@@ -23,6 +23,7 @@
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp import SUPERUSER_ID
from openerp.exceptions import UserError
class crm_lead_forward_to_partner(osv.TransientModel):
@@ -41,7 +42,7 @@ class crm_lead_forward_to_partner(osv.TransientModel):
def action_confirm(self, cr, uid, ids, context=None):
wizard = self.browse(cr, uid, ids[0], context=context)
if wizard.interested and not wizard.contacted:
raise osv.except_osv(_('Error!'), _("You must contact the lead before saying that you are interested"))
raise UserError(_("You must contact the lead before saying that you are interested"))
lead_obj = self.pool.get('crm.lead')
lead_obj.check_access_rights(cr, uid, 'write')
if wizard.interested:
@@ -22,6 +22,7 @@
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class crm_lead_forward_to_partner(osv.TransientModel):
@@ -84,13 +85,11 @@ class crm_lead_forward_to_partner(osv.TransientModel):
try:
template_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'crm_partner_assign', 'email_template_lead_forward_mail')[1]
except ValueError:
raise osv.except_osv(_('Email Template Error'),
_('The Forward Email Template is not in the database'))
raise UserError(_('The Forward Email Template is not in the database'))
try:
portal_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'base', 'group_portal')[1]
except ValueError:
raise osv.except_osv(_('Portal Group Error'),
_('The Portal group cannot be found'))
raise UserError(_('The Portal group cannot be found'))
local_context = context.copy()
if not (record.forward_type == 'single'):
@@ -99,11 +98,9 @@ class crm_lead_forward_to_partner(osv.TransientModel):
if lead.partner_assigned_id and not lead.partner_assigned_id.email:
no_email.add(lead.partner_assigned_id.name)
if no_email:
raise osv.except_osv(_('Email Error'),
('Set an email address for the partner(s): %s' % ", ".join(no_email)))
raise UserError(_('Set an email address for the partner(s): %s') % ", ".join(no_email))
if record.forward_type == 'single' and not record.partner_id.email:
raise osv.except_osv(_('Email Error'),
('Set an email address for the partner %s' % record.partner_id.name))
raise UserError(_('Set an email address for the partner %s') % record.partner_id.name)
partners_leads = {}
for lead in record.assignation_lines:
+4 -3
View File
@@ -24,6 +24,7 @@ import time
from openerp.osv import fields,osv
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
from openerp.exceptions import UserError
_logger = logging.getLogger(__name__)
@@ -62,9 +63,9 @@ class delivery_carrier(osv.osv):
try:
price=grid_obj.get_price(cr, uid, carrier_grid, order, time.strftime('%Y-%m-%d'), context)
available = True
except osv.except_osv, e:
except UserError, e:
# no suitable delivery method found, probably configuration error
_logger.error("Carrier %s: %s\n%s" % (carrier.name, e.name, e.value))
_logger.info("Carrier %s: %s", carrier.name, e.name)
price = 0.0
else:
price = 0.0
@@ -234,7 +235,7 @@ class delivery_grid(osv.osv):
ok = True
break
if not ok:
raise osv.except_osv(_("Unable to fetch delivery method!"), _("Selected product in the delivery method doesn't fulfill any of the delivery grid(s) criteria."))
raise UserError(_("Selected product in the delivery method doesn't fulfill any of the delivery grid(s) criteria."))
return price
+3 -2
View File
@@ -22,6 +22,7 @@
import time
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class sale_order_line(osv.Model):
@@ -68,10 +69,10 @@ class sale_order(osv.Model):
for order in self.browse(cr, uid, ids, context=context):
grid_id = carrier_obj.grid_get(cr, uid, [order.carrier_id.id], order.partner_shipping_id.id)
if not grid_id:
raise osv.except_osv(_('No Grid Available!'), _('No grid matching for this carrier!'))
raise UserError(_('No grid matching for this carrier!'))
if order.state not in ('draft', 'sent'):
raise osv.except_osv(_('Order not in Draft State!'), _('The order state have to be draft to add delivery lines.'))
raise UserError(_('The order state have to be draft to add delivery lines.'))
grid = grid_obj.browse(cr, uid, grid_id, context=context)
+2 -4
View File
@@ -21,6 +21,7 @@
from openerp.osv import fields,osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
import openerp.addons.decimal_precision as dp
@@ -87,10 +88,7 @@ class stock_picking(osv.osv):
grid_id = carrier_obj.grid_get(cr, uid, [picking.carrier_id.id],
picking.partner_id.id, context=context)
if not grid_id:
raise osv.except_osv(_('Warning!'),
_('The carrier %s (id: %d) has no delivery grid!') \
% (picking.carrier_id.name,
picking.carrier_id.id))
raise UserError(_('The carrier %s (id: %d) has no delivery grid!') % (picking.carrier_id.name,picking.carrier_id.id))
quantity = sum([line.product_uom_qty for line in picking.move_lines])
price = grid_obj.get_price_from_picking(cr, uid, grid_id,
invoice.amount_untaxed, picking.weight, picking.volume,
+11 -14
View File
@@ -23,8 +23,6 @@ import os
import tempfile
from subprocess import Popen, PIPE
_logger = logging.getLogger(__name__)
class NhException(Exception):
pass
class indexer(object):
@@ -61,13 +59,13 @@ class indexer(object):
try:
if content != None:
return self._doIndexContent(content)
except NhException:
except NotImplementedError:
pass
if realfile != None:
try:
return self._doIndexFile(realfile)
except NhException:
except NotImplementedError:
pass
fp = open(realfile,'rb')
@@ -90,16 +88,16 @@ class indexer(object):
res = self._doIndexFile(rfname)
os.unlink(rfname)
return res
except NhException:
except NotImplementedError:
pass
raise NhException('No appropriate method to index file.')
raise ValueError('No appropriate method to index file.')
def _doIndexContent(self, content):
raise NhException("Content cannot be handled here.")
raise NotImplementedError("Content cannot be handled here.")
def _doIndexFile(self, fpath):
raise NhException("Content cannot be handled here.")
raise NotImplementedError("Content cannot be handled here.")
def __repr__(self):
return "<indexer %s.%s>" %(self.__module__, self.__class__.__name__)
@@ -130,10 +128,9 @@ class contentIndex(object):
self.exts[ext] = obj
f = True
if f:
_logger.debug('Register content indexer: %r.', obj)
if not f:
raise Exception("Your indexer should at least support a mimetype or extension.")
raise ValueError("Your indexer should at least support a mimetype or extension.")
_logger.debug('Register content indexer: %r.', obj)
def doIndex(self, content, filename=None, content_type=None, realfname=None, debug=False):
fobj = None
@@ -174,7 +171,7 @@ class contentIndex(object):
if not mime:
mime = mime2
except Exception:
_logger.exception('Cannot determine mime type.')
_logger.info('Cannot determine mime type.', exc_info=True)
try:
if fobj:
@@ -183,8 +180,8 @@ class contentIndex(object):
_logger.debug("Have no object, return (%s, None).", mime)
res = (mime, '')
except Exception:
_logger.exception("Cannot index file %s (%s).",
filename, fname or realfname)
_logger.info("Cannot index file %s (%s).",
filename, fname or realfname, exc_info=True)
res = (mime, '')
# If we created a tmp file, unlink it now
+15 -15
View File
@@ -34,7 +34,7 @@ import openerp
from openerp import tools
from openerp import SUPERUSER_ID
from openerp.osv import fields, osv
from openerp.osv.orm import except_orm
from openerp.exceptions import UserError, AccessError, ValidationError
import openerp.report.interface
from openerp.tools.misc import ustr
from openerp.tools.translate import _
@@ -290,7 +290,7 @@ class document_directory(osv.osv):
try:
self.check_access_rule(cr, uid, ids, pperms[0], context=context)
res |= pperms[1]
except except_orm:
except AccessError:
pass
return res
@@ -334,17 +334,17 @@ class document_directory(osv.osv):
def write(self, cr, uid, ids, vals, context=None):
if not self._check_duplication(cr, uid, vals, ids, op='write'):
raise osv.except_osv(_('ValidateError'), _('Directory name must be unique!'))
raise ValidationError(_('Directory name must be unique!'))
return super(document_directory,self).write(cr, uid, ids, vals, context=context)
def create(self, cr, uid, vals, context=None):
if not self._check_duplication(cr, uid, vals):
raise osv.except_osv(_('ValidateError'), _('Directory name must be unique!'))
raise ValidationError(_('Directory name must be unique!'))
newname = vals.get('name',False)
if newname:
for illeg in ('/', '@', '$', '#'):
if illeg in newname:
raise osv.except_osv(_('ValidateError'), _('Directory name contains special characters!'))
raise ValidationError(_('Directory name contains special characters!'))
return super(document_directory,self).create(cr, uid, vals, context)
class document_directory_dctx(osv.osv):
@@ -567,10 +567,10 @@ class document_storage(osv.osv):
file_node.content_type = mime
return True
except Exception, e :
_logger.warning("Cannot save data.", exc_info=True)
_logger.info("Cannot save data.", exc_info=True)
# should we really rollback once we have written the actual data?
# at the db case (only), that rollback would be safe
raise except_orm(_('Error at doc write!'), str(e))
raise UserError(ustr(e))
def _str2time(cre):
""" Convert a string with time representation (from db) into time (float)
@@ -862,13 +862,13 @@ class node_class(object):
def create_child(self, cr, path, data=None):
""" Create a regular file under this node
"""
_logger.warning("Attempted to create a file under %r, not possible.", self)
_logger.info("Attempted to create a file under %r, not possible.", self)
raise IOError(errno.EPERM, "Not allowed to create file(s) here.")
def create_child_collection(self, cr, objname):
""" Create a child collection (directory) under self
"""
_logger.warning("Attempted to create a collection under %r, not possible.", self)
_logger.info("Attempted to create a collection under %r, not possible.", self)
raise IOError(errno.EPERM, "Not allowed to create folder(s) here.")
def rm(self, cr):
@@ -1477,7 +1477,7 @@ class node_res_obj(node_class):
def get_dav_eprop_DEPR(self, cr, ns, prop):
# Deprecated!
if ns != 'http://groupdav.org/' or prop != 'resourcetype':
_logger.warning("Who asks for %s:%s?" % (ns, prop))
_logger.info("Who asks for %s:%s?", ns, prop)
return None
cntobj = self.context._dirobj.pool.get('document.directory.content')
uid = self.context.uid
@@ -1980,7 +1980,7 @@ class nodefd_content(StringIO, node_descriptor):
elif mode == 'a':
StringIO.__init__(self, None)
else:
_logger.error("Incorrect mode %s is specified.", mode)
_logger.info("Incorrect mode %s is specified.", mode)
raise IOError(errno.EINVAL, "Invalid file mode.")
self.mode = mode
@@ -2006,7 +2006,7 @@ class nodefd_content(StringIO, node_descriptor):
raise NotImplementedError
cr.commit()
except Exception:
_logger.exception('Cannot update db content #%d for close.', par.cnt_id)
_logger.info('Cannot update db content #%d for close.', par.cnt_id)
raise
finally:
cr.close()
@@ -2033,7 +2033,7 @@ class nodefd_static(StringIO, node_descriptor):
elif mode == 'a':
StringIO.__init__(self, None)
else:
_logger.error("Incorrect mode %s is specified.", mode)
_logger.info("Incorrect mode %s is specified.", mode)
raise IOError(errno.EINVAL, "Invalid file mode.")
self.mode = mode
@@ -2058,7 +2058,7 @@ class nodefd_static(StringIO, node_descriptor):
raise NotImplementedError
cr.commit()
except Exception:
_logger.exception('Cannot update db content #%d for close.', par.cnt_id)
_logger.info('Cannot update db content #%d for close.', par.cnt_id)
raise
finally:
cr.close()
@@ -2086,7 +2086,7 @@ class nodefd_db(StringIO, node_descriptor):
elif mode == 'a':
StringIO.__init__(self, None)
else:
_logger.error("Incorrect mode %s is specified.", mode)
_logger.info("Incorrect mode %s is specified.", mode)
raise IOError(errno.EINVAL, "Invalid file mode.")
self.mode = mode
+1 -1
View File
@@ -73,7 +73,7 @@
new_dir_id = self.create(cr, demo_uid, dir_vals, context=None)
self.unlink(cr, uid, [new_dir_id], context=None)
except except_osv, e:
duplicate_detected = e.value == u'Directory name must be unique!'
duplicate_detected = e.name == u'Directory name must be unique!'
assert duplicate_detected is True, 'Failed to detect duplicate directory'
-
I delete the attachments
+3 -3
View File
@@ -33,6 +33,7 @@ from openerp.osv import osv, fields
from openerp.tools.translate import _
from openerp.tools.safe_eval import safe_eval as eval
_logger = logging.getLogger(__name__)
from openerp.exceptions import UserError
EXTERNAL_ID_PATTERN = re.compile(r'^([^.:]+)(?::([^.]+))?\.(\S+)$')
EDI_VIEW_WEB_URL = '%s/edi/view?db=%s&token=%s'
@@ -126,9 +127,8 @@ class edi(osv.AbstractModel):
module = edi_document.get('__import_module') or edi_document.get('__module')
assert module, 'a `__module` or `__import_module` attribute is required in each EDI document.'
if module != 'base' and not ir_module.search(cr, uid, [('name','=',module),('state','=','installed')]):
raise osv.except_osv(_('Missing Application.'),
_("The document you are trying to import requires the Odoo `%s` application. "
"You can install it by connecting as the administrator and opening the configuration assistant.")%(module,))
raise UserError(_("The document you are trying to import requires the Odoo `%s` application. "
"You can install it by connecting as the administrator and opening the configuration assistant.")%(module,))
model = edi_document.get('__import_model') or edi_document.get('__model')
assert model, 'a `__model` or `__import_model` attribute is required in each EDI document.'
assert model in self.pool, 'model `%s` cannot be found, despite module `%s` being available - '\
+4 -4
View File
@@ -24,6 +24,7 @@ from openerp.osv import osv
from edi import EDIMixin
from openerp import SUPERUSER_ID
_logger = logging.getLogger(__name__)
from openerp.exceptions import UserError
RES_PARTNER_EDI_STRUCT = {
'name': True,
@@ -82,9 +83,8 @@ class res_partner(osv.osv, EDIMixin):
try:
self.edi_import_relation(cr, uid, 'res.partner.bank',
bank_name, ext_bank_id, context=import_ctx)
except osv.except_osv:
except UserError:
# failed to import it, try again with unrestricted default type
_logger.warning('Failed to import bank account using'
'bank type: %s, ignoring', import_ctx['default_state'],
exc_info=True)
_logger.info('Failed to import bank account using '
'bank type: %s, ignoring', import_ctx['default_state'], exc_info=True)
return contact_id
+6 -6
View File
@@ -3,7 +3,7 @@
import pytz
from openerp import _, api, fields, models
from openerp.exceptions import Warning
from openerp.exceptions import UserError
class event_type(models.Model):
@@ -184,13 +184,13 @@ class event_event(models.Model):
@api.constrains('seats_max', 'seats_available')
def _check_seats_limit(self):
if self.seats_max and self.seats_available < 0:
raise Warning(_('No more available seats.'))
raise UserError(_('No more available seats.'))
@api.one
@api.constrains('date_begin', 'date_end')
def _check_closing_date(self):
if self.date_end < self.date_begin:
raise Warning(_('Closing Date cannot be set before Beginning Date.'))
raise UserError(_('Closing Date cannot be set before Beginning Date.'))
@api.model
def create(self, vals):
@@ -207,7 +207,7 @@ class event_event(models.Model):
def button_cancel(self):
for event_reg in self.registration_ids:
if event_reg.state == 'done':
raise Warning(_("You have already set a registration for this event as 'Attended'. Please reset it to draft if you want to cancel this event."))
raise UserError(_("You have already set a registration for this event as 'Attended'. Please reset it to draft if you want to cancel this event."))
self.registration_ids.write({'state': 'cancel'})
self.state = 'cancel'
@@ -275,7 +275,7 @@ class event_registration(models.Model):
@api.constrains('event_id', 'state')
def _check_seats_limit(self):
if self.event_id.seats_max and self.event_id.seats_available < (1 if self.state == 'draft' else 0):
raise Warning(_('No more seats available for this event.'))
raise UserError(_('No more seats available for this event.'))
@api.multi
def _check_auto_confirmation(self):
@@ -312,7 +312,7 @@ class event_registration(models.Model):
if self.event_id.date_begin <= today:
self.write({'state': 'done', 'date_closed': today})
else:
raise Warning(_("You must wait for the starting day of the event to do this action."))
raise UserError(_("You must wait for the starting day of the event to do this action."))
@api.one
def button_reg_cancel(self):
+2 -2
View File
@@ -4,7 +4,7 @@ import datetime
from dateutil.relativedelta import relativedelta
from openerp.addons.event.tests.common import TestEventCommon
from openerp.exceptions import AccessError, ValidationError, Warning
from openerp.exceptions import AccessError, ValidationError, UserError
from openerp.tools import mute_logger
@@ -57,7 +57,7 @@ class TestEventFlow(TestEventCommon):
test_event.button_done()
# EventUser cancels -> not possible when having attendees
with self.assertRaises(Warning):
with self.assertRaises(UserError):
test_event.button_cancel()
+3 -3
View File
@@ -2,7 +2,7 @@
from openerp import models, fields, api, _
import openerp.addons.decimal_precision as dp
from openerp.exceptions import Warning
from openerp.exceptions import UserError
from openerp.osv import fields as old_fields
@@ -137,7 +137,7 @@ class event_ticket(models.Model):
@api.constrains('registration_ids', 'seats_max')
def _check_seats_limit(self):
if self.seats_max and self.seats_available < 0:
raise Warning('No more available seats for the ticket')
raise UserError(_('No more available seats for the ticket'))
@api.onchange('product_id')
def onchange_product_id(self):
@@ -159,7 +159,7 @@ class event_registration(models.Model):
@api.constrains('event_ticket_id', 'state')
def _check_ticket_seats_limit(self):
if self.event_ticket_id.seats_max and self.event_ticket_id.seats_available < 0:
raise Warning('No more available seats for this ticket')
raise UserError(_('No more available seats for this ticket'))
@api.multi
def _check_auto_confirmation(self):
+1 -1
View File
@@ -57,4 +57,4 @@
order = self.pool.get('sale.order').browse(cr, uid,order_id)
registration_ids = self.search(cr,uid,[('origin', '=', order.name)])
if registration_ids == []:
raise osv.except_osv(_('Error!'),_("The registration is not created."))
raise UserError(_("The registration is not created."))
+7 -6
View File
@@ -37,6 +37,7 @@ from openerp import addons
from openerp.osv import fields, osv
from openerp import tools, api
from openerp.tools.translate import _
from openerp.exceptions import UserError
_logger = logging.getLogger(__name__)
@@ -159,8 +160,8 @@ openerp_mailgate: "|/path/to/openerp-mailgate.py --host=localhost -u %(uid)d -p
connection = server.connect()
server.write({'state':'done'})
except Exception, e:
_logger.exception("Failed to connect to %s server %s.", server.type, server.name)
raise osv.except_osv(_("Connection test failed!"), _("Here is what we got instead:\n %s.") % tools.ustr(e))
_logger.info("Failed to connect to %s server %s.", server.type, server.name, exc_info=True)
raise UserError(_("Connection test failed: %s") % tools.ustr(e))
finally:
try:
if connection:
@@ -206,7 +207,7 @@ openerp_mailgate: "|/path/to/openerp-mailgate.py --host=localhost -u %(uid)d -p
strip_attachments=(not server.attach),
context=context)
except Exception:
_logger.exception('Failed to process mail from %s server %s.', server.type, server.name)
_logger.info('Failed to process mail from %s server %s.', server.type, server.name, exc_info=True)
failed += 1
if res_id and server.action_id:
action_pool.run(cr, uid, [server.action_id.id], {'active_id': res_id, 'active_ids': [res_id], 'active_model': context.get("thread_model", server.object_id.model)})
@@ -215,7 +216,7 @@ openerp_mailgate: "|/path/to/openerp-mailgate.py --host=localhost -u %(uid)d -p
count += 1
_logger.info("Fetched %d email(s) on %s server %s; %d succeeded, %d failed.", count, server.type, server.name, (count - failed), failed)
except Exception:
_logger.exception("General failure when trying to fetch mail from %s server %s.", server.type, server.name)
_logger.info("General failure when trying to fetch mail from %s server %s.", server.type, server.name, exc_info=True)
finally:
if imap_server:
imap_server.close()
@@ -237,14 +238,14 @@ openerp_mailgate: "|/path/to/openerp-mailgate.py --host=localhost -u %(uid)d -p
context=context)
pop_server.dele(num)
except Exception:
_logger.exception('Failed to process mail from %s server %s.', server.type, server.name)
_logger.info('Failed to process mail from %s server %s.', server.type, server.name, exc_info=True)
failed += 1
if res_id and server.action_id:
action_pool.run(cr, uid, [server.action_id.id], {'active_id': res_id, 'active_ids': [res_id], 'active_model': context.get("thread_model", server.object_id.model)})
cr.commit()
_logger.info("Fetched %d email(s) on %s server %s; %d succeeded, %d failed.", numMsgs, server.type, server.name, (numMsgs - failed), failed)
except Exception:
_logger.exception("General failure when trying to fetch mail from %s server %s.", server.type, server.name)
_logger.info("General failure when trying to fetch mail from %s server %s.", server.type, server.name, exc_info=True)
finally:
if pop_server:
pop_server.quit()
+2 -2
View File
@@ -23,7 +23,7 @@ from openerp.osv import fields, osv
import time
import datetime
from openerp import tools
from openerp.osv.orm import except_orm
from openerp.exceptions import UserError
from openerp.tools.translate import _
from dateutil.relativedelta import relativedelta
@@ -44,7 +44,7 @@ class fleet_vehicle_cost(osv.Model):
def _set_odometer(self, cr, uid, id, name, value, args=None, context=None):
if not value:
raise except_orm(_('Operation not allowed!'), _('Emptying the odometer value of a vehicle is not allowed.'))
raise UserError(_('Emptying the odometer value of a vehicle is not allowed.'))
date = self.browse(cr, uid, id, context=context).date
if not(date):
date = fields.date.context_today(self, cr, uid, context=context)
+5 -4
View File
@@ -26,6 +26,7 @@ from openerp.tools.translate import _
from datetime import date
import logging
from openerp.exceptions import UserError
_logger = logging.getLogger(__name__)
@@ -235,13 +236,13 @@ class gamification_badge(osv.Model):
if status_code == self.CAN_GRANT:
return True
elif status_code == self.NOBODY_CAN_GRANT:
raise osv.except_osv(_('Warning!'), _('This badge can not be sent by users.'))
raise UserError(_('This badge can not be sent by users.'))
elif status_code == self.USER_NOT_VIP:
raise osv.except_osv(_('Warning!'), _('You are not in the user allowed list.'))
raise UserError(_('You are not in the user allowed list.'))
elif status_code == self.BADGE_REQUIRED:
raise osv.except_osv(_('Warning!'), _('You do not have the required badges.'))
raise UserError(_('You do not have the required badges.'))
elif status_code == self.TOO_MANY:
raise osv.except_osv(_('Warning!'), _('You have already sent this badge too many time this month.'))
raise UserError(_('You have already sent this badge too many time this month.'))
else:
_logger.exception("Unknown badge status code: %d" % int(status_code))
return False
+3 -2
View File
@@ -28,6 +28,7 @@ from openerp.tools.translate import _
from datetime import date, datetime, timedelta
import calendar
import logging
from openerp.exceptions import UserError
_logger = logging.getLogger(__name__)
# display top 3 in ranking, could be db variable
@@ -248,7 +249,7 @@ class gamification_challenge(osv.Model):
elif vals.get('state') == 'draft':
# resetting progress
if self.pool.get('gamification.goal').search(cr, uid, [('challenge_id', 'in', ids), ('state', '=', 'inprogress')], context=context):
raise osv.except_osv("Error", "You can not reset a challenge with unfinished goals.")
raise UserError(_("You can not reset a challenge with unfinished goals."))
return write_res
@@ -553,7 +554,7 @@ class gamification_challenge(osv.Model):
if challenge.visibility_mode == 'personal':
if not user_id:
raise osv.except_osv(_('Error!'),_("Retrieving progress for personal challenge without user information"))
raise UserError(_("Retrieving progress for personal challenge without user information"))
domain.append(('user_id', '=', user_id))
sorting = goal_obj._order
limit = 1
+3 -2
View File
@@ -24,6 +24,7 @@ from openerp.osv import fields, osv
from openerp.tools import DEFAULT_SERVER_DATE_FORMAT as DF
from openerp.tools.safe_eval import safe_eval
from openerp.tools.translate import _
from openerp.exceptions import UserError
import logging
import time
@@ -145,7 +146,7 @@ class gamification_goal_definition(osv.Model):
obj.search(cr, uid, domain, context=context, count=True)
except (ValueError, SyntaxError), e:
msg = e.message or (e.msg + '\n' + e.text)
raise osv.except_osv(_('Error!'),_("The domain for the definition %s seems incorrect, please check it.\n\n%s" % (definition.name, msg)))
raise UserError(_("The domain for the definition %s seems incorrect, please check it.\n\n%s" % (definition.name, msg)))
return True
def create(self, cr, uid, vals, context=None):
@@ -450,7 +451,7 @@ class gamification_goal(osv.Model):
for goal in self.browse(cr, uid, ids, context=context):
if goal.state != "draft" and ('definition_id' in vals or 'user_id' in vals):
# avoid drag&drop in kanban view
raise osv.except_osv(_('Error!'), _('Can not modify the configuration of a started goal'))
raise UserError(_('Can not modify the configuration of a started goal'))
if vals.get('current'):
if 'no_remind_goal' in context:
+2 -1
View File
@@ -21,6 +21,7 @@
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class grant_badge_wizard(osv.TransientModel):
@@ -40,7 +41,7 @@ class grant_badge_wizard(osv.TransientModel):
for wiz in self.browse(cr, uid, ids, context=context):
if uid == wiz.user_id.id:
raise osv.except_osv(_('Warning!'), _('You can not grant a badge to yourself'))
raise UserError(_('You can not grant a badge to yourself'))
#create the badge
values = {
+3 -3
View File
@@ -596,8 +596,8 @@ class google_calendar(osv.AbstractModel):
att_obj.write(cr, uid, [att.id], {'google_internal_event_id': response['id'], 'oe_synchro_date': update_date})
cr.commit()
else:
_logger.warning("Impossible to create event %s. [%s]" % (att.event_id.id, st))
_logger.warning("Response : %s" % response)
_logger.warning("Impossible to create event %s. [%s] Enable DEBUG for response detail.", att.event_id.id, st)
_logger.debug("Response : %s" % response)
return new_ids
def get_context_no_virtual(self, context):
@@ -643,7 +643,7 @@ class google_calendar(osv.AbstractModel):
cr.commit()
else:
_logger.warning("Impossible to create event %s. [%s]" % (att.event_id.id, st))
_logger.warning("Response : %s" % response)
_logger.debug("Response : %s" % response)
except:
pass
return new_ids
+7 -6
View File
@@ -22,6 +22,7 @@ import logging
from openerp import SUPERUSER_ID
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
import werkzeug.urls
import urllib2
@@ -46,7 +47,7 @@ class config(osv.Model):
try:
name_gdocs = name_gdocs % record
except:
raise osv.except_osv(_('Key Error!'), _("At least one key cannot be found in your Google Drive name pattern"))
raise UserError(_("At least one key cannot be found in your Google Drive name pattern"))
attach_pool = self.pool.get("ir.attachment")
attach_ids = attach_pool.search(cr, uid, [('res_model', '=', model.model), ('name', '=', name_gdocs), ('res_id', '=', res_id)])
@@ -68,7 +69,7 @@ class config(osv.Model):
msg = _("You haven't configured 'Authorization Code' generated from google, Please generate and configure it .")
raise openerp.exceptions.RedirectWarning(msg, action_id, _('Go to the configuration panel'))
else:
raise osv.except_osv(_('Error!'), _("Google Drive is not yet configured. Please contact your administrator."))
raise UserError(_("Google Drive is not yet configured. Please contact your administrator."))
google_drive_client_id = ir_config.get_param(cr, SUPERUSER_ID, 'google_drive_client_id')
google_drive_client_secret = ir_config.get_param(cr, SUPERUSER_ID, 'google_drive_client_secret')
#For Getting New Access Token With help of old Refresh Token
@@ -88,7 +89,7 @@ class config(osv.Model):
msg = _("Something went wrong during the token generation. Please request again an authorization code .")
raise openerp.exceptions.RedirectWarning(msg, action_id, _('Go to the configuration panel'))
else:
raise osv.except_osv(_('Error!'), _("Google Drive is not yet configured. Please contact your administrator."))
raise UserError(_("Google Drive is not yet configured. Please contact your administrator."))
content = json.loads(content)
return content.get('access_token')
@@ -103,7 +104,7 @@ class config(osv.Model):
req = urllib2.Request(request_url, None, headers)
parents = urllib2.urlopen(req).read()
except urllib2.HTTPError:
raise osv.except_osv(_('Warning!'), _("The Google Template cannot be found. Maybe it has been deleted."))
raise UserError(_("The Google Template cannot be found. Maybe it has been deleted."))
parents_dict = json.loads(parents)
record_url = "Click on link to open Record in Odoo\n %s/?db=%s#id=%s&model=%s" % (google_web_base_url, cr.dbname, res_id, res_model)
@@ -154,7 +155,7 @@ class config(osv.Model):
:return: the config id and config name
'''
if not res_id:
raise osv.except_osv(_('Google Drive Error!'), _("Creating google drive may only be done by one at a time."))
raise UserError(_("Creating google drive may only be done by one at a time."))
# check if a model is configured with a template
config_ids = self.search(cr, uid, [('model_id', '=', res_model)], context=context)
configs = []
@@ -186,7 +187,7 @@ class config(osv.Model):
if mo:
result[data.id] = mo
else:
raise osv.except_osv(_('Incorrect URL!'), _("Please enter a valid Google Document URL."))
raise UserError(_("Please enter a valid Google Document URL."))
return result
def _client_id_get(self, cr, uid, ids, name, arg, context=None):
+2 -1
View File
@@ -24,6 +24,7 @@ from datetime import datetime
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class hr_action_reason(osv.osv):
@@ -179,7 +180,7 @@ class hr_employee(osv.osv):
if employee.state == 'absent': action = 'sign_in'
if not self._action_check(cr, uid, employee.id, action_date, context):
raise osv.except_osv(_('Warning'), _('You tried to %s with a date anterior to another event !\nTry to contact the HR Manager to correct attendances.')%(warning_sign[action],))
raise UserError(_('You tried to %s with a date anterior to another event !\nTry to contact the HR Manager to correct attendances.') % (warning_sign[action],))
vals = {'action': action, 'employee_id': employee.id}
if action_date:
@@ -46,8 +46,8 @@
import time
try:
self.create(cr, uid, {'employee_id': ref('hr.employee_niv'), 'name': time.strftime('%Y-%m-%d 09:59:25'), 'action': 'sign_out'}, None)
except Exception, e:
assert e[0]=='ValidateError', e
except openerp.exceptions.ValidationError:
pass
-
First of all, Employee Sign's In.
-
@@ -62,8 +62,8 @@
import time
try:
self.create(cr, uid, {'employee_id': ref('hr.employee_niv'), 'name': time.strftime('%Y-%m-%d 08:59:25'), 'action': 'sign_in'}, None)
except Exception, e:
assert e[0]=='ValidateError', e
except openerp.exceptions.ValidationError:
pass
-
After that Employee is going to Sign In after First Sign In.
-
@@ -71,8 +71,8 @@
import time
try:
self.create(cr, uid, {'employee_id': ref('hr.employee_niv'), 'name': time.strftime('%Y-%m-%d 10:59:25'), 'action': 'sign_in'}, None)
except Exception, e:
assert e[0]=='ValidateError', e
except openerp.exceptions.ValidationError:
pass
-
After two hours, Employee Sign's Out.
-
@@ -87,8 +87,8 @@
import time
try:
self.create(cr, uid, {'employee_id': ref('hr.employee_niv'), 'name': time.strftime('%Y-%m-%d 10:59:25'), 'action': 'sign_out'}, None)
except Exception, e:
assert e[0]=='ValidateError', e
except openerp.exceptions.ValidationError:
pass
-
After that Employee is going to Sign Out After First Sign Out.
-
@@ -96,5 +96,5 @@
import time
try:
self.create(cr, uid, {'employee_id': ref('hr.employee_niv'), 'name': time.strftime('%Y-%m-%d 12:59:25'), 'action': 'sign_out'}, None)
except Exception, e:
assert e[0]=='ValidateError', e
except openerp.exceptions.ValidationError:
pass
@@ -22,6 +22,7 @@ import time
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class hr_attendance_error(osv.osv_memory):
@@ -47,7 +48,7 @@ class hr_attendance_error(osv.osv_memory):
cr.execute("SELECT id FROM hr_attendance WHERE employee_id IN %s AND to_char(name,'YYYY-mm-dd')<=%s AND to_char(name,'YYYY-mm-dd')>=%s AND action IN %s ORDER BY name" ,(tuple(context['active_ids']), date_to, date_from, tuple(['sign_in','sign_out'])))
attendance_ids = [x[0] for x in cr.fetchall()]
if not attendance_ids:
raise osv.except_osv(_('No Data Available!'), _('No records are found for your selection!'))
raise UserError(_('No records are found for your selection!'))
attendance_records = self.pool.get('hr.attendance').browse(cr, uid, attendance_ids, context=context)
for rec in attendance_records:
+3 -2
View File
@@ -27,6 +27,7 @@ import time
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT as DF
from openerp.exceptions import UserError
class hr_evaluation_plan(osv.Model):
@@ -236,7 +237,7 @@ class hr_evaluation(osv.Model):
if evaluation.employee_id and evaluation.employee_id.parent_id and evaluation.employee_id.parent_id.user_id:
self.message_subscribe_users(cr, uid, [evaluation.id], user_ids=[evaluation.employee_id.parent_id.user_id.id], context=context)
if len(evaluation.survey_request_ids) != len(request_obj.search(cr, uid, [('evaluation_id', '=', evaluation.id), ('state', 'in', ['done', 'cancel'])], context=context)):
raise osv.except_osv(_('Warning!'), _("You cannot change state, because some appraisal forms have not been completed."))
raise UserError(_("You cannot change state, because some appraisal forms have not been completed."))
return True
def button_done(self, cr, uid, ids, context=None):
@@ -336,7 +337,7 @@ class hr_evaluation_interview(osv.Model):
flag = False
wating_id = 0
if not id.evaluation_id.id:
raise osv.except_osv(_('Warning!'), _("You cannot start evaluation without Appraisal."))
raise UserError(_("You cannot start evaluation without Appraisal."))
records = id.evaluation_id.survey_request_ids
for child in records:
if child.state == "draft":
+7 -6
View File
@@ -25,6 +25,7 @@ from openerp.osv import fields, osv
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
from openerp.exceptions import UserError
def _employee_get(obj, cr, uid, context=None):
if context is None:
@@ -114,7 +115,7 @@ class hr_expense_expense(osv.osv):
def unlink(self, cr, uid, ids, context=None):
for rec in self.browse(cr, uid, ids, context=context):
if rec.state != 'draft':
raise osv.except_osv(_('Warning!'),_('You can only delete draft expenses!'))
raise UserError(_('You can only delete draft expenses!'))
return super(hr_expense_expense, self).unlink(cr, uid, ids, context)
def onchange_currency_id(self, cr, uid, ids, currency_id=False, company_id=False, context=None):
@@ -140,7 +141,7 @@ class hr_expense_expense(osv.osv):
def expense_confirm(self, cr, uid, ids, context=None):
for expense in self.browse(cr, uid, ids):
if not expense.line_ids:
raise osv.except_osv(_('Error!'), _('You cannot submit expense which has no expense line.'))
raise UserError(_('You cannot submit expense which has no expense line.'))
if expense.employee_id and expense.employee_id.parent_id.user_id:
self.message_subscribe_users(cr, uid, [expense.id], user_ids=[expense.employee_id.parent_id.user_id.id])
return self.write(cr, uid, ids, {'state': 'confirm', 'date_confirm': time.strftime('%Y-%m-%d')}, context=context)
@@ -170,7 +171,7 @@ class hr_expense_expense(osv.osv):
else:
journal_id = journal_obj.search(cr, uid, [('type', '=', 'purchase'), ('company_id', '=', company_id)])
if not journal_id:
raise osv.except_osv(_('Error!'), _("No expense journal found. Please make sure you have a journal with type 'purchase' configured."))
raise UserError(_("No expense journal found. Please make sure you have a journal with type 'purchase' configured."))
journal_id = journal_id[0]
return self.pool.get('account.move').account_move_prepare(cr, uid, journal_id, date=date, ref=ref, company_id=company_id, context=context)
@@ -233,7 +234,7 @@ class hr_expense_expense(osv.osv):
move_obj = self.pool.get('account.move')
for exp in self.browse(cr, uid, ids, context=context):
if not exp.employee_payable_account_id:
raise osv.except_osv(_('Error!'), _('No employee account payable found for the expense '))
raise UserError(_('No employee account payable found for the expense '))
company_currency = exp.company_id.currency_id.id
diff_currency_p = exp.currency_id.id != company_currency
@@ -347,11 +348,11 @@ class hr_expense_expense(osv.osv):
if not acc:
acc = line.product_id.categ_id.property_account_expense_categ
if not acc:
raise osv.except_osv(_('Error!'), _('No purchase account found for the product %s (or for his category), please configure one.') % (line.product_id.name))
raise UserError(_('No purchase account found for the product %s (or for his category), please configure one.') % (line.product_id.name))
else:
acc = property_obj.get(cr, uid, 'property_account_expense_categ', 'product.category', context={'force_company': company.id})
if not acc:
raise osv.except_osv(_('Error!'), _('Please configure Default Expense account for Product purchase: `property_account_expense_categ`.'))
raise UserError(_('Please configure Default Expense account for Product purchase: `property_account_expense_categ`.'))
return {
'type':'src',
'name': line.name.split('\n')[0][:64],
+3 -2
View File
@@ -21,6 +21,7 @@
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class hr_grant_badge_wizard(osv.TransientModel):
_name = 'gamification.badge.user.wizard'
@@ -42,10 +43,10 @@ class hr_grant_badge_wizard(osv.TransientModel):
for wiz in self.browse(cr, uid, ids, context=context):
if not wiz.user_id:
raise osv.except_osv(_('Warning!'), _('You can send badges only to employees linked to a user.'))
raise UserError(_('You can send badges only to employees linked to a user.'))
if uid == wiz.user_id.id:
raise osv.except_osv(_('Warning!'), _('You can not send a badge to yourself'))
raise UserError(_('You can not send a badge to yourself'))
values = {
'user_id': wiz.user_id.id,
+9 -9
View File
@@ -29,7 +29,7 @@ import math
import time
from operator import attrgetter
from openerp.exceptions import Warning
from openerp.exceptions import UserError, AccessError
from openerp import tools
from openerp.osv import fields, osv
from openerp.tools.translate import _
@@ -305,7 +305,7 @@ class hr_holidays(osv.osv):
def unlink(self, cr, uid, ids, context=None):
for rec in self.browse(cr, uid, ids, context=context):
if rec.state not in ['draft', 'cancel', 'confirm']:
raise osv.except_osv(_('Warning!'),_('You cannot delete a leave which is in %s state.')%(rec.state))
raise UserError(_('You cannot delete a leave which is in %s state.') % (rec.state,))
return super(hr_holidays, self).unlink(cr, uid, ids, context)
def onchange_date_from(self, cr, uid, ids, date_to, date_from):
@@ -316,7 +316,7 @@ class hr_holidays(osv.osv):
"""
# date_to has to be greater than date_from
if (date_from and date_to) and (date_from > date_to):
raise osv.except_osv(_('Warning!'),_('The start date must be anterior to the end date.'))
raise UserError(_('The start date must be anterior to the end date.'))
result = {'value': {}}
@@ -340,7 +340,7 @@ class hr_holidays(osv.osv):
"""
# date_to has to be greater than date_from
if (date_from and date_to) and (date_from > date_to):
raise osv.except_osv(_('Warning!'),_('The start date must be anterior to the end date.'))
raise UserError(_('The start date must be anterior to the end date.'))
result = {'value': {}}
@@ -358,12 +358,12 @@ class hr_holidays(osv.osv):
context = {}
context = dict(context, mail_create_nolog=True)
if values.get('state') and values['state'] not in ['draft', 'confirm', 'cancel'] and not self.pool['res.users'].has_group(cr, uid, 'base.group_hr_user'):
raise osv.except_osv(_('Warning!'), _('You cannot set a leave request as \'%s\'. Contact a human resource manager.') % values.get('state'))
raise AccessError(_('You cannot set a leave request as \'%s\'. Contact a human resource manager.') % values.get('state'))
return super(hr_holidays, self).create(cr, uid, values, context=context)
def write(self, cr, uid, ids, vals, context=None):
if vals.get('state') and vals['state'] not in ['draft', 'confirm', 'cancel'] and not self.pool['res.users'].has_group(cr, uid, 'base.group_hr_user'):
raise osv.except_osv(_('Warning!'), _('You cannot set a leave request as \'%s\'. Contact a human resource manager.') % vals.get('state'))
raise AccessError(_('You cannot set a leave request as \'%s\'. Contact a human resource manager.') % vals.get('state'))
return super(hr_holidays, self).write(cr, uid, ids, vals, context=context)
def holidays_reset(self, cr, uid, ids, context=None):
@@ -480,7 +480,7 @@ class hr_holidays(osv.osv):
leave_days = self.pool.get('hr.holidays.status').get_days(cr, uid, [record.holiday_status_id.id], record.employee_id.id, context=context)[record.holiday_status_id.id]
if leave_days['remaining_leaves'] < 0 or leave_days['virtual_remaining_leaves'] < 0:
# Raising a warning gives a more user-friendly feedback than the default constraint error
raise Warning(_('The number of remaining leaves is not sufficient for this leave type.\n'
raise UserError(_('The number of remaining leaves is not sufficient for this leave type.\n'
'Please verify also the leaves waiting for validation.'))
return True
@@ -517,14 +517,14 @@ class hr_employee(osv.Model):
# Find for holidays status
status_ids = type_obj.search(cr, uid, [('limit', '=', False)], context=context)
if len(status_ids) != 1 :
raise osv.except_osv(_('Warning!'),_("The feature behind the field 'Remaining Legal Leaves' can only be used when there is only one leave type with the option 'Allow to Override Limit' unchecked. (%s Found). Otherwise, the update is ambiguous as we cannot decide on which leave type the update has to be done. \nYou may prefer to use the classic menus 'Leave Requests' and 'Allocation Requests' located in 'Human Resources \ Leaves' to manage the leave days of the employees if the configuration does not allow to use this field.") % (len(status_ids)))
raise UserError(_("The feature behind the field 'Remaining Legal Leaves' can only be used when there is only one leave type with the option 'Allow to Override Limit' unchecked. (%s Found). Otherwise, the update is ambiguous as we cannot decide on which leave type the update has to be done. \nYou may prefer to use the classic menus 'Leave Requests' and 'Allocation Requests' located in 'Human Resources \ Leaves' to manage the leave days of the employees if the configuration does not allow to use this field.") % (len(status_ids)))
status_id = status_ids and status_ids[0] or False
if not status_id:
return False
if diff > 0:
leave_id = holiday_obj.create(cr, uid, {'name': _('Allocation for %s') % employee.name, 'employee_id': employee.id, 'holiday_status_id': status_id, 'type': 'add', 'holiday_type': 'employee', 'number_of_days_temp': diff}, context=context)
elif diff < 0:
raise osv.except_osv(_('Warning!'), _('You cannot reduce validated allocation requests'))
raise UserError(_('You cannot reduce validated allocation requests'))
else:
return False
for sig in ('confirm', 'validate', 'second_validate'):
@@ -24,7 +24,7 @@ from dateutil.relativedelta import relativedelta
from openerp.addons.hr_holidays.tests.common import TestHrHolidaysBase
from openerp.exceptions import AccessError
from openerp.osv.orm import except_orm
from openerp.exceptions import ValidationError
from openerp.tools import mute_logger
class TestHolidaysFlow(TestHrHolidaysBase):
@@ -72,7 +72,7 @@ class TestHolidaysFlow(TestHrHolidaysBase):
# --------------------------------------------------
# Employee creates a leave request for another employee -> should crash
with self.assertRaises(except_orm):
with self.assertRaises(ValidationError):
self.hr_holidays.create(cr, self.user_employee_id, {
'name': 'Hol10',
'employee_id': self.employee_hruser_id,
@@ -111,7 +111,7 @@ class TestHolidaysFlow(TestHrHolidaysBase):
# --------------------------------------------------
# Employee creates a new leave request at the same time -> crash, avoid interlapping
with self.assertRaises(except_orm):
with self.assertRaises(ValidationError):
self.hr_holidays.create(cr, self.user_employee_id, {
'name': 'Hol21',
'employee_id': self.employee_emp_id,
@@ -122,7 +122,7 @@ class TestHolidaysFlow(TestHrHolidaysBase):
})
# Employee creates a leave request in a limited category -> crash, not enough days left
with self.assertRaises(except_orm):
with self.assertRaises(ValidationError):
self.hr_holidays.create(cr, self.user_employee_id, {
'name': 'Hol22',
'employee_id': self.employee_emp_id,
@@ -205,5 +205,5 @@ class TestHolidaysFlow(TestHrHolidaysBase):
'date_to': (datetime.today() + relativedelta(days=7)),
'number_of_days_temp': 4,
})
with self.assertRaises(except_orm):
with self.assertRaises(ValidationError):
self.hr_holidays.signal_workflow(cr, self.user_hrmanager_id, [hol2_id], 'confirm')
@@ -23,6 +23,7 @@ import time
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class hr_holidays_summary_dept(osv.osv_memory):
_name = 'hr.holidays.summary.dept'
@@ -41,7 +42,7 @@ class hr_holidays_summary_dept(osv.osv_memory):
def print_report(self, cr, uid, ids, context=None):
data = self.read(cr, uid, ids, context=context)[0]
if not data['depts']:
raise osv.except_osv(_('Error!'), _('You have to select at least one Department. And try again.'))
raise UserError(_('You have to select at least one Department. And try again.'))
datas = {
'ids': [],
'model': 'ir.ui.menu',
+7 -6
View File
@@ -32,6 +32,7 @@ from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
from openerp.tools.safe_eval import safe_eval as eval
from openerp.exceptions import UserError
class hr_payroll_structure(osv.osv):
"""
@@ -350,7 +351,7 @@ class hr_payslip(osv.osv):
def unlink(self, cr, uid, ids, context=None):
for payslip in self.browse(cr, uid, ids, context=context):
if payslip.state not in ['draft','cancel']:
raise osv.except_osv(_('Warning!'),_('You cannot delete a payslip which is not draft or cancelled!'))
raise UserError(_('You cannot delete a payslip which is not draft or cancelled!'))
return super(hr_payslip, self).unlink(cr, uid, ids, context)
#TODO move this function into hr_contract module, on hr.employee object
@@ -848,18 +849,18 @@ result = rules.NET > categories.NET * 0.10''',
try:
return rule.amount_fix, eval(rule.quantity, localdict), 100.0
except:
raise osv.except_osv(_('Error!'), _('Wrong quantity defined for salary rule %s (%s).')% (rule.name, rule.code))
raise UserError(_('Wrong quantity defined for salary rule %s (%s).') % (rule.name, rule.code))
elif rule.amount_select == 'percentage':
try:
return eval(rule.amount_percentage_base, localdict), eval(rule.quantity, localdict), rule.amount_percentage
except:
raise osv.except_osv(_('Error!'), _('Wrong percentage base or quantity defined for salary rule %s (%s).')% (rule.name, rule.code))
raise UserError(_('Wrong percentage base or quantity defined for salary rule %s (%s).') % (rule.name, rule.code))
else:
try:
eval(rule.amount_python_compute, localdict, mode='exec', nocopy=True)
return localdict['result'], 'result_qty' in localdict and localdict['result_qty'] or 1.0, 'result_rate' in localdict and localdict['result_rate'] or 100.0
except:
raise osv.except_osv(_('Error!'), _('Wrong python code defined for salary rule %s (%s).')% (rule.name, rule.code))
raise UserError(_('Wrong python code defined for salary rule %s (%s).') % (rule.name, rule.code))
def satisfy_condition(self, cr, uid, rule_id, localdict, context=None):
"""
@@ -876,13 +877,13 @@ result = rules.NET > categories.NET * 0.10''',
result = eval(rule.condition_range, localdict)
return rule.condition_range_min <= result and result <= rule.condition_range_max or False
except:
raise osv.except_osv(_('Error!'), _('Wrong range condition defined for salary rule %s (%s).')% (rule.name, rule.code))
raise UserError(_('Wrong range condition defined for salary rule %s (%s).') % (rule.name, rule.code))
else: #python code
try:
eval(rule.condition_python, localdict, mode='exec', nocopy=True)
return 'result' in localdict and localdict['result'] or False
except:
raise osv.except_osv(_('Error!'), _('Wrong python condition defined for salary rule %s (%s).')% (rule.name, rule.code))
raise UserError(_('Wrong python condition defined for salary rule %s (%s).') % (rule.name, rule.code))
class hr_rule_input(osv.osv):
@@ -25,6 +25,7 @@ from dateutil import relativedelta
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class hr_payslip_employees(osv.osv_memory):
@@ -49,7 +50,7 @@ class hr_payslip_employees(osv.osv_memory):
to_date = run_data.get('date_end', False)
credit_note = run_data.get('credit_note', False)
if not data['employee_ids']:
raise osv.except_osv(_("Warning!"), _("You must select employee(s) to generate payslip(s)."))
raise UserError(_("You must select employee(s) to generate payslip(s)."))
for emp in emp_pool.browse(cr, uid, data['employee_ids'], context=context):
slip_data = slip_pool.onchange_employee_id(cr, uid, [], from_date, to_date, emp.id, contract_id=False, context=context)
res = {
@@ -25,6 +25,7 @@ from datetime import date, datetime, timedelta
from openerp.osv import fields, osv
from openerp.tools import float_compare, float_is_zero
from openerp.tools.translate import _
from openerp.exceptions import UserError
class hr_payslip(osv.osv):
'''
@@ -149,7 +150,7 @@ class hr_payslip(osv.osv):
if float_compare(credit_sum, debit_sum, precision_digits=precision) == -1:
acc_id = slip.journal_id.default_credit_account_id.id
if not acc_id:
raise osv.except_osv(_('Configuration Error!'),_('The Expense Journal "%s" has not properly configured the Credit Account!')%(slip.journal_id.name))
raise UserError(_('The Expense Journal "%s" has not properly configured the Credit Account!') % (slip.journal_id.name))
adjust_credit = (0, 0, {
'name': _('Adjustment Entry'),
'date': timenow,
@@ -165,7 +166,7 @@ class hr_payslip(osv.osv):
elif float_compare(debit_sum, credit_sum, precision_digits=precision) == -1:
acc_id = slip.journal_id.default_debit_account_id.id
if not acc_id:
raise osv.except_osv(_('Configuration Error!'),_('The Expense Journal "%s" has not properly configured the Debit Account!')%(slip.journal_id.name))
raise UserError(_('The Expense Journal "%s" has not properly configured the Debit Account!') % (slip.journal_id.name))
adjust_debit = (0, 0, {
'name': _('Adjustment Entry'),
'date': timenow,
+2 -1
View File
@@ -26,6 +26,7 @@ from openerp import tools
from openerp import SUPERUSER_ID
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
AVAILABLE_PRIORITIES = [
@@ -568,7 +569,7 @@ class hr_applicant(osv.Model):
body=_('New Employee %s Hired') % applicant.partner_name if applicant.partner_name else applicant.name,
subtype="hr_recruitment.mt_job_applicant_hired", context=context)
else:
raise osv.except_osv(_('Warning!'), _('You must define an Applied Job and a Contact Name for this applicant.'))
raise UserError(_('You must define an Applied Job and a Contact Name for this applicant.'))
action_model, action_id = model_data.get_object_reference(cr, uid, 'hr', 'open_view_employee_list')
dict_act_window = act_window.read(cr, uid, [action_id], [])[0]
@@ -21,6 +21,7 @@
##############################################################################
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class hr_recruitment_partner_create(osv.osv_memory):
_name = 'hr.recruitment.partner.create'
@@ -35,8 +36,7 @@ class hr_recruitment_partner_create(osv.osv_memory):
context = {}
for case in case_obj.browse(cr, uid, context['active_ids'], context=context):
if case.partner_id:
raise osv.except_osv(_('Error!'),
_('A contact is already defined on this job request.'))
raise UserError(_('A contact is already defined on this job request.'))
pass
def make_order(self, cr, uid, ids, context=None):
@@ -53,7 +53,7 @@ class hr_recruitment_partner_create(osv.osv_memory):
for case in case_obj.browse(cr, uid, context['active_ids'], context=context):
partner_id = partner_obj.search(cr, uid, [('name', '=', case.partner_name or case.name)], context=context)
if partner_id:
raise osv.except_osv(_('Error!'),_('A contact is already existing with the same name.'))
raise UserError(_('A contact is already existing with the same name.'))
partner_id = partner_obj.create(cr, uid, {
'name': case.partner_name or case.name,
'user_id': case.user_id.id,
+4 -3
View File
@@ -25,6 +25,7 @@ from openerp.osv import fields
from openerp.osv import osv
from openerp.tools.translate import _
import openerp
from openerp.exceptions import UserError
class hr_employee(osv.osv):
_name = "hr.employee"
@@ -155,7 +156,7 @@ class hr_analytic_timesheet(osv.osv):
if emp.journal_id:
return emp.journal_id.id
else :
raise osv.except_osv(_('Warning!'), _('No analytic journal defined for \'%s\'.\nYou should assign an analytic journal on the employee form.')%(emp.name))
raise UserError(_('No analytic journal defined for \'%s\'.\nYou should assign an analytic journal on the employee form.') % (emp.name,))
_defaults = {
@@ -186,9 +187,9 @@ class hr_analytic_timesheet(osv.osv):
if emp_id:
ename = emp_obj.browse(cr, uid, emp_id[0], context=context).name
if not vals.get('journal_id',False):
raise osv.except_osv(_('Warning!'), _('No \'Analytic Journal\' is defined for employee %s \nDefine an employee for the selected user and assign an \'Analytic Journal\'!')%(ename,))
raise UserError(_('No \'Analytic Journal\' is defined for employee %s \nDefine an employee for the selected user and assign an \'Analytic Journal\'!') % (ename,))
if not vals.get('account_id',False):
raise osv.except_osv(_('Warning!'), _('No analytic account is defined on the project.\nPlease set one or we cannot automatically fill the timesheet.'))
raise UserError(_('No analytic account is defined on the project.\nPlease set one or we cannot automatically fill the timesheet.'))
return super(hr_analytic_timesheet, self).create(cr, uid, vals, context=context)
def on_change_user_id(self, cr, uid, ids, user_id):
@@ -22,6 +22,7 @@ import time
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class hr_so_project(osv.osv_memory):
_name = 'hr.sign.out.project'
@@ -74,7 +75,7 @@ class hr_so_project(osv.osv_memory):
res = timesheet_obj.default_get(cr, uid, ['product_id','product_uom_id'], context=context)
if not res['product_uom_id']:
raise osv.except_osv(_('User Error!'), _('Please define cost unit for this employee.'))
raise UserError(_('Please define cost unit for this employee.'))
up = timesheet_obj.on_change_unit_amount(cr, uid, False, res['product_id'], hour,False, res['product_uom_id'])['value']
res['name'] = data['info']
@@ -128,7 +129,7 @@ class hr_si_project(osv.osv_memory):
emp_obj = self.pool.get('hr.employee')
emp_id = emp_obj.search(cr, uid, [('user_id', '=', uid)], context=context)
if not emp_id:
raise osv.except_osv(_('User Error!'), _('Please define employee for your user.'))
raise UserError(_('Please define employee for your user.'))
return False
def check_state(self, cr, uid, ids, context=None):
@@ -23,6 +23,7 @@ import time
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class hr_timesheet_invoice_factor(osv.osv):
_name = "hr_timesheet_invoice.factor"
@@ -141,8 +142,7 @@ class account_analytic_line(osv.osv):
if ( not vals.has_key('invoice_id')) or vals['invoice_id' ] == False:
for line in self.browse(cr, uid, select):
if line.invoice_id:
raise osv.except_osv(_('Error!'),
_('You cannot modify an invoiced analytic line!'))
raise UserError(_('You cannot modify an invoiced analytic line!'))
return True
def _get_invoice_price(self, cr, uid, account, product_id, user_id, qty, context = {}):
@@ -180,8 +180,7 @@ class account_analytic_line(osv.osv):
for account in analytic_account_obj.browse(cr, uid, list(account_ids), context=context):
partner = account.partner_id
if (not partner) or not (account.pricelist_id):
raise osv.except_osv(_('Analytic Account Incomplete!'),
_('Contract incomplete. Please fill in the Customer and Pricelist fields.'))
raise UserError(_('Contract incomplete. Please fill in the Customer and Pricelist fields.'))
date_due = False
if partner.property_payment_term:
@@ -254,7 +253,7 @@ class account_analytic_line(osv.osv):
general_account = product.property_account_income or product.categ_id.property_account_income_categ
if not general_account:
raise osv.except_osv(_("Configuration Error!"), _("Please define income account for product '%s'.") % product.name)
raise UserError(_("Configuration Error!") + '\n' + _("Please define income account for product '%s'.") % product.name)
taxes = product.taxes_id or general_account.tax_ids
tax = fiscal_pos_obj.map_tax(cr, uid, account.partner_id.property_account_position, taxes)
curr_line.update({
@@ -22,6 +22,7 @@ import datetime
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class account_analytic_profit(osv.osv_memory):
@@ -56,7 +57,7 @@ class account_analytic_profit(osv.osv_memory):
('user_id', 'in', data['form']['employee_ids']),
], context=context)
if not ids_chk:
raise osv.except_osv(_('Insufficient Data!'), _('No record(s) found for this report.'))
raise UserError(_('No record(s) found for this report.'))
data['form']['journal_ids'] = [(6, 0, data['form']['journal_ids'])] # Improve me => Change the rml/sxw so that it can support withou [0][2]
data['form']['employee_ids'] = [(6, 0, data['form']['employee_ids'])]
@@ -22,6 +22,7 @@
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
class hr_timesheet_invoice_create(osv.osv_memory):
@@ -53,7 +54,7 @@ class hr_timesheet_invoice_create(osv.osv_memory):
data = context and context.get('active_ids', [])
for analytic in analytic_obj.browse(cr, uid, data, context=context):
if analytic.invoice_id:
raise osv.except_osv(_('Warning!'), _("Invoice is already linked to some of the analytic line(s)!"))
raise UserError(_("Invoice is already linked to some of the analytic line(s)!"))
def do_create(self, cr, uid, ids, context=None):
data = self.read(cr, uid, ids, context=context)[0]

Some files were not shown because too many files have changed in this diff Show More