Odoo 15客户发票树视图新增记录时如何实现自动刷新
Odoo 15 客户发票树视图自动刷新实现方案
Odoo 原生没有树视图自动感知数据更新刷新的功能,可通过Odoo自带的bus长连接消息模块实现,以下是具体实现步骤,稳定性高、性能损耗小:
不推荐使用前端定时轮询的方案,会持续占用服务端资源,用户量较多时会产生明显性能压力。
1. 自定义模块依赖声明
在你的自定义模块的__manifest__.py配置文件中,添加依赖项:
'depends': ['base', 'account', 'bus'],
2. 发票创建时推送消息通知
继承account.move模型,重写create方法,新发票创建后推送总线通知:
from odoo import models, api import json class AccountMove(models.Model): _inherit = 'account.move' @api.model def create(self, vals): record = super().create(vals) # 仅针对客户发票推送通知,可根据move_type调整过滤范围 if record.move_type == 'out_invoice': # 推送消息到指定总线频道 self.env['bus.bus']._sendone( 'account_move_updates', 'new_invoice', json.dumps({'id': record.id}) ) return record
3. 前端树视图监听消息触发刷新
在自定义模块中新增静态JS文件static/src/js/invoice_auto_refresh.js,扩展树视图控制器逻辑:
odoo.define('your_module_name.invoice_auto_refresh', function (require) { "use strict"; const ListController = require('web.ListController'); const bus = require('bus.bus'); ListController.include({ init: function () { this._super.apply(this, arguments); // 仅对客户发票树视图生效 if (this.modelName === 'account.move' && this.getContext().default_move_type === 'out_invoice') { // 订阅发票更新频道 bus.bus.add_channel('account_move_updates'); // 绑定消息监听回调 bus.bus.on('notification', this, this._handleInvoiceUpdate); } }, _handleInvoiceUpdate: function (notifications) { for (const notif of notifications) { if (notif[0] === 'account_move_updates' && notif[1] === 'new_invoice') { // 刷新树视图数据,不会重载整个页面 this.reload(); } } } }); });
注意将代码中的your_module_name替换为你自己的自定义模块的技术名称
4. 引入JS资源到后端视图
在自定义模块的XML视图文件中添加资源引入配置:
<odoo> <template id="assets_backend_custom" inherit_id="web.assets_backend"> <xpath expr="." position="inside"> <script type="text/javascript" src="/your_module_name/static/src/js/invoice_auto_refresh.js"/> </xpath> </template> </odoo>
额外优化说明
- 如需做权限控制,避免无发票查看权限的用户收到通知,可根据用户权限组生成独立频道,仅向有权限的用户推送消息
- 可调整刷新逻辑,不需要全量重载列表,仅将新增记录插入到列表头部,进一步提升性能
- 生产环境需确保Odoo长连接服务配置正常,建议启用worker模式优化bus消息推送效率
内容的提问来源于stack exchange,提问作者shashank verma
相关产品推荐
相关产品推荐

