from odoo import fields, models, tools class PromotionMonitoring(models.Model): _name = "promotion.monitoring" _auto = False _rec_name = "product_id" product_id = fields.Many2one(comodel_name="product.product", string="Product") manufacture_id = fields.Many2one(comodel_name="x_manufactures", string="Manufacture", related="product_id.x_manufacture") price = fields.Float(string="Price", help="Computed Price di Product Pricelist (Tier 1 New)") has_promo = fields.Boolean(string="Has Promo") count_active = fields.Integer(string="Count Active") count_inactive = fields.Integer(string="Count Inactive") human_last_update = fields.Datetime(string='Human Last Update') promotion_program_line_names = fields.Text(string="Promotion Program Line Names") def init(self): tools.drop_view_if_exists(self.env.cr, self._table) sql = { 'count_active': "COUNT(CASE WHEN ppl.active = True THEN ppl.id ELSE NULL END)", 'count_inactive': "COUNT(CASE WHEN ppl.active = False THEN ppl.id ELSE NULL END)" } self.env.cr.execute(""" CREATE OR REPLACE VIEW {table} AS ( SELECT p.id as id, p.id as product_id, ppi.computed_price as price, (COUNT(ppl.id) FILTER (WHERE ppl.active = True) > 0) as has_promo, COUNT(ppl.id) FILTER (WHERE ppl.active = True) as count_active, COUNT(ppl.id) FILTER (WHERE ppl.active = False) as count_inactive, pr.human_last_update as human_last_update, STRING_AGG(DISTINCT ppl.name, ', ') as promotion_program_line_names -- Concatenate promotion_program_line names FROM product_product p LEFT JOIN product_template pt ON pt.id = p.product_tmpl_id LEFT JOIN promotion_product pp ON pp.product_id = p.id LEFT JOIN promotion_program_line ppl ON ppl.id = pp.program_line_id LEFT JOIN product_pricelist_item ppi ON ppi.product_id = p.id LEFT JOIN purchase_pricelist pr ON pr.product_id = p.id LEFT JOIN promotion_product prp ON prp.product_id = p.id -- Join with promotion.product WHERE p.active = True AND pt.sale_ok = True AND ppi.pricelist_id = 17023 GROUP BY p.id, ppi.id, pr.human_last_update ); """.format( table=self._table, count_active=sql['count_active'], count_inactive=sql['count_inactive'] ))