-- Fix v_listprice issues

-- Only change from previous view definition:
-- 1) designers price premium coeffient should default to 1.0, not 1.01 (line 33)
-- 2) round to 8 decimals instead of 2 (line 41)

drop view if exists v_listprices;

create view v_listprices as
select
    printid printproduct_id,
    markets.id market_id,
    round(
		-- Base price
		CASE
			WHEN groupid IN (1,3) THEN -- Wallpaper
				(select (price/100.0) from "product-materials" where material = 'standard-wallpaper')
			WHEN groupid = 2 THEN -- Canvas
				(select min(price_sek) from external_print_products where group_id = 2)
			WHEN groupid IN (7,8) THEN -- Poster
				(select min(price_sek) from external_print_products where group_id in (7,8))
		END
        -- Market price adjustment, and VAT, and currency exchange rate
        * exchange_rate * price_adjustment * vat
        -- Designer price premium, if exist
        * (coalesce(
			CASE
				WHEN groupid IN (1,3) THEN pricepremium_wallpaper
				WHEN groupid = 2 THEN pricepremium_canvas
				WHEN groupid = 7 THEN pricepremium_poster
				WHEN groupid = 8 THEN pricepremium_framed_print
			END
			, 0) / 100.0 + 1)
		-- Local product type adjustments, if wallpaper, and if exists
		* COALESCE(
			CASE WHEN groupid in (1,3) THEN
				(select value from price_adjustments where material_id = 1 and product_type = 'product' and market_id = markets.id limit 1)
			END
		, 1.0)
        -- Round to eight decimals
        , 8) listprice
from
    "product-printproducts"
    join "product-products" using (productid)
    left join designers using (designerid),
    markets join "product-currencies" on currency = iso3char
;

COMMENT ON COLUMN v_listprices.listprice IS 'Canvas and poster listprice:
Start with price (SEK) for cheapest canvas/poster size.
Multiply with market price adjustment, VAT and currency exchange rate.
Multiply with designer price premium, if exists.
Round to two decimals.

Wallpaper listprice:
Same as poster/canvas, but start with the price for 1 m/2 standard wallpaper.
Also include local wallpaper price adjustments (per market, product type, and material) if exists.';
