-- P5-358
DROP MATERIALIZED VIEW IF EXISTS v_esales_category_count;
CREATE MATERIALIZED VIEW v_esales_category_count
AS
SELECT  id, locale_id, product_id, groupid, wallpapertype_id,
        CASE
            WHEN blacklist_id IS NULL AND visible = 1 AND browsable = 1 THEN true
            ELSE false
        END AS is_visible
  FROM  (
            SELECT  p.id,
                    locales.id AS locale_id,
                    pc.product_id,
                    groupid,
                    CASE groupid
                        WHEN 2 THEN NULL
                        ELSE wallpapertype_id
                    END AS wallpapertype_id,
                    (
                        SELECT  id
                          FROM  product_blacklist
                         WHERE  product_id = pc.product_id
                           AND  language_id = SUBSTR(locales.value, 1, 2)
                           AND  territory_id = SUBSTR(locales.value, 4)
                           AND  (group_id = groupid OR group_id IS NULL)
                    ) blacklist_id,
                    visible,
                    browsable
              FROM  categories p
              JOIN  categories c ON c.lft >= p.lft AND c.rgt <= p.rgt
              JOIN  product_category pc ON c.id = pc.category_id
              JOIN  (
                        SELECT  productid,
                                groupid
                          FROM  "product-printproducts"
                    ) pp ON pc.product_id = pp.productid
              JOIN  (SELECT productid, visible, browsable FROM "product-products") prod ON pc.product_id = prod.productid
              LEFT  JOIN product_wallpapertypes pw ON pc.product_id = pw.product_id,
              locales
        ) main
 GROUP  BY id, locale_id, product_id, groupid, wallpapertype_id, visible, browsable, blacklist_id;

-- DROP INDEX public.v_esales_category_count_id_idx;
CREATE UNIQUE INDEX v_esales_category_count_id_idx
    ON v_esales_category_count (id, locale_id, product_id, groupid, wallpapertype_id);
