Odoo中的通知或异常提示

发布时间 2023-09-25 14:11:00作者: CrossPython

在Odoo框架中,可以找到各种各样的通知类型。用于在用户进行系统操作时,即时反馈相关的异常信息。常用的通知选项有如下几种:

1. Sticky Notification
2. Rainbow Man Effect
3. Alert
4. Raise Exception/Validation

第一种显示通知设计为非侵入式通知。它们显示为临时弹出消息,不会阻止用户与系统的交互。用户可以继续执行其任务,同时仍能了解该消息。如下图样式:

这类通知可以由后端python代码触发,也可以由前端的js代码触发。其中python代码示例为:

notification = {
    'type': 'ir.actions.client',
    'tag': 'display_notification',
    'params': {
        'title': _('Warning'),
        'type': 'warning',
        'message': 'You cannot do this action now',
        'sticky': True,
    }
 }
 return notification

  

上面params中的参数有如下几个:

title:消息的标题
message:消息正文
type:消息类型(info,success, warning, danger)影响消息框左边的颜色显示
links:消息附带的超链接,如[{label:'ok',url:'#'}]
sticky:消息是否自动关闭(True:手动关闭,False:自动关闭)
next:下一个动作定义{'type': 'ir.actions.act_window_close'}

  

JS前端触发消息提醒的代码示例为:

this.displayNotification({
    message: _.str.sprintf(_t("Could not save file <strong>%s</strong>"),_.escape(file.name)),
    type: 'warning',
    sticky: true,
});

  

在js中参数对象就是上面py方法中的params对象内容。

第二种消息提醒是彩虹人特效。这个在odoo的内核中使用了一个特效服务,代码是在:

addons\web\static\src\core\effects\effect_service.js

  

这个代码里注册了一个'rainbow_man'类型的特效,主要效果就是在完成某个操作以后,在屏幕上显示出一个图像动画,比如CRM中的线索转换为商机以后会有类似的提示。在python方法中可以用如下语法触发这个物效:

return {
   'effect': {
      'fadeout': 'fast',
      'message': '这里是提示的内容',
      'img_url': '/web/image/%s/%s/image_1024' % (self.team_id.user_id._name, self.team_id.user_id.id) if self.team_id.user_id.image_1024 else '/web/static/img/smile.svg',
      'type': 'rainbow_man',
   }
}

  

这里的图片链接地址根据你自己的记录来进行调整。参数fadeout是指特效淡出的速度,是快、中、慢几个选项。

如果是在JS的controller对象中的话,可以用如下语法来执行;

async setup() {
    super.setup();
    this.effect = useService("effect");
}

async setRainbowMan(message) {
    this.effect.add({
        message,
         type: "rainbow_man",
    });
}

  

第三种消息提醒是浏览器中自带的alert方法,如:

alert(_t('An error occurred when loading product prices. ' +
         'Make sure all pricelists are available in the POS.'
));

  

第四种消息是我们见得最多的,就是在python中执行时如果抛出一个异常,则会在浏览器中提示一个弹窗,需要用户关闭弹窗后才能继续作业。这个js处理的主要代码是在:

addons\web\static\src\core\errors\error_dialogs.js

  

我们主要看最后一句的内容:

registry
    .category("error_dialogs")
    .add("odoo.exceptions.AccessDenied", WarningDialog)
    .add("odoo.exceptions.AccessError", WarningDialog)
    .add("odoo.exceptions.MissingError", WarningDialog)
    .add("odoo.exceptions.UserError", WarningDialog)
    .add("odoo.exceptions.ValidationError", WarningDialog)
    .add("odoo.exceptions.RedirectWarning", RedirectWarningDialog)
    .add("odoo.http.SessionExpiredException", SessionExpiredDialog)
    .add("werkzeug.exceptions.Forbidden", SessionExpiredDialog)
    .add("504", Error504Dialog);

  

这里我们可以看出,不管从python中抛出来的异常是AccessDenied、AccessError、MissingError、UserError、ValidationError,在前端都是响应WarningDialog对话框,只是根据不同的异常类型显示了不同的对话框标题栏文字(源码中odooExceptionTitleMap对像映射)。

上面有一种特殊的异常类型为RedirectWarning,这个在python中的定义为:

class RedirectWarning(Exception):
    """ Warning with a possibility to redirect the user instead of simply
    displaying the warning message.

    :param str message: exception message and frontend modal content
    :param int action_id: id of the action where to perform the redirection
    :param str button_text: text to put on the button that will trigger
        the redirection.
    :param dict additional_context: parameter passed to action_id.
           Can be used to limit a view to active_ids for example.
    """
    def __init__(self, message, action, button_text, additional_context=None):
        super().__init__(message, action, button_text, additional_context)

  

 

说明这个异常在调用时可以传四个参数进去,提示的文字消息、要跳转的动作ID,跳转链接的文字,跳转动作的上下文。一个实际使用的例子如下:

action = self.env.ref('account.action_account_config')
msg = _('Cannot find a chart of accounts for this company, You should configure it. \nPlease go to Account Configuration.')
raise RedirectWarning(msg, action.id, _('Go to the configuration panel'))

  

最后还有一个比较特殊的消息提醒异常是SessionExpiredException,这个主要是当前操作的连线丢失或过期了,就会有提示,当你关闭这个对话框时,浏览器会重定向到login界面。

以上就是在Odoo中各类消息提醒的简要总结,大家可以根据业务需要选择不同的消息提醒方式来简化系统交互,增强用户的参与度。