From 0fd773a486fbc1aeef7f00ec5eab3eaf0e4c6a9d Mon Sep 17 00:00:00 2001 From: Goffin Simon Date: Thu, 18 Dec 2014 16:38:09 +0100 Subject: [PATCH] [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. --- addons/account/account.py | 81 ++++++++--------- addons/account/account_analytic_line.py | 5 +- addons/account/account_bank_statement.py | 30 +++--- addons/account/account_cash_statement.py | 7 +- addons/account/account_invoice.py | 41 ++++----- addons/account/account_move_line.py | 53 +++++------ addons/account/installer.py | 3 +- addons/account/product.py | 4 +- .../wizard/account_automatic_reconcile.py | 3 +- .../account/wizard/account_change_currency.py | 9 +- .../wizard/account_financial_report.py | 3 +- .../wizard/account_fiscalyear_close.py | 11 +-- .../wizard/account_fiscalyear_close_state.py | 3 +- .../account/wizard/account_invoice_refund.py | 8 +- .../account/wizard/account_invoice_state.py | 5 +- .../wizard/account_move_bank_reconcile.py | 4 +- .../wizard/account_open_closed_fiscalyear.py | 3 +- addons/account/wizard/account_period_close.py | 3 +- .../account_report_aged_partner_balance.py | 5 +- .../account/wizard/account_report_common.py | 3 +- addons/account/wizard/account_state_open.py | 3 +- addons/account/wizard/account_use_model.py | 3 +- .../wizard/account_validate_account_move.py | 5 +- addons/account/wizard/pos_box.py | 11 +-- .../account_analytic_analysis.py | 6 +- .../account_analytic_analysis/res_config.py | 4 +- .../account_analytic_plans.py | 9 +- .../wizard/account_crossovered_analytic.py | 3 +- .../wizard/analytic_plan_create_model.py | 5 +- addons/account_asset/account_asset.py | 3 +- .../account_bank_statement.py | 4 +- .../account_bank_statement_import.py | 16 ++-- .../account_bank_statement_import_ofx.py | 5 +- .../account_bank_statement_import_qif.py | 6 +- addons/account_budget/account_budget.py | 3 +- .../account_check_writing/account_voucher.py | 3 +- .../wizard/account_check_batch_printing.py | 3 +- addons/account_followup/account_followup.py | 5 +- .../report/account_followup_print.py | 3 +- addons/account_payment/account_invoice.py | 3 +- addons/account_payment/account_move_line.py | 3 +- addons/account_voucher/account_voucher.py | 15 ++- addons/analytic/models/analytic.py | 5 +- addons/analytic/security/ir.model.access.csv | 2 +- .../analytic_user_function.py | 8 +- addons/anonymization/anonymization.py | 13 +-- addons/auth_signup/res_users.py | 3 +- addons/base_gengo/ir_translation.py | 3 +- .../wizard/base_gengo_translations.py | 7 +- addons/base_geolocalize/models/res_partner.py | 4 +- addons/base_import_module/models/ir_module.py | 7 +- addons/base_vat/base_vat.py | 3 +- addons/calendar/calendar.py | 17 ++-- addons/crm/base_partner_merge.py | 12 +-- addons/crm/crm_lead.py | 26 +++--- addons/crm/crm_phonecall.py | 3 +- addons/crm/wizard/crm_lead_to_opportunity.py | 3 +- addons/crm_helpdesk/crm_helpdesk.py | 3 +- addons/crm_partner_assign/crm_lead.py | 3 +- .../wizard/crm_channel_interested.py | 3 +- .../wizard/crm_forward_to_partner.py | 13 +-- addons/delivery/delivery.py | 7 +- addons/delivery/sale.py | 5 +- addons/delivery/stock.py | 6 +- addons/document/content_index.py | 25 +++-- addons/document/document.py | 30 +++--- addons/document/test/document_test2.yml | 2 +- addons/edi/models/edi.py | 6 +- addons/edi/models/res_partner.py | 8 +- addons/event/event.py | 12 +-- addons/event/tests/test_event_flow.py | 4 +- addons/event_sale/models/event.py | 6 +- addons/event_sale/test/confirm.yml | 2 +- addons/fetchmail/fetchmail.py | 13 +-- addons/fleet/fleet.py | 4 +- addons/gamification/models/badge.py | 9 +- addons/gamification/models/challenge.py | 5 +- addons/gamification/models/goal.py | 5 +- addons/gamification/wizard/grant_badge.py | 3 +- addons/google_calendar/google_calendar.py | 6 +- addons/google_drive/google_drive.py | 13 +-- addons/hr_attendance/hr_attendance.py | 3 +- .../hr_attendance/test/attendance_process.yml | 20 ++-- .../wizard/hr_attendance_error.py | 3 +- addons/hr_evaluation/hr_evaluation.py | 5 +- addons/hr_expense/hr_expense.py | 13 +-- addons/hr_gamification/wizard/grant_badge.py | 5 +- addons/hr_holidays/hr_holidays.py | 18 ++-- .../hr_holidays/tests/test_holidays_flow.py | 10 +- .../wizard/hr_holidays_summary_department.py | 3 +- addons/hr_payroll/hr_payroll.py | 13 +-- .../hr_payroll_payslips_by_employees.py | 3 +- .../hr_payroll_account/hr_payroll_account.py | 5 +- addons/hr_recruitment/hr_recruitment.py | 3 +- .../hr_recruitment_create_partner_job.py | 6 +- addons/hr_timesheet/hr_timesheet.py | 7 +- .../wizard/hr_timesheet_sign_in_out.py | 5 +- .../hr_timesheet_invoice.py | 9 +- .../wizard/hr_timesheet_analytic_profit.py | 3 +- .../wizard/hr_timesheet_invoice_create.py | 3 +- .../hr_timesheet_sheet/hr_timesheet_sheet.py | 37 ++++---- .../wizard/hr_timesheet_current.py | 3 +- addons/hw_scale/controllers/main.py | 2 +- addons/hw_scanner/controllers/main.py | 2 +- addons/im_chat/im_chat.py | 5 +- .../wizard/l10n_be_account_vat_declaration.py | 7 +- .../wizard/l10n_be_partner_vat_listing.py | 17 ++-- addons/l10n_be/wizard/l10n_be_vat_intra.py | 15 +-- .../wizard/account_coda_import.py | 19 ++-- addons/l10n_be_invoice_bba/invoice.py | 36 +++----- .../l10n_in_hr_payroll/l10n_in_hr_payroll.py | 9 +- addons/mail/mail_group.py | 3 +- addons/mail/mail_mail.py | 2 +- addons/mail/mail_message.py | 9 +- addons/mail/mail_template.py | 10 +- addons/mail/mail_thread.py | 9 +- addons/mail/tests/test_mail_group.py | 7 +- addons/mail/tests/test_mail_message.py | 15 ++- addons/mail/update.py | 5 +- .../marketing_campaign/marketing_campaign.py | 11 ++- addons/mass_mailing/models/mass_mailing.py | 5 +- addons/membership/membership.py | 7 +- addons/mrp/mrp.py | 18 ++-- addons/mrp/stock.py | 11 ++- addons/mrp/wizard/change_production_qty.py | 5 +- addons/mrp_operations/mrp_operations.py | 19 ++-- addons/mrp_repair/mrp_repair.py | 15 +-- addons/mrp_repair/wizard/cancel_repair.py | 3 +- addons/pad/pad.py | 4 +- addons/payment_adyen/models/adyen.py | 17 ++-- addons/payment_adyen/tests/test_adyen.py | 1 - addons/payment_buckaroo/models/buckaroo.py | 17 ++-- addons/payment_ogone/models/ogone.py | 21 +++-- addons/payment_paypal/models/paypal.py | 7 +- .../models/payment_acquirer.py | 8 +- addons/point_of_sale/point_of_sale.py | 49 +++++----- addons/point_of_sale/report/pos_invoice.py | 3 +- addons/point_of_sale/wizard/pos_box.py | 4 +- .../wizard/pos_open_statement.py | 3 +- addons/portal/mail_message.py | 6 +- addons/portal/tests/test_portal.py | 9 +- addons/portal/wizard/portal_wizard.py | 6 +- .../tests/test_access_rights.py | 19 ++-- addons/procurement/procurement.py | 4 +- addons/product/pricelist.py | 4 +- addons/product/product.py | 13 ++- .../product_extended/wizard/wizard_price.py | 4 +- addons/project/project.py | 10 +- addons/project_issue/project_issue.py | 7 +- addons/project_timesheet/project_timesheet.py | 17 ++-- addons/purchase/purchase.py | 35 +++---- addons/purchase/stock.py | 3 +- .../purchase/wizard/purchase_order_group.py | 4 +- .../purchase_requisition.py | 9 +- .../wizard/purchase_requisition_partner.py | 3 +- addons/report/controllers/main.py | 1 - addons/report/models/report.py | 13 +-- addons/report_webkit/webkit_report.py | 44 ++++----- addons/resource/resource.py | 3 +- addons/sale/sale.py | 27 +++--- addons/sale/wizard/sale_line_invoice.py | 3 +- addons/sale/wizard/sale_make_invoice.py | 5 +- .../sale/wizard/sale_make_invoice_advance.py | 8 +- addons/sale_crm/wizard/crm_make_sale.py | 3 +- addons/sale_stock/sale_stock.py | 5 +- addons/share/wizard/share_wizard.py | 17 ++-- addons/stock/product.py | 3 +- addons/stock/stock.py | 43 +++++---- .../stock/wizard/make_procurement_product.py | 3 +- .../stock/wizard/stock_change_product_qty.py | 9 +- addons/stock/wizard/stock_return_picking.py | 9 +- addons/stock_account/product.py | 5 +- .../wizard/stock_invoice_onshipping.py | 5 +- .../stock_landed_costs/stock_landed_costs.py | 7 +- .../stock_picking_wave/stock_picking_wave.py | 5 +- addons/subscription/subscription.py | 5 +- addons/survey/survey.py | 12 +-- .../wizard/survey_email_compose_message.py | 7 +- addons/web/controllers/main.py | 3 +- addons/web/static/src/js/chrome.js | 55 +++++++++-- addons/web/static/src/xml/base.xml | 2 +- addons/website_blog/controllers/main.py | 4 +- .../website_event_sale/models/sale_order.py | 3 +- addons/website_forum/models/forum.py | 8 +- addons/website_forum/tests/test_forum.py | 6 +- addons/website_mail/models/mail_message.py | 5 +- .../tests/test_access_rights.py | 1 - .../website_twitter/models/twitter_config.py | 14 +-- openerp/addons/base/ir/ir_actions.py | 5 +- openerp/addons/base/ir/ir_attachment.py | 12 +-- openerp/addons/base/ir/ir_cron.py | 7 +- openerp/addons/base/ir/ir_http.py | 2 +- openerp/addons/base/ir/ir_mail_server.py | 20 ++-- openerp/addons/base/ir/ir_model.py | 57 ++++++------ openerp/addons/base/ir/ir_sequence.py | 4 +- openerp/addons/base/ir/ir_translation.py | 3 +- openerp/addons/base/ir/ir_ui_view.py | 2 +- openerp/addons/base/ir/ir_values.py | 8 +- openerp/addons/base/module/module.py | 18 ++-- .../base/module/wizard/base_module_upgrade.py | 4 +- .../module/wizard/base_update_translations.py | 3 +- openerp/addons/base/res/ir_property.py | 3 +- openerp/addons/base/res/res_bank.py | 3 +- openerp/addons/base/res/res_config.py | 5 +- openerp/addons/base/res/res_currency.py | 5 +- openerp/addons/base/res/res_lang.py | 7 +- openerp/addons/base/res/res_partner.py | 5 +- openerp/addons/base/res/res_users.py | 12 +-- openerp/addons/base/tests/test_acl.py | 11 ++- openerp/addons/base/tests/test_api.py | 26 +++--- openerp/addons/base/tests/test_base.py | 10 +- openerp/addons/base/tests/test_ir_actions.py | 4 +- openerp/addons/base/workflow/workflow.py | 7 +- openerp/addons/test_exceptions/models.py | 24 ++++- openerp/addons/test_exceptions/view.xml | 26 ++++++ .../test_new_api/tests/test_new_fields.py | 6 +- openerp/api.py | 4 +- openerp/exceptions.py | 47 ++++++++-- openerp/fields.py | 2 +- openerp/http.py | 21 ++++- openerp/models.py | 91 ++++++++----------- openerp/modules/loading.py | 3 +- openerp/report/custom.py | 4 +- openerp/report/render/rml2pdf/trml2pdf.py | 18 ++-- openerp/report/render/rml2pdf/utils.py | 10 +- openerp/report/report_sxw.py | 5 +- openerp/service/db.py | 8 +- openerp/service/model.py | 18 ++-- openerp/service/report.py | 3 +- openerp/service/wsgi_server.py | 15 ++- openerp/sql_db.py | 18 ++-- openerp/tools/convert.py | 6 +- openerp/tools/misc.py | 4 +- openerp/tools/safe_eval.py | 4 +- openerp/tools/test_reports.py | 2 +- openerp/tools/translate.py | 2 +- 236 files changed, 1264 insertions(+), 1107 deletions(-) diff --git a/addons/account/account.py b/addons/account/account.py index 2e71bf6e6e0..75978ffd654 100644 --- a/addons/account/account.py +++ b/addons/account/account.py @@ -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: diff --git a/addons/account/account_analytic_line.py b/addons/account/account_analytic_line.py index 9d018828e57..81d10e66f4a 100644 --- a/addons/account/account_analytic_line.py +++ b/addons/account/account_analytic_line.py @@ -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,)) diff --git a/addons/account/account_bank_statement.py b/addons/account/account_bank_statement.py index abd1a784206..c93e27db3ce 100644 --- a/addons/account/account_bank_statement.py +++ b/addons/account/account_bank_statement.py @@ -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)] diff --git a/addons/account/account_cash_statement.py b/addons/account/account_cash_statement.py index 3a1be9736d0..78101f1b6d2 100644 --- a/addons/account/account_cash_statement.py +++ b/addons/account/account_cash_statement.py @@ -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, diff --git a/addons/account/account_invoice.py b/addons/account/account_invoice.py index dc8c0fd9d8b..9dda9d0b772 100644 --- a/addons/account/account_invoice.py +++ b/addons/account/account_invoice.py @@ -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': []}} diff --git a/addons/account/account_move_line.py b/addons/account/account_move_line.py index f1f3f09d308..20e8a0e9036 100644 --- a/addons/account/account_move_line.py +++ b/addons/account/account_move_line.py @@ -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 diff --git a/addons/account/installer.py b/addons/account/installer.py index b6ac7af4dac..0ebbd1a1cf4 100644 --- a/addons/account/installer.py +++ b/addons/account/installer.py @@ -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 = {} diff --git a/addons/account/product.py b/addons/account/product.py index e0cf19017f8..a8730581b6b 100644 --- a/addons/account/product.py +++ b/addons/account/product.py @@ -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) diff --git a/addons/account/wizard/account_automatic_reconcile.py b/addons/account/wizard/account_automatic_reconcile.py index f30991fc91b..a9a6d8f8790 100644 --- a/addons/account/wizard/account_automatic_reconcile.py +++ b/addons/account/wizard/account_automatic_reconcile.py @@ -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: diff --git a/addons/account/wizard/account_change_currency.py b/addons/account/wizard/account_change_currency.py index 33e6848aaaf..a5491dd0c94 100644 --- a/addons/account/wizard/account_change_currency.py +++ b/addons/account/wizard/account_change_currency.py @@ -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) diff --git a/addons/account/wizard/account_financial_report.py b/addons/account/wizard/account_financial_report.py index 5f07308b8cc..6f062967167 100644 --- a/addons/account/wizard/account_financial_report.py +++ b/addons/account/wizard/account_financial_report.py @@ -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 diff --git a/addons/account/wizard/account_fiscalyear_close.py b/addons/account/wizard/account_fiscalyear_close.py index 3c60b2c2036..9483af205ed 100644 --- a/addons/account/wizard/account_fiscalyear_close.py +++ b/addons/account/wizard/account_fiscalyear_close.py @@ -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, [ diff --git a/addons/account/wizard/account_fiscalyear_close_state.py b/addons/account/wizard/account_fiscalyear_close_state.py index 276abc6d282..064eadd3538 100644 --- a/addons/account/wizard/account_fiscalyear_close_state.py +++ b/addons/account/wizard/account_fiscalyear_close_state.py @@ -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 ' \ diff --git a/addons/account/wizard/account_invoice_refund.py b/addons/account/wizard/account_invoice_refund.py index ebd825e8ebf..f050e13e104 100644 --- a/addons/account/wizard/account_invoice_refund.py +++ b/addons/account/wizard/account_invoice_refund.py @@ -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) diff --git a/addons/account/wizard/account_invoice_state.py b/addons/account/wizard/account_invoice_state.py index db11a39df5b..63c2efa9018 100644 --- a/addons/account/wizard/account_invoice_state.py +++ b/addons/account/wizard/account_invoice_state.py @@ -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'} diff --git a/addons/account/wizard/account_move_bank_reconcile.py b/addons/account/wizard/account_move_bank_reconcile.py index c66e2e91627..46b74673618 100644 --- a/addons/account/wizard/account_move_bank_reconcile.py +++ b/addons/account/wizard/account_move_bank_reconcile.py @@ -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'), diff --git a/addons/account/wizard/account_open_closed_fiscalyear.py b/addons/account/wizard/account_open_closed_fiscalyear.py index 8dd00b6a505..c2eb8b42181 100644 --- a/addons/account/wizard/account_open_closed_fiscalyear.py +++ b/addons/account/wizard/account_open_closed_fiscalyear.py @@ -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: diff --git a/addons/account/wizard/account_period_close.py b/addons/account/wizard/account_period_close.py index 7a86b149db6..17a05765cc2 100644 --- a/addons/account/wizard/account_period_close.py +++ b/addons/account/wizard/account_period_close.py @@ -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)) diff --git a/addons/account/wizard/account_report_aged_partner_balance.py b/addons/account/wizard/account_report_aged_partner_balance.py index 7e132e8f2f6..9f566387856 100644 --- a/addons/account/wizard/account_report_aged_partner_balance.py +++ b/addons/account/wizard/account_report_aged_partner_balance.py @@ -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") diff --git a/addons/account/wizard/account_report_common.py b/addons/account/wizard/account_report_common.py index ae47c3ec38d..982d16009ab 100644 --- a/addons/account/wizard/account_report_common.py +++ b/addons/account/wizard/account_report_common.py @@ -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 diff --git a/addons/account/wizard/account_state_open.py b/addons/account/wizard/account_state_open.py index c484ae585cc..27abcf41b7f 100644 --- a/addons/account/wizard/account_state_open.py +++ b/addons/account/wizard/account_state_open.py @@ -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'} diff --git a/addons/account/wizard/account_use_model.py b/addons/account/wizard/account_use_model.py index 57ce6c9b9e1..fdcc8304945 100644 --- a/addons/account/wizard/account_use_model.py +++ b/addons/account/wizard/account_use_model.py @@ -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 diff --git a/addons/account/wizard/account_validate_account_move.py b/addons/account/wizard/account_validate_account_move.py index c5dc23cb505..748846e4301 100644 --- a/addons/account/wizard/account_validate_account_move.py +++ b/addons/account/wizard/account_validate_account_move.py @@ -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'} diff --git a/addons/account/wizard/pos_box.py b/addons/account/wizard/pos_box.py index 5edfa9d0e7b..ce68d3ec586 100644 --- a/addons/account/wizard/pos_box.py +++ b/addons/account/wizard/pos_box.py @@ -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, diff --git a/addons/account_analytic_analysis/account_analytic_analysis.py b/addons/account_analytic_analysis/account_analytic_analysis.py index 31fc4970d05..49e1245c408 100644 --- a/addons/account_analytic_analysis/account_analytic_analysis.py +++ b/addons/account_analytic_analysis/account_analytic_analysis.py @@ -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 diff --git a/addons/account_analytic_analysis/res_config.py b/addons/account_analytic_analysis/res_config.py index a6f02b04582..c67dd3e2af6 100644 --- a/addons/account_analytic_analysis/res_config.py +++ b/addons/account_analytic_analysis/res_config.py @@ -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) diff --git a/addons/account_analytic_plans/account_analytic_plans.py b/addons/account_analytic_plans/account_analytic_plans.py index 2d2f117dc86..2ddfdebeff2 100644 --- a/addons/account_analytic_plans/account_analytic_plans.py +++ b/addons/account_analytic_plans/account_analytic_plans.py @@ -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 diff --git a/addons/account_analytic_plans/wizard/account_crossovered_analytic.py b/addons/account_analytic_plans/wizard/account_crossovered_analytic.py index 8781c4e6d2e..dda643a50cc 100644 --- a/addons/account_analytic_plans/wizard/account_crossovered_analytic.py +++ b/addons/account_analytic_plans/wizard/account_crossovered_analytic.py @@ -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': [], diff --git a/addons/account_analytic_plans/wizard/analytic_plan_create_model.py b/addons/account_analytic_plans/wizard/analytic_plan_create_model.py index 2a95dab0b01..2911dc56b01 100644 --- a/addons/account_analytic_plans/wizard/analytic_plan_create_model.py +++ b/addons/account_analytic_plans/wizard/analytic_plan_create_model.py @@ -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) diff --git a/addons/account_asset/account_asset.py b/addons/account_asset/account_asset.py index c99ed9617bd..e3f69d79e26 100644 --- a/addons/account_asset/account_asset.py +++ b/addons/account_asset/account_asset.py @@ -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): diff --git a/addons/account_bank_statement_extensions/account_bank_statement.py b/addons/account_bank_statement_extensions/account_bank_statement.py index 460524e52f9..069dff25a1f 100644 --- a/addons/account_bank_statement_extensions/account_bank_statement.py +++ b/addons/account_bank_statement_extensions/account_bank_statement.py @@ -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) diff --git a/addons/account_bank_statement_import/account_bank_statement_import.py b/addons/account_bank_statement_import/account_bank_statement_import.py index f3e281ac7aa..a175f5d0e96 100644 --- a/addons/account_bank_statement_import/account_bank_statement_import.py +++ b/addons/account_bank_statement_import/account_bank_statement_import.py @@ -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 + diff --git a/addons/account_bank_statement_import_ofx/account_bank_statement_import_ofx.py b/addons/account_bank_statement_import_ofx/account_bank_statement_import_ofx.py index 6141c08be2e..7f197d9ea7a 100644 --- a/addons/account_bank_statement_import_ofx/account_bank_statement_import_ofx.py +++ b/addons/account_bank_statement_import_ofx/account_bank_statement_import_ofx.py @@ -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, diff --git a/addons/account_bank_statement_import_qif/account_bank_statement_import_qif.py b/addons/account_bank_statement_import_qif/account_bank_statement_import_qif.py index 3ec93241c2c..95c2eb28e1a 100644 --- a/addons/account_bank_statement_import_qif/account_bank_statement_import_qif.py +++ b/addons/account_bank_statement_import_qif/account_bank_statement_import_qif.py @@ -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] + diff --git a/addons/account_budget/account_budget.py b/addons/account_budget/account_budget.py index 4cd02eae9ea..9b436378c2a 100644 --- a/addons/account_budget/account_budget.py +++ b/addons/account_budget/account_budget.py @@ -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: diff --git a/addons/account_check_writing/account_voucher.py b/addons/account_check_writing/account_voucher.py index 51bdf7883d7..135fcbbc4f7 100644 --- a/addons/account_check_writing/account_voucher.py +++ b/addons/account_check_writing/account_voucher.py @@ -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], diff --git a/addons/account_check_writing/wizard/account_check_batch_printing.py b/addons/account_check_writing/wizard/account_check_batch_printing.py index aab8ca277f2..21e5704da44 100644 --- a/addons/account_check_writing/wizard/account_check_batch_printing.py +++ b/addons/account_check_writing/wizard/account_check_batch_printing.py @@ -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 diff --git a/addons/account_followup/account_followup.py b/addons/account_followup/account_followup.py index 23727a1cbb4..c7e397a19f2 100644 --- a/addons/account_followup/account_followup.py +++ b/addons/account_followup/account_followup.py @@ -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], diff --git a/addons/account_followup/report/account_followup_print.py b/addons/account_followup/report/account_followup_print.py index 4946db01585..1fba7cc5280 100644 --- a/addons/account_followup/report/account_followup_print.py +++ b/addons/account_followup/report/account_followup_print.py @@ -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 = [] diff --git a/addons/account_payment/account_invoice.py b/addons/account_payment/account_invoice.py index ae12f4abfb8..18da13e50e8 100644 --- a/addons/account_payment/account_invoice.py +++ b/addons/account_payment/account_invoice.py @@ -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) diff --git a/addons/account_payment/account_move_line.py b/addons/account_payment/account_move_line.py index 287e20a8a7c..b955356d291 100644 --- a/addons/account_payment/account_move_line.py +++ b/addons/account_payment/account_move_line.py @@ -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 diff --git a/addons/account_voucher/account_voucher.py b/addons/account_voucher/account_voucher.py index b7ff709d1c8..d01b20ab5a7 100644 --- a/addons/account_voucher/account_voucher.py +++ b/addons/account_voucher/account_voucher.py @@ -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 diff --git a/addons/analytic/models/analytic.py b/addons/analytic/models/analytic.py index 6d7423d1adf..227683f8bd0 100644 --- a/addons/analytic/models/analytic.py +++ b/addons/analytic/models/analytic.py @@ -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: diff --git a/addons/analytic/security/ir.model.access.csv b/addons/analytic/security/ir.model.access.csv index 4a08a4aa60d..58262d4440d 100644 --- a/addons/analytic/security/ir.model.access.csv +++ b/addons/analytic/security/ir.model.access.csv @@ -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 \ No newline at end of file diff --git a/addons/analytic_user_function/analytic_user_function.py b/addons/analytic_user_function/analytic_user_function.py index 4337e7a72e2..855ee4ced47 100644 --- a/addons/analytic_user_function/analytic_user_function.py +++ b/addons/analytic_user_function/analytic_user_function.py @@ -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,)) diff --git a/addons/anonymization/anonymization.py b/addons/anonymization/anonymization.py index 9c7a72576ab..1134a849f6f 100644 --- a/addons/anonymization/anonymization.py +++ b/addons/anonymization/anonymization.py @@ -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: diff --git a/addons/auth_signup/res_users.py b/addons/auth_signup/res_users.py index 9447cf1031e..00c27e38c58 100644 --- a/addons/auth_signup/res_users.py +++ b/addons/auth_signup/res_users.py @@ -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): diff --git a/addons/base_gengo/ir_translation.py b/addons/base_gengo/ir_translation.py index 142180a3627..4c3142a12e1 100644 --- a/addons/base_gengo/ir_translation.py +++ b/addons/base_gengo/ir_translation.py @@ -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': diff --git a/addons/base_gengo/wizard/base_gengo_translations.py b/addons/base_gengo/wizard/base_gengo_translations.py index 7bc38f5e082..21b4f579191 100644 --- a/addons/base_gengo/wizard/base_gengo_translations.py +++ b/addons/base_gengo/wizard/base_gengo_translations.py @@ -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']: diff --git a/addons/base_geolocalize/models/res_partner.py b/addons/base_geolocalize/models/res_partner.py index 6e89b312f4b..b2727e1fa5e 100644 --- a/addons/base_geolocalize/models/res_partner.py +++ b/addons/base_geolocalize/models/res_partner.py @@ -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 diff --git a/addons/base_import_module/models/ir_module.py b/addons/base_import_module/models/ir_module.py index 02965ef6074..3e35de2b0a1 100644 --- a/addons/base_import_module/models/ir_module.py +++ b/addons/base_import_module/models/ir_module.py @@ -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) diff --git a/addons/base_vat/base_vat.py b/addons/base_vat/base_vat.py index 02007e6cfbf..27e7607effa 100644 --- a/addons/base_vat/base_vat.py +++ b/addons/base_vat/base_vat.py @@ -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): diff --git a/addons/calendar/calendar.py b/addons/calendar/calendar.py index 56a6870172b..e7c784d3865 100644 --- a/addons/calendar/calendar.py +++ b/addons/calendar/calendar.py @@ -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) diff --git a/addons/crm/base_partner_merge.py b/addons/crm/base_partner_merge.py index f76c77553e9..321c5caa517 100644 --- a/addons/crm/base_partner_merge.py +++ b/addons/crm/base_partner_merge.py @@ -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 diff --git a/addons/crm/crm_lead.py b/addons/crm/crm_lead.py index a63fc616c8d..b702daf7b6f 100644 --- a/addons/crm/crm_lead.py +++ b/addons/crm/crm_lead.py @@ -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 ")') - ) + raise UserError(_('No customer name defined. Please fill one of the following fields: Company Name, Contact Name or Email ("Name ")')) 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 diff --git a/addons/crm/crm_phonecall.py b/addons/crm/crm_phonecall.py index fe82458f431..63ac29b183b 100644 --- a/addons/crm/crm_phonecall.py +++ b/addons/crm/crm_phonecall.py @@ -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) diff --git a/addons/crm/wizard/crm_lead_to_opportunity.py b/addons/crm/wizard/crm_lead_to_opportunity.py index ee222a684eb..49e65151612 100644 --- a/addons/crm/wizard/crm_lead_to_opportunity.py +++ b/addons/crm/wizard/crm_lead_to_opportunity.py @@ -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): diff --git a/addons/crm_helpdesk/crm_helpdesk.py b/addons/crm_helpdesk/crm_helpdesk.py index 48af1eaec0a..c622d45da3a 100644 --- a/addons/crm_helpdesk/crm_helpdesk.py +++ b/addons/crm_helpdesk/crm_helpdesk.py @@ -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 diff --git a/addons/crm_partner_assign/crm_lead.py b/addons/crm_partner_assign/crm_lead.py index dc7c25347af..c37cfdfd72f 100644 --- a/addons/crm_partner_assign/crm_lead.py +++ b/addons/crm_partner_assign/crm_lead.py @@ -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 diff --git a/addons/crm_partner_assign/wizard/crm_channel_interested.py b/addons/crm_partner_assign/wizard/crm_channel_interested.py index a23de29d766..d3693cd32b9 100644 --- a/addons/crm_partner_assign/wizard/crm_channel_interested.py +++ b/addons/crm_partner_assign/wizard/crm_channel_interested.py @@ -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: diff --git a/addons/crm_partner_assign/wizard/crm_forward_to_partner.py b/addons/crm_partner_assign/wizard/crm_forward_to_partner.py index e3c29a99dbb..f0e89d61e64 100644 --- a/addons/crm_partner_assign/wizard/crm_forward_to_partner.py +++ b/addons/crm_partner_assign/wizard/crm_forward_to_partner.py @@ -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: diff --git a/addons/delivery/delivery.py b/addons/delivery/delivery.py index c1740b886ed..84f092f1454 100644 --- a/addons/delivery/delivery.py +++ b/addons/delivery/delivery.py @@ -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 diff --git a/addons/delivery/sale.py b/addons/delivery/sale.py index 43fb7902943..b5645072db1 100644 --- a/addons/delivery/sale.py +++ b/addons/delivery/sale.py @@ -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) diff --git a/addons/delivery/stock.py b/addons/delivery/stock.py index 5675c2eb483..2ccb1c41915 100644 --- a/addons/delivery/stock.py +++ b/addons/delivery/stock.py @@ -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, diff --git a/addons/document/content_index.py b/addons/document/content_index.py index b6f89604c3e..8c2c9209ced 100644 --- a/addons/document/content_index.py +++ b/addons/document/content_index.py @@ -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 "" %(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 diff --git a/addons/document/document.py b/addons/document/document.py index 86eea66cab2..0d08d54e7fb 100644 --- a/addons/document/document.py +++ b/addons/document/document.py @@ -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 diff --git a/addons/document/test/document_test2.yml b/addons/document/test/document_test2.yml index 0c6345ef6c4..1eed98aa901 100644 --- a/addons/document/test/document_test2.yml +++ b/addons/document/test/document_test2.yml @@ -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 diff --git a/addons/edi/models/edi.py b/addons/edi/models/edi.py index 06ad6c41b9a..4809051dafc 100644 --- a/addons/edi/models/edi.py +++ b/addons/edi/models/edi.py @@ -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 - '\ diff --git a/addons/edi/models/res_partner.py b/addons/edi/models/res_partner.py index 6b7b302e391..ac09a569491 100644 --- a/addons/edi/models/res_partner.py +++ b/addons/edi/models/res_partner.py @@ -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 diff --git a/addons/event/event.py b/addons/event/event.py index 3e95cab2f60..639d4533960 100644 --- a/addons/event/event.py +++ b/addons/event/event.py @@ -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): diff --git a/addons/event/tests/test_event_flow.py b/addons/event/tests/test_event_flow.py index f94567ba50a..ccddd11e00b 100644 --- a/addons/event/tests/test_event_flow.py +++ b/addons/event/tests/test_event_flow.py @@ -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() diff --git a/addons/event_sale/models/event.py b/addons/event_sale/models/event.py index ca214bdfce4..9f710fa0f07 100644 --- a/addons/event_sale/models/event.py +++ b/addons/event_sale/models/event.py @@ -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): diff --git a/addons/event_sale/test/confirm.yml b/addons/event_sale/test/confirm.yml index 1f5afbcfc8c..5c300a09127 100644 --- a/addons/event_sale/test/confirm.yml +++ b/addons/event_sale/test/confirm.yml @@ -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.")) diff --git a/addons/fetchmail/fetchmail.py b/addons/fetchmail/fetchmail.py index 38e7a1b9e4b..9f57e0fe616 100644 --- a/addons/fetchmail/fetchmail.py +++ b/addons/fetchmail/fetchmail.py @@ -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() diff --git a/addons/fleet/fleet.py b/addons/fleet/fleet.py index ae2da5ea509..5367ea1f003 100644 --- a/addons/fleet/fleet.py +++ b/addons/fleet/fleet.py @@ -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) diff --git a/addons/gamification/models/badge.py b/addons/gamification/models/badge.py index c078943ee0e..c21595a5d0d 100644 --- a/addons/gamification/models/badge.py +++ b/addons/gamification/models/badge.py @@ -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 diff --git a/addons/gamification/models/challenge.py b/addons/gamification/models/challenge.py index a804d816a05..22f054eb7a9 100644 --- a/addons/gamification/models/challenge.py +++ b/addons/gamification/models/challenge.py @@ -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 diff --git a/addons/gamification/models/goal.py b/addons/gamification/models/goal.py index 415befbc8e8..48adf095ac5 100644 --- a/addons/gamification/models/goal.py +++ b/addons/gamification/models/goal.py @@ -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: diff --git a/addons/gamification/wizard/grant_badge.py b/addons/gamification/wizard/grant_badge.py index 513a1526c8b..b826bc4e563 100644 --- a/addons/gamification/wizard/grant_badge.py +++ b/addons/gamification/wizard/grant_badge.py @@ -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 = { diff --git a/addons/google_calendar/google_calendar.py b/addons/google_calendar/google_calendar.py index bc93c584764..1482d71b2c7 100644 --- a/addons/google_calendar/google_calendar.py +++ b/addons/google_calendar/google_calendar.py @@ -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 diff --git a/addons/google_drive/google_drive.py b/addons/google_drive/google_drive.py index 1a95a5ec1ee..019ea745ce6 100644 --- a/addons/google_drive/google_drive.py +++ b/addons/google_drive/google_drive.py @@ -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): diff --git a/addons/hr_attendance/hr_attendance.py b/addons/hr_attendance/hr_attendance.py index 012d3257b6b..35a850fb410 100644 --- a/addons/hr_attendance/hr_attendance.py +++ b/addons/hr_attendance/hr_attendance.py @@ -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: diff --git a/addons/hr_attendance/test/attendance_process.yml b/addons/hr_attendance/test/attendance_process.yml index e8e97d57ee9..2ecd2df3531 100644 --- a/addons/hr_attendance/test/attendance_process.yml +++ b/addons/hr_attendance/test/attendance_process.yml @@ -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 diff --git a/addons/hr_attendance/wizard/hr_attendance_error.py b/addons/hr_attendance/wizard/hr_attendance_error.py index 0a0a0d3d79a..4660d9abe03 100644 --- a/addons/hr_attendance/wizard/hr_attendance_error.py +++ b/addons/hr_attendance/wizard/hr_attendance_error.py @@ -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: diff --git a/addons/hr_evaluation/hr_evaluation.py b/addons/hr_evaluation/hr_evaluation.py index 41687bcd04e..1a945650666 100644 --- a/addons/hr_evaluation/hr_evaluation.py +++ b/addons/hr_evaluation/hr_evaluation.py @@ -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": diff --git a/addons/hr_expense/hr_expense.py b/addons/hr_expense/hr_expense.py index 0f2ad19fc06..09c6d4bee84 100644 --- a/addons/hr_expense/hr_expense.py +++ b/addons/hr_expense/hr_expense.py @@ -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], diff --git a/addons/hr_gamification/wizard/grant_badge.py b/addons/hr_gamification/wizard/grant_badge.py index b8a51044d4c..e5497c89dff 100644 --- a/addons/hr_gamification/wizard/grant_badge.py +++ b/addons/hr_gamification/wizard/grant_badge.py @@ -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, diff --git a/addons/hr_holidays/hr_holidays.py b/addons/hr_holidays/hr_holidays.py index 287f2d8eeef..b8ec3793d71 100644 --- a/addons/hr_holidays/hr_holidays.py +++ b/addons/hr_holidays/hr_holidays.py @@ -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'): diff --git a/addons/hr_holidays/tests/test_holidays_flow.py b/addons/hr_holidays/tests/test_holidays_flow.py index 96ab20f6ae5..0fc56e6547b 100644 --- a/addons/hr_holidays/tests/test_holidays_flow.py +++ b/addons/hr_holidays/tests/test_holidays_flow.py @@ -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') diff --git a/addons/hr_holidays/wizard/hr_holidays_summary_department.py b/addons/hr_holidays/wizard/hr_holidays_summary_department.py index bb40866a97e..5fb4745c941 100644 --- a/addons/hr_holidays/wizard/hr_holidays_summary_department.py +++ b/addons/hr_holidays/wizard/hr_holidays_summary_department.py @@ -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', diff --git a/addons/hr_payroll/hr_payroll.py b/addons/hr_payroll/hr_payroll.py index 0c019bc6530..aa052d40738 100644 --- a/addons/hr_payroll/hr_payroll.py +++ b/addons/hr_payroll/hr_payroll.py @@ -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): diff --git a/addons/hr_payroll/wizard/hr_payroll_payslips_by_employees.py b/addons/hr_payroll/wizard/hr_payroll_payslips_by_employees.py index 0b620954e45..394754eb1ba 100644 --- a/addons/hr_payroll/wizard/hr_payroll_payslips_by_employees.py +++ b/addons/hr_payroll/wizard/hr_payroll_payslips_by_employees.py @@ -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 = { diff --git a/addons/hr_payroll_account/hr_payroll_account.py b/addons/hr_payroll_account/hr_payroll_account.py index 623bc016b77..cb1fddb5539 100644 --- a/addons/hr_payroll_account/hr_payroll_account.py +++ b/addons/hr_payroll_account/hr_payroll_account.py @@ -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, diff --git a/addons/hr_recruitment/hr_recruitment.py b/addons/hr_recruitment/hr_recruitment.py index b818f49a67f..e4fb4c7b629 100644 --- a/addons/hr_recruitment/hr_recruitment.py +++ b/addons/hr_recruitment/hr_recruitment.py @@ -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] diff --git a/addons/hr_recruitment/wizard/hr_recruitment_create_partner_job.py b/addons/hr_recruitment/wizard/hr_recruitment_create_partner_job.py index 95d245ebcda..2f14ff2a62a 100644 --- a/addons/hr_recruitment/wizard/hr_recruitment_create_partner_job.py +++ b/addons/hr_recruitment/wizard/hr_recruitment_create_partner_job.py @@ -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, diff --git a/addons/hr_timesheet/hr_timesheet.py b/addons/hr_timesheet/hr_timesheet.py index cc0b2004be5..0319c94ceec 100644 --- a/addons/hr_timesheet/hr_timesheet.py +++ b/addons/hr_timesheet/hr_timesheet.py @@ -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): diff --git a/addons/hr_timesheet/wizard/hr_timesheet_sign_in_out.py b/addons/hr_timesheet/wizard/hr_timesheet_sign_in_out.py index 7e32e110ee9..44185da6685 100644 --- a/addons/hr_timesheet/wizard/hr_timesheet_sign_in_out.py +++ b/addons/hr_timesheet/wizard/hr_timesheet_sign_in_out.py @@ -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): diff --git a/addons/hr_timesheet_invoice/hr_timesheet_invoice.py b/addons/hr_timesheet_invoice/hr_timesheet_invoice.py index 91ed4e899dc..0276e49582d 100644 --- a/addons/hr_timesheet_invoice/hr_timesheet_invoice.py +++ b/addons/hr_timesheet_invoice/hr_timesheet_invoice.py @@ -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({ diff --git a/addons/hr_timesheet_invoice/wizard/hr_timesheet_analytic_profit.py b/addons/hr_timesheet_invoice/wizard/hr_timesheet_analytic_profit.py index 6b1f1047f02..712494461cb 100644 --- a/addons/hr_timesheet_invoice/wizard/hr_timesheet_analytic_profit.py +++ b/addons/hr_timesheet_invoice/wizard/hr_timesheet_analytic_profit.py @@ -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'])] diff --git a/addons/hr_timesheet_invoice/wizard/hr_timesheet_invoice_create.py b/addons/hr_timesheet_invoice/wizard/hr_timesheet_invoice_create.py index 2e34bc9b3b5..b71950b08aa 100644 --- a/addons/hr_timesheet_invoice/wizard/hr_timesheet_invoice_create.py +++ b/addons/hr_timesheet_invoice/wizard/hr_timesheet_invoice_create.py @@ -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] diff --git a/addons/hr_timesheet_sheet/hr_timesheet_sheet.py b/addons/hr_timesheet_sheet/hr_timesheet_sheet.py index 5f108e24249..a10cf4e84a3 100644 --- a/addons/hr_timesheet_sheet/hr_timesheet_sheet.py +++ b/addons/hr_timesheet_sheet/hr_timesheet_sheet.py @@ -28,6 +28,7 @@ import pytz from openerp.osv import fields, osv from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT from openerp.tools.translate import _ +from openerp.exceptions import UserError class hr_timesheet_sheet(osv.osv): _name = "hr_timesheet_sheet.sheet" @@ -66,20 +67,20 @@ class hr_timesheet_sheet(osv.osv): ids_signout = self.pool.get('hr.attendance').search(cr,uid,[('sheet_id', '=', sheet_id),('action','=','sign_out')]) if len(ids_signin) != len(ids_signout): - raise osv.except_osv(('Warning!'),_('The timesheet cannot be validated as it does not contain an equal number of sign ins and sign outs.')) + raise UserError(_('The timesheet cannot be validated as it does not contain an equal number of sign ins and sign outs.')) return True def copy(self, cr, uid, ids, *args, **argv): - raise osv.except_osv(_('Error!'), _('You cannot duplicate a timesheet.')) + raise UserError(_('You cannot duplicate a timesheet.')) def create(self, cr, uid, vals, context=None): if 'employee_id' in vals: if not self.pool.get('hr.employee').browse(cr, uid, vals['employee_id'], context=context).user_id: - raise osv.except_osv(_('Error!'), _('In order to create a timesheet for this employee, you must link him/her to a user.')) + raise UserError(_('In order to create a timesheet for this employee, you must link him/her to a user.')) if not self.pool.get('hr.employee').browse(cr, uid, vals['employee_id'], context=context).product_id: - raise osv.except_osv(_('Error!'), _('In order to create a timesheet for this employee, you must link the employee to a product, like \'Consultant\'.')) + raise UserError(_('In order to create a timesheet for this employee, you must link the employee to a product, like \'Consultant\'.')) if not self.pool.get('hr.employee').browse(cr, uid, vals['employee_id'], context=context).journal_id: - raise osv.except_osv(_('Configuration Error!'), _('In order to create a timesheet for this employee, you must assign an analytic journal to the employee, like \'Timesheet Journal\'.')) + raise UserError(_('In order to create a timesheet for this employee, you must assign an analytic journal to the employee, like \'Timesheet Journal\'.')) if vals.get('attendances_ids'): # If attendances, we sort them by date asc before writing them, to satisfy the alternance constraint vals['attendances_ids'] = self.sort_attendances(cr, uid, vals['attendances_ids'], context=context) @@ -89,13 +90,13 @@ class hr_timesheet_sheet(osv.osv): if 'employee_id' in vals: new_user_id = self.pool.get('hr.employee').browse(cr, uid, vals['employee_id'], context=context).user_id.id or False if not new_user_id: - raise osv.except_osv(_('Error!'), _('In order to create a timesheet for this employee, you must link him/her to a user.')) + raise UserError(_('In order to create a timesheet for this employee, you must link him/her to a user.')) if not self._sheet_date(cr, uid, ids, forced_user_id=new_user_id, context=context): - raise osv.except_osv(_('Error!'), _('You cannot have 2 timesheets that overlap!\nYou should use the menu \'My Timesheet\' to avoid this problem.')) + raise UserError(_('You cannot have 2 timesheets that overlap!\nYou should use the menu \'My Timesheet\' to avoid this problem.')) if not self.pool.get('hr.employee').browse(cr, uid, vals['employee_id'], context=context).product_id: - raise osv.except_osv(_('Error!'), _('In order to create a timesheet for this employee, you must link the employee to a product.')) + raise UserError(_('In order to create a timesheet for this employee, you must link the employee to a product.')) if not self.pool.get('hr.employee').browse(cr, uid, vals['employee_id'], context=context).journal_id: - raise osv.except_osv(_('Configuration Error!'), _('In order to create a timesheet for this employee, you must assign an analytic journal to the employee, like \'Timesheet Journal\'.')) + raise UserError(_('In order to create a timesheet for this employee, you must assign an analytic journal to the employee, like \'Timesheet Journal\'.')) if vals.get('attendances_ids'): # If attendances, we sort them by date asc before writing them, to satisfy the alternance constraint # In addition to the date order, deleting attendances are done before inserting attendances @@ -104,7 +105,7 @@ class hr_timesheet_sheet(osv.osv): if vals.get('attendances_ids'): for timesheet in self.browse(cr, uid, ids): if not self.pool['hr.attendance']._altern_si_so(cr, uid, [att.id for att in timesheet.attendances_ids]): - raise osv.except_osv(_('Warning !'), _('Error ! Sign in (resp. Sign out) must follow Sign out (resp. Sign in)')) + raise UserError(_('Error ! Sign in (resp. Sign out) must follow Sign out (resp. Sign in)')) return res def sort_attendances(self, cr, uid, attendance_tuples, context=None): @@ -135,7 +136,7 @@ class hr_timesheet_sheet(osv.osv): if (abs(sheet.total_difference) < di) or not di: sheet.signal_workflow('confirm') else: - raise osv.except_osv(_('Warning!'), _('Please verify that the total difference of the sheet is lower than %.2f.') %(di,)) + raise UserError(_('Please verify that the total difference of the sheet is lower than %.2f.') %(di,)) return True def attendance_action_change(self, cr, uid, ids, context=None): @@ -261,9 +262,9 @@ class hr_timesheet_sheet(osv.osv): sheets = self.read(cr, uid, ids, ['state','total_attendance'], context=context) for sheet in sheets: if sheet['state'] in ('confirm', 'done'): - raise osv.except_osv(_('Invalid Action!'), _('You cannot delete a timesheet which is already confirmed.')) + raise UserError(_('You cannot delete a timesheet which is already confirmed.')) elif sheet['total_attendance'] <> 0.00: - raise osv.except_osv(_('Invalid Action!'), _('You cannot delete a timesheet which have attendance entries.')) + raise UserError(_('You cannot delete a timesheet which have attendance entries.')) return super(hr_timesheet_sheet, self).unlink(cr, uid, ids, context=context) def onchange_employee_id(self, cr, uid, ids, employee_id, context=None): @@ -386,7 +387,7 @@ class hr_timesheet_line(osv.osv): def _check(self, cr, uid, ids): for att in self.browse(cr, uid, ids): if att.sheet_id and att.sheet_id.state not in ('draft', 'new'): - raise osv.except_osv(_('Error!'), _('You cannot modify an entry in a confirmed timesheet.')) + raise UserError(_('You cannot modify an entry in a confirmed timesheet.')) return True def multi_on_change_account_id(self, cr, uid, ids, account_ids, context=None): @@ -499,9 +500,9 @@ class hr_attendance(osv.osv): date=vals.get('name'), context=context) ts = self.pool.get('hr_timesheet_sheet.sheet').browse(cr, uid, sheet_id, context=context) if ts.state not in ('draft', 'new'): - raise osv.except_osv(_('Error!'), _('You can not enter an attendance in a submitted timesheet. Ask your manager to reset it before adding attendance.')) + raise UserError(_('You can not enter an attendance in a submitted timesheet. Ask your manager to reset it before adding attendance.')) elif ts.date_from > att_tz_date_str or ts.date_to < att_tz_date_str: - raise osv.except_osv(_('User Error!'), _('You can not enter an attendance date outside the current timesheet dates.')) + raise UserError(_('You can not enter an attendance date outside the current timesheet dates.')) return super(hr_attendance,self).create(cr, uid, vals, context=context) def unlink(self, cr, uid, ids, *args, **kwargs): @@ -520,14 +521,14 @@ class hr_attendance(osv.osv): if 'sheet_id' in context: for attendance in self.browse(cr, uid, ids, context=context): if context['sheet_id'] != attendance.sheet_id.id: - raise osv.except_osv(_('User Error!'), _('You cannot enter an attendance ' \ + raise UserError(_('You cannot enter an attendance ' \ 'date outside the current timesheet dates.')) return res def _check(self, cr, uid, ids): for att in self.browse(cr, uid, ids): if att.sheet_id and att.sheet_id.state not in ('draft', 'new'): - raise osv.except_osv(_('Error!'), _('You cannot modify an entry in a confirmed timesheet')) + raise UserError(_('You cannot modify an entry in a confirmed timesheet')) return True diff --git a/addons/hr_timesheet_sheet/wizard/hr_timesheet_current.py b/addons/hr_timesheet_sheet/wizard/hr_timesheet_current.py index 12ce41e8766..77eb4c67b2e 100644 --- a/addons/hr_timesheet_sheet/wizard/hr_timesheet_current.py +++ b/addons/hr_timesheet_sheet/wizard/hr_timesheet_current.py @@ -22,6 +22,7 @@ import time from openerp.osv import fields, osv from openerp.tools.translate import _ +from openerp.exceptions import UserError class hr_timesheet_current_open(osv.osv_memory): _name = 'hr.timesheet.current.open' @@ -35,7 +36,7 @@ class hr_timesheet_current_open(osv.osv_memory): user_ids = self.pool.get('hr.employee').search(cr, uid, [('user_id','=',uid)], context=context) if not len(user_ids): - raise osv.except_osv(_('Error!'), _('Please create an employee and associate it with this user.')) + raise UserError(_('Please create an employee and associate it with this user.')) ids = ts.search(cr, uid, [('user_id','=',uid),('state','in',('draft','new')),('date_from','<=',time.strftime('%Y-%m-%d')), ('date_to','>=',time.strftime('%Y-%m-%d'))], context=context) if len(ids) > 1: diff --git a/addons/hw_scale/controllers/main.py b/addons/hw_scale/controllers/main.py index fcfa6ede536..531f2739f55 100644 --- a/addons/hw_scale/controllers/main.py +++ b/addons/hw_scale/controllers/main.py @@ -54,7 +54,7 @@ class Scale(Thread): if status == 'error' and message: _logger.error('Scale Error: '+message) elif status == 'disconnected' and message: - _logger.warning('Disconnected Scale: '+message) + _logger.info('Disconnected Scale: %s', message) def get_device(self): try: diff --git a/addons/hw_scanner/controllers/main.py b/addons/hw_scanner/controllers/main.py index 237b301bb0e..7e4ae417b91 100644 --- a/addons/hw_scanner/controllers/main.py +++ b/addons/hw_scanner/controllers/main.py @@ -107,7 +107,7 @@ class Scanner(Thread): if status == 'error' and message: _logger.error('Barcode Scanner Error: '+message) elif status == 'disconnected' and message: - _logger.warning('Disconnected Barcode Scanner: '+message) + _logger.info('Disconnected Barcode Scanner: %s', message) def get_device(self): try: diff --git a/addons/im_chat/im_chat.py b/addons/im_chat/im_chat.py index 9b8bf853dbf..c63e3d9926c 100644 --- a/addons/im_chat/im_chat.py +++ b/addons/im_chat/im_chat.py @@ -10,6 +10,7 @@ import simplejson import openerp import cgi +from openerp import tools from openerp.http import request from openerp.osv import osv, fields from openerp.tools.misc import DEFAULT_SERVER_DATETIME_FORMAT @@ -347,7 +348,9 @@ class im_chat_presence(osv.Model): # write only if the last_poll is passed TIMEOUT, or if the status has changed delta = datetime.datetime.now() - datetime.datetime.strptime(presences[0].last_poll, DEFAULT_SERVER_DATETIME_FORMAT) if (delta > datetime.timedelta(seconds=TIMEOUT) or send_notification): - self.write(cr, uid, presence_ids, vals, context=context) + # Hide transaction serialization errors, which can be ignored, the presence update is not essential + with tools.mute_logger('openerp.sql_db'): + self.write(cr, uid, presence_ids, vals, context=context) # avoid TransactionRollbackError cr.commit() # notify if the status has changed diff --git a/addons/l10n_be/wizard/l10n_be_account_vat_declaration.py b/addons/l10n_be/wizard/l10n_be_account_vat_declaration.py index 6acf5572ed0..ffc5c28753a 100644 --- a/addons/l10n_be/wizard/l10n_be_account_vat_declaration.py +++ b/addons/l10n_be/wizard/l10n_be_account_vat_declaration.py @@ -28,6 +28,7 @@ import base64 from openerp.osv import fields, osv from openerp.tools.translate import _ +from openerp.exceptions import UserError class l10n_be_vat_declaration(osv.osv_memory): """ Vat Declaration """ @@ -84,7 +85,7 @@ class l10n_be_vat_declaration(osv.osv_memory): obj_company = obj_user.browse(cr, uid, uid, context=context).company_id vat_no = obj_company.partner_id.vat if not vat_no: - raise osv.except_osv(_('Insufficient Data!'), _('No VAT number associated with your company.')) + raise UserError(_('No VAT number associated with your company.')) vat_no = vat_no.replace(' ','').upper() vat = vat_no[2:] @@ -109,9 +110,9 @@ class l10n_be_vat_declaration(osv.osv_memory): quarter = str(((int(starting_month) - 1) / 3) + 1) if not address_id.email: - raise osv.except_osv(_('Insufficient Data!'),_('No email address associated with the company.')) + raise UserError(_('No email address associated with the company.')) if not address_id.phone: - raise osv.except_osv(_('Insufficient Data!'),_('No phone associated with the company.')) + raise UserError(_('No phone associated with the company.')) file_data = { 'issued_by': issued_by, 'vat_no': vat_no, diff --git a/addons/l10n_be/wizard/l10n_be_partner_vat_listing.py b/addons/l10n_be/wizard/l10n_be_partner_vat_listing.py index c22af289a17..465dd44de31 100644 --- a/addons/l10n_be/wizard/l10n_be_partner_vat_listing.py +++ b/addons/l10n_be/wizard/l10n_be_partner_vat_listing.py @@ -29,6 +29,7 @@ import base64 from openerp.tools.translate import _ from openerp.osv import fields, osv from openerp.report import report_sxw +from openerp.exceptions import UserError class vat_listing_clients(osv.osv_memory): _name = 'vat.listing.clients' @@ -60,12 +61,12 @@ class partner_vat(osv.osv_memory): company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id period_ids = obj_period.search(cr, uid, [('date_start' ,'>=', date_start), ('date_stop','<=',date_stop), ('company_id','=',company_id)]) if not period_ids: - raise osv.except_osv(_('Insufficient Data!'), _('No data for the selected year.')) + raise UserError(_('No data for the selected year.')) partners = [] partner_ids = obj_partner.search(cr, uid, [('vat_subjected', '!=', False), ('vat','ilike','BE%')], context=context) if not partner_ids: - raise osv.except_osv(_('Error'),_('No belgium contact with a VAT number in your database.')) + raise UserError(_('No belgium contact with a VAT number in your database.')) cr.execute("""SELECT sub1.partner_id, sub1.name, sub1.vat, sub1.turnover, sub2.vat_amount FROM (SELECT l.partner_id, p.name, p.vat, SUM(CASE WHEN c.code ='49' THEN -l.tax_amount ELSE l.tax_amount END) as turnover FROM account_move_line l @@ -90,7 +91,7 @@ class partner_vat(osv.osv_memory): partners.append(id_client) if not partners: - raise osv.except_osv(_('Insufficient Data!'), _('No data found for the selected year.')) + raise UserError(_('No data found for the selected year.')) context.update({'partner_ids': partners, 'year': data['year'], 'limit_amount': data['limit_amount']}) model_data_ids = obj_model_data.search(cr, uid, [('model','=','ir.ui.view'), ('name','=','view_vat_listing')]) resource_id = obj_model_data.read(cr, uid, model_data_ids, fields=['res_id'])[0]['res_id'] @@ -179,7 +180,7 @@ class partner_vat_list(osv.osv_memory): company_vat = obj_cmpny.partner_id.vat if not company_vat: - raise osv.except_osv(_('Insufficient Data!'),_('No VAT number associated with the company.')) + raise UserError(_('No VAT number associated with the company.')) company_vat = company_vat.replace(' ','').upper() SenderId = company_vat[2:] @@ -208,9 +209,9 @@ class partner_vat_list(osv.osv_memory): comp_name = obj_cmpny.name if not email: - raise osv.except_osv(_('Insufficient Data!'),_('No email address associated with the company.')) + raise UserError(_('No email address associated with the company.')) if not phone: - raise osv.except_osv(_('Insufficient Data!'),_('No phone associated with the company.')) + raise UserError(_('No phone associated with the company.')) annual_listing_data = { 'issued_by': issued_by, 'company_vat': company_vat, @@ -259,7 +260,7 @@ class partner_vat_list(osv.osv_memory): # Turnover and Farmer tags are not included client_datas = self._get_datas(cr, uid, ids, context=context) if not client_datas: - raise osv.except_osv(_('Data Insufficient!'),_('No data available for the client.')) + raise UserError(_('No data available for the client.')) data_client_info = '' for amount_data in client_datas: data_client_info += """ @@ -310,7 +311,7 @@ class partner_vat_list(osv.osv_memory): datas['limit_amount'] = context['limit_amount'] datas['client_datas'] = self._get_datas(cr, uid, ids, context=context) if not datas['client_datas']: - raise osv.except_osv(_('Error!'), _('No record to print.')) + raise UserError(_('No record to print.')) return self.pool['report'].get_action( cr, uid, [], 'l10n_be.report_l10nvatpartnerlisting', data=datas, context=context ) diff --git a/addons/l10n_be/wizard/l10n_be_vat_intra.py b/addons/l10n_be/wizard/l10n_be_vat_intra.py index ff1f4880f60..9c10151bdf2 100644 --- a/addons/l10n_be/wizard/l10n_be_vat_intra.py +++ b/addons/l10n_be/wizard/l10n_be_vat_intra.py @@ -28,6 +28,7 @@ import base64 from openerp.osv import fields, osv from openerp.tools.translate import _ from openerp.report import report_sxw +from openerp.exceptions import UserError class partner_vat_intra(osv.osv_memory): @@ -109,19 +110,19 @@ class partner_vat_intra(osv.osv_memory): # Get Company vat company_vat = data_company.partner_id.vat if not company_vat: - raise osv.except_osv(_('Insufficient Data!'),_('No VAT number associated with your company.')) + raise UserError(_('No VAT number associated with your company.')) company_vat = company_vat.replace(' ','').upper() issued_by = company_vat[:2] if len(wiz_data.period_code) != 6: - raise osv.except_osv(_('Error!'), _('Period code is not valid.')) + raise UserError(_('Period code is not valid.')) if not wiz_data.period_ids: - raise osv.except_osv(_('Insufficient Data!'),_('Please select at least one Period.')) + raise UserError(_('Please select at least one Period.')) p_id_list = obj_partner.search(cr, uid, [('vat','!=',False)], context=context) if not p_id_list: - raise osv.except_osv(_('Insufficient Data!'),_('No partner has a VAT number associated with him.')) + raise UserError(_('No partner has a VAT number associated with him.')) seq_declarantnum = obj_sequence.next_by_code(cr, uid, 'declarantnum') dnum = company_vat[2:] + seq_declarantnum[-4:] @@ -145,9 +146,9 @@ class partner_vat_intra(osv.osv_memory): if not country: country = company_vat[:2] if not email: - raise osv.except_osv(_('Insufficient Data!'),_('No email address associated with the company.')) + raise UserError(_('No email address associated with the company.')) if not phone: - raise osv.except_osv(_('Insufficient Data!'),_('No phone associated with the company.')) + raise UserError(_('No phone associated with the company.')) xmldict.update({ 'company_name': data_company.name, 'company_vat': company_vat, @@ -247,7 +248,7 @@ class partner_vat_intra(osv.osv_memory): data_clientinfo = '' for client in xml_data['clientlist']: if not client['vatnum']: - raise osv.except_osv(_('Insufficient Data!'),_('No vat number defined for %s.') % client['partner_name']) + raise UserError(_('No vat number defined for %s.') % client['partner_name']) data_clientinfo +='\n\t\t\n\t\t\t%(vatnum)s\n\t\t\t%(code)s\n\t\t\t%(amount).2f\n\t\t' % (client) data_decl = '\n\t' % (xml_data) diff --git a/addons/l10n_be_coda/wizard/account_coda_import.py b/addons/l10n_be_coda/wizard/account_coda_import.py index fc2c4c51657..7fc3aaddd6a 100644 --- a/addons/l10n_be_coda/wizard/account_coda_import.py +++ b/addons/l10n_be_coda/wizard/account_coda_import.py @@ -25,6 +25,7 @@ import re from openerp.osv import osv from openerp.tools.translate import _ from openerp import tools +from openerp.exceptions import UserError import logging @@ -55,7 +56,7 @@ class account_bank_statement_import(osv.TransientModel): statements.append(statement) statement['version'] = line[127] if statement['version'] not in ['1', '2']: - raise osv.except_osv(_('Error') + ' R001', _('CODA V%s statements are not supported, please contact your bank') % statement['version']) + raise UserError(_('Error') + ' R001: ' + _('CODA V%s statements are not supported, please contact your bank') % statement['version']) statement['lines'] = [] statement['date'] = time.strftime(tools.DEFAULT_SERVER_DATE_FORMAT, time.strptime(rmspaces(line[5:11]), '%d%m%y')) statement['separateApplication'] = rmspaces(line[83:88]) @@ -69,14 +70,14 @@ class account_bank_statement_import(osv.TransientModel): statement['acc_number'] = rmspaces(line[5:17]) statement['currency'] = rmspaces(line[18:21]) elif line[1] == '1': # foreign bank account BBAN structure - raise osv.except_osv(_('Error') + ' R1001', _('Foreign bank accounts with BBAN structure are not supported ')) + raise UserError(_('Error') + ' R1001: ' + _('Foreign bank accounts with BBAN structure are not supported ')) elif line[1] == '2': # Belgian bank account IBAN structure statement['acc_number'] = rmspaces(line[5:21]) statement['currency'] = rmspaces(line[39:42]) elif line[1] == '3': # foreign bank account IBAN structure - raise osv.except_osv(_('Error') + ' R1002', _('Foreign bank accounts with IBAN structure are not supported ')) + raise UserError(_('Error') + ' R1002: ' + _('Foreign bank accounts with IBAN structure are not supported ')) else: # Something else, not supported - raise osv.except_osv(_('Error') + ' R1003', _('Unsupported bank account structure ')) + raise UserError(_('Error') + ' R1003: ' + _('Unsupported bank account structure ')) statement['description'] = rmspaces(line[90:125]) statement['balance_start'] = float(rmspaces(line[43:58])) / 1000 if line[42] == '1': # 1 = Debit, the starting balance is negative @@ -122,13 +123,13 @@ class account_bank_statement_import(osv.TransientModel): statement['lines'].append(statementLine) elif line[1] == '2': if statement['lines'][-1]['ref'][0:4] != line[2:6]: - raise osv.except_osv(_('Error') + 'R2004', _('CODA parsing error on movement data record 2.2, seq nr %s! Please report this issue via your Odoo support channel.') % line[2:10]) + raise UserError(_('Error') + 'R2004: ' + _('CODA parsing error on movement data record 2.2, seq nr %s! Please report this issue via your Odoo support channel.') % line[2:10]) statement['lines'][-1]['communication'] += rmspaces(line[10:63]) statement['lines'][-1]['payment_reference'] = rmspaces(line[63:98]) statement['lines'][-1]['counterparty_bic'] = rmspaces(line[98:109]) elif line[1] == '3': if statement['lines'][-1]['ref'][0:4] != line[2:6]: - raise osv.except_osv(_('Error') + 'R2005', _('CODA parsing error on movement data record 2.3, seq nr %s! Please report this issue via your Odoo support channel.') % line[2:10]) + raise UserError(_('Error') + 'R2005: ' + _('CODA parsing error on movement data record 2.3, seq nr %s! Please report this issue via your Odoo support channel.') % line[2:10]) if statement['version'] == '1': statement['lines'][-1]['counterpartyNumber'] = rmspaces(line[10:22]) statement['lines'][-1]['counterpartyName'] = rmspaces(line[47:73]) @@ -145,7 +146,7 @@ class account_bank_statement_import(osv.TransientModel): statement['lines'][-1]['communication'] += rmspaces(line[82:125]) else: # movement data record 2.x (x != 1,2,3) - raise osv.except_osv(_('Error') + 'R2006', _('\nMovement data records of type 2.%s are not supported ') % line[1]) + raise UserError(_('Error') + 'R2006: ' + _('\nMovement data records of type 2.%s are not supported ') % line[1]) elif line[0] == '3': if line[1] == '1': infoLine = {} @@ -161,11 +162,11 @@ class account_bank_statement_import(osv.TransientModel): statement['lines'].append(infoLine) elif line[1] == '2': if infoLine['ref'] != rmspaces(line[2:10]): - raise osv.except_osv(_('Error') + 'R3004', _('CODA parsing error on information data record 3.2, seq nr %s! Please report this issue via your Odoo support channel.') % line[2:10]) + raise UserError(_('Error') + 'R3004: ' + _('CODA parsing error on information data record 3.2, seq nr %s! Please report this issue via your Odoo support channel.') % line[2:10]) statement['lines'][-1]['communication'] += rmspaces(line[10:100]) elif line[1] == '3': if infoLine['ref'] != rmspaces(line[2:10]): - raise osv.except_osv(_('Error') + 'R3005', _('CODA parsing error on information data record 3.3, seq nr %s! Please report this issue via your Odoo support channel.') % line[2:10]) + raise UserError(_('Error') + 'R3005: ' + _('CODA parsing error on information data record 3.3, seq nr %s! Please report this issue via your Odoo support channel.') % line[2:10]) statement['lines'][-1]['communication'] += rmspaces(line[10:100]) elif line[0] == '4': comm_line = {} diff --git a/addons/l10n_be_invoice_bba/invoice.py b/addons/l10n_be_invoice_bba/invoice.py index 78233ca66ab..00a276431ec 100644 --- a/addons/l10n_be_invoice_bba/invoice.py +++ b/addons/l10n_be_invoice_bba/invoice.py @@ -25,6 +25,7 @@ from openerp import api from openerp.osv import fields, osv from openerp.tools.translate import _ import logging +from openerp.exceptions import UserError _logger = logging.getLogger(__name__) """ @@ -109,9 +110,8 @@ class account_invoice(osv.osv): if prev_seq < 999: seq = '%03d' % (prev_seq + 1) else: - raise osv.except_osv(_('Warning!'), - _('The daily maximum of outgoing invoices with an automatically generated BBA Structured Communications has been exceeded!' \ - '\nPlease create manually a unique BBA Structured Communication.')) + raise UserError(_('The daily maximum of outgoing invoices with an automatically generated BBA Structured Communications has been exceeded!' \ + '\nPlease create manually a unique BBA Structured Communication.')) bbacomm = doy + year + seq base = int(bbacomm) mod = base % 97 or 97 @@ -121,9 +121,8 @@ class account_invoice(osv.osv): partner_ref = self.pool.get('res.partner').browse(cr, uid, partner_id).ref partner_ref_nr = re.sub('\D', '', partner_ref or '') if (len(partner_ref_nr) < 3) or (len(partner_ref_nr) > 7): - raise osv.except_osv(_('Warning!'), - _('The Partner should have a 3-7 digit Reference Number for the generation of BBA Structured Communications!' \ - '\nPlease correct the Partner record.')) + raise UserError(_('The Partner should have a 3-7 digit Reference Number for the generation of BBA Structured Communications!' \ + '\nPlease correct the Partner record.')) else: partner_ref_nr = partner_ref_nr.ljust(7, '0') seq = '001' @@ -135,9 +134,8 @@ class account_invoice(osv.osv): if prev_seq < 999: seq = '%03d' % (prev_seq + 1) else: - raise osv.except_osv(_('Warning!'), - _('The daily maximum of outgoing invoices with an automatically generated BBA Structured Communications has been exceeded!' \ - '\nPlease create manually a unique BBA Structured Communication.')) + raise UserError(_('The daily maximum of outgoing invoices with an automatically generated BBA Structured Communications has been exceeded!' \ + '\nPlease create manually a unique BBA Structured Communication.')) bbacomm = partner_ref_nr + seq base = int(bbacomm) mod = base % 97 or 97 @@ -151,9 +149,8 @@ class account_invoice(osv.osv): mod = str(mod).rjust(2, '0') reference = '+++%s/%s/%s%s+++' % (bbacomm[:3], bbacomm[3:7], bbacomm[7:], mod) else: - raise osv.except_osv(_('Error!'), - _("Unsupported Structured Communication Type Algorithm '%s' !" \ - "\nPlease contact your Odoo support channel.") % algorithm) + raise UserError(_("Unsupported Structured Communication Type Algorithm '%s' !" \ + "\nPlease contact your Odoo support channel.") % algorithm) return {'value': {'reference': reference}} def create(self, cr, uid, vals, context=None): @@ -171,9 +168,8 @@ class account_invoice(osv.osv): if reference_type == 'bba': if not reference: - raise osv.except_osv(_('Warning!'), - _('Empty BBA Structured Communication!' \ - '\nPlease fill in a unique BBA Structured Communication.')) + raise UserError(_('Empty BBA Structured Communication!' \ + '\nPlease fill in a unique BBA Structured Communication.')) if self.check_bbacomm(reference): reference = re.sub('\D', '', reference) vals['reference'] = '+++' + reference[0:3] + '/' + reference[3:7] + '/' + reference[7:] + '+++' @@ -181,9 +177,8 @@ class account_invoice(osv.osv): [('type', '=', 'out_invoice'), ('reference_type', '=', 'bba'), ('reference', '=', vals['reference'])]) if same_ids: - raise osv.except_osv(_('Warning!'), - _('The BBA Structured Communication has already been used!' \ - '\nPlease create manually a unique BBA Structured Communication.')) + raise UserError(_('The BBA Structured Communication has already been used!' \ + '\nPlease create manually a unique BBA Structured Communication.')) return super(account_invoice, self).create(cr, uid, vals, context=context) def write(self, cr, uid, ids, vals, context=None): @@ -206,9 +201,8 @@ class account_invoice(osv.osv): [('id', '!=', inv.id), ('type', '=', 'out_invoice'), ('reference_type', '=', 'bba'), ('reference', '=', vals['reference'])]) if same_ids: - raise osv.except_osv(_('Warning!'), - _('The BBA Structured Communication has already been used!' \ - '\nPlease create manually a unique BBA Structured Communication.')) + raise UserError(_('The BBA Structured Communication has already been used!' \ + '\nPlease create manually a unique BBA Structured Communication.')) return super(account_invoice, self).write(cr, uid, ids, vals, context) def copy(self, cr, uid, id, default=None, context=None): diff --git a/addons/l10n_in_hr_payroll/l10n_in_hr_payroll.py b/addons/l10n_in_hr_payroll/l10n_in_hr_payroll.py index 0824fdf376b..c2cd7a64fc6 100644 --- a/addons/l10n_in_hr_payroll/l10n_in_hr_payroll.py +++ b/addons/l10n_in_hr_payroll/l10n_in_hr_payroll.py @@ -27,6 +27,7 @@ from calendar import isleap from openerp.tools.translate import _ from openerp.osv import fields, osv import openerp.addons.decimal_precision as dp +from openerp.exceptions import UserError DATETIME_FORMAT = "%Y-%m-%d" @@ -103,7 +104,7 @@ class payroll_advice(osv.osv): slip_ids = payslip_pool.search(cr, uid, [('date_from', '<=', advice.date), ('date_to', '>=', advice.date), ('state', '=', 'done')], context=context) for slip in payslip_pool.browse(cr, uid, slip_ids, context=context): if not slip.employee_id.bank_account_id and not slip.employee_id.bank_account_id.acc_number: - raise osv.except_osv(_('Error!'), _('Please define bank account for the %s employee') % (slip.employee_id.name)) + raise UserError(_('Please define bank account for the %s employee') % (slip.employee_id.name,)) line_ids = payslip_line_pool.search(cr, uid, [ ('slip_id', '=', slip.id), ('code', '=', 'NET')], context=context) if line_ids: line = payslip_line_pool.browse(cr, uid, line_ids, context=context)[0] @@ -129,7 +130,7 @@ class payroll_advice(osv.osv): seq_obj = self.pool.get('ir.sequence') for advice in self.browse(cr, uid, ids, context=context): if not advice.line_ids: - raise osv.except_osv(_('Error!'), _('You can not confirm Payment advice without advice lines.')) + raise UserError(_('You can not confirm Payment advice without advice lines.')) advice_date = datetime.strptime(advice.date, DATETIME_FORMAT) advice_year = advice_date.strftime('%m') + '-' + advice_date.strftime('%Y') number = seq_obj.next_by_code(cr, uid, 'payment.advice') @@ -180,7 +181,7 @@ class hr_payslip_run(osv.osv): users = self.pool.get('res.users').browse(cr, uid, [uid], context=context) for run in self.browse(cr, uid, ids, context=context): if run.available_advice: - raise osv.except_osv(_('Error!'), _("Payment advice already exists for %s, 'Set to Draft' to create a new advice.") %(run.name)) + raise UserError(_("Payment advice already exists for %s, 'Set to Draft' to create a new advice.") % (run.name,)) advice_data = { 'batch_id': run.id, 'company_id': users[0].company_id.id, @@ -198,7 +199,7 @@ class hr_payslip_run(osv.osv): for slip in payslip_pool.browse(cr, uid, slip_ids, context=context): if not slip.employee_id.bank_account_id or not slip.employee_id.bank_account_id.acc_number: - raise osv.except_osv(_('Error!'), _('Please define bank account for the %s employee') % (slip.employee_id.name)) + raise UserError(_('Please define bank account for the %s employee') % (slip.employee_id.name)) line_ids = payslip_line_pool.search(cr, uid, [('slip_id', '=', slip.id), ('code', '=', 'NET')], context=context) if line_ids: line = payslip_line_pool.browse(cr, uid, line_ids, context=context)[0] diff --git a/addons/mail/mail_group.py b/addons/mail/mail_group.py index 8ef5b56a44c..4f30a16bbf7 100644 --- a/addons/mail/mail_group.py +++ b/addons/mail/mail_group.py @@ -26,6 +26,7 @@ from openerp.osv import fields from openerp.tools.safe_eval import safe_eval as eval from openerp import SUPERUSER_ID from openerp.tools.translate import _ +from openerp.exceptions import UserError class mail_group(osv.Model): """ A mail_group is a collection of users sharing messages in a discussion @@ -171,7 +172,7 @@ class mail_group(osv.Model): except ValueError: all_emp_group = None if all_emp_group and all_emp_group in ids: - raise osv.except_osv(_('Warning!'), _('You cannot delete those groups, as the Whole Company group is required by other modules.')) + raise UserError(_('You cannot delete those groups, as the Whole Company group is required by other modules.')) res = super(mail_group, self).unlink(cr, uid, ids, context=context) # Cascade-delete mail aliases as well, as they should not exist without the mail group. self.pool.get('mail.alias').unlink(cr, SUPERUSER_ID, alias_ids, context=context) diff --git a/addons/mail/mail_mail.py b/addons/mail/mail_mail.py index 0034c15a87b..5a54de14094 100644 --- a/addons/mail/mail_mail.py +++ b/addons/mail/mail_mail.py @@ -313,7 +313,7 @@ class mail_mail(osv.Model): # mail item -> ignore error to avoid blocking # delivery to next recipients, if any. If this is # the only recipient, the mail will show as failed. - _logger.warning("Ignoring invalid recipients for mail.mail %s: %s", + _logger.info("Ignoring invalid recipients for mail.mail %s: %s", mail.message_id, email.get('email_to')) else: raise diff --git a/addons/mail/mail_message.py b/addons/mail/mail_message.py index fe433657077..2780a659008 100644 --- a/addons/mail/mail_message.py +++ b/addons/mail/mail_message.py @@ -26,10 +26,11 @@ from openerp import tools from email.header import decode_header from email.utils import formataddr from openerp import SUPERUSER_ID, api -from openerp.osv import osv, orm, fields +from openerp.osv import osv, fields from openerp.tools import html_email_clean from openerp.tools.translate import _ from HTMLParser import HTMLParser +from openerp.exceptions import UserError, AccessError _logger = logging.getLogger(__name__) @@ -174,7 +175,7 @@ class mail_message(osv.Model): return formataddr((this.name, '%s@%s' % (this.alias_name, this.alias_domain))) elif this.email: return formataddr((this.name, this.email)) - raise osv.except_osv(_('Invalid Action!'), _("Unable to send email, please configure the sender's email address or alias.")) + raise UserError(_("Unable to send email, please configure the sender's email address or alias.")) def _get_default_author(self, cr, uid, context=None): return self.pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context=context).partner_id.id @@ -770,10 +771,10 @@ class mail_message(osv.Model): other_ids = other_ids.difference(set(document_related_ids)) if not other_ids: return - raise orm.except_orm(_('Access Denied'), - _('The requested operation cannot be completed due to security restrictions. Please contact your system administrator.\n\n(Document type: %s, Operation: %s)') % + raise AccessError(_('The requested operation cannot be completed due to security restrictions. Please contact your system administrator.\n\n(Document type: %s, Operation: %s)') % (self._description, operation)) + def _get_record_name(self, cr, uid, values, context=None): """ Return the related document name, using name_get. It is done using SUPERUSER_ID, to be sure to have the record name correctly stored. """ diff --git a/addons/mail/mail_template.py b/addons/mail/mail_template.py index af4ea07fa4e..7525fe2fd81 100644 --- a/addons/mail/mail_template.py +++ b/addons/mail/mail_template.py @@ -33,6 +33,7 @@ from openerp.osv import osv, fields from openerp import tools, api from openerp.tools.translate import _ from urllib import urlencode, quote as quote +from openerp.exceptions import UserError _logger = logging.getLogger(__name__) @@ -183,7 +184,7 @@ class mail_template(osv.osv): try: template = mako_template_env.from_string(tools.ustr(template)) except Exception: - _logger.exception("Failed to load template %r", template) + _logger.info("Failed to load template %r", template, exc_info=True) return results # prepare template variables @@ -200,7 +201,8 @@ class mail_template(osv.osv): try: render_result = template.render(variables) except Exception: - _logger.exception("Failed to render template %r using values %r" % (template, variables)) + _logger.info("Failed to render template %r using values %r" % (template, variables), exc_info=True) + raise UserError(_("Failed to render template %r using values %r")% (template, variables)) render_result = u"" if render_result == u"False": render_result = u"" @@ -353,7 +355,7 @@ class mail_template(osv.osv): ir_values_obj = self.pool.get('ir.values') ir_values_obj.unlink(cr, SUPERUSER_ID, template.ref_ir_value.id, context) except Exception: - raise osv.except_osv(_("Warning"), _("Deletion of the action record failed.")) + raise UserError(_("Deletion of the action record failed.")) return True def unlink(self, cr, uid, ids, context=None): @@ -549,7 +551,7 @@ class mail_template(osv.osv): # create a mail_mail based on values, without attachments values = self.generate_email(cr, uid, template_id, res_id, context=context) if not values.get('email_from'): - raise osv.except_osv(_('Warning!'), _("Sender email is missing or empty after template rendering. Specify one to deliver your message")) + raise UserError(_("Sender email is missing or empty after template rendering. Specify one to deliver your message")) values['recipient_ids'] = [(4, pid) for pid in values.get('partner_ids', list())] attachment_ids = values.pop('attachment_ids', []) attachments = values.pop('attachments', []) diff --git a/addons/mail/mail_thread.py b/addons/mail/mail_thread.py index db1ea225713..254cd193285 100644 --- a/addons/mail/mail_thread.py +++ b/addons/mail/mail_thread.py @@ -46,6 +46,7 @@ from openerp.osv import fields, osv, orm from openerp.osv.orm import BaseModel from openerp.tools.safe_eval import safe_eval as eval from openerp.tools.translate import _ +from openerp.exceptions import AccessError _logger = logging.getLogger(__name__) @@ -649,7 +650,7 @@ class mail_thread(osv.AbstractModel): try: model_obj.check_access_rule(cr, uid, [res_id], 'read', context=context) action = model_obj.get_access_action(cr, uid, res_id, context=context) - except (osv.except_osv, orm.except_orm): + except AccessError: pass action.update({ 'context': { @@ -803,7 +804,7 @@ class mail_thread(osv.AbstractModel): mail_mail.send(cr, uid, [mail_id], context=context) def _warn(message): - _logger.warning('Routing mail with Message-Id %s: route %s: %s', + _logger.info('Routing mail with Message-Id %s: route %s: %s', message_id, route, message) # Wrong model @@ -1352,7 +1353,7 @@ class mail_thread(osv.AbstractModel): else: stored_date = parsed_date.astimezone(tz=pytz.utc) except Exception: - _logger.warning('Failed to parse Date header %r in incoming mail ' + _logger.info('Failed to parse Date header %r in incoming mail ' 'with message-id %r, assuming current date/time.', message.get('Date'), message_id) stored_date = datetime.datetime.now() @@ -1698,7 +1699,7 @@ class mail_thread(osv.AbstractModel): try: self.check_access_rights(cr, uid, 'read') self.check_access_rule(cr, uid, ids, 'read') - except (osv.except_osv, orm.except_orm): + except AccessError: return False else: self.check_access_rights(cr, uid, 'write') diff --git a/addons/mail/tests/test_mail_group.py b/addons/mail/tests/test_mail_group.py index c131ce0bd0b..25a4d5b199e 100644 --- a/addons/mail/tests/test_mail_group.py +++ b/addons/mail/tests/test_mail_group.py @@ -21,7 +21,6 @@ from openerp.addons.mail.tests.common import TestMail from openerp.exceptions import AccessError -from openerp.osv.orm import except_orm from openerp.tools import mute_logger @@ -35,7 +34,7 @@ class TestMailGroup(TestMail): # Do: Bert reads Jobs -> ok, public self.mail_group.read(cr, user_noone_id, [self.group_jobs_id]) # Do: Bert read Pigs -> ko, restricted to employees - with self.assertRaises(except_orm): + with self.assertRaises(AccessError): self.mail_group.read(cr, user_noone_id, [self.group_pigs_id]) # Do: Raoul read Pigs -> ok, belong to employees self.mail_group.read(cr, user_employee_id, [self.group_pigs_id]) @@ -50,7 +49,7 @@ class TestMailGroup(TestMail): self.mail_group.read(cr, user_noone_id, [new_group_id]) # Do: Raoul reads Priv -> ko, private - with self.assertRaises(except_orm): + with self.assertRaises(AccessError): self.mail_group.read(cr, user_employee_id, [self.group_priv_id]) # Do: Raoul added in follower, read -> ok, in followers self.mail_group.message_subscribe_users(cr, uid, [self.group_priv_id], [user_employee_id]) @@ -62,7 +61,7 @@ class TestMailGroup(TestMail): with self.assertRaises(AccessError): self.mail_group.write(cr, user_noone_id, [self.group_priv_id], {'name': 're-modified'}) # Test: Bert cannot unlink the group - with self.assertRaises(except_orm): + with self.assertRaises(AccessError): self.mail_group.unlink(cr, user_noone_id, [self.group_priv_id]) # Do: Raoul unlinks the group, there are no followers and messages left self.mail_group.unlink(cr, user_employee_id, [self.group_priv_id]) diff --git a/addons/mail/tests/test_mail_message.py b/addons/mail/tests/test_mail_message.py index 9883449d754..3bd089bd87c 100644 --- a/addons/mail/tests/test_mail_message.py +++ b/addons/mail/tests/test_mail_message.py @@ -21,7 +21,6 @@ from openerp.addons.mail.tests.common import TestMail from openerp.exceptions import AccessError -from openerp.osv.orm import except_orm from openerp.tools import mute_logger @@ -218,7 +217,7 @@ class TestMailMessage(TestMail): message_id = self.mail_message.create(cr, uid, {'body': 'My Body', 'attachment_ids': [(4, attachment_id)]}) # Test: Bert reads the message, crash because not notification/not in doc followers/not read on doc - with self.assertRaises(except_orm): + with self.assertRaises(AccessError): self.mail_message.read(cr, user_bert_id, message_id) # Do: message is pushed to Bert notif_id = self.mail_notification.create(cr, uid, {'message_id': message_id, 'partner_id': partner_bert_id}) @@ -229,10 +228,10 @@ class TestMailMessage(TestMail): # Do: remove notification self.mail_notification.unlink(cr, uid, notif_id) # Test: Bert reads the message, crash because not notification/not in doc followers/not read on doc - with self.assertRaises(except_orm): + with self.assertRaises(AccessError): self.mail_message.read(cr, self.user_bert_id, message_id) # Test: Bert downloads attachment, crash because he can't read message - with self.assertRaises(except_orm): + with self.assertRaises(AccessError): self.mail_message.download_attachment(cr, user_bert_id, message_id, attachment_id) # Do: Bert is now the author self.mail_message.write(cr, uid, [message_id], {'author_id': partner_bert_id}) @@ -241,7 +240,7 @@ class TestMailMessage(TestMail): # Do: Bert is not the author anymore self.mail_message.write(cr, uid, [message_id], {'author_id': partner_raoul_id}) # Test: Bert reads the message, crash because not notification/not in doc followers/not read on doc - with self.assertRaises(except_orm): + with self.assertRaises(AccessError): self.mail_message.read(cr, user_bert_id, message_id) # Do: message is attached to a document Bert can read, Jobs self.mail_message.write(cr, uid, [message_id], {'model': 'mail.group', 'res_id': self.group_jobs_id}) @@ -250,7 +249,7 @@ class TestMailMessage(TestMail): # Do: message is attached to a document Bert cannot read, Pigs self.mail_message.write(cr, uid, [message_id], {'model': 'mail.group', 'res_id': self.group_pigs_id}) # Test: Bert reads the message, crash because not notification/not in doc followers/not read on doc - with self.assertRaises(except_orm): + with self.assertRaises(AccessError): self.mail_message.read(cr, user_bert_id, message_id) # ---------------------------------------- @@ -270,12 +269,12 @@ class TestMailMessage(TestMail): # Do: Raoul creates a message on Jobs -> ok, write access to the related document self.mail_message.create(cr, user_raoul_id, {'model': 'mail.group', 'res_id': self.group_jobs_id, 'body': 'Test'}) # Do: Raoul creates a message on Priv -> ko, no write access to the related document - with self.assertRaises(except_orm): + with self.assertRaises(AccessError): self.mail_message.create(cr, user_raoul_id, {'model': 'mail.group', 'res_id': self.group_priv_id, 'body': 'Test'}) # Do: Raoul creates a private message -> ok self.mail_message.create(cr, user_raoul_id, {'body': 'Test'}) # Do: Raoul creates a reply to a message on Priv -> ko - with self.assertRaises(except_orm): + with self.assertRaises(AccessError): self.mail_message.create(cr, user_raoul_id, {'model': 'mail.group', 'res_id': self.group_priv_id, 'body': 'Test', 'parent_id': priv_msg_id}) # Do: Raoul creates a reply to a message on Priv-> ok if has received parent self.mail_notification.create(cr, uid, {'message_id': priv_msg_id, 'partner_id': self.partner_raoul_id}) diff --git a/addons/mail/update.py b/addons/mail/update.py index 7f9ec9727f4..92ea8440fde 100644 --- a/addons/mail/update.py +++ b/addons/mail/update.py @@ -12,6 +12,7 @@ from openerp.osv import osv from openerp.tools.translate import _ from openerp.tools.config import config from openerp.tools import misc +from openerp.exceptions import UserError _logger = logging.getLogger(__name__) @@ -88,7 +89,7 @@ class publisher_warranty_contract(AbstractModel): if cron_mode: # we don't want to see any stack trace in cron return False _logger.debug("Exception while sending a get logs messages", exc_info=1) - raise osv.except_osv(_("Error"), _("Error during communication with the publisher warranty server.")) + raise UserError(_("Error during communication with the publisher warranty server.")) # old behavior based on res.log; now on mail.message, that is not necessarily installed IMD = self.pool['ir.model.data'] user = self.pool['res.users'].browse(cr, SUPERUSER_ID, SUPERUSER_ID) @@ -101,7 +102,7 @@ class publisher_warranty_contract(AbstractModel): try: poster.message_post(body=message, subtype='mt_comment', partner_ids=[user.partner_id.id]) except Exception: - _logger.warning('Cannot send ping message', exc_info=True) + pass except Exception: if cron_mode: return False # we don't want to see any stack trace in cron diff --git a/addons/marketing_campaign/marketing_campaign.py b/addons/marketing_campaign/marketing_campaign.py index b02f4e82cce..bf2b35eb200 100644 --- a/addons/marketing_campaign/marketing_campaign.py +++ b/addons/marketing_campaign/marketing_campaign.py @@ -35,6 +35,7 @@ from openerp import api from openerp.osv import fields, osv from openerp.report import render_report from openerp.tools.translate import _ +from openerp.exceptions import UserError _intervalTypes = { 'hours': lambda interval: relativedelta(hours=interval), @@ -108,7 +109,7 @@ Normal - the campaign runs normally and automatically sends all emails and repor campaign = self.browse(cr, uid, ids[0]) if not campaign.activity_ids: - raise osv.except_osv(_("Error"), _("The campaign cannot be started. There are no activities in it.")) + raise UserError(_("The campaign cannot be started. There are no activities in it.")) has_start = False has_signal_without_from = False @@ -120,7 +121,7 @@ Normal - the campaign runs normally and automatically sends all emails and repor has_signal_without_from = True if not has_start and not has_signal_without_from: - raise osv.except_osv(_("Error"), _("The campaign cannot be started. It does not have any starting activity. Modify campaign's activities to mark one as the starting point.")) + raise UserError(_("The campaign cannot be started. It does not have any starting activity. Modify campaign's activities to mark one as the starting point.")) return self.write(cr, uid, ids, {'state': 'running'}) @@ -130,7 +131,7 @@ Normal - the campaign runs normally and automatically sends all emails and repor [('campaign_id', 'in', ids), ('state', '=', 'running')]) if segment_ids : - raise osv.except_osv(_("Error"), _("The campaign cannot be marked as done before all segments are closed.")) + raise UserError(_("The campaign cannot be marked as done before all segments are closed.")) self.write(cr, uid, ids, {'state': 'done'}) return True @@ -186,7 +187,7 @@ Normal - the campaign runs normally and automatically sends all emails and repor # prevent duplication until the server properly duplicates several levels of nested o2m def copy(self, cr, uid, id, default=None, context=None): - raise osv.except_osv(_("Operation not supported"), _("You cannot duplicate a campaign, Not supported yet.")) + raise UserError(_('Duplicating campaigns is not supported.')) def _find_duplicate_workitems(self, cr, uid, record, campaign_rec, context=None): """Finds possible duplicates workitems for a record in this campaign, based on a uniqueness @@ -797,7 +798,7 @@ class marketing_campaign_workitem(osv.osv): 'datas' : datas, } else: - raise osv.except_osv(_('No preview'),_('The current step for this item has no email or report to preview.')) + raise UserError(_('The current step for this item has no email or report to preview.')) return res diff --git a/addons/mass_mailing/models/mass_mailing.py b/addons/mass_mailing/models/mass_mailing.py index 3af897a4daa..80ae9651084 100644 --- a/addons/mass_mailing/models/mass_mailing.py +++ b/addons/mass_mailing/models/mass_mailing.py @@ -7,8 +7,7 @@ import re from openerp import tools from openerp import models, api, _ -from openerp.exceptions import Warning -from openerp.tools import ustr +from openerp.exceptions import UserError from openerp.tools.misc import DEFAULT_SERVER_DATETIME_FORMAT from openerp.tools.safe_eval import safe_eval as eval from openerp.tools import ustr @@ -776,7 +775,7 @@ class MassMailing(osv.Model): # instantiate an email composer + send emails res_ids = self.get_remaining_recipients(cr, uid, mailing, context=context) if not res_ids: - raise Warning('Please select recipients.') + raise UserError(_('Please select recipients.')) if context: comp_ctx = dict(context, active_ids=res_ids) diff --git a/addons/membership/membership.py b/addons/membership/membership.py index fb4b167c43d..b4588b09df6 100644 --- a/addons/membership/membership.py +++ b/addons/membership/membership.py @@ -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 STATE = [ ('none', 'Non Member'), @@ -399,11 +400,9 @@ class Partner(osv.osv): fpos_id = partner.property_account_position and partner.property_account_position.id or False addr = self.address_get(cr, uid, [partner.id], ['invoice']) if partner.free_member: - raise osv.except_osv(_('Error!'), - _("Partner is a free Member.")) + raise UserError(_("Partner is a free Member.")) if not addr.get('invoice', False): - raise osv.except_osv(_('Error!'), - _("Partner doesn't have an address to make the invoice.")) + raise UserError(_("Partner doesn't have an address to make the invoice.")) quantity = 1 line_value = { 'product_id': product_id, diff --git a/addons/mrp/mrp.py b/addons/mrp/mrp.py index f4967baf447..74fdbaea709 100644 --- a/addons/mrp/mrp.py +++ b/addons/mrp/mrp.py @@ -21,12 +21,12 @@ import time import openerp.addons.decimal_precision as dp -from openerp.osv import fields, osv, orm +from openerp.osv import fields, osv from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT -from openerp.tools import float_compare from openerp.tools.translate import _ from openerp import tools, SUPERUSER_ID from openerp.addons.product import _common +from openerp.exceptions import UserError, AccessError class mrp_property_group(osv.osv): @@ -286,7 +286,7 @@ class mrp_bom(osv.osv): continue if previous_products and bom_line_id.product_id.product_tmpl_id.id in previous_products: - raise osv.except_osv(_('Invalid Action!'), _('BoM "%s" contains a BoM line with a product recursion: "%s".') % (master_bom.name,bom_line_id.product_id.name_get()[0][1])) + raise UserError(_('BoM "%s" contains a BoM line with a product recursion: "%s".') % (master_bom.name,bom_line_id.product_id.name_get()[0][1])) quantity = _factor(bom_line_id.product_qty * factor, bom_line_id.product_efficiency, bom_line_id.product_rounding) bom_id = self._bom_find(cr, uid, product_id=bom_line_id.product_id.id, properties=properties, context=context) @@ -312,7 +312,7 @@ class mrp_bom(osv.osv): result = result + res[0] result2 = result2 + res[1] else: - raise osv.except_osv(_('Invalid Action!'), _('BoM "%s" contains a phantom BoM line but the product "%s" does not have any BoM defined.') % (master_bom.name,bom_line_id.product_id.name_get()[0][1])) + raise UserError(_('BoM "%s" contains a phantom BoM line but the product "%s" does not have any BoM defined.') % (master_bom.name,bom_line_id.product_id.name_get()[0][1])) return result, result2 @@ -336,7 +336,7 @@ class mrp_bom(osv.osv): def unlink(self, cr, uid, ids, context=None): if self.pool['mrp.production'].search(cr, uid, [('bom_id', 'in', ids), ('state', 'not in', ['done', 'cancel'])], context=context): - raise osv.except_osv(_('Warning!'), _('You can not delete a Bill of Material with running manufacturing orders.\nPlease close or cancel it first.')) + raise UserError(_('You can not delete a Bill of Material with running manufacturing orders.\nPlease close or cancel it first.')) return super(mrp_bom, self).unlink(cr, uid, ids, context=context) def onchange_product_tmpl_id(self, cr, uid, ids, product_tmpl_id, product_qty=0, context=None): @@ -478,7 +478,7 @@ class mrp_production(osv.osv): try: location_model, location_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'stock', 'stock_location_stock') self.pool.get('stock.location').check_access_rule(cr, uid, [location_id], 'read', context=context) - except (orm.except_orm, ValueError): + except (AccessError, ValueError): location_id = False return location_id @@ -486,7 +486,7 @@ class mrp_production(osv.osv): try: location_model, location_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'stock', 'stock_location_stock') self.pool.get('stock.location').check_access_rule(cr, uid, [location_id], 'read', context=context) - except (orm.except_orm, ValueError): + except (AccessError, ValueError): location_id = False return location_id @@ -618,7 +618,7 @@ class mrp_production(osv.osv): def unlink(self, cr, uid, ids, context=None): for production in self.browse(cr, uid, ids, context=context): if production.state not in ('draft', 'cancel'): - raise osv.except_osv(_('Invalid Action!'), _('Cannot delete a manufacturing order in state \'%s\'.') % production.state) + raise UserError(_('Cannot delete a manufacturing order in state \'%s\'.') % production.state) return super(mrp_production, self).unlink(cr, uid, ids, context=context) def location_id_change(self, cr, uid, ids, src, dest, context=None): @@ -705,7 +705,7 @@ class mrp_production(osv.osv): self.write(cr, uid, [production.id], {'bom_id': bom_id, 'routing_id': routing_id}) if not bom_id: - raise osv.except_osv(_('Error!'), _("Cannot find a bill of material for this product.")) + raise UserError(_("Cannot find a bill of material for this product.")) # get components and workcenter_lines from BoM structure factor = uom_obj._compute_qty(cr, uid, production.product_uom.id, production.product_qty, bom_point.product_uom.id) diff --git a/addons/mrp/stock.py b/addons/mrp/stock.py index e22105edd42..70e0f4a9ee3 100644 --- a/addons/mrp/stock.py +++ b/addons/mrp/stock.py @@ -26,6 +26,7 @@ from openerp.osv import osv from openerp.tools.translate import _ from openerp import SUPERUSER_ID from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT, float_compare +from openerp.exceptions import UserError class StockMove(osv.osv): _inherit = 'stock.move' @@ -39,9 +40,9 @@ class StockMove(osv.osv): def check_tracking(self, cr, uid, move, lot_id, context=None): super(StockMove, self).check_tracking(cr, uid, move, lot_id, context=context) if move.product_id.track_production and (move.location_id.usage == 'production' or move.location_dest_id.usage == 'production') and not lot_id: - raise osv.except_osv(_('Warning!'), _('You must assign a serial number for the product %s') % (move.product_id.name)) + raise UserError(_('You must assign a serial number for the product %s') % (move.product_id.name)) if move.raw_material_production_id and move.location_dest_id.usage == 'production' and move.raw_material_production_id.product_id.track_production and not move.consumed_for: - raise osv.except_osv(_('Warning!'), _("Because the product %s requires it, you must assign a serial number to your raw material %s to proceed further in your production. Please use the 'Produce' button to do so.") % (move.raw_material_production_id.product_id.name, move.product_id.name)) + raise UserError(_("Because the product %s requires it, you must assign a serial number to your raw material %s to proceed further in your production. Please use the 'Produce' button to do so.") % (move.raw_material_production_id.product_id.name, move.product_id.name)) def _check_phantom_bom(self, cr, uid, move, context=None): """check if product associated to move has a phantom bom @@ -166,7 +167,7 @@ class StockMove(osv.osv): production_obj = self.pool.get('mrp.production') if product_qty <= 0: - raise osv.except_osv(_('Warning!'), _('Please provide proper quantity.')) + raise UserError(_('Please provide proper quantity.')) #because of the action_confirm that can create extra moves in case of phantom bom, we need to make 2 loops ids2 = [] for move in self.browse(cr, uid, ids, context=context): @@ -180,7 +181,7 @@ class StockMove(osv.osv): prod_orders.add(move.raw_material_production_id.id or move.production_id.id) move_qty = move.product_qty if move_qty <= 0: - raise osv.except_osv(_('Error!'), _('Cannot consume a move with negative or zero quantity.')) + raise UserError(_('Cannot consume a move with negative or zero quantity.')) quantity_rest = move_qty - product_qty # Compare with numbers of move uom as we want to avoid a split with 0 qty quantity_rest_uom = move.product_uom_qty - self.pool.get("product.uom")._compute_qty_obj(cr, uid, move.product_id.uom_id, product_qty, move.product_uom) @@ -256,7 +257,7 @@ class stock_warehouse(osv.osv): manufacture_route_id = route_obj.search(cr, uid, [('name', 'like', _('Manufacture'))], context=context) manufacture_route_id = manufacture_route_id and manufacture_route_id[0] or False if not manufacture_route_id: - raise osv.except_osv(_('Error!'), _('Can\'t find any generic Manufacture route.')) + raise UserError(_('Can\'t find any generic Manufacture route.')) return { 'name': self._format_routename(cr, uid, warehouse, _(' Manufacture'), context=context), diff --git a/addons/mrp/wizard/change_production_qty.py b/addons/mrp/wizard/change_production_qty.py index 2f7e223fe17..30e54424f43 100644 --- a/addons/mrp/wizard/change_production_qty.py +++ b/addons/mrp/wizard/change_production_qty.py @@ -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 change_production_qty(osv.osv_memory): _name = 'change.production.qty' @@ -80,12 +81,12 @@ class change_production_qty(osv.osv_memory): if not bom_point: bom_id = bom_obj._bom_find(cr, uid, product_id=prod.product_id.id, context=context) if not bom_id: - raise osv.except_osv(_('Error!'), _("Cannot find bill of material for this product.")) + raise UserError(_("Cannot find bill of material for this product.")) prod_obj.write(cr, uid, [prod.id], {'bom_id': bom_id}) bom_point = bom_obj.browse(cr, uid, [bom_id])[0] if not bom_id: - raise osv.except_osv(_('Error!'), _("Cannot find bill of material for this product.")) + raise UserError(_("Cannot find bill of material for this product.")) factor = prod.product_qty * prod.product_uom.factor / bom_point.product_uom.factor product_details, workcenter_details = \ diff --git a/addons/mrp_operations/mrp_operations.py b/addons/mrp_operations/mrp_operations.py index 1f1624b94ee..2aaf1e1bf17 100644 --- a/addons/mrp_operations/mrp_operations.py +++ b/addons/mrp_operations/mrp_operations.py @@ -24,6 +24,7 @@ from openerp.osv import osv import time from datetime import datetime from openerp.tools.translate import _ +from openerp.exceptions import UserError #---------------------------------------------------------- # Work Centers @@ -119,7 +120,7 @@ class mrp_production_workcenter_line(osv.osv): elif prod_obj.state =='in_production': return else: - raise osv.except_osv(_('Error!'),_('Manufacturing order cannot be started in state "%s"!') % (prod_obj.state,)) + raise UserError(_('Manufacturing order cannot be started in state "%s"!') % (prod_obj.state,)) else: open_count = self.search_count(cr,uid,[('production_id','=',prod_obj.id), ('state', '!=', 'done')]) flag = not bool(open_count) @@ -431,37 +432,37 @@ class mrp_operations_operation(osv.osv): if not oper_objs: if code.start_stop!='start': - raise osv.except_osv(_('Sorry!'),_('Operation is not started yet!')) + raise UserError(_('Operation is not started yet!')) return False else: for oper in oper_objs: code_lst.append(oper.code_id.start_stop) if code.start_stop=='start': if 'start' in code_lst: - raise osv.except_osv(_('Sorry!'),_('Operation has already started! You can either Pause/Finish/Cancel the operation.')) + raise UserError(_('Operation has already started! You can either Pause/Finish/Cancel the operation.')) return False if code.start_stop=='pause': if code_lst[len(code_lst)-1]!='resume' and code_lst[len(code_lst)-1]!='start': - raise osv.except_osv(_('Error!'),_('In order to Pause the operation, it must be in the Start or Resume state!')) + raise UserError(_('In order to Pause the operation, it must be in the Start or Resume state!')) return False if code.start_stop=='resume': if code_lst[len(code_lst)-1]!='pause': - raise osv.except_osv(_('Error!'),_('In order to Resume the operation, it must be in the Pause state!')) + raise UserError(_('In order to Resume the operation, it must be in the Pause state!')) return False if code.start_stop=='done': if code_lst[len(code_lst)-1]!='start' and code_lst[len(code_lst)-1]!='resume': - raise osv.except_osv(_('Sorry!'),_('In order to Finish the operation, it must be in the Start or Resume state!')) + raise UserError(_('In order to Finish the operation, it must be in the Start or Resume state!')) return False if 'cancel' in code_lst: - raise osv.except_osv(_('Sorry!'),_('Operation is Already Cancelled!')) + raise UserError(_('Operation is Already Cancelled!')) return False if code.start_stop=='cancel': if not 'start' in code_lst : - raise osv.except_osv(_('Error!'),_('No operation to cancel.')) + raise UserError(_('No operation to cancel.')) return False if 'done' in code_lst: - raise osv.except_osv(_('Error!'),_('Operation is already finished!')) + raise UserError(_('Operation is already finished!')) return False return True diff --git a/addons/mrp_repair/mrp_repair.py b/addons/mrp_repair/mrp_repair.py index 32d9da3c832..2ef40504c49 100644 --- a/addons/mrp_repair/mrp_repair.py +++ b/addons/mrp_repair/mrp_repair.py @@ -23,6 +23,7 @@ from openerp.osv import fields, osv from datetime import datetime from openerp.tools.translate import _ import openerp.addons.decimal_precision as dp +from openerp.exceptions import UserError class mrp_repair(osv.osv): _name = 'mrp.repair' @@ -286,7 +287,7 @@ class mrp_repair(osv.osv): self.write(cr, uid, [o.id], {'state': 'confirmed'}) for line in o.operations: if line.product_id.track_production: - raise osv.except_osv(_('Warning!'), _("Serial number is required for operation line with product '%s'") % (line.product_id.name)) + raise UserError(_("Serial number is required for operation line with product '%s'") % (line.product_id.name)) mrp_line_obj.write(cr, uid, [l.id for l in o.operations], {'state': 'confirmed'}) return True @@ -299,7 +300,7 @@ class mrp_repair(osv.osv): if not repair.invoiced: mrp_line_obj.write(cr, uid, [l.id for l in repair.operations], {'state': 'cancel'}, context=context) else: - raise osv.except_osv(_('Warning!'), _('Repair order is already invoiced.')) + raise UserError(_('Repair order is already invoiced.')) return self.write(cr, uid, ids, {'state': 'cancel'}) def wkf_invoice_create(self, cr, uid, ids, *args): @@ -322,7 +323,7 @@ class mrp_repair(osv.osv): if repair.state in ('draft', 'cancel') or repair.invoice_id: continue if not (repair.partner_id.id and repair.partner_invoice_id.id): - raise osv.except_osv(_('No partner!'), _('You have to select a Partner Invoice Address in the repair form!')) + raise UserError(_('You have to select a Partner Invoice Address in the repair form!')) comment = repair.quotation_notes if (repair.invoice_method != 'none'): if group and repair.partner_invoice_id.id in invoices_group: @@ -336,7 +337,7 @@ class mrp_repair(osv.osv): inv_obj.write(cr, uid, [inv_id], invoice_vals, context=context) else: if not repair.partner_id.property_account_receivable: - raise osv.except_osv(_('Error!'), _('No account defined for partner "%s".') % repair.partner_id.name) + raise UserError(_('No account defined for partner "%s".') % repair.partner_id.name) account_id = repair.partner_id.property_account_receivable.id inv = { 'name': repair.name, @@ -364,7 +365,7 @@ class mrp_repair(osv.osv): elif operation.product_id.categ_id.property_account_income_categ: account_id = operation.product_id.categ_id.property_account_income_categ.id else: - raise osv.except_osv(_('Error!'), _('No account defined for product "%s".') % operation.product_id.name) + raise UserError(_('No account defined for product "%s".') % operation.product_id.name) invoice_line_id = inv_line_obj.create(cr, uid, { 'invoice_id': inv_id, @@ -386,14 +387,14 @@ class mrp_repair(osv.osv): else: name = fee.name if not fee.product_id: - raise osv.except_osv(_('Warning!'), _('No product defined on Fees!')) + raise UserError(_('No product defined on Fees!')) if fee.product_id.property_account_income: account_id = fee.product_id.property_account_income.id elif fee.product_id.categ_id.property_account_income_categ: account_id = fee.product_id.categ_id.property_account_income_categ.id else: - raise osv.except_osv(_('Error!'), _('No account defined for product "%s".') % fee.product_id.name) + raise UserError(_('No account defined for product "%s".') % fee.product_id.name) invoice_fee_id = inv_line_obj.create(cr, uid, { 'invoice_id': inv_id, diff --git a/addons/mrp_repair/wizard/cancel_repair.py b/addons/mrp_repair/wizard/cancel_repair.py index 36cdb8bb3f9..04c383ff4e9 100644 --- a/addons/mrp_repair/wizard/cancel_repair.py +++ b/addons/mrp_repair/wizard/cancel_repair.py @@ -21,6 +21,7 @@ from openerp.osv import osv,fields from openerp.tools.translate import _ +from openerp.exceptions import UserError class repair_cancel(osv.osv_memory): _name = 'mrp.repair.cancel' @@ -46,7 +47,7 @@ class repair_cancel(osv.osv_memory): if repair_order.invoiced or repair_order.invoice_method == 'none': repair_order_obj.action_cancel(cr, uid, [record_id], context=context) else: - raise osv.except_osv(_('Warning!'),_('Repair order is not invoiced.')) + raise UserError(_('Repair order is not invoiced.')) return {'type': 'ir.actions.act_window_close'} diff --git a/addons/pad/pad.py b/addons/pad/pad.py index 491e3142c34..2cd22e0f6ca 100644 --- a/addons/pad/pad.py +++ b/addons/pad/pad.py @@ -9,6 +9,7 @@ from openerp import SUPERUSER_ID from openerp.tools.translate import _ from openerp.tools import html2plaintext from py_etherpad import EtherpadLiteClient +from openerp.exceptions import UserError _logger = logging.getLogger(__name__) @@ -49,8 +50,7 @@ class pad_common(osv.osv_memory): try: myPad.createPad(path) except urllib2.URLError: - raise osv.except_osv(_("Error"), _("Pad creation failed, \ - either there is a problem with your pad server URL or with your connection.")) + raise UserError(_("Pad creation failed, either there is a problem with your pad server URL or with your connection.")) #get attr on the field model model = self.pool[context["model"]] diff --git a/addons/payment_adyen/models/adyen.py b/addons/payment_adyen/models/adyen.py index ab210fed890..8caab19e45c 100644 --- a/addons/payment_adyen/models/adyen.py +++ b/addons/payment_adyen/models/adyen.py @@ -14,6 +14,7 @@ from openerp.addons.payment.models.payment_acquirer import ValidationError from openerp.addons.payment_adyen.controllers.main import AdyenController from openerp.osv import osv, fields from openerp.tools import float_round +from openerp.tools.translate import _ _logger = logging.getLogger(__name__) @@ -114,26 +115,26 @@ class TxAdyen(osv.Model): def _adyen_form_get_tx_from_data(self, cr, uid, data, context=None): reference, pspReference = data.get('merchantReference'), data.get('pspReference') if not reference or not pspReference: - error_msg = 'Adyen: received data with missing reference (%s) or missing pspReference (%s)' % (reference, pspReference) - _logger.error(error_msg) + error_msg = _('Adyen: received data with missing reference (%s) or missing pspReference (%s)') % (reference, pspReference) + _logger.info(error_msg) raise ValidationError(error_msg) # find tx -> @TDENOTE use pspReference ? tx_ids = self.pool['payment.transaction'].search(cr, uid, [('reference', '=', reference)], context=context) if not tx_ids or len(tx_ids) > 1: - error_msg = 'Adyen: received data for reference %s' % (reference) + error_msg = _('Adyen: received data for reference %s') % (reference) if not tx_ids: - error_msg += '; no order found' + error_msg += _('; no order found') else: - error_msg += '; multiple order found' - _logger.error(error_msg) + error_msg += _('; multiple order found') + _logger.info(error_msg) raise ValidationError(error_msg) tx = self.pool['payment.transaction'].browse(cr, uid, tx_ids[0], context=context) # verify shasign shasign_check = self.pool['payment.acquirer']._adyen_generate_merchant_sig(tx.acquirer_id, 'out', data) if shasign_check != data.get('merchantSig'): - error_msg = 'Adyen: invalid merchantSig, received %s, computed %s' % (data.get('merchantSig'), shasign_check) + error_msg = _('Adyen: invalid merchantSig, received %s, computed %s') % (data.get('merchantSig'), shasign_check) _logger.warning(error_msg) # raise ValidationError(error_msg) @@ -171,7 +172,7 @@ class TxAdyen(osv.Model): }) return True else: - error = 'Paypal: feedback error' + error = _('Paypal: feedback error') _logger.info(error) tx.write({ 'state': 'error', diff --git a/addons/payment_adyen/tests/test_adyen.py b/addons/payment_adyen/tests/test_adyen.py index c4e9356136c..223d0274b3f 100644 --- a/addons/payment_adyen/tests/test_adyen.py +++ b/addons/payment_adyen/tests/test_adyen.py @@ -6,7 +6,6 @@ import urlparse from openerp.addons.payment.models.payment_acquirer import ValidationError from openerp.addons.payment.tests.common import PaymentAcquirerCommon from openerp.addons.payment_adyen.controllers.main import AdyenController -from openerp.osv.orm import except_orm from openerp.tools import mute_logger diff --git a/addons/payment_buckaroo/models/buckaroo.py b/addons/payment_buckaroo/models/buckaroo.py index 41c143fad27..5b0530a60de 100644 --- a/addons/payment_buckaroo/models/buckaroo.py +++ b/addons/payment_buckaroo/models/buckaroo.py @@ -7,6 +7,7 @@ from openerp.addons.payment.models.payment_acquirer import ValidationError from openerp.addons.payment_buckaroo.controllers.main import BuckarooController from openerp.osv import osv, fields from openerp.tools.float_utils import float_compare +from openerp.tools.translate import _ _logger = logging.getLogger(__name__) @@ -125,26 +126,26 @@ class TxBuckaroo(osv.Model): transaction record. """ reference, pay_id, shasign = data.get('BRQ_INVOICENUMBER'), data.get('BRQ_PAYMENT'), data.get('BRQ_SIGNATURE') if not reference or not pay_id or not shasign: - error_msg = 'Buckaroo: received data with missing reference (%s) or pay_id (%s) or shashign (%s)' % (reference, pay_id, shasign) - _logger.error(error_msg) + error_msg = _('Buckaroo: received data with missing reference (%s) or pay_id (%s) or shashign (%s)') % (reference, pay_id, shasign) + _logger.info(error_msg) raise ValidationError(error_msg) tx_ids = self.search(cr, uid, [('reference', '=', reference)], context=context) if not tx_ids or len(tx_ids) > 1: - error_msg = 'Buckaroo: received data for reference %s' % (reference) + error_msg = _('Buckaroo: received data for reference %s') % (reference) if not tx_ids: - error_msg += '; no order found' + error_msg += _('; no order found') else: - error_msg += '; multiple order found' - _logger.error(error_msg) + error_msg += _('; multiple order found') + _logger.info(error_msg) raise ValidationError(error_msg) tx = self.pool['payment.transaction'].browse(cr, uid, tx_ids[0], context=context) #verify shasign shasign_check = self.pool['payment.acquirer']._buckaroo_generate_digital_sign(tx.acquirer_id, 'out' ,data) if shasign_check.upper() != shasign.upper(): - error_msg = 'Buckaroo: invalid shasign, received %s, computed %s, for data %s' % (shasign, shasign_check, data) - _logger.error(error_msg) + error_msg = _('Buckaroo: invalid shasign, received %s, computed %s, for data %s') % (shasign, shasign_check, data) + _logger.info(error_msg) raise ValidationError(error_msg) return tx diff --git a/addons/payment_ogone/models/ogone.py b/addons/payment_ogone/models/ogone.py index b94b34f77d8..ea7434a80ec 100644 --- a/addons/payment_ogone/models/ogone.py +++ b/addons/payment_ogone/models/ogone.py @@ -3,6 +3,7 @@ from hashlib import sha1 import logging from lxml import etree, objectify +from openerp.tools.translate import _ from pprint import pformat import time from urllib import urlencode @@ -196,27 +197,27 @@ class PaymentTxOgone(osv.Model): transaction record. """ reference, pay_id, shasign = data.get('orderID'), data.get('PAYID'), data.get('SHASIGN') if not reference or not pay_id or not shasign: - error_msg = 'Ogone: received data with missing reference (%s) or pay_id (%s) or shashign (%s)' % (reference, pay_id, shasign) - _logger.error(error_msg) + error_msg = _('Ogone: received data with missing reference (%s) or pay_id (%s) or shashign (%s)') % (reference, pay_id, shasign) + _logger.info(error_msg) raise ValidationError(error_msg) # find tx -> @TDENOTE use paytid ? tx_ids = self.search(cr, uid, [('reference', '=', reference)], context=context) if not tx_ids or len(tx_ids) > 1: - error_msg = 'Ogone: received data for reference %s' % (reference) + error_msg = _('Ogone: received data for reference %s') % (reference) if not tx_ids: - error_msg += '; no order found' + error_msg += _('; no order found') else: - error_msg += '; multiple order found' - _logger.error(error_msg) + error_msg += _('; multiple order found') + _logger.info(error_msg) raise ValidationError(error_msg) tx = self.pool['payment.transaction'].browse(cr, uid, tx_ids[0], context=context) # verify shasign shasign_check = self.pool['payment.acquirer']._ogone_generate_shasign(tx.acquirer_id, 'out', data) if shasign_check.upper() != shasign.upper(): - error_msg = 'Ogone: invalid shasign, received %s, computed %s, for data %s' % (shasign, shasign_check, data) - _logger.error(error_msg) + error_msg = _('Ogone: invalid shasign, received %s, computed %s, for data %s') % (shasign, shasign_check, data) + _logger.info(error_msg) raise ValidationError(error_msg) return tx @@ -237,7 +238,7 @@ class PaymentTxOgone(osv.Model): def _ogone_form_validate(self, cr, uid, tx, data, context=None): if tx.state == 'done': - _logger.warning('Ogone: trying to validate an already validated tx (ref %s)' % tx.reference) + _logger.info('Ogone: trying to validate an already validated tx (ref %s)', tx.reference) return True status = int(data.get('STATUS', '0')) @@ -330,7 +331,7 @@ class PaymentTxOgone(osv.Model): if error_code: error_msg = ogone.OGONE_ERROR_MAP.get(error_code) error = '%s\n\n%s: %s' % (error_str, error_code, error_msg) - _logger.error(error) + _logger.info(error) raise Exception(error) # TODO specific exception tx.write({'partner_reference': alias}) diff --git a/addons/payment_paypal/models/paypal.py b/addons/payment_paypal/models/paypal.py index 2bdaead2c5d..6aa86631653 100644 --- a/addons/payment_paypal/models/paypal.py +++ b/addons/payment_paypal/models/paypal.py @@ -15,6 +15,7 @@ from openerp.addons.payment_paypal.controllers.main import PaypalController from openerp.osv import osv, fields from openerp.tools.float_utils import float_compare from openerp import SUPERUSER_ID +from openerp.tools.translate import _ _logger = logging.getLogger(__name__) @@ -185,8 +186,8 @@ class TxPaypal(osv.Model): def _paypal_form_get_tx_from_data(self, cr, uid, data, context=None): reference, txn_id = data.get('item_number'), data.get('txn_id') if not reference or not txn_id: - error_msg = 'Paypal: received data with missing reference (%s) or txn_id (%s)' % (reference, txn_id) - _logger.error(error_msg) + error_msg = _('Paypal: received data with missing reference (%s) or txn_id (%s)') % (reference, txn_id) + _logger.info(error_msg) raise ValidationError(error_msg) # find tx -> @TDENOTE use txn_id ? @@ -197,7 +198,7 @@ class TxPaypal(osv.Model): error_msg += '; no order found' else: error_msg += '; multiple order found' - _logger.error(error_msg) + _logger.info(error_msg) raise ValidationError(error_msg) return self.browse(cr, uid, tx_ids[0], context=context) diff --git a/addons/payment_transfer/models/payment_acquirer.py b/addons/payment_transfer/models/payment_acquirer.py index 18b0bfd5c63..b55fb055ab7 100644 --- a/addons/payment_transfer/models/payment_acquirer.py +++ b/addons/payment_transfer/models/payment_acquirer.py @@ -61,12 +61,12 @@ class TransferPaymentTransaction(osv.Model): ], context=context) if not tx_ids or len(tx_ids) > 1: - error_msg = 'received data for reference %s' % (pprint.pformat(reference)) + error_msg = _('received data for reference %s') % (pprint.pformat(reference)) if not tx_ids: - error_msg += '; no order found' + error_msg += _('; no order found') else: - error_msg += '; multiple order found' - _logger.error(error_msg) + error_msg += _('; multiple order found') + _logger.info(error_msg) raise ValidationError(error_msg) return self.browse(cr, uid, tx_ids[0], context=context) diff --git a/addons/point_of_sale/point_of_sale.py b/addons/point_of_sale/point_of_sale.py index 9cb42c3975c..a4a0807411e 100644 --- a/addons/point_of_sale/point_of_sale.py +++ b/addons/point_of_sale/point_of_sale.py @@ -27,7 +27,7 @@ import sets from openerp import tools, models from openerp.osv import fields, osv from openerp.tools.translate import _ -from openerp.exceptions import Warning +from openerp.exceptions import UserError import openerp.addons.decimal_precision as dp import openerp.addons.product.product @@ -402,8 +402,7 @@ class pos_session(osv.osv): context = dict(context or {}) config_id = values.get('config_id', False) or context.get('default_config_id', False) if not config_id: - raise osv.except_osv( _('Error!'), - _("You should assign a Point of Sale to your session.")) + raise UserError(_("You should assign a Point of Sale to your session.")) # journal_id is not required on the pos_config because it does not # exists at the installation. If nothing is configured at the @@ -417,8 +416,7 @@ class pos_session(osv.osv): if jid: jobj.write(cr, uid, [pos_config.id], {'journal_id': jid}, context=context) else: - raise osv.except_osv( _('error!'), - _("Unable to open the session. You have to assign a sale journal to your point of sale.")) + raise UserError(_("Unable to open the session. You have to assign a sale journal to your point of sale.")) # define some cash journal if no payment method exists if not pos_config.journal_ids: @@ -515,11 +513,9 @@ class pos_session(osv.osv): if abs(st.difference) > st.journal_id.amount_authorized_diff: # The pos manager can close statements with maximums. if not self.pool.get('ir.model.access').check_groups(cr, uid, "point_of_sale.group_pos_manager"): - raise osv.except_osv( _('Error!'), - _("Your ending balance is too different from the theoretical cash closing (%.2f), the maximum allowed is: %.2f. You can contact your manager to force it.") % (st.difference, st.journal_id.amount_authorized_diff)) + raise UserError(_("Your ending balance is too different from the theoretical cash closing (%.2f), the maximum allowed is: %.2f. You can contact your manager to force it.") % (st.difference, st.journal_id.amount_authorized_diff)) if (st.journal_id.type not in ['bank', 'cash']): - raise osv.except_osv(_('Error!'), - _("The type of the journal for your payment method should be bank or cash ")) + raise UserError(_("The type of the journal for your payment method should be bank or cash ")) getattr(st, 'button_confirm_%s' % st.journal_id.type)(context=context) self._confirm_orders(cr, uid, ids, context=context) self.write(cr, uid, ids, {'state' : 'closed'}, context=context) @@ -547,9 +543,7 @@ class pos_session(osv.osv): if order.state == 'done': continue if order.state not in ('paid', 'invoiced'): - raise osv.except_osv( - _('Error!'), - _("You cannot confirm all orders of this session, because they have not the 'paid' status")) + raise UserError(_("You cannot confirm all orders of this session, because they have not the 'paid' status")) else: pos_order_obj.signal_workflow(cr, uid, [order.id], 'done') @@ -562,9 +556,8 @@ class pos_session(osv.osv): return {} for session in self.browse(cr, uid, ids, context=context): if session.user_id.id != uid: - raise osv.except_osv( - _('Error!'), - _("You cannot use the session of another users. This session is owned by %s. Please first close this one to use this point of sale." % session.user_id.name)) + raise UserError(_("You cannot use the session of another users. This session is owned by %s. " + "Please first close this one to use this point of sale.") % session.user_id.name) context.update({'active_id': ids[0]}) return { 'type' : 'ir.actions.act_url', @@ -624,7 +617,7 @@ class pos_order(osv.osv): if not cash_journal: cash_journal_ids = filter(lambda st: st.journal_id.type=='cash', session.statement_ids) if not len(cash_journal_ids): - raise Warning(_("No cash statement found for this session. Unable to record returned cash.")) + raise UserError(_("No cash statement found for this session. Unable to record returned cash.")) cash_journal = cash_journal_ids[0].journal_id self.add_payment(cr, uid, order_id, { 'amount': -order['amount_return'], @@ -654,7 +647,7 @@ class pos_order(osv.osv): if 'partner_id' in vals: for posorder in self.browse(cr, uid, ids, context=context): if posorder.invoice_id: - raise osv.except_osv( _('Error!'), _("You cannot change the partner of a POS order for which an invoice has already been issued.")) + raise UserError(_("You cannot change the partner of a POS order for which an invoice has already been issued.")) if vals['partner_id']: p_id = partner_obj.browse(cr, uid, vals['partner_id'], context=context) part_id = partner_obj._find_accounting_partner(p_id).id @@ -667,7 +660,7 @@ class pos_order(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'): - raise osv.except_osv(_('Unable to Delete!'), _('In order to delete a sale, it must be new or cancelled.')) + raise UserError(_('In order to delete a sale, it must be new or cancelled.')) return super(pos_order, self).unlink(cr, uid, ids, context=context) def onchange_partner_id(self, cr, uid, ids, part=False, context=None): @@ -813,7 +806,7 @@ class pos_order(osv.osv): destination_id = order.partner_id.property_stock_customer.id elif picking_type: if not picking_type.default_location_dest_id: - raise osv.except_osv(_('Error!'), _('Missing source or destination location for picking type %s. Please configure those fields and try again.' % (picking_type.name,))) + raise UserError(_('Missing source or destination location for picking type %s. Please configure those fields and try again.' % (picking_type.name,))) destination_id = picking_type.default_location_dest_id.id else: destination_id = partner_obj.default_get(cr, uid, ['property_stock_customer'], context=context)['property_stock_customer'] @@ -855,7 +848,7 @@ class pos_order(osv.osv): for order in self.browse(cr, uid, ids, context=context): stock_picking_obj.action_cancel(cr, uid, [order.picking_id.id]) if stock_picking_obj.browse(cr, uid, order.picking_id.id, context=context).state <> 'cancel': - raise osv.except_osv(_('Error!'), _('Unable to cancel the picking.')) + raise UserError(_('Unable to cancel the picking.')) self.write(cr, uid, ids, {'state': 'cancel'}, context=context) return True @@ -888,7 +881,7 @@ class pos_order(osv.osv): msg = _('There is no receivable account defined to make payment.') else: msg = _('There is no receivable account defined to make payment for the partner: "%s" (id:%d).') % (order.partner_id.name, order.partner_id.id,) - raise osv.except_osv(_('Configuration Error!'), msg) + raise UserError(msg) context.pop('pos_session_id', False) @@ -901,7 +894,7 @@ class pos_order(osv.osv): break if not statement_id: - raise osv.except_osv(_('Error!'), _('You have to open at least one cashbox.')) + raise UserError(_('You have to open at least one cashbox.')) args.update({ 'statement_id': statement_id, @@ -924,7 +917,7 @@ class pos_order(osv.osv): ('state', '!=', 'closed'), ('user_id', '=', uid)], context=context) if not current_session_ids: - raise osv.except_osv(_('Error!'), _('To return product(s), you need to open a session that will be used to register the refund.')) + raise UserError(_('To return product(s), you need to open a session that will be used to register the refund.')) clone_id = self.copy(cr, uid, order.id, { 'name': order.name + ' REFUND', # not used, name forced by create @@ -968,7 +961,7 @@ class pos_order(osv.osv): continue if not order.partner_id: - raise osv.except_osv(_('Error!'), _('Please provide a partner for the sale.')) + raise UserError(_('Please provide a partner for the sale.')) acc = order.partner_id.property_account_receivable.id inv = { @@ -1047,7 +1040,7 @@ class pos_order(osv.osv): #session_ids = set(order.session_id for order in self.browse(cr, uid, ids, context=context)) if session and not all(session.id == order.session_id.id for order in self.browse(cr, uid, ids, context=context)): - raise osv.except_osv(_('Error!'), _('Selected orders do not have the same session!')) + raise UserError(_('Selected orders do not have the same session!')) grouped_data = {} have_to_group_by = session and session.config_id.group_by or False @@ -1162,9 +1155,9 @@ class pos_order(osv.osv): elif line.product_id.categ_id.property_account_income_categ.id: income_account = line.product_id.categ_id.property_account_income_categ.id else: - raise osv.except_osv(_('Error!'), _('Please define income '\ + raise UserError(_('Please define income '\ 'account for this product: "%s" (id:%d).') \ - % (line.product_id.name, line.product_id.id, )) + % (line.product_id.name, line.product_id.id)) # Empty the tax list as long as there is no tax code: tax_code_id = False @@ -1307,7 +1300,7 @@ class pos_order_line(osv.osv): if not product_id: return {} if not pricelist: - raise osv.except_osv(_('No Pricelist!'), + raise UserError( _('You have to select a pricelist in the sale form !\n' \ 'Please set one before choosing a product.')) diff --git a/addons/point_of_sale/report/pos_invoice.py b/addons/point_of_sale/report/pos_invoice.py index 6007b007639..70fe2974070 100644 --- a/addons/point_of_sale/report/pos_invoice.py +++ b/addons/point_of_sale/report/pos_invoice.py @@ -21,6 +21,7 @@ from openerp.osv import osv from openerp.tools.translate import _ +from openerp.exceptions import UserError class PosInvoiceReport(osv.AbstractModel): @@ -43,7 +44,7 @@ class PosInvoiceReport(osv.AbstractModel): if not_invoiced_orders_ids: not_invoiced_posorders = posorder_obj.browse(cr, uid, not_invoiced_orders_ids, context=context) not_invoiced_orders_names = list(map(lambda a: a.name, not_invoiced_posorders)) - raise osv.except_osv(_('Error!'), _('No link to an invoice for %s.' % ', '.join(not_invoiced_orders_names))) + raise UserError(_('No link to an invoice for %s.') % ', '.join(not_invoiced_orders_names)) docargs = { 'doc_ids': ids_to_print, diff --git a/addons/point_of_sale/wizard/pos_box.py b/addons/point_of_sale/wizard/pos_box.py index ad6719343d8..e013aea3167 100644 --- a/addons/point_of_sale/wizard/pos_box.py +++ b/addons/point_of_sale/wizard/pos_box.py @@ -1,6 +1,7 @@ from openerp.osv import osv from openerp.tools.translate import _ +from openerp.exceptions import UserError from openerp.addons.account.wizard.pos_box import CashBox @@ -19,8 +20,7 @@ class PosBox(CashBox): bank_statements = [record.cash_register_id for record in records if record.cash_register_id] if not bank_statements: - raise osv.except_osv(_('Error!'), - _("There is no cash register for this PoS Session")) + raise UserError(_("There is no cash register for this PoS Session")) return self._run(cr, uid, ids, bank_statements, context=context) else: diff --git a/addons/point_of_sale/wizard/pos_open_statement.py b/addons/point_of_sale/wizard/pos_open_statement.py index 83f6bca1163..4dd485d8cbd 100644 --- a/addons/point_of_sale/wizard/pos_open_statement.py +++ b/addons/point_of_sale/wizard/pos_open_statement.py @@ -21,6 +21,7 @@ from openerp.osv import osv from openerp.tools.translate import _ +from openerp.exceptions import UserError class pos_open_statement(osv.osv_memory): _name = 'pos.open.statement' @@ -46,7 +47,7 @@ class pos_open_statement(osv.osv_memory): st_ids = [] j_ids = journal_obj.search(cr, uid, [('journal_user','=',1)], context=context) if not j_ids: - raise osv.except_osv(_('No Cash Register Defined!'), _('You have to define which payment method must be available in the point of sale by reusing existing bank and cash through "Accounting / Configuration / Journals / Journals". Select a journal and check the field "PoS Payment Method" from the "Point of Sale" tab. You can also create new payment methods directly from menu "PoS Backend / Configuration / Payment Methods".')) + raise UserError(_('You have to define which payment method must be available in the point of sale by reusing existing bank and cash through "Accounting / Configuration / Journals / Journals". Select a journal and check the field "PoS Payment Method" from the "Point of Sale" tab. You can also create new payment methods directly from menu "PoS Backend / Configuration / Payment Methods".')) for journal in journal_obj.browse(cr, uid, j_ids, context=context): ids = statement_obj.search(cr, uid, [('state', '!=', 'confirm'), ('user_id', '=', uid), ('journal_id', '=', journal.id)], context=context) diff --git a/addons/portal/mail_message.py b/addons/portal/mail_message.py index 36b06484e9e..a54b4f423c4 100644 --- a/addons/portal/mail_message.py +++ b/addons/portal/mail_message.py @@ -20,7 +20,8 @@ ############################################################################## from openerp import SUPERUSER_ID -from openerp.osv import osv, orm +from openerp.osv import osv +from openerp.exceptions import AccessError from openerp.tools.translate import _ @@ -56,8 +57,7 @@ class mail_message(osv.Model): if group_user_id not in [group.id for group in group_ids]: cr.execute('SELECT DISTINCT id FROM "%s" WHERE type = %%s AND subtype_id IS NULL AND id = ANY (%%s)' % (self._table), ('comment', ids,)) if cr.fetchall(): - raise orm.except_orm(_('Access Denied'), - _('The requested operation cannot be completed due to security restrictions. Please contact your system administrator.\n\n(Document type: %s, Operation: %s)') % \ + raise AccessError(_('The requested operation cannot be completed due to security restrictions. Please contact your system administrator.\n\n(Document type: %s, Operation: %s)') % \ (self._description, operation)) return super(mail_message, self).check_access_rule(cr, uid, ids=ids, operation=operation, context=context) diff --git a/addons/portal/tests/test_portal.py b/addons/portal/tests/test_portal.py index 6a8242bf0cf..6e23ca3d50c 100644 --- a/addons/portal/tests/test_portal.py +++ b/addons/portal/tests/test_portal.py @@ -21,7 +21,6 @@ from openerp.addons.mail.tests.common import TestMail from openerp.exceptions import AccessError -from openerp.osv.orm import except_orm from openerp.tools.misc import mute_logger @@ -60,7 +59,7 @@ class test_portal(TestMail): # Do: Chell browses Pigs -> ko, employee group chell_pigs = self.mail_group.browse(cr, self.user_chell_id, self.group_pigs_id) - with self.assertRaises(except_orm): + with self.assertRaises(AccessError): trigger_read = chell_pigs.name # Do: Chell posts a message on Pigs, crash because can not write on group or is not in the followers @@ -77,7 +76,7 @@ class test_portal(TestMail): if partner.id == self.partner_chell_id: # Chell can read her own partner record continue - with self.assertRaises(except_orm): + with self.assertRaises(AccessError): trigger_read = partner.name # Do: Chell comments Pigs, ok because he is now in the followers @@ -99,7 +98,7 @@ class test_portal(TestMail): for message in chell_port.message_ids: trigger_read = message.subject for partner in chell_port.message_follower_ids: - with self.assertRaises(except_orm): + with self.assertRaises(AccessError): trigger_read = partner.name def test_10_mail_invite(self): @@ -225,5 +224,5 @@ class test_portal(TestMail): self.mail_message.read(cr, self.user_chell_id, msg_ids, ['body', 'type', 'subtype_id']) # Do: Chell read a message she should not be able to read - with self.assertRaises(except_orm): + with self.assertRaises(AccessError): self.mail_message.read(cr, self.user_chell_id, [msg4_id], ['body', 'type', 'subtype_id']) diff --git a/addons/portal/wizard/portal_wizard.py b/addons/portal/wizard/portal_wizard.py index 24158b41448..0571941b950 100644 --- a/addons/portal/wizard/portal_wizard.py +++ b/addons/portal/wizard/portal_wizard.py @@ -25,6 +25,7 @@ from openerp.osv import fields, osv from openerp.tools.translate import _ from openerp.tools import email_split from openerp import SUPERUSER_ID +from openerp.exceptions import UserError _logger = logging.getLogger(__name__) @@ -160,7 +161,7 @@ class wizard_user(osv.osv_memory): def action_apply(self, cr, uid, ids, context=None): error_msg = self.get_error_messages(cr, uid, ids, context=context) if error_msg: - raise osv.except_osv(_('Contacts Error'), "\n\n".join(error_msg)) + raise UserError( "\n\n".join(error_msg)) for wizard_user in self.browse(cr, SUPERUSER_ID, ids, context): portal = wizard_user.wizard_id.portal_id @@ -222,8 +223,7 @@ class wizard_user(osv.osv_memory): this_context = context this_user = self.pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context) if not this_user.email: - raise osv.except_osv(_('Email Required'), - _('You must have an email address in your User Preferences to send emails.')) + raise UserError(_('You must have an email address in your User Preferences to send emails.')) # determine subject and body in the portal user's language user = self._retrieve_user(cr, SUPERUSER_ID, wizard_user, context) diff --git a/addons/portal_project/tests/test_access_rights.py b/addons/portal_project/tests/test_access_rights.py index a4f29735a69..c1b75b07bff 100644 --- a/addons/portal_project/tests/test_access_rights.py +++ b/addons/portal_project/tests/test_access_rights.py @@ -21,7 +21,7 @@ from openerp.addons.project.tests.test_project_base import TestProjectBase from openerp.exceptions import AccessError -from openerp.osv.orm import except_orm +from openerp.exceptions import except_orm from openerp.tools import mute_logger @@ -156,7 +156,7 @@ class TestPortalProject(TestPortalProjectBase): self.project_project.read(cr, self.user_portal_id, [pigs_id], ['state']) # Do: Donovan reads project -> ko (public ko portal) - self.assertRaises(except_orm, self.project_project.read, cr, self.user_public_id, [pigs_id], ['state']) + self.assertRaises(AccessError, self.project_project.read, cr, self.user_public_id, [pigs_id], ['state']) # Test: no project task visible task_ids = self.project_task.search(cr, self.user_public_id, [('project_id', '=', pigs_id)]) self.assertFalse(task_ids, 'access rights: public user should not see tasks of a portal project') @@ -182,13 +182,13 @@ class TestPortalProject(TestPortalProjectBase): self.assertRaises(AccessError, self.project_project.read, cr, self.user_none_id, [pigs_id], ['state']) # Do: Chell reads project -> ko (portal ko employee) - self.assertRaises(except_orm, self.project_project.read, cr, self.user_portal_id, [pigs_id], ['state']) + self.assertRaises(AccessError, self.project_project.read, cr, self.user_portal_id, [pigs_id], ['state']) # Test: no project task visible + assigned task_ids = self.project_task.search(cr, self.user_portal_id, [('project_id', '=', pigs_id)]) self.assertFalse(task_ids, 'access rights: portal user should not see tasks of an employees project, even if assigned') # Do: Donovan reads project -> ko (public ko employee) - self.assertRaises(except_orm, self.project_project.read, cr, self.user_public_id, [pigs_id], ['state']) + self.assertRaises(AccessError, self.project_project.read, cr, self.user_public_id, [pigs_id], ['state']) # Test: no project task visible task_ids = self.project_task.search(cr, self.user_public_id, [('project_id', '=', pigs_id)]) self.assertFalse(task_ids, 'access rights: public user should not see tasks of an employees project') @@ -206,7 +206,7 @@ class TestPortalProject(TestPortalProjectBase): self.project_project.invalidate_cache(cr, uid) # Do: Alfred reads project -> ko (employee ko followers) - self.assertRaises(except_orm, self.project_project.read, cr, self.user_projectuser_id, [pigs_id], ['state']) + self.assertRaises(AccessError, self.project_project.read, cr, self.user_projectuser_id, [pigs_id], ['state']) # Test: no project task visible task_ids = self.project_task.search(cr, self.user_projectuser_id, [('project_id', '=', pigs_id)]) test_task_ids = set([self.task_4_id]) @@ -219,6 +219,7 @@ class TestPortalProject(TestPortalProjectBase): # Do: Chell reads project -> ko (portal ko followers) self.project_project.message_unsubscribe_users(cr, self.user_portal_id, [pigs_id], [self.user_portal_id]) self.assertRaises(except_orm, self.project_project.read, cr, self.user_portal_id, [pigs_id], ['state']) + # Test: no project task visible task_ids = self.project_task.search(cr, self.user_portal_id, [('project_id', '=', pigs_id)]) test_task_ids = set([self.task_5_id]) @@ -226,7 +227,7 @@ class TestPortalProject(TestPortalProjectBase): 'access rights: portal user should not see tasks of a not-followed followers project, only assigned') # Do: Donovan reads project -> ko (public ko employee) - self.assertRaises(except_orm, self.project_project.read, cr, self.user_public_id, [pigs_id], ['state']) + self.assertRaises(AccessError, self.project_project.read, cr, self.user_public_id, [pigs_id], ['state']) # Test: no project task visible task_ids = self.project_task.search(cr, self.user_public_id, [('project_id', '=', pigs_id)]) self.assertFalse(task_ids, 'access rights: public user should not see tasks of a followers project') @@ -242,6 +243,7 @@ class TestPortalProject(TestPortalProjectBase): self.project_project.read(cr, self.user_portal_id, [pigs_id], ['state']) # Do: Donovan reads project -> ko (public ko follower even if follower) + self.assertRaises(except_orm, self.project_project.read, cr, self.user_public_id, [pigs_id], ['state']) # Do: project user is follower of the project and can create a task @@ -256,6 +258,5 @@ class TestPortalProject(TestPortalProjectBase): ) # Do: project user can create a task without project - self.project_task.create(cr, self.user_projectuser_id, { - 'name': 'Pigs task', 'project_id': False - }, {'mail_create_nolog': True}) + self.project_task.create(cr, self.user_projectuser_id, {'name': 'Pigs task', 'project_id': False}, {'mail_create_nolog': True}) + \ No newline at end of file diff --git a/addons/procurement/procurement.py b/addons/procurement/procurement.py index c37dc68b3c3..816d999da47 100644 --- a/addons/procurement/procurement.py +++ b/addons/procurement/procurement.py @@ -27,6 +27,7 @@ from openerp.osv import fields, osv import openerp.addons.decimal_precision as dp from openerp.tools.translate import _ import openerp +from openerp.exceptions import UserError PROCUREMENT_PRIORITIES = [('0', 'Not urgent'), ('1', 'Normal'), ('2', 'Urgent'), ('3', 'Very Urgent')] @@ -152,8 +153,7 @@ class procurement_order(osv.osv): if s['state'] == 'cancel': unlink_ids.append(s['id']) else: - raise osv.except_osv(_('Invalid Action!'), - _('Cannot delete Procurement Order(s) which are in %s state.') % s['state']) + raise UserError(_('Cannot delete Procurement Order(s) which are in %s state.') % s['state']) return osv.osv.unlink(self, cr, uid, unlink_ids, context=context) def do_view_procurements(self, cr, uid, ids, context=None): diff --git a/addons/product/pricelist.py b/addons/product/pricelist.py index ef17133ba77..1821cfccc4b 100644 --- a/addons/product/pricelist.py +++ b/addons/product/pricelist.py @@ -24,9 +24,9 @@ import time from openerp import tools from openerp.osv import fields, osv from openerp.tools.translate import _ -from openerp.exceptions import except_orm import openerp.addons.decimal_precision as dp +from openerp.exceptions import UserError class price_type(osv.osv): @@ -212,7 +212,7 @@ class product_pricelist(osv.osv): version = v break if not version: - raise osv.except_osv(_('Warning!'), _("At least one pricelist has no active version !\nPlease create or activate one.")) + raise UserError(_("At least one pricelist has no active version !\nPlease create or activate one.")) categ_ids = {} for p in products: categ = p.categ_id diff --git a/addons/product/product.py b/addons/product/product.py index 83680510c81..c3e340618c1 100644 --- a/addons/product/product.py +++ b/addons/product/product.py @@ -33,6 +33,8 @@ import psycopg2 import openerp.addons.decimal_precision as dp from openerp.tools.float_utils import float_round, float_compare +from openerp.exceptions import UserError +from openerp.exceptions import except_orm def ean_checksum(eancode): """returns the checksum of an ean string of length 13, returns -1 if the string has the wrong length""" @@ -166,7 +168,7 @@ class product_uom(osv.osv): context = {} if from_unit.category_id.id != to_unit.category_id.id: if context.get('raise-exception', True): - raise osv.except_osv(_('Error!'), _('Conversion from Product UoM %s to Default UoM %s is not possible as they both belong to different Category!.') % (from_unit.name,to_unit.name,)) + raise UserError(_('Conversion from Product UoM %s to Default UoM %s is not possible as they both belong to different Category!.') % (from_unit.name,to_unit.name)) else: return qty amount = qty/from_unit.factor @@ -199,7 +201,7 @@ class product_uom(osv.osv): if 'category_id' in vals: for uom in self.browse(cr, uid, ids, context=context): if uom.category_id.id != vals['category_id']: - raise osv.except_osv(_('Warning!'),_("Cannot change the category of existing Unit of Measure '%s'.") % (uom.name,)) + raise UserError(_("Cannot change the category of existing Unit of Measure '%s'.") % (uom.name,)) return super(product_uom, self).write(cr, uid, ids, vals, context=context) @@ -384,7 +386,7 @@ class product_attribute_value(osv.osv): ctx = dict(context or {}, active_test=False) product_ids = self.pool['product.product'].search(cr, uid, [('attribute_value_ids', 'in', ids)], context=ctx) if product_ids: - raise osv.except_osv(_('Integrity Error!'), _('The operation cannot be completed:\nYou trying to delete an attribute value with a reference on a product variant.')) + raise UserError(_('The operation cannot be completed:\nYou trying to delete an attribute value with a reference on a product variant.')) return super(product_attribute_value, self).unlink(cr, uid, ids, context=context) class product_attribute_price(osv.osv): @@ -690,7 +692,8 @@ class product_template(osv.osv): try: with cr.savepoint(): product_obj.unlink(cr, uid, [variant_id], context=ctx) - except (psycopg2.Error, osv.except_osv): + #We catch all kind of exception to be sure that the operation doesn't fail. + except (psycopg2.Error, except_orm): product_obj.write(cr, uid, [variant_id], {'active': False}, context=ctx) pass return True @@ -724,7 +727,7 @@ class product_template(osv.osv): old_uom = product.uom_id if old_uom != new_uom: if self.pool.get('stock.move').search(cr, uid, [('product_id', 'in', [x.id for x in product.product_variant_ids]), ('state', '!=', 'cancel')], context=context): - raise osv.except_osv(_('Unit of Measure can not be changed anymore!'), _("As there are existing stock moves of this product, you can not change the Unit of Measurement anymore. ")) + raise UserError(_('Unit of Measure can not be changed anymore!') + " " + _("As there are existing stock moves of this product, you can not change the Unit of Measurement anymore. ")) if 'standard_price' in vals: for prod_template_id in ids: self._set_standard_price(cr, uid, prod_template_id, vals['standard_price'], context=context) diff --git a/addons/product_extended/wizard/wizard_price.py b/addons/product_extended/wizard/wizard_price.py index 6adda8f8cd0..1cf663d50d6 100644 --- a/addons/product_extended/wizard/wizard_price.py +++ b/addons/product_extended/wizard/wizard_price.py @@ -21,7 +21,7 @@ # ############################################################################## -from openerp.exceptions import except_orm +from openerp.exceptions import UserError from openerp.osv import fields, osv from openerp.tools.translate import _ @@ -51,7 +51,7 @@ class wizard_price(osv.osv): context = {} model = context.get('active_model') if model != 'product.template': - raise except_orm(_('Wrong model!'), _('This wizard is build for product templates, while you are currently running it from a product variant.')) + raise UserError(_('This wizard is build for product templates, while you are currently running it from a product variant.')) rec_id = context and context.get('active_id', False) assert rec_id, _('Active ID is not set in Context.') prod_obj = self.pool.get('product.template') diff --git a/addons/project/project.py b/addons/project/project.py index 57eea1d3ff7..1e76378d5b7 100644 --- a/addons/project/project.py +++ b/addons/project/project.py @@ -31,6 +31,7 @@ from openerp import tools from openerp.addons.resource.faces import task as Task from openerp.osv import fields, osv from openerp.tools.translate import _ +from openerp.exceptions import UserError class project_task_type(osv.osv): @@ -185,8 +186,7 @@ class project(osv.osv): analytic_account_to_delete = set() for proj in self.browse(cr, uid, ids, context=context): if proj.tasks: - raise osv.except_osv(_('Invalid Action!'), - _('You cannot delete a project containing tasks. You can either delete all the project\'s tasks and then delete the project or simply deactivate the project.')) + raise UserError(_('You cannot delete a project containing tasks. You can either delete all the project\'s tasks and then delete the project or simply deactivate the project.')) elif proj.alias_id: alias_ids.append(proj.alias_id.id) if proj.analytic_account_id and not proj.analytic_account_id.line_ids: @@ -504,7 +504,7 @@ class project(osv.osv): for project in projects: if (not project.members) and force_members: - raise osv.except_osv(_('Warning!'),_("You must assign members on the project '%s'!") % (project.name,)) + raise UserError(_("You must assign members on the project '%s'!") % (project.name,)) resource_pool = self.pool.get('resource.resource') @@ -994,7 +994,7 @@ class task(osv.osv): if task.child_ids: for child in task.child_ids: if child.stage_id and not child.stage_id.fold: - raise osv.except_osv(_("Warning!"), _("Child task still open.\nPlease cancel or complete child task first.")) + raise UserError(_("Child task still open.\nPlease cancel or complete child task first.")) return True def _delegate_task_attachments(self, cr, uid, task_id, delegated_task_id, context=None): @@ -1303,7 +1303,7 @@ class account_analytic_account(osv.osv): proj_ids = self.pool['project.project'].search(cr, uid, [('analytic_account_id', 'in', ids)]) has_tasks = self.pool['project.task'].search(cr, uid, [('project_id', 'in', proj_ids)], count=True, context=context) if has_tasks: - raise osv.except_osv(_('Warning!'), _('Please remove existing tasks in the project linked to the accounts you want to delete.')) + raise UserError(_('Please remove existing tasks in the project linked to the accounts you want to delete.')) return super(account_analytic_account, self).unlink(cr, uid, ids, context=context) def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100): diff --git a/addons/project_issue/project_issue.py b/addons/project_issue/project_issue.py index 0dc3e0a5925..8898272b744 100644 --- a/addons/project_issue/project_issue.py +++ b/addons/project_issue/project_issue.py @@ -31,6 +31,7 @@ from openerp.osv import fields, osv, orm from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT from openerp.tools import html2plaintext from openerp.tools.translate import _ +from openerp.exceptions import UserError, AccessError class project_issue_version(osv.Model): @@ -408,7 +409,7 @@ class project_issue(osv.Model): data = {} esc_proj = issue.project_id.project_escalation_id if not esc_proj: - raise osv.except_osv(_('Warning!'), _('You cannot escalate this issue.\nThe relevant Project has not configured the Escalation Project!')) + raise UserError(_('You cannot escalate this issue.\nThe relevant Project has not configured the Escalation Project!')) data['project_id'] = esc_proj.id if esc_proj.user_id: @@ -438,7 +439,7 @@ class project_issue(osv.Model): self._message_add_suggested_recipient(cr, uid, recipients, issue, partner=issue.partner_id, reason=_('Customer')) elif issue.email_from: self._message_add_suggested_recipient(cr, uid, recipients, issue, email=issue.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 @@ -544,7 +545,7 @@ class account_analytic_account(osv.Model): proj_ids = self.pool['project.project'].search(cr, uid, [('analytic_account_id', 'in', ids)]) has_issues = self.pool['project.issue'].search(cr, uid, [('project_id', 'in', proj_ids)], count=True, context=context) if has_issues: - raise osv.except_osv(_('Warning!'), _('Please remove existing issues in the project linked to the accounts you want to delete.')) + raise UserError(_('Please remove existing issues in the project linked to the accounts you want to delete.')) return super(account_analytic_account, self).unlink(cr, uid, ids, context=context) diff --git a/addons/project_timesheet/project_timesheet.py b/addons/project_timesheet/project_timesheet.py index 819b482c114..dfa2ea0cad7 100644 --- a/addons/project_timesheet/project_timesheet.py +++ b/addons/project_timesheet/project_timesheet.py @@ -24,6 +24,7 @@ import datetime from openerp.osv import fields, osv from openerp import tools from openerp.tools.translate import _ +from openerp.exceptions import UserError class project_project(osv.osv): _inherit = 'project.project' @@ -79,23 +80,19 @@ class project_work(osv.osv): emp_id = emp_obj.search(cr, uid, [('user_id', '=', user_id)]) if not emp_id: user_name = self.pool.get('res.users').read(cr, uid, [user_id], ['name'])[0]['name'] - raise osv.except_osv(_('Bad Configuration!'), - _('Please define employee for user "%s". You must create one.')% (user_name,)) + raise UserError(_('Please define employee for user "%s". You must create one.')% (user_name,)) emp = emp_obj.browse(cr, uid, emp_id[0]) if not emp.product_id: - raise osv.except_osv(_('Bad Configuration!'), - _('Please define product and product category property account on the related employee.\nFill in the HR Settings tab of the employee form.')) + raise UserError(_('Please define product and product category property account on the related employee.\nFill in the HR Settings tab of the employee form.')) if not emp.journal_id: - raise osv.except_osv(_('Bad Configuration!'), - _('Please define journal on the related employee.\nFill in the timesheet tab of the employee form.')) + raise UserError(_('Please define journal on the related employee.\nFill in the timesheet tab of the employee form.')) acc_id = emp.product_id.property_account_expense.id if not acc_id: acc_id = emp.product_id.categ_id.property_account_expense_categ.id if not acc_id: - raise osv.except_osv(_('Bad Configuration!'), - _('Please define product and product category property account on the related employee.\nFill in the timesheet tab of the employee form.')) + raise UserError(_('Please define product and product category property account on the related employee.\nFill in the timesheet tab of the employee form.')) res['product_id'] = emp.product_id.id res['journal_id'] = emp.journal_id.id @@ -291,7 +288,7 @@ class res_partner(osv.osv): def unlink(self, cursor, user, ids, context=None): parnter_id=self.pool.get('project.project').search(cursor, user, [('partner_id', 'in', ids)]) if parnter_id: - raise osv.except_osv(_('Invalid Action!'), _('You cannot delete a partner which is assigned to project, but you can uncheck the active box.')) + raise UserError(_('You cannot delete a partner which is assigned to project, but you can uncheck the active box.')) return super(res_partner,self).unlink(cursor, user, ids, context=context) @@ -318,5 +315,5 @@ class account_analytic_line(osv.osv): st = acc.to_invoice.id res['value']['to_invoice'] = st or False if acc.state == 'close' or acc.state == 'cancelled': - raise osv.except_osv(_('Invalid Analytic Account!'), _('You cannot select a Analytic Account which is in Close or Cancelled state.')) + raise UserError(_('You cannot select a Analytic Account which is in Close or Cancelled state.')) return res diff --git a/addons/purchase/purchase.py b/addons/purchase/purchase.py index b1d2add98ad..33badfa98b4 100644 --- a/addons/purchase/purchase.py +++ b/addons/purchase/purchase.py @@ -31,6 +31,7 @@ import openerp.addons.decimal_precision as dp from openerp.osv.orm import browse_record_list, browse_record, browse_null from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT, DATETIME_FORMATS_MAP from openerp.tools.float_utils import float_compare +from openerp.exceptions import UserError class purchase_order(osv.osv): @@ -159,7 +160,7 @@ class purchase_order(osv.osv): if not types: types = type_obj.search(cr, uid, [('code', '=', 'incoming'), ('warehouse_id', '=', False)], context=context) if not types: - raise osv.except_osv(_('Error!'), _("Make sure you have at least an incoming picking type defined")) + raise UserError(_("Make sure you have at least an incoming picking type defined")) return types[0] def _get_picking_ids(self, cr, uid, ids, field_names, args, context=None): @@ -338,7 +339,7 @@ class purchase_order(osv.osv): if s['state'] in ['draft','cancel']: unlink_ids.append(s['id']) else: - raise osv.except_osv(_('Invalid Action!'), _('In order to delete a purchase order, you must cancel it first.')) + raise UserError(_('In order to delete a purchase order, you must cancel it first.')) # automatically sending subflow.delete upon deletion self.signal_workflow(cr, uid, unlink_ids, 'purchase_cancel') @@ -414,9 +415,8 @@ class purchase_order(osv.osv): for po in self.browse(cr, uid, ids, context=context): inv_ids+= [invoice.id for invoice in po.invoice_ids] if not inv_ids: - raise osv.except_osv(_('Error!'), _('Please create Invoices.')) + raise UserError(_('Please create Invoices.')) result['domain'] = [('id', 'in', inv_ids)] - return result def view_invoice(self, cr, uid, ids, context=None): ''' @@ -533,7 +533,7 @@ class purchase_order(osv.osv): todo = [] for po in self.browse(cr, uid, ids, context=context): if not po.order_line: - raise osv.except_osv(_('Error!'),_('You cannot confirm a purchase order without any purchase order line.')) + raise UserError(_('You cannot confirm a purchase order without any purchase order line.')) for line in po.order_line: if line.state=='draft': todo.append(line.id) @@ -550,7 +550,7 @@ class purchase_order(osv.osv): if not acc_id: acc_id = po_line.product_id.categ_id.property_account_expense_categ.id if not acc_id: - raise osv.except_osv(_('Error!'), _('Define an expense account for this product: "%s" (id:%d).') % (po_line.product_id.name, po_line.product_id.id,)) + raise UserError(_('Define an expense account for this product: "%s" (id:%d).') % (po_line.product_id.name, po_line.product_id.id,)) else: acc_id = property_obj.get(cr, uid, 'property_account_expense_categ', 'product.category', context=context).id fpos = po_line.order_id.fiscal_position or False @@ -592,10 +592,7 @@ class purchase_order(osv.osv): ('company_id', '=', order.company_id.id)], limit=1) if not journal_ids: - raise osv.except_osv( - _('Error!'), - _('Define purchase journal for this company: "%s" (id:%d).') % \ - (order.company_id.name, order.company_id.id)) + raise UserError(_('Define purchase journal for this company: "%s" (id:%d).') % (order.company_id.name, order.company_id.id)) return { 'name': order.partner_ref or order.name, 'reference': order.partner_ref or order.name, @@ -688,15 +685,11 @@ class purchase_order(osv.osv): for pick in purchase.picking_ids: for move in pick.move_lines: if pick.state == 'done': - raise osv.except_osv( - _('Unable to cancel the purchase order %s.') % (purchase.name), - _('You have already received some goods for it. ')) + raise UserError(_('Unable to cancel the purchase order %s.') % (purchase.name) + _('You have already received some goods for it. ')) self.pool.get('stock.picking').action_cancel(cr, uid, [x.id for x in purchase.picking_ids if x.state != 'cancel'], context=context) for inv in purchase.invoice_ids: if inv and inv.state not in ('cancel', 'draft'): - raise osv.except_osv( - _('Unable to cancel this purchase order.'), - _('You must first cancel all invoices related to this purchase order.')) + raise UserError(_("Unable to cancel this purchase order.") + " " + _("You must first cancel all invoices related to this purchase order.")) self.pool.get('account.invoice') \ .signal_workflow(cr, uid, map(attrgetter('id'), purchase.invoice_ids), 'invoice_cancel') self.signal_workflow(cr, uid, ids, 'purchase_cancel') @@ -1014,7 +1007,7 @@ class purchase_order_line(osv.osv): def unlink(self, cr, uid, ids, context=None): for line in self.browse(cr, uid, ids, context=context): if line.state not in ['draft', 'cancel']: - raise osv.except_osv(_('Invalid Action!'), _('Cannot delete a purchase order line which is in state \'%s\'.') %(line.state,)) + raise UserError(_('Cannot delete a purchase order line which is in state \'%s\'.') %(line.state,)) procurement_obj = self.pool.get('procurement.order') procurement_ids_to_cancel = procurement_obj.search(cr, uid, [('purchase_line_id', 'in', ids)], context=context) if procurement_ids_to_cancel: @@ -1086,9 +1079,9 @@ class purchase_order_line(osv.osv): # - check for the presence of partner_id and pricelist_id #if not partner_id: - # raise osv.except_osv(_('No Partner!'), _('Select a partner in purchase order to choose a product.')) + # raise UserError(_('Select a partner in purchase order to choose a product.')) #if not pricelist_id: - # raise osv.except_osv(_('No Pricelist !'), _('Select a price list in the purchase order form before choosing a product.')) + # raise UserError(_('Select a price list in the purchase order form before choosing a product.')) # - determine name and notes based on product in partner lang. context_partner = context.copy() @@ -1188,7 +1181,7 @@ class procurement_order(osv.osv): uom = procurement.purchase_line_id.product_uom product_qty = uom_obj._compute_qty_obj(cr, uid, procurement.product_uom, procurement.product_qty, uom, context=context) if procurement.purchase_line_id.state not in ('draft', 'cancel'): - raise osv.except_osv(_('Error!'), + raise UserError( _('Can not cancel this procurement like this as the related purchase order has been confirmed already. Please cancel the purchase order first. ')) if float_compare(procurement.purchase_line_id.product_qty, product_qty, 0, precision_rounding=uom.rounding) > 0: purchase_line_obj.write(cr, uid, [procurement.purchase_line_id.id], {'product_qty': procurement.purchase_line_id.product_qty - product_qty}, context=context) @@ -1256,7 +1249,7 @@ class procurement_order(osv.osv): if user.company_id and user.company_id.partner_id: if partner.id == user.company_id.partner_id.id: - raise osv.except_osv(_('Configuration Error!'), _('The product "%s" has been defined with your company as reseller which seems to be a configuration error!' % procurement.product_id.name)) + raise UserError(_('The product "%s" has been defined with your company as reseller which seems to be a configuration error!' % procurement.product_id.name)) return True diff --git a/addons/purchase/stock.py b/addons/purchase/stock.py index 167efab33f8..e951aa03b71 100644 --- a/addons/purchase/stock.py +++ b/addons/purchase/stock.py @@ -22,6 +22,7 @@ from openerp import SUPERUSER_ID from openerp.osv import fields, osv from openerp.tools.translate import _ +from openerp.exceptions import UserError class stock_move(osv.osv): _inherit = 'stock.move' @@ -192,7 +193,7 @@ class stock_warehouse(osv.osv): buy_route_id = route_obj.search(cr, uid, [('name', 'like', _('Buy'))], context=context) buy_route_id = buy_route_id and buy_route_id[0] or False if not buy_route_id: - raise osv.except_osv(_('Error!'), _('Can\'t find any generic Buy route.')) + raise UserError(_('Can\'t find any generic Buy route.')) return { 'name': self._format_routename(cr, uid, warehouse, _(' Buy'), context=context), diff --git a/addons/purchase/wizard/purchase_order_group.py b/addons/purchase/wizard/purchase_order_group.py index 8ada5a73352..0a03f720f2a 100644 --- a/addons/purchase/wizard/purchase_order_group.py +++ b/addons/purchase/wizard/purchase_order_group.py @@ -22,6 +22,7 @@ import time from openerp.osv import fields, osv from openerp.tools.translate import _ +from openerp.exceptions import UserError class purchase_order_group(osv.osv_memory): _name = "purchase.order.group" @@ -41,8 +42,7 @@ class purchase_order_group(osv.osv_memory): context={} res = super(purchase_order_group, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar,submenu=False) if context.get('active_model','') == 'purchase.order' and len(context['active_ids']) < 2: - raise osv.except_osv(_('Warning!'), - _('Please select multiple order to merge in the list view.')) + raise UserError(_('Please select multiple order to merge in the list view.')) return res def merge_orders(self, cr, uid, ids, context=None): """ diff --git a/addons/purchase_requisition/purchase_requisition.py b/addons/purchase_requisition/purchase_requisition.py index 85b2e98f356..7fd33c367d9 100644 --- a/addons/purchase_requisition/purchase_requisition.py +++ b/addons/purchase_requisition/purchase_requisition.py @@ -25,6 +25,7 @@ from openerp.osv import fields, osv from openerp.tools.translate import _ from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT import openerp.addons.decimal_precision as dp +from openerp.exceptions import UserError class purchase_requisition(osv.osv): _name = "purchase.requisition" @@ -87,7 +88,7 @@ class purchase_requisition(osv.osv): def tender_in_progress(self, cr, uid, ids, context=None): if not all(obj.line_ids for obj in self.pool['purchase.requisition'].browse(cr, uid, ids, context=context)): - raise osv.except_osv(_('Warning!'), _('You can not confirm call because there is no product line.')) + raise UserError(_('You can not confirm call because there is no product line.')) return self.write(cr, uid, ids, {'state': 'in_progress'}, context=context) def tender_open(self, cr, uid, ids, context=None): @@ -188,7 +189,7 @@ class purchase_requisition(osv.osv): res = {} for requisition in self.browse(cr, uid, ids, context=context): if not requisition.multiple_rfq_per_supplier and supplier.id in filter(lambda x: x, [rfq.state != 'cancel' and rfq.partner_id.id or None for rfq in requisition.purchase_ids]): - raise osv.except_osv(_('Warning!'), _('You have already one %s purchase order for this partner, you must cancel this purchase order to create a new quotation.') % rfq.state) + raise UserError(_('You have already one %s purchase order for this partner, you must cancel this purchase order to create a new quotation.') % rfq.state) context.update({'mail_create_nolog': True}) purchase_id = purchase_order.create(cr, uid, self._prepare_purchase_order(cr, uid, requisition, supplier, context=context), context=context) purchase_order.message_post(cr, uid, [purchase_id], body=_("RFQ created"), context=context) @@ -239,7 +240,7 @@ class purchase_requisition(osv.osv): id_per_supplier = {} for tender in self.browse(cr, uid, ids, context=context): if tender.state == 'done': - raise osv.except_osv(_('Warning!'), _('You have already generate the purchase order(s).')) + raise UserError(_('You have already generate the purchase order(s).')) confirm = False #check that we have at least confirm one line @@ -248,7 +249,7 @@ class purchase_requisition(osv.osv): confirm = True break if not confirm: - raise osv.except_osv(_('Warning!'), _('You have no line selected for buying.')) + raise UserError(_('You have no line selected for buying.')) #check for complete RFQ for quotation in tender.purchase_ids: diff --git a/addons/purchase_requisition/wizard/purchase_requisition_partner.py b/addons/purchase_requisition/wizard/purchase_requisition_partner.py index 613feab8e28..de999647766 100644 --- a/addons/purchase_requisition/wizard/purchase_requisition_partner.py +++ b/addons/purchase_requisition/wizard/purchase_requisition_partner.py @@ -21,6 +21,7 @@ from openerp.osv import fields, osv from openerp.tools.translate import _ +from openerp.exceptions import UserError class purchase_requisition_partner(osv.osv_memory): _name = "purchase.requisition.partner" @@ -36,7 +37,7 @@ class purchase_requisition_partner(osv.osv_memory): record_id = context and context.get('active_id', False) or False tender = self.pool.get('purchase.requisition').browse(cr, uid, record_id, context=context) if not tender.line_ids: - raise osv.except_osv(_('Error!'), _('Define product(s) you want to include in the call for tenders.')) + raise UserError(_('Define product(s) you want to include in the call for tenders.')) return res def create_order(self, cr, uid, ids, context=None): diff --git a/addons/report/controllers/main.py b/addons/report/controllers/main.py index 56236990316..4436e57b29e 100644 --- a/addons/report/controllers/main.py +++ b/addons/report/controllers/main.py @@ -21,7 +21,6 @@ from openerp.addons.web.http import Controller, route, request from openerp.addons.web.controllers.main import _serialize_exception -from openerp.osv import osv from openerp.tools import html_escape import simplejson diff --git a/addons/report/models/report.py b/addons/report/models/report.py index 855bc5f56a0..574aa3c7947 100644 --- a/addons/report/models/report.py +++ b/addons/report/models/report.py @@ -28,6 +28,7 @@ from openerp.tools.misc import find_in_path from openerp.tools.translate import _ from openerp.addons.web.http import request from openerp.tools.safe_eval import safe_eval as eval +from openerp.exceptions import UserError import re import time @@ -288,10 +289,7 @@ class Report(osv.Model): try: report = report_obj.browse(cr, uid, idreport[0], context=context) except IndexError: - raise osv.except_osv( - _('Bad Report Reference'), - _('This report is not loaded into the database: %s.' % report_name) - ) + raise UserError(_("Bad Report Reference") + _("This report is not loaded into the database: %s.") % report_name) return { 'context': context, @@ -443,9 +441,8 @@ class Report(osv.Model): out, err = process.communicate() if process.returncode not in [0, 1]: - raise osv.except_osv(_('Report (PDF)'), - _('Wkhtmltopdf failed (error code: %s). ' - 'Message: %s') % (str(process.returncode), err)) + raise UserError(_('Wkhtmltopdf failed (error code: %s). ' + 'Message: %s') % (str(process.returncode), err)) # Save the pdf in attachment if marked if reporthtml[0] is not False and save_in_attachment.get(reporthtml[0]): @@ -460,7 +457,7 @@ class Report(osv.Model): try: self.pool['ir.attachment'].create(cr, uid, attachment) except AccessError: - _logger.warning("Cannot save PDF report %r as attachment", + _logger.info("Cannot save PDF report %r as attachment", attachment['name']) else: _logger.info('The PDF document %s is now saved in the database', diff --git a/addons/report_webkit/webkit_report.py b/addons/report_webkit/webkit_report.py index 299a68284e7..aadae9f1764 100644 --- a/addons/report_webkit/webkit_report.py +++ b/addons/report_webkit/webkit_report.py @@ -45,8 +45,8 @@ from openerp.modules.module import get_module_resource from openerp.report.report_sxw import * from openerp import tools from openerp.tools.translate import _ -from openerp.osv.osv import except_osv from urllib import urlencode, quote as quote +from openerp.exceptions import UserError _logger = logging.getLogger(__name__) @@ -143,14 +143,12 @@ class WebKitParser(report_sxw): if webkit_path: return webkit_path - raise except_osv( - _('Wkhtmltopdf library path is not set'), - _('Please install executable on your system' \ - ' (sudo apt-get install wkhtmltopdf) or download it from here:' \ - ' http://code.google.com/p/wkhtmltopdf/downloads/list and set the' \ - ' path in the ir.config_parameter with the webkit_path key.' \ - 'Minimal version is 0.9.9') - ) + raise UserError(_('Wkhtmltopdf library path is not set') + ' ' + + _('Please install executable on your system' + ' (sudo apt-get install wkhtmltopdf) or download it from here:' + ' http://code.google.com/p/wkhtmltopdf/downloads/list and set the' + ' path in the ir.config_parameter with the webkit_path key.' + 'Minimal version is 0.9.9')) def generate_pdf(self, comm_path, report_xml, header, footer, html_list, webkit_header=False): """Call webkit in order to generate pdf""" @@ -215,8 +213,7 @@ class WebKitParser(report_sxw): else: error_message = _('The following diagnosis message was provided:\n') + error_message if status : - raise except_osv(_('Webkit error' ), - _("The command 'wkhtmltopdf' failed with error code = %s. Message: %s") % (status, error_message)) + raise UserError(_("The command 'wkhtmltopdf' failed with error code = %s. Message: %s") % (status, error_message)) with open(out_filename, 'rb') as pdf_file: pdf = pdf_file.read() os.close(fd) @@ -282,14 +279,11 @@ class WebKitParser(report_sxw): if not template and report_xml.report_webkit_data : template = report_xml.report_webkit_data if not template : - raise except_osv(_('Error!'), _('Webkit report template not found!')) + raise UserError(_('Webkit report template not found!')) header = report_xml.webkit_header.html footer = report_xml.webkit_header.footer_html if not header and report_xml.use_global_header: - raise except_osv( - _('No header defined for this Webkit report!'), - _('Please set a header in company settings.') - ) + raise UserError(_('No header defined for this Webkit report!') + " " + _('Please set a header in company settings.')) if not report_xml.use_global_header : header = '' default_head = get_module_resource('report_webkit', 'default_header.html') @@ -321,21 +315,21 @@ class WebKitParser(report_sxw): htmls.append(html) except Exception, e: msg = u"%s" % e - _logger.error(msg) - raise except_osv(_('Webkit render!'), msg) + _logger.info(msg, exc_info=True) + raise UserError(msg) else: try : html = body_mako_tpl.render(dict(parser_instance.localcontext)) htmls.append(html) except Exception, e: msg = u"%s" % e - _logger.error(msg) - raise except_osv(_('Webkit render!'), msg) + _logger.info(msg, exc_info=True) + raise UserError(msg) head_mako_tpl = mako_template(header) try : head = head_mako_tpl.render(dict(parser_instance.localcontext, _debug=False)) except Exception, e: - raise except_osv(_('Webkit render!'), u"%s" % e) + raise UserError(tools.ustr(e)) foot = False if footer : foot_mako_tpl = mako_template(footer) @@ -343,15 +337,15 @@ class WebKitParser(report_sxw): foot = foot_mako_tpl.render(dict(parser_instance.localcontext)) except Exception, e: msg = u"%s" % e - _logger.error(msg) - raise except_osv(_('Webkit render!'), msg) + _logger.info(msg, exc_info=True) + raise UserError(msg) if report_xml.webkit_debug : try : deb = head_mako_tpl.render(dict(parser_instance.localcontext, _debug=tools.ustr("\n".join(htmls)))) except Exception, e: msg = u"%s" % e - _logger.error(msg) - raise except_osv(_('Webkit render!'), msg) + _logger.info(msg, exc_info=True) + raise UserError(msg) return (deb, 'html') bin = self.get_lib(cursor, uid) pdf = self.generate_pdf(bin, report_xml, head, foot, htmls) diff --git a/addons/resource/resource.py b/addons/resource/resource.py index eef5ffa49fb..bf7f708abb8 100644 --- a/addons/resource/resource.py +++ b/addons/resource/resource.py @@ -29,6 +29,7 @@ from openerp import tools from openerp.osv import fields, osv from openerp.tools.float_utils import float_compare from openerp.tools.translate import _ +from openerp.exceptions import UserError class resource_calendar(osv.osv): """ Calendar model for a resource. It has @@ -790,7 +791,7 @@ class resource_resource(osv.osv): day = week_days[week['dayofweek']] wk_days[week['dayofweek']] = week_days[week['dayofweek']] else: - raise osv.except_osv(_('Configuration Error!'),_('Make sure the Working time has been configured with proper week days!')) + raise UserError(_('Make sure the Working time has been configured with proper week days!')) hour_from_str = hours_time_string(week['hour_from']) hour_to_str = hours_time_string(week['hour_to']) res_str = hour_from_str + '-' + hour_to_str diff --git a/addons/sale/sale.py b/addons/sale/sale.py index 5ed81d029b5..d8b7bad4733 100644 --- a/addons/sale/sale.py +++ b/addons/sale/sale.py @@ -26,6 +26,7 @@ from openerp.tools.translate import _ from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT import openerp.addons.decimal_precision as dp from openerp import workflow +from openerp.exceptions import UserError class res_company(osv.Model): _inherit = "res.company" @@ -151,7 +152,7 @@ class sale_order(osv.osv): def _get_default_company(self, cr, uid, context=None): company_id = self.pool.get('res.users')._get_company(cr, uid, context=context) if not company_id: - raise osv.except_osv(_('Error!'), _('There is no default company for the current user!')) + raise UserError(_('There is no default company for the current user!')) return company_id def _get_default_team_id(self, cr, uid, context=None): @@ -270,7 +271,7 @@ class sale_order(osv.osv): if s['state'] in ['draft', 'cancel']: unlink_ids.append(s['id']) else: - raise osv.except_osv(_('Invalid Action!'), _('In order to delete a confirmed sales order, you must cancel it before!')) + raise UserError(_('In order to delete a confirmed sales order, you must cancel it before!')) return osv.osv.unlink(self, cr, uid, unlink_ids, context=context) @@ -386,8 +387,7 @@ class sale_order(osv.osv): [('type', '=', 'sale'), ('company_id', '=', order.company_id.id)], limit=1) if not journal_ids: - raise osv.except_osv(_('Error!'), - _('Please define sales journal for this company: "%s" (id:%d).') % (order.company_id.name, order.company_id.id)) + raise UserError(_('Please define sales journal for this company: "%s" (id:%d).') % (order.company_id.name, order.company_id.id)) invoice_vals = { 'name': order.client_order_ref or '', 'origin': order.name, @@ -517,9 +517,7 @@ class sale_order(osv.osv): for o in self.browse(cr, uid, ids, context=context): currency_id = o.pricelist_id.currency_id.id if (o.partner_id.id in partner_currency) and (partner_currency[o.partner_id.id] <> currency_id): - raise osv.except_osv( - _('Error!'), - _('You cannot group sales having different currencies for the same partner.')) + raise UserError(_('You cannot group sales having different currencies for the same partner.')) partner_currency[o.partner_id.id] = currency_id lines = [] @@ -583,9 +581,7 @@ class sale_order(osv.osv): for sale in self.browse(cr, uid, ids, context=context): for inv in sale.invoice_ids: if inv.state not in ('draft', 'cancel'): - raise osv.except_osv( - _('Cannot cancel this sales order!'), - _('First cancel all invoices attached to this sales order.')) + raise UserError(_('Cannot cancel this sales order!') + ':' + _('First cancel all invoices attached to this sales order.')) inv.signal_workflow('invoice_cancel') sale_order_line_obj.write(cr, uid, [l.id for l in sale.order_line], {'state': 'cancel'}) @@ -601,7 +597,7 @@ class sale_order(osv.osv): context = context or {} for o in self.browse(cr, uid, ids): if not o.order_line: - raise osv.except_osv(_('Error!'),_('You cannot confirm a sales order which has no line.')) + raise UserError(_('You cannot confirm a sales order which has no line.')) noprod = self.test_no_product(cr, uid, o, context) if (o.order_policy == 'manual') or noprod: self.write(cr, uid, [o.id], {'state': 'manual', 'date_confirm': fields.date.context_today(self, cr, uid, context=context)}) @@ -930,7 +926,7 @@ class sale_order_line(osv.osv): if not account_id: account_id = line.product_id.categ_id.property_account_income_categ.id if not account_id: - raise osv.except_osv(_('Error!'), + raise UserError( _('Please define income account for this product: "%s" (id:%d).') % \ (line.product_id.name, line.product_id.id,)) else: @@ -947,8 +943,7 @@ class sale_order_line(osv.osv): fpos = line.order_id.fiscal_position or False account_id = self.pool.get('account.fiscal.position').map_account(cr, uid, fpos, account_id) if not account_id: - raise osv.except_osv(_('Error!'), - _('There is no Fiscal Position defined or Income category account defined for default properties of Product categories.')) + raise UserError(_('There is no Fiscal Position defined or Income category account defined for default properties of Product categories.')) res = { 'name': line.name, 'sequence': line.sequence, @@ -986,7 +981,7 @@ class sale_order_line(osv.osv): def button_cancel(self, cr, uid, ids, context=None): for line in self.browse(cr, uid, ids, context=context): if line.invoiced: - raise osv.except_osv(_('Invalid Action!'), _('You cannot cancel a sales order line that has already been invoiced.')) + raise UserError(_('You cannot cancel a sales order line that has already been invoiced.')) return self.write(cr, uid, ids, {'state': 'cancel'}) def button_confirm(self, cr, uid, ids, context=None): @@ -1153,7 +1148,7 @@ class sale_order_line(osv.osv): """Allows to delete sales order lines in draft,cancel states""" for rec in self.browse(cr, uid, ids, context=context): if rec.state not in ['draft', 'cancel']: - raise osv.except_osv(_('Invalid Action!'), _('Cannot delete a sales order line which is in state \'%s\'.') %(rec.state,)) + raise UserError(_('Cannot delete a sales order line which is in state \'%s\'.') % (rec.state,)) return super(sale_order_line, self).unlink(cr, uid, ids, context=context) diff --git a/addons/sale/wizard/sale_line_invoice.py b/addons/sale/wizard/sale_line_invoice.py index efad865c94d..3b81374c721 100644 --- a/addons/sale/wizard/sale_line_invoice.py +++ b/addons/sale/wizard/sale_line_invoice.py @@ -22,6 +22,7 @@ from openerp.osv import osv, fields from openerp.tools.translate import _ from openerp import workflow +from openerp.exceptions import UserError class sale_order_line_make_invoice(osv.osv_memory): _name = "sale.order.line.make.invoice" @@ -105,7 +106,7 @@ class sale_order_line_make_invoice(osv.osv_memory): workflow.trg_validate(uid, 'sale.order', order.id, 'all_lines', cr) if not invoices: - raise osv.except_osv(_('Warning!'), _('Invoice cannot be created for this Sales Order Line due to one of the following reasons:\n1.The state of this sales order line is either "draft" or "cancel"!\n2.The Sales Order Line is Invoiced!')) + raise UserError(_('Invoice cannot be created for this Sales Order Line due to one of the following reasons:\n1.The state of this sales order line is either "draft" or "cancel"!\n2.The Sales Order Line is Invoiced!')) if context.get('open_invoices', False): return self.open_invoices(cr, uid, ids, res, context=context) return {'type': 'ir.actions.act_window_close'} diff --git a/addons/sale/wizard/sale_make_invoice.py b/addons/sale/wizard/sale_make_invoice.py index 732a4bec499..ba4e0f9a96c 100644 --- a/addons/sale/wizard/sale_make_invoice.py +++ b/addons/sale/wizard/sale_make_invoice.py @@ -20,6 +20,7 @@ from openerp.osv import fields, osv from openerp.tools.translate import _ +from openerp.exceptions import UserError class sale_make_invoice(osv.osv_memory): _name = "sale.make.invoice" @@ -39,7 +40,7 @@ class sale_make_invoice(osv.osv_memory): record_id = context and context.get('active_id', False) order = self.pool.get('sale.order').browse(cr, uid, record_id, context=context) if order.state == 'draft': - raise osv.except_osv(_('Warning!'), _('You cannot create invoice when sales order is not confirmed.')) + raise UserError(_('You cannot create invoice when sales order is not confirmed.')) return False def make_invoices(self, cr, uid, ids, context=None): @@ -52,7 +53,7 @@ class sale_make_invoice(osv.osv_memory): data = self.read(cr, uid, ids)[0] for sale_order in order_obj.browse(cr, uid, context.get(('active_ids'), []), context=context): if sale_order.state != 'manual': - raise osv.except_osv(_('Warning!'), _("You shouldn't manually invoice the following sale order %s") % (sale_order.name)) + raise UserError(_("You shouldn't manually invoice the following sale order %s") % (sale_order.name)) order_obj.action_invoice_create(cr, uid, context.get(('active_ids'), []), data['grouped'], date_invoice=data['invoice_date']) orders = order_obj.browse(cr, uid, context.get(('active_ids'), []), context=context) diff --git a/addons/sale/wizard/sale_make_invoice_advance.py b/addons/sale/wizard/sale_make_invoice_advance.py index fa32635aa95..c62f6eb3aa6 100644 --- a/addons/sale/wizard/sale_make_invoice_advance.py +++ b/addons/sale/wizard/sale_make_invoice_advance.py @@ -21,6 +21,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 sale_advance_payment_inv(osv.osv_memory): _name = "sale.advance.payment.inv" @@ -88,18 +89,17 @@ class sale_advance_payment_inv(osv.osv_memory): prop_id = prop and prop.id or False account_id = fiscal_obj.map_account(cr, uid, sale.fiscal_position or False, prop_id) if not account_id: - raise osv.except_osv(_('Configuration Error!'), + raise UserError( _('There is no income account defined as global property.')) res['account_id'] = account_id if not res.get('account_id'): - raise osv.except_osv(_('Configuration Error!'), + raise UserError( _('There is no income account defined for this product: "%s" (id:%d).') % \ (wizard.product_id.name, wizard.product_id.id,)) # determine invoice amount if wizard.amount <= 0.00: - raise osv.except_osv(_('Incorrect Data'), - _('The value of Advance Amount must be positive.')) + raise UserError(_('The value of Advance Amount must be positive.')) if wizard.advance_payment_method == 'percentage': inv_amount = sale.amount_total * wizard.amount / 100 if not res.get('name'): diff --git a/addons/sale_crm/wizard/crm_make_sale.py b/addons/sale_crm/wizard/crm_make_sale.py index c139234c246..6795f34fd13 100644 --- a/addons/sale_crm/wizard/crm_make_sale.py +++ b/addons/sale_crm/wizard/crm_make_sale.py @@ -21,6 +21,7 @@ from openerp.osv import fields, osv from openerp.tools.translate import _ +from openerp.exceptions import UserError class crm_make_sale(osv.osv_memory): @@ -88,7 +89,7 @@ class crm_make_sale(osv.osv_memory): ['default', 'invoice', 'delivery', 'contact']) pricelist = partner.property_product_pricelist.id if False in partner_addr.values(): - raise osv.except_osv(_('Insufficient Data!'), _('No address(es) defined for this customer.')) + raise UserError(_('No address(es) defined for this customer.')) vals = { 'origin': _('Opportunity: %s') % str(case.id), diff --git a/addons/sale_stock/sale_stock.py b/addons/sale_stock/sale_stock.py index de433719a8c..9a70d3df803 100644 --- a/addons/sale_stock/sale_stock.py +++ b/addons/sale_stock/sale_stock.py @@ -26,6 +26,7 @@ from openerp.tools.safe_eval import safe_eval as eval from openerp.tools.translate import _ import pytz from openerp import SUPERUSER_ID +from openerp.exceptions import UserError class sale_order(osv.osv): _inherit = "sale.order" @@ -163,9 +164,7 @@ class sale_order(osv.osv): for sale in self.browse(cr, uid, ids, context=context): for pick in sale.picking_ids: if pick.state not in ('draft', 'cancel'): - raise osv.except_osv( - _('Cannot cancel sales order!'), - _('You must first cancel all delivery order(s) attached to this sales order.')) + raise UserError(_('Cannot cancel sales order!') + '\n' + _('You must first cancel all delivery order(s) attached to this sales order.')) stock_obj.signal_workflow(cr, uid, [p.id for p in sale.picking_ids], 'button_cancel') return super(sale_order, self).action_cancel(cr, uid, ids, context=context) diff --git a/addons/share/wizard/share_wizard.py b/addons/share/wizard/share_wizard.py index f48ad7654e7..161cbfba112 100644 --- a/addons/share/wizard/share_wizard.py +++ b/addons/share/wizard/share_wizard.py @@ -33,6 +33,7 @@ from openerp.osv import expression from openerp.tools.translate import _ from openerp.tools.safe_eval import safe_eval import openerp +from openerp.exceptions import UserError _logger = logging.getLogger(__name__) FULL_ACCESS = ('perm_read', 'perm_write', 'perm_create', 'perm_unlink') @@ -58,7 +59,7 @@ class share_wizard(osv.TransientModel): The error_message should have been translated with _(). """ if not condition: - raise osv.except_osv(_('Sharing access cannot be created.'), error_message) + raise UserError(error_message) def has_group(self, cr, uid, module, group_xml_id, context=None): """Returns True if current user is a member of the group identified by the module, group_xml_id pair.""" @@ -201,8 +202,7 @@ class share_wizard(osv.TransientModel): def go_step_1(self, cr, uid, ids, context=None): wizard_data = self.browse(cr,uid,ids,context)[0] if wizard_data.user_type == 'emails' and not self.has_email(cr, uid, context=context): - raise osv.except_osv(_('No email address configured'), - _('You must configure your email address in the user preferences before using the Share button.')) + raise UserError(_('You must configure your email address in the user preferences before using the Share button.')) model, res_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'share', 'action_share_wizard_step1') action = self.pool[model].read(cr, uid, [res_id], context=context)[0] action['res_id'] = ids[0] @@ -631,9 +631,8 @@ class share_wizard(osv.TransientModel): group_id, model_id=model.id, domain=str(related_domain), rule_name=rule_name, restrict=True, context=context) except Exception: - _logger.exception('Failed to create share access') - raise osv.except_osv(_('Sharing access cannot be created.'), - _('Sorry, the current screen and filter you are trying to share are not supported at the moment.\nYou may want to try a simpler filter.')) + _logger.info('Failed to create share access', exc_info=True) + raise UserError(_('Sorry, the current screen and filter you are trying to share are not supported at the moment.\nYou may want to try a simpler filter.')) def _check_preconditions(self, cr, uid, wizard_data, context=None): self._assert(wizard_data.action_id and wizard_data.access_mode, @@ -755,7 +754,7 @@ class share_wizard(osv.TransientModel): res_id = cond[2] # Record id not found: issue if res_id <= 0: - raise osv.except_osv(_('Record id not found'), _('The share engine has not been able to fetch a record_id for your invitation.')) + raise UserError(_('The share engine has not been able to fetch a record_id for your invitation.')) self.pool[model.model].message_subscribe(cr, uid, [res_id], new_ids + existing_ids, context=context) # self.send_invite_email(cr, uid, wizard_data, context=context) # self.send_invite_note(cr, uid, model.model, res_id, wizard_data, context=context) @@ -810,7 +809,7 @@ class share_wizard(osv.TransientModel): notification_obj = self.pool.get('mail.notification') user = self.pool.get('res.users').browse(cr, UID_ROOT, uid) if not user.email: - raise osv.except_osv(_('Email Required'), _('The current user must have an email address configured in User Preferences to be able to send outgoing emails.')) + raise UserError(_('The current user must have an email address configured in User Preferences to be able to send outgoing emails.')) # TODO: also send an HTML version of this mail for result_line in wizard_data.result_line_ids: @@ -841,7 +840,7 @@ class share_wizard(osv.TransientModel): mail_mail = self.pool.get('mail.mail') user = self.pool.get('res.users').browse(cr, UID_ROOT, uid) if not user.email: - raise osv.except_osv(_('Email Required'), _('The current user must have an email address configured in User Preferences to be able to send outgoing emails.')) + raise UserError(_('The current user must have an email address configured in User Preferences to be able to send outgoing emails.')) # TODO: also send an HTML version of this mail mail_ids = [] diff --git a/addons/stock/product.py b/addons/stock/product.py index 8ae369be5c7..11d805eb90a 100644 --- a/addons/stock/product.py +++ b/addons/stock/product.py @@ -24,6 +24,7 @@ from openerp.tools.translate import _ from openerp.tools.safe_eval import safe_eval as eval import openerp.addons.decimal_precision as dp from openerp.tools.float_utils import float_round +from openerp.exceptions import UserError class product_product(osv.osv): _inherit = "product.product" @@ -451,7 +452,7 @@ 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('stock.move').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 already been used in a stock move. 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 already been used in a stock move. 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) diff --git a/addons/stock/stock.py b/addons/stock/stock.py index 6732e33afe7..ecb76489aa4 100644 --- a/addons/stock/stock.py +++ b/addons/stock/stock.py @@ -34,6 +34,7 @@ from openerp import SUPERUSER_ID, api, models import openerp.addons.decimal_precision as dp from openerp.addons.procurement import procurement import logging +from openerp.exceptions import UserError _logger = logging.getLogger(__name__) @@ -368,7 +369,7 @@ class stock_quant(osv.osv): #split quants if needed for quant, qty in quants: if qty <= 0.0 or (quant and quant.qty <= 0.0): - raise osv.except_osv(_('Error!'), _('You can not reserve a negative quantity or a negative quant.')) + raise UserError(_('You can not reserve a negative quantity or a negative quant.')) if not quant: continue self._quant_split(cr, uid, quant, qty, context=context) @@ -479,7 +480,7 @@ class stock_quant(osv.osv): elif removal_strategy == 'lifo': order = 'in_date desc, id desc' return self._quants_get_order(cr, uid, location, product, quantity, domain, order, context=context) - raise osv.except_osv(_('Error!'), _('Removal strategy %s not implemented.' % (removal_strategy,))) + raise UserError(_('Removal strategy %s not implemented.' % (removal_strategy,))) def _quant_create(self, cr, uid, qty, move, lot_id=False, owner_id=False, src_package_id=False, dest_package_id=False, force_location_from=False, force_location_to=False, context=None): @@ -638,7 +639,7 @@ class stock_quant(osv.osv): def _check_location(self, cr, uid, location, context=None): if location.usage == 'view': - raise osv.except_osv(_('Error'), _('You cannot move to a location of type view %s.') % (location.name)) + raise UserError(_('You cannot move to a location of type view %s.') % (location.name)) return True #---------------------------------------------------------- @@ -880,7 +881,7 @@ class stock_picking(osv.osv): #skip the moves that don't need to be checked move_ids = [x.id for x in pick.move_lines if x.state not in ('draft', 'cancel', 'done')] if not move_ids: - raise osv.except_osv(_('Warning!'), _('Nothing to check the availability for.')) + raise UserError(_('Nothing to check the availability for.')) self.pool.get('stock.move').action_assign(cr, uid, move_ids, context=context) return True @@ -1706,7 +1707,7 @@ class stock_move(osv.osv): for `product_qty`, where the same write should set the `product_uom_qty` field instead, in order to detect errors. """ - raise osv.except_osv(_('Programming Error!'), _('The requested operation cannot be processed because of a programming error setting the `product_qty` field instead of the `product_uom_qty`.')) + raise UserError(_('The requested operation cannot be processed because of a programming error setting the `product_qty` field instead of the `product_uom_qty`.')) _columns = { 'name': fields.char('Description', required=True, select=True), @@ -1847,7 +1848,7 @@ class stock_move(osv.osv): quant_obj = self.pool.get("stock.quant") for move in self.browse(cr, uid, move_ids, context=context): if move.state in ('done', 'cancel'): - raise osv.except_osv(_('Operation Forbidden!'), _('Cannot unreserve a done move')) + raise UserError(_('Cannot unreserve a done move')) quant_obj.quants_unreserve(cr, uid, move, context=context) if self.find_move_ancestors(cr, uid, move, context=context): self.write(cr, uid, [move.id], {'state': 'waiting'}, context=context) @@ -1922,8 +1923,7 @@ class stock_move(osv.osv): for move in self.browse(cr, uid, ids, context=context): if move.state == 'done': if frozen_fields.intersection(vals): - raise osv.except_osv(_('Operation Forbidden!'), - _('Quantities, Units of Measure, Products and Locations cannot be modified on stock moves that have already been processed (except by the Administrator).')) + raise UserError(_('Quantities, Units of Measure, Products and Locations cannot be modified on stock moves that have already been processed (except by the Administrator).')) propagated_changes_dict = {} #propagation of quantity change if vals.get('product_uom_qty'): @@ -2166,7 +2166,7 @@ class stock_move(osv.osv): elif product.track_outgoing and location_dest.usage in ('customer', 'transit') and location.usage == 'internal': check = True if check and not lot_id: - raise osv.except_osv(_('Warning!'), _('You must assign a serial number for the product %s') % (product.name)) + raise UserError(_('You must assign a serial number for the product %s') % (product.name)) def check_tracking(self, cr, uid, move, lot_id, context=None): @@ -2250,8 +2250,7 @@ class stock_move(osv.osv): procs_to_check = [] for move in self.browse(cr, uid, ids, context=context): if move.state == 'done': - raise osv.except_osv(_('Operation Forbidden!'), - _('You cannot cancel a stock move that has been set to \'Done\'.')) + raise UserError(_('You cannot cancel a stock move that has been set to \'Done\'.')) if move.reserved_quant_ids: self.pool.get("stock.quant").quants_unreserve(cr, uid, move, context=context) if context.get('cancel_procurement'): @@ -2360,7 +2359,7 @@ class stock_move(osv.osv): if not ops.product_id and ops.package_id and ops.result_package_id.id != ops.package_id.parent_id.id: self.pool.get('stock.quant.package').write(cr, SUPERUSER_ID, [ops.package_id.id], {'parent_id': ops.result_package_id.id}, context=context) if not move_qty.get(move.id): - raise osv.except_osv(_("Error"), _("The roundings of your Unit of Measures %s on the move vs. %s on the product don't allow to do these operations or you are not transferring the picking at once. ") % (move.product_uom.name, move.product_id.uom_id.name)) + raise UserError(_("The roundings of your Unit of Measures %s on the move vs. %s on the product don't allow to do these operations or you are not transferring the picking at once. ") % (move.product_uom.name, move.product_id.uom_id.name)) move_qty[move.id] -= record.qty #Check for remaining qtys and unreserve/check move_dest_id in move_dest_ids = set() @@ -2407,7 +2406,7 @@ class stock_move(osv.osv): context = context or {} for move in self.browse(cr, uid, ids, context=context): if move.state not in ('draft', 'cancel'): - raise osv.except_osv(_('User Error!'), _('You can only delete draft moves.')) + raise UserError(_('You can only delete draft moves.')) return super(stock_move, self).unlink(cr, uid, ids, context=context) def action_scrap(self, cr, uid, ids, quantity, location_id, restrict_lot_id=False, restrict_partner_id=False, context=None): @@ -2422,7 +2421,7 @@ class stock_move(osv.osv): """ #quantity should be given in MOVE UOM if quantity <= 0: - raise osv.except_osv(_('Warning!'), _('Please provide a positive quantity to scrap.')) + raise UserError(_('Please provide a positive quantity to scrap.')) res = [] for move in self.browse(cr, uid, ids, context=context): source_location = move.location_id @@ -2431,7 +2430,7 @@ class stock_move(osv.osv): #Previously used to prevent scraping from virtual location but not necessary anymore #if source_location.usage != 'internal': #restrict to scrap from a virtual location because it's meaningless and it may introduce errors in stock ('creating' new products from nowhere) - #raise osv.except_osv(_('Error!'), _('Forbidden operation: it is not allowed to scrap products from a virtual location.')) + #raise UserError(_('Forbidden operation: it is not allowed to scrap products from a virtual location.')) move_qty = move.product_qty uos_qty = quantity / move_qty * move.product_uos_qty default_val = { @@ -2468,11 +2467,11 @@ class stock_move(osv.osv): returns the ID of the backorder move created """ if move.state in ('done', 'cancel'): - raise osv.except_osv(_('Error'), _('You cannot split a move done')) + raise UserError(_('You cannot split a move done')) if move.state == 'draft': #we restrict the split of a draft move because if not confirmed yet, it may be replaced by several other moves in #case of phantom bom (with mrp module). And we don't want to deal with this complexity by copying the product that will explode. - raise osv.except_osv(_('Error'), _('You cannot split a draft move. It needs to be confirmed first.')) + raise UserError(_('You cannot split a draft move. It needs to be confirmed first.')) if move.product_qty <= qty or qty == 0: return move.id @@ -2632,7 +2631,7 @@ class stock_inventory(osv.osv): for inv in self.browse(cr, uid, ids, context=context): for inventory_line in inv.line_ids: if inventory_line.product_qty < 0 and inventory_line.product_qty != inventory_line.theoretical_qty: - raise osv.except_osv(_('Warning'), _('You cannot set a negative product quantity in an inventory line:\n\t%s - qty: %s' % (inventory_line.product_id.name, inventory_line.product_qty))) + raise UserError(_('You cannot set a negative product quantity in an inventory line:\n\t%s - qty: %s' % (inventory_line.product_id.name, inventory_line.product_qty))) self.action_check(cr, uid, [inv.id], context=context) self.write(cr, uid, [inv.id], {'state': 'done'}, context=context) self.post_inventory(cr, uid, inv, context=context) @@ -3004,7 +3003,7 @@ class stock_warehouse(osv.osv): supplier_loc = location_obj.search(cr, uid, [('usage', '=', 'supplier')], context=context) supplier_loc = supplier_loc and supplier_loc[0] or False if not (customer_loc and supplier_loc): - raise osv.except_osv(_('Error!'), _('Can\'t find any customer or supplier location.')) + raise UserError(_('Can\'t find any customer or supplier location.')) return location_obj.browse(cr, uid, [customer_loc, supplier_loc], context=context) def switch_location(self, cr, uid, ids, warehouse, new_reception_step=False, new_delivery_step=False, context=None): @@ -3089,7 +3088,7 @@ class stock_warehouse(osv.osv): mto_route_id = route_obj.search(cr, uid, [('name', 'like', _('Make To Order'))], context=context) mto_route_id = mto_route_id and mto_route_id[0] or False if not mto_route_id: - raise osv.except_osv(_('Error!'), _('Can\'t find any generic Make To Order route.')) + raise UserError(_('Can\'t find any generic Make To Order route.')) return mto_route_id def _check_remove_mto_resupply_rules(self, cr, uid, warehouse, context=None): @@ -3537,7 +3536,7 @@ class stock_warehouse(osv.osv): pass if 'default_resupply_wh_id' in vals: if vals.get('default_resupply_wh_id') == warehouse.id: - raise osv.except_osv(_('Warning'),_('The default resupply warehouse should be different than the warehouse itself!')) + raise UserError(_('The default resupply warehouse should be different than the warehouse itself!')) if warehouse.default_resupply_wh_id: #remove the existing resupplying route on the warehouse to_remove_route_ids = route_obj.search(cr, uid, [('supplied_wh_id', '=', warehouse.id), ('supplier_wh_id', '=', warehouse.default_resupply_wh_id.id)], context=context) @@ -3768,7 +3767,7 @@ class stock_package(osv.osv): quants = [x for x in quant_obj.browse(cr, uid, quant_ids, context=context) if x.qty > 0] location_id = quants and quants[0].location_id.id or False if not [quant.location_id.id == location_id for quant in quants]: - raise osv.except_osv(_('Error'), _('Everything inside a package should be in the same location')) + raise UserError(_('Everything inside a package should be in the same location')) return True def action_print(self, cr, uid, ids, context=None): diff --git a/addons/stock/wizard/make_procurement_product.py b/addons/stock/wizard/make_procurement_product.py index 3978a6f2d68..9e337a0e9eb 100644 --- a/addons/stock/wizard/make_procurement_product.py +++ b/addons/stock/wizard/make_procurement_product.py @@ -21,6 +21,7 @@ from openerp.osv import fields, osv, orm +from openerp.exceptions import UserError from openerp.tools.translate import _ class make_procurement(osv.osv_memory): @@ -114,7 +115,7 @@ class make_procurement(osv.osv_memory): if len(product_ids) == 1: record_id = product_ids[0] else: - raise orm.except_orm(_('Warning'), _('Please use the Product Variant vue to request a procurement.')) + raise UserError(_('Please use the Product Variant vue to request a procurement.')) res = super(make_procurement, self).default_get(cr, uid, fields, context=context) diff --git a/addons/stock/wizard/stock_change_product_qty.py b/addons/stock/wizard/stock_change_product_qty.py index 9c262cdd081..d541338ed2e 100644 --- a/addons/stock/wizard/stock_change_product_qty.py +++ b/addons/stock/wizard/stock_change_product_qty.py @@ -23,6 +23,7 @@ from openerp.osv import fields, osv, orm import openerp.addons.decimal_precision as dp from openerp.tools.translate import _ from openerp import tools +from openerp.exceptions import UserError, AccessError class stock_change_product_qty(osv.osv_memory): _name = "stock.change.product.qty" @@ -55,19 +56,19 @@ class stock_change_product_qty(osv.osv_memory): if len(product_ids) == 1: res['product_id'] = product_ids[0] else: - raise orm.except_orm(_('Warning'), _('Please use the Product Variant view to update the product quantity.')) + raise UserError(_('Please use the Product Variant view to update the product quantity.')) if 'location_id' in fields: location_id = res.get('location_id', False) if not location_id: try: model, location_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'stock', 'stock_location_stock') - except (orm.except_orm, ValueError): + except (AccessError): pass if location_id: try: self.pool.get('stock.location').check_access_rule(cr, uid, [location_id], 'read', context=context) - except (orm.except_orm, ValueError): + except (AccessError): pass res['location_id'] = location_id return res @@ -89,7 +90,7 @@ class stock_change_product_qty(osv.osv_memory): for data in self.browse(cr, uid, ids, context=context): if data.new_quantity < 0: - raise osv.except_osv(_('Warning!'), _('Quantity cannot be negative.')) + raise UserError(_('Quantity cannot be negative.')) ctx = context.copy() ctx['location'] = data.location_id.id ctx['lot_id'] = data.lot_id.id diff --git a/addons/stock/wizard/stock_return_picking.py b/addons/stock/wizard/stock_return_picking.py index 6ac37fbe071..c72a4ccce86 100644 --- a/addons/stock/wizard/stock_return_picking.py +++ b/addons/stock/wizard/stock_return_picking.py @@ -22,6 +22,7 @@ from openerp.osv import osv, fields from openerp.tools.translate import _ import openerp.addons.decimal_precision as dp +from openerp.exceptions import UserError class stock_return_picking_line(osv.osv_memory): _name = "stock.return.picking.line" @@ -66,7 +67,7 @@ class stock_return_picking(osv.osv_memory): chained_move_exist = False if pick: if pick.state != 'done': - raise osv.except_osv(_('Warning!'), _("You may only return pickings that are Done!")) + raise UserError(_("You may only return pickings that are Done!")) for move in pick.move_lines: if move.move_dest_id: @@ -81,7 +82,7 @@ class stock_return_picking(osv.osv_memory): result1.append({'product_id': move.product_id.id, 'quantity': qty, 'move_id': move.id}) if len(result1) == 0: - raise osv.except_osv(_('Warning!'), _("No products to return (only lines in Done state and not fully returned yet can be returned)!")) + raise UserError(_("No products to return (only lines in Done state and not fully returned yet can be returned)!")) if 'product_return_moves' in fields: res.update({'product_return_moves': result1}) if 'move_dest_exists' in fields: @@ -129,7 +130,7 @@ class stock_return_picking(osv.osv_memory): for data_get in data_obj.browse(cr, uid, data['product_return_moves'], context=context): move = data_get.move_id if not move: - raise osv.except_osv(_('Warning !'), _("You have manually created product lines, please delete them to proceed")) + raise UserError(_("You have manually created product lines, please delete them to proceed")) new_qty = data_get.quantity if new_qty: returned_lines += 1 @@ -147,7 +148,7 @@ class stock_return_picking(osv.osv_memory): }) if not returned_lines: - raise osv.except_osv(_('Warning!'), _("Please specify at least one non-zero quantity.")) + raise UserError(_("Please specify at least one non-zero quantity.")) pick_obj.action_confirm(cr, uid, [new_picking], context=context) pick_obj.action_assign(cr, uid, [new_picking], context) diff --git a/addons/stock_account/product.py b/addons/stock_account/product.py index fa2ba8ab80f..d606f427e24 100644 --- a/addons/stock_account/product.py +++ b/addons/stock_account/product.py @@ -22,6 +22,7 @@ from openerp.osv import fields, osv from openerp.tools.translate import _ from openerp.fields import Many2one +from openerp.exceptions import UserError @@ -80,7 +81,7 @@ class product_template(osv.osv): account_valuation = product_obj.categ_id.property_stock_valuation_account_id and product_obj.categ_id.property_stock_valuation_account_id.id or False if not all([stock_input_acc, stock_output_acc, account_valuation, journal_id]): - raise osv.except_osv(_('Error!'), _('''One of the following information is missing on the product or product category and prevents the accounting valuation entries to be created: + raise UserError(_('''One of the following information is missing on the product or product category and prevents the accounting valuation entries to be created: Product: %s Stock Input Account: %s Stock Output Account: %s @@ -113,7 +114,7 @@ class product_template(osv.osv): diff = product.standard_price - new_price if not diff: - raise osv.except_osv(_('Error!'), _("No difference between standard price and new price!")) + raise UserError(_("No difference between standard price and new price!")) for prod_variant in product.product_variant_ids: qty = prod_variant.qty_available if qty: diff --git a/addons/stock_account/wizard/stock_invoice_onshipping.py b/addons/stock_account/wizard/stock_invoice_onshipping.py index 99fb2c31762..a9d2e017f01 100644 --- a/addons/stock_account/wizard/stock_invoice_onshipping.py +++ b/addons/stock_account/wizard/stock_invoice_onshipping.py @@ -21,6 +21,7 @@ from openerp.osv import fields, osv from openerp.tools.translate import _ +from openerp.exceptions import UserError class stock_invoice_onshipping(osv.osv_memory): def _get_journal(self, cr, uid, context=None): @@ -79,7 +80,7 @@ class stock_invoice_onshipping(osv.osv_memory): if pick.invoice_state != '2binvoiced': count += 1 if len(active_ids) == count: - raise osv.except_osv(_('Warning!'), _('None of these picking lists require invoicing.')) + raise UserError(_('None of these picking lists require invoicing.')) return res def open_invoice(self, cr, uid, ids, context=None): @@ -88,7 +89,7 @@ class stock_invoice_onshipping(osv.osv_memory): invoice_ids = self.create_invoice(cr, uid, ids, context=context) if not invoice_ids: - raise osv.except_osv(_('Error!'), _('No invoice created!')) + raise UserError(_('No invoice created!')) data = self.browse(cr, uid, ids[0], context=context) diff --git a/addons/stock_landed_costs/stock_landed_costs.py b/addons/stock_landed_costs/stock_landed_costs.py index 498dc9e3143..1bae68dbab3 100644 --- a/addons/stock_landed_costs/stock_landed_costs.py +++ b/addons/stock_landed_costs/stock_landed_costs.py @@ -23,6 +23,7 @@ from openerp.osv import fields, osv import openerp.addons.decimal_precision as dp from openerp.tools.translate import _ import product +from openerp.exceptions import UserError class stock_landed_cost(osv.osv): @@ -71,7 +72,7 @@ class stock_landed_cost(osv.osv): vals = dict(product_id=move.product_id.id, move_id=move.id, quantity=move.product_uom_qty, former_cost=total_cost * total_qty, weight=weight, volume=volume) lines.append(vals) if not lines: - raise osv.except_osv(_('Error!'), _('The selected picking does not contain any move that would be impacted by landed costs. Landed costs are only possible for products configured in real time valuation with real price costing method. Please make sure it is the case, or you selected the correct picking')) + raise UserError(_('The selected picking does not contain any move that would be impacted by landed costs. Landed costs are only possible for products configured in real time valuation with real price costing method. Please make sure it is the case, or you selected the correct picking')) return lines _columns = { @@ -109,7 +110,7 @@ class stock_landed_cost(osv.osv): credit_account_id = line.cost_line_id.account_id.id or cost_product.property_account_expense.id or cost_product.categ_id.property_account_expense_categ.id if not credit_account_id: - raise osv.except_osv(_('Error!'), _('Please configure Stock Expense Account for product: %s.') % (cost_product.name)) + raise UserError(_('Please configure Stock Expense Account for product: %s.') % (cost_product.name)) return self._create_account_move_line(cr, uid, line, move_id, credit_account_id, debit_account_id, qty_out, already_out_account_id, context=context) @@ -189,7 +190,7 @@ class stock_landed_cost(osv.osv): for cost in self.browse(cr, uid, ids, context=context): if not cost.valuation_adjustment_lines or not self._check_sum(cr, uid, cost, context=context): - raise osv.except_osv(_('Error!'), _('You cannot validate a landed cost which has no valid valuation lines.')) + raise UserError(_('You cannot validate a landed cost which has no valid valuation lines.')) move_id = self._create_account_move(cr, uid, cost, context=context) quant_dict = {} for line in cost.valuation_adjustment_lines: diff --git a/addons/stock_picking_wave/stock_picking_wave.py b/addons/stock_picking_wave/stock_picking_wave.py index 86809a8d58f..dcae78761e1 100644 --- a/addons/stock_picking_wave/stock_picking_wave.py +++ b/addons/stock_picking_wave/stock_picking_wave.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- from openerp.osv import fields, osv from openerp.tools.translate import _ +from openerp.exceptions import UserError class stock_picking_wave(osv.osv): _name = "stock.picking.wave" @@ -37,7 +38,7 @@ class stock_picking_wave(osv.osv): for wave in self.browse(cr, uid, ids, context=context): picking_ids += [picking.id for picking in wave.picking_ids] if not picking_ids: - raise osv.except_osv(_('Error!'), _('Nothing to print.')) + raise UserError(_('Nothing to print.')) context['active_ids'] = picking_ids context['active_model'] = 'stock.picking' return self.pool.get("report").get_action(cr, uid, [], 'stock.report_picking', context=context) @@ -54,7 +55,7 @@ class stock_picking_wave(osv.osv): if picking.state in ('cancel', 'done'): continue if picking.state != 'assigned': - raise osv.except_osv(_('Warning'), _('Some pickings are still waiting for goods. Please check or force their availability before setting this wave to done.')) + raise UserError(_('Some pickings are still waiting for goods. Please check or force their availability before setting this wave to done.')) picking_todo.add(picking.id) if picking_todo: self.pool.get('stock.picking').action_done(cr, uid, list(picking_todo), context=context) diff --git a/addons/subscription/subscription.py b/addons/subscription/subscription.py index 48492fbef01..d0546cadaea 100644 --- a/addons/subscription/subscription.py +++ b/addons/subscription/subscription.py @@ -25,6 +25,7 @@ import time from openerp.osv import fields,osv from openerp.tools.translate import _ +from openerp.exceptions import UserError class subscription_document(osv.osv): _name = "subscription.document" @@ -115,7 +116,7 @@ class subscription_subscription(osv.osv): id = int(id) model = self.pool[model_name] except: - raise osv.except_osv(_('Wrong Source Document!'), _('Please provide another source document.\nThis one does not exist!')) + raise UserError(_('Please provide another source document.\nThis one does not exist!')) default = {'state':'draft'} doc_obj = self.pool.get('subscription.document') @@ -142,7 +143,7 @@ class subscription_subscription(osv.osv): def unlink(self, cr, uid, ids, context=None): for record in self.browse(cr, uid, ids, context or {}): if record.state=="running": - raise osv.except_osv(_('Error!'),_('You cannot delete an active subscription!')) + raise UserError(_('You cannot delete an active subscription!')) return super(subscription_subscription, self).unlink(cr, uid, ids, context) def set_done(self, cr, uid, ids, context=None): diff --git a/addons/survey/survey.py b/addons/survey/survey.py index 76eeda2c3f6..da84d8ddc8c 100644 --- a/addons/survey/survey.py +++ b/addons/survey/survey.py @@ -27,6 +27,7 @@ from urlparse import urljoin from itertools import product from collections import Counter from collections import OrderedDict +from openerp.exceptions import UserError import datetime import logging @@ -436,13 +437,12 @@ class survey_survey(osv.Model): ''' Open a window to compose an email, pre-filled with the survey message ''' if not self._has_questions(cr, uid, ids, context=None): - raise osv.except_osv(_('Error!'), _('You cannot send an invitation for a survey that has no questions.')) + raise UserError(_('You cannot send an invitation for a survey that has no questions.')) survey_browse = self.pool.get('survey.survey').browse(cr, uid, ids, context=context)[0] if survey_browse.stage_id.closed: - raise osv.except_osv(_('Warning!'), - _("You cannot send invitations for closed surveys.")) + raise UserError(_("You cannot send invitations for closed surveys.")) assert len(ids) == 1, 'This option should only be used for a single \ survey at a time.' @@ -895,8 +895,7 @@ class survey_user_input(osv.Model): ] def copy_data(self, cr, uid, id, default=None, context=None): - raise osv.except_osv(_('Warning!'), _('You cannot duplicate this \ - element!')) + raise UserError(_('You cannot duplicate this element!')) def do_clean_emptys(self, cr, uid, automatic=False, context=None): ''' Remove empty user inputs that have been created manually @@ -1027,8 +1026,7 @@ class survey_user_input_line(osv.Model): return super(survey_user_input_line, self).write(cr, uid, ids, vals, context=context) def copy_data(self, cr, uid, id, default=None, context=None): - raise osv.except_osv(_('Warning!'), _('You cannot duplicate this \ - element!')) + raise UserError(_('You cannot duplicate this element!')) def save_lines(self, cr, uid, user_input_id, question, post, answer_tag, context=None): diff --git a/addons/survey/wizard/survey_email_compose_message.py b/addons/survey/wizard/survey_email_compose_message.py index b9ac466331c..712b37b1f83 100644 --- a/addons/survey/wizard/survey_email_compose_message.py +++ b/addons/survey/wizard/survey_email_compose_message.py @@ -23,6 +23,7 @@ from openerp.osv import osv from openerp.osv import fields from openerp.tools.translate import _ from datetime import datetime +from openerp.exceptions import UserError import re import uuid @@ -92,7 +93,7 @@ class survey_mail_compose_message(osv.TransientModel): else: emails_checked.append(email) if error_message: - raise osv.except_osv(_('Warning!'), _("One email at least is incorrect: %s" % error_message)) + raise UserError(_("One email at least is incorrect: %s" % error_message)) emails_checked.sort() values = {'multi_email': '\n'.join(emails_checked)} @@ -185,7 +186,7 @@ class survey_mail_compose_message(osv.TransientModel): for wizard in self.browse(cr, uid, ids, context=context): # check if __URL__ is in the text if wizard.body.find("__URL__") < 0: - raise osv.except_osv(_('Warning!'), _("The content of the text don't contain '__URL__'. \ + raise UserError(_("The content of the text don't contain '__URL__'. \ __URL__ is automaticaly converted into the special url of the survey.")) if not wizard.multi_email and not wizard.partner_ids and (context.get('default_partner_ids') or context.get('default_multi_email')): @@ -210,7 +211,7 @@ class survey_mail_compose_message(osv.TransientModel): if not len(emails_list) and not len(partner_list): if wizard.model == 'res.partner' and wizard.res_id: return False - raise osv.except_osv(_('Warning!'), _("Please enter at least one valid recipient.")) + raise UserError(_("Please enter at least one valid recipient.")) for email in emails_list: partner_id = partner_obj.search(cr, uid, [('email', '=', email)], context=context) diff --git a/addons/web/controllers/main.py b/addons/web/controllers/main.py index 7890d0947b0..6bd249db364 100644 --- a/addons/web/controllers/main.py +++ b/addons/web/controllers/main.py @@ -38,6 +38,7 @@ from openerp.tools.translate import _ from openerp import http from openerp.http import request, serialize_exception as _serialize_exception +from openerp.exceptions import AccessError _logger = logging.getLogger(__name__) @@ -959,7 +960,7 @@ class DataSet(http.Controller): return records if method.startswith('_'): - raise Exception("Access Denied: Underscore prefixed methods cannot be remotely called") + raise AccessError(_("Underscore prefixed methods cannot be remotely called")) return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs) diff --git a/addons/web/static/src/js/chrome.js b/addons/web/static/src/js/chrome.js index add1e4e4dfa..e832ecbf2cc 100644 --- a/addons/web/static/src/js/chrome.js +++ b/addons/web/static/src/js/chrome.js @@ -7,7 +7,8 @@ var instance = openerp; openerp.web.chrome = {}; var QWeb = instance.web.qweb, - _t = instance.web._t; + _t = instance.web._t, + _lt = instance.web._lt; instance.web.Notification = instance.web.Widget.extend({ template: 'Notification', @@ -260,8 +261,52 @@ instance.web.CrashManager = instance.web.Class.extend({ this.show_warning({type: "Session Expired", data: { message: _t("Your Odoo session expired. Please refresh the current web page.") }}); return; } - if (error.data.exception_type === "except_osv" || error.data.exception_type === "warning" || error.data.exception_type === "access_error") { + var map_title ={ + user_error: _lt('Warning'), + warning: _lt('Warning'), + access_error: _lt('Access Error'), + missing_error: _lt('Missing Record'), + validation_error: _lt('Validation Error'), + except_orm: _lt('Global Business Error'), + access_denied: _lt('Access Denied'), + }; + if (_.has(map_title, error.data.exception_type)) { + if(error.data.exception_type == 'except_orm'){ + if(error.data.arguments[1]) { + error = _.extend({}, error, + { + data: _.extend({}, error.data, + { + message: error.data.arguments[1], + title: error.data.arguments[0] !== 'Warning' ? (" - " + error.data.arguments[0]) : '', + }) + }); + } + else { + error = _.extend({}, error, + { + data: _.extend({}, error.data, + { + message: error.data.arguments[0], + title: '', + }) + }); + } + } + else { + error = _.extend({}, error, + { + data: _.extend({}, error.data, + { + message: error.data.arguments[0], + title: map_title[error.data.exception_type] !== 'Warning' ? (" - " + map_title[error.data.exception_type]) : '', + }) + }); + } + this.show_warning(error); + //InternalError + } else { this.show_error(error); } @@ -270,12 +315,10 @@ instance.web.CrashManager = instance.web.Class.extend({ if (!this.active) { return; } - if (error.data.exception_type === "except_osv") { - error = _.extend({}, error, {data: _.extend({}, error.data, {message: error.data.arguments[0] + "\n\n" + error.data.arguments[1]})}); - } new instance.web.Dialog(this, { size: 'medium', - title: "Odoo " + (_.str.capitalize(error.type) || "Warning"), + title: "Odoo " + (_.str.capitalize(error.type) || _t("Warning")), + subtitle: error.data.title, buttons: [ {text: _t("Ok"), click: function() { this.parents('.modal').modal('hide'); }} ], diff --git a/addons/web/static/src/xml/base.xml b/addons/web/static/src/xml/base.xml index cee3bcd936b..b0bceafc5a3 100644 --- a/addons/web/static/src/xml/base.xml +++ b/addons/web/static/src/xml/base.xml @@ -29,7 +29,7 @@