-- This view needs to be dropped and recreated in order to change the type of the column external_status to text
DROP VIEW v_funnel_order_rows;

ALTER TABLE order_rows
ALTER COLUMN external_status SET DATA TYPE text,
ALTER COLUMN external_status SET default 'N/A';

-- Recreate view v_funnel_order_rows
CREATE OR REPLACE VIEW public.v_funnel_order_rows
 AS
 SELECT r.id,
    r.order_id,
    r.inserted,
    r.type,
    o.customer_type,
    o.market,
    pp.path,
    pp.publishing_date,
    pp.ref1,
    pp.ref2,
    r.data ->> 'width'::text AS width,
    r.data ->> 'height'::text AS height,
    r.sub_type,
    r.status,
    r.price,
    r.commission_amount,
    r.external_status,
    r.data ->> 'productId'::text AS product_id,
    r.data ->> 'material'::text AS material,
    r.data ->> 'artNo'::text AS artno,
    r.data ->> 'designer'::text AS designer,
    (r.data ->> 'inquiryid'::text)::integer AS inquiry_id,
        CASE r.type
            WHEN 'refund'::order_row_type THEN COALESCE((r.data ->> 'discount_amount'::text)::numeric, 0::numeric)
            ELSE 0::numeric - COALESCE((r.data ->> 'discount_amount'::text)::numeric, 0::numeric)
        END AS discount,
        CASE r.type
            WHEN 'refund'::order_row_type THEN NULL::text
            ELSE r.data ->> 'segment'::text
        END AS segment,
        CASE r.type
            WHEN 'refund'::order_row_type THEN NULL::numeric
            ELSE (r.data ->> 'segment_price'::text)::numeric
        END AS segment_price,
    r.data ->> 'reprinted_order_row_id'::text AS reprinted_order_row_id
   FROM order_rows r
     JOIN orders o ON r.order_id = o.id
     LEFT JOIN "product-products" pp ON ((r.data ->> 'productId'::text)::integer) = pp.productid;

ALTER TABLE public.v_funnel_order_rows
    OWNER TO root;

GRANT SELECT ON TABLE public.v_funnel_order_rows TO funnel;
GRANT DELETE, UPDATE, SELECT, INSERT ON TABLE public.v_funnel_order_rows TO photowall;
GRANT ALL ON TABLE public.v_funnel_order_rows TO root;
