-- View: public.vw_utility_sale_physical_contract

-- DROP VIEW public.vw_utility_sale_physical_contract;

CREATE OR REPLACE VIEW public.vw_utility_sale_physical_contract AS
 SELECT sl.id AS "intSaleLineId",
    sl.from_del AS "dtmDeliveryDateFrom",
    sl.to_del AS "dtmDeliveryDateTo",
    sl.quantity AS "dblQuantity",
    pu1.name AS "strSaleUom",
    0 AS "dblDeliveredQuantity",
    sl.linked_price AS "dblPrice",
    pu2.name AS "strPriceUnit",
    'n/a'::text AS "strPriceCurrency",
    sl.unit_price AS "dblUnitPrice",
    sl.quantity_theorical AS "dblTheoreticalQuantity",
    round((sl.quantity * sl.unit_price::double precision)::numeric, get_rounding_position(2::numeric)) AS "dblLineAmount",
    'n/a'::text AS "strCurrency",
    0::numeric AS "dblLineBaseAmount",
    ''::text AS "strBaseCurrency",
    0::numeric AS "dblQuantityInBaseUnit",
    ''::text AS "strBaseUnit",
    0::numeric AS "dblFixedPrice",
    0::numeric AS "dblFixedQuantity",
    0::numeric AS "dblFixedAmount",
    0::numeric AS "dblUnFixedPrice",
    0::numeric AS "dblUnfixedQuantity",
    0::numeric AS "dblUnfixedAmount",
    0::numeric AS "dblInvoicedQuantity",
    0::numeric AS "dblInvoicedAmount",
    ''::text AS "strInvoiceCurrency",
    convert_weight(sl.quantity_theorical, pu1.name::text, 'Kilogram'::text) AS "dblTheoreticalWeightKg",
    COALESCE(shipped."dblNetWeightKg"::double precision, 0::double precision) AS "dblPhysicalWeightKg",
    convert_weight(sl.quantity_theorical, pu1.name::text, 'Kilogram'::text)::double precision - COALESCE(shipped."dblNetWeightKg"::double precision, 0::double precision) AS "dblOpenWeightKg",
    COALESCE(bl.estimated_date, sl.from_del) AS "dtmEstimatedBLDate"
   FROM sale_line sl
     JOIN sale_sale sc ON sl.sale = sc.id
     JOIN product_uom pu1 ON sl.unit = pu1.id
     LEFT JOIN product_uom pu2 ON sl.linked_unit = pu2.id
     LEFT JOIN ( SELECT lot."intSaleLineId",
            sum(lot."dblNetWeightKg") AS "dblNetWeightKg"
           FROM vw_utility_lot lot
          WHERE lot."strType"::text = 'physic'::text AND lot."intSaleLineId" IS NOT NULL AND lot."intSaleLineId" > 0
          GROUP BY lot."intSaleLineId") shipped ON sl.id = shipped."intSaleLineId"
     LEFT JOIN pricing_estimated bl ON sl.id = bl.sale_line
  WHERE 1 = 1;

ALTER TABLE public.vw_utility_sale_physical_contract
    OWNER TO postgres;
