 
 
/*********************************************\
*   ABSSOLUTE Oracle Objects                  *
*                                             *
*   Objects:           VIEWS                  *
*   Database version:  09.09.00               *
*   Date:              15-APR-2026            *
\*********************************************/
 
set define off 
 

  CREATE OR REPLACE VIEW "MAX_DELIVERYFREQUENCY" ("FREQUENCY", "CUSTOMER_ID") AS 
  select --a.deliveryscheme_id,a.code,
min(a.frequency)frequency, c.customer_id--, c.customernumber
from deliveryscheme a,customerdeliveryscheme b, customer c
where a.deliveryscheme_id = b.deliveryscheme_id
and b.customer_id = c.customer_id
GROUP by
--a.deliveryscheme_id,a.code, a.frequency,
 --b.day_id,
 c.customer_id--, c.customernumber
 union
(select 0, c2.customer_id
from customer c2
where not exists (select 1
                 from customerdeliveryscheme cds
                 where cds.customer_id = c2.customer_id))
/

  CREATE OR REPLACE VIEW "V_AMOUNTDAY" ("STANDARDDELIVERYLINE_ID", "AMOUNT_MO", "AMOUNT_TU", "AMOUNT_WE", "AMOUNT_TH", "AMOUNT_FR", "AMOUNT_SA", "AMOUNT_SU") AS 
  SELECT   STANDARDDELIVERYAMOUNT.STANDARDDELIVERYLINE_ID, STANDARDDELIVERYAMOUNT.AMOUNT AMOUNT_MO, 0 amount_tu,0 amount_we,0 amount_th,0 amount_fr,0 amount_sa,0 amount_su
FROM STANDARDDELIVERYAMOUNT, DAY
WHERE
STANDARDDELIVERYAMOUNT.DAY_ID=DAY.DAY_ID
and DAY.DAYNUMBER=1
UNION ALL
SELECT    STANDARDDELIVERYAMOUNT.STANDARDDELIVERYLINE_ID,0,STANDARDDELIVERYAMOUNT.AMOUNT AMOUNT_TU, 0,0,0,0,0  FROM STANDARDDELIVERYAMOUNT, DAY
WHERE
STANDARDDELIVERYAMOUNT.DAY_ID=DAY.DAY_ID
and DAY.DAYNUMBER=2
UNION ALL
SELECT  STANDARDDELIVERYAMOUNT.STANDARDDELIVERYLINE_ID,0,0,STANDARDDELIVERYAMOUNT.AMOUNT AMOUNT_WE,0,0,0,0  FROM STANDARDDELIVERYAMOUNT, DAY
WHERE
STANDARDDELIVERYAMOUNT.DAY_ID=DAY.DAY_ID
and DAY.DAYNUMBER=3
UNION ALL
SELECT   STANDARDDELIVERYAMOUNT.STANDARDDELIVERYLINE_ID, 0,0,0,STANDARDDELIVERYAMOUNT.AMOUNT AMOUNT_TH,0,0,0  FROM STANDARDDELIVERYAMOUNT, DAY
WHERE
STANDARDDELIVERYAMOUNT.DAY_ID=DAY.DAY_ID
and DAY.DAYNUMBER=4
UNION ALL
SELECT   STANDARDDELIVERYAMOUNT.STANDARDDELIVERYLINE_ID, 0,0,0,0,STANDARDDELIVERYAMOUNT.AMOUNT AMOUNT_FR,0,0  FROM STANDARDDELIVERYAMOUNT, DAY
WHERE
STANDARDDELIVERYAMOUNT.DAY_ID=DAY.DAY_ID
and DAY.DAYNUMBER=5
UNION ALL
SELECT   STANDARDDELIVERYAMOUNT.STANDARDDELIVERYLINE_ID, 0,0,0,0,0,STANDARDDELIVERYAMOUNT.AMOUNT AMOUNT_SA,0  FROM STANDARDDELIVERYAMOUNT, DAY
WHERE
STANDARDDELIVERYAMOUNT.DAY_ID=DAY.DAY_ID
and DAY.DAYNUMBER=6
UNION ALL
SELECT   STANDARDDELIVERYAMOUNT.STANDARDDELIVERYLINE_ID, 0,0,0,0,0,0,STANDARDDELIVERYAMOUNT.AMOUNT AMOUNT_Su  FROM STANDARDDELIVERYAMOUNT, DAY
WHERE
STANDARDDELIVERYAMOUNT.DAY_ID=DAY.DAY_ID
and DAY.DAYNUMBER=7
/

  CREATE OR REPLACE VIEW "V_COUNTDELIVERIES" ("CUSTOMER_LINK_ID", "DISTRIBUTIONPOINT_LINK_ID", "DELIVERYDATE") AS 
  select distinct
a.customer_link_id, a.distributionpoint_link_id, a.deliverydate
from deliveryhistory a
/

  CREATE OR REPLACE VIEW "V_DELIVERYDAY" ("DEPARTMENT_ID", "DAYNUMBER", "DELIVERY_MO", "DELIVERY_TU", "DELIVERY_WE", "DELIVERY_TH", "DELIVERY_FR", "DELIVERY_SA", "DELIVERY_SU") AS 
  select   DELIVERYDAY.DEPARTMENT_ID, DAY.DAYNUMBER,1,0,0,0,0,0,0 from deliveryday, day
where deliveryday.day_id = day.day_id
AND DAY.DAYNUMBER=1
UNION ALL
select   DELIVERYDAY.DEPARTMENT_ID, DAY.DAYNUMBER,0,1,0,0,0,0,0  from deliveryday, day
where deliveryday.day_id = day.day_id
AND DAY.DAYNUMBER=2
UNION ALL
select   DELIVERYDAY.DEPARTMENT_ID, DAY.DAYNUMBER,0,0,1,0,0,0,0 from deliveryday, day
where deliveryday.day_id = day.day_id
AND DAY.DAYNUMBER=3
UNION ALL
select   DELIVERYDAY.DEPARTMENT_ID, DAY.DAYNUMBER,0,0,0,1,0,0,0 from deliveryday, day
where deliveryday.day_id = day.day_id
AND DAY.DAYNUMBER=4
UNION ALL
select   DELIVERYDAY.DEPARTMENT_ID, DAY.DAYNUMBER,0,0,0,0,1,0,0 from deliveryday, day
where deliveryday.day_id = day.day_id
AND DAY.DAYNUMBER=5
UNION ALL
select   DELIVERYDAY.DEPARTMENT_ID, DAY.DAYNUMBER,0,0,0,0,0,1,0 from deliveryday, day
where deliveryday.day_id = day.day_id
AND DAY.DAYNUMBER=6
UNION ALL
select   DELIVERYDAY.DEPARTMENT_ID, DAY.DAYNUMBER,0,0,0,0,0,0,1 from deliveryday, day
where deliveryday.day_id = day.day_id
AND DAY.DAYNUMBER=7
/

  CREATE OR REPLACE VIEW "V_MOVEDOUTSTOPS" ("STOP_ID", "ROUTENUMBER", "DESCRIPTION", "MOVEDTOSTOP_ID") AS 
  select s.stop_id, r.routenumber, r.description, s.movedtostop_id
from stop s , routecontrol t, route r
where s.routecontrol_id = t.routecontrol_id
and t.route_id = r.route_id
and s.status = 2
/

  CREATE OR REPLACE VIEW "V_NORMSTOCKAMOUNTDAY" ("PRODUCTLISTPERDISTRIBPOINT_ID", "AMOUNT_MO", "AMOUNT_TU", "AMOUNT_WE", "AMOUNT_TH", "AMOUNT_FR", "AMOUNT_SA", "AMOUNT_SU") AS 
  SELECT   NORMSTOCKAMOUNT.PRODUCTLISTPERDISTRIBPOINT_ID, NORMSTOCKAMOUNT.AMOUNT AMOUNT_MO, 0,0,0,0,0,0
FROM NORMSTOCKAMOUNT, DAY
WHERE
NORMSTOCKAMOUNT.DAY_ID=DAY.DAY_ID
and DAY.DAYNUMBER=1
UNION ALL
SELECT     NORMSTOCKAMOUNT.PRODUCTLISTPERDISTRIBPOINT_ID,0,NORMSTOCKAMOUNT.AMOUNT AMOUNT_TU, 0,0,0,0,0  FROM NORMSTOCKAMOUNT, DAY
WHERE
NORMSTOCKAMOUNT.DAY_ID=DAY.DAY_ID
and DAY.DAYNUMBER=2
UNION ALL
SELECT NORMSTOCKAMOUNT.PRODUCTLISTPERDISTRIBPOINT_ID,0,0,NORMSTOCKAMOUNT.AMOUNT AMOUNT_WE,0,0,0,0  FROM NORMSTOCKAMOUNT, DAY
WHERE
NORMSTOCKAMOUNT.DAY_ID=DAY.DAY_ID
and DAY.DAYNUMBER=3
UNION ALL
SELECT   NORMSTOCKAMOUNT.PRODUCTLISTPERDISTRIBPOINT_ID, 0,0,0,NORMSTOCKAMOUNT.AMOUNT AMOUNT_TH,0,0,0  FROM NORMSTOCKAMOUNT, DAY
WHERE
NORMSTOCKAMOUNT.DAY_ID=DAY.DAY_ID
and DAY.DAYNUMBER=4
UNION ALL
SELECT   NORMSTOCKAMOUNT.PRODUCTLISTPERDISTRIBPOINT_ID, 0,0,0,0,NORMSTOCKAMOUNT.AMOUNT AMOUNT_FR,0,0  FROM NORMSTOCKAMOUNT, DAY
WHERE
NORMSTOCKAMOUNT.DAY_ID=DAY.DAY_ID
and DAY.DAYNUMBER=5
UNION ALL
SELECT   NORMSTOCKAMOUNT.PRODUCTLISTPERDISTRIBPOINT_ID, 0,0,0,0,0,NORMSTOCKAMOUNT.AMOUNT AMOUNT_SA,0  FROM NORMSTOCKAMOUNT, DAY
WHERE
NORMSTOCKAMOUNT.DAY_ID=DAY.DAY_ID
and DAY.DAYNUMBER=6
UNION ALL
SELECT   NORMSTOCKAMOUNT.PRODUCTLISTPERDISTRIBPOINT_ID, 0,0,0,0,0,0,NORMSTOCKAMOUNT.AMOUNT AMOUNT_SO  FROM NORMSTOCKAMOUNT, DAY
WHERE
NORMSTOCKAMOUNT.DAY_ID=DAY.DAY_ID
and DAY.DAYNUMBER=7
/

  CREATE OR REPLACE VIEW "V_PACKINGNOTELINEPERDELSCH_EXT" ("PACKINGNOTELINE_ID", "DELIVEREDQTY", "TOBEDELIVEREDQTY", "DELIVERYSCHEME_ID", "STARTDATE") AS 
  select  l.packingnoteline_id, sum(ld.deliveredqty) deliveredqty,
       sum(ld.tobedeliveredqty) tobedeliveredqty,
       ld.deliveryscheme_id deliveryscheme_id, ld.startdate
from   packingnoteline l, packingnotelineperdelscheme ld
where  l.packingnoteline_id = ld.packingnoteline_id
group  by l.packingnoteline_id,ld.deliveryscheme_id, ld.startdate
union all
select l.packingnoteline_id, sum(l.deliveredamount) - sum(ld.deliveredqty) deliveredqty,
       sum(l.tobedeliveredamount) - sum(ld.tobedeliveredqty) tobedeliveredqty,
       null deliveryscheme_id, null startdate
from   packingnoteline l, packingnotelineperdelscheme ld
where  l.packingnoteline_id = ld.packingnoteline_id
and ld.deliveryscheme_id is null
group  by l.packingnoteline_id,  LD.DELIVERYSCHEME_ID
having sum(l.deliveredamount) > sum(ld.deliveredqty)
/

  CREATE OR REPLACE VIEW "V_PEPPOL_INVOICELINE_CREDIT" ("INVOICELINE_ID", "INVOICEHEADER_ID", "LINENUMBER", "INVOICELINETYPE_ID", "CODE", "DESCRIPTION", "ADJUSTEDAMOUNT", "ADJUSTEDPRICE", "ADJUSTMENTBILLEDQTY", "EXTEND", "AMOUNT", "DISCOUNTPERCENTAGE", "PRICE", "BILLEDQTY", "ADJUSTMENTREASON_ID", "TAXGROUPCODE", "SUBJECTTOMINIMUM", "TURNOVERGROUP_ID", "SYSTEMUSER_ID", "TIMESTAMP", "TAXTYPE", "REMARK", "GENERATED", "INVOICELINESUBTYPE", "LOSSWEEKSTOGO", "CREDIT", "CREDITINVOICELINE_ID", "PROCESSINGBUSINESSUNIT_ID", "INVENTORYCATEGORY_ID", "INVENTORYCATEGORYCODE", "BUDGETCODE", "ORIGINALAMOUNT", "REPAIRNUMBEROFMINUTES", "REPAIRPRICEPERMINUTE", "CONTRACTPURCHASEORDER_ID", "CONTRACTPURCHASEORDERLINE_ID", "CONTRACTCOEFFICIENT", "LOSSRECHARGECANCELUSER_ID", "LOSSRECHARGECANCELTIMESTAMP") AS 
  select /*view v_peppol_invoiceline_credit vesion 0.7*/
invoiceline_id,
invoiceheader_id,
linenumber,
invoicelinetype_id,
code,
description,
adjustedamount,
adjustedprice,
adjustmentbilledqty,
extend,
amount * -1 amount,
discountpercentage,
case when nvl(price,0) = 0 then abs(amount)
else abs(price) end price,
case when nvl(price,0) = 0 then
      case when amount < 0
        then 1
        else -1
    end
  else
    case
      when billedqty = round(billedqty) and billedqty <> 0 and abs(round(il.billedqty * il.price, 3) - amount) < 0.01 then
       case
         when amount < 0 then
          round(abs(amount) / abs(price))
         else
          round(abs(amount) / abs(price)) * -1
       end
      else
       case
         when amount < 0 then
          round(abs(amount) / abs(price), 3)
         else
          round(abs(amount) / abs(price), 3) * -1
       end
    end
end billedqty,
adjustmentreason_id,
taxgroupcode,
subjecttominimum,
turnovergroup_id,
systemuser_id,
timestamp,
taxtype,
remark,
generated,
invoicelinesubtype,
lossweekstogo,
credit,
creditinvoiceline_id,
processingbusinessunit_id,
inventorycategory_id,
inventorycategorycode,
budgetcode,
originalamount,
repairnumberofminutes,
repairpriceperminute,
contractpurchaseorder_id,
contractpurchaseorderline_id,
contractcoefficient,
lossrechargecanceluser_id,
lossrechargecanceltimestamp
from invoiceline il
where il.extend = 'Y'
/

  CREATE OR REPLACE VIEW "V_PEPPOL_INVOICELINE_DEBIT" ("INVOICELINE_ID", "INVOICEHEADER_ID", "LINENUMBER", "INVOICELINETYPE_ID", "CODE", "DESCRIPTION", "ADJUSTEDAMOUNT", "ADJUSTEDPRICE", "ADJUSTMENTBILLEDQTY", "EXTEND", "AMOUNT", "DISCOUNTPERCENTAGE", "PRICE", "BILLEDQTY", "ADJUSTMENTREASON_ID", "TAXGROUPCODE", "SUBJECTTOMINIMUM", "TURNOVERGROUP_ID", "SYSTEMUSER_ID", "TIMESTAMP", "TAXTYPE", "REMARK", "GENERATED", "INVOICELINESUBTYPE", "LOSSWEEKSTOGO", "CREDIT", "CREDITINVOICELINE_ID", "PROCESSINGBUSINESSUNIT_ID", "INVENTORYCATEGORY_ID", "INVENTORYCATEGORYCODE", "BUDGETCODE", "ORIGINALAMOUNT", "REPAIRNUMBEROFMINUTES", "REPAIRPRICEPERMINUTE", "CONTRACTPURCHASEORDER_ID", "CONTRACTPURCHASEORDERLINE_ID", "CONTRACTCOEFFICIENT", "LOSSRECHARGECANCELUSER_ID", "LOSSRECHARGECANCELTIMESTAMP") AS 
  select /*view v_peppol_invoiceline_debit vesion 0.7*/
invoiceline_id,
invoiceheader_id,
linenumber,
invoicelinetype_id,
code,
description,
adjustedamount,
adjustedprice,
adjustmentbilledqty,
extend,
amount amount,
discountpercentage,
case when nvl(price,0) = 0 then abs(amount)
else abs(price) end price,
case when nvl(price,0) = 0 then
      case when amount > 0
        then 1
        else -1
    end
  else
    case
      when billedqty = round(billedqty) and billedqty <> 0 and abs(round(il.billedqty * il.price, 3) - amount) < 0.01  then
       case
         when amount > 0 then
          round(abs(amount) / abs(price))
         else
          round(abs(amount) / abs(price)) * -1
       end
      else
       case
         when amount > 0 then
          round(abs(amount) / abs(price), 3)
         else
          round(abs(amount) / abs(price), 3) * -1
       end
    end
end billedqty,
adjustmentreason_id,
taxgroupcode,
subjecttominimum,
turnovergroup_id,
systemuser_id,
timestamp,
taxtype,
remark,
generated,
invoicelinesubtype,
lossweekstogo,
credit,
creditinvoiceline_id,
processingbusinessunit_id,
inventorycategory_id,
inventorycategorycode,
budgetcode,
originalamount,
repairnumberofminutes,
repairpriceperminute,
contractpurchaseorder_id,
contractpurchaseorderline_id,
contractcoefficient,
lossrechargecanceluser_id,
lossrechargecanceltimestamp
from invoiceline il
where il.extend = 'Y'
/

  CREATE OR REPLACE VIEW "V_ROUTECONTAINERS" ("COUNTCONTAINER", "STOP_ID", "ROUTE_ID") AS 
  select /*version 2.0*/
       count(distinct pnc.container_id) countcontainer, pn.stop_id, pn.route_id
  from packingnote pn
       join packingnotecontainer pnc on pn.packingnote_id = pnc.packingnote_id
 where pnc.container_id is not null
 group by pn.stop_id, pn.route_id
/

  CREATE OR REPLACE VIEW "V_STOCKCOUNTDAY" ("STOCKCOUNTSCHEDULE_ID", "DAYNUMBER", "COUNT_MO", "COUNT_TU", "COUNT_WE", "COUNT_TH", "COUNT_FR", "COUNT_SA", "COUNT_SU") AS 
  SELECT   STOCKCOUNTSCHEDULEDAY.STOCKCOUNTSCHEDULE_ID,DAY.DAYNUMBER, 1, 0,0,0,0,0,0
FROM STOCKCOUNTSCHEDULEDAY, DAY
WHERE
STOCKCOUNTSCHEDULEDAY.DAY_ID=DAY.DAY_ID
and DAY.DAYNUMBER=1
UNION ALL
SELECT     STOCKCOUNTSCHEDULEDAY.STOCKCOUNTSCHEDULE_ID, DAY.DAYNUMBER, 0, 1, 0,0,0,0,0  FROM STOCKCOUNTSCHEDULEDAY, DAY
WHERE
STOCKCOUNTSCHEDULEDAY.DAY_ID=DAY.DAY_ID
and DAY.DAYNUMBER=2
UNION ALL
SELECT STOCKCOUNTSCHEDULEDAY.STOCKCOUNTSCHEDULE_ID, DAY.DAYNUMBER, 0,0, 1,0,0,0,0  FROM STOCKCOUNTSCHEDULEDAY, DAY
WHERE
STOCKCOUNTSCHEDULEDAY.DAY_ID=DAY.DAY_ID
and DAY.DAYNUMBER=3
UNION ALL
SELECT   STOCKCOUNTSCHEDULEDAY.STOCKCOUNTSCHEDULE_ID, DAY.DAYNUMBER, 0,0,0, 1,0,0,0  FROM STOCKCOUNTSCHEDULEDAY, DAY
WHERE
STOCKCOUNTSCHEDULEDAY.DAY_ID=DAY.DAY_ID
and DAY.DAYNUMBER=4
UNION ALL
SELECT   STOCKCOUNTSCHEDULEDAY.STOCKCOUNTSCHEDULE_ID, DAY.DAYNUMBER, 0,0,0,0, 1,0,0  FROM STOCKCOUNTSCHEDULEDAY, DAY
WHERE
STOCKCOUNTSCHEDULEDAY.DAY_ID=DAY.DAY_ID
and DAY.DAYNUMBER=5
UNION ALL
SELECT   STOCKCOUNTSCHEDULEDAY.STOCKCOUNTSCHEDULE_ID, DAY.DAYNUMBER, 0,0,0,0,0, 1,0  FROM STOCKCOUNTSCHEDULEDAY, DAY
WHERE
STOCKCOUNTSCHEDULEDAY.DAY_ID=DAY.DAY_ID
and DAY.DAYNUMBER=6
UNION ALL
SELECT   STOCKCOUNTSCHEDULEDAY.STOCKCOUNTSCHEDULE_ID, DAY.DAYNUMBER, 0,0,0,0,0,0, 1  FROM STOCKCOUNTSCHEDULEDAY, DAY
WHERE
STOCKCOUNTSCHEDULEDAY.DAY_ID=DAY.DAY_ID
and DAY.DAYNUMBER=7
/

  CREATE OR REPLACE VIEW "V_STOCKCOUNTSCHEDULEDAY" ("STOCKCOUNTSCHEDULE_ID", "COUNT_MO", "COUNT_TU", "COUNT_WE", "COUNT_TH", "COUNT_FR", "COUNT_SA", "COUNT_SU") AS 
  SELECT STOCKCOUNTSCHEDULE_ID, SUM(COUNT_MO), SUM(COUNT_TU), SUM(COUNT_WE), SUM(COUNT_TH),SUM(COUNT_FR), SUM(COUNT_SA), SUM(COUNT_SU)
FROM V_STOCKCOUNTDAY
GROUP BY STOCKCOUNTSCHEDULE_ID
/

  CREATE OR REPLACE VIEW "V_DELIVERYDAY_F" ("DEPARTMENT_ID", "DELIVERY_MO", "DELIVERY_TU", "DELIVERY_WE", "DELIVERY_TH", "DELIVERY_FR", "DELIVERY_SA", "DELIVERY_SU") AS 
  SELECT DEPARTMENT_ID, SUM(DELIVERY_MO), SUM(DELIVERY_TU), SUM(DELIVERY_WE), SUM(DELIVERY_TH),SUM(DELIVERY_FR), SUM(DELIVERY_SA), SUM(DELIVERY_SU)
FROM V_DELIVERYDAY
GROUP BY DEPARTMENT_ID
/

  CREATE OR REPLACE VIEW "V_NORMSTOCKAMOUNT" ("PRODUCTLISTPERDISTRIBPOINT_ID", "AMOUNT_MO", "AMOUNT_TU", "AMOUNT_WE", "AMOUNT_TH", "AMOUNT_FR", "AMOUNT_SA", "AMOUNT_SU") AS 
  SELECT PRODUCTLISTPERDISTRIBPOINT_ID, SUM(AMOUNT_MO), SUM(AMOUNT_TU), SUM(AMOUNT_WE), SUM(AMOUNT_TH),SUM(AMOUNT_FR), SUM(AMOUNT_SA), SUM(AMOUNT_SU)
FROM V_NORMSTOCKAMOUNTDAY
GROUP BY PRODUCTLISTPERDISTRIBPOINT_ID
/

  CREATE OR REPLACE VIEW "V_ORDERFORM_AUX" ("REPORTPARAM_ID", "COPY_NUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "STREET", "STREET2", "ADDRESS", "ZIPCODE", "CITY", "DEPARTMENTNUMBER", "DEPARTMENTNAME", "DEPACTIVE", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTNUMBERNAME", "DISTRIBACTIVE", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESC", "FINISHINGMETHODCODE", "FINISHINGMETHODDESC", "PRODUCTCODE", "PRODUCTDESC", "CUSTOMCODE", "CUSTOMDESCRIPTION", "CUSTOMER_ID", "AMOUNT", "DELIVERIES", "ORDERINGMETHOD", "SEQUENCENUMBER", "PACKINGSEQUENCE", "DELIVERYPOINT_ID") AS 
  SELECT distinct RP.REPORTPARAM_ID, rp.copy_number, A.CUSTOMERNUMBER--, A.LEGALNAME CUSTOMERNAME
, A.NAME CUSTOMERNAME, F.STREET, F.STREET2
, cast(CONCATENATEWITHBLANK(F.STREET, F.STREET2) as varchar2(255)) ADDRESS, F.ZIPCODE, F.CITY,
  B.DEPARTMENTNUMBER, B.DESCRIPTION DEPARTMENTNAME, b.active DepActive,
  C.DISTRIBUTIONPOINTNUMBER, C.DESCRIPTION DISTRIBUTIONPOINTNUMBERNAME, c.active DistribActive,
  H.CODE SIZEDEFINITIONCODE,
  (SELECT X.DESCRIPTION FROM SIZEDEFINITION_DESC X WHERE X.SIZEDEFINITION_ID = D.SIZEDEFINITION_ID
    AND A.LANGUAGE_ID = X.LANGUAGE_ID) SIZEDEFINITIONDESC,
  I.CODE FINISHINGMETHODCODE,
  (SELECT Y.DESCRIPTION FROM FINISHINGMETHOD_DESC Y WHERE Y.FINISHINGMETHOD_ID= D.FINISHINGMETHOD_ID
    AND A.LANGUAGE_ID = Y.LANGUAGE_ID) FINISHINGMETHODDESC,
  G.CODE PRODUCTCODE,
  (SELECT Z.DESCRIPTION FROM PRODUCT_DESC Z WHERE Z.PRODUCT_ID = D.PRODUCT_ID
    AND A.LANGUAGE_ID = Z.LANGUAGE_ID) PRODUCTDESC,
  E.CUSTOMCODE, E.CUSTOMDESCRIPTION,
  A.CUSTOMER_ID,
  (select sum(dh.amountdelivered) from deliveryhistory dh
    where dh.deliverydate >= RP.DATE_VALUE1-24*7
     and dh.deliverydate <= RP.DATE_VALUE1
     AND dh.CUSTOMER_LINK_ID = RP.NUMBER_VALUE
--     and dh.packindication>=1
--     and dh.packindication<=2
     and E.CUSTOMER_ID = dh.customer_link_id
     and d.sizedefinition_id = dh.sizedefinition_link_id
     and d.finishingmethod_id = dh.finishingmethod_id
     and d.product_id = dh.product_link_id
     and d.distributionpoint_id = dh.distributionpoint_link_id) amount,
  (select count(*) from V_COUNTDELIVERIES cntd
    where cntd.customer_link_id = A.CUSTOMER_ID
     and cntd.deliverydate >= RP.DATE_VALUE1-24*7
     and cntd.deliverydate <= RP.DATE_VALUE1
     and cntd.distributionpoint_link_id = C.DISTRIBUTIONPOINT_ID) deliveries
, d.orderingmethod
  , (select max(psz.sequencenumber) from productsize psz where psz.product_id = g.product_id and psz.sizedefinition_id = h.sizedefinition_id) sequencenumber
  , g.packingsequence, dp.deliverypoint_id
FROM CUSTOMER A left outer join (routestop rs  left join route r on r.route_id = rs.route_id)
     on rs.customer_id=a.customer_id, DEPARTMENT B, DISTRIBUTIONPOINT C, DELIVERYPOINT DP,
  PRODUCTLISTPERDISTRIBPOINT D, PRODUCTLISTPERCUSTOMER E, ADDRESS F, PRODUCT G,
  SIZEDEFINITION H, FINISHINGMETHOD I, STANDARDDELIVERYLINE J, REPORTPARAM RP
WHERE A.CUSTOMER_ID = B.CUSTOMER_ID
  AND B.DEPARTMENT_ID = C.DEPARTMENT_ID
  AND C.DELIVERYPOINT_ID = DP.DELIVERYPOINT_ID
  AND DP.DELIVERYADDRESS_ID = F.ADDRESS_ID
  AND C.DISTRIBUTIONPOINT_ID = D.DISTRIBUTIONPOINT_ID
  AND D.PRODUCT_ID = G.PRODUCT_ID
  AND D.SIZEDEFINITION_ID = H.SIZEDEFINITION_ID
  AND D.FINISHINGMETHOD_ID = I.FINISHINGMETHOD_ID
  AND E.CUSTOMER_ID = A.CUSTOMER_ID
  AND E.PRODUCTLISTPERCUSTOMER_ID = J.PRODUCTLISTPERCUSTOMER_ID
  AND J.PRODUCTLISTPERDISTRIBPOINT_ID = D.PRODUCTLISTPERDISTRIBPOINT_ID
  AND RP.NUMBER_VALUE = A.CUSTOMER_ID
  AND J.DATEINACTIVE > RP.DATE_VALUE1
  and ( RP.NUMBER_VALUE2=0 or RP.NUMBER_VALUE2=r.route_id)
  and (rp.number_value4=0 or rp.number_value4=dp.deliverypoint_id)
union all
SELECT distinct RP.REPORTPARAM_ID, rp.copy_number, A.CUSTOMERNUMBER--, A.LEGALNAME CUSTOMERNAME
, A.NAME CUSTOMERNAME, F.STREET, F.STREET2
, cast(CONCATENATEWITHBLANK(F.STREET, F.STREET2) as varchar2(255)) ADDRESS
, F.ZIPCODE, F.CITY,
  B.DEPARTMENTNUMBER, B.DESCRIPTION DEPARTMENTNAME,  b.active DepActive,
  C.DISTRIBUTIONPOINTNUMBER, C.DESCRIPTION DISTRIBUTIONPOINTNUMBERNAME, c.active DistribActive,
  H.CODE SIZEDEFINITIONCODE,
  (SELECT X.DESCRIPTION FROM SIZEDEFINITION_DESC X WHERE X.SIZEDEFINITION_ID = D.SIZEDEFINITION_ID
    AND A.LANGUAGE_ID = X.LANGUAGE_ID) SIZEDEFINITIONDESC,
  I.CODE FINISHINGMETHODCODE,
  (SELECT Y.DESCRIPTION FROM FINISHINGMETHOD_DESC Y WHERE Y.FINISHINGMETHOD_ID= D.FINISHINGMETHOD_ID
    AND A.LANGUAGE_ID = Y.LANGUAGE_ID) FINISHINGMETHODDESC,
  G.CODE PRODUCTCODE,
  (SELECT Z.DESCRIPTION FROM PRODUCT_DESC Z WHERE Z.PRODUCT_ID = D.PRODUCT_ID
    AND A.LANGUAGE_ID = Z.LANGUAGE_ID) PRODUCTDESC,
  E.CUSTOMCODE, E.CUSTOMDESCRIPTION,
  A.CUSTOMER_ID,
  0 amount ,0 deliveries, d.orderingmethod
  , (select max(psz.sequencenumber) from productsize psz where psz.product_id = g.product_id and psz.sizedefinition_id = h.sizedefinition_id) sequencenumber
  , g.packingsequence, dp.deliverypoint_id
FROM CUSTOMER A left outer join (routestop rs  left join route r on r.route_id = rs.route_id)
     on rs.customer_id=a.customer_id, DEPARTMENT B, DISTRIBUTIONPOINT C, DELIVERYPOINT DP,
  PRODUCTLISTPERDISTRIBPOINT D, PRODUCTLISTPERCUSTOMER E, ADDRESS F, PRODUCT G,
  SIZEDEFINITION H, FINISHINGMETHOD I, STANDARDDELIVERYLINE J, REPORTPARAM RP
WHERE A.CUSTOMER_ID = B.CUSTOMER_ID
  AND B.DEPARTMENT_ID = C.DEPARTMENT_ID
  AND C.DELIVERYPOINT_ID = DP.DELIVERYPOINT_ID
  AND DP.DELIVERYADDRESS_ID = F.ADDRESS_ID
  AND C.DISTRIBUTIONPOINT_ID = D.DISTRIBUTIONPOINT_ID
  AND D.PRODUCT_ID = G.PRODUCT_ID
  AND D.SIZEDEFINITION_ID = H.SIZEDEFINITION_ID
  AND D.FINISHINGMETHOD_ID = I.FINISHINGMETHOD_ID
  AND E.CUSTOMER_ID = A.CUSTOMER_ID
  AND E.PRODUCTLISTPERCUSTOMER_ID = J.PRODUCTLISTPERCUSTOMER_ID
  AND J.PRODUCTLISTPERDISTRIBPOINT_ID = D.PRODUCTLISTPERDISTRIBPOINT_ID
  AND RP.NUMBER_VALUE = A.CUSTOMER_ID
  AND J.DATEINACTIVE > RP.DATE_VALUE1
  and ( RP.NUMBER_VALUE2=0 or RP.NUMBER_VALUE2=r.route_id)
  and (rp.number_value4=0 or rp.number_value4=dp.deliverypoint_id)
/

  CREATE OR REPLACE VIEW "V_SALESMONITORPERCUSTOMER_AUX" ("INVOICEHEADER_ID", "PARENTINVOICEHEADER_ID", "INVOICENUMBER", "YEAR", "WEEK", "FREQUENCY", "ISCONSOLIDATEINV", "PROCESSINGBUSINESSUNIT_ID", "PROCBUCODE", "PROCBUDESC", "PLANT", "PLANTNAME", "INVOICINGBU_ID", "BUSINESSUNIT", "BUSINESSUNITDESC", "INVOICEDATE", "DEPOT", "DEPOTDESC", "ROUTENUMBER", "ROUTEDESC", "STATE", "MARKETSEGMENT", "MARKETSEGMENTDESC", "SICCODE", "MASTERACCOUNTCUST", "MASTERACCOUNTNUMBER", "MASTERACCOUNT", "CHAIN", "CHAINNAME", "CUSTOMERNUMBER", "CUSTOMERNAME", "LANGUAGECODE") AS 
  select /*version 2.0*/
       ih.invoiceheader_id, ih.parentinvoiceheader_id, ih.invoicenumber, ih.invoiceyear year, ih.invoiceweek week, md.frequency,
       (case when ih.invoiceheader_id = ih.parentinvoiceheader_id then 1 else 0 end) isconsolidateinv,
       coalesce(il.processingbusinessunit_id, ih.invoicebusinessunit_id) processingbusinessunit_id,
       procbu.code procbucode, procbu.description procbudesc, p.code plant, p.name plantname, bu.businessunit_id invoicingbu_id,
       bu.code businessunit, bu.description businessunitdesc, ih.invoicedate, dpt.code depot, dpt.description depotdesc, ro.routenumber, ro.description routedesc,
       ads.state state, ms.code marketsegment,
       (select mds.description
          from marketsegment_desc mds
         where ms.marketsegment_id = mds.marketsegment_id
           and mds.language_id = lan.language_id) marketsegmentdesc,
       cu.siccode, cu.masteraccount masteraccountcust, cum.customernumber masteraccountnumber, cum.masteraccount masteraccount,
       ch.code chain, ch.name chainname, cu.customernumber, cu.name customername, lan.code languagecode
from invoiceline il
     join invoiceheader ih on il.invoiceheader_id = ih.invoiceheader_id
     left join route ro
          left join depot dpt on ro.depot_id = dpt.depot_id
     on ih.route_id = ro.route_id
     join businessunit bu on ih.invoicebusinessunit_id = bu.businessunit_id
     join status st on ih.status_id = st.status_id
     join businessunit procbu on coalesce(il.processingbusinessunit_id, ih.invoicebusinessunit_id) = procbu.businessunit_id
     join plant p on procbu.plant_id = p.plant_id
     join customer cu on ih.deltocustomer_link_id = cu.customer_id
     left join chain ch on cu.chain_id = ch.chain_id
     join customer cum on cu.masteraccount_id = cum.customer_id
     join marketsegment ms on cu.marketsegment_id = ms.marketsegment_id
     join max_deliveryfrequency md on cu.customer_id = md.customer_id
     join address ads on cu.visitaddress_id = ads.address_id
     ,languages lan
where ih.documenttype = 1
  and st.statustype = 'IN'
  and st.code = '2'
/

  CREATE OR REPLACE VIEW "V_STANDARDDELIVERYAMOUNT" ("STANDARDDELIVERYLINE_ID", "AMOUNT_MO", "AMOUNT_TU", "AMOUNT_WE", "AMOUNT_TH", "AMOUNT_FR", "AMOUNT_SA", "AMOUNT_SU") AS 
  SELECT STANDARDDELIVERYline_ID, SUM(AMOUNT_MO) amount_mo, SUM(AMOUNT_TU) AMOUNT_TU , SUM(AMOUNT_WE) AMOUNT_we, SUM(AMOUNT_TH) AMOUNT_Th,SUM(AMOUNT_FR) AMOUNT_fr, SUM(AMOUNT_SA) AMOUNT_sa, SUM(AMOUNT_Su) AMOUNT_sU
FROM V_AMOUNTDAY
GROUP BY STANDARDDELIVERYline_ID
/

  CREATE OR REPLACE VIEW "V_STOCKCOUNTSCHEDULE" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CODE", "DESCRIPTION", "PACKONCOUNTDAY", "COUNT_MO", "COUNT_TU", "COUNT_WE", "COUNT_TH", "COUNT_FR", "COUNT_SA", "COUNT_SU", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  SELECT
 CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, STOCKCOUNTSCHEDULE.CODE, STOCKCOUNTSCHEDULE.DESCRIPTION
,STOCKCOUNTSCHEDULE.PACKONCOUNTDAY,
cast( F_DELIVERYDAY(V_STOCKCOUNTSCHEDULEDAY.COUNT_MO) as varchar2(1)),
cast( F_DELIVERYDAY(V_STOCKCOUNTSCHEDULEDAY.COUNT_TU) as varchar2(1)),
cast( F_DELIVERYDAY(V_STOCKCOUNTSCHEDULEDAY.COUNT_WE) as varchar2(1)),
cast( F_DELIVERYDAY(V_STOCKCOUNTSCHEDULEDAY.COUNT_TH) as varchar2(1)),
cast( F_DELIVERYDAY(V_STOCKCOUNTSCHEDULEDAY.COUNT_FR) as varchar2(1)),
cast( F_DELIVERYDAY(V_STOCKCOUNTSCHEDULEDAY.COUNT_SA) as varchar2(1)),
cast( F_DELIVERYDAY(V_STOCKCOUNTSCHEDULEDAY.COUNT_SU) as varchar2(1))
, STOCKCOUNTSCHEDULE.SYSTEMUSER_ID, STOCKCOUNTSCHEDULE.TIMESTAMP
FROM
  CUSTOMER, STOCKCOUNTSCHEDULE, V_STOCKCOUNTSCHEDULEDAY V_STOCKCOUNTSCHEDULEDAY
WHERE
    STOCKCOUNTSCHEDULE.CUSTOMER_ID =  CUSTOMER.CUSTOMER_ID
AND STOCKCOUNTSCHEDULE.STOCKCOUNTSCHEDULE_ID = V_STOCKCOUNTSCHEDULEDAY.STOCKCOUNTSCHEDULE_ID
/

  CREATE OR REPLACE VIEW "V_STOCKCOUNTSCHEDULEDAY" ("STOCKCOUNTSCHEDULE_ID", "COUNT_MO", "COUNT_TU", "COUNT_WE", "COUNT_TH", "COUNT_FR", "COUNT_SA", "COUNT_SU") AS 
  SELECT STOCKCOUNTSCHEDULE_ID, SUM(COUNT_MO), SUM(COUNT_TU), SUM(COUNT_WE), SUM(COUNT_TH),SUM(COUNT_FR), SUM(COUNT_SA), SUM(COUNT_SU)
FROM V_STOCKCOUNTDAY
GROUP BY STOCKCOUNTSCHEDULE_ID
/

  CREATE OR REPLACE VIEW "V_VIRTUALROUTES" ("LINETYPE", "ROUTESTOP_ID", "DRIVINGYEAR", "DRIVINGWEEK", "NOTENUMBER", "CUSTOMER_ID", "SHOWSTOP", "ROUTECONTROL_ID", "STOP_DELIVERYPOINT_ID", "PN_DELIVERYPOINT_ID", "PLANTCODE", "ROUTENUMBER", "ROUTEDESCRIPTION", "DRIVINGDATE", "DEPOTCODE", "DEPOTDESCRIPTION", "LOADINGDOCK", "STARTTIME", "DRIVERNAME", "TRUCKCODE", "TRUCKDESCRIPTION", "VATNUMBER", "STOPNUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTNR", "DELIVERYADDRESS1", "DELIVERYADDRESS2", "CITY", "STATE", "ZIPCODE", "HOUSENUMBER", "HOUSENUMBEREXT", "C_DELIVERYADDRESS1", "C_DELIVERYADDRESS2", "C_CITY", "C_STATE", "C_ZIPCODE", "C_HOUSENUMBER", "C_HOUSENUMBEREXT", "ROUTELISTINSTRUCTIONS", "CONTACTPERSONNAME", "CONTACTPERSONPHONE", "MOBILEPHONE", "CUSTOMERPHONE", "STOP_ID", "DEPARTMENTNUMBER", "DISTRIBUTIONPOINTNUMBER", "DELIVERYPOINTCODE", "DEPARTMENTDESC", "DISTRIBUTIONPOINTDESC", "DELIVERYPOINTDESC", "PRODUCTCODE", "SIZECODE", "FINISHINGMETHODCODE", "DELIVERYSCHEMECODE", "PRODUCTDESCRIPTION", "DELIVERYSCHEMESTARTDATE", "QTYDELIVERED", "QTYEXPECTED", "ENDCONTRACT", "LANGUAGECODE", "DETAIL", "MOVEDROUTENUMBER", "MOVEDROUTEDESCRIPTION", "STATUS", "CUSTOMERCOUNTRYID", "COUNTRY", "PLANTCOUNTRYID", "TYPEOFMERCHADISE", "ROUTE_ID", "STOPTYPE", "REPORTPARAM_ID", "SHOWLOCKERONROUTELIST", "PUTUPTYPE_PRODUCT", "PUTUPTYPE_PLPC", "STRAIGHTEVENEXCHANGE", "QTYDELIVERED_PNL", "DELNOTEFORBULKPUTUPITEMS", "DEL_POINT_START_TIME", "DEL_POINT_END_TIME", "BREAKSTARTTIME", "BREAKENDTIME", "ROUTE_START_TIME", "STOP_TRAVELMINUTES", "STOP_SERVICEMINUTES", "DATEACTIVE", "DATEINACTIVE", "DEL_POINT_START_TIMECH", "DEL_POINT_END_TIMECH", "BREAKSTARTTIMECH", "BREAKENDTIMECH", "ROUTE_START_TIMECH", "ROUTE_START_TIMECH24", "STARTTIMECH", "SHOWONROUTELIST", "CONTACTNOTES", "CONTACTSTATUS", "PLANT_ID", "PLANTEMAIL", "DRIVINGINSTRUCTIONS", "COUNTCONTAINER", "DISTRIBUTIONPOINT_ID", "NUMBEROFCOLLI", "INTERNALPROCESSINGBU_ID", "DEFAULTBUSINESSUNIT_ID", "PROCESSINGPLANT_ID") AS 
  select /*version 2.0*/ 4 linetype, --packing notes --virtual routes for linetype 1
  st.routestop_id, getyearofweek(rc.drivingdate) drivingyear, getisoweek(rc.drivingdate) drivingweek,
  pn.notenumber, cu.customer_id,
  f_show_routestop_std(st.stop_id, st.routestop_id, st.stoptype, pl.plant_id) showstop,
  rc.routecontrol_id, st.deliverypoint_id stop_deliverypoint_id, delp.deliverypoint_id pn_deliverypoint_id,
  pl.code plantcode, ru.routenumber, ru.description routedescription, rc.drivingdate,
  d.code depotcode,d.description depotdescription, rc.loadingdock, rc.starttime,
  (case when rc.drivernumber = 0 then em.name
        else (select employee.name from employee where employee.employeenumber = rc.drivernumber
             and employee.plant_id = pl.plant_id)
   end) drivername,
   coalesce (rc.truckcode, tr.code) truckcode,
  (case when rc.truckcode is null then tr.description
        else (select truck.description from truck where truck.code = rc.truckcode
             and truck.plant_id = pl.plant_id)
   end) truckdescription, cu.vatnumber,
  st.stopnumber, cu.customernumber, cu.name customername,insertspace_after_x_characters(to_char(cu.customernumber),3) custnr,
  ad.street deliveryaddress1, ad.street2 deliveryaddress2, ad.city, ad.state, ad.zipcode, ad.housenumber, ad.housenumberext,
  '' c_deliveryaddress1, '' c_deliveryaddress2, '' c_city, '' c_state, '' c_zipcode, null c_housenumber, null c_housenumberext,
  st.routelistinstructions,
  cp.name contactpersonname, cp.phone contactpersonphone, cp.mobilephone, cu.phoneno customerphone, st.stop_id,
  dep.departmentnumber, disp.distributionpointnumber, delp.code deliverypointcode,
  dep.description departmentdesc, disp.description distributionpointdesc, delp.description deliverypointdesc,
  pr.code productcode, sd.code sizecode, fm.code finishingmethodcode, ds.code deliveryschemecode,
  (select pd.description from product_desc pd where pr.product_id = pd.product_id and pd.language_id = languages.language_id) productdescription,
  h.startdate deliveryschemestartdate,
  h.deliveredqty qtydelivered, 0 qtyexpected, 'P' endcontract,
  languages.code languagecode, 1 detail, v.routenumber movedroutenumber, v.description movedroutedescription, st.status,
  cu.country_id customercountryid, co.description country, pl.country_id plantcountryid,
  (select sum(cdd.typeofmerchadise) from customerdeliveryday cdd where cu.customer_id = cdd.customer_id
     and coalesce((select rm.drivingday_id from route rm where rs.route_id=rm.route_id), ru.drivingday_id) = cdd.day_id
     and cdd.typeofmerchadise >=1 and cdd.typeofmerchadise <=2) typeofmerchadise,
  ru.route_id, coalesce(st.stoptype, 0) stoptype, rp.reportparam_id,
  coalesce(clm.showlockeronroutelist, 'N') showlockeronroutelist,
  pr.putuptype putuptype_product, pnl.putuptype putuptype_plpc,
  case when h.packingnoteline_id is null then 0 else 1 end straightevenexchange,
  pnl.deliveredamount qtydelivered_pnl, cu.delnoteforbulkputupitems
  , (select hh.starttime from deliverypointopeninghour hh
            where hh.deliverypoint_id = delp.deliverypoint_id and hh.day_id = ru.drivingday_id) del_point_start_time
  , (select hh.endtime from deliverypointopeninghour hh
            where hh.deliverypoint_id = delp.deliverypoint_id and hh.day_id = ru.drivingday_id) del_point_end_time
  , delp.breakstarttime breakstarttime, delp.breakendtime breakendtime
  , ru.starttime route_start_time, rs.travelminutes stop_travelminutes, rs.serviceminutes stop_serviceminutes
  , cu.dateactive, cu.dateinactive
  , (select to_char(hh.starttime,'fmhhfm:MI:AM') from deliverypointopeninghour hh
            where hh.deliverypoint_id = delp.deliverypoint_id and hh.day_id = ru.drivingday_id) del_point_start_timech
  , (select to_char(hh.endtime,'fmhhfm:MI:AM') from deliverypointopeninghour hh
            where hh.deliverypoint_id = delp.deliverypoint_id and hh.day_id = ru.drivingday_id) del_point_end_timech
  , to_char(delp.breakstarttime,'fmHH:MI:AM') breakstarttimech, to_char(delp.breakendtime,'fmHH:MI:AM') breakendtimech
  , to_char(ru.starttime,'fmhhfm:MI:AM') route_start_timech
  , to_char(ru.starttime,'fmhh24fm:MI') route_start_timech24
  , to_char(rc.starttime,'fmhhfm:MI:AM') starttimech
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, rc.plant_id
 , cast(getsubstringonlength(pl.email,0,40) as varchar2(40)) plantemail
 , (select cri.routedescription from customerrouteinfo cri where cri.customer_id = cu.customer_id) drivinginstructions
 , (select sum(v2.countContainer) from V_ROUTECONTAINERS v2 where v2.STOP_ID = st.stop_id and v2.route_id = ru.route_id) CountContainer
 , disp.distributionpoint_id, pn.numberofcolli
 , pn.internalprocessingbu_id, cu.defaultbusinessunit_id
 , (select pbu.plant_id from businessunit pbu where pbu.businessunit_id = pn.processbusinessunit_id) processingplant_id
from reportparam rp
     inner join routecontrolextrainfo rcx
           inner join routecontrol rc on rc.routecontrol_id = rcx.routecontrol_id
           inner join route ru
                 left outer join depot d on ru.depot_id =d.depot_id
                 left outer join employee em on ru.driver_id = em.employee_id
                 left outer join truck tr on ru.truck_id = tr.truck_id
           on rc.route_id = ru.route_id
           inner join stop st
                 left outer join v_movedoutstops v on st.stop_id = v.movedtostop_id
                 left outer join contactperson cp on st.contactperson_id = cp.contactperson_id
                 left outer join routestop rs on st.routestop_id = rs.routestop_id
                 inner join packingnote pn
                       inner join packingnoteline pnl
                             left outer join v_packingnotelineperdelsch_ext h
                                  left outer join deliveryscheme ds on h.deliveryscheme_id = ds.deliveryscheme_id
                             on pnl.packingnoteline_id = h.packingnoteline_id
                             inner join product pr on pnl.product_id = pr.product_id
                             inner join sizedefinition sd on pnl.sizedefinition_id = sd.sizedefinition_id
                             inner join finishingmethod fm on pnl.finishingmethod_id = fm.finishingmethod_id
                       on pn.packingnote_id = pnl.packingnote_id
                       inner join distributionpoint disp
                             inner join department dep on disp.department_id = dep.department_id
                       on pn.distributionpoint_id = disp.distributionpoint_id
                       inner join deliverypoint delp
                             inner join address ad on delp.deliveryaddress_id = ad.address_id
                       on pn.deliverypoint_id = delp.deliverypoint_id
                       inner join status stat on pn.status_id = stat.status_id
                 on st.stop_id = pn.stop_id
                 inner join customer cu
                       left outer join customerlockermanagement clm on cu.customer_id = clm.customer_id
                       left outer join contact cont on cont.contact_id = coalesce(f_getcontactonroutelist(cu.customer_id), -1)
                       inner join country co on cu.country_id = co.country_id
                 on st.customer_link_id = cu.customer_id
           on rc.routecontrol_id = st.routecontrol_id
           inner join plant pl on rc.plant_id = pl.plant_id
     on rp.number_value = rcx.mainroutecontrol_id
     , languages
where stat.statustype = 'PN' and stat.code <> '40' and st.status in (0, 3, 4)
      and (nvl(rp.number_value5, -1) = -1 or (rp.number_value5 <> -1 and exists (select 1 from customeractivities ca
                                    where ca.customer_id = cu.customer_id and ca.internalprocessingbu_id = rp.number_value5)))
      and (nvl(rp.number_value6, -1) = -1 or (rp.number_value6 <> -1 and exists (select 1 from customeractivities ca, businessunit bu
                                    where ca.customer_id = cu.customer_id and ca.processbusinessunit_id = bu.businessunit_id
                                          and bu.plant_id = rp.number_value6)))
union all          -- 5 --
select 5 linetype, -- straight even return -- virtual routes for linetype 2
  st.routestop_id, getyearofweek(rc.drivingdate) drivingyear, getisoweek(rc.drivingdate) drivingweek,
  0 notenumber, cu.customer_id,
  f_show_routestop_std(st.stop_id, st.routestop_id, st.stoptype, pl.plant_id) showstop,
  rc.routecontrol_id, st.deliverypoint_id stopdeliverypoint_id, delp.deliverypoint_id pn_deliverypoint_id,
  pl.code plantcode, ru.routenumber, ru.description routedescription, rc.drivingdate,
  d.code depotcode,d.description depotdescription, rc.loadingdock, rc.starttime,
  (case when rc.drivernumber = 0 then em.name
        else (select employee.name from employee where employee.employeenumber = rc.drivernumber
             and employee.plant_id = pl.plant_id)
   end) drivername,
  coalesce (rc.truckcode, tr.code) truckcode,
  (case when rc.truckcode is null then tr.description
        else (select truck.description from truck where truck.code = rc.truckcode
             and truck.plant_id = pl.plant_id)
   end) truckdescription, cu.vatnumber,
  st.stopnumber, cu.customernumber, cu.name customername,insertspace_after_x_characters(to_char(cu.customernumber),3) custnr,
  ad.street deliveryaddress1, ad.street2 deliveryaddress2, ad.city, ad.state, ad.zipcode, ad.housenumber, ad.housenumberext,
  '' c_deliveryaddress1, '' c_deliveryaddress2, '' c_city, '' c_state, '' c_zipcode, null c_housenumber, null c_housenumberext,
  st.routelistinstructions,
  cp.name contactpersonname, cp.phone contactpersonphone, cp.mobilephone,cu.phoneno customerphone,  st.stop_id,
  dep.departmentnumber, disp.distributionpointnumber, delp.code deliverypointcode,
  dep.description departmentdesc, disp.description distributionpointdesc, delp.description deliverypointdesc,
  pr.code productcode, sd.code sizecode, fm.code finishingmethodcode, ds.code deliveryschemecode,
  (select description from product_desc pd where pr.product_id = pd.product_id and pd.language_id = languages.language_id) productdescription,
  null deliveryschemestartdate,
  0 qtydelivered, ser.qtyexpected qtyexpected, ser.endcontract,
  languages.code languagecode, 1 detail, v.routenumber movedroutenumber, v.description movedroutedescription, st.status,
  cu.country_id customercountryid, co.description country, pl.country_id plantcountryid,
  (select sum(cdd.typeofmerchadise) from customerdeliveryday cdd where cu.customer_id = cdd.customer_id
     and coalesce((select rm.drivingday_id from route rm where rs.route_id=rm.route_id), ru.drivingday_id) = cdd.day_id
     and cdd.typeofmerchadise >=1 and cdd.typeofmerchadise <=2) typeofmerchadise,
  ru.route_id, coalesce(st.stoptype, 0) stoptype, rp.reportparam_id,
  coalesce(clm.showlockeronroutelist, 'N') showlockeronroutelist,
  pr.putuptype putuptype_product, 0 putuptype_plpc, 1 straightevenexchange,
  0 qtydelivered_pnl, cu.delnoteforbulkputupitems
  , (select hh.starttime from deliverypointopeninghour hh
            where hh.deliverypoint_id = delp.deliverypoint_id and hh.day_id = ru.drivingday_id) del_point_start_time
  , (select hh.endtime  from deliverypointopeninghour hh
            where hh.deliverypoint_id = delp.deliverypoint_id and hh.day_id = ru.drivingday_id) del_point_end_time
  ,  delp.breakstarttime breakstarttime, delp.breakendtime breakendtime
  , ru.starttime route_start_time, rs.travelminutes stop_travelminutes, rs.serviceminutes stop_serviceminutes
  , cu.dateactive, cu.dateinactive
  , (select to_char(hh.starttime,'fmHHfm:MI:AM') from deliverypointopeninghour hh
            where hh.deliverypoint_id = delp.deliverypoint_id and hh.day_id = ru.drivingday_id) del_point_start_timech
  , (select to_char(hh.endtime,'fmHHfm:MI:AM') from deliverypointopeninghour hh
            where hh.deliverypoint_id = delp.deliverypoint_id and hh.day_id = ru.drivingday_id) del_point_end_timech
  , to_char(delp.breakstarttime,'fmHHfm:MI:AM') breakstarttimech, to_char(delp.breakendtime,'fmHH:MI:AM') breakendtimech
  , to_char(ru.starttime,'fmHHfm:MI:AM') route_start_timech
  , to_char(ru.starttime,'fmHH24fm:MI') route_start_timech24
  , to_char(rc.starttime,'fmHHfm:MI:AM') starttimech
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, rc.plant_id
  , cast(getsubstringonlength(pl.email,0,40) as varchar2(40)) plantemail
  , (select cri.routedescription from customerrouteinfo cri where cri.customer_id = cu.customer_id) drivinginstructions
  , (select sum(v2.countContainer) from V_ROUTECONTAINERS v2 where v2.STOP_ID = st.stop_id and v2.route_id = ru.route_id) CountContainer
  , disp.distributionpoint_id, null numberofcolli
  , -1 internalprocessingbu_id, cu.defaultbusinessunit_id
  , (select pbu.plant_id from businessunit pbu where pbu.businessunit_id = ser.processbusinessunit_id) processingplant_id
from reportparam rp
     inner join routecontrolextrainfo rcx
           inner join routecontrol rc on rc.routecontrol_id = rcx.routecontrol_id
           inner join route ru
                 left outer join depot d on ru.depot_id =d.depot_id
                 left outer join employee em on ru.driver_id = em.employee_id
                 left outer join truck tr on ru.truck_id = tr.truck_id
           on rc.route_id = ru.route_id
           inner join stop st
                 left outer join v_movedoutstops v on st.stop_id = v.movedtostop_id
                 left outer join contactperson cp on st.contactperson_id = cp.contactperson_id
                 left outer join routestop rs on st.routestop_id = rs.routestop_id
                 inner join straightevenreturn ser
                       inner join product pr on ser.product_id = pr.product_id
                       inner join sizedefinition sd on ser.sizedefinition_id = sd.sizedefinition_id
                       inner join finishingmethod fm on ser.finishingmethod_id = fm.finishingmethod_id
                       inner join deliveryscheme ds on ser.deliveryscheme_id = ds.deliveryscheme_id
                       inner join distributionpoint disp
                             inner join deliverypoint delp
                                   inner join address ad on delp.deliveryaddress_id = ad.address_id
                             on disp.deliverypoint_id = delp.deliverypoint_id
                             inner join department dep on  disp.department_id = dep.department_id
                       on ser.distributionpoint_id = disp.distributionpoint_id
                       inner join status stat on ser.status_id = stat.status_id
                 on st.stop_id = ser.stop_id
                 inner join customer cu
                       left outer join customerlockermanagement clm on cu.customer_id = clm.customer_id
                       left outer join contact cont on cont.contact_id = coalesce(f_getcontactonroutelist(cu.customer_id), -1)
                       inner join country co on cu.country_id = co.country_id
                 on st.customer_link_id = cu.customer_id
           on rc.routecontrol_id = st.routecontrol_id
           inner join plant pl on rc.plant_id = pl.plant_id
     on rp.number_value = rcx.mainroutecontrol_id
     , languages
where stat.statustype = 'SR' and stat.code <> '30' and st.status in (0, 3, 4)
      and (nvl(rp.number_value5, -1) = -1 or (rp.number_value5 <> -1 and exists (select 1 from customeractivities ca
                                    where ca.customer_id = cu.customer_id and ca.internalprocessingbu_id = rp.number_value5)))
      and (nvl(rp.number_value6, -1) = -1 or (rp.number_value6 <> -1 and exists (select 1 from customeractivities ca, businessunit bu
                                    where ca.customer_id = cu.customer_id and ca.processbusinessunit_id = bu.businessunit_id
                                          and bu.plant_id = rp.number_value6)))
union all  -- 6 --
select 6 linetype, -- no packing notes - used only for header in rpt -- virtual routes for linetype 3
  st.routestop_id, getyearofweek(rc.drivingdate) drivingyear, getisoweek(rc.drivingdate) drivingweek,
  0 notenumber, cu.customer_id,
  f_show_routestop_std(st.stop_id, st.routestop_id, st.stoptype, pl.plant_id) showstop,
  rc.routecontrol_id, st.deliverypoint_id stopdeliverypoint_id, 0 pn_deliverypoint_id,
  pl.code plantcode, ru.routenumber, ru.description routedescription, rc.drivingdate,
 d.code depotcode,d.description depotdescription, rc.loadingdock, rc.starttime,
  (case when rc.drivernumber = 0 then em.name
        else (select employee.name from employee where employee.employeenumber = rc.drivernumber
             and employee.plant_id = pl.plant_id)
   end) drivername,
  coalesce (rc.truckcode, tr.code) truckcode,
  (case when rc.truckcode is null then tr.description
        else (select truck.description from truck where truck.code = rc.truckcode
             and truck.plant_id = pl.plant_id)
   end) truckdescription, cu.vatnumber,
  st.stopnumber, cu.customernumber, cu.name customername,insertspace_after_x_characters(to_char(cu.customernumber),3) custnr,
  ad.street deliveryaddress1, ad.street2 deliveryaddress2, ad.city, ad.state, ad.zipcode, ad.housenumber, ad.housenumberext,
  add2.street c_deliveryaddress1, add2.street2 c_deliveryaddress2, add2.city c_city, add2.state c_state, add2.zipcode c_zipcode,
  add2.housenumber c_housenumber, add2.housenumberext c_housenumberext, st.routelistinstructions,
  cp.name contactpersonname, cp.phone contactpersonphone,cp.mobilephone, cu.phoneno customerphone, st.stop_id,
  -1 departmentnumber, -1 distributionpointnumber, dp.code deliverypointcode,
  '' departmentdesc, '' distributionpointdesc, dp.description deliverypointdesc,
  '' productcode,'' sizecode,'' finishingmethodcode,'' deliveryschemecode,'' productdescription,null deliveryschemestartdate,0 qtydelivered,0 qtyexpected,'A' endcontract,
  languages.code languagecode, 0 detail, v.routenumber movedroutenumber, v.description movedroutedescription, st.status,
  cu.country_id customercountryid, co.description country, pl.country_id plantcountryid,
  (select sum(cdd.typeofmerchadise) from customerdeliveryday cdd where cu.customer_id = cdd.customer_id
     and coalesce((select rm.drivingday_id from route rm where rs.route_id=rm.route_id), ru.drivingday_id) = cdd.day_id
     and cdd.typeofmerchadise >= 1 and cdd.typeofmerchadise <= 2) typeofmerchadise,
  ru.route_id, coalesce(st.stoptype, 0) stoptype, rp.reportparam_id,
  coalesce(clm.showlockeronroutelist, 'N') showlockeronroutelist,
  0 putuptype_product, 0 putuptype_plpc, 0 straightevenexchange,
  0 qtydelivered_pnl, cu.delnoteforbulkputupitems
  , (select hh.starttime from deliverypointopeninghour hh
            where hh.deliverypoint_id = dp.deliverypoint_id and hh.day_id = ru.drivingday_id) del_point_start_time
  , (select hh.endtime  from deliverypointopeninghour hh
            where hh.deliverypoint_id = dp.deliverypoint_id and hh.day_id = ru.drivingday_id) del_point_end_time
             ,dp.breakstarttime breakstarttime, dp.breakendtime breakendtime
  , ru.starttime route_start_time, rs.travelminutes routestop_travelminutes, rs.serviceminutes routestop_serviceminutes
  , cu.dateactive, cu.dateinactive
  , (select to_char(hh.starttime,'fmHHfm:MI:AM') from deliverypointopeninghour hh
            where hh.deliverypoint_id = dp.deliverypoint_id and hh.day_id = ru.drivingday_id) del_point_start_timech
  , (select to_char(hh.endtime,'fmHHfm:MI:AM') from deliverypointopeninghour hh
            where hh.deliverypoint_id = dp.deliverypoint_id and hh.day_id = ru.drivingday_id) del_point_end_timech
  , to_char(dp.breakstarttime,'fmHHfm:MI:AM') breakstarttimech, to_char(dp.breakendtime,'fmHH:MI:AM') breakendtimech
  , to_char(ru.starttime,'fmHHfm:MI:AM') route_start_timech
  , to_char(ru.starttime,'fmHH24fm:MI') route_start_timech24
  , to_char(rc.starttime,'fmHHfm:MI:AM') starttimech
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, rc.plant_id
  , cast(getsubstringonlength(pl.email,0,40) as varchar2(40)) plantemail
  , (select cri.routedescription from customerrouteinfo cri where cri.customer_id = cu.customer_id) drivinginstructions
  , (select sum(v2.countContainer) from V_ROUTECONTAINERS v2 where v2.STOP_ID = st.stop_id and v2.route_id = ru.route_id) CountContainer
  , null distributionpoint_id, null numberofcolli
  , -1 internalprocessingbu_id, cu.defaultbusinessunit_id, -1 processingplant_id
from reportparam rp
     inner join routecontrolextrainfo rcx
     inner join routecontrol rc on rc.routecontrol_id = rcx.routecontrol_id
     left outer join routecontrolextrainfo rcx2 on rcx2.mainroutecontrol_id = rc.routecontrol_id
           inner join route ru
                 left outer join depot d on ru.depot_id =d.depot_id
                 left outer join employee em on ru.driver_id = em.employee_id
                 left outer join truck tr on ru.truck_id = tr.truck_id
           on rc.route_id = ru.route_id
           inner join stop st
                 left outer join v_movedoutstops v on st.stop_id = v.movedtostop_id
                 left outer join contactperson cp on st.contactperson_id = cp.contactperson_id
                 left outer join routestop rs on st.routestop_id = rs.routestop_id
                 left outer join deliverypoint dp
                      inner join address ad on dp.deliveryaddress_id = ad.address_id
                 on st.deliverypoint_id = dp.deliverypoint_id
                 inner join customer cu
                       left outer join customerlockermanagement clm on cu.customer_id = clm.customer_id
                       left outer join contact cont on cont.contact_id = coalesce(f_getcontactonroutelist(cu.customer_id), -1)
                       inner join country co on cu.country_id = co.country_id
                       inner join address add2 on cu.visitaddress_id = add2.address_id
                 on st.customer_link_id = cu.customer_id
           on rc.routecontrol_id = st.routecontrol_id
           inner join plant pl on rc.plant_id = pl.plant_id
     on rp.number_value = rcx.mainroutecontrol_id
     , languages
where st.status in (0, 3, 4)
      and (nvl(rp.number_value5, -1) = -1 or (rp.number_value5 <> -1 and exists (select 1 from customeractivities ca
                                    where ca.customer_id = cu.customer_id and ca.internalprocessingbu_id = rp.number_value5)))
      and (nvl(rp.number_value6, -1) = -1 or (rp.number_value6 <> -1 and exists (select 1 from customeractivities ca, businessunit bu
                                    where ca.customer_id = cu.customer_id and ca.processbusinessunit_id = bu.businessunit_id
                                          and bu.plant_id = rp.number_value6)))
/

  CREATE OR REPLACE VIEW "V_XML_PEPPOL_BILLING_CREDIT" ("INVOICEHEADER_ID", "INVOICEDATE", "INVOICENUMBER", "PAYTHISAMOUNT", "BILLTOCUSTOMER_LINK_ID", "TMC_XML") AS 
  select /*view v_xml_peppol_billing_credit version 10.10
     ABS-133143 Pagero PEPPOL format - changes needed to standard format- rounding issue and negative lines issue
     ABS-136080 Peppol - CompanyID not correct in XML files
     ABS-136299 Filling tabel invoiceheaderxml and creating XML files a comma is put where a point should be
     ABS-142977 Peppol: PRICEAMOUNT price per unit
     ABS-152442 PEPPOL XML customized
     ABS-153477 Add Global Location Number (GLN) and extend country code - PEPPOL procedure
     ABS-155461 PEPPOL - company name and address option to also use legal entity
     ABS-159140 VAT number from laundry where VAT number from customer should be placed
     ABS-159618 M2 wrong fromat in XML
     ABS-159918 XML for PEPPOL Pagero tag BaseQuantity
     ABS-160092 GLN number where VAT number should be
     ABS-160788 Invoice XML Peppol unit EA
     ABS-163171 Add Belgium Enterprise number
     ABS-160461 CreditedQuantity negative in XML ABS-160465
     ABS-165659 requisitionnumber from costcenter in XML for Peppol
     ABS-163251 Include new Out Going Message (OGM) in PEPPOL export
     ABS-168116 Peppol XML COCNumber as part of AccountingCustomerParty
     ABS-168722 Peppol - XML files wrong totals per taxgroup
     ABSN-3698 PEPPOL: Replacement dots and spaces for accountsupplierparty VAT code
     ABSN-6958 ABS Peppol XML credit invoice negative price
     ABSN-8431 Peppol financial interface modification - database
     */
  ---Credit note
  ih.invoiceheader_id,ih.invoicedate,ih.invoicenumber,ih.paythisamount,ih.billtocustomer_link_id,
  xmlserialize(content
   xmltype('<?xml version="1.0" encoding="UTF-8" standalone="no"?>' ||
       (xmlelement("CreditNote",
        xmlattributes('urn:pagero:CommonAggregateComponents:1.0' as "xmlns:cac",
                      'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2' as "xmlns:cbc",
                      'urn:pagero:ExtensionComponent:1.0' as "xmlns:puf",
                      'urn:un:unece:uncefact:documentation:2' as "xmlns:ccts",
                      'urn:oasis:names:specification:ubl:schema:xsd:QualifiedDatatypes-2' as "xmlns:qdt",
                      'urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2' as "xmlns:udt",
                      'urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2' as "xmlns:ext",
                      'urn:pagero:PageroUniversalFormat:CreditNote:1.0' as "xmlns"),
        xmlelement("cbc:CustomizationID", 'urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0#conformant#urn:pagero.com:puf:billing:1.0'),
        xmlelement("cbc:ProfileID", 'urn:pagero.com:puf:billing:1.0'),
        xmlelement("cbc:ID", ih.invoicenumber),
        xmlelement("cbc:IssueDate", to_char(ih.invoicedate,'YYYY-MM-DD')),
        xmlelement("cbc:CreditNoteTypeCode",'381'),
        xmlelement("cbc:Note", replace(replace(trim(ih.invoicecomments), chr(13), ''), chr(10), ' ')),
        xmlelement("cbc:DocumentCurrencyCode", cu.code),
        xmlelement("cbc:BuyerReference", coalesce(cpcc.name, cpedi.name, ih.contactpersonname)),
        xmlelement("cac:InvoicePeriod",
          xmlelement("cbc:StartDate", nvl(ih.startdate, ih.nextperiodstartdate)),
          xmlelement("cbc:EndDate", nvl(ih.enddate, ih.nextperiodenddate))),
        xmlelement("cac:OrderReference",
           xmlelement("cbc:ID", coalesce(cc.requisitionnumber, case when ih.splitupcode = '0' then null else ih.splitupcode end,
                                (select ce.requisitionnumber
                                 from customerediinfo ce
                                 where ce.customer_id = ih.billtocustomer_link_id),'-')),
             xmlelement("cbc:SalesOrderID", ih.invoicenumber)),
        xmlelement("cac:AdditionalDocumentReference",
          xmlelement("cbc:ID", ih.invoiceheader_id),
          xmlelement("cac:Attachment",
           xmlelement("cac:ExternalReference",
             xmlelement("cbc:URI",'Invoice_'||to_char(ih.invoicenumber) || '.pdf')))),
        xmlelement("cac:AccountingSupplierParty",
          xmlelement("cac:Party",
          xmlelement("cbc:EndpointID",xmlattributes(ppl.schemeid  as "schemeID"), ppl.endpointid),
          xmlelement("cac:PartyIdentification",
          xmlelement("cbc:ID",xmlattributes(ppl.schemeid  as "schemeID"), ppl.endpointid)),
          xmlelement("cac:PartyName",
          xmlelement("cbc:Name", nvl(le.name,pt.name))),
          xmlelement("cac:PostalAddress",
           xmlelement("cbc:StreetName", nvl(ad.street,trim(replace(adp.street, gethousenumber(adp.street, 1))))),
           xmlelement("cbc:CityName", nvl(ad.city,adp.city)),
           xmlelement("cbc:PostalZone", nvl(ad.zipcode,adp.zipcode)),
           xmlelement("cac:Country",
           xmlelement("cbc:IdentificationCode", plantcountry.code))),
          xmlelement("cac:PartyTaxScheme",
           xmlelement("cbc:CompanyID",xmlattributes(get_peppol_schemeid(ppl.countrycode, 'VAT') as "schemeID"), ppl.vatcode),
           xmlelement("cac:TaxScheme", xmlelement("cbc:ID", 'VAT'))),
          xmlelement("cac:PartyLegalEntity",
          xmlelement("cbc:RegistrationName", (select max(pc.name) from plantcompany pc where pc.plant_id = bu.plant_id and pc.active ='Y')),
          xmlelement("cbc:CompanyID",xmlattributes(ppl.schemeid  as "schemeID"), ppl.endpointid)),
          xmlelement("cac:Contact",
          xmlelement("cbc:ID", le.legalentity_id),
          xmlelement("cbc:Name", le.legalname),
          xmlelement("cbc:Telephone", le.phone),
          xmlelement("cbc:Telefax", pt.faxno),
          xmlelement("cbc:ElectronicMail", le.email)))),
      xmlelement("cac:AccountingCustomerParty", xmlelement("cbc:SupplierAssignedAccountID", ih.billtocustomernumber),
          xmlelement("cac:Party",
           xmlelement("cbc:EndpointID",
               xmlattributes(pp.schemeid as "schemeID"),pp.endpointid),
          xmlelement("cac:PartyIdentification",
            xmlelement("cbc:ID",
               xmlattributes(pp.schemeid as "schemeID"),pp.endpointid)),
          xmlelement("cac:PartyName",
            xmlelement("cbc:Name", ih.billtocustomername)),
          xmlelement("cac:PostalAddress",
            xmlelement("cbc:StreetName", ih.street),
            xmlelement("cbc:CityName", ih.city),
            xmlelement("cbc:PostalZone", ih.zipcode),
          xmlelement("cac:Country",
            xmlelement("cbc:IdentificationCode", xmlattributes('ISO3166-1:Alpha2' as "listID"), billtocountry.code))),
          xmlelement("cac:PartyTaxScheme",
            xmlelement("cbc:CompanyID", pp.vatcode),
            xmlelement("cac:TaxScheme", xmlelement("cbc:ID", 'VAT'))),
          xmlelement("cac:PartyLegalEntity", xmlelement("cbc:RegistrationName", ih.billtocustomername),
            xmlelement("cbc:CompanyID",
               xmlattributes(pp.schemeid as "schemeID"),pp.endpointid)),
          xmlelement("cac:Contact",
            xmlelement("cbc:ID",   coalesce(cpcc.name, cpedi.name, ih.contactpersonname)),
            xmlelement("cbc:Name", coalesce(cpcc.name, cpedi.name, ih.contactpersonname)),
            xmlelement("cbc:Telephone", coalesce(cpcc.phone, cpedi.phone, ih.contactpersonphone)),
            xmlelement("cbc:ElectronicMail", coalesce(cpcc.email, cpedi.email, ih.emailaddress))))),
          xmlelement("cac:Delivery",
                          xmlelement("cbc:ActualDeliveryDate", ih.invoicedate),
                            xmlelement("cac:DeliveryLocation",
                              xmlelement("cbc:ID",ih.deltocustomernumber),
                              xmlelement("cac:Address",
                              xmlelement("cbc:StreetName", ih.deltostreet),
                              xmlelement("cbc:CityName", ih.deltocity),
                              xmlelement("cbc:PostalZone", ih.deltozipcode),
                              xmlelement("cac:Country",
                                 xmlelement("cbc:IdentificationCode",deltocountry.code)))),
                          xmlelement("cac:DeliveryParty", xmlelement("cac:PartyName", xmlelement("cbc:Name", ih.billtocustomername)))),
            case when binst.laundrybankaccount is not null then
                              xmlelement("cac:PaymentMeans",
                                      xmlelement("cbc:ID",'1'),
                                      xmlelement("cbc:PaymentMeansCode", xmlattributes('UNCL4461' as "listID"),
                                                  case
                                                     when ih.realcollectiontype = 1 then
                                                      '10'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 0 then
                                                      '10'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 1 then
                                                      '20'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 2 then
                                                      '48'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 3 then
                                                      '42'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 4 then
                                                      '30'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 5 then
                                                      '30'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 6 then
                                                      '42'
                                                     else
                                                      '1'
                                                   end),
                                      xmlelement("cbc:PaymentDueDate", ihe.paymenttermsduedate),
                                      xmlelement("cbc:InstructionID", substr(ihe.acceptgirocodeline, 5, 15)),
                                      xmlelement("cbc:PaymentID", nvl(ihe.ogm, ih.invoicenumber)),
                                      xmlelement("cac:PayeeFinancialAccount",
                                             xmlelement("cbc:ID", xmlattributes('BBAN' as "schemeID"), binst.laundrybankaccount)),
                                      case when ih.realcollectiontype = 2 and ihe.paymenttype = 6 then
                                        null
                                       else
                                        xmlelement("cac:CreditAccount", xmlelement("cbc:AccountID",  substr(ihe.acceptgirocodeline,22,8)))
                                       end)
                             else null
                           end,
                           case
                            when binst.ibanno is not null then
                              xmlelement("cac:PaymentMeans",
                                      xmlelement("cbc:ID",'1'),
                                      xmlelement("cbc:PaymentMeansCode", xmlattributes('UNCL4461' as "listID"),
                                                  case
                                                     when ih.realcollectiontype = 1 then
                                                      '10'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 0 then
                                                      '10'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 1 then
                                                      '20'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 2 then
                                                      '48'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 3 then
                                                      '42'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 4 then
                                                      '30'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 5 then
                                                      '30'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 6 then
                                                      '42'
                                                     else
                                                      '1'
                                                   end),
                                      xmlelement("cbc:PaymentDueDate", ihe.paymenttermsduedate),
                                      xmlelement("cbc:InstructionID", substr(ihe.acceptgirocodeline, 5, 15)),
                                      xmlelement("cbc:PaymentID", ih.invoicenumber),
                                         xmlelement("cac:PayeeFinancialAccount",
                                             xmlelement("cbc:ID", xmlattributes('IBAN' as "schemeID"), binst.ibanno),
                                             xmlelement("cac:FinancialInstitutionBranch",
                                                xmlelement("cac:FinancialInstitution",
                                                  xmlelement("cbc:ID", xmlattributes('BIC' as "schemeID"), binst.internalidcode)))),
                                      case when ih.realcollectiontype = 2 and ihe.paymenttype = 6 then
                                        null
                                       else
                                        xmlelement("cac:CreditAccount", xmlelement("cbc:AccountID",  substr(ihe.acceptgirocodeline,22,8)))
                                       end)
                             else null
                           end,
      xmlelement("cac:TaxTotal",
          xmlelement("cbc:TaxAmount",
           xmlattributes(cu.code as "currencyID"),
             f_num2char(((select sum(il.amount) from   invoiceline il
                          join taxgroup tx on tx.code = il.code and tx.country_id = delto.country_id
                          where  il.invoiceheader_id = ih.invoiceheader_id
                          and il.invoicelinetype_id = 18)*-1),cu.invoiceamountdecimals)), --------------------------------
     (select xmlagg( xmlelement("cac:TaxSubtotal",
         xmlelement("cbc:TaxableAmount", xmlattributes(cu.code as "currencyID"),
             f_num2char(iv.overamount*-1,cu.invoiceamountdecimals)),
         xmlelement("cbc:TaxAmount", xmlattributes(cu.code as "currencyID"), f_num2char(il.amount*-1,cu.invoiceamountdecimals)),
         xmlelement("cac:TaxCategory",
            xmlelement("cbc:ID",case when (nvl(tx.taxrate,0) = 0 and tx.code = 'AE') then 'AE' when nvl(tx.taxrate,0) = 0 then 'Z' else 'S' end),
            xmlelement("cbc:Percent",tx.taxrate),
            xmlelement("cac:TaxScheme", xmlelement("cbc:ID",'VAT'), xmlelement("cbc:Name",tx.description)))) order by il.linenumber, il.invoiceline_id)
      from   invoiceline il
      join taxgroup tx on tx.code = il.code and tx.country_id = delto.country_id
      join invoicelinevarious iv on iv.invoiceline_id = il.invoiceline_id
      where  il.invoiceheader_id = ih.invoiceheader_id
      and il.invoicelinetype_id = 18)),
       xmlelement("cac:LegalMonetaryTotal",
       xmlelement("cbc:LineExtensionAmount", xmlattributes(cu.code as "currencyID"),
        f_num2char((ih.totalamountexclvat+nvl(ih.peppol_amount_correction,0))*-1,cu.invoiceamountdecimals)),
       xmlelement("cbc:TaxExclusiveAmount", xmlattributes(cu.code as "currencyID"),
        f_num2char((ih.totalamountexclvat+nvl(ih.peppol_amount_correction,0))*-1,cu.invoiceamountdecimals)),
       xmlelement("cbc:TaxInclusiveAmount", xmlattributes(cu.code as "currencyID"),
        f_num2char((ih.paythisamount+nvl(ih.peppol_amount_correction,0))*-1, cu.invoiceamountdecimals)),
       xmlelement("cbc:PayableAmount", xmlattributes(cu.code as "currencyID"),
        f_num2char((ih.paythisamount+nvl(ih.peppol_amount_correction,0))*-1, cu.invoiceamountdecimals))),
       (select xmlagg(
     xmlelement("cac:CreditNoteLine",
     case when ihl.parentinvoiceheader_id is not null then
        xmlelement("cbc:ID", (ihl.invoicenumber*1000) + ic.linenumber)
     else
        xmlelement("cbc:ID", ic.linenumber)
     end,
        xmlelement("cbc:Note", nvl(ic.remark,'-')),
        xmlelement("cbc:CreditedQuantity", xmlattributes(( nvl(ru.peppolcode,
           case when ic.invoicelinetype_id in (3,4) then 'KG'
                else 'EA'end)) as "unitCode", 'UNECERec20' as "unitCodeListID"),
           f_num2char(ic.billedqty, case when round(ic.billedqty) = ic.billedqty then 0 else 2 end)),
        xmlelement("cbc:LineExtensionAmount", xmlattributes(cu.code as "currencyID"),
           f_num2char(ic.amount,cu.invoiceamountdecimals)),
        xmlelement("cac:OrderLineReference", xmlelement("cbc:LineID", ic.linenumber)),
        case when tx.code is not null then
         xmlelement("cac:TaxTotal",
            xmlelement("cbc:TaxAmount",
            xmlattributes(cu.code as "currencyID"),
             f_num2char(ic.amount * tx.taxrate / 100, cu.invoiceamountdecimals)),
            xmlelement("cac:TaxSubtotal",
              xmlelement("cbc:TaxableAmount", xmlattributes(cu.code as "currencyID"), f_num2char(ic.amount, cu.invoiceamountdecimals)),
              xmlelement("cbc:TaxAmount", xmlattributes(cu.code as "currencyID"), f_num2char(ic.amount * tx.taxrate / 100, cu.invoiceamountdecimals)),
              xmlelement("cac:TaxCategory",
                    xmlelement("cbc:ID",'UNCL5305'),
                    xmlelement("cbc:Percent",tx.taxrate),
                    xmlelement("cac:TaxScheme", xmlelement("cbc:ID",'VAT'), xmlelement("cbc:Name",tx.description)))))
        else null end,
        xmlelement("cac:Item",
          xmlelement("cbc:Name",ic.description)),
        xmlelement("cac:Price",
          xmlelement("cbc:PriceAmount", xmlattributes(cu.code as "currencyID"),
           f_num2char(ic.price, cu.decimals)),
          xmlelement("cbc:BaseQuantity", xmlattributes(( nvl(ru.peppolcode,
           case when ic.invoicelinetype_id in (3,4) then 'KG'
                else 'EA'end)) as "unitCode", 'UNECERec20' as "unitCodeListID"),f_num2char(1,0)))
        ) order by ihl.invoicenumber, ic.linenumber, ic.invoiceline_id)
     from v_peppol_invoiceline_credit ic
     join invoiceheader ihl on ihl.invoiceheader_id = ic.invoiceheader_id
     left outer join invoicelineproduct ilp on ilp.invoiceline_id = ic.invoiceline_id
     left outer join product p join registrationunit ru on ru.registrationunit_id = p.registrationunit_id on p.product_id = ilp.product_link_id
     left outer join invoicelinevarious ilv on ilv.invoiceline_id = ic.invoiceline_id
     left outer join taxgroup tx on tx.code = ic.taxgroupcode and tx.country_id = delto.country_id
     where ic.invoicelinetype_id not in (14, 18)
     and nvl(ihl.parentinvoiceheader_id, ihl.invoiceheader_id) = ih.invoiceheader_id)
        )).getclobval())
        indent size = 3) as tmc_xml
from   invoiceheader ih
join   invoiceheaderextrainfo ihe
on     ihe.invoiceheader_id = ih.invoiceheader_id
left   outer join invoiceheaderediinfo ihde
on     ihde.invoiceheader_id = ih.invoiceheader_id
join   currency cu
on     cu.currency_id = ih.currency_id
join   businessunit bu
on     bu.businessunit_id = ih.invoicebusinessunit_id
join  (legalentity le
join   address ad
on     le.address_id = ad.address_id
join   get_peppol_legalentity(le.legalentity_id) ppl
on     ppl.entity_id = le.legalentity_id) on le.legalentity_id = bu.legalentity_id
left   outer join bankinstitution binst
on     binst.bankinstitution_id = ihe.laundrybankinstitution_id
join   plant pt
on     pt.plant_id = bu.plant_id
join   address adp
on     adp.address_id = pt.address_id
join   country plantcountry
on     plantcountry.country_id = pt.country_id
join   customer billto
on     billto.customer_id = ih.billtocustomer_link_id
join   get_peppol_endpoint(billto.customer_id) pp
on     pp.entity_id = billto.customer_id
left   join customergeneral cg
on     cg.customer_id = billto.customer_id
join   country billtocountry
on     billtocountry.country_id = billto.country_id
join   customer delto
on     delto.customer_id = ih.deltocustomer_link_id
join   country deltocountry
on     deltocountry.country_id = delto.country_id
left   outer join(customerediinfo cedi
join   contactperson cpedi
on     cpedi.contactperson_id = cedi.edicontactperson_id) on cedi.customer_id = billto.customer_id
left   outer join(customerediinfo cedi2
join   contactperson cpedi2
on     cpedi2.contactperson_id = cedi2.edicontactperson_id) on cedi2.customer_id = ih.deltocustomer_link_id
left   outer join(costcenter cc
left   outer join contactperson cpcc
on     cpcc.contactperson_id = cc.contactperson_id) on (cc.code = ih.splitupcode and cc.customer_id = ih.deltocustomer_link_id and cc.exportedi = 1)
where  ih.documenttype = 1
and    ih.paythisamount < 0
and    billto.edimethod = 3 --EDI
and    ih.status_id = (select st.status_id
                       from   status st
                       where  st.code = '2'
                       and    st.statustype = 'IN')
and    (ih.parentinvoiceheader_id is null or ih.parentinvoiceheader_id = ih.invoiceheader_id)
and    ih.paythisamount < 0
/

  CREATE OR REPLACE VIEW "V_XML_PEPPOL_BILLING_CREDIT_30" ("INVOICEHEADER_ID", "INVOICEDATE", "INVOICENUMBER", "PAYTHISAMOUNT", "BILLTOCUSTOMER_LINK_ID", "TMC_XML") AS 
  select /*view v_xml_peppol_billing_credit version 2.1
     ABS-133143 Pagero PEPPOL format - changes needed to standard format- rounding issue and negative lines issue
     ABS-136080 Peppol - CompanyID not correct in XML files
     ABS-136299 Filling tabel invoiceheaderxml and creating XML files a comma is put where a point should be
     ABS-142977 Peppol: PRICEAMOUNT price per unit
     ABS-152442 PEPPOL XML customized
     ABS-153477 Add Global Location Number (GLN) and extend country code - PEPPOL procedure
     ABS-155461 PEPPOL - company name and address option to also use legal entity
     ABS-159140 VAT number from laundry where VAT number from customer should be placed
     ABS-159618 M2 wrong fromat in XML
     ABS-159918 XML for PEPPOL Pagero tag BaseQuantity
     ABS-160092 GLN number where VAT number should be
     ABS-160788 Invoice XML Peppol unit EA
     ABS-163171 Add Belgium Enterprise number
     ABS-160461 CreditedQuantity negative in XML ABS-160465
     ABS-165659 requisitionnumber from costcenter in XML for Peppol
     ABS-163251 Include new Out Going Message (OGM) in PEPPOL export
     ABS-168116 Peppol XML COCNumber as part of AccountingCustomerParty
     ABS-168722 Peppol - XML files wrong totals per taxgroup
     ABSN-3698 PEPPOL: Replacement dots and spaces for accountsupplierparty VAT code
     ABSN-6958 ABS Peppol XML credit invoice negative price
     ABSN-8431 Peppol financial interface modification - database phase 1
     */
  ---Credit note
  ih.invoiceheader_id,ih.invoicedate,ih.invoicenumber,ih.paythisamount,ih.billtocustomer_link_id,
  xmlserialize(content
   xmltype('<?xml version="1.0" encoding="UTF-8" standalone="no"?>' ||
       (xmlelement("CreditNote",
        xmlattributes('urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2' as "xmlns:cac",
          'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2' as "xmlns:cbc",
          'urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2' as "xmlns"),
        xmlelement("cbc:CustomizationID", 'urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0'), --M: added default from doc
        xmlelement("cbc:ProfileID", 'urn:fdc:peppol.eu:2017:poacc:billing:01:1.0'), --M: added default from doc
        xmlelement("cbc:ID", ih.invoicenumber),
        xmlelement("cbc:IssueDate", to_char(ih.invoicedate,'YYYY-MM-DD')),
        xmlelement("cbc:CreditNoteTypeCode",'381'),
        xmlelement("cbc:Note", nvl(trim(replace(replace(trim(ih.invoicecomments), chr(13), ''), chr(10), ' ')),'-')),
        xmlelement("cbc:DocumentCurrencyCode", cu.code),
        xmlelement("cbc:BuyerReference", coalesce(cpcc.name, cpedi.name, ih.contactpersonname)),
        xmlelement("cac:InvoicePeriod",
          xmlelement("cbc:StartDate", nvl(ih.startdate, ih.nextperiodstartdate)),
          xmlelement("cbc:EndDate", nvl(ih.enddate, ih.nextperiodenddate))),
        xmlelement("cac:OrderReference",
           xmlelement("cbc:ID", coalesce(cc.requisitionnumber, case when ih.splitupcode = '0' then null else ih.splitupcode end,
                                (select ce.requisitionnumber
                                 from customerediinfo ce
                                 where ce.customer_id = ih.billtocustomer_link_id),'-'))),
        xmlelement("cac:AdditionalDocumentReference",
          xmlelement("cbc:ID", ih.invoiceheader_id),
          xmlelement("cac:Attachment",
           xmlelement("cac:ExternalReference",
             xmlelement("cbc:URI",'Invoice_'||to_char(ih.invoicenumber) || '.pdf')))),
        xmlelement("cac:AccountingSupplierParty",
          xmlelement("cac:Party",
          xmlelement("cbc:EndpointID",xmlattributes(ppl.schemeid  as "schemeID"), ppl.endpointid),
          xmlelement("cac:PartyIdentification",
          xmlelement("cbc:ID",xmlattributes(ppl.schemeid  as "schemeID"), ppl.endpointid)),
          xmlelement("cac:PartyName",
          xmlelement("cbc:Name", nvl(le.name,pt.name))),
          xmlelement("cac:PostalAddress",
           xmlelement("cbc:StreetName", nvl(ad.street,trim(replace(adp.street, gethousenumber(adp.street, 1))))),
           xmlelement("cbc:CityName", nvl(ad.city,adp.city)),
           xmlelement("cbc:PostalZone", nvl(ad.zipcode,adp.zipcode)),
           xmlelement("cac:Country",
           xmlelement("cbc:IdentificationCode", ppl.countrycode))),
          xmlelement("cac:PartyTaxScheme",
           xmlelement("cbc:CompanyID", ppl.vatcode),
           xmlelement("cac:TaxScheme", xmlelement("cbc:ID", 'VAT'))),
          xmlelement("cac:PartyLegalEntity",
          xmlelement("cbc:RegistrationName", nvl((select max(pc.name) from plantcompany pc where pc.plant_id = bu.plant_id and pc.active ='Y'),'-')),
          xmlelement("cbc:CompanyID",xmlattributes(ppl.schemeid  as "schemeID"), ppl.endpointid)),
          xmlelement("cac:Contact",
          xmlelement("cbc:Name", le.legalname),
          xmlelement("cbc:Telephone", nvl(le.phone,000)),--this could not be empty,
          xmlelement("cbc:ElectronicMail", nvl(le.email,'-'))))),--this could not be empty,
      xmlelement("cac:AccountingCustomerParty",
          xmlelement("cac:Party",
           xmlelement("cbc:EndpointID",
               xmlattributes(pp.schemeid as "schemeID"),pp.endpointid),
          xmlelement("cac:PartyIdentification",
            xmlelement("cbc:ID",
               xmlattributes(pp.schemeid as "schemeID"),pp.endpointid)),
          xmlelement("cac:PartyName",
            xmlelement("cbc:Name", ih.billtocustomername)),
          xmlelement("cac:PostalAddress",
            xmlelement("cbc:StreetName", ih.street),
            xmlelement("cbc:CityName", ih.city),
            xmlelement("cbc:PostalZone", ih.zipcode),
          xmlelement("cac:Country",
            xmlelement("cbc:IdentificationCode", pp.countrycode))),
          xmlelement("cac:PartyTaxScheme",
            xmlelement("cbc:CompanyID", pp.vatcode),
            xmlelement("cac:TaxScheme", xmlelement("cbc:ID", 'VAT'))),
          xmlelement("cac:PartyLegalEntity", xmlelement("cbc:RegistrationName", ih.billtocustomername),
            xmlelement("cbc:CompanyID",
               xmlattributes(pp.schemeid as "schemeID"),pp.endpointid)),
          xmlelement("cac:Contact",
            xmlelement("cbc:Name", coalesce(cpcc.name, cpedi.name, ih.contactpersonname)),
            xmlelement("cbc:Telephone", coalesce(cpcc.phone, cpedi.phone, ih.contactpersonphone, '000')), --could not be null, 000  added as default
            xmlelement("cbc:ElectronicMail", coalesce(cpcc.email, cpedi.email, ih.emailaddress, '-'))))),
          xmlelement("cac:Delivery",
                          xmlelement("cbc:ActualDeliveryDate", ih.invoicedate),
                            xmlelement("cac:DeliveryLocation",
                              xmlelement("cbc:ID",ih.deltocustomernumber),
                              xmlelement("cac:Address",
                              xmlelement("cbc:StreetName", ih.deltostreet),
                              xmlelement("cbc:CityName", ih.deltocity),
                              xmlelement("cbc:PostalZone", ih.deltozipcode),
                              xmlelement("cac:Country",
                                 xmlelement("cbc:IdentificationCode",deltocountry.code)))),
                          xmlelement("cac:DeliveryParty", xmlelement("cac:PartyName", xmlelement("cbc:Name", ih.billtocustomername)))),
            case when binst.laundrybankaccount is not null then
                              xmlelement("cac:PaymentMeans",
                                      xmlelement("cbc:PaymentMeansCode",
                                                  case
                                                     when ih.realcollectiontype = 1 then
                                                      '10'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 0 then
                                                      '10'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 1 then
                                                      '20'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 2 then
                                                      '48'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 3 then
                                                      '42'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 4 then
                                                      '30'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 5 then
                                                      '30'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 6 then
                                                      '42'
                                                     else
                                                      '1'
                                                   end),
                                      xmlelement("cbc:PaymentDueDate", ihe.paymenttermsduedate),
                                      xmlelement("cbc:PaymentID", nvl(ihe.ogm, ih.invoicenumber)),
                                      xmlelement("cac:PayeeFinancialAccount",
                                             xmlelement("cbc:ID", binst.laundrybankaccount)))
                             else null
                           end,
                           case
                            when binst.ibanno is not null then
                              xmlelement("cac:PaymentMeans",
                    xmlelement("cbc:PaymentMeansCode",
                                                  case
                                                     when ih.realcollectiontype = 1 then
                                                      '10'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 0 then
                                                      '10'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 1 then
                                                      '20'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 2 then
                                                      '48'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 3 then
                                                      '42'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 4 then
                                                      '30'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 5 then
                                                      '30'
                                                     when ih.realcollectiontype = 2 and ihe.paymenttype = 6 then
                                                      '42'
                                                     else
                                                      '1'
                                                   end),
                    xmlelement("cbc:PaymentID", nvl(ihe.ogm, ih.invoicenumber)),
                       xmlelement("cac:PayeeFinancialAccount",
                           xmlelement("cbc:ID", binst.ibanno),
                           xmlelement("cac:FinancialInstitutionBranch",
                                xmlelement("cbc:ID", binst.internalidcode))),
                    case when (ih.realcollectiontype = 2 and ihe.paymenttype = 6) or substr(ihe.acceptgirocodeline,22,8) is null then
                                        null
                                       else
                                        xmlelement("cac:CreditAccount", xmlelement("cbc:AccountID",  substr(ihe.acceptgirocodeline,22,8)))
                                       end)
                             else null
                           end,
      case when ih.peppol_amount_correction is null then
       null
      else
       xmlelement("cac:AllowanceCharge",
        xmlelement("cbc:ChargeIndicator", 'false'),
        xmlelement("cbc:AllowanceChargeReasonCode", '95'),
        xmlelement("cbc:AllowanceChargeReason", 'Discount'),
        xmlelement("cbc:MultiplierFactorNumeric", ih.creditsqueezeperc),
        xmlelement("cbc:Amount", xmlattributes(cu.code as "currencyID"), f_num2char(ih.peppol_amount_correction,cu.invoiceamountdecimals)*-1),
        xmlelement("cbc:BaseAmount", xmlattributes(cu.code as "currencyID"), f_num2char(ih.totalamountexclvat,cu.invoiceamountdecimals)*-1),
        xmlelement("cac:TaxCategory",
            --(mis)used ih.deltocounty for vatrate read percentage and ih.deltostate as vatcode
            xmlelement("cbc:ID", case when (nvl(ih.deltocounty,0) = 0 and ih.deltostate = 'AE') then 'AE' when nvl(ih.deltocounty,0) = 0 then 'Z' else 'S' end),
            xmlelement("cbc:Percent",ih.deltocounty),
            case when (ih.deltostate = 'AE')
              then xmlelement("cbc:TaxExemptionReason", 'Reverse charge')
              else null end,
            xmlelement("cac:TaxScheme", xmlelement("cbc:ID",'VAT'))))
      end,
      xmlelement("cac:TaxTotal",
          xmlelement("cbc:TaxAmount",
           xmlattributes(cu.code as "currencyID"),
             f_num2char(((select sum(il.amount) from   invoiceline il
                          join taxgroup tx on tx.code = il.code and tx.country_id = delto.country_id
                          where  il.invoiceheader_id = ih.invoiceheader_id
                          and il.invoicelinetype_id = 18)*-1),cu.invoiceamountdecimals)),
     (select xmlagg( xmlelement("cac:TaxSubtotal",
         xmlelement("cbc:TaxableAmount", xmlattributes(cu.code as "currencyID"),
             f_num2char(iv.overamount*-1,cu.invoiceamountdecimals)),
         xmlelement("cbc:TaxAmount", xmlattributes(cu.code as "currencyID"), f_num2char(il.amount*-1,cu.invoiceamountdecimals)),
         xmlelement("cac:TaxCategory",
            xmlelement("cbc:ID",case when (nvl(tx.taxrate,0) = 0 and tx.code = 'AE') then 'AE' when nvl(tx.taxrate,0) = 0 then 'Z' else 'S' end),
            xmlelement("cbc:Percent",tx.taxrate),
            case when (il.taxtype = 0 and tx.code = 'AE')
              then xmlelement("cbc:TaxExemptionReason", 'Reverse charge')
              else null end,
            xmlelement("cac:TaxScheme", xmlelement("cbc:ID",'VAT')))) order by il.linenumber, il.invoiceline_id)
      from   invoiceline il
      join taxgroup tx on tx.code = il.code and tx.country_id = delto.country_id
      join invoicelinevarious iv on iv.invoiceline_id = il.invoiceline_id
      where  il.invoiceheader_id = ih.invoiceheader_id
      and il.invoicelinetype_id = 18)),
       xmlelement("cac:LegalMonetaryTotal",
       xmlelement("cbc:LineExtensionAmount", xmlattributes(cu.code as "currencyID"),
        f_num2char((ih.totalamountexclvat)*-1,cu.invoiceamountdecimals)),
       xmlelement("cbc:TaxExclusiveAmount", xmlattributes(cu.code as "currencyID"),
        f_num2char((ih.totalamountexclvat-nvl(ih.peppol_amount_correction,0))*-1,cu.invoiceamountdecimals)),
       xmlelement("cbc:TaxInclusiveAmount", xmlattributes(cu.code as "currencyID"),
        f_num2char((ih.paythisamount-nvl(ih.peppol_amount_correction,0))*-1, cu.invoiceamountdecimals)),
      case when ih.peppol_amount_correction is null then
       null
      else
       xmlelement("cbc:AllowanceTotalAmount", xmlattributes(cu.code as "currencyID"),
         f_num2char(nvl(ih.peppol_amount_correction,0), cu.invoiceamountdecimals))
      end,
       xmlelement("cbc:PayableAmount", xmlattributes(cu.code as "currencyID"),
        f_num2char((ih.paythisamount-nvl(ih.peppol_amount_correction,0))*-1, cu.invoiceamountdecimals))),
       (select xmlagg(
     xmlelement("cac:CreditNoteLine",
     case when ihl.parentinvoiceheader_id is not null then
        xmlelement("cbc:ID", (ihl.invoicenumber*1000) + il.linenumber)
     else
        xmlelement("cbc:ID", il.linenumber)
     end,
        xmlelement("cbc:Note", nvl(il.remark,'-')),
        xmlelement("cbc:CreditedQuantity", xmlattributes(( nvl(ru.peppolcode,
           case when il.invoicelinetype_id in (3,4) then 'KGM'
                else 'EA'end)) as "unitCode"),
           f_num2char(il.billedqty, case when round(il.billedqty) = il.billedqty then 0 else 3 end)),
        xmlelement("cbc:LineExtensionAmount", xmlattributes(cu.code as "currencyID"),
           f_num2char(il.amount,cu.invoiceamountdecimals)),
        xmlelement("cac:OrderLineReference", xmlelement("cbc:LineID", il.linenumber)),
        xmlelement("cac:Item",
          xmlelement("cbc:Name",il.description),
          xmlelement( "cac:ClassifiedTaxCategory",
            xmlelement("cbc:ID", case when (nvl(tx.taxrate,0) = 0 and tx.code = 'AE') then 'AE' when nvl(tx.taxrate,0) = 0 then 'Z' else 'S' end),          -- Standard rated
            xmlelement("cbc:Percent", tx.taxrate),      -- VAT rate
            xmlelement("cac:TaxScheme", xmlelement("cbc:ID", 'VAT')))),
        xmlelement("cac:Price",
          xmlelement("cbc:PriceAmount", xmlattributes(cu.code as "currencyID"),
           f_num2char(il.price, cu.decimals)),
          xmlelement("cbc:BaseQuantity", xmlattributes(( nvl(ru.peppolcode,
           case when il.invoicelinetype_id in (3,4) then 'KGM'
                else 'EA'end)) as "unitCode"),f_num2char(1,0)))
        ) order by ihl.invoicenumber, il.linenumber, il.invoiceline_id)
     from v_peppol_invoiceline_credit il
     join invoiceheader ihl on ihl.invoiceheader_id = il.invoiceheader_id
     left outer join invoicelineproduct ilp on ilp.invoiceline_id = il.invoiceline_id
     left outer join product p join registrationunit ru on ru.registrationunit_id = p.registrationunit_id on p.product_id = ilp.product_link_id
     left outer join invoicelinevarious ilv on ilv.invoiceline_id = il.invoiceline_id
     left outer join taxgroup tx on tx.code = il.taxgroupcode and tx.country_id = billto.country_id
     where il.invoicelinetype_id not in (14, 18)
     and nvl(ihl.parentinvoiceheader_id, ihl.invoiceheader_id) = ih.invoiceheader_id)
        )).getclobval())
        indent size = 3) as tmc_xml
from   invoiceheader ih
join   invoiceheaderextrainfo ihe
on     ihe.invoiceheader_id = ih.invoiceheader_id
left   outer join invoiceheaderediinfo ihde
on     ihde.invoiceheader_id = ih.invoiceheader_id
join   currency cu
on     cu.currency_id = ih.currency_id
join   businessunit bu
on     bu.businessunit_id = ih.invoicebusinessunit_id
join  (legalentity le
join   address ad
on     le.address_id = ad.address_id
join   get_peppol_legalentity(le.legalentity_id) ppl
on     ppl.entity_id = le.legalentity_id) on le.legalentity_id = bu.legalentity_id
left   outer join bankinstitution binst
on     binst.bankinstitution_id = ihe.laundrybankinstitution_id
join   plant pt
on     pt.plant_id = bu.plant_id
join   address adp
on     adp.address_id = pt.address_id
join   customer billto
on     billto.customer_id = ih.billtocustomer_link_id
join   get_peppol_endpoint(billto.customer_id) pp
on     pp.entity_id = billto.customer_id
left   join customergeneral cg
on     cg.customer_id = billto.customer_id
join   customer delto
on     delto.customer_id = ih.deltocustomer_link_id
join   country deltocountry
on     deltocountry.country_id = delto.country_id
left   outer join(customerediinfo cedi
join   contactperson cpedi
on     cpedi.contactperson_id = cedi.edicontactperson_id) on cedi.customer_id = billto.customer_id
left   outer join(customerediinfo cedi2
join   contactperson cpedi2
on     cpedi2.contactperson_id = cedi2.edicontactperson_id) on cedi2.customer_id = ih.deltocustomer_link_id
left   outer join(costcenter cc
left   outer join contactperson cpcc
on     cpcc.contactperson_id = cc.contactperson_id) on (cc.code = ih.splitupcode and cc.customer_id = ih.deltocustomer_link_id and cc.exportedi = 1)
where  ih.documenttype = 1
and    ih.paythisamount < 0
and    billto.edimethod = 3 --EDI
and    ih.status_id = (select st.status_id
                       from   status st
                       where  st.code = '2'
                       and    st.statustype = 'IN')
and    (ih.parentinvoiceheader_id is null or ih.parentinvoiceheader_id = ih.invoiceheader_id)
and    ih.paythisamount < 0
/

  CREATE OR REPLACE VIEW "V_XML_PEPPOL_BILLING_DEBIT" ("INVOICEHEADER_ID", "INVOICEDATE", "INVOICENUMBER", "PAYTHISAMOUNT", "BILLTOCUSTOMER_LINK_ID", "TMC_XML") AS 
  select /*view v_xml_peppol_billing_debit version 10.10
     ABS-133143 Pagero PEPPOL format - changes needed to standard format- rounding issue and negative lines issue
     ABS-136080 Peppol - CompanyID not correct in XML files
     ABS-136299 Filling tabel invoiceheaderxml and creating XML files a comma is put where a point should be
     ABS-142977 Peppol: PRICEAMOUNT price per unit
     ABS-152442 PEPPOL XML customized
     ABS-153477 Add Global Location Number (GLN) and extend country code - PEPPOL procedure
     ABS-155461 PEPPOL - company name and address option to also use legal entity
     ABS-159140 VAT number from laundry where VAT number from customer should be placed
     ABS-159618 M2 wrong fromat in XML
     ABS-159918 XML for PEPPOL Pagero tag BaseQuantity
     ABS-160092 GLN number where VAT number should be
     ABS-160788 Invoice XML Peppol unit EA
     ABS-163171 Add Belgium Enterprise number
     ABS-165659 requisitionnumber from costcenter in XML for Peppol
     ABS-163251 Include new Out Going Message (OGM) in PEPPOL export
     ABS-168116 Peppol XML COCNumber as part of AccountingCustomerParty
     ABS-168722 Peppol - XML files wrong totals per taxgroup
     ABSN-3698 PEPPOL: Replacement dots and spaces for accountsupplierparty VAT code
     ABSN-6958 ABS Peppol XML credit invoice negative price
     ABSN-8431 Peppol financial interface modification - database
     */
  ---Invoice
  ih.invoiceheader_id,ih.invoicedate,ih.invoicenumber,ih.paythisamount,ih.billtocustomer_link_id,
  xmlserialize(content
   xmltype('<?xml version="1.0" encoding="UTF-8" standalone="no"?>' ||
       (xmlelement("Invoice",
        xmlattributes('urn:pagero:CommonAggregateComponents:1.0' as "xmlns:cac",
                      'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2' as "xmlns:cbc",
                      'urn:pagero:ExtensionComponent:1.0' as "xmlns:puf",
                      'urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2' as "xmlns:ext",
                      'urn:pagero:PageroUniversalFormat:Invoice:1.0' as "xmlns"),
        xmlelement("cbc:CustomizationID", 'urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0#conformant#urn:pagero.com:puf:billing:1.0'),
        xmlelement("cbc:ProfileID", 'urn:pagero.com:puf:billing:1.0'),
        xmlelement("cbc:ID", ih.invoicenumber),
        xmlelement("cbc:IssueDate", to_char(ih.invoicedate,'YYYY-MM-DD')),
        xmlelement("cbc:DueDate", to_char(ihe.paymenttermsduedate,'YYYY-MM-DD')),
        xmlelement("cbc:InvoiceTypeCode",'380'),
        xmlelement("cbc:Note", replace(replace(trim(ih.invoicecomments), chr(13), ''), chr(10), ' ')),
        xmlelement("cbc:DocumentCurrencyCode", cu.code),
        xmlelement("cbc:BuyerReference", coalesce(cpcc.name, cpedi.name, ih.contactpersonname)),
        xmlelement("cac:InvoicePeriod",
          xmlelement("cbc:StartDate", nvl(ih.startdate, ih.nextperiodstartdate)),
          xmlelement("cbc:EndDate", nvl(ih.enddate, ih.nextperiodenddate))),
        xmlelement("cac:OrderReference",
           xmlelement("cbc:ID", coalesce(cc.requisitionnumber, case when ih.splitupcode = '0' then null else ih.splitupcode end,
                                (select ce.requisitionnumber
                                 from customerediinfo ce
                                 where ce.customer_id = ih.billtocustomer_link_id),'-'))),
        xmlelement("cac:AdditionalDocumentReference",
          xmlelement("cbc:ID", ih.invoicenumber),
          xmlelement("cac:Attachment",
           xmlelement("cac:ExternalReference",
             xmlelement("cbc:URI",'Invoice_'||to_char(ih.invoicenumber) || '.pdf')))),
        xmlelement("cac:AccountingSupplierParty",
          xmlelement("cac:Party",
          xmlelement("cbc:EndpointID",xmlattributes(ppl.schemeid  as "schemeID"), ppl.endpointid),
          xmlelement("cac:PartyIdentification",
          xmlelement("cbc:ID",xmlattributes(ppl.schemeid  as "schemeID"), ppl.endpointid)),
          xmlelement("cac:PartyName",
          xmlelement("cbc:Name", nvl(le.name,pt.name))),
          xmlelement("cac:PostalAddress",
           xmlelement("cbc:StreetName", nvl(ad.street,trim(replace(adp.street, gethousenumber(adp.street, 1))))),
           xmlelement("cbc:CityName", nvl(ad.city,adp.city)),
           xmlelement("cbc:PostalZone", nvl(ad.zipcode,adp.zipcode)),
           xmlelement("cac:Country",
           xmlelement("cbc:IdentificationCode", ppl.countrycode))),
          xmlelement("cac:PartyTaxScheme",
           xmlelement("cbc:CompanyID", xmlattributes(get_peppol_schemeid(ppl.countrycode, 'VAT') as "schemeID"), ppl.vatcode),
           xmlelement("cac:TaxScheme", xmlelement("cbc:ID", 'VAT'))),
          xmlelement("cac:PartyLegalEntity",
          xmlelement("cbc:RegistrationName", (select max(pc.name) from plantcompany pc where pc.plant_id = bu.plant_id and pc.active ='Y')),
          xmlelement("cbc:CompanyID",xmlattributes(ppl.schemeid  as "schemeID"), ppl.endpointid)),
          xmlelement("cac:Contact",
          xmlelement("cbc:ID", le.legalentity_id),
          xmlelement("cbc:Name", le.legalname),
          xmlelement("cbc:Telephone", le.phone),
          xmlelement("cbc:Telefax", pt.faxno),
          xmlelement("cbc:ElectronicMail", le.email)))),
      xmlelement("cac:AccountingCustomerParty", xmlelement("cbc:SupplierAssignedAccountID", ih.billtocustomernumber),
          xmlelement("cac:Party",
           xmlelement("cbc:EndpointID",
               xmlattributes(pp.schemeid as "schemeID"), pp.endpointid),
          xmlelement("cac:PartyIdentification",
            xmlelement("cbc:ID",
               xmlattributes(pp.schemeid as "schemeID"),pp.endpointid)),
          xmlelement("cac:PartyName",
            xmlelement("cbc:Name", ih.billtocustomername)),
          xmlelement("cac:PostalAddress",
            xmlelement("cbc:StreetName", ih.street),
            xmlelement("cbc:CityName", ih.city),
            xmlelement("cbc:PostalZone", ih.zipcode),
          xmlelement("cac:Country",
            xmlelement("cbc:IdentificationCode", xmlattributes('ISO3166-1:Alpha2' as "listID"), billtocountry.code))),
          xmlelement("cac:PartyTaxScheme",
            xmlelement("cbc:CompanyID", pp.vatcode),
            xmlelement("cac:TaxScheme", xmlelement("cbc:ID", 'VAT'))),
          xmlelement("cac:PartyLegalEntity", xmlelement("cbc:RegistrationName", ih.billtocustomername),
            xmlelement("cbc:CompanyID",
               xmlattributes(pp.schemeid "schemeID"),pp.endpointid)),
          xmlelement("cac:Contact",
            xmlelement("cbc:ID",   coalesce(cpcc.name, cpedi.name, ih.contactpersonname)),
            xmlelement("cbc:Name", coalesce(cpcc.name, cpedi.name, ih.contactpersonname)),
            xmlelement("cbc:Telephone", coalesce(cpcc.phone, cpedi.phone, ih.contactpersonphone)),
            xmlelement("cbc:ElectronicMail", coalesce(cpcc.email, cpedi.email, ih.emailaddress))))),
        xmlelement("cac:Delivery",
                       xmlelement("cbc:ActualDeliveryDate", ih.invoicedate),
                       xmlelement("cac:DeliveryLocation",
                              xmlelement("cbc:ID",ih.deltocustomernumber),
                              xmlelement("cac:Address",
                              xmlelement("cbc:StreetName", ih.deltostreet),
                              xmlelement("cbc:CityName", ih.deltocity),
                              xmlelement("cbc:PostalZone", ih.deltozipcode),
                              xmlelement("cac:Country",
                                 xmlelement("cbc:IdentificationCode",deltocountry.code)))),
                       xmlelement("cac:DeliveryParty", xmlelement("cac:PartyName", xmlelement("cbc:Name", ih.billtocustomername)))),
        case
          when binst.ibanno is not null then
            xmlelement("cac:PaymentMeans",
                    xmlelement("cbc:ID",'1'),
                    xmlelement("cbc:PaymentMeansCode", xmlattributes('UNCL4461' as "listID"),
                                case
                                   when ih.realcollectiontype = 1 then
                                    '10'
                                   when ih.realcollectiontype = 2 and ihe.paymenttype = 0 then
                                    '10'
                                   when ih.realcollectiontype = 2 and ihe.paymenttype = 1 then
                                    '20'
                                   when ih.realcollectiontype = 2 and ihe.paymenttype = 2 then
                                    '48'
                                   when ih.realcollectiontype = 2 and ihe.paymenttype = 3 then
                                    '42'
                                   when ih.realcollectiontype = 2 and ihe.paymenttype = 4 then
                                    '30'
                                   when ih.realcollectiontype = 2 and ihe.paymenttype = 5 then
                                    '30'
                                   when ih.realcollectiontype = 2 and ihe.paymenttype = 6 then
                                    '42'
                                   else
                                    '1'
                                 end),
                    xmlelement("cbc:PaymentDueDate", ihe.paymenttermsduedate),
                    xmlelement("cbc:InstructionID", substr(ihe.acceptgirocodeline, 5, 15)),
                    xmlelement("cbc:PaymentID", nvl(ihe.ogm, ih.invoicenumber)),
                       xmlelement("cac:PayeeFinancialAccount",
                           xmlelement("cbc:ID", xmlattributes('IBAN' as "schemeID"), binst.ibanno),
                           xmlelement("cac:FinancialInstitutionBranch",
                                xmlelement("cbc:ID", xmlattributes('BIC' as "schemeID"), binst.internalidcode))),
                    case when ih.realcollectiontype = 2 and ihe.paymenttype = 6 then
                      null
                     else
                      xmlelement("cac:CreditAccount", xmlelement("cbc:AccountID",  substr(ihe.acceptgirocodeline,22,8)))
                     end)
           else null
        end,
      xmlelement("cac:PaymentTerms", xmlelement("cbc:ID", 1),
                                 xmlelement("cbc:PaymentMeansID", 1),
                                 xmlelement("cbc:Note", ihe.paymenttermsdescription),
                                 xmlelement("cbc:Amount", xmlattributes(cu.code as "currencyID"), f_num2char(ih.paythisamount, cu.invoiceamountdecimals)),
                                 xmlelement("cac:PenaltyPeriod", xmlelement("cbc:StartDate", ihe.paymenttermsduedate))),
      xmlelement("cac:TaxTotal",
          xmlelement("cbc:TaxAmount",
           xmlattributes(cu.code as "currencyID"),
             f_num2char(((select sum(il.amount) from invoiceline il
                          join taxgroup tx on tx.code = il.code and tx.country_id = delto.country_id
                          where  il.invoiceheader_id = ih.invoiceheader_id
                          and il.invoicelinetype_id = 18)),cu.invoiceamountdecimals)), --------------------------------
     (select xmlagg( xmlelement("cac:TaxSubtotal",
         xmlelement("cbc:TaxableAmount", xmlattributes(cu.code as "currencyID"),
             f_num2char(iv.overamount,cu.invoiceamountdecimals)),
         xmlelement("cbc:TaxAmount", xmlattributes(cu.code as "currencyID"), f_num2char(il.amount,cu.invoiceamountdecimals)),
         xmlelement("cac:TaxCategory",
            xmlelement("cbc:ID",'S'),
            xmlelement("cbc:Percent",tx.taxrate),
            xmlelement("cac:TaxScheme", xmlelement("cbc:ID",'VAT'), xmlelement("cbc:Name",tx.description)))) order by il.linenumber, il.invoiceline_id)
      from invoiceline il
      join taxgroup tx on tx.code = il.code and tx.country_id = delto.country_id
      join invoicelinevarious iv on iv.invoiceline_id = il.invoiceline_id
      where  il.invoiceheader_id = ih.invoiceheader_id
     and il.invoicelinetype_id = 18)),
       xmlelement("cac:LegalMonetaryTotal",
       xmlelement("cbc:LineExtensionAmount", xmlattributes(cu.code as "currencyID"),
         f_num2char(ih.totalamountexclvat+nvl(ih.peppol_amount_correction,0), cu.invoiceamountdecimals)),
       xmlelement("cbc:TaxExclusiveAmount", xmlattributes(cu.code as "currencyID"),
         f_num2char(ih.totalamountexclvat+nvl(ih.peppol_amount_correction,0), cu.invoiceamountdecimals)),
       xmlelement("cbc:TaxInclusiveAmount", xmlattributes(cu.code as "currencyID"),
         f_num2char(ih.paythisamount+nvl(ih.peppol_amount_correction,0), cu.invoiceamountdecimals)),
       xmlelement("cbc:PayableAmount", xmlattributes(cu.code as "currencyID"),
         f_num2char(ih.paythisamount+nvl(ih.peppol_amount_correction,0), cu.invoiceamountdecimals))),
       (select xmlagg(
     xmlelement("cac:InvoiceLine",
     case when ihl.parentinvoiceheader_id is not null then
        xmlelement("cbc:ID", (ihl.invoicenumber*1000) + il.linenumber)
     else
        xmlelement("cbc:ID", il.linenumber)
     end,
        xmlelement("cbc:Note", nvl(il.remark,'-')),
        xmlelement("cbc:InvoicedQuantity", xmlattributes(( nvl(ru.peppolcode,
           case when il.invoicelinetype_id in (3,4) then 'KG'
                else 'EA'end)) as "unitCode", 'UNECERec20' as "unitCodeListID"),
           f_num2char(il.billedqty, case when round(il.billedqty) = il.billedqty then 0 else 2 end)),
        xmlelement("cbc:LineExtensionAmount", xmlattributes(cu.code as "currencyID"),
           f_num2char(il.amount,cu.invoiceamountdecimals)),
        xmlelement("cac:OrderLineReference", xmlelement("cbc:LineID", il.linenumber)),
        case when tx.code is not null then
          xmlelement("cac:TaxTotal",
            xmlelement("cbc:TaxAmount",
            xmlattributes(cu.code as "currencyID"),
             f_num2char(il.amount * tx.taxrate / 100, cu.invoiceamountdecimals)),
            xmlelement("cac:TaxSubtotal",
              xmlelement("cbc:TaxableAmount", xmlattributes(cu.code as "currencyID"), f_num2char(il.amount, cu.invoiceamountdecimals)),
              xmlelement("cbc:TaxAmount", xmlattributes(cu.code as "currencyID"), f_num2char(il.amount * tx.taxrate / 100,cu.invoiceamountdecimals)),
              xmlelement("cac:TaxCategory",
                    xmlelement("cbc:ID",'UNCL5305'),
                    xmlelement("cbc:Percent",tx.taxrate),
                    xmlelement("cac:TaxScheme", xmlelement("cbc:ID",'VAT'), xmlelement("cbc:Name",tx.description)))))
          else null end,
        xmlelement("cac:Item",
          xmlelement("cbc:Name",il.description)),
        xmlelement("cac:Price",
          xmlelement("cbc:PriceAmount", xmlattributes(cu.code as "currencyID"),
           f_num2char(il.price, cu.decimals)),
          xmlelement("cbc:BaseQuantity", xmlattributes(( nvl(ru.peppolcode,
           case when il.invoicelinetype_id in (3,4) then 'KG'
                else 'EA'end)) as "unitCode", 'UNECERec20' as "unitCodeListID"),f_num2char(1,0)))
        ) order by ihl.invoicenumber, il.linenumber, il.invoiceline_id)
     from v_peppol_invoiceline_debit il
     join invoiceheader ihl on ihl.invoiceheader_id = il.invoiceheader_id
     left outer join invoicelineproduct ilp on ilp.invoiceline_id = il.invoiceline_id
     left outer join product p join registrationunit ru on ru.registrationunit_id = p.registrationunit_id on p.product_id = ilp.product_link_id
     left outer join invoicelinevarious ilv on ilv.invoiceline_id = il.invoiceline_id
     left outer join taxgroup tx on tx.code = il.taxgroupcode and tx.country_id = delto.country_id
     where il.invoicelinetype_id not in (14, 18)
     and nvl(ihl.parentinvoiceheader_id, ihl.invoiceheader_id) = ih.invoiceheader_id)
        )).getclobval())
        indent size = 3) as tmc_xml
from   invoiceheader ih
join   invoiceheaderextrainfo ihe
on     ihe.invoiceheader_id = ih.invoiceheader_id
left   outer join invoiceheaderediinfo ihde
on     ihde.invoiceheader_id = ih.invoiceheader_id
join   currency cu
on     cu.currency_id = ih.currency_id
join   businessunit bu
on     bu.businessunit_id = ih.invoicebusinessunit_id
join  (legalentity le
join   address ad
on     le.address_id = ad.address_id
join   get_peppol_legalentity(le.legalentity_id) ppl
on     ppl.entity_id = le.legalentity_id) on le.legalentity_id = bu.legalentity_id
left   outer join bankinstitution binst
on     binst.bankinstitution_id = ihe.laundrybankinstitution_id
join   plant pt
on     pt.plant_id = bu.plant_id
join   address adp
on     adp.address_id = pt.address_id
join   customer billto
on     billto.customer_id = ih.billtocustomer_link_id
join   get_peppol_endpoint(billto.customer_id) pp
on     pp.entity_id = billto.customer_id
left   join customergeneral cg
on     cg.customer_id = billto.customer_id
join   country billtocountry
on     billtocountry.country_id = billto.country_id
join   customer delto
on     delto.customer_id = ih.deltocustomer_link_id
join   country deltocountry
on     deltocountry.country_id = delto.country_id
left   outer join(customerediinfo cedi
join   contactperson cpedi
on     cpedi.contactperson_id = cedi.edicontactperson_id) on cedi.customer_id = billto.customer_id
left   outer join(customerediinfo cedi2
join   contactperson cpedi2
on     cpedi2.contactperson_id = cedi2.edicontactperson_id) on cedi2.customer_id = ih.deltocustomer_link_id
left   outer join(costcenter cc
left   outer join contactperson cpcc
on     cpcc.contactperson_id = cc.contactperson_id) on (cc.code = ih.splitupcode and cc.customer_id = ih.deltocustomer_link_id and cc.exportedi = 1)
where  ih.documenttype = 1
and    billto.edimethod = 3 --EDI
and    ih.paythisamount > 0
and    ih.status_id = (select st.status_id
                       from   status st
                       where  st.code = '2'
                       and    st.statustype = 'IN')
and    (ih.parentinvoiceheader_id is null or ih.parentinvoiceheader_id = ih.invoiceheader_id)
and    ih.paythisamount > 0
/

  CREATE OR REPLACE VIEW "V_XML_PEPPOL_BILLING_DEBIT_30" ("INVOICEHEADER_ID", "INVOICEDATE", "INVOICENUMBER", "PAYTHISAMOUNT", "BILLTOCUSTOMER_LINK_ID", "TMC_XML") AS 
  select /*view v_xml_peppol_billing_debit_30 version 2.1
     ABS-133143 Pagero PEPPOL format - changes needed to standard format- rounding issue and negative lines issue
     ABS-136080 Peppol - CompanyID not correct in XML files
     ABS-136299 Filling tabel invoiceheaderxml and creating XML files a comma is put where a point should be
     ABS-142977 Peppol: PRICEAMOUNT price per unit
     ABS-152442 PEPPOL XML customized
     ABS-153477 Add Global Location Number (GLN) and extend country code - PEPPOL procedure
     ABS-155461 PEPPOL - company name and address option to also use legal entity
     ABS-159140 VAT number from laundry where VAT number from customer should be placed
     ABS-159618 M2 wrong fromat in XML
     ABS-159918 XML for PEPPOL Pagero tag BaseQuantity
     ABS-160092 GLN number where VAT number should be
     ABS-160788 Invoice XML Peppol unit EA
     ABS-163171 Add Belgium Enterprise number
     ABS-165659 requisitionnumber from costcenter in XML for Peppol
     ABS-163251 Include new Out Going Message (OGM) in PEPPOL export
     ABS-168116 Peppol XML COCNumber as part of AccountingCustomerParty
     ABS-168722 Peppol - XML files wrong totals per taxgroup
     ABSN-3698 PEPPOL: Replacement dots and spaces for accountsupplierparty VAT code
     ABSN-6958 ABS Peppol XML credit invoice negative price
     ABSN-8431 Peppol financial interface modification - database phase 1
     */
  ---Invoice
  ih.invoiceheader_id,ih.invoicedate,ih.invoicenumber,ih.paythisamount,ih.billtocustomer_link_id,
  xmlserialize(content
   xmltype('<?xml version="1.0" encoding="UTF-8" standalone="no"?>' ||
       (xmlelement("Invoice",
        xmlattributes('urn:oasis:names:specification:ubl:schema:xsd:Invoice-2' as "xmlns",
          'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2' as "xmlns:cac",
          'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2' as "xmlns:cbc",
          'urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2' as "xmlns:ext"),
        xmlelement("cbc:CustomizationID", 'urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0'), --M: added default from doc
        xmlelement("cbc:ProfileID", 'urn:fdc:peppol.eu:2017:poacc:billing:01:1.0'), --M: added default from doc
        xmlelement("cbc:ID", ih.invoicenumber),
        xmlelement("cbc:IssueDate", to_char(ih.invoicedate,'YYYY-MM-DD')),
        xmlelement("cbc:InvoiceTypeCode",'380'),
        xmlelement("cbc:Note", nvl(trim(replace(replace(trim(ih.invoicecomments), chr(13), ''), chr(10), ' ')),'-')),
        xmlelement("cbc:DocumentCurrencyCode", cu.code),
        xmlelement("cbc:BuyerReference", coalesce(cpcc.name, cpedi.name, ih.contactpersonname)),
        xmlelement("cac:InvoicePeriod",
          xmlelement("cbc:StartDate", nvl(ih.startdate, ih.nextperiodstartdate)),
          xmlelement("cbc:EndDate", nvl(ih.enddate, ih.nextperiodenddate))),
        xmlelement("cac:OrderReference",
           xmlelement("cbc:ID", coalesce(cc.requisitionnumber, case when ih.splitupcode = '0' then null else ih.splitupcode end,
                                (select ce.requisitionnumber
                                 from customerediinfo ce
                                 where ce.customer_id = ih.billtocustomer_link_id),'-'))),
        xmlelement("cac:AdditionalDocumentReference",
          xmlelement("cbc:ID", ih.invoicenumber),
          xmlelement("cac:Attachment",
           xmlelement("cac:ExternalReference",
             xmlelement("cbc:URI",'Invoice_'||to_char(ih.invoicenumber) || '.pdf')))),
        xmlelement("cac:AccountingSupplierParty",
          xmlelement("cac:Party",
          xmlelement("cbc:EndpointID",xmlattributes(ppl.schemeid  as "schemeID"), ppl.endpointid),
          xmlelement("cac:PartyIdentification",
          xmlelement("cbc:ID",xmlattributes(ppl.schemeid  as "schemeID"), ppl.endpointid)),
          xmlelement("cac:PartyName",
          xmlelement("cbc:Name", nvl(le.name,pt.name))),
          xmlelement("cac:PostalAddress",
           xmlelement("cbc:StreetName", nvl(ad.street,trim(replace(adp.street, gethousenumber(adp.street, 1))))),
           xmlelement("cbc:CityName", nvl(ad.city,adp.city)),
           xmlelement("cbc:PostalZone", nvl(ad.zipcode,adp.zipcode)),
           xmlelement("cac:Country",
           xmlelement("cbc:IdentificationCode", ppl.countrycode))),
          xmlelement("cac:PartyTaxScheme",
           xmlelement("cbc:CompanyID", ppl.vatcode),
           xmlelement("cac:TaxScheme", xmlelement("cbc:ID", 'VAT'))),
          xmlelement("cac:PartyLegalEntity",
          xmlelement("cbc:RegistrationName", nvl((select max(pc.name) from plantcompany pc where pc.plant_id = bu.plant_id and pc.active ='Y'),'-')),
          xmlelement("cbc:CompanyID",xmlattributes(ppl.schemeid  as "schemeID"), ppl.endpointid)),
          xmlelement("cac:Contact",
          xmlelement("cbc:Name", le.legalname),
          xmlelement("cbc:Telephone", nvl(le.phone,000)),--this could not be empty,
          xmlelement("cbc:ElectronicMail", nvl(le.email,'-'))))),--this could not be empty,
      xmlelement("cac:AccountingCustomerParty",
          xmlelement("cac:Party",
           xmlelement("cbc:EndpointID",
               xmlattributes(pp.schemeid as "schemeID"), pp.EndpointID),
          xmlelement("cac:PartyIdentification",
            xmlelement("cbc:ID",
               xmlattributes(pp.schemeid as "schemeID"), pp.EndpointID)),
          xmlelement("cac:PartyName",
            xmlelement("cbc:Name", ih.billtocustomername)),
          xmlelement("cac:PostalAddress",
            xmlelement("cbc:StreetName", ih.street),
            xmlelement("cbc:CityName", ih.city),
            xmlelement("cbc:PostalZone", ih.zipcode),
          xmlelement("cac:Country",
            xmlelement("cbc:IdentificationCode", pp.countrycode))),
          xmlelement("cac:PartyTaxScheme",
            xmlelement("cbc:CompanyID", pp.vatcode),
            xmlelement("cac:TaxScheme", xmlelement("cbc:ID", 'VAT'))),
          xmlelement("cac:PartyLegalEntity", xmlelement("cbc:RegistrationName", ih.billtocustomername),
            xmlelement("cbc:CompanyID",
               xmlattributes(pp.schemeid "schemeID"),pp.endpointid)),
          xmlelement("cac:Contact",
            xmlelement("cbc:Name", coalesce(cpcc.name, cpedi.name, ih.contactpersonname)),
            xmlelement("cbc:Telephone", coalesce(cpcc.phone, cpedi.phone, ih.contactpersonphone, '000')), --could not be null, 000  added as default
            xmlelement("cbc:ElectronicMail", coalesce(cpcc.email, cpedi.email, ih.emailaddress, '-'))))),
        xmlelement("cac:Delivery",
                       xmlelement("cbc:ActualDeliveryDate", ih.invoicedate),
                       xmlelement("cac:DeliveryLocation",
                              xmlelement("cbc:ID",ih.deltocustomernumber),
                              xmlelement("cac:Address",
                              xmlelement("cbc:StreetName", ih.deltostreet),
                              xmlelement("cbc:CityName", ih.deltocity),
                              xmlelement("cbc:PostalZone", ih.deltozipcode),
                              xmlelement("cac:Country",
                                 xmlelement("cbc:IdentificationCode",deltocountry.code)))),
                       xmlelement("cac:DeliveryParty", xmlelement("cac:PartyName", xmlelement("cbc:Name", ih.billtocustomername)))),
        case
          when binst.ibanno is not null then
            xmlelement("cac:PaymentMeans",
                    xmlelement("cbc:PaymentMeansCode",
                                case
                                   when ih.realcollectiontype = 1 then
                                    '10'
                                   when ih.realcollectiontype = 2 and ihe.paymenttype = 0 then
                                    '10'
                                   when ih.realcollectiontype = 2 and ihe.paymenttype = 1 then
                                    '20'
                                   when ih.realcollectiontype = 2 and ihe.paymenttype = 2 then
                                    '48'
                                   when ih.realcollectiontype = 2 and ihe.paymenttype = 3 then
                                    '42'
                                   when ih.realcollectiontype = 2 and ihe.paymenttype = 4 then
                                    '30'
                                   when ih.realcollectiontype = 2 and ihe.paymenttype = 5 then
                                    '30'
                                   when ih.realcollectiontype = 2 and ihe.paymenttype = 6 then
                                    '42'
                                   else
                                    '1'
                                 end),
                    case when ihe.acceptgirocodeline is not null
                      then xmlelement("cbc:InstructionID", substr(ihe.acceptgirocodeline, 5, 15))
                      else null end,
                    xmlelement("cbc:PaymentID", nvl(ihe.ogm, ih.invoicenumber)),
                       xmlelement("cac:PayeeFinancialAccount",
                           xmlelement("cbc:ID", binst.ibanno),
                           xmlelement("cac:FinancialInstitutionBranch",
                                xmlelement("cbc:ID", binst.internalidcode))),
                    case when (ih.realcollectiontype = 2 and ihe.paymenttype = 6) or substr(ihe.acceptgirocodeline,22,8) is null then
                      null
                     else
                      xmlelement("cac:CreditAccount", xmlelement("cbc:AccountID",  substr(ihe.acceptgirocodeline,22,8)))
                     end)
           else null
        end,
      xmlelement("cac:PaymentTerms", xmlelement("cbc:Note", nvl(ihe.paymenttermsdescription,'-'))),
      case when ih.peppol_amount_correction is null then
       null
      else
       xmlelement("cac:AllowanceCharge",
        xmlelement("cbc:ChargeIndicator", 'false'),
        xmlelement("cbc:AllowanceChargeReasonCode", '95'),
        xmlelement("cbc:AllowanceChargeReason", 'Discount'),
        xmlelement("cbc:MultiplierFactorNumeric", ih.creditsqueezeperc),
        xmlelement("cbc:Amount", xmlattributes(cu.code as "currencyID"), f_num2char(ih.peppol_amount_correction,cu.invoiceamountdecimals)),
        xmlelement("cbc:BaseAmount", xmlattributes(cu.code as "currencyID"), f_num2char(ih.totalamountexclvat,cu.invoiceamountdecimals)),
        xmlelement("cac:TaxCategory",
            --(mis)used ih.deltocounty for vatrate read percentage and ih.deltostate as vatcode
            xmlelement("cbc:ID", case when (nvl(ih.deltocounty,0) = 0 and ih.deltostate = 'AE') then 'AE' when nvl(ih.deltocounty,0) = 0 then 'Z' else 'S' end),
            xmlelement("cbc:Percent",ih.deltocounty),
            case when (ih.deltostate = 'AE')
              then xmlelement("cbc:TaxExemptionReason", 'Reverse charge')
              else null end,
            xmlelement("cac:TaxScheme", xmlelement("cbc:ID",'VAT'))))
      end,
      xmlelement("cac:TaxTotal",
          xmlelement("cbc:TaxAmount",
           xmlattributes(cu.code as "currencyID"),
             f_num2char(((select sum(il.amount) from invoiceline il
                          join taxgroup tx on tx.code = il.code and tx.country_id = delto.country_id
                          where  il.invoiceheader_id = ih.invoiceheader_id
                          and il.invoicelinetype_id = 18)),cu.invoiceamountdecimals)),
     (select xmlagg( xmlelement("cac:TaxSubtotal",
         xmlelement("cbc:TaxableAmount", xmlattributes(cu.code as "currencyID"),
             f_num2char(iv.overamount,cu.invoiceamountdecimals)),
         xmlelement("cbc:TaxAmount", xmlattributes(cu.code as "currencyID"), f_num2char(il.amount,cu.invoiceamountdecimals)),
         xmlelement("cac:TaxCategory",
            xmlelement("cbc:ID", case when (nvl(tx.taxrate,0) = 0 and tx.code = 'AE') then 'AE' when nvl(tx.taxrate,0) = 0 then 'Z' else 'S' end),
            xmlelement("cbc:Percent",tx.taxrate),
            case when (il.taxtype = 0 and tx.code = 'AE')
              then xmlelement("cbc:TaxExemptionReason", 'Reverse charge')
              else null end,
            xmlelement("cac:TaxScheme", xmlelement("cbc:ID",'VAT')))) order by il.linenumber, il.invoiceline_id)
      from invoiceline il
      join taxgroup tx on tx.code = il.code and tx.country_id = delto.country_id
      join invoicelinevarious iv on iv.invoiceline_id = il.invoiceline_id
      where  il.invoiceheader_id = ih.invoiceheader_id
     and il.invoicelinetype_id = 18)),
       xmlelement("cac:LegalMonetaryTotal",
       xmlelement("cbc:LineExtensionAmount", xmlattributes(cu.code as "currencyID"),
         f_num2char(ih.totalamountexclvat, cu.invoiceamountdecimals)),
       xmlelement("cbc:TaxExclusiveAmount", xmlattributes(cu.code as "currencyID"),
         f_num2char(ih.totalamountexclvat-nvl(ih.peppol_amount_correction,0), cu.invoiceamountdecimals)),
       xmlelement("cbc:TaxInclusiveAmount", xmlattributes(cu.code as "currencyID"),
         f_num2char(ih.paythisamount-nvl(ih.peppol_amount_correction,0), cu.invoiceamountdecimals)),
      case when ih.peppol_amount_correction is null then
       null
      else
       xmlelement("cbc:AllowanceTotalAmount", xmlattributes(cu.code as "currencyID"),
         f_num2char(nvl(ih.peppol_amount_correction,0), cu.invoiceamountdecimals))
      end,
       xmlelement("cbc:PayableAmount", xmlattributes(cu.code as "currencyID"),
         f_num2char(ih.paythisamount-nvl(ih.peppol_amount_correction,0), cu.invoiceamountdecimals))),
       (select xmlagg(
     xmlelement("cac:InvoiceLine",
     case when ihl.parentinvoiceheader_id is not null then
        xmlelement("cbc:ID", (ihl.invoicenumber*1000) + il.linenumber)
     else
        xmlelement("cbc:ID", il.linenumber)
     end,
        xmlelement("cbc:Note", nvl(il.remark,'-')),
        xmlelement("cbc:InvoicedQuantity", xmlattributes(( nvl(ru.peppolcode,
           case when il.invoicelinetype_id in (3,4) then 'KGM'
                else 'EA'end)) as "unitCode"),
           f_num2char(il.billedqty, case when round(il.billedqty) = il.billedqty then 0 else 3 end)),
        xmlelement("cbc:LineExtensionAmount", xmlattributes(cu.code as "currencyID"),
           f_num2char(il.amount,cu.invoiceamountdecimals)),
        xmlelement("cac:OrderLineReference", xmlelement("cbc:LineID", il.linenumber)),
        xmlelement("cac:Item",
          xmlelement("cbc:Name",il.description),
          xmlelement( "cac:ClassifiedTaxCategory",
            xmlelement("cbc:ID", case when (nvl(tx.taxrate,0) = 0 and tx.code = 'AE') then 'AE' when nvl(tx.taxrate,0) = 0 then 'Z' else 'S' end),          -- Standard rated
            xmlelement("cbc:Percent", tx.taxrate),      -- VAT rate
            xmlelement("cac:TaxScheme", xmlelement("cbc:ID", 'VAT')))),
        xmlelement("cac:Price",
          xmlelement("cbc:PriceAmount", xmlattributes(cu.code as "currencyID"),
           f_num2char(il.price, cu.decimals)),
          xmlelement("cbc:BaseQuantity", xmlattributes(( nvl(ru.peppolcode,
           case when il.invoicelinetype_id in (3,4) then 'KGM'
                else 'EA'end)) as "unitCode"),f_num2char(1,0)))
        ) order by ihl.invoicenumber, il.linenumber, il.invoiceline_id)
     from v_peppol_invoiceline_debit il
     join invoiceheader ihl on ihl.invoiceheader_id = il.invoiceheader_id
     left outer join invoicelineproduct ilp on ilp.invoiceline_id = il.invoiceline_id
     left outer join product p join registrationunit ru on ru.registrationunit_id = p.registrationunit_id on p.product_id = ilp.product_link_id
     left outer join invoicelinevarious ilv on ilv.invoiceline_id = il.invoiceline_id
     left outer join taxgroup tx on tx.code = il.taxgroupcode and tx.country_id = billto.country_id
     where il.invoicelinetype_id not in (14, 18)
     and nvl(ihl.parentinvoiceheader_id, ihl.invoiceheader_id) = ih.invoiceheader_id)
        )).getclobval())
        indent size = 3) as tmc_xml
from   invoiceheader ih
join   invoiceheaderextrainfo ihe
on     ihe.invoiceheader_id = ih.invoiceheader_id
left   outer join invoiceheaderediinfo ihde
on     ihde.invoiceheader_id = ih.invoiceheader_id
join   currency cu
on     cu.currency_id = ih.currency_id
join   businessunit bu
on     bu.businessunit_id = ih.invoicebusinessunit_id
join  (legalentity le
join   address ad
on     le.address_id = ad.address_id
join   get_peppol_legalentity(le.legalentity_id) ppl
on     ppl.entity_id = le.legalentity_id) on le.legalentity_id = bu.legalentity_id
left   outer join bankinstitution binst
on     binst.bankinstitution_id = ihe.laundrybankinstitution_id
join   plant pt
on     pt.plant_id = bu.plant_id
join   address adp
on     adp.address_id = pt.address_id
join   customer billto
on     billto.customer_id = ih.billtocustomer_link_id
join   get_peppol_endpoint(billto.customer_id) pp
on     pp.entity_id = billto.customer_id
left   join customergeneral cg
on     cg.customer_id = billto.customer_id
join   customer delto
on     delto.customer_id = ih.deltocustomer_link_id
join   country deltocountry
on     deltocountry.country_id = delto.country_id
left   outer join(customerediinfo cedi
join   contactperson cpedi
on     cpedi.contactperson_id = cedi.edicontactperson_id) on cedi.customer_id = billto.customer_id
left   outer join(customerediinfo cedi2
join   contactperson cpedi2
on     cpedi2.contactperson_id = cedi2.edicontactperson_id) on cedi2.customer_id = ih.deltocustomer_link_id
left   outer join(costcenter cc
left   outer join contactperson cpcc
on     cpcc.contactperson_id = cc.contactperson_id) on (cc.code = ih.splitupcode and cc.customer_id = ih.deltocustomer_link_id and cc.exportedi = 1)
where  ih.documenttype = 1
and    billto.edimethod = 3 --EDI
and    ih.paythisamount > 0
and    ih.status_id = (select st.status_id
                       from   status st
                       where  st.code = '2'
                       and    st.statustype = 'IN')
and    (ih.parentinvoiceheader_id is null or ih.parentinvoiceheader_id = ih.invoiceheader_id)
and    ih.paythisamount > 0
/

  CREATE OR REPLACE VIEW "VR_SALESJOURNALAMOUNT" ("BUSINESSUNIT_ID", "PROCESSBUSINESSUNIT_ID", "ROUTE_ID", "TURNOVERGROUP_ID", "SALESJOURNALGROUP_ID", "ARTRANSACTIONDATE", "CURRENCYCODE", "CASHAMOUNT", "CHARGEAMOUNT") AS 
  select /*version 2.0*/
       ar.businessunit_id, ar.processbusinessunit_id, ar.route_id, tg.turnovergroup_id,
       tg.salesjournalgroup_id, ar.artransactiondate, cr.code currencycode,
       (case when ar.paymenttype = 0 then ardl.amount else 0 end) cashamount,
       (case when ar.paymenttype = 1 then ardl.amount else 0 end) chargeamount
  from turnovergroup tg
       join artransactiondetail ardl
            join artransaction ar
                 join artransactiontype art on ar.artransactiontype_id = art.artransactiontype_id
                 join currency cr on ar.currency_id = cr.currency_id
                 join invoiceheader ih on ar.invoiceheader_id = ih.invoiceheader_id
            on ardl.artransaction_id = ar.artransaction_id
       on tg.turnovergroup_id = ardl.turnovergroup_id
 where art.typenumber in (1,3) --todo 4653
   and art.debitcredit = 'D'
   and ar.debitcredit = 'D'
/

  CREATE OR REPLACE VIEW "VR_UNIQUEITEMFLAG" ("UNIQUEITEM_ID", "UNIQUEITEMFLAGDATE") AS 
  select ui.uniqueitem_id, min(uf.startdate) uniqueitemflagdate
from uniqueitem ui, uniqueitemflag uf, flag f
where ui.uniqueitem_id = uf.uniqueitem_id
  and uf.flag_id = f.flag_id
  and f.includeincompletnesscheck = 'N'
group by ui.uniqueitem_id
/

  CREATE OR REPLACE VIEW "VTEST_1_SOIL" ("WEIGHINGDATE", "CUSTOMER_ID", "DEPARTMENT_ID", "DISTRIBUTIONPOINT_ID", "WEIGHINGCATEGORY_ID", "BU_ID", "NET_TICKET", "NET_HIST") AS 
  select t.weighingdate, t.customer_id, tl.department_id,
	(select dip.distributionpoint_id from distributionpoint dip
		where dip.department_id = tl.department_id and
			dip.distributionpointnumber = (select min(x.distributionpointnumber) from distributionpoint x
							where x.department_id = tl.department_id)),
	tl.weighingcategory_id, t.processbusinessunit_id, tl.grossweight - tl.tareweight, 0
from weighingticket t, weighingticketline tl, status s
where t.weighingticket_id = tl.weighingticket_id and t.soilticket = 'Y' and
      t.status_id = s.status_id and s.code = '30'
union all
select w.weighingdate, w.customer_link_id, w.department_link_id, w.distributionpoint_link_id,
	w.weighingcategory_link_id, w.processbusinessunit_id, 0, w.soilweight
from weighinghistory w
/

  CREATE OR REPLACE VIEW "V_ACTIVESTOCKLOCATION_DET" ("PRODUCT_ID", "SIZEDEFINITION_ID", "UNIQUEITEM_ID", "PRIMARYID", "ACTIVESTOCKLOCATION_ID", "BUSINESSUNIT_ID", "RELATEDCUSTOMER_ID", "SECTION", "LOCATION", "UNIQUEID", "ASL_LINE") AS 
  select /*version 2.0*/
       ui.product_id, ui.sizedefinition_id, ui.uniqueitem_id, ui.primaryid, ui.activestocklocation_id, ui.businessunit_id,
       ui.relatedcustomer_id, asl.section, asl.location, asl.uniqueid,
       ROW_NUMBER() OVER(partition by ui.businessunit_id, ui.relatedcustomer_id, ui.product_id, ui.sizedefinition_id
                         ORDER BY asl.section, asl.location, asl.uniqueid) asl_line
from uniqueitem ui
     left join activestocklocation asl on ui.activestocklocation_id = asl.activestocklocation_id
                                              and ui.businessunit_id = asl.businessunit_id
/

  CREATE OR REPLACE VIEW "V_AGEANALYSIS_ROUTE" ("CUSTOMER_ID", "EXPDATE", "ROUTE_ID", "REPORTPARAM_ID") AS 
  select /*version 2.0*/
       c.customer_id, (select max(cp.dateinactive) from contractspercustomer cp where c.customer_id = cp.customer_id) expdate,
       get_routeandfilter(rp.reportparam_id, c.customer_id) route_id, rp.reportparam_id
  from customer c
 cross join reportparam rp
/

  CREATE OR REPLACE VIEW "V_AVAILABLEBUNDLES_PND" ("TOBEDELIVEREDAMOUNT1", "TOBEDELIVEREDAMOUNT2", "TOBEDELIVEREDAMOUNT3", "TOBEDELIVEREDAMOUNT4", "TOBEDELIVEREDAMOUNT5", "TOBEDELIVEREDAMOUNT6", "TOBEDELIVEREDAMOUNT7", "BUSINESSUNIT_ID", "PLANTDEPARTMENTCODE", "PLANTDEPARTMENTDESC", "ACTIVITYCODE", "ACTIVITYDESC", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTDESC", "PRODUCTGROUPCODE", "PRODUCTGROUPDESC", "SIZECODE", "SIZEDEFINITION_ID", "FINMETHCODE", "FINISHINGMETHOD_ID", "LANGUAGECODE", "REPORTPARAM_ID") AS 
  select
  sum (CASE WHEN pn.daynumber = 1 THEN pnl.tobedeliveredamount else 0 end) tobedeliveredamount1,
  sum (CASE WHEN pn.daynumber = 2 THEN pnl.tobedeliveredamount else 0 end) tobedeliveredamount2,
  sum (CASE WHEN pn.daynumber = 3 THEN pnl.tobedeliveredamount else 0 end) tobedeliveredamount3,
  sum (CASE WHEN pn.daynumber = 4 THEN pnl.tobedeliveredamount else 0 end) tobedeliveredamount4,
  sum (CASE WHEN pn.daynumber = 5 THEN pnl.tobedeliveredamount else 0 end) tobedeliveredamount5,
  sum (CASE WHEN pn.daynumber = 6 THEN pnl.tobedeliveredamount else 0 end) tobedeliveredamount6,
  sum (CASE WHEN pn.daynumber = 7 THEN pnl.tobedeliveredamount else 0 end) tobedeliveredamount7,
  bu.businessunit_id,
  pd.code plantdepartmentcode, pd.description plantdepartmentdesc,
  ac.code activitycode,
  (select acd.description from activity_desc acd where acd.activity_id = ac.activity_id
    and acd.language_id = languages.language_id) activitydesc,
  pr.product_id, pr.code productcode,
  (select prd.description from product_desc prd where prd.product_id = pr.product_id
    and prd.language_id = languages.language_id) productdesc,
  pg.code productgroupcode,
  (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pg.productgroup_id
    and pgd.language_id = languages.language_id) productgroupdesc,
  sz.code sizecode, sz.sizedefinition_id,
  fm.code finmethcode, pnl.finishingmethod_id,
  languages.code languagecode, rp.reportparam_id
from packingnote pn, route ru, depot de,
  packingnoteline pnl, product pr, sizedefinition sz, plantdepartment pd,
  productgroup pg, activity ac, status st, businessunit bu, finishingmethod fm,
  languages, reportparam rp
where pn.packingnote_id = pnl.packingnote_id
  and pnl.product_id = pr.product_id
  and pnl.sizedefinition_id = sz.sizedefinition_id
  and pnl.finishingmethod_id = fm.finishingmethod_id
  and pn.processbusinessunit_id = bu.businessunit_id
  and bu.plant_id = pd.plant_id
  and pn.plantdepartment_id = pd.plantdepartment_id
  and pr.productgroup_id = pg.productgroup_id
  and pg.activity_id = ac.activity_id
  and pn.route_id = ru.route_id and ru.active = 'Y'
  and ru.depot_id = de.depot_id
  and pn.status_id = st.status_id
  and st.code in ('10', '20')
  and ac.active = 'Y'
  and pn.deliverydate between rp.date_value1 and rp.date_value2
  and ru.routenumber between rp.number_value1 and rp.number_value2
  and de.code between rp.string_value1 and rp.string_value2
group by ac.code, ac.activity_id, pr.product_id, pg.productgroup_id, pr.code, pg.code, sz.code,
  pd.code, pd.description, bu.businessunit_id, fm.code, pnl.finishingmethod_id,
  sz.sizedefinition_id, languages.code, languages.language_id, rp.reportparam_id
union all -- without depot
select
  sum (CASE WHEN pn.daynumber = 1 THEN pnl.tobedeliveredamount else 0 end) tobedeliveredamount1,
  sum (CASE WHEN pn.daynumber = 2 THEN pnl.tobedeliveredamount else 0 end) tobedeliveredamount2,
  sum (CASE WHEN pn.daynumber = 3 THEN pnl.tobedeliveredamount else 0 end) tobedeliveredamount3,
  sum (CASE WHEN pn.daynumber = 4 THEN pnl.tobedeliveredamount else 0 end) tobedeliveredamount4,
  sum (CASE WHEN pn.daynumber = 5 THEN pnl.tobedeliveredamount else 0 end) tobedeliveredamount5,
  sum (CASE WHEN pn.daynumber = 6 THEN pnl.tobedeliveredamount else 0 end) tobedeliveredamount6,
  sum (CASE WHEN pn.daynumber = 7 THEN pnl.tobedeliveredamount else 0 end) tobedeliveredamount7,
  bu.businessunit_id,
  pd.code plantdepartmentcode, pd.description plantdepartmentdesc,
  ac.code activitycode,
  (select acd.description from activity_desc acd where acd.activity_id = ac.activity_id
    and acd.language_id = languages.language_id) activitydesc,
  pr.product_id, pr.code productcode,
  (select prd.description from product_desc prd where prd.product_id = pr.product_id
    and prd.language_id = languages.language_id) productdesc,
  pg.code productgroupcode,
  (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pg.productgroup_id
    and pgd.language_id = languages.language_id) productgroupdesc,
  sz.code sizecode, sz.sizedefinition_id,
  fm.code finmethcode, pnl.finishingmethod_id,
  languages.code languagecode, rp.reportparam_id
from packingnote pn, route ru,
  packingnoteline pnl, product pr, sizedefinition sz, plantdepartment pd,
  productgroup pg, activity ac, status st, businessunit bu, finishingmethod fm,
  languages, reportparam rp
where pn.packingnote_id = pnl.packingnote_id
  and pnl.product_id = pr.product_id
  and pnl.sizedefinition_id = sz.sizedefinition_id
  and pnl.finishingmethod_id = fm.finishingmethod_id
  and pn.processbusinessunit_id = bu.businessunit_id
  and bu.plant_id = pd.plant_id
  and pn.plantdepartment_id = pd.plantdepartment_id
  and pr.productgroup_id = pg.productgroup_id
  and pg.activity_id = ac.activity_id
  and pn.route_id = ru.route_id and ru.active = 'Y'
  and ru.depot_id is null
  and pn.status_id = st.status_id
  and st.code in ('10', '20')
  and ac.active = 'Y'
  and pn.deliverydate between rp.date_value1 and rp.date_value2
  and ru.routenumber between rp.number_value1 and rp.number_value2
group by ac.code, ac.activity_id, pr.product_id, pg.productgroup_id, pr.code, pg.code, sz.code,
  pd.code, pd.description, bu.businessunit_id, fm.code, pnl.finishingmethod_id,
  sz.sizedefinition_id, languages.code, languages.language_id, rp.reportparam_id
union all -- without route
select
  sum (CASE WHEN pn.daynumber = 1 THEN pnl.tobedeliveredamount else 0 end) tobedeliveredamount1,
  sum (CASE WHEN pn.daynumber = 2 THEN pnl.tobedeliveredamount else 0 end) tobedeliveredamount2,
  sum (CASE WHEN pn.daynumber = 3 THEN pnl.tobedeliveredamount else 0 end) tobedeliveredamount3,
  sum (CASE WHEN pn.daynumber = 4 THEN pnl.tobedeliveredamount else 0 end) tobedeliveredamount4,
  sum (CASE WHEN pn.daynumber = 5 THEN pnl.tobedeliveredamount else 0 end) tobedeliveredamount5,
  sum (CASE WHEN pn.daynumber = 6 THEN pnl.tobedeliveredamount else 0 end) tobedeliveredamount6,
  sum (CASE WHEN pn.daynumber = 7 THEN pnl.tobedeliveredamount else 0 end) tobedeliveredamount7,
  bu.businessunit_id,
  pd.code plantdepartmentcode, pd.description plantdepartmentdesc,
  ac.code activitycode,
  (select acd.description from activity_desc acd where acd.activity_id = ac.activity_id
    and acd.language_id = languages.language_id) activitydesc,
  pr.product_id, pr.code productcode,
  (select prd.description from product_desc prd where prd.product_id = pr.product_id
    and prd.language_id = languages.language_id) productdesc,
  pg.code productgroupcode,
  (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pg.productgroup_id
    and pgd.language_id = languages.language_id) productgroupdesc,
  sz.code sizecode, sz.sizedefinition_id,
  fm.code finmethcode, pnl.finishingmethod_id,
  languages.code languagecode, rp.reportparam_id
from packingnote pn,
  packingnoteline pnl, product pr, sizedefinition sz, plantdepartment pd,
  productgroup pg, activity ac, status st, businessunit bu, finishingmethod fm,
  languages, reportparam rp
where pn.packingnote_id = pnl.packingnote_id
  and pnl.product_id = pr.product_id
  and pnl.sizedefinition_id = sz.sizedefinition_id
  and pnl.finishingmethod_id = fm.finishingmethod_id
  and pn.processbusinessunit_id = bu.businessunit_id
  and bu.plant_id = pd.plant_id
  and pn.plantdepartment_id = pd.plantdepartment_id
  and pr.productgroup_id = pg.productgroup_id
  and pg.activity_id = ac.activity_id
  and pn.route_id is null
  and pn.status_id = st.status_id
  and st.code in ('10', '20')
  and ac.active = 'Y'
  and pn.deliverydate between rp.date_value1 and rp.date_value2
group by ac.code, ac.activity_id, pr.product_id, pg.productgroup_id, pr.code, pg.code, sz.code,
  pd.code, pd.description, bu.businessunit_id, fm.code, pnl.finishingmethod_id,
  sz.sizedefinition_id, languages.code, languages.language_id, rp.reportparam_id
/

  CREATE OR REPLACE VIEW "V_BATCHCARD_AUX" ("LINETYPE", "BATCH_ID", "CUSTOMER_LINK_ID", "WASHINGPROCESS_ID", "QUANTITY", "CLIENTID", "THEORETICALWEIGHT") AS 
  select y.linetype, y.batch_id, y.customer_link_id, y.washingprocess_id, sum(y.quantity) quantity, y.client_id clientid,
       sum(y.theoreticalweight) theoreticalweight
         from   (select 1 linetype, rsi.batch_id, rsi.customer_link_id, rsi.client_id,
                         coalesce(urp.specificwashingprocess_id, l.washingprocess_id, p.washingprocess_id) washingprocess_id
                         , count(1) quantity
                         , (select ps.theoreticalweight from productsize ps
                         where ps.product_id = rsi.product_link_id
                         and ps.sizedefinition_id = rsi.sizedefinition_link_id) theoreticalweight
                  from   residentialitemscan rsi
                  join   uniqueresidentialitemproduct urp
                  on     urp.uniqueresidentialitem_id = rsi.uniqueresidentialitem_link_id
                  left   outer join productlistpercustomer l
                  on     (l.customer_id = rsi.customer_link_id and l.product_id = rsi.product_link_id and
                         l.sizedefinition_id = rsi.sizedefinition_link_id and
                         l.finishingmethod_id = rsi.finishingmethod_id and
                         rsi.scantimestamp between l.dateactive and l.dateinactive)
                  join   product p
                  on     p.product_id = rsi.product_link_id
                  where rsi.transactiontype_id = 1 --only inscans!
                  group by rsi.batch_id, rsi.customer_link_id, rsi.client_id,
                            coalesce(urp.specificwashingprocess_id, l.washingprocess_id, p.washingprocess_id),
                            rsi.product_link_id, rsi.sizedefinition_link_id
                  union all
                  select 2 linetype, cld.batch_id, cld.customer_link_id, cld.client_link_id clientid,
                         coalesce(l.washingprocess_id, p.washingprocess_id) washingprocess_id,
                         sum(--cldl.qtyscannedin + --already calculated in branch 1 there is no need to be here !!!
                         cldl.qtycountedin) quantity,
                         (select ps.theoreticalweight from productsize ps
                         where ps.product_id = cldl.product_link_id
                         and ps.sizedefinition_id = cldl.sizedefinition_link_id) theoreticalweight
                  from   clientdeliverynote cld
                  join   clientdeliverynoteline cldl
                  on     cldl.clientdeliverinote_id = cld.clientdeliverynote_id
                  left   outer join productlistpercustomer l
                  on     (l.customer_id = cld.customer_link_id and l.product_id = cldl.product_link_id and
                         l.sizedefinition_id = cldl.sizedefinition_link_id and
                         l.finishingmethod_id = cldl.finishingmethod_id and
                         cld.deliverydate between l.dateactive and l.dateinactive)
                  join   product p
                  on     p.product_id = cldl.product_link_id
                  group  by cld.batch_id, cld.customer_link_id, cld.client_link_id,
                            coalesce(l.washingprocess_id, p.washingprocess_id),
                            cldl.product_link_id, cldl.sizedefinition_link_id
                  union all
                  Select 3 linetype, GBS.GarmentBatch_ID batch_id, WR.Customer_ID customer_link_id, null clientid,
                         coalesce(PLPC.WashingProcess_ID, P.WashingProcess_ID) washingprocess_id,
                         Count (GBS.UniqueItem_ID) quantity,
                         (select ps.theoreticalweight from productsize ps
                         where ps.product_id = ui.product_id
                         and ps.sizedefinition_id = ui.sizedefinition_id) theoreticalweight
                  From GarmentBatchScan GBS, UniqueItem UI, UniqueItemNonPool NP, Product P, WearerEmployment WE, Wearer WR, ProductListPerCustomer PLPC
                  Where GBS.ScanType = 0
                        And UI.UniqueItem_ID = GBS.UniqueItem_ID
                        And NP.UniqueItem_ID = GBS.UniqueItem_ID
                        And WE.WearerEmployment_ID = NP.WearerEmployment_ID
                        And WR.Wearer_ID = WE.Wearer_ID
                        And P.Product_ID = UI.Product_Id
                        And PLPC.Customer_ID = WR.Customer_Id
                        And PLPC.Product_ID = UI.Product_ID
                        And ((PLPC.SizeDefinition_ID = UI.SizeDefinition_ID)
                          Or (PLPC.SizeDefinition_ID in (select sizestar.sizedefinition_id from sizedefinition sizestar where sizestar.code ='*')))
                        And PLPC.FinishingMethod_ID = UI.FinishingMethod_ID
                        And PLPC.DateActive <= sysdate
                        And PLPC.DateInactive > sysdate
                  Group by GBS.GarmentBatch_ID, WR.Customer_ID, coalesce(PLPC.WashingProcess_ID, P.WashingProcess_ID),
                  ui.product_id, ui.sizedefinition_id) y
group by y.linetype, y.batch_id, y.customer_link_id, y.washingprocess_id,  y.client_id
/

  CREATE OR REPLACE VIEW "V_CDN_DELAYEDDELIVERY" ("LINETYPE", "CLIENTDELIVERYNOTE_ID", "PACKINGSEQUENCE", "PRODUCTCODE", "SIZECODE", "FINISHINGMETHODCODE", "PRODUCTDESC", "PRIMARYID", "FINISHINGMETHODDESC", "LANGUAGECODE", "PRODCUSTOM_CODE", "PRODCUSTOM_DESC", "WORKSTATION_ID", "WORKSTATION_CODE") AS 
  select  -- ui
  1 linetype, cdn.clientdeliverynote_id, prd.packingsequence, prd.code productCode, sz.code sizeCode, fm.code finishingmethodCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc, uri.primaryid
, ( select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
  and fmd.language_id = languages.language_id ) finishingmethodDesc
, languages.code languageCode
, (SELECT plpc.customcode FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Code
, (SELECT plpc.customdescription FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc
  , ws.workstation_id, ws.code workstation_code
from
  clientdeliverynote cdn, clientdeliverynoteline cdl, clientdelnotelinescan cds, uniqueresidentialitem uri
, product prd, sizedefinition sz, finishingmethod fm, batch b
, languages, workstation ws
where
    cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
and cdl.clientdeliverynoteline_id = cds.inscanclientdelnoteline_id
    and ( cds.outscanclientdelnoteline_id is null or cds.delayed = 'Y' or cds.deliveryexception in (1, 3) or (cds.deliveryexception in (2, 4) and cds.inscanclientdelnoteline_id <> cds.outscanclientdelnoteline_id))
        and cds.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id
and cdl.product_link_id = prd.product_id
and cdl.sizedefinition_link_id = sz.sizedefinition_id
and cdl.finishingmethod_id = fm.finishingmethod_id
and cdn.batch_id = b.batch_id
and b.closingdate is not null -- closed batch
and not exists
(select PDFM.FinishingMethod_ID from PlantDepartmentFinMethod PDFM where PDFM.PlantDepartment_ID = WS.PlantDepartment_ID
)
union all  -- nui
select
  2 linetype, cdn.clientdeliverynote_id, prd.packingsequence, prd.code productCode, sz.code sizeCode, fm.code finishingmethodCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc, '' primaryid
, ( select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
  and fmd.language_id = languages.language_id ) finishingmethodDesc
, languages.code languageCode
, (SELECT plpc.customcode FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Code
, (SELECT plpc.customdescription FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc
, ws.workstation_id, ws.code workstation_code
from
  clientdeliverynote cdn, clientdeliverynoteline cdl, clientdelnotelinedelayed cdd
, product prd, sizedefinition sz, finishingmethod fm, batch b
, languages, workstation ws
where
    cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
and cdl.clientdeliverynoteline_id = cdd.clientdeliverynoteline_id
and cdl.product_link_id = prd.product_id
and cdl.sizedefinition_link_id = sz.sizedefinition_id
and cdl.finishingmethod_id = fm.finishingmethod_id
and cdn.batch_id = b.batch_id
and b.closingdate is not null -- closed batch
and not exists
(select PDFM.FinishingMethod_ID from PlantDepartmentFinMethod PDFM where PDFM.PlantDepartment_ID = WS.PlantDepartment_ID
)
union all
select  -- ui
  3 linetype, cdn.clientdeliverynote_id, prd.packingsequence, prd.code productCode, sz.code sizeCode, fm.code finishingmethodCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc, uri.primaryid
, ( select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
  and fmd.language_id = languages.language_id ) finishingmethodDesc
, languages.code languageCode
, (SELECT plpc.customcode FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Code
, (SELECT plpc.customdescription FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc
, ws.workstation_id, ws.code workstation_code
from
  clientdeliverynote cdn, clientdeliverynoteline cdl, clientdelnotelinescan cds, uniqueresidentialitem uri
, product prd, sizedefinition sz, finishingmethod fm, batch b
, languages, workstation ws
where
    cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
and cdl.clientdeliverynoteline_id = cds.inscanclientdelnoteline_id
    and ( cds.outscanclientdelnoteline_id is null or cds.delayed = 'Y' or cds.deliveryexception in (1, 3) or (cds.deliveryexception in (2, 4) and cds.inscanclientdelnoteline_id <> cds.outscanclientdelnoteline_id))
        and cds.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id
and cdl.product_link_id = prd.product_id
and cdl.sizedefinition_link_id = sz.sizedefinition_id
and cdl.finishingmethod_id = fm.finishingmethod_id
and cdn.batch_id = b.batch_id
and b.closingdate is not null -- closed batch
and fm.finishingmethod_id in
(select PDFM.FinishingMethod_ID from PlantDepartmentFinMethod PDFM where PDFM.PlantDepartment_ID = WS.PlantDepartment_ID
)
union all  -- nui
select
  4 linetype, cdn.clientdeliverynote_id, prd.packingsequence, prd.code productCode, sz.code sizeCode, fm.code finishingmethodCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc, '' primaryid
, ( select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
  and fmd.language_id = languages.language_id ) finishingmethodDesc
, languages.code languageCode
, (SELECT plpc.customcode FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Code
, (SELECT plpc.customdescription FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc
, ws.workstation_id, ws.code workstation_code
from
  clientdeliverynote cdn, clientdeliverynoteline cdl, clientdelnotelinedelayed cdd
, product prd, sizedefinition sz, finishingmethod fm, batch b
, languages, workstation ws
where
    cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
and cdl.clientdeliverynoteline_id = cdd.clientdeliverynoteline_id
and cdl.product_link_id = prd.product_id
and cdl.sizedefinition_link_id = sz.sizedefinition_id
and cdl.finishingmethod_id = fm.finishingmethod_id
and cdn.batch_id = b.batch_id
and b.closingdate is not null -- closed batch
and fm.finishingmethod_id in
(select PDFM.FinishingMethod_ID from PlantDepartmentFinMethod PDFM where PDFM.PlantDepartment_ID = WS.PlantDepartment_ID)
/

  CREATE OR REPLACE VIEW "V_CDN_DELIVEREDAFTER" ("LINETYPE", "CLIENTDELIVERYNOTE_ID", "PACKINGSEQUENCE", "PRODUCTCODE", "SIZECODE", "FINISHINGMETHODCODE", "PRODUCTDESC", "PRIMARYID", "FINISHINGMETHODDESC", "FROMNOTENR", "FROMDELDATE", "LANGUAGECODE", "PRODCUSTOM_CODE", "PRODCUSTOM_DESC", "WORKSTATION_ID", "WORKSTATION_CODE") AS 
  select  -- ui
  1 linetype, cdn.clientdeliverynote_id, prd.packingsequence, prd.code productCode, sz.code sizeCode, fm.code finishingmethodCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc, uri.primaryid
, ( select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
  and fmd.language_id = languages.language_id ) finishingmethodDesc
, cdn_From.Clientdeliverynotenumber fromNoteNr, cdn_From.Deliverydate fromDelDate
, languages.code languageCode
, (SELECT plpc.customcode FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Code
, (SELECT plpc.customdescription FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc
, ws.workstation_id, ws.code workstation_code
from
  clientdeliverynote cdn, clientdeliverynoteline cdl, clientdelnotelinescan cds, uniqueresidentialitem uri
, product prd, sizedefinition sz, finishingmethod fm
, clientdeliverynoteline cdl_From, clientdeliverynote cdn_From
, languages, workstation ws
where
    cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
and cdl.clientdeliverynoteline_id = cds.outscanclientdelnoteline_id
    and cds.inscanclientdelnoteline_id <> cds.outscanclientdelnoteline_id
        and (cds.delayed = 'Y' or cds.deliveryexception in (2, 4))
            and cds.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id
and cdl.product_link_id = prd.product_id
and cdl.sizedefinition_link_id = sz.sizedefinition_id
and cdl.finishingmethod_id = fm.finishingmethod_id
and cds.inscanclientdelnoteline_id = cdl_From.Clientdeliverynoteline_Id
    and cdl_From.Clientdeliverinote_Id = cdn_From.Clientdeliverynote_Id
and not exists
(select PDFM.FinishingMethod_ID from PlantDepartmentFinMethod PDFM where PDFM.PlantDepartment_ID = WS.PlantDepartment_ID
)
union all  -- n_ui
select
  2 linetype, cdn.clientdeliverynote_id, prd.packingsequence, prd.code productCode, sz.code sizeCode, fm.code finishingmethodCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc, '' primaryid
, ( select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
  and fmd.language_id = languages.language_id ) finishingmethodDesc
, cdn_From.Clientdeliverynotenumber fromNoteNr, cdn_From.Deliverydate fromDelDate
, languages.code languageCode
, (SELECT plpc.customcode FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Code
, (SELECT plpc.customdescription FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc
, ws.workstation_id, ws.code workstation_code
from
  clientdeliverynote cdn, clientdeliverynoteline cdl, clientdelnotelinedelayed cdd
, product prd, sizedefinition sz, finishingmethod fm, clientdeliverynoteline cdl_From, clientdeliverynote cdn_From
, languages, workstation ws
where
    cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
and cdl.clientdeliverynoteline_id = cdd.deliverdline_id
and cdl.product_link_id = prd.product_id
and cdl.sizedefinition_link_id = sz.sizedefinition_id
and cdl.finishingmethod_id = fm.finishingmethod_id
and cdd.clientdeliverynoteline_id = cdl_From.Clientdeliverynoteline_Id
    and cdl_From.Clientdeliverinote_Id = cdn_From.Clientdeliverynote_Id
and not exists
(select PDFM.FinishingMethod_ID from PlantDepartmentFinMethod PDFM where PDFM.PlantDepartment_ID = WS.PlantDepartment_ID
)
union all
select  -- ui
  3 linetype, cdn.clientdeliverynote_id, prd.packingsequence, prd.code productCode, sz.code sizeCode, fm.code finishingmethodCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc, uri.primaryid
, ( select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
  and fmd.language_id = languages.language_id ) finishingmethodDesc
, cdn_From.Clientdeliverynotenumber fromNoteNr, cdn_From.Deliverydate fromDelDate
, languages.code languageCode
, (SELECT plpc.customcode FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Code
, (SELECT plpc.customdescription FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc
, ws.workstation_id, ws.code workstation_code
from
  clientdeliverynote cdn, clientdeliverynoteline cdl, clientdelnotelinescan cds, uniqueresidentialitem uri
, product prd, sizedefinition sz, finishingmethod fm
, clientdeliverynoteline cdl_From, clientdeliverynote cdn_From
, languages, workstation ws
where
    cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
and cdl.clientdeliverynoteline_id = cds.outscanclientdelnoteline_id
    and cds.inscanclientdelnoteline_id <> cds.outscanclientdelnoteline_id
        and (cds.delayed = 'Y' or cds.deliveryexception in (2, 4))
            and cds.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id
and cdl.product_link_id = prd.product_id
and cdl.sizedefinition_link_id = sz.sizedefinition_id
and cdl.finishingmethod_id = fm.finishingmethod_id
and cds.inscanclientdelnoteline_id = cdl_From.Clientdeliverynoteline_Id
    and cdl_From.Clientdeliverinote_Id = cdn_From.Clientdeliverynote_Id
and fm.finishingmethod_id in
(select PDFM.FinishingMethod_ID from PlantDepartmentFinMethod PDFM where PDFM.PlantDepartment_ID = WS.PlantDepartment_ID
)
union all  -- n_ui
select
  4 linetype, cdn.clientdeliverynote_id, prd.packingsequence, prd.code productCode, sz.code sizeCode, fm.code finishingmethodCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc, '' primaryid
, ( select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
  and fmd.language_id = languages.language_id ) finishingmethodDesc
, cdn_From.Clientdeliverynotenumber fromNoteNr, cdn_From.Deliverydate fromDelDate
, languages.code languageCode
, (SELECT plpc.customcode FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Code
, (SELECT plpc.customdescription FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc
, ws.workstation_id, ws.code workstation_code
from
  clientdeliverynote cdn, clientdeliverynoteline cdl, clientdelnotelinedelayed cdd
, product prd, sizedefinition sz, finishingmethod fm, clientdeliverynoteline cdl_From, clientdeliverynote cdn_From
, languages, workstation ws
where
    cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
and cdl.clientdeliverynoteline_id = cdd.deliverdline_id
and cdl.product_link_id = prd.product_id
and cdl.sizedefinition_link_id = sz.sizedefinition_id
and cdl.finishingmethod_id = fm.finishingmethod_id
and cdd.clientdeliverynoteline_id = cdl_From.Clientdeliverynoteline_Id
    and cdl_From.Clientdeliverinote_Id = cdn_From.Clientdeliverynote_Id
and fm.finishingmethod_id in
(select PDFM.FinishingMethod_ID from PlantDepartmentFinMethod PDFM where PDFM.PlantDepartment_ID = WS.PlantDepartment_ID
)
/

  CREATE OR REPLACE VIEW "V_CDN_RECEIVEFROMOWNER" ("LINETYPE", "CLIENTDELIVERYNOTE_ID", "PACKINGSEQUENCE", "PRODUCTCODE", "SIZECODE", "FINISHINGMETHODCODE", "PRODUCTDESC", "PRIMARYID", "OWNERNUMBER", "OWNERNAME", "ROOMNUMBER", "NOTENUMBER", "LANGUAGECODE", "PRODCUSTOM_CODE", "PRODCUSTOM_DESC", "WORKSTATION_ID", "WORKSTATION_CODE") AS 
  select
  1 linetype, cdn.clientdeliverynote_id, prd.packingsequence, prd.code productCode, sz.code sizeCode, fm.code finishingmethodCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, uri.primaryid, client.clientnumber ownerNumber, client.name ownerName, dr.roomnumber
--, cdn.clientdeliverynotenumber noteNumber
, cdn_note.clientdeliverynotenumber noteNumber
, languages.code languageCode
, (SELECT plpc.customcode FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Code
, (SELECT plpc.customdescription FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc
, ws.workstation_id, ws.code workstation_code
from
  clientdeliverynote cdn, clientdeliverynoteline cdl
, clientdelnotelinescan cds, clientdeliverynoteline cdl_note, clientdeliverynote cdn_note
, uniqueresidentialitem uri
, client, clientresident cr, departmentroom dr
, product prd, sizedefinition sz, finishingmethod fm
, languages, workstation ws
WHERE cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
and (cdl.clientdeliverynoteline_id = cds.outscanclientdelnoteline_id and cds.deliveryexception not in (1, 3))
    and cds.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id
and cdl.product_link_id = prd.product_id
and cdl.sizedefinition_link_id = sz.sizedefinition_id
and cdl.finishingmethod_id = fm.finishingmethod_id
and cds.inscanclientdelnoteline_id = cdl_note.clientdeliverynoteline_id
    and cdl_note.clientdeliverinote_id = cdn_note.clientdeliverynote_id
        and cdn_note.client_link_id <> cdn.client_link_id
            and cdn.client_link_id = client.client_id
                and client.client_id = cr.client_id
                    and cr.departmentroom_id = dr.departmentroom_id
and not exists
(select PDFM.FinishingMethod_ID from PlantDepartmentFinMethod PDFM where PDFM.PlantDepartment_ID = WS.PlantDepartment_ID
)
union all
select
  2 linetype, cdn.clientdeliverynote_id, prd.packingsequence, prd.code productCode, sz.code sizeCode, fm.code finishingmethodCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, uri.primaryid, client.clientnumber ownerNumber, client.name ownerName, dr.roomnumber
--, cdn.clientdeliverynotenumber noteNumber
, cdn_note.clientdeliverynotenumber noteNumber
, languages.code languageCode
, (SELECT plpc.customcode FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Code
, (SELECT plpc.customdescription FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc
, ws.workstation_id, ws.code workstation_code
from
  clientdeliverynote cdn, clientdeliverynoteline cdl
, clientdelnotelinescan cds, clientdeliverynoteline cdl_note, clientdeliverynote cdn_note
, uniqueresidentialitem uri
, client, clientresident cr, departmentroom dr
, product prd, sizedefinition sz, finishingmethod fm
, languages, workstation ws
WHERE cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
and cdl.clientdeliverynoteline_id = cds.outscanclientdelnoteline_id
    and cds.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id
and cdl.product_link_id = prd.product_id
and cdl.sizedefinition_link_id = sz.sizedefinition_id
and cdl.finishingmethod_id = fm.finishingmethod_id
and cds.inscanclientdelnoteline_id = cdl_note.clientdeliverynoteline_id
    and cdl_note.clientdeliverinote_id = cdn_note.clientdeliverynote_id
        and cdn_note.client_link_id <> cdn.client_link_id
            and cdn.client_link_id = client.client_id
                and client.client_id = cr.client_id
                    and cr.departmentroom_id = dr.departmentroom_id
and fm.finishingmethod_id in
(select PDFM.FinishingMethod_ID from PlantDepartmentFinMethod PDFM where PDFM.PlantDepartment_ID = WS.PlantDepartment_ID
)
/

  CREATE OR REPLACE VIEW "V_CDN_SENDTOOWNER" ("LINETYPE", "CLIENTDELIVERYNOTE_ID", "PACKINGSEQUENCE", "PRODUCTCODE", "SIZECODE", "FINISHINGMETHODCODE", "PRODUCTDESC", "PRIMARYID", "OWNERNUMBER", "OWNERNAME", "ROOMNUMBER", "NOTENUMBER", "LANGUAGECODE", "PRODCUSTOM_CODE", "PRODCUSTOM_DESC", "WORKSTATION_ID", "WORKSTATION_CODE") AS 
  select
  1 linetype, cdn.clientdeliverynote_id, prd.packingsequence, prd.code productCode, sz.code sizeCode, fm.code finishingmethodCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, uri.primaryid, client.clientnumber ownerNumber, client.name ownerName, dr.roomnumber
, cdn_note.clientdeliverynotenumber noteNumber
, languages.code languageCode
, (SELECT plpc.customcode FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Code
, (SELECT plpc.customdescription FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc
, ws.workstation_id, ws.code workstation_code
from
  clientdeliverynote cdn, clientdeliverynoteline cdl
, clientdelnotelinescan cds
    left outer join
      ( clientdeliverynoteline cdl_note join clientdeliverynote cdn_note on cdl_note.clientdeliverinote_id = cdn_note.clientdeliverynote_id
         ) on (cds.outscanclientdelnoteline_id = cdl_note.clientdeliverynoteline_id and cds.deliveryexception not in (1, 3))
, uniqueresidentialitem uri, client, clientresident cr, departmentroom dr
, product prd, sizedefinition sz, finishingmethod fm
, languages, workstation ws
WHERE  cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
and cdl.clientdeliverynoteline_id = cds.inscanclientdelnoteline_id
    and cds.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id
        and uri.client_id = client.client_id
            and client.client_id = cr.client_id
                and cr.departmentroom_id = dr.departmentroom_id
and cdl.product_link_id = prd.product_id
and cdl.sizedefinition_link_id = sz.sizedefinition_id
and cdl.finishingmethod_id = fm.finishingmethod_id
and uri.client_id <> cdn.client_link_id
and not exists
(select PDFM.FinishingMethod_ID from PlantDepartmentFinMethod PDFM where PDFM.PlantDepartment_ID = WS.PlantDepartment_ID
)
union all
select
  2 linetype, cdn.clientdeliverynote_id, prd.packingsequence, prd.code productCode, sz.code sizeCode, fm.code finishingmethodCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, uri.primaryid, client.clientnumber ownerNumber, client.name ownerName, dr.roomnumber
, cdn_note.clientdeliverynotenumber noteNumber
, languages.code languageCode
, (SELECT plpc.customcode FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Code
, (SELECT plpc.customdescription FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc
, ws.workstation_id, ws.code workstation_code
from
  clientdeliverynote cdn, clientdeliverynoteline cdl
, clientdelnotelinescan cds
    left outer join
      ( clientdeliverynoteline cdl_note join clientdeliverynote cdn_note on cdl_note.clientdeliverinote_id = cdn_note.clientdeliverynote_id
         ) on (cds.outscanclientdelnoteline_id = cdl_note.clientdeliverynoteline_id and cds.deliveryexception not in (1, 3))
, uniqueresidentialitem uri, client, clientresident cr, departmentroom dr
, product prd, sizedefinition sz, finishingmethod fm
, languages, workstation ws
WHERE  cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
and cdl.clientdeliverynoteline_id = cds.inscanclientdelnoteline_id
    and cds.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id
        and uri.client_id = client.client_id
            and client.client_id = cr.client_id
                and cr.departmentroom_id = dr.departmentroom_id
and cdl.product_link_id = prd.product_id
and cdl.sizedefinition_link_id = sz.sizedefinition_id
and cdl.finishingmethod_id = fm.finishingmethod_id
and uri.client_id <> cdn.client_link_id
and fm.finishingmethod_id in
(select PDFM.FinishingMethod_ID from PlantDepartmentFinMethod PDFM where PDFM.PlantDepartment_ID = WS.PlantDepartment_ID
)
/

  CREATE OR REPLACE VIEW "V_CIRCULATIONSPEED_DELIV" ("REPORTPARAM_ID", "CUSTOMER_ID", "PRODUCTLISTPERDISTRIBPOINT_ID", "YEAR", "WEEK", "AMOUNTDELIVERED") AS 
  select rp.reportparam_id, dh.customer_link_id customer_id, p.productlistperdistribpoint_id, dh.year, dh.week
       , sum(dh.amountdelivered) amountdelivered
from reportparam rp, productlistperdistribpoint p, deliveryhistory dh
where  dh.product_link_id = p.product_id and
       dh.sizedefinition_link_id = p.sizedefinition_id and
       dh.finishingmethod_id = p.finishingmethod_id and
       dh.deliverydate between rp.date_value1 and rp.date_value2
group by rp.reportparam_id, dh.customer_link_id, p.productlistperdistribpoint_id, dh.year, dh.week
/

  CREATE OR REPLACE VIEW "V_CLIENTDEPARTMENT" ("CUSTOMER_ID", "CLIENT_ID", "CLIENTNUMBER", "CLIENT_SEARCHNAME", "CLIENT_NAME", "PUBLICSERVICENUMBER", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEP_DESC", "ROOMNUMBER") AS 
  select /*view v_clientdepartment version 0.2*/
  cli.customer_id, cli.client_id, cli.clientnumber
, cli.searchname Client_searchname, cli.name Client_name
, cli.publicservicenumber
, coalesce(d.department_id,d1.department_id) department_id
, coalesce(d.departmentnumber,d1.departmentnumber) departmentnumber
, coalesce(d.description, d1.description) Dep_desc
, coalesce(dr.roomnumber, '-') roomnumber
from client cli left outer join clientresident cr
                     join departmentroom dr
                       join department d on dr.department_id = d.department_id
                     on dr.departmentroom_id = cr.departmentroom_id
                on cli.client_id = cr.client_id
                left outer join clientprivateperson cpp
                        join distributionpoint dp
                            join department d1 on d1.department_id = dp.department_id
                        on cpp.distributionpoint_id = dp.distributionpoint_id
                on cpp.client_id = cli.client_id
/

  CREATE OR REPLACE VIEW "V_COMPLETENESSOVERVIEWOUT" ("STOP_ID", "PLANTCODE", "PLANTNAME", "ROUTE_ID", "ROUTENUMBER", "ROUTEDESCRIPTION", "DAYCODE", "DAYDESC", "RCDATE", "STOPNUMBER", "DEPOTCODE", "DEPOTDESCRIPTION", "CUSTOMERNUMBER", "CUSTNAME", "DELIVERYPOINT_ID", "DELPSTOPCODE", "DELPSTOPDESCR", "DELPCUSTCODE", "DELPCUSTDESCR", "CUSTADDRESS", "DELPSTOPADDRESS", "PRODCLEANCODE", "PRODCLEANDESCR", "QTYIN", "QTYOUT", "LANGUAGECODE") AS 
  SELECT -- clean count
s.stop_id,p.code plantcode, p.name plantname, r.route_id, r.routenumber, r.description routedescription,
(select dd.code from day_desc dd where dd.day_id=d.day_id and dd.language_id=lan.language_id ) Daycode,
(select dd.description from day_desc dd where dd.day_id=d.day_id and dd.language_id=lan.language_id ) Daydesc,
to_char(rc.drivingdate,'DD.MM.YYYY') RCDate,
s.stopnumber,
(select dpd.code from depot dpd where dpd.depot_id=r.depot_id) depotcode,
(select dpd.description from depot dpd where dpd.depot_id=r.depot_id) depotdescription,
c.customernumber, c.name custname,
delpstop.deliverypoint_id, delpstop.code delpstopcode, delpstop.description delpstopdescr,
delpcust.code delpcustcode, delpcust.description delpcustdescr,
(select (a.street||', '||a.city ||', ' ||a.zipcode) from address a where a.address_id=c.visitaddress_id) custaddress,
(select (a.street||', '||a.city ||', ' ||a.zipcode) from address a where a.address_id=delpstop.deliveryaddress_id) delpstopaddress,
pclean.code prodcleancode,
(select pdesc.description from product_desc pdesc where pdesc.product_id=pclean.product_id and pdesc.language_id=lan.language_id) prodcleandescr,
0 qtyIN,
sum(coalesce(cc.quantity+cc.quantitycog,0)) qtyOUT,
lan.code languagecode
from stop s
     left outer join deliverypoint delpstop on s.deliverypoint_id = delpstop.deliverypoint_id
     left outer join routestop rs on s.routestop_id = rs.routestop_id
, routecontrol rc
, route r
, day  d
, plant p
, customer c
, deliverypoint delpcust
, distributionpoint dp join (cleancountdelivery cc join product pclean
                                                               on cc.product_id=pclean.product_id)
                                   on (cc.distributionpoint_id = dp.distributionpoint_id and
                                   ( cc.packingnote_id is null
                                   or (cc.packingnote_id is not null and (( select s.code from packingnote pn, status s
                                            where pn.packingnote_id=cc.packingnote_id and pn.status_id=s.status_id and s.statustype='PN') ='20'))))
, languages lan
where s.routecontrol_id = rc.routecontrol_id
and rc.route_id = r.route_id
and r.drivingday_id = d.day_id
and r.plant_id = p.plant_id
and s.customer_link_id = c.customer_id
and delpcust.customer_id = c.customer_id
and dp.deliverypoint_id = delpcust.deliverypoint_id
and (delpstop.deliverypoint_id is null or delpstop.deliverypoint_id = delpcust.deliverypoint_id)
and  cc.deliverydate <= rc.drivingdate
and s.status in (0,3)
and not exists (select 1 FROM STOP s2 left outer join routestop rs2 on s2.routestop_id = rs2.routestop_id
         where s2.routecontrol_id = s.ROUTECONTROL_ID
         and s2.status IN (0,3)
         and s2.customer_link_id = s.Customer_Link_Id
         and ( (s.DELIVERYPOINT_ID is null and s2.DELIVERYPOINT_ID is null)
               or (s.DELIVERYPOINT_ID = s2.deliverypoint_id))
         and s2.stop_id < s.stop_id)
and ((nvl(s.DELIVERYPOINT_ID, 0) = 0
                and not exists (SELECT 1 FROM STOP s2, routestop rs2
                       WHERE s2.routecontrol_id = s.ROUTECONTROL_ID
                            and s2.status IN (0,3)
                            and s2.customer_link_id = s.Customer_Link_Id
                            and s2.routestop_id = rs2.routestop_id
                            and s2.deliverypoint_id = dp.DELIVERYPOINT_ID))
       or (dp.DELIVERYPOINT_ID = s.DELIVERYPOINT_ID))
group by s.stop_id, p.code, p.name, r.route_id,rc.drivingdate, r.routenumber, r.description,pclean.code ,d.day_id,lan.language_id,
s.stopnumber,r.depot_id, c.customernumber, c.name,delpstop.deliverypoint_id,delpstop.code,delpstop.description,delpcust.code,delpcust.description
,c.visitaddress_id,delpstop.deliveryaddress_id,pclean.product_id,lan.code
/

  CREATE OR REPLACE VIEW "V_COMPLETENESSOVERVIEW_AUX" ("DELIVERYDATE", "STOP_ID", "PLANTCODE", "PLANTNAME", "ROUTE_ID", "ROUTENUMBER", "ROUTEDESCRIPTION", "DAYCODE", "DAYDESC", "RCDATE", "DAY_OF_MONTH", "ROUTEMONTH", "ROUTEYEAR", "STOPNUMBER", "DEPOTCODE", "DEPOTDESCRIPTION", "CUSTOMERNUMBER", "CUSTNAME", "DELIVERYPOINT_ID", "DELPSTOPCODE", "DELPSTOPDESCR", "DELPCUSTCODE", "DELPCUSTDESCR", "CUSTADDRESS", "DELPSTOPADDRESS", "PRODCODE", "PRODDESCR", "QTYIN_VAL0", "QTYIN_VAL2", "QTYOUT", "INTERNALPLANTCODE", "INTERNALPLANTNAME", "LANGUAGECODE") AS 
  SELECT --soil count dv + delivery note dv
dv.deliverydate deliverydate,s.stop_id,
p.code plantcode, p.name plantname, r.route_id, r.routenumber, r.description routedescription,
(select dd.code from day_desc dd where dd.day_id=d.day_id and dd.language_id=lan.language_id ) Daycode,
(select dd.description from day_desc dd where dd.day_id=d.day_id and dd.language_id=lan.language_id ) Daydesc,
to_char(rc.drivingdate,'DD.MM.YYYY') RCDate,
to_number(to_char(rc.drivingdate,'DD'))  Day_of_month,to_number(to_char(rc.drivingdate,'MM')) RouteMonth,to_number(to_char(rc.drivingdate,'YYYY'))Routeyear,
s.stopnumber,
(select dpd.code from depot dpd where dpd.depot_id=r.depot_id) depotcode,
(select dpd.description from depot dpd where dpd.depot_id=r.depot_id) depotdescription,
c.customernumber, c.name custname,
delpstop.deliverypoint_id, delpstop.code delpstopcode, delpstop.description delpstopdescr,
delpcust.code delpcustcode, delpcust.description delpcustdescr,
(select (a.street||', '||a.city ||', ' ||a.zipcode) from address a where a.address_id=c.visitaddress_id) custaddress,
(select (a.street||', '||a.city ||', ' ||a.zipcode) from address a where a.address_id=delpstop.deliveryaddress_id) delpstopaddress,
psoil.code prodcode,
(select pdesc.description from product_desc pdesc where pdesc.product_id=psoil.product_id and pdesc.language_id=lan.language_id) proddescr,
coalesce(dv.amount,0) qtyIN_val0,
(case when dv.soilcountsubtype = 7 then coalesce(dv.amount,0) else 0 end) qtyIN_val2,
0 qtyOUT,
(select plint.code from plant plint, plantdepartment pldepint where dv.plantdepartment_id=pldepint.plantdepartment_id and pldepint.plant_id=plint.plant_id) internalplantcode,
(select plint.name from plant plint, plantdepartment pldepint where dv.plantdepartment_id=pldepint.plantdepartment_id and pldepint.plant_id=plint.plant_id) internalplantname,
lan.code languagecode
from stop s
     left outer join deliverypoint delpstop on s.deliverypoint_id = delpstop.deliverypoint_id
     left outer join routestop rs on s.routestop_id = rs.routestop_id
, routecontrol rc, route r, day  d, plant p, customer c, deliverypoint delpcust
, distributionpoint dp join (deliveryvariations dv join product psoil
                                                              on dv.product_id=psoil.product_id)
                                   on (dv.distributionpoint_id = dp.distributionpoint_id  and dv.origin in(1,5)  and (( dv.packingnote_id is null and dv.processed = 'N') or
                                   (dv.packingnote_id is not null and (( select s.code from packingnote pn, status s
                                            where pn.packingnote_id=dv.packingnote_id and pn.status_id=s.status_id and s.statustype='PN') ='20'))))
, languages lan
where s.routecontrol_id = rc.routecontrol_id
and rc.route_id = r.route_id
and r.drivingday_id = d.day_id
and r.plant_id = p.plant_id
and s.customer_link_id = c.customer_id
and delpcust.customer_id = c.customer_id
and dp.deliverypoint_id = delpcust.deliverypoint_id
and (dv.deliverydate is null or dv.deliverydate <= rc.drivingdate)
and (delpstop.deliverypoint_id is null or delpstop.deliverypoint_id = delpcust.deliverypoint_id)
and s.status in (0,3)
and (select count(1) FROM STOP s2 left outer join routestop rs2 on s2.routestop_id = rs2.routestop_id
         where s2.routecontrol_id = s.ROUTECONTROL_ID
         and s2.status IN (0,3)
         and s2.customer_link_id = s.Customer_Link_Id
         and ( (s.DELIVERYPOINT_ID is null and s2.DELIVERYPOINT_ID is null)
               or (s.DELIVERYPOINT_ID = s2.deliverypoint_id))
         and s2.stop_id < s.stop_id) = 0
and ((nvl(s.DELIVERYPOINT_ID, 0) = 0
                and (SELECT count(1) FROM STOP s2, routestop rs2
                       WHERE s2.routecontrol_id = s.ROUTECONTROL_ID
                            and s2.status IN (0,3)
                            and s2.customer_link_id = s.Customer_Link_Id
                            and s2.routestop_id = rs2.routestop_id
                            and s2.deliverypoint_id = dp.DELIVERYPOINT_ID)=0)
       or (dp.DELIVERYPOINT_ID = s.DELIVERYPOINT_ID))
/

  CREATE OR REPLACE VIEW "V_CONTACTPERCATEGORY_AUX" ("CUSTOMER_ID", "PLANT_ID", "BUSINESSUNIT_ID") AS 
  select cu.customer_id, bu.plant_id, bu.businessunit_id
from customer cu, customeractivities ca, businessunit bu
where
    cu.customer_id = ca.customer_id
and ( ca.invoicebusinessunit_id = bu.businessunit_id
        or ca.processbusinessunit_id = bu.businessunit_id )
union
select cu.customer_id, bu.plant_id, bu.businessunit_id
from customer cu , businessunit bu
where
    cu.defaultbusinessunit_id = bu.businessunit_id
/

  CREATE OR REPLACE VIEW "V_CONTRACTEXPIRATION_RC" ("CUSTOMERNUMBER", "NAME", "DEFAULTBUSINESSUNIT_ID", "MAILADDRESS_ID", "PHONENO", "ACTIVE", "ROUTENUMBER", "ROUTEDESC", "DRIVINGDAY_ID", "ROUTE_ID", "CUSTOMER_ID") AS 
  select distinct cu.customernumber, cu.name,
  cu.defaultbusinessunit_id, cu.mailaddress_id, cu.phoneno, cu.active,
  r.routenumber, r.description routedesc, r.drivingday_id,
  r.route_id, cu.customer_id
from route r, routestop rs, customer cu
where r.route_id = rs.route_id
  and rs.customer_id = cu.customer_id
  and (rs.dateinactive>=sysdate and rs.dateactive<=sysdate)
/

  CREATE OR REPLACE VIEW "V_CONTRACTPRICEUPDATE_BUDGETPROT" ("AGREED", "CONTRACTCODE", "CONTRACTDESC", "STARTDATE", "ENDDATE", "NEXTSCHEDULEPRICEINCREASE", "PRODUCTCODE", "TYPEOFMERCHANDISE", "SIZECODE", "FINISHCODE", "SIZE_SEQUENCE", "PRODUCTDESC", "SIZEDESC", "FINISHDESC", "PRICEINDEXCODE", "PRICEINDEXDESC", "PRICEINDEXSTART", "PIHPERCENT", "CURRENCYCODE", "CURRENCYDESC", "DECIMALS", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE", "GPLCODE", "GPLDESC", "PRICE", "VOLUMEPRICE", "SOIL") AS 
  select 'Y' agreed, con.code contractcode, con.description contractdesc, con.startdate, con.enddate, con.nextschedulepriceincrease,
       pr.code productcode, pr.typeofmerchandise, sd.code sizecode, null finishcode,
       (select psz.sequencenumber
          from productsize psz
         where psz.product_id = pr.product_id
           and psz.sizedefinition_id = sd.sizedefinition_id) size_sequence,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdesc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc,
       null finishdesc,
       pia.code priceindexcode, pia.description priceindexdesc, pih.startdate priceindexstart, pih.percinsurance pihpercent,
       cry.code currencycode, cry.description currencydesc, cry.decimals, cry.invoiceamountdecimals, lan.code languagecode,
       gpl.code gplcode, gpl.description gpldesc, gbpp.price, 0 volumeprice, null soil
  from contract con
       join priceindex pia on con.agreedpriceindex_id = pia.priceindex_id
       join priceindexhistory pih on con.agreedpriceindex_id = pih.priceindex_id
       join status st on con.status_id = st.status_id and st.statustype = 'CO' and st.code = '20'
       join contractpricelist cpl
            join generalpricelist gpl
                 join generalbgprotectionprice gbpp
                      join product pr on gbpp.product_id = pr.product_id
                      join sizedefinition sd on gbpp.sizedefinition_id = sd.sizedefinition_id
                 on gpl.generalpricelist_id = gbpp.generalpricelist_id
                 join currency cry on gpl.currency_id = cry.currency_id
            on cpl.generalpricelist_id = gpl.generalpricelist_id and gpl.pricetype = 9 and gpl.usage = 1 and gpl.active = 'Y'
       on con.contract_id = cpl.contract_id and cpl.agreed = 'Y' and cpl.pricetype = 9
       , languages lan
 where (con.terminationdate = getabsmaxdate()
       or
       (con.terminationdate < getabsmaxdate() and con.enddate > con.nextschedulepriceincrease and con.updateevery <> 0)
       )
   and pih.startdate = (select max(pih2.startdate)
                          from priceindexhistory pih2
                         where con.agreedpriceindex_id = pih2.priceindex_id
                           and con.nextschedulepriceincrease >= pih2.startdate)
   and cpl.startdate <= con.nextschedulepriceincrease
   and cpl.enddate > con.nextschedulepriceincrease
   and gbpp.startdate = (select max(gbpp2.startdate)
	                         from generalbgprotectionprice gbpp2
                          where gbpp2.generalpricelist_id = gbpp.generalpricelist_id
                            and gbpp2.product_id = gbpp.product_id
                            and gbpp2.sizedefinition_id = gbpp.sizedefinition_id
                            and gbpp2.startdate <= con.nextschedulepriceincrease)
 union all
select 'N' agreed, con.code contractcode, con.description contractdesc, con.startdate, con.enddate, con.nextschedulepriceincrease,
       pr.code productcode, pr.typeofmerchandise, sd.code sizecode, null finishcode,
       (select psz.sequencenumber
          from productsize psz
         where psz.product_id = pr.product_id
           and psz.sizedefinition_id = sd.sizedefinition_id) size_sequence,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdesc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc,
       null finishdesc,
       pina.code priceindexcode, pina.description priceindexdesc, pinh.startdate priceindexstart, pinh.percinsurance pihpercent,
       cry.code currencycode, cry.description currencydesc, cry.decimals, cry.invoiceamountdecimals, lan.code languagecode,
       gpl.code gplcode, gpl.description gpldesc, gbpp.price, 0 volumeprice, null soil
  from contract con
       join priceindex pina on con.notagreedpriceindex_id = pina.priceindex_id
       join priceindexhistory pinh on con.notagreedpriceindex_id = pinh.priceindex_id
       join status st on con.status_id = st.status_id and st.statustype = 'CO' and st.code = '20'
       join contractpricelist cpl
            join generalpricelist gpl
                 join generalbgprotectionprice gbpp
                      join product pr on gbpp.product_id = pr.product_id
                      join sizedefinition sd on gbpp.sizedefinition_id = sd.sizedefinition_id
                 on gpl.generalpricelist_id = gbpp.generalpricelist_id
                 join currency cry on gpl.currency_id = cry.currency_id
            on cpl.generalpricelist_id = gpl.generalpricelist_id and gpl.pricetype = 9 and gpl.usage = 1 and gpl.active = 'Y'
       on con.contract_id = cpl.contract_id and cpl.agreed = 'N' and cpl.pricetype = 9
       , languages lan
 where (con.terminationdate = getabsmaxdate()
       or
       (con.terminationdate < getabsmaxdate() and con.enddate > con.nextschedulepriceincrease and con.updateevery <> 0)
       )
   and con.allownotagreedpricelists = 'Y'
   and pinh.startdate = (select max(pinh2.startdate)
                           from priceindexhistory pinh2
                          where con.notagreedpriceindex_id = pinh2.priceindex_id
                            and con.nextschedulepriceincrease >= pinh2.startdate)
   and cpl.startdate <= con.nextschedulepriceincrease
   and cpl.enddate > con.nextschedulepriceincrease
   and gbpp.startdate = (select max(gbpp2.startdate)
	                         from generalbgprotectionprice gbpp2
                          where gbpp2.generalpricelist_id = gbpp.generalpricelist_id
                            and gbpp2.product_id = gbpp.product_id
                            and gbpp2.sizedefinition_id = gbpp.sizedefinition_id
                            and gbpp2.startdate <= con.nextschedulepriceincrease)
/

  CREATE OR REPLACE VIEW "V_CONTRACTPRICEUPDATE_EMBLEM" ("AGREED", "CONTRACTCODE", "CONTRACTDESC", "STARTDATE", "ENDDATE", "NEXTSCHEDULEPRICEINCREASE", "PRODUCTCODE", "TYPEOFMERCHANDISE", "SIZECODE", "FINISHCODE", "SIZE_SEQUENCE", "PRODUCTDESC", "SIZEDESC", "FINISHDESC", "PRICEINDEXCODE", "PRICEINDEXDESC", "PRICEINDEXSTART", "PIHPERCENT", "CURRENCYCODE", "CURRENCYDESC", "DECIMALS", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE", "GPLCODE", "GPLDESC", "PRICE", "VOLUMEPRICE", "SOIL") AS 
  select 'Y' agreed, con.code contractcode, con.description contractdesc, con.startdate, con.enddate, con.nextschedulepriceincrease,
       pr.code productcode, pr.typeofmerchandise, sd.code sizecode, null finishcode,
       (select psz.sequencenumber
          from productsize psz
         where psz.product_id = pr.product_id
           and psz.sizedefinition_id = sd.sizedefinition_id) size_sequence,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdesc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc,
       null finishdesc,
       pia.code priceindexcode, pia.description priceindexdesc, pih.startdate priceindexstart, pih.percemblem pihpercent,
       cry.code currencycode, cry.description currencydesc, cry.decimals, cry.invoiceamountdecimals, lan.code languagecode,
       gpl.code gplcode, gpl.description gpldesc, gep.price, 0 volumeprice, null soil
  from contract con
       join priceindex pia on con.agreedpriceindex_id = pia.priceindex_id
       join priceindexhistory pih on con.agreedpriceindex_id = pih.priceindex_id
       join status st on con.status_id = st.status_id and st.statustype = 'CO' and st.code = '20'
       join contractpricelist cpl
            join generalpricelist gpl
                 join generalemblemprice gep
                      join product pr on gep.product_id = pr.product_id
                      join sizedefinition sd on gep.sizedefinition_id = sd.sizedefinition_id
                 on gpl.generalpricelist_id = gep.generalpricelist_id
                 join currency cry on gpl.currency_id = cry.currency_id
            on cpl.generalpricelist_id = gpl.generalpricelist_id and gpl.pricetype = 7 and gpl.usage = 1 and gpl.active = 'Y'
       on con.contract_id = cpl.contract_id and cpl.agreed = 'Y' and cpl.pricetype = 7
       , languages lan
 where (con.terminationdate = getabsmaxdate()
       or
       (con.terminationdate < getabsmaxdate() and con.enddate > con.nextschedulepriceincrease and con.updateevery <> 0)
       )
   and pih.startdate = (select max(pih2.startdate)
                          from priceindexhistory pih2
                         where con.agreedpriceindex_id = pih2.priceindex_id
                           and con.nextschedulepriceincrease >= pih2.startdate)
   and cpl.startdate <= con.nextschedulepriceincrease
   and cpl.enddate > con.nextschedulepriceincrease
   and gep.startdate = (select max(gep2.startdate)
	                        from generalemblemprice gep2
                         where gep2.generalpricelist_id = gep.generalpricelist_id
                           and gep2.product_id = gep.product_id
                           and gep2.sizedefinition_id = gep.sizedefinition_id
                           and gep2.startdate <= con.nextschedulepriceincrease)
 union all
select 'N' agreed, con.code contractcode, con.description contractdesc, con.startdate, con.enddate, con.nextschedulepriceincrease,
       pr.code productcode, pr.typeofmerchandise, sd.code sizecode, null finishcode,
       (select psz.sequencenumber
          from productsize psz
         where psz.product_id = pr.product_id
           and psz.sizedefinition_id = sd.sizedefinition_id) size_sequence,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdesc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc,
       null finishdesc,
       pina.code priceindexcode, pina.description priceindexdesc, pinh.startdate priceindexstart, pinh.percemblem pihpercent,
       cry.code currencycode, cry.description currencydesc, cry.decimals, cry.invoiceamountdecimals, lan.code languagecode,
       gpl.code gplcode, gpl.description gpldesc, gep.price, 0 volumeprice, null soil
  from contract con
       join priceindex pina on con.notagreedpriceindex_id = pina.priceindex_id
       join priceindexhistory pinh on con.notagreedpriceindex_id = pinh.priceindex_id
       join status st on con.status_id = st.status_id and st.statustype = 'CO' and st.code = '20'
       join contractpricelist cpl
            join generalpricelist gpl
                 join generalemblemprice gep
                      join product pr on gep.product_id = pr.product_id
                      join sizedefinition sd on gep.sizedefinition_id = sd.sizedefinition_id
                 on gpl.generalpricelist_id = gep.generalpricelist_id
                 join currency cry on gpl.currency_id = cry.currency_id
            on cpl.generalpricelist_id = gpl.generalpricelist_id and gpl.pricetype = 7 and gpl.usage = 1 and gpl.active = 'Y'
       on con.contract_id = cpl.contract_id and cpl.agreed = 'N' and cpl.pricetype = 7
       , languages lan
 where (con.terminationdate = getabsmaxdate()
       or
       (con.terminationdate < getabsmaxdate() and con.enddate > con.nextschedulepriceincrease and con.updateevery <> 0)
       )
   and con.allownotagreedpricelists = 'Y'
   and pinh.startdate = (select max(pinh2.startdate)
                           from priceindexhistory pinh2
                          where con.notagreedpriceindex_id = pinh2.priceindex_id
                            and con.nextschedulepriceincrease >= pinh2.startdate)
   and cpl.startdate <= con.nextschedulepriceincrease
   and cpl.enddate > con.nextschedulepriceincrease
   and gep.startdate = (select max(gep2.startdate)
	                        from generalemblemprice gep2
                         where gep2.generalpricelist_id = gep.generalpricelist_id
                           and gep2.product_id = gep.product_id
                           and gep2.sizedefinition_id = gep.sizedefinition_id
                           and gep2.startdate <= con.nextschedulepriceincrease)
/

  CREATE OR REPLACE VIEW "V_CONTRACTPRICEUPDATE_INSURANCE" ("AGREED", "CONTRACTCODE", "CONTRACTDESC", "STARTDATE", "ENDDATE", "NEXTSCHEDULEPRICEINCREASE", "PRODUCTCODE", "TYPEOFMERCHANDISE", "SIZECODE", "FINISHCODE", "SIZE_SEQUENCE", "PRODUCTDESC", "SIZEDESC", "FINISHDESC", "PRICEINDEXCODE", "PRICEINDEXDESC", "PRICEINDEXSTART", "PIHPERCENT", "CURRENCYCODE", "CURRENCYDESC", "DECIMALS", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE", "GPLCODE", "GPLDESC", "PRICE", "VOLUMEPRICE", "SOIL") AS 
  select 'Y' agreed, con.code contractcode, con.description contractdesc, con.startdate, con.enddate, con.nextschedulepriceincrease,
       pr.code productcode, pr.typeofmerchandise, sd.code sizecode, fm.code finishcode,
       (select psz.sequencenumber
          from productsize psz
         where psz.product_id = pr.product_id
           and psz.sizedefinition_id = sd.sizedefinition_id) size_sequence,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdesc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc,
       (select fmd.description
          from finishingmethod_desc fmd
         where fmd.finishingmethod_id = fm.finishingmethod_id
           and fmd.language_id = lan.language_id) finishdesc,
       pia.code priceindexcode, pia.description priceindexdesc, pih.startdate priceindexstart, pih.percinsurance pihpercent,
       cry.code currencycode, cry.description currencydesc, cry.decimals, cry.invoiceamountdecimals, lan.code languagecode,
       gpl.code gplcode, gpl.description gpldesc, gip.price, 0 volumeprice, null soil
  from contract con
       join priceindex pia on con.agreedpriceindex_id = pia.priceindex_id
       join priceindexhistory pih on con.agreedpriceindex_id = pih.priceindex_id
       join status st on con.status_id = st.status_id and st.statustype = 'CO' and st.code = '20'
       join contractpricelist cpl
            join generalpricelist gpl
                 join generalinsuranceprice gip
                      join product pr on gip.product_id = pr.product_id
                      join sizedefinition sd on gip.sizedefinition_id = sd.sizedefinition_id
                      join finishingmethod fm on gip.finishingmethod_id = fm.finishingmethod_id
                 on gpl.generalpricelist_id = gip.generalpricelist_id
                 join currency cry on gpl.currency_id = cry.currency_id
            on cpl.generalpricelist_id = gpl.generalpricelist_id and gpl.pricetype = 9 and gpl.usage = 1 and gpl.active = 'Y'
       on con.contract_id = cpl.contract_id and cpl.agreed = 'Y' and cpl.pricetype = 9
       , languages lan
 where (con.terminationdate = getabsmaxdate()
       or
       (con.terminationdate < getabsmaxdate() and con.enddate > con.nextschedulepriceincrease and con.updateevery <> 0)
       )
   and pih.startdate = (select max(pih2.startdate)
                          from priceindexhistory pih2
                         where con.agreedpriceindex_id = pih2.priceindex_id
                           and con.nextschedulepriceincrease >= pih2.startdate)
   and cpl.startdate <= con.nextschedulepriceincrease
   and cpl.enddate > con.nextschedulepriceincrease
   and gip.startdate = (select max(gip2.startdate)
	                        from generalinsuranceprice gip2
                         where gip2.generalpricelist_id = gip.generalpricelist_id
                           and gip2.product_id = gip.product_id
                           and gip2.sizedefinition_id = gip.sizedefinition_id
                           and gip2.startdate <= con.nextschedulepriceincrease)
 union all
select 'N' agreed, con.code contractcode, con.description contractdesc, con.startdate, con.enddate, con.nextschedulepriceincrease,
       pr.code productcode, pr.typeofmerchandise, sd.code sizecode, fm.code finishcode,
       (select psz.sequencenumber
          from productsize psz
         where psz.product_id = pr.product_id
           and psz.sizedefinition_id = sd.sizedefinition_id) size_sequence,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdesc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc,
       (select fmd.description
          from finishingmethod_desc fmd
         where fmd.finishingmethod_id = fm.finishingmethod_id
           and fmd.language_id = lan.language_id) finishdesc,
       pina.code priceindexcode, pina.description priceindexdesc, pinh.startdate priceindexstart, pinh.percinsurance pihpercent,
       cry.code currencycode, cry.description currencydesc, cry.decimals, cry.invoiceamountdecimals, lan.code languagecode,
       gpl.code gplcode, gpl.description gpldesc, gip.price, 0 volumeprice, null soil
  from contract con
       join priceindex pina on con.notagreedpriceindex_id = pina.priceindex_id
       join priceindexhistory pinh on con.notagreedpriceindex_id = pinh.priceindex_id
       join status st on con.status_id = st.status_id and st.statustype = 'CO' and st.code = '20'
       join contractpricelist cpl
            join generalpricelist gpl
                 join generalinsuranceprice gip
                      join product pr on gip.product_id = pr.product_id
                      join sizedefinition sd on gip.sizedefinition_id = sd.sizedefinition_id
                      join finishingmethod fm on gip.finishingmethod_id = fm.finishingmethod_id
                 on gpl.generalpricelist_id = gip.generalpricelist_id
                 join currency cry on gpl.currency_id = cry.currency_id
            on cpl.generalpricelist_id = gpl.generalpricelist_id and gpl.pricetype = 9 and gpl.usage = 1 and gpl.active = 'Y'
       on con.contract_id = cpl.contract_id and cpl.agreed = 'N' and cpl.pricetype = 9
       , languages lan
 where (con.terminationdate = getabsmaxdate()
       or
       (con.terminationdate < getabsmaxdate() and con.enddate > con.nextschedulepriceincrease and con.updateevery <> 0)
       )
   and con.allownotagreedpricelists = 'Y'
   and pinh.startdate = (select max(pinh2.startdate)
                           from priceindexhistory pinh2
                          where con.notagreedpriceindex_id = pinh2.priceindex_id
                            and con.nextschedulepriceincrease >= pinh2.startdate)
   and cpl.startdate <= con.nextschedulepriceincrease
   and cpl.enddate > con.nextschedulepriceincrease
   and gip.startdate = (select max(gip2.startdate)
	                        from generalinsuranceprice gip2
                         where gip2.generalpricelist_id = gip.generalpricelist_id
                           and gip2.product_id = gip.product_id
                           and gip2.sizedefinition_id = gip.sizedefinition_id
                           and gip2.startdate <= con.nextschedulepriceincrease)
/

  CREATE OR REPLACE VIEW "V_CONTRACTPRICEUPDATE_RENT" ("LINETYPE", "AGREED", "CONTRACTCODE", "CONTRACTDESC", "STARTDATE", "ENDDATE", "NEXTSCHEDULEPRICEINCREASE", "PRODUCTCODE", "TYPEOFMERCHANDISE", "SIZECODE", "FINISHCODE", "SIZE_SEQUENCE", "PRODUCTDESC", "SIZEDESC", "FINISHDESC", "PRICEINDEXCODE", "PRICEINDEXDESC", "PRICEINDEXSTART", "PIHPERCENT", "CURRENCYCODE", "CURRENCYDESC", "DECIMALS", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE", "GPLCODE", "GPLDESC", "PRICE", "VOLUMEPRICE", "SOIL") AS 
  select 3 linetype, 'Y' agreed, con.code contractcode, con.description contractdesc, con.startdate, con.enddate, con.nextschedulepriceincrease,
       pr.code productcode, pr.typeofmerchandise, sd.code sizecode, fm.code finishcode,
       (select psz.sequencenumber
          from productsize psz
         where psz.product_id = pr.product_id
           and psz.sizedefinition_id = sd.sizedefinition_id) size_sequence,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdesc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc,
       (select fmd.description
          from finishingmethod_desc fmd
         where fmd.finishingmethod_id = fm.finishingmethod_id
           and fmd.language_id = lan.language_id) finishdesc,
       pia.code priceindexcode, pia.description priceindexdesc, pih.startdate priceindexstart, pih.percrent pihpercent,
       cry.code currencycode, cry.description currencydesc, cry.decimals, cry.invoiceamountdecimals, lan.code languagecode,
       gpl.code gplcode, gpl.description gpldesc, grp.price, 0 volumeprice, null soil
  from contract con
       join priceindex pia on con.agreedpriceindex_id = pia.priceindex_id
       join priceindexhistory pih on con.agreedpriceindex_id = pih.priceindex_id
       join status st on con.status_id = st.status_id and st.statustype = 'CO' and st.code = '20'
       join contractpricelist cpl
            join generalpricelist gpl
                 join generalrentprice grp
                      join product pr on grp.product_id = pr.product_id
                      join sizedefinition sd on grp.sizedefinition_id = sd.sizedefinition_id
                      join finishingmethod fm on grp.finishingmethod_id = fm.finishingmethod_id
                 on gpl.generalpricelist_id = grp.generalpricelist_id
                 join currency cry on gpl.currency_id = cry.currency_id
            on cpl.generalpricelist_id = gpl.generalpricelist_id and gpl.pricetype = 2 and gpl.usage = 1 and gpl.active = 'Y'
       on con.contract_id = cpl.contract_id and cpl.agreed = 'Y' and cpl.pricetype = 2
       , languages lan
 where (con.terminationdate = getabsmaxdate()
       or
       (con.terminationdate < getabsmaxdate() and con.enddate > con.nextschedulepriceincrease and con.updateevery <> 0)
       )
   and pih.startdate = (select max(pih2.startdate)
                          from priceindexhistory pih2
                         where con.agreedpriceindex_id = pih2.priceindex_id
                           and con.nextschedulepriceincrease >= pih2.startdate)
   and cpl.startdate <= con.nextschedulepriceincrease
   and cpl.enddate > con.nextschedulepriceincrease
   and grp.startdate = (select max(grp2.startdate)
	                        from generalrentprice grp2
                         where grp2.generalpricelist_id = grp.generalpricelist_id
                           and grp2.product_id = grp.product_id
                           and grp2.sizedefinition_id = grp.sizedefinition_id
                           and grp2.finishingmethod_id = grp.finishingmethod_id
                           and grp2.startdate <= con.nextschedulepriceincrease)
 union all
select 3 linetype, 'N' agreed, con.code contractcode, con.description contractdesc, con.startdate, con.enddate, con.nextschedulepriceincrease,
       pr.code productcode, pr.typeofmerchandise, sd.code sizecode, fm.code finishcode,
       (select psz.sequencenumber
          from productsize psz
         where psz.product_id = pr.product_id
           and psz.sizedefinition_id = sd.sizedefinition_id) size_sequence,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdesc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc,
       (select fmd.description
          from finishingmethod_desc fmd
         where fmd.finishingmethod_id = fm.finishingmethod_id
           and fmd.language_id = lan.language_id) finishdesc,
       pina.code priceindexcode, pina.description priceindexdesc, pinh.startdate priceindexstart, pinh.percrent pihpercent,
       cry.code currencycode, cry.description currencydesc, cry.decimals, cry.invoiceamountdecimals, lan.code languagecode,
       gpl.code gplcode, gpl.description gpldesc, grp.price, 0 volumeprice, null soil
  from contract con
       join priceindex pina on con.notagreedpriceindex_id = pina.priceindex_id
       join priceindexhistory pinh on con.notagreedpriceindex_id = pinh.priceindex_id
       join status st on con.status_id = st.status_id and st.statustype = 'CO' and st.code = '20'
       join contractpricelist cpl
            join generalpricelist gpl
                 join generalrentprice grp
                      join product pr on grp.product_id = pr.product_id
                      join sizedefinition sd on grp.sizedefinition_id = sd.sizedefinition_id
                      join finishingmethod fm on grp.finishingmethod_id = fm.finishingmethod_id
                 on gpl.generalpricelist_id = grp.generalpricelist_id
                 join currency cry on gpl.currency_id = cry.currency_id
            on cpl.generalpricelist_id = gpl.generalpricelist_id and gpl.pricetype = 2 and gpl.usage = 1 and gpl.active = 'Y'
       on con.contract_id = cpl.contract_id and cpl.agreed = 'N' and cpl.pricetype = 2
       , languages lan
 where (con.terminationdate = getabsmaxdate()
       or
       (con.terminationdate < getabsmaxdate() and con.enddate > con.nextschedulepriceincrease and con.updateevery <> 0)
       )
   and con.allownotagreedpricelists = 'Y'
   and pinh.startdate = (select max(pinh2.startdate)
                           from priceindexhistory pinh2
                          where con.notagreedpriceindex_id = pinh2.priceindex_id
                            and con.nextschedulepriceincrease >= pinh2.startdate)
   and cpl.startdate <= con.nextschedulepriceincrease
   and cpl.enddate > con.nextschedulepriceincrease
   and grp.startdate = (select max(grp2.startdate)
	                        from generalrentprice grp2
                         where grp2.generalpricelist_id = grp.generalpricelist_id
                           and grp2.product_id = grp.product_id
                           and grp2.sizedefinition_id = grp.sizedefinition_id
                           and grp2.finishingmethod_id = grp.finishingmethod_id
                           and grp2.startdate <= con.nextschedulepriceincrease)
/

  CREATE OR REPLACE VIEW "V_CONTRACTPRICEUPDATE_REPAIR" ("AGREED", "CONTRACTCODE", "CONTRACTDESC", "STARTDATE", "ENDDATE", "NEXTSCHEDULEPRICEINCREASE", "PRODUCTCODE", "TYPEOFMERCHANDISE", "SIZECODE", "FINISHCODE", "SIZE_SEQUENCE", "PRODUCTDESC", "SIZEDESC", "FINISHDESC", "PRICEINDEXCODE", "PRICEINDEXDESC", "PRICEINDEXSTART", "PIHPERCENT", "CURRENCYCODE", "CURRENCYDESC", "DECIMALS", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE", "GPLCODE", "GPLDESC", "PRICE", "VOLUMEPRICE", "SOIL") AS 
  select 'Y' agreed, con.code contractcode, con.description contractdesc, con.startdate, con.enddate, con.nextschedulepriceincrease,
       (select rt.code
          from repairtype rt
         where rt.repairtype_id = grep.repairtype_id) productcode,
       null typeofmerchandise, null sizecode, null finishcode,
       0 size_sequence,
       (select rtd.description
          from repairtype_desc rtd
         where rtd.repairtype_id = grep.repairtype_id
           and rtd.language_id = lan.language_id) productdesc,
       null sizedesc,
       null finishdesc,
       pia.code priceindexcode, pia.description priceindexdesc, pih.startdate priceindexstart, pih.percrepair pihpercent,
       cry.code currencycode, cry.description currencydesc, cry.decimals, cry.invoiceamountdecimals, lan.code languagecode,
       gpl.code gplcode, gpl.description gpldesc, grep.price, grep.priceperminute volumeprice, null soil
  from contract con
       join priceindex pia on con.agreedpriceindex_id = pia.priceindex_id
       join priceindexhistory pih on con.agreedpriceindex_id = pih.priceindex_id
       join status st on con.status_id = st.status_id and st.statustype = 'CO' and st.code = '20'
       join contractpricelist cpl
            join generalpricelist gpl
                 join generalrepairprice grep on gpl.generalpricelist_id = grep.generalpricelist_id
                 join currency cry on gpl.currency_id = cry.currency_id
            on cpl.generalpricelist_id = gpl.generalpricelist_id and gpl.pricetype = 6 and gpl.usage = 1 and gpl.active = 'Y'
       on con.contract_id = cpl.contract_id and cpl.agreed = 'Y' and cpl.pricetype = 6
       , languages lan
 where (con.terminationdate = getabsmaxdate()
       or
       (con.terminationdate < getabsmaxdate() and con.enddate > con.nextschedulepriceincrease and con.updateevery <> 0)
       )
   and pih.startdate = (select max(pih2.startdate)
                          from priceindexhistory pih2
                         where con.agreedpriceindex_id = pih2.priceindex_id
                           and con.nextschedulepriceincrease >= pih2.startdate)
   and cpl.startdate <= con.nextschedulepriceincrease
   and cpl.enddate > con.nextschedulepriceincrease
   and grep.startdate = (select max(grep2.startdate)
	                         from generalrepairprice grep2
                          where grep2.generalpricelist_id = grep.generalpricelist_id
                            and grep2.repairtype_id = grep.repairtype_id
                            and grep2.startdate <= con.nextschedulepriceincrease)
 union all
select 'N' agreed, con.code contractcode, con.description contractdesc, con.startdate, con.enddate, con.nextschedulepriceincrease,
       (select rt.code
          from repairtype rt
         where rt.repairtype_id = grep.repairtype_id) productcode,
       null typeofmerchandise, null sizecode, null finishcode,
       0 size_sequence,
       (select rtd.description
          from repairtype_desc rtd
         where rtd.repairtype_id = grep.repairtype_id
           and rtd.language_id = lan.language_id) productdesc,
       null sizedesc,
       null finishdesc,
       pina.code priceindexcode, pina.description priceindexdesc, pinh.startdate priceindexstart, pinh.percrepair pihpercent,
       cry.code currencycode, cry.description currencydesc, cry.decimals, cry.invoiceamountdecimals, lan.code languagecode,
       gpl.code gplcode, gpl.description gpldesc, grep.price, grep.priceperminute volumeprice, null soil
  from contract con
       join priceindex pina on con.notagreedpriceindex_id = pina.priceindex_id
       join priceindexhistory pinh on con.notagreedpriceindex_id = pinh.priceindex_id
       join status st on con.status_id = st.status_id and st.statustype = 'CO' and st.code = '20'
       join contractpricelist cpl
            join generalpricelist gpl
                 join generalrepairprice grep on gpl.generalpricelist_id = grep.generalpricelist_id
                 join currency cry on gpl.currency_id = cry.currency_id
            on cpl.generalpricelist_id = gpl.generalpricelist_id and gpl.pricetype = 6 and gpl.usage = 1 and gpl.active = 'Y'
       on con.contract_id = cpl.contract_id and cpl.agreed = 'N' and cpl.pricetype = 6
       , languages lan
 where (con.terminationdate = getabsmaxdate()
       or
       (con.terminationdate < getabsmaxdate() and con.enddate > con.nextschedulepriceincrease and con.updateevery <> 0)
       )
   and con.allownotagreedpricelists = 'Y'
   and pinh.startdate = (select max(pinh2.startdate)
                           from priceindexhistory pinh2
                          where con.notagreedpriceindex_id = pinh2.priceindex_id
                            and con.nextschedulepriceincrease >= pinh2.startdate)
   and cpl.startdate <= con.nextschedulepriceincrease
   and cpl.enddate > con.nextschedulepriceincrease
   and grep.startdate = (select max(grep2.startdate)
	                         from generalrepairprice grep2
                          where grep2.generalpricelist_id = grep.generalpricelist_id
                            and grep2.repairtype_id = grep.repairtype_id
                            and grep2.startdate <= con.nextschedulepriceincrease)
/

  CREATE OR REPLACE VIEW "V_CONTRACTPRICEUPDATE_REPLACEMENT" ("AGREED", "CONTRACTCODE", "CONTRACTDESC", "STARTDATE", "ENDDATE", "NEXTSCHEDULEPRICEINCREASE", "PRODUCTCODE", "TYPEOFMERCHANDISE", "SIZECODE", "FINISHCODE", "SIZE_SEQUENCE", "PRODUCTDESC", "SIZEDESC", "FINISHDESC", "PRICEINDEXCODE", "PRICEINDEXDESC", "PRICEINDEXSTART", "PIHPERCENT", "CURRENCYCODE", "CURRENCYDESC", "DECIMALS", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE", "GPLCODE", "GPLDESC", "PRICE", "VOLUMEPRICE", "SOIL") AS 
  select 'Y' agreed, con.code contractcode, con.description contractdesc, con.startdate, con.enddate, con.nextschedulepriceincrease,
       pr.code productcode, pr.typeofmerchandise, sd.code sizecode, null finishcode,
       (select psz.sequencenumber
          from productsize psz
         where psz.product_id = pr.product_id
           and psz.sizedefinition_id = sd.sizedefinition_id) size_sequence,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdesc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc,
       null finishdesc,
       pia.code priceindexcode, pia.description priceindexdesc, pih.startdate priceindexstart, pih.percreplace pihpercent,
       cry.code currencycode, cry.description currencydesc, cry.decimals, cry.invoiceamountdecimals, lan.code languagecode,
       gpl.code gplcode, gpl.description gpldesc, grpp.price, 0 volumeprice, null soil
  from contract con
       join priceindex pia on con.agreedpriceindex_id = pia.priceindex_id
       join priceindexhistory pih on con.agreedpriceindex_id = pih.priceindex_id
       join status st on con.status_id = st.status_id and st.statustype = 'CO' and st.code = '20'
       join contractpricelist cpl
            join generalpricelist gpl
                 join generalreplacementprice grpp
                      join product pr on grpp.product_id = pr.product_id
                      join sizedefinition sd on grpp.sizedefinition_id = sd.sizedefinition_id
                 on gpl.generalpricelist_id = grpp.generalpricelist_id
                 join currency cry on gpl.currency_id = cry.currency_id
            on cpl.generalpricelist_id = gpl.generalpricelist_id and gpl.pricetype = 3 and gpl.usage = 1 and gpl.active = 'Y'
       on con.contract_id = cpl.contract_id and cpl.agreed = 'Y' and cpl.pricetype = 3
       , languages lan
 where (con.terminationdate = getabsmaxdate()
       or
       (con.terminationdate < getabsmaxdate() and con.enddate > con.nextschedulepriceincrease and con.updateevery <> 0)
       )
   and pih.startdate = (select max(pih2.startdate)
                          from priceindexhistory pih2
                         where con.agreedpriceindex_id = pih2.priceindex_id
                           and con.nextschedulepriceincrease >= pih2.startdate)
   and cpl.startdate <= con.nextschedulepriceincrease
   and cpl.enddate > con.nextschedulepriceincrease
   and grpp.startdate = (select max(grpp2.startdate)
	                         from generalreplacementprice grpp2
                          where grpp2.generalpricelist_id = grpp.generalpricelist_id
                            and grpp2.product_id = grpp.product_id
                            and grpp2.sizedefinition_id = grpp.sizedefinition_id
                            and nvl(grpp2.sizebillinggroup_id, 0) = nvl(grpp.sizebillinggroup_id, 0)
                            and grpp2.startdate <= con.nextschedulepriceincrease)
 union all
select 'N' agreed, con.code contractcode, con.description contractdesc, con.startdate, con.enddate, con.nextschedulepriceincrease,
       pr.code productcode, pr.typeofmerchandise, sd.code sizecode, null finishcode,
       (select psz.sequencenumber
          from productsize psz
         where psz.product_id = pr.product_id
           and psz.sizedefinition_id = sd.sizedefinition_id) size_sequence,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdesc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc,
       null finishdesc,
       pina.code priceindexcode, pina.description priceindexdesc, pinh.startdate priceindexstart, pinh.percreplace pihpercent,
       cry.code currencycode, cry.description currencydesc, cry.decimals, cry.invoiceamountdecimals, lan.code languagecode,
       gpl.code gplcode, gpl.description gpldesc, grpp.price, 0 volumeprice, null soil
  from contract con
       join priceindex pina on con.notagreedpriceindex_id = pina.priceindex_id
       join priceindexhistory pinh on con.notagreedpriceindex_id = pinh.priceindex_id
       join status st on con.status_id = st.status_id and st.statustype = 'CO' and st.code = '20'
       join contractpricelist cpl
            join generalpricelist gpl
                 join generalreplacementprice grpp
                      join product pr on grpp.product_id = pr.product_id
                      join sizedefinition sd on grpp.sizedefinition_id = sd.sizedefinition_id
                 on gpl.generalpricelist_id = grpp.generalpricelist_id
                 join currency cry on gpl.currency_id = cry.currency_id
            on cpl.generalpricelist_id = gpl.generalpricelist_id and gpl.pricetype = 3 and gpl.usage = 1 and gpl.active = 'Y'
       on con.contract_id = cpl.contract_id and cpl.agreed = 'N' and cpl.pricetype = 3
       , languages lan
 where (con.terminationdate = getabsmaxdate()
       or
       (con.terminationdate < getabsmaxdate() and con.enddate > con.nextschedulepriceincrease and con.updateevery <> 0)
       )
   and con.allownotagreedpricelists = 'Y'
   and pinh.startdate = (select max(pinh2.startdate)
                           from priceindexhistory pinh2
                          where con.notagreedpriceindex_id = pinh2.priceindex_id
                            and con.nextschedulepriceincrease >= pinh2.startdate)
   and cpl.startdate <= con.nextschedulepriceincrease
   and cpl.enddate > con.nextschedulepriceincrease
   and grpp.startdate = (select max(grpp2.startdate)
	                         from generalreplacementprice grpp2
                          where grpp2.generalpricelist_id = grpp.generalpricelist_id
                            and grpp2.product_id = grpp.product_id
                            and grpp2.sizedefinition_id = grpp.sizedefinition_id
                            and nvl(grpp2.sizebillinggroup_id, 0) = nvl(grpp.sizebillinggroup_id, 0)
                            and grpp2.startdate <= con.nextschedulepriceincrease)
/

  CREATE OR REPLACE VIEW "V_CONTRACTPRICEUPDATE_SALES" ("AGREED", "CONTRACTCODE", "CONTRACTDESC", "STARTDATE", "ENDDATE", "NEXTSCHEDULEPRICEINCREASE", "PRODUCTCODE", "TYPEOFMERCHANDISE", "SIZECODE", "FINISHCODE", "SIZE_SEQUENCE", "PRODUCTDESC", "SIZEDESC", "FINISHDESC", "PRICEINDEXCODE", "PRICEINDEXDESC", "PRICEINDEXSTART", "PIHPERCENT", "CURRENCYCODE", "CURRENCYDESC", "DECIMALS", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE", "GPLCODE", "GPLDESC", "PRICE", "VOLUMEPRICE", "SOIL") AS 
  select 'Y' agreed, con.code contractcode, con.description contractdesc, con.startdate, con.enddate, con.nextschedulepriceincrease,
       pr.code productcode, pr.typeofmerchandise, sd.code sizecode, null finishcode,
       (select psz.sequencenumber
          from productsize psz
         where psz.product_id = pr.product_id
           and psz.sizedefinition_id = sd.sizedefinition_id) size_sequence,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdesc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc,
       null finishdesc,
       pia.code priceindexcode, pia.description priceindexdesc, pih.startdate priceindexstart, pih.percsales pihpercent,
       cry.code currencycode, cry.description currencydesc, cry.decimals, cry.invoiceamountdecimals, lan.code languagecode,
       gpl.code gplcode, gpl.description gpldesc, gsp.price, gsp.volumeprice, null soil
  from contract con
            join priceindex pia on con.agreedpriceindex_id = pia.priceindex_id
            join priceindexhistory pih on con.agreedpriceindex_id = pih.priceindex_id
            join status st on con.status_id = st.status_id and st.statustype = 'CO' and st.code = '20'
       join contractpricelist cpl
            join generalpricelist gpl
                 join generalsalesprice gsp
                      join product pr on gsp.product_id = pr.product_id
                      join sizedefinition sd on gsp.sizedefinition_id = sd.sizedefinition_id
                 on gpl.generalpricelist_id = gsp.generalpricelist_id
                 join currency cry on gpl.currency_id = cry.currency_id
            on cpl.generalpricelist_id = gpl.generalpricelist_id and gpl.pricetype = 4 and gpl.usage = 1 and gpl.active = 'Y'
       on con.contract_id = cpl.contract_id and cpl.agreed = 'Y' and cpl.pricetype = 4
       , languages lan
 where (con.terminationdate = getabsmaxdate()
       or
       (con.terminationdate < getabsmaxdate() and con.enddate > con.nextschedulepriceincrease and con.updateevery <> 0)
       )
   and pih.startdate = (select max(pih2.startdate)
                          from priceindexhistory pih2
                         where con.agreedpriceindex_id = pih2.priceindex_id
                           and con.nextschedulepriceincrease >= pih2.startdate)
   and cpl.startdate <= con.nextschedulepriceincrease
   and cpl.enddate > con.nextschedulepriceincrease
   and gsp.startdate = (select max(gsp2.startdate)
	                        from generalsalesprice gsp2
                         where gsp2.generalpricelist_id = gsp.generalpricelist_id
                           and gsp2.product_id = gsp.product_id
                           and gsp2.sizedefinition_id = gsp.sizedefinition_id
                           and gsp2.volumeprice = gsp.volumeprice
                           and nvl(gsp2.sizebillinggroup_id, 0) = nvl(gsp.sizebillinggroup_id, 0)
                           and gsp2.startdate <= con.nextschedulepriceincrease)
 union all
select 'N' agreed, con.code contractcode, con.description contractdesc, con.startdate, con.enddate, con.nextschedulepriceincrease,
       pr.code productcode, pr.typeofmerchandise, sd.code sizecode, null finishcode,
       (select psz.sequencenumber
          from productsize psz
         where psz.product_id = pr.product_id
           and psz.sizedefinition_id = sd.sizedefinition_id) size_sequence,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdesc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc,
       null finishdesc,
       pina.code priceindexcode, pina.description priceindexdesc, pinh.startdate priceindexstart, pinh.percsales pihpercent,
       cry.code currencycode, cry.description currencydesc, cry.decimals, cry.invoiceamountdecimals, lan.code languagecode,
       gpl.code gplcode, gpl.description gpldesc, gsp.price, gsp.volumeprice, null soil
  from contract con
       join priceindex pina on con.notagreedpriceindex_id = pina.priceindex_id
       join priceindexhistory pinh on con.notagreedpriceindex_id = pinh.priceindex_id
       join status st on con.status_id = st.status_id and st.statustype = 'CO' and st.code = '20'
       join contractpricelist cpl
            join generalpricelist gpl
                 join generalsalesprice gsp
                      join product pr on gsp.product_id = pr.product_id
                      join sizedefinition sd on gsp.sizedefinition_id = sd.sizedefinition_id
                 on gpl.generalpricelist_id = gsp.generalpricelist_id
                 join currency cry on gpl.currency_id = cry.currency_id
            on cpl.generalpricelist_id = gpl.generalpricelist_id and gpl.pricetype = 4 and gpl.usage = 1 and gpl.active = 'Y'
       on con.contract_id = cpl.contract_id and cpl.agreed = 'N' and cpl.pricetype = 4
       , languages lan
 where (con.terminationdate = getabsmaxdate()
       or
       (con.terminationdate < getabsmaxdate() and con.enddate > con.nextschedulepriceincrease and con.updateevery <> 0)
       )
   and con.allownotagreedpricelists = 'Y'
   and pinh.startdate = (select max(pinh2.startdate)
                           from priceindexhistory pinh2
                          where con.notagreedpriceindex_id = pinh2.priceindex_id
                            and con.nextschedulepriceincrease >= pinh2.startdate)
   and cpl.startdate <= con.nextschedulepriceincrease
   and cpl.enddate > con.nextschedulepriceincrease
   and gsp.startdate = (select max(gsp2.startdate)
	                        from generalsalesprice gsp2
                         where gsp2.generalpricelist_id = gsp.generalpricelist_id
                           and gsp2.product_id = gsp.product_id
                           and gsp2.sizedefinition_id = gsp.sizedefinition_id
                           and gsp2.volumeprice = gsp.volumeprice
                           and nvl(gsp2.sizebillinggroup_id, 0) = nvl(gsp.sizebillinggroup_id, 0)
                           and gsp2.startdate <= con.nextschedulepriceincrease)
/

  CREATE OR REPLACE VIEW "V_CONTRACTPRICEUPDATE_SPECCHARGE" ("AGREED", "CONTRACTCODE", "CONTRACTDESC", "STARTDATE", "ENDDATE", "NEXTSCHEDULEPRICEINCREASE", "PRODUCTCODE", "TYPEOFMERCHANDISE", "SIZECODE", "FINISHCODE", "SIZE_SEQUENCE", "PRODUCTDESC", "SIZEDESC", "FINISHDESC", "PRICEINDEXCODE", "PRICEINDEXDESC", "PRICEINDEXSTART", "PIHPERCENT", "CURRENCYCODE", "CURRENCYDESC", "DECIMALS", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE", "GPLCODE", "GPLDESC", "PRICE", "VOLUMEPRICE", "SOIL") AS 
  select 'Y' agreed, con.code contractcode, con.description contractdesc, con.startdate, con.enddate, con.nextschedulepriceincrease,
       (select sc.code
          from specialcharge sc
         where sc.specialcharge_id = gscp.specialcharge_id) productcode,
       null typeofmerchandise, null sizecode, null finishcode,
       0 size_sequence,
       (select scd.description
          from specialcharge_desc scd
         where scd.specialcharge_id = gscp.specialcharge_id
           and scd.language_id = lan.language_id) productdesc,
       null sizedesc,
       null finishdesc,
       pia.code priceindexcode, pia.description priceindexdesc, pih.startdate priceindexstart, pih.percspecialcharge pihpercent,
       cry.code currencycode, cry.description currencydesc, cry.decimals, cry.invoiceamountdecimals, lan.code languagecode,
       gpl.code gplcode, gpl.description gpldesc, gscp.price, 0 volumeprice, null soil
  from contract con
       join priceindex pia on con.agreedpriceindex_id = pia.priceindex_id
       join priceindexhistory pih on con.agreedpriceindex_id = pih.priceindex_id
       join status st on con.status_id = st.status_id and st.statustype = 'CO' and st.code = '20'
       join contractpricelist cpl
            join generalpricelist gpl
                 join generalspecialchargeprice gscp on gpl.generalpricelist_id = gscp.generalpricelist_id and gscp.price is not null
                 join currency cry on gpl.currency_id = cry.currency_id
            on cpl.generalpricelist_id = gpl.generalpricelist_id and gpl.pricetype = 10 and gpl.usage = 1 and gpl.active = 'Y'
       on con.contract_id = cpl.contract_id and cpl.agreed = 'Y' and cpl.pricetype = 10
       , languages lan
 where (con.terminationdate = getabsmaxdate()
       or
       (con.terminationdate < getabsmaxdate() and con.enddate > con.nextschedulepriceincrease and con.updateevery <> 0)
       )
   and pih.startdate = (select max(pih2.startdate)
                          from priceindexhistory pih2
                         where con.agreedpriceindex_id = pih2.priceindex_id
                           and con.nextschedulepriceincrease >= pih2.startdate)
   and cpl.startdate <= con.nextschedulepriceincrease
   and cpl.enddate > con.nextschedulepriceincrease
   and gscp.startdate = (select max(gscp2.startdate)
	                         from generalspecialchargeprice gscp2
                          where gscp2.generalpricelist_id = gscp.generalpricelist_id
                            and gscp2.specialcharge_id = gscp.specialcharge_id
                            and gscp2.price is not null
                            and gscp2.startdate <= con.nextschedulepriceincrease)
 union all
select 'N' agreed, con.code contractcode, con.description contractdesc, con.startdate, con.enddate, con.nextschedulepriceincrease,
       (select sc.code
          from specialcharge sc
         where sc.specialcharge_id = gscp.specialcharge_id) productcode,
       null typeofmerchandise, null sizecode, null finishcode,
       0 size_sequence,
       (select scd.description
          from specialcharge_desc scd
         where scd.specialcharge_id = gscp.specialcharge_id
           and scd.language_id = lan.language_id) productdesc,
       null sizedesc,
       null finishdesc,
       pina.code priceindexcode, pina.description priceindexdesc, pinh.startdate priceindexstart, pinh.percspecialcharge pihpercent,
       cry.code currencycode, cry.description currencydesc, cry.decimals, cry.invoiceamountdecimals, lan.code languagecode,
       gpl.code gplcode, gpl.description gpldesc, gscp.price, 0 volumeprice, null soil
  from contract con
       join priceindex pina on con.notagreedpriceindex_id = pina.priceindex_id
       join priceindexhistory pinh on con.notagreedpriceindex_id = pinh.priceindex_id
       join status st on con.status_id = st.status_id and st.statustype = 'CO' and st.code = '20'
       join contractpricelist cpl
            join generalpricelist gpl
                 join generalspecialchargeprice gscp on gpl.generalpricelist_id = gscp.generalpricelist_id and gscp.price is not null
                 join currency cry on gpl.currency_id = cry.currency_id
            on cpl.generalpricelist_id = gpl.generalpricelist_id and gpl.pricetype = 10 and gpl.usage = 1 and gpl.active = 'Y'
       on con.contract_id = cpl.contract_id and cpl.agreed = 'N' and cpl.pricetype = 10
       , languages lan
 where (con.terminationdate = getabsmaxdate()
       or
       (con.terminationdate < getabsmaxdate() and con.enddate > con.nextschedulepriceincrease and con.updateevery <> 0)
       )
   and con.allownotagreedpricelists = 'Y'
   and pinh.startdate = (select max(pinh2.startdate)
                           from priceindexhistory pinh2
                          where con.notagreedpriceindex_id = pinh2.priceindex_id
                            and con.nextschedulepriceincrease >= pinh2.startdate)
   and cpl.startdate <= con.nextschedulepriceincrease
   and cpl.enddate > con.nextschedulepriceincrease
   and gscp.startdate = (select max(gscp2.startdate)
                           from generalspecialchargeprice gscp2
                          where gscp2.generalpricelist_id = gscp.generalpricelist_id
                            and gscp2.specialcharge_id = gscp.specialcharge_id
                            and gscp2.price is not null
                            and gscp2.startdate <= con.nextschedulepriceincrease)
/

  CREATE OR REPLACE VIEW "V_CONTRACTPRICEUPDATE_SPECSIZECHARGE" ("AGREED", "CONTRACTCODE", "CONTRACTDESC", "STARTDATE", "ENDDATE", "NEXTSCHEDULEPRICEINCREASE", "PRODUCTCODE", "TYPEOFMERCHANDISE", "SIZECODE", "FINISHCODE", "SIZE_SEQUENCE", "PRODUCTDESC", "SIZEDESC", "FINISHDESC", "PRICEINDEXCODE", "PRICEINDEXDESC", "PRICEINDEXSTART", "PIHPERCENT", "CURRENCYCODE", "CURRENCYDESC", "DECIMALS", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE", "GPLCODE", "GPLDESC", "PRICE", "VOLUMEPRICE", "SOIL") AS 
  select 'Y' agreed, con.code contractcode, con.description contractdesc, con.startdate, con.enddate, con.nextschedulepriceincrease,
       pr.code productcode, pr.typeofmerchandise, sd.code sizecode, null finishcode,
       (select psz.sequencenumber
          from productsize psz
         where psz.product_id = pr.product_id
           and psz.sizedefinition_id = sd.sizedefinition_id) size_sequence,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdesc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc,
       null finishdesc,
       pia.code priceindexcode, pia.description priceindexdesc, pih.startdate priceindexstart, pih.percspecialcharge pihpercent,
       cry.code currencycode, cry.description currencydesc, cry.decimals, cry.invoiceamountdecimals, lan.code languagecode,
       gpl.code gplcode, gpl.description gpldesc, gsscp.price, 0 volumeprice, null soil
  from contract con
       join priceindex pia on con.agreedpriceindex_id = pia.priceindex_id
       join priceindexhistory pih on con.agreedpriceindex_id = pih.priceindex_id
       join status st on con.status_id = st.status_id and st.statustype = 'CO' and st.code = '20'
       join contractpricelist cpl
            join generalpricelist gpl
                 join generalspecsizechargeprice gsscp
                      join product pr on gsscp.product_id = pr.product_id
                      join sizedefinition sd on gsscp.sizedefinition_id = sd.sizedefinition_id
                 on gpl.generalpricelist_id = gsscp.generalpricelist_id
                 join currency cry on gpl.currency_id = cry.currency_id
            on cpl.generalpricelist_id = gpl.generalpricelist_id and gpl.pricetype = 12 and gpl.usage = 1 and gpl.active = 'Y'
       on con.contract_id = cpl.contract_id and cpl.agreed = 'Y' and cpl.pricetype = 12
       , languages lan
 where (con.terminationdate = getabsmaxdate()
       or
       (con.terminationdate < getabsmaxdate() and con.enddate > con.nextschedulepriceincrease and con.updateevery <> 0)
       )
   and pih.startdate = (select max(pih2.startdate)
                          from priceindexhistory pih2
                         where con.agreedpriceindex_id = pih2.priceindex_id
                           and con.nextschedulepriceincrease >= pih2.startdate)
   and cpl.startdate <= con.nextschedulepriceincrease
   and cpl.enddate > con.nextschedulepriceincrease
   and gsscp.startdate = (select max(gsscp2.startdate)
	                          from generalspecsizechargeprice gsscp2
                           where gsscp2.generalpricelist_id = gsscp.generalpricelist_id
                             and gsscp2.product_id = gsscp.product_id
                             and gsscp2.sizedefinition_id = gsscp.sizedefinition_id
                             and gsscp2.startdate <= con.nextschedulepriceincrease)
 union all
select 'N' agreed, con.code contractcode, con.description contractdesc, con.startdate, con.enddate, con.nextschedulepriceincrease,
       pr.code productcode, pr.typeofmerchandise, sd.code sizecode, null finishcode,
       (select psz.sequencenumber
          from productsize psz
         where psz.product_id = pr.product_id
           and psz.sizedefinition_id = sd.sizedefinition_id) size_sequence,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdesc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc,
       null finishdesc,
       pina.code priceindexcode, pina.description priceindexdesc, pinh.startdate priceindexstart, pinh.percspecialcharge pihpercent,
       cry.code currencycode, cry.description currencydesc, cry.decimals, cry.invoiceamountdecimals, lan.code languagecode,
       gpl.code gplcode, gpl.description gpldesc, gsscp.price, 0 volumeprice, null soil
  from contract con
       join priceindex pina on con.notagreedpriceindex_id = pina.priceindex_id
       join priceindexhistory pinh on con.notagreedpriceindex_id = pinh.priceindex_id
       join status st on con.status_id = st.status_id and st.statustype = 'CO' and st.code = '20'
       join contractpricelist cpl
            join generalpricelist gpl
                 join generalspecsizechargeprice gsscp
                      join product pr on gsscp.product_id = pr.product_id
                      join sizedefinition sd on gsscp.sizedefinition_id = sd.sizedefinition_id
                 on gpl.generalpricelist_id = gsscp.generalpricelist_id
                 join currency cry on gpl.currency_id = cry.currency_id
            on cpl.generalpricelist_id = gpl.generalpricelist_id and gpl.pricetype = 12 and gpl.usage = 1 and gpl.active = 'Y'
       on con.contract_id = cpl.contract_id and cpl.agreed = 'N' and cpl.pricetype = 12
       , languages lan
 where (con.terminationdate = getabsmaxdate()
       or
       (con.terminationdate < getabsmaxdate() and con.enddate > con.nextschedulepriceincrease and con.updateevery <> 0)
       )
   and con.allownotagreedpricelists = 'Y'
   and pinh.startdate = (select max(pinh2.startdate)
                           from priceindexhistory pinh2
                          where con.notagreedpriceindex_id = pinh2.priceindex_id
                            and con.nextschedulepriceincrease >= pinh2.startdate)
   and cpl.startdate <= con.nextschedulepriceincrease
   and cpl.enddate > con.nextschedulepriceincrease
   and gsscp.startdate = (select max(gsscp2.startdate)
	                          from generalspecsizechargeprice gsscp2
                           where gsscp2.generalpricelist_id = gsscp.generalpricelist_id
                             and gsscp2.product_id = gsscp.product_id
                             and gsscp2.sizedefinition_id = gsscp.sizedefinition_id
                             and gsscp2.startdate <= con.nextschedulepriceincrease)
/

  CREATE OR REPLACE VIEW "V_CONTRACTPRICEUPDATE_WASH" ("AGREED", "CONTRACTCODE", "CONTRACTDESC", "STARTDATE", "ENDDATE", "NEXTSCHEDULEPRICEINCREASE", "PRODUCTCODE", "TYPEOFMERCHANDISE", "SIZECODE", "FINISHCODE", "SIZE_SEQUENCE", "PRODUCTDESC", "SIZEDESC", "FINISHDESC", "PRICEINDEXCODE", "PRICEINDEXDESC", "PRICEINDEXSTART", "PIHPERCENT", "CURRENCYCODE", "CURRENCYDESC", "DECIMALS", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE", "GPLCODE", "GPLDESC", "PRICE", "VOLUMEPRICE", "SOIL") AS 
  select 'Y' agreed, con.code contractcode, con.description contractdesc, con.startdate, con.enddate, con.nextschedulepriceincrease,
       pr.code productcode, pr.typeofmerchandise, sd.code sizecode, fm.code finishcode,
       (select psz.sequencenumber
          from productsize psz
         where psz.product_id = pr.product_id
           and psz.sizedefinition_id = sd.sizedefinition_id) size_sequence,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdesc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc,
       (select fmd.description
          from finishingmethod_desc fmd
         where fmd.finishingmethod_id = fm.finishingmethod_id
           and fmd.language_id = lan.language_id) finishdesc,
       pia.code priceindexcode, pia.description priceindexdesc, pih.startdate priceindexstart, pih.percwashlog pihpercent,
       cry.code currencycode, cry.description currencydesc, cry.decimals, cry.invoiceamountdecimals, lan.code languagecode,
       gpl.code gplcode, gpl.description gpldesc, gwp.price, 0 volumeprice, null soil
  from contract con
       join priceindex pia on con.agreedpriceindex_id = pia.priceindex_id
       join priceindexhistory pih on con.agreedpriceindex_id = pih.priceindex_id
       join status st on con.status_id = st.status_id and st.statustype = 'CO' and st.code = '20'
       join contractpricelist cpl
            join generalpricelist gpl
                 join generalwashprice gwp
                      join product pr on gwp.product_id = pr.product_id
                      join sizedefinition sd on gwp.sizedefinition_id = sd.sizedefinition_id
                      join finishingmethod fm on gwp.finishingmethod_id = fm.finishingmethod_id
                 on gpl.generalpricelist_id = gwp.generalpricelist_id and gwp.pricetype = 1
                 join currency cry on gpl.currency_id = cry.currency_id
            on cpl.generalpricelist_id = gpl.generalpricelist_id and gpl.pricetype = 1 and gpl.usage = 1 and gpl.active = 'Y'
       on con.contract_id = cpl.contract_id and cpl.agreed = 'Y' and cpl.pricetype = 1
       , languages lan
 where (con.terminationdate = getabsmaxdate()
       or
       (con.terminationdate < getabsmaxdate() and con.enddate > con.nextschedulepriceincrease and con.updateevery <> 0)
       )
   and pih.startdate = (select max(pih2.startdate)
                          from priceindexhistory pih2
                         where con.agreedpriceindex_id = pih2.priceindex_id
                           and con.nextschedulepriceincrease >= pih2.startdate)
   and cpl.startdate <= con.nextschedulepriceincrease
   and cpl.enddate > con.nextschedulepriceincrease
   and gwp.startdate = (select max(gwp2.startdate)
                          from generalwashprice gwp2
                         where gwp2.generalpricelist_id = gwp.generalpricelist_id
                           and gwp2.pricetype = 1
                           and gwp2.product_id = gwp.product_id
                           and gwp2.sizedefinition_id = gwp.sizedefinition_id
                           and gwp2.finishingmethod_id = gwp.finishingmethod_id
                           and gwp2.startdate <= con.nextschedulepriceincrease)
 union all
select 'N' agreed, con.code contractcode, con.description contractdesc, con.startdate, con.enddate, con.nextschedulepriceincrease,
       pr.code productcode, pr.typeofmerchandise, sd.code sizecode, fm.code finishcode,
       (select psz.sequencenumber
          from productsize psz
         where psz.product_id = pr.product_id
           and psz.sizedefinition_id = sd.sizedefinition_id) size_sequence,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdesc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc,
       (select fmd.description
          from finishingmethod_desc fmd
         where fmd.finishingmethod_id = fm.finishingmethod_id
           and fmd.language_id = lan.language_id) finishdesc,
       pina.code priceindexcode, pina.description priceindexdesc, pinh.startdate priceindexstart, pinh.percwashlog pihpercent,
       cry.code currencycode, cry.description currencydesc, cry.decimals, cry.invoiceamountdecimals, lan.code languagecode,
       gpl.code gplcode, gpl.description gpldesc, gwp.price, 0 volumeprice, null soil
  from contract con
       join priceindex pina on con.notagreedpriceindex_id = pina.priceindex_id
       join priceindexhistory pinh on con.notagreedpriceindex_id = pinh.priceindex_id
       join status st on con.status_id = st.status_id and st.statustype = 'CO' and st.code = '20'
       join contractpricelist cpl
            join generalpricelist gpl
                 join generalwashprice gwp
                      join product pr on gwp.product_id = pr.product_id
                      join sizedefinition sd on gwp.sizedefinition_id = sd.sizedefinition_id
                      join finishingmethod fm on gwp.finishingmethod_id = fm.finishingmethod_id
                 on gpl.generalpricelist_id = gwp.generalpricelist_id and gwp.pricetype = 1
                 join currency cry on gpl.currency_id = cry.currency_id
            on cpl.generalpricelist_id = gpl.generalpricelist_id and gpl.pricetype = 1 and gpl.usage = 1 and gpl.active = 'Y'
       on con.contract_id = cpl.contract_id and cpl.agreed = 'N' and cpl.pricetype = 1
       , languages lan
 where (con.terminationdate = getabsmaxdate()
       or
       (con.terminationdate < getabsmaxdate() and con.enddate > con.nextschedulepriceincrease and con.updateevery <> 0)
       )
   and con.allownotagreedpricelists = 'Y'
   and pinh.startdate = (select max(pinh2.startdate)
                           from priceindexhistory pinh2
                          where con.notagreedpriceindex_id = pinh2.priceindex_id
                            and con.nextschedulepriceincrease >= pinh2.startdate)
   and cpl.startdate <= con.nextschedulepriceincrease
   and cpl.enddate > con.nextschedulepriceincrease
   and gwp.startdate = (select max(gwp2.startdate)
                          from generalwashprice gwp2
                         where gwp2.generalpricelist_id = gwp.generalpricelist_id
                           and gwp2.pricetype = 1
                           and gwp2.product_id = gwp.product_id
                           and gwp2.sizedefinition_id = gwp.sizedefinition_id
                           and gwp2.finishingmethod_id = gwp.finishingmethod_id
                           and gwp2.startdate <= con.nextschedulepriceincrease)
/

  CREATE OR REPLACE VIEW "V_CONTRACTPRICEUPDATE_WASHCOG" ("AGREED", "CONTRACTCODE", "CONTRACTDESC", "STARTDATE", "ENDDATE", "NEXTSCHEDULEPRICEINCREASE", "PRODUCTCODE", "TYPEOFMERCHANDISE", "SIZECODE", "FINISHCODE", "SIZE_SEQUENCE", "PRODUCTDESC", "SIZEDESC", "FINISHDESC", "PRICEINDEXCODE", "PRICEINDEXDESC", "PRICEINDEXSTART", "PIHPERCENT", "CURRENCYCODE", "CURRENCYDESC", "DECIMALS", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE", "GPLCODE", "GPLDESC", "PRICE", "VOLUMEPRICE", "SOIL") AS 
  select 'Y' agreed, con.code contractcode, con.description contractdesc, con.startdate, con.enddate, con.nextschedulepriceincrease,
       pr.code productcode, pr.typeofmerchandise, sd.code sizecode, fm.code finishcode,
       (select psz.sequencenumber
          from productsize psz
         where psz.product_id = pr.product_id
           and psz.sizedefinition_id = sd.sizedefinition_id) size_sequence,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdesc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc,
       (select fmd.description
          from finishingmethod_desc fmd
         where fmd.finishingmethod_id = fm.finishingmethod_id
           and fmd.language_id = lan.language_id) finishdesc,
       pia.code priceindexcode, pia.description priceindexdesc, pih.startdate priceindexstart, pih.percwashcog pihpercent,
       cry.code currencycode, cry.description currencydesc, cry.decimals, cry.invoiceamountdecimals, lan.code languagecode,
       gpl.code gplcode, gpl.description gpldesc, gwp.price, 0 volumeprice, null soil
  from contract con
       join priceindex pia on con.agreedpriceindex_id = pia.priceindex_id
       join priceindexhistory pih on con.agreedpriceindex_id = pih.priceindex_id
       join status st on con.status_id = st.status_id and st.statustype = 'CO' and st.code = '20'
       join contractpricelist cpl
            join generalpricelist gpl
                 join generalwashprice gwp
                      join product pr on gwp.product_id = pr.product_id
                      join sizedefinition sd on gwp.sizedefinition_id = sd.sizedefinition_id
                      join finishingmethod fm on gwp.finishingmethod_id = fm.finishingmethod_id
                 on gpl.generalpricelist_id = gwp.generalpricelist_id and gwp.pricetype = 1
                 join currency cry on gpl.currency_id = cry.currency_id
            on cpl.generalpricelist_id = gpl.generalpricelist_id and gpl.pricetype = 1 and gpl.usage = 1 and gpl.active = 'Y'
       on con.contract_id = cpl.contract_id and cpl.agreed = 'Y' and cpl.pricetype = 1
       , languages lan
 where (con.terminationdate = getabsmaxdate()
       or
       (con.terminationdate < getabsmaxdate() and con.enddate > con.nextschedulepriceincrease and con.updateevery <> 0)
       )
   and pih.startdate = (select max(pih2.startdate)
                          from priceindexhistory pih2
                         where con.agreedpriceindex_id = pih2.priceindex_id
                           and con.nextschedulepriceincrease >= pih2.startdate)
   and cpl.startdate <= con.nextschedulepriceincrease
   and cpl.enddate > con.nextschedulepriceincrease
   and gwp.startdate = (select max(gwp2.startdate)
	                        from generalwashprice gwp2
                         where gwp2.generalpricelist_id = gwp.generalpricelist_id
                           and gwp2.pricetype = 2
                           and gwp2.product_id = gwp.product_id
                           and gwp2.sizedefinition_id = gwp.sizedefinition_id
                           and gwp2.finishingmethod_id = gwp.finishingmethod_id
                           and gwp2.startdate <= con.nextschedulepriceincrease)
 union all
select 'N' agreed, con.code contractcode, con.description contractdesc, con.startdate, con.enddate, con.nextschedulepriceincrease,
       pr.code productcode, pr.typeofmerchandise, sd.code sizecode, fm.code finishcode,
       (select psz.sequencenumber
          from productsize psz
         where psz.product_id = pr.product_id
           and psz.sizedefinition_id = sd.sizedefinition_id) size_sequence,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdesc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc,
       (select fmd.description
          from finishingmethod_desc fmd
         where fmd.finishingmethod_id = fm.finishingmethod_id
           and fmd.language_id = lan.language_id) finishdesc,
       pina.code priceindexcode, pina.description priceindexdesc, pinh.startdate priceindexstart, pinh.percwashcog pihpercent,
       cry.code currencycode, cry.description currencydesc, cry.decimals, cry.invoiceamountdecimals, lan.code languagecode,
       gpl.code gplcode, gpl.description gpldesc, gwp.price, 0 volumeprice, null soil
  from contract con
       join priceindex pina on con.notagreedpriceindex_id = pina.priceindex_id
       join priceindexhistory pinh on con.notagreedpriceindex_id = pinh.priceindex_id
       join status st on con.status_id = st.status_id and st.statustype = 'CO' and st.code = '20'
       join contractpricelist cpl
            join generalpricelist gpl
                 join generalwashprice gwp
                      join product pr on gwp.product_id = pr.product_id
                      join sizedefinition sd on gwp.sizedefinition_id = sd.sizedefinition_id
                      join finishingmethod fm on gwp.finishingmethod_id = fm.finishingmethod_id
                 on gpl.generalpricelist_id = gwp.generalpricelist_id and gwp.pricetype = 1
                 join currency cry on gpl.currency_id = cry.currency_id
            on cpl.generalpricelist_id = gpl.generalpricelist_id and gpl.pricetype = 1 and gpl.usage = 1 and gpl.active = 'Y'
       on con.contract_id = cpl.contract_id and cpl.agreed = 'N' and cpl.pricetype = 1
       , languages lan
 where (con.terminationdate = getabsmaxdate()
       or
       (con.terminationdate < getabsmaxdate() and con.enddate > con.nextschedulepriceincrease and con.updateevery <> 0)
       )
   and con.allownotagreedpricelists = 'Y'
   and pinh.startdate = (select max(pinh2.startdate)
                           from priceindexhistory pinh2
                          where con.notagreedpriceindex_id = pinh2.priceindex_id
                            and con.nextschedulepriceincrease >= pinh2.startdate)
   and cpl.startdate <= con.nextschedulepriceincrease
   and cpl.enddate > con.nextschedulepriceincrease
   and gwp.startdate = (select max(gwp2.startdate)
	                        from generalwashprice gwp2
                         where gwp2.generalpricelist_id = gwp.generalpricelist_id
                           and gwp2.pricetype = 1
                           and gwp2.product_id = gwp.product_id
                           and gwp2.sizedefinition_id = gwp.sizedefinition_id
                           and gwp2.finishingmethod_id = gwp.finishingmethod_id
                           and gwp2.startdate <= con.nextschedulepriceincrease)
/

  CREATE OR REPLACE VIEW "V_CONTRACTPRICEUPDATE_WEIGHT" ("AGREED", "CONTRACTCODE", "CONTRACTDESC", "STARTDATE", "ENDDATE", "NEXTSCHEDULEPRICEINCREASE", "PRODUCTCODE", "TYPEOFMERCHANDISE", "SIZECODE", "FINISHCODE", "SIZE_SEQUENCE", "PRODUCTDESC", "SIZEDESC", "FINISHDESC", "PRICEINDEXCODE", "PRICEINDEXDESC", "PRICEINDEXSTART", "PIHPERCENT", "CURRENCYCODE", "CURRENCYDESC", "DECIMALS", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE", "GPLCODE", "GPLDESC", "PRICE", "VOLUMEPRICE", "SOIL") AS 
  select 'Y' agreed, con.code contractcode, con.description contractdesc, con.startdate, con.enddate, con.nextschedulepriceincrease,
       (select wcy.code
          from weighingcategory wcy
         where wcy.weighingcategory_id = gwgp.weighingcategory_id) productcode,
       null typeofmerchandise, null sizecode, null finishcode,
       0 size_sequence,
       (select wcd.description
          from weighingcategory_desc wcd
         where wcd.weighingcategory_id = gwgp.weighingcategory_id
           and wcd.language_id = lan.language_id) productdesc,
       null sizedesc,
       null finishdesc,
       pia.code priceindexcode, pia.description priceindexdesc, pih.startdate priceindexstart, pih.percweight pihpercent,
       cry.code currencycode, cry.description currencydesc, cry.decimals, cry.invoiceamountdecimals, lan.code languagecode,
       gpl.code gplcode, gpl.description gpldesc, gwgp.price, 0 volumeprice, gwgp.soil
  from contract con
       join priceindex pia on con.agreedpriceindex_id = pia.priceindex_id
       join priceindexhistory pih on con.agreedpriceindex_id = pih.priceindex_id
       join status st on con.status_id = st.status_id and st.statustype = 'CO' and st.code = '20'
       join contractpricelist cpl
            join generalpricelist gpl
                 join generalweightprice gwgp on gpl.generalpricelist_id = gwgp.generalpricelist_id
                 join currency cry on gpl.currency_id = cry.currency_id
            on cpl.generalpricelist_id = gpl.generalpricelist_id and gpl.pricetype = 5 and gpl.usage = 1 and gpl.active = 'Y'
       on con.contract_id = cpl.contract_id and cpl.agreed = 'Y' and cpl.pricetype = 5
       , languages lan
 where (con.terminationdate = getabsmaxdate()
       or
       (con.terminationdate < getabsmaxdate() and con.enddate > con.nextschedulepriceincrease and con.updateevery <> 0)
       )
   and pih.startdate = (select max(pih2.startdate)
                          from priceindexhistory pih2
                         where con.agreedpriceindex_id = pih2.priceindex_id
                           and con.nextschedulepriceincrease >= pih2.startdate)
   and cpl.startdate <= con.nextschedulepriceincrease
   and cpl.enddate > con.nextschedulepriceincrease
   and gwgp.startdate = (select max(gwgp2.startdate)
	                         from generalweightprice gwgp2
                          where gwgp2.generalpricelist_id = gwgp.generalpricelist_id
                            and gwgp2.weighingcategory_id = gwgp.weighingcategory_id
                            and gwgp2.soil = gwgp.soil
                            and gwgp2.startdate <= con.nextschedulepriceincrease)
 union all
select 'N' agreed, con.code contractcode, con.description contractdesc, con.startdate, con.enddate, con.nextschedulepriceincrease,
       (select wcy.code
          from weighingcategory wcy
         where wcy.weighingcategory_id = gwgp.weighingcategory_id) productcode,
       null typeofmerchandise, null sizecode, null finishcode,
       0 size_sequence,
       (select wcd.description
          from weighingcategory_desc wcd
         where wcd.weighingcategory_id = gwgp.weighingcategory_id
           and wcd.language_id = lan.language_id) productdesc,
       null sizedesc,
       null finishdesc,
       pina.code priceindexcode, pina.description priceindexdesc, pinh.startdate priceindexstart, pinh.percweight pihpercent,
       cry.code currencycode, cry.description currencydesc, cry.decimals, cry.invoiceamountdecimals, lan.code languagecode,
       gpl.code gplcode, gpl.description gpldesc, gwgp.price, 0 volumeprice, gwgp.soil
  from contract con
       join priceindex pina on con.notagreedpriceindex_id = pina.priceindex_id
       join priceindexhistory pinh on con.notagreedpriceindex_id = pinh.priceindex_id
       join status st on con.status_id = st.status_id and st.statustype = 'CO' and st.code = '20'
       join contractpricelist cpl
            join generalpricelist gpl
                 join generalweightprice gwgp on gpl.generalpricelist_id = gwgp.generalpricelist_id
                 join currency cry on gpl.currency_id = cry.currency_id
            on cpl.generalpricelist_id = gpl.generalpricelist_id and gpl.pricetype = 5 and gpl.usage = 1 and gpl.active = 'Y'
       on con.contract_id = cpl.contract_id and cpl.agreed = 'N' and cpl.pricetype = 5
       , languages lan
 where (con.terminationdate = getabsmaxdate()
       or
       (con.terminationdate < getabsmaxdate() and con.enddate > con.nextschedulepriceincrease and con.updateevery <> 0)
       )
   and con.allownotagreedpricelists = 'Y'
   and pinh.startdate = (select max(pinh2.startdate)
                           from priceindexhistory pinh2
                          where con.notagreedpriceindex_id = pinh2.priceindex_id
                            and con.nextschedulepriceincrease >= pinh2.startdate)
   and cpl.startdate <= con.nextschedulepriceincrease
   and cpl.enddate > con.nextschedulepriceincrease
   and gwgp.startdate = (select max(gwgp2.startdate)
	                         from generalweightprice gwgp2
                          where gwgp2.generalpricelist_id = gwgp.generalpricelist_id
                            and gwgp2.weighingcategory_id = gwgp.weighingcategory_id
                            and gwgp2.soil = gwgp.soil
                            and gwgp2.startdate <= con.nextschedulepriceincrease)
/

  CREATE OR REPLACE VIEW "V_COSTCENTERINVOICELINE" ("INVOICEDATE", "INVOICENUMBER", "LINENUMBER", "INVOICELINETYPE", "INVOICELINETYPEDESC", "CODE", "TAXCODE", "DESCRIPTION", "ADJUSTEDAMOUNT", "ADJUSTEDPRICE", "ADJUSTMENTBILLEDQTY", "EXTEND", "AMOUNT", "DISCOUNTPERCENTAGE", "PRICE", "BILLEDQTY", "TAXGROUPCODE", "TAXTYPE", "SUBJECTTOMINIMUM", "TURNOVERGROUPCODE", "TURNOVERGROUPDESCRIPTION", "INVOICELINESUBTYPE", "PRODUCTGROUPCODE", "PRODUCTGROUPDESCRIPTION", "PRODUCTSHORTDESCRIPTION", "SHORTDESCRIPTION", "SIZECODE", "SIZEDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "INVOICEQTYCOLUMN", "INVENTORYQTY", "DELIVEREDQTY", "ABUSEDQUANTITY", "SOILQUANTITY", "SOILCOUNTMETHOD", "BILLINGMETHOD", "WEARERNUMBER", "WEARERNAME", "WEARERADMINNR", "WEARERBANK", "WEARERLOCKER", "TRANSACTIONTYPE", "TRANSACTIONDATE", "PERCENTAGE", "SYSTEMUSER_ID", "TIMESTAMP", "INVOICELINE_ID", "REMARK", "LANGUAGECODE", "INVOICEHEADER_ID", "OVERAMOUNT", "COSTCENTER_CODE", "COSTCENTER_DESCRIPTION", "COSTCENTERINVOICELINE_QUANTITY", "COSTCENTERINVOICELINE_AMOUNT", "COSTCENTER_LINK_ID", "REGISTRATIONUNITDESCRIPTION", "SEQUENCENUMBER", "TOTALAMOUNTEXCLVAT", "SUBTYPE_DESC", "COSTCENTER_PONUMBER") AS 
  select /*version 2.1*/
       ih.invoicedate, ih.invoicenumber, il.linenumber,
       (select ilt.type from invoicelinetype ilt where il.invoicelinetype_id = ilt.invoicelinetype_id) invoicelinetype,
       (select iltd.description
          from invoicelinetype_desc iltd
         where iltd.invoicelinetype_id = il.invoicelinetype_id
           and iltd.language_id = lan.language_id) invoicelinetypedesc, il.code,
       cast(fsget_taxcode(ih.invoicenumber, il.linenumber) as varchar2(255)) taxcode, il.description,
       il.adjustedamount, il.adjustedprice, il.adjustmentbilledqty, il.extend, il.amount,
       il.discountpercentage, il.price, il.billedqty, il.taxgroupcode, il.taxtype, il.subjecttominimum,
       (select tg.code from turnovergroup tg where il.turnovergroup_id = tg.turnovergroup_id) turnovergroupcode,
       (select tgd.description
          from turnovergroup_desc tgd
         where tgd.turnovergroup_id = il.turnovergroup_id
           and tgd.language_id = lan.language_id) turnovergroupdescription,
       il.invoicelinesubtype, ilp.productgroupcode, ilp.productgroupdescription, ilp.productshortdescription,
       cast(fsget_code(ih.invoicenumber, il.linenumber) as varchar2(255)) shortdescription, ilp.sizecode,
       ilp.sizedescription, ilp.finishingmethodcode, ilp.finishingmethoddescription, ilp.invoiceqtycolumn,
       ilp.inventoryqty, ilp.deliveredqty, ilp.abusedquantity, ilp.soilquantity, ilp.soilcountmethod,
       ilp.billingmethod, ilp.wearernumber, ilp.wearername, ilp.weareradminnr, ilp.wearerbank, ilp.wearerlocker,
       ilv.transactiontype, ilv.transactiondate, ilv.percentage, il.systemuser_id, il.timestamp,
       il.invoiceline_id, il.remark, lan.code languagecode, il.invoiceheader_id, ilv.overamount,
       cc.code costcenter_code, cc.description costcenter_description,
       coalesce(ccil.quantity, ilv.overamount, il.billedqty) costcenterinvoiceline_quantity,
       coalesce(ccil.amount, il.amount) costcenterinvoiceline_amount, ccil.costcenter_link_id,
       (select pd.registrationunitdescription
          from product_link_desc pd
         where pd.product_link_id = ilp.product_link_id
           and pd.language_id = lan.language_id) registrationunitdescription,
       (select pilt.sequencenumber
          from plantinvoicelinetype pilt, businessunit bu
         where ih.invoicebusinessunit_id = bu.businessunit_id
           and bu.plant_id = pilt.plant_id
           and pilt.invoicelinetype_id = il.invoicelinetype_id) sequencenumber,
       nvl((select sum(ccil2.amount)
              from invoiceline il2, costcenterinvoiceline ccil2
             where il2.invoiceline_id = ccil2.invoiceline_id
               and ccil.costcenter_link_id = ccil2.costcenter_link_id
               and il2.invoiceheader_id = ih.invoiceheader_id
               and il2.invoicelinetype_id = (select ilt.invoicelinetype_id
                                               from invoicelinetype ilt
                                              where ilt.type <> 18
                                                and il2.invoicelinetype_id = ilt.invoicelinetype_id
                                                and ccil2.amount <> 0)), 0) totalamountexclvat,
       (select ilstd.description
          from invoicelinesubtype ilst, invoicelinesubtype_desc ilstd
         where ilst.invoicelinetype_id = il.invoicelinetype_id
           and ilst.subtype = il.invoicelinesubtype
           and ilstd.invoicelinesubtype_id = ilst.invoicelinesubtype_id
           and ilstd.language_id = lan.language_id) subtype_desc,
       (select coc.ponumber from costcenter coc where coc.costcenter_id = ccil.costcenter_link_id) costcenter_ponumber
  from invoiceline il
       left join costcenterinvoiceline ccil
            join costcenter_link cc on ccil.costcenter_link_id = cc.costcenter_link_id
       on il.invoiceline_id = ccil.invoiceline_id
       left join invoicelineproduct ilp on il.invoiceline_id = ilp.invoiceline_id
       left join invoicelinevarious ilv on il.invoiceline_id = ilv.invoiceline_id
       join invoiceheader ih on il.invoiceheader_id = ih.invoiceheader_id
       cross join languages lan
 where ih.documenttype = 1
/

  CREATE OR REPLACE VIEW "V_COSTREPORTINFOHELP" ("INVOICELINE_ID", "COSTCENTER_LINK_ID", "QUANTITY") AS 
  select CCIL.INVOICELINE_ID, CCIL.COSTCENTER_LINK_ID, sum(CCIL.QUANTITY) QUANTITY
from COSTCENTERINVOICELINE CCIL
group by CCIL.INVOICELINE_ID, CCIL.COSTCENTER_LINK_ID
/

  CREATE OR REPLACE VIEW "V_CUSTOMERINROUTES" ("CUSTOMER_ID", "ROUTENUMBER", "STOPNUMBER", "STOPTYPE", "ROUTE_ID", "ROUTESTOP_ID", "DRIVINGDAY_ID", "ROUTE_DESC") AS 
  select rs.customer_id
, r.routenumber, rs.stopnumber, rs.stoptype, r.route_id, rs.routestop_id, r.drivingday_id
, r.description Route_desc
from route r, routestop rs
where rs.route_id = r.route_id
/

  CREATE OR REPLACE VIEW "V_CUSTOMERSPERBUSINESSUNITDP" ("BUSINESSUNIT_ID", "CUSTOMER_ID") AS 
  select defaultbusinessunit_id, customer_id
	from customer
union
select processbusinessunit_id, customer_id
	from customeractivities
/

  CREATE OR REPLACE VIEW "V_DECREASEINVANALYSIS_1" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DATEACTIVE", "TOTALCIRCINV", "CNTCIRCINV", "CIRCINVWEEK", "ADDITION", "DELETIONS", "REPORTPARAM_ID") AS 
  select cu.customernumber, cu.name customername, cu.dateactive,
coalesce(  (select sum(sqii1.totalcircinv)
     from statusquoheader sqh1, sqitemincirculation sqii1
     where sqh1.statusquoheader_id = sqii1.statusquoheader_id
       and sqii1.customer_link_id = cu.customer_id
       and sqh1.processbusinessunit_id = CASTVARCHARASNUMBER(rp.string_value)
       and sqh1.statusquodate between rp.date_value1 and rp.date_value2), 0) totalcircinv,
coalesce(  (select count(distinct sqh1.week)
     from statusquoheader sqh1, sqitemincirculation sqii1
     where sqh1.statusquoheader_id = sqii1.statusquoheader_id
       and sqii1.customer_link_id = cu.customer_id
       and sqh1.statusquodate between rp.date_value1 and rp.date_value2), 0) cntcircinv,
   sum(sqii.totalcircinv)    circinvweek,
coalesce( (select sum(sa.variationtotalcircinv)
     from sqitemincirculation sa, statusquoheader sha
     where sa.statusquoheader_id = sha.statusquoheader_id
       and sa.variationtotalcircinv > 0
       and sa.customer_link_id = cu.customer_id
       and sha.processbusinessunit_id = CASTVARCHARASNUMBER(rp.string_value)
       and sha.year = rp.number_value3
       and sha.week = rp.number_value4), 0) addition,
coalesce( (select sum(-sa1.variationtotalcircinv)
     from sqitemincirculation sa1, statusquoheader sha1
     where sa1.statusquoheader_id = sha1.statusquoheader_id
       and sa1.variationtotalcircinv < 0
       and sa1.customer_link_id = cu.customer_id
       and sha1.processbusinessunit_id = CASTVARCHARASNUMBER(rp.string_value)
       and sha1.year = rp.number_value3
       and sha1.week = rp.number_value4), 0) deletions,
  rp.reportparam_id
from statusquoheader sqh, sqitemincirculation sqii, customer cu,
  reportparam rp
where sqh.statusquoheader_id = sqii.statusquoheader_id
  and sqii.customer_link_id = cu.customer_id
  and cu.active = 'Y'
  and trunc(sysdate) between cu.dateactive and cu.dateinactive
  and rp.number_value = 1
  and cu.customernumber between rp.number_value5 and rp.number_value6
  and sqh.year = rp.number_value3 and sqh.week = rp.number_value4
  and sqh.processbusinessunit_id = CASTVARCHARASNUMBER(rp.string_value)
and sqh.subtype in (0, 2)
group by  cu.customernumber, cu.name, cu.dateactive, rp.reportparam_id, cu.customer_id,
  rp.number_value, rp.date_value1, rp.date_value2, rp.number_value3, rp.number_value4, rp.string_value
/

  CREATE OR REPLACE VIEW "V_DECREASEINVANALYSIS_2" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DATEACTIVE", "TOTALCIRCINV", "CNTCIRCINV", "CIRCINVWEEK", "ADDITION", "DELETIONS", "REPORTPARAM_ID") AS 
  select cu.customernumber, cu.name customername, cu.dateactive,
coalesce(  (select sum(sqii1.totalcircinv)
     from statusquoheader sqh1, sqitemincirculation sqii1
     where sqh1.statusquoheader_id = sqii1.statusquoheader_id
       and sqii1.customer_link_id = cu.customer_id
       and sqh1.processbusinessunit_id = CASTVARCHARASNUMBER(rp.string_value)
       and sqh1.statusquodate between rp.date_value1 and rp.date_value2), 0) totalcircinv,
coalesce(  (select count(distinct sqh1.week)
     from statusquoheader sqh1, sqitemincirculation sqii1
     where sqh1.statusquoheader_id = sqii1.statusquoheader_id
       and sqii1.customer_link_id = cu.customer_id
       and sqh1.statusquodate between rp.date_value1 and rp.date_value2), 0) cntcircinv,
   sum(sqii.totalcircinv)    circinvweek,
coalesce( (select sum(sa.variationtotalcircinv)
     from sqitemincirculation sa, statusquoheader sha
     where sa.statusquoheader_id = sha.statusquoheader_id
       and sa.variationtotalcircinv > 0
       and sa.customer_link_id = cu.customer_id
       and sha.processbusinessunit_id = CASTVARCHARASNUMBER(rp.string_value)
       and sha.year = rp.number_value3
       and sha.week = rp.number_value4), 0) addition,
coalesce( (select sum(-sa1.variationtotalcircinv)
     from sqitemincirculation sa1, statusquoheader sha1
     where sa1.statusquoheader_id = sha1.statusquoheader_id
       and sa1.variationtotalcircinv < 0
       and sa1.customer_link_id = cu.customer_id
       and sha1.processbusinessunit_id = CASTVARCHARASNUMBER(rp.string_value)
       and sha1.year = rp.number_value3
       and sha1.week = rp.number_value4), 0) deletions,
  rp.reportparam_id
from statusquoheader sqh, sqitemincirculation sqii, customer cu,
  reportparam rp
where sqh.statusquoheader_id = sqii.statusquoheader_id
  and sqii.customer_link_id = cu.customer_id
  and cu.active = 'Y'
  and trunc(sysdate) between cu.dateactive and cu.dateinactive
  and rp.number_value = 2
  and cu.customernumber between rp.number_value5 and rp.number_value6
  and sqh.year = rp.number_value3 and sqh.week = rp.number_value4
  and sqh.processbusinessunit_id = CASTVARCHARASNUMBER(rp.string_value)
and sqh.subtype in (0, 2)
group by  cu.customernumber, cu.name, cu.dateactive, rp.reportparam_id, cu.customer_id,
  rp.number_value, rp.date_value1, rp.date_value2, rp.number_value3, rp.number_value4, rp.string_value
/

  CREATE OR REPLACE VIEW "V_DECREASEINVANALYSIS_3" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DATEACTIVE", "TOTALCIRCINV", "CNTCIRCINV", "CIRCINVWEEK", "ADDITION", "DELETIONS", "REPORTPARAM_ID") AS 
  select cu.customernumber, cu.name customername, cu.dateactive,
coalesce(  (select sum(sqii1.totalcircinv)
     from statusquoheader sqh1, sqitemincirculation sqii1
     where sqh1.statusquoheader_id = sqii1.statusquoheader_id
       and sqii1.customer_link_id = cu.customer_id
       and sqh1.processbusinessunit_id = CASTVARCHARASNUMBER(rp.string_value)
       and sqh1.statusquodate between rp.date_value1 and rp.date_value2), 0) totalcircinv,
coalesce(  (select count(distinct sqh1.week)
     from statusquoheader sqh1, sqitemincirculation sqii1
     where sqh1.statusquoheader_id = sqii1.statusquoheader_id
       and sqii1.customer_link_id = cu.customer_id
       and sqh1.statusquodate between rp.date_value1 and rp.date_value2), 0) cntcircinv,
   sum(sqii.totalcircinv)    circinvweek,
coalesce( (select sum(sa.variationtotalcircinv)
     from sqitemincirculation sa, statusquoheader sha
     where sa.statusquoheader_id = sha.statusquoheader_id
       and sa.variationtotalcircinv > 0
       and sa.customer_link_id = cu.customer_id
       and sha.processbusinessunit_id = CASTVARCHARASNUMBER(rp.string_value)
       and sha.year = rp.number_value3
       and sha.week = rp.number_value4), 0) addition,
coalesce( (select sum(-sa1.variationtotalcircinv)
     from sqitemincirculation sa1, statusquoheader sha1
     where sa1.statusquoheader_id = sha1.statusquoheader_id
       and sa1.variationtotalcircinv < 0
       and sa1.customer_link_id = cu.customer_id
       and sha1.processbusinessunit_id = CASTVARCHARASNUMBER(rp.string_value)
       and sha1.year = rp.number_value3
       and sha1.week = rp.number_value4), 0) deletions,
  rp.reportparam_id
from statusquoheader sqh, sqitemincirculation sqii, customer cu,
  reportparam rp
where sqh.statusquoheader_id = sqii.statusquoheader_id
  and sqii.customer_link_id = cu.customer_id
  and cu.active = 'Y'
  and trunc(sysdate) between cu.dateactive and cu.dateinactive
  and rp.number_value = 3
  and cu.customernumber between rp.number_value5 and rp.number_value6
  and sqh.year = rp.number_value3 and sqh.week = rp.number_value4
  and sqh.processbusinessunit_id = CASTVARCHARASNUMBER(rp.string_value)
and sqh.subtype in (0, 2)
group by  cu.customernumber, cu.name, cu.dateactive, rp.reportparam_id, cu.customer_id,
  rp.number_value, rp.date_value1, rp.date_value2, rp.number_value3, rp.number_value4, rp.string_value
/

  CREATE OR REPLACE VIEW "V_DECREASEINVANALYSIS_4" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DATEACTIVE", "TOTALCIRCINV", "CNTCIRCINV", "CIRCINVWEEK", "ADDITION", "DELETIONS", "REPORTPARAM_ID") AS 
  select cu.customernumber, cu.name customername, cu.dateactive,
coalesce(  (select sum(sqii1.totalcircinv)
     from statusquoheader sqh1, sqitemincirculation sqii1
     where sqh1.statusquoheader_id = sqii1.statusquoheader_id
       and sqii1.customer_link_id = cu.customer_id
       and sqh1.processbusinessunit_id = CASTVARCHARASNUMBER(rp.string_value)
       and sqh1.statusquodate between rp.date_value1 and rp.date_value2), 0) totalcircinv,
coalesce(  (select count(distinct sqh1.week)
     from statusquoheader sqh1, sqitemincirculation sqii1
     where sqh1.statusquoheader_id = sqii1.statusquoheader_id
       and sqii1.customer_link_id = cu.customer_id
       and sqh1.statusquodate between rp.date_value1 and rp.date_value2), 0) cntcircinv,
   sum(sqii.totalcircinv)    circinvweek,
coalesce( (select sum(sa.variationtotalcircinv)
     from sqitemincirculation sa, statusquoheader sha
     where sa.statusquoheader_id = sha.statusquoheader_id
       and sa.variationtotalcircinv > 0
       and sa.customer_link_id = cu.customer_id
       and sha.processbusinessunit_id = CASTVARCHARASNUMBER(rp.string_value)
       and sha.year = rp.number_value3
       and sha.week = rp.number_value4), 0) addition,
coalesce( (select sum(-sa1.variationtotalcircinv)
     from sqitemincirculation sa1, statusquoheader sha1
     where sa1.statusquoheader_id = sha1.statusquoheader_id
       and sa1.variationtotalcircinv < 0
       and sa1.customer_link_id = cu.customer_id
       and sha1.processbusinessunit_id = CASTVARCHARASNUMBER(rp.string_value)
       and sha1.year = rp.number_value3
       and sha1.week = rp.number_value4), 0) deletions,
  rp.reportparam_id
from statusquoheader sqh, sqitemincirculation sqii, customer cu,
  reportparam rp
where sqh.statusquoheader_id = sqii.statusquoheader_id
  and sqii.customer_link_id = cu.customer_id
  and cu.active = 'Y'
  and trunc(sysdate) between cu.dateactive and cu.dateinactive
  and rp.number_value = 4
  and cu.customernumber between rp.number_value5 and rp.number_value6
  and sqh.year = rp.number_value3 and sqh.week = rp.number_value4
  and sqh.processbusinessunit_id = CASTVARCHARASNUMBER(rp.string_value)
and sqh.subtype in (0, 2)
group by  cu.customernumber, cu.name, cu.dateactive, rp.reportparam_id, cu.customer_id,
  rp.number_value, rp.date_value1, rp.date_value2, rp.number_value3, rp.number_value4, rp.string_value
/

  CREATE OR REPLACE VIEW "V_DECREASEINVANALYSIS_5" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DATEACTIVE", "TOTALCIRCINV", "CNTCIRCINV", "CIRCINVWEEK", "ADDITION", "DELETIONS", "REPORTPARAM_ID") AS 
  select cu.customernumber, cu.name customername, cu.dateactive,
coalesce(  (select sum(sqii1.totalcircinv)
     from statusquoheader sqh1, sqitemincirculation sqii1
     where sqh1.statusquoheader_id = sqii1.statusquoheader_id
       and sqii1.customer_link_id = cu.customer_id
       and sqh1.processbusinessunit_id = CASTVARCHARASNUMBER(rp.string_value)
       and sqh1.statusquodate between rp.date_value1 and rp.date_value2), 0) totalcircinv,
coalesce(  (select count(distinct sqh1.week)
     from statusquoheader sqh1, sqitemincirculation sqii1
     where sqh1.statusquoheader_id = sqii1.statusquoheader_id
       and sqii1.customer_link_id = cu.customer_id
       and sqh1.statusquodate between rp.date_value1 and rp.date_value2), 0) cntcircinv,
   sum(sqii.totalcircinv)    circinvweek,
coalesce( (select sum(sa.variationtotalcircinv)
     from sqitemincirculation sa, statusquoheader sha
     where sa.statusquoheader_id = sha.statusquoheader_id
       and sa.variationtotalcircinv > 0
       and sa.customer_link_id = cu.customer_id
       and sha.processbusinessunit_id = CASTVARCHARASNUMBER(rp.string_value)
       and sha.year = rp.number_value3
       and sha.week = rp.number_value4), 0) addition,
coalesce( (select sum(-sa1.variationtotalcircinv)
     from sqitemincirculation sa1, statusquoheader sha1
     where sa1.statusquoheader_id = sha1.statusquoheader_id
       and sa1.variationtotalcircinv < 0
       and sa1.customer_link_id = cu.customer_id
       and sha1.processbusinessunit_id = CASTVARCHARASNUMBER(rp.string_value)
       and sha1.year = rp.number_value3
       and sha1.week = rp.number_value4), 0) deletions,
  rp.reportparam_id
from statusquoheader sqh, sqitemincirculation sqii, customer cu,
  reportparam rp
where sqh.statusquoheader_id = sqii.statusquoheader_id
  and sqii.customer_link_id = cu.customer_id
  and cu.active = 'Y'
  and trunc(sysdate) between cu.dateactive and cu.dateinactive
  and rp.number_value = 5
  and cu.customernumber between rp.number_value5 and rp.number_value6
  and sqh.year = rp.number_value3 and sqh.week = rp.number_value4
  and sqh.processbusinessunit_id = CASTVARCHARASNUMBER(rp.string_value)
and sqh.subtype in (0, 2)
group by  cu.customernumber, cu.name, cu.dateactive, rp.reportparam_id, cu.customer_id,
  rp.number_value, rp.date_value1, rp.date_value2, rp.number_value3, rp.number_value4, rp.string_value
/

  CREATE OR REPLACE VIEW "V_DELINQUENCYLETTER_IH" ("INVOICEDATE", "CUSTOMER_ID") AS 
  select max(ih.invoicedate) invoicedate, coalesce(ih.deltocustomer_link_id, ih.billtocustomer_link_id) customer_id
from invoiceheader ih, status s
where ih.status_id = s.status_id
  and s.code = '2'
  and ih.documenttype = 2
group by coalesce(ih.deltocustomer_link_id, ih.billtocustomer_link_id)
/

  CREATE OR REPLACE VIEW "V_DELIVERYDETAILSNETID" ("CUSTOMER_ID", "CUSTOMERNUMBER", "NAME", "STREET", "CITY", "STATE", "ZIPCODE", "DEPARTMENTNUMBER", "DEP_DESC", "DISTRIBUTIONPOINTNUMBER", "DP_DESC", "ROOM", "BED", "NETID", "LASTINSCANDATE", "STAY_DESC", "LASTOUTSCANDATE", "BUSINESSUNIT_ID", "DELIVERYDATE", "FLAG_DESC", "PLANT_NAME", "PLANT_STREET", "PLANT_STREET2", "PLANT_CITY", "PLANT_STATE", "PLANT_ZIPCODE", "PLANTPHONE", "PLANTFAX", "PLANTWEBSITE", "LANGUAGE_CODE") AS 
  select  cus.customer_id, cus.customernumber, cus.name,
a.street, a.city, a.state, a.zipcode,
dep.departmentnumber, dep.description Dep_desc,
dp.distributionpointnumber, dp.description Dp_desc,
coalesce(l.bank,'') room, coalesce(l.locker,'') bed,
u.primaryid NetId, u.lastinscandate,
(SELECT B.DESCRIPTION FROM stay_desc B WHERE b.stay_id=u.prevstay_id AND b.language_id=lan.language_id) Stay_desc,
u.lastoutscandate, u.businessunit_id, p.deliverydate,
(select fd.description
from flag f, flag_desc fd
where f.flag_id = fd.flag_id
  and fd.language_id = lan.language_id
  and f.priority = (select min(ff.priority)
       from scan ss, scanflag sf, flag ff
       where d.scantimestamp = ss.scantimestamp
             and ss.transactiontype_id = 2
             and ss.scan_id = sf.scan_id
             and ss.uniqueitem_link_id = u.uniqueitem_id
             and ff.flag_id = sf.flag_id)
  and f.code = (select min(ff.code)
       from scan ss, scanflag sf, flag ff
       where d.scantimestamp = ss.scantimestamp
             and ss.transactiontype_id = 2
             and ss.scan_id = sf.scan_id
             and ss.uniqueitem_link_id = u.uniqueitem_id
             and ff.flag_id = sf.flag_id
             and ff.priority = f.priority)
  and f.flagtype = 1
  ) Flag_desc,
pl.name Plant_name, pl_ad.street Plant_street, pl_ad.street2 Plant_street2, pl_ad.city Plant_city, pl_ad.state Plant_state, pl_ad.zipcode Plant_zipcode,
pl.phoneno PlantPhone, pl.faxno PlantFax, pl.website PlantWebsite,
lan.code Language_code
from uniqueitem u, packingnote p
, plant pl, businessunit bu
, deliveryscan d
  left outer join locker l on d.locker_id=l.locker_id
, distributionpoint dp, department dep, customer cus
, address a, address Pl_ad, languages lan
where d.distributionpoint_link_id=dp.distributionpoint_id and
      dp.department_id = dep.department_id and
      dep.customer_id = cus.customer_id and
      a.address_id = cus.visitaddress_id and
      d.packingnote_id=p.packingnote_id and
      d.uniqueitem_link_id=u.uniqueitem_id and
--      d.customer_link_id=cus.customer_id and
      d.businessunit_id = bu.businessunit_id and
      bu.plant_id=pl.plant_id and
      pl_ad.address_id=pl.address_id
/

  CREATE OR REPLACE VIEW "V_DETAILCOSTSPERPATIENT_PD" ("CUSTOMER_ID", "COSTCENTER_ID", "REPORTPARAM_ID", "PATIENTDAYS", "PATIENTS", "YEAR", "WEEK") AS 
  select c.customer_id, c.costcenter_id,
  rp.reportparam_id,
  sum(p.patientdays) patientdays, sum(p.patients) patients, p.year, p.week
from costcenter c, distributionpoint dp, patientday p, reportparam rp
where c.costcenter_id = dp.costcenter_id
  and dp.distributionpoint_id = p.distributionpoint_link_id
  and p.month = 0--and rp.number_value = p.year
  and p.year >= rp.number_value
  and p.year <= rp.number_value3
  and p.week >= rp.number_value1
  and p.week <= rp.number_value2
  and c.budgetrelevant = 'Y'
group by c.customer_id, c.costcenter_id, rp.reportparam_id, p.year, p.week
/

  CREATE OR REPLACE VIEW "V_DETAILCOSTSPERPATIENT_PD_QF" ("CUSTOMER_ID", "COSTCENTER_ID", "REPORTPARAM_ID", "PATIENTDAYS", "PATIENTS", "YEAR", "WEEK") AS 
  select c.customer_id, c.costcenter_id,
  0 reportparam_id,
  sum(p.patientdays) patientdays, sum(p.patients) patients, p.year, p.week
from costcenter c, distributionpoint dp, patientday p--, reportparam rp
where c.costcenter_id = dp.costcenter_id
  and dp.distributionpoint_id = p.distributionpoint_link_id
  and p.month = 0
  and p.year >= year(sysdate)-2
  and p.year <= year(sysdate)
--  and p.week >= rp.number_value1
--  and p.week <= rp.number_value2
  and c.budgetrelevant = 'Y'
group by c.customer_id, c.costcenter_id--, rp.reportparam_id
, p.year, p.week
/

  CREATE OR REPLACE VIEW "V_DETAILCOSTSPERPATIENT_SUM" ("REPORTPARAM_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CURRENCYCODE", "YEAR", "WEEK", "PRODUCTCODE", "PRODUCTDESC", "COSTCENTER_ID", "CCBUDGETRELEVANT", "COSTCENTERCODE", "COSTCENTERDESC", "INVOICED_AMOUNT", "INVOICED_TAX", "INVOICED_QUANTITY", "INVOICELINETYPE", "INVOICEAMOUNTDECIMALS") AS 
  select rp.reportparam_id,
  cu.customer_id, cu.customernumber, cu.name customername,
  cr.code currencycode,
  cri.year, cri.week,
  il.code productcode, il.description productdesc,
  cc.costcenter_id, cc.budgetrelevant ccbudgetrelevant,
  cc.code costcentercode, cc.description costcenterdesc,
  /*cri.quantity * coalesce(il.price, 0) * coalesce((select max(ilp.pricefactor) from invoicelineproduct ilp where ilp.invoiceline_id=il.invoiceline_id), 1) +
    (case when coalesce(il.price, 0) = 0 then cri.amount else 0 end)*/
     cri.amount invoiced_amount,
  /*coalesce(((cri.quantity * coalesce(il.price, 0) * coalesce((select max(ilp.pricefactor) from invoicelineproduct ilp where ilp.invoiceline_id=il.invoiceline_id), 1)) +
    (case when coalesce(il.price, 0) = 0 then cri.amount else 0 end))*
    (select tg.taxrate from taxgroup tg
      where il.taxgroupcode = tg.code
        and tg.country_id = cu.country_id)/100, 0)*/0 invoiced_tax,
  cri.quantity invoiced_quantity,
  ilt.type invoicelinetype, cr.invoiceamountdecimals
from invoiceheader ih, invoiceline il, costreportinfo cri, costcenter cc,
  customer cu, currency cr,
  status st, invoicelinetype ilt, reportparam rp
where ih.invoiceheader_id = il.invoiceheader_id
  and il.invoiceline_id = cri.invoiceline_id
  and cri.costcenter_link_id = cc.costcenter_id
  and cu.customer_id = ih.deltocustomer_link_id
  and cu.currency_id = cr.currency_id
  and ih.status_id = st.status_id
  and st.code = '2'
  and il.invoicelinetype_id = ilt.invoicelinetype_id
  and cu.customernumber >= rp.number_value8
  and cu.customernumber <= rp.number_value9
  and cc.code >= rp.string_value1
  and cc.code <= rp.string_value2
  and cri.year >= rp.number_value
  and cri.year <= rp.number_value3
  and cri.week >= rp.number_value1
  and cri.week <= rp.number_value2
/

  CREATE OR REPLACE VIEW "V_DETAILCOSTSPERPATIENT_SUM_QF" ("REPORTPARAM_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CURRENCYCODE", "YEAR", "WEEK", "PRODUCTCODE", "PRODUCTDESC", "COSTCENTER_ID", "CCBUDGETRELEVANT", "COSTCENTERCODE", "COSTCENTERDESC", "INVOICED_AMOUNT", "INVOICED_TAX", "INVOICED_QUANTITY", "INVOICELINETYPE", "INVOICEAMOUNTDECIMALS") AS 
  select 0 reportparam_id,
  cu.customer_id, cu.customernumber, cu.name customername,
  cr.code currencycode,
  cri.year, cri.week,
  il.code productcode, il.description productdesc,
  cc.costcenter_id, cc.budgetrelevant ccbudgetrelevant,
  cc.code costcentercode, cc.description costcenterdesc,
  cri.amount invoiced_amount,
  0 invoiced_tax,
  cri.quantity invoiced_quantity,
  ilt.type invoicelinetype, cr.invoiceamountdecimals
from invoiceheader ih, invoiceline il, costreportinfo cri, costcenter cc,
  customer cu, currency cr,
  status st, invoicelinetype ilt--, reportparam rp
where ih.invoiceheader_id = il.invoiceheader_id
  and il.invoiceline_id = cri.invoiceline_id
  and cri.costcenter_link_id = cc.costcenter_id
  and cu.customer_id = ih.deltocustomer_link_id
  and cu.currency_id = cr.currency_id
  and ih.status_id = st.status_id
  and st.code = '2'
  and il.invoicelinetype_id = ilt.invoicelinetype_id
--  and cu.customernumber >= rp.number_value8
--  and cu.customernumber <= rp.number_value9
--  and cc.code >= rp.string_value1
--  and cc.code <= rp.string_value2
  and cri.year >= year(sysdate)-2
  and cri.year <= year(sysdate)
--  and cri.week >= rp.number_value1
--  and cri.week <= rp.number_value2
/

  CREATE OR REPLACE VIEW "V_DEVIATEDCIRCINV" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "CITY", "WEARERNUMBER", "WEARERNAME", "SEQUENCENUMBER", "ACTIVE", "DATEACTIVE", "DATEINACTIVE", "FUNCTIONCODE", "PRODUCTCODE", "SIZECODE", "PRODUCTDESC", "SIZEDESC", "MAXINVENTORY", "CIRCINVENTORY", "QTYTOBERETURNEDREPLACEMENT", "QTYTOBERETURNEDDECREASEMAX", "QTYTOBERETURNED", "WEAREREMPLOYMENT_ID", "PRODUCT_ID", "SIZEDEFINITION_ID", "WEARERDATEINACTIVE", "WEARERINVENTORYDATEINACTIVE", "DEFAULTBUSINESSUNIT_ID", "WEARERINVENTORY_ID", "PROCESSBUSINESSUNIT_ID", "INTERNALPROCESSINGBU_ID", "LANGUAGECODE") AS 
  select /*version 1.0*/
       cu.customernumber, cu.name customername, dep.departmentnumber, dep.description departmentdesc,
       (select vad.city
          from address vad
         where cu.visitaddress_id = vad.address_id) city,
       we.wearernumber, we.fullname wearername, wey.sequencenumber, cu.active,
       cu.dateactive, cu.dateinactive, wef.code functioncode, pr.code productcode, sz.code sizecode,
       (select prd.description
          from product_desc prd
         where prd.product_id = weinv.product_id
           and prd.language_id = lan.language_id) productdesc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = weinv.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc,
       sum(weinv.maxinventory) maxinventory, sum(weinv.circinventory) circinventory,
       sum(weinv.qtytobereturnedreplacement) qtytobereturnedreplacement,
       sum(weinv.qtytobereturneddecreasemax) qtytobereturneddecreasemax,
       coalesce((select count(1)
                   from uniqueitemnonpool uinp
                        join uniqueitem ui on uinp.uniqueitem_id = ui.uniqueitem_id
                        join uniqueitemflag uif
                             join automaticflag afl on uif.flag_id = afl.flag_id
                        on uinp.uniqueitem_id = uif.uniqueitem_id
                  where weinv.wearerinventory_id = uinp.wearerinventory_id
                    and wey.weareremployment_id = uinp.weareremployment_id
                    and ui.replacementworkorder_id is not null
                    and afl.event = 'Flag for return to stock due to manual decrease of max inv'), 0) +
        coalesce((select count(1)
                   from nonuniqueitem nui
                        join automaticflag afl on nui.flag_id = afl.flag_id
                  where weinv.wearerinventory_id = nui.wearerinventory_id
                    and afl.event = 'Flag for return to stock due to manual decrease of max inv'), 0) qtytobereturned,
       wey.weareremployment_id, weinv.product_id, weinv.sizedefinition_id,
       we.dateinactive wearerdateinactive, weinv.dateinactive wearerinventorydateinactive,
       cu.defaultbusinessunit_id, weinv.wearerinventory_id, ca.processbusinessunit_id,
       ca.internalprocessingbu_id, lan.code languagecode
  from wearerinventory weinv
       join weareremployment wey
            left join wearerfunction wef on wey.wearerfunction_id = wef.wearerfunction_id
            join wearer we on wey.wearer_id = we.wearer_id
            join distributionpoint dip
                 join department dep
                      join customer cu
                           join customeractivities ca on cu.customer_id = ca.customer_id
                      on dep.customer_id = cu.customer_id
                 on dip.department_id = dep.department_id
            on wey.distributionpoint_id = dip.distributionpoint_id
       on weinv.weareremployment_id = wey.weareremployment_id
       join product pr
            join productgroup pg on pr.productgroup_id = pg.productgroup_id
       on weinv.product_id = pr.product_id
       join sizedefinition sz on weinv.sizedefinition_id = sz.sizedefinition_id
       cross join languages lan
 where pg.activity_id = ca.activity_id
 group by cu.customernumber, cu.name, cu.visitaddress_id, dep.departmentnumber, dep.description,
          we.wearernumber, we.fullname, we.dateinactive, weinv.dateinactive, wey.sequencenumber,
          wef.code, pr.code, sz.code, wey.weareremployment_id, weinv.product_id,
          weinv.sizedefinition_id, cu.defaultbusinessunit_id, ca.processbusinessunit_id,
          ca.internalprocessingbu_id, lan.language_id, lan.code,
          weinv.wearerinventory_id, cu.active, cu.dateactive, cu.dateinactive
/

  CREATE OR REPLACE VIEW "V_DEVIATEDCIRCINV_AUX" ("OUTSTANDINGQTY", "WEAREREMPLOYMENT_LINK_ID", "PRODUCT_LINK_ID", "SIZEDEFINITION_LINK_ID") AS 
  select /*version 1.0*/
       sum(wokli.quantityordered - wokli.quantityfilled - wokli.quantitycancelled) outstandingqty,
       wok.weareremployment_link_id, wokli.product_link_id, wokli.sizedefinition_link_id
  from workorderline wokli
       join workorder wok
            join status sta on wok.status_id = sta.status_id and sta.statustype = 'WO'
       on wokli.workorder_id = wok.workorder_id
       join reasoncode rc on wokli.reasoncode_id = rc.reasoncode_id
 where sta.code not in ('30', '40')
   and rc.inventorytrigger <> 5
 group by wok.weareremployment_link_id, wokli.product_link_id, wokli.sizedefinition_link_id
/

  CREATE OR REPLACE VIEW "V_EMBLEMHISTORYCC" ("LINETYPE", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DEPARTMENT_LINK_ID", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "WEARERNUMBER", "WEARERNAME", "DISTRIBUTIONPOINT_ID", "CUSTOMER_LINK_ID", "PRODUCTCODE", "PRODUCTDESC", "EMBLEMTEMPLATELINEDESC", "EMBLEMTEMPLATECODE", "EMBLEMTEMPLATEDESC", "SIZECODE", "QUANTITY", "AMOUNT", "UNIQUEITEM_LINK_ID", "EMBLEMSPECIFICATION", "PARENTINVOICEHEADER_ID", "INVOICEHEADER_ID", "LANGUAGECODE", "CC_CODE_DESC") AS 
  select 1 linetype
, f.customernumber, f.name customername, e.departmentnumber, e.description departmentdesc, e.department_link_id
, d.distributionpointnumber, d.description distributionpointdesc, w.wearernumber, w.wearername, d.distributionpoint_id, e.customer_link_id
, (select p.code from product p where a.emblemproduct_id = p.product_id) productcode
, (select pd.description from product_desc pd where a.emblemproduct_id = pd.product_id and pd.language_id = languages.language_id) productdesc
, (select etl.description from emblemtemplateline etl where a.emblemtemplateline_id = etl.emblemtemplateline_id) emblemtemplatelinedesc
, (select et.code from emblemtemplateline etl, emblemtemplate et where a.emblemtemplateline_id = etl.emblemtemplateline_id and etl.emblemtemplate_id = et.emblemtemplate_id) emblemtemplatecode
, (select et.description from emblemtemplateline etl, emblemtemplate et where a.emblemtemplateline_id = etl.emblemtemplateline_id and etl.emblemtemplate_id = et.emblemtemplate_id) emblemtemplatedesc
, (select sd.code from emblemtemplateline emb, sizedefinition sd where a.emblemtemplateline_id = emb.emblemtemplateline_id and emb.sizedefinition_id = sd.sizedefinition_id) sizecode
, a.quantity, a.amount, a.uniqueitem_link_id
, (select bill.emblemspecification from invoiceheader ih, customer bill where ih.invoiceheader_id = a.invoiceheader_id and ih.billtocustomer_link_id = bill.customer_id) emblemspecification
, (select i.parentinvoiceheader_id from invoiceheader i where i.invoiceheader_id = a.invoiceheader_id) parentinvoiceheader_id
, a.invoiceheader_id, languages.code languagecode,
(select coc.code || ' ' || coc.description
from costcenter coc
where coc.costcenter_id in
 coalesce((select cc1.costcenter_id from distributionpoint dp, costcenter cc1 where d.distributionpoint_id = dp.distributionpoint_id
 and dp.costcenter_id = cc1.costcenter_id),
 (select min(cc2.costcenter_id) from costcenter cc2 where f.customer_id = cc2.customer_id ))) cc_code_desc
from emblemhistory a, weareremployment_link w,
 distributionpoint_link d, department_link e, customer_link f, languages
where w.distributionpoint_link_id = d.distributionpoint_link_id--distrib point is taken via weareremployment
and d.department_link_id = e.department_link_id
and e.customer_link_id = f.customer_link_id--and a.status = 0
and a.weareremployment_link_id = w.weareremployment_link_id
union all
select 2 linetype
, f.customernumber, f.name customername, e.departmentnumber, e.description departmentdesc, e.department_link_id
, d.distributionpointnumber, d.description distributionpointdesc, -1 wearernumber, '' wearername, d.distributionpoint_id, e.customer_link_id
, (select p.code from product p where a.emblemproduct_id = p.product_id) productcode
, (select pd.description from product_desc pd where a.emblemproduct_id = pd.product_id and pd.language_id = languages.language_id) productdesc
, (select etl.description from emblemtemplateline etl where a.emblemtemplateline_id = etl.emblemtemplateline_id) emblemtemplatelinedesc
, (select et.code from emblemtemplateline etl, emblemtemplate et where a.emblemtemplateline_id = etl.emblemtemplateline_id and etl.emblemtemplate_id = et.emblemtemplate_id) emblemtemplatecode
, (select et.description from emblemtemplateline etl, emblemtemplate et where a.emblemtemplateline_id = etl.emblemtemplateline_id and etl.emblemtemplate_id = et.emblemtemplate_id) emblemtemplatedesc
, (select sd.code from emblemtemplateline emb, sizedefinition sd where a.emblemtemplateline_id = emb.emblemtemplateline_id and emb.sizedefinition_id = sd.sizedefinition_id) sizecode
, a.quantity, a.amount, a.uniqueitem_link_id
, (select bill.emblemspecification from invoiceheader ih, customer bill where ih.invoiceheader_id = a.invoiceheader_id and ih.billtocustomer_link_id = bill.customer_id) emblemspecification
, (select i.parentinvoiceheader_id from invoiceheader i where i.invoiceheader_id = a.invoiceheader_id) parentinvoiceheader_id
, a.invoiceheader_id, languages.code languagecode,
(select coc.code || ' ' || coc.description
from costcenter coc
where coc.costcenter_id in
 coalesce((select cc1.costcenter_id from distributionpoint dp, costcenter cc1 where d.distributionpoint_id = dp.distributionpoint_id
 and dp.costcenter_id = cc1.costcenter_id),
 (select min(cc2.costcenter_id) from costcenter cc2 where f.customer_id = cc2.customer_id ))) cc_code_desc
from emblemhistory a,
 distributionpoint_link d, department_link e, customer_link f, languages
where a.distributionpoint_link_id = d.distributionpoint_link_id--distrib point is taken via emblemhistory
and d.department_link_id = e.department_link_id
and e.customer_link_id = f.customer_link_id--and a.status = 0
and a.weareremployment_link_id is null
/

  CREATE OR REPLACE VIEW "V_EMBLEMPICKLIST_STOCK" ("BUSINESSUNITCODE", "BUSINESSUNITDESC", "PLANTCODE", "PLANTSTREET", "PLANTZIP", "PLANTCITY", "PLANTPHONE", "PLANTFAX", "STOCKROOMCODE", "STOCKROOMDESC", "ROWCODE", "LOCATIONCODE", "PRODUCT_ID", "SIZEDEFINITION_ID", "STOCKROOM_ID") AS 
  select
  bu.code BusinessunitCode, bu.description BusinessunitDesc,plant.code PlantCode--, plant.name PlantName
  ,addressPlant.Street PlantStreet, addressPlant.Zipcode PlantZip
, addressPlant.City PlantCity, plant.phoneno PlantPhone, plant.faxno PlantFax
, s.code StockroomCode, s.name StockroomDesc
, sl.rowcode, sl.locationcode
, sdi.product_id, sdi.sizedefinition_id---, sdi.customer_id, sdi.customerowned
, s.stockroom_id
from
  stockroom s, stockdefinitionperitem sdi, stockreservationpergrade srg, stockquantity sq, stockroomlocation sl
, businessunit bu, plant, address addressPlant
where
    s.managedbybu_id = bu.businessunit_id
and bu.plant_id = plant.plant_id
    and plant.address_id = addressPlant.Address_Id
and s.stockroom_id = sdi.stockroom_id
        and sdi.stockdefinitionperitem_id = srg.stockdefinitionperitem_id
            and srg.qualitygrade_id = ( select qualitygrade.qualitygrade_id from qualitygrade
                                      where qualitygrade.priority =1)
            and srg.stockreservationpergrade_id = sq.stockreservationpergrade_id
                 and sq.stockroomlocation_id = sl.stockroomlocation_id
/

  CREATE OR REPLACE VIEW "V_EMBLEMPICKLIST_STOCK_USERDEF" ("BUSINESSUNITCODE", "BUSINESSUNITDESC", "PLANTCODE", "PLANTSTREET", "PLANTZIP", "PLANTCITY", "PLANTPHONE", "PLANTFAX", "STOCKROOMCODE", "STOCKROOMDESC", "STOCKROOM_ID") AS 
  select
  bu.code businessunitcode, bu.description businessunitdesc,plant.code plantcode,
  addressplant.street plantstreet, addressplant.zipcode plantzip,
  addressplant.city plantcity, plant.phoneno plantphone, plant.faxno plantfax,
  s.code stockroomcode, s.name stockroomdesc, s.stockroom_id
from stockroom s, businessunit bu, plant, address addressplant
where s.managedbybu_id = bu.businessunit_id
and bu.plant_id = plant.plant_id
and plant.address_id = addressplant.address_id
-- 22-10-2008, RVI - 502536 End
/

  CREATE OR REPLACE VIEW "V_FINISHINGPROGRAMS" ("PLANT_ID", "FINISHPROG") AS 
  select distinct p.plant_id, wp2.code finishprog
from machinewashingprocess mwp join machine m  on mwp.machine_id=m.machine_id join plant p on m.plant_id=p.plant_id inner join machinetype mt on m.machinetype_id=mt.machinetype_id
join washingprocess wp2 on mwp.washingprocess_id= wp2.washingprocess_id where mt.code='3' and m.active='Y'
/

  CREATE OR REPLACE VIEW "V_GARMENTHISTORYCC" ("YEAR", "WEEK", "PRIMARYID", "DISTRIBUTIONPOINT_ID", "CUSTOMER_LINK_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DEPARTMENT_LINK_ID", "WEARERNUMBER", "WEARERNAME", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "QUANTITY", "SALESPRICE", "INVOICEHEADER_ID", "LANGUAGECODE", "DISCOUNTPERCENTAGE", "AMOUNT", "CC_CODE_DESC") AS 
  select
 a.year, a.week, a.primaryid, d.distributionpoint_id, e.customer_link_id,
 e.departmentnumber, e.description departmentdesc, e.department_link_id,
 w.wearernumber, w.wearername,
 p.code productcode,
 (select description from product_link_desc z where z.product_link_id = a.product_link_id
  and z.language_id = languages.language_id) productdesc,
 r.code sizecode, a.quantity, coalesce(a.salesprice, 0) salesprice, a.invoiceheader_id,
 languages.code languagecode,
 a.DiscountPercentage, a.amount,
(SELECT coc.code || ' ' || coc.description
FROM Costcenter coc
WHERE coc.Costcenter_Id IN
 COALESCE((SELECT cc1.Costcenter_Id FROM distributionpoint dp, Costcenter cc1 WHERE d.distributionpoint_id = dp.distributionpoint_id
 AND dp.costcenter_id = cc1.Costcenter_Id),
 (SELECT min(cc2.Costcenter_Id) FROM customer_link cl, Costcenter cc2 WHERE e.customer_link_id = cl.customer_id
 AND cl.customer_id = cc2.customer_id ))) CC_Code_Desc
from garmentsaleshistory a
 left outer join weareremployment_link w on (a.weareremployment_link_id = w.weareremployment_link_id),
 distributionpoint_link d, department_link e, product_link p,  sizedefinition_link r, languages
where a.distributionpoint_link_id = d.distributionpoint_link_id
 and d.department_link_id = e.department_link_id
 and a.product_link_id = p.product_link_id
 and a.sizedefinition_link_id = r.sizedefinition_link_id
 and a.status = 0 -- todo 3876
/

  CREATE OR REPLACE VIEW "V_GARMENTINSURANCERAGGED" ("BU_CODE", "BU_DESC", "SYSTEMUSER_ID", "DATEACTIVE", "DATEINACTIVE", "MAXINVENTORY", "BILLTONR", "BILLTONAME", "DELTONR", "DELTONAME", "GARMENTINSURANCE", "PRODUCTCODE", "SIZECODE", "PRODUCTDESC", "SIZEDESC", "SIZESEQ", "DAMAGEDITEMS", "LOSTITEMS", "REPAIREDITEMS", "REPORTPARAM_ID", "LANGUAGE_CODE") AS 
  select bu.code bu_code, bu.description bu_desc, SU.SystemUser_ID, WI.DateActive, WI.DateInactive, wi.maxinventory,
       deb.customernumber BillToNr, deb.name BillToName, cu.customernumber DelToNr, cu.name DelToName, cu.garmentinsurance,
       pr.code ProductCode, sd.code SizeCode,
       (select prd.description from product_desc prd where prd.product_id = pr.product_id and prd.language_id = lan.language_id) ProductDesc,
       (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sd.sizedefinition_id and sdd.language_id = lan.language_id) SizeDesc,
       (select ps.sequencenumber from productsize ps where ps.product_id = pr.product_id and ps.sizedefinition_id = sd.sizedefinition_id) SizeSeq,
       coalesce((select Sum( OCH.Quantity) From OutOfCirculationHistory OCH, RagReason RR
       Where OCH.Customer_Link_ID = cu.Customer_ID
       And OCH.WearerEmployment_Link_ID = We.WearerEmployment_ID
       And OCH.Product_Link_ID = pr.Product_ID
       And OCH.SizeDefinition_Link_ID = sd.SizeDefinition_ID
       And OCH.RagReason_ID = RR.Ragreason_Id And OCH.Status <> 2 --(Cancelled)
       And rr.processlostitems = 'N' and rr.chargeresidualvalue = 'Y'
       And OCH.OutOfCircDate >= Rp.Date_Value1 And OCH.OutOfCircDate <= Rp.Date_Value2+1
       ), 0) DamagedItems,
       coalesce((select Sum( OCH.Quantity) From OutOfCirculationHistory OCH, RagReason RR
       Where OCH.Customer_Link_ID = cu.Customer_ID
       And OCH.WearerEmployment_Link_ID = We.WearerEmployment_ID
       And OCH.Product_Link_ID = pr.Product_ID
       And OCH.SizeDefinition_Link_ID = sd.SizeDefinition_ID
       And OCH.RagReason_ID = RR.Ragreason_Id And OCH.Status <> 2 --(Cancelled)
       And rr.processlostitems = 'Y' and rr.chargeresidualvalue = 'Y'
       And OCH.OutOfCircDate >= Rp.Date_Value1 And OCH.OutOfCircDate <= Rp.Date_Value2+1
       ), 0) LostItems,
       coalesce((select Sum(RPH.Quantity) From RepairHistory RPH, uniqueitem ui
       Where RPH.Customer_Link_ID = cu.Customer_ID
       And RPH.WearerEmployment_Link_ID = we.WearerEmployment_ID
       And RPH.Product_Link_ID = pr.Product_ID
       and rph.uniqueitem_link_id = ui.uniqueitem_id
       and ui.product_id = pr.product_id
       and ui.sizedefinition_id = sd.sizedefinition_id
       And RPH.Status <> 2 --(Cancelled)
       And RPH.RepairDate >= Rp.Date_Value1 And RPH.RepairDate  <= Rp.Date_Value2+1
       ), 0) RepairedItems,
       rp.reportparam_id, lan.code Language_Code
from WearerInventory WI, Weareremployment WE, product pr, sizedefinition sd, Wearer w,
     BusinessUnit BU, Customer cu, Customer Deb, SystemUser SU, ReportParam RP, Languages Lan
where WI.Weareremployment_Id = we.weareremployment_id and we.wearer_id = w.wearer_id and
      w.Customer_ID = cu.Customer_ID and cu.debtor_id = deb.customer_id and
      wi.product_id = pr.product_id and wi.sizedefinition_id = sd.sizedefinition_id and
      bu.businessunit_id = cu.defaultbusinessunit_id and cu.GarmentInsurance <> 0 and pr.typeofmerchandise = 2 and --Only Garments
      cu.DefaultBusinessUnit_ID in (Select BUUG.BusinessUnit_ID From BusinessUnitsPerUsergroup BUUG Where BUUG.UserGroup_ID = SU.UserGroup_ID)
      and Exists (select 1 from CustomerActivities CA, productgroup pg
         Where CA.Customer_ID = cu.Customer_ID and pg.productgroup_id = pr.productgroup_id
           And CA.Activity_ID = pg.Activity_ID And CA.Processbusinessunit_Id in
           (Select BUUG2.BusinessUnit_ID From BusinessUnitsPerUsergroup BUUG2 Where BUUG2.UserGroup_ID = SU.UserGroup_ID)
                 )
/

  CREATE OR REPLACE VIEW "V_INVOICEAPPENDIXCNTAX" ("INVOICEHEADER_ID", "DESCRIPTION", "AMOUNT", "OVERAMOUNT", "PERCENTAGE") AS 
  select il.invoiceheader_id, il.description, il.amount, ilv.overamount, ilv.percentage
from invoiceline il, invoicelinevarious ilv, invoicelinetype ilt
where il.invoiceline_id = ilv.invoiceline_id and il.invoicelinetype_id = ilt.invoicelinetype_id
      and ilt.type = 18
/

  CREATE OR REPLACE VIEW "V_INVOICEDGARMENTLABELS" ("STATUS", "PROCESSED", "LABELTYPE", "INVOICEHEADER_ID", "CREATIONDATE", "YEAR", "WEEK", "LABELCODE", "LABELDESC", "LABELLAYOUTTYPE", "WEARERNUMBER", "WEARERNAME", "WEARERSEARCHNAME", "DEPARTMENT_LINK_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "CUSTOMER_LINK_ID", "DISTRIBUTIONPOINT_ID", "PRODUCTCODE", "PRODUCTDESC", "PRIMARYID", "QUANTITY", "PRICE", "AMOUNT", "LANGUAGECODE") AS 
  select pr.status, pr.processed, pr.labeltype, pr.invoiceheader_id, pr.creationdate, year(pr.creationdate) year, getisoweek(pr.creationdate) week,
       ll.code labelcode, ll.description labeldesc, ll.labeltype labellayouttype,
       wel.wearernumber, wel.wearername, wel.wearersearchname, dep.department_link_id,
       dep.departmentnumber, dep.description departmentdesc, dep.customer_link_id, dl.distributionpoint_id,
       (select p.code from product_link p where pr.product_link_id = p.product_link_id) productcode,
       (select pd.description from product_link_desc pd where pr.product_link_id = pd.product_link_id and pd.language_id = lan.language_id) productdesc,
       (select max(ui.primaryid) from uniqueitem ui where ui.uniqueitem_id = pr.uniqueitem_link_id) primaryid,
       pr.quantity, pr.price, pr.amount,
       lan.code languagecode
from printqueue pr
       left outer join product_link prdl on pr.product_link_id = prdl.product_link_id
     , weareremployment_link wel
     , distributionpoint_link dl
     , department_link dep
     , labellayout ll
     , languages lan
where pr.invoiceheader_id is not null
      and pr.status = 0
      and pr.labellayout_id = ll.labellayout_id
      and pr.weareremployment_link_id = wel.weareremployment_link_id
      and wel.distributionpoint_link_id = dl.distributionpoint_link_id
      and dl.department_link_id = dep.department_link_id
      and pr.amount <> 0 --todo 23122
/

  CREATE OR REPLACE VIEW "V_INVOICELINE" ("INVOICEDATE", "INVOICENUMBER", "LINENUMBER", "INVOICELINETYPE", "INVOICELINETYPEDESC", "INVOICELINESUBTYPEDESC", "CODE", "DESCRIPTION", "ADJUSTEDAMOUNT", "ADJUSTEDPRICE", "ADJUSTMENTBILLEDQTY", "TAXCODE", "EXTEND", "AMOUNT", "DISCOUNTPERCENTAGE", "PRICE", "BILLEDQTY", "TAXGROUPCODE", "TAXTYPE", "SUBJECTTOMINIMUM", "TURNOVERGROUPCODE", "TURNOVERGROUPDESCRIPTION", "INVOICELINESUBTYPE", "PRODUCTGROUPCODE", "PRODUCTGROUPDESCRIPTION", "PRODUCTSHORTDESCRIPTION", "SHORTDESCRIPTION", "SIZECODE", "SIZEDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "INVOICEQTYCOLUMN", "INVENTORYQTY", "DELIVEREDQTY", "ABUSEDQUANTITY", "SOILQUANTITY", "SOILCOUNTMETHOD", "BILLINGMETHOD", "WEARERNUMBER", "WEARERNAME", "WEARERADMINNR", "WEARERBANK", "WEARERLOCKER", "TRANSACTIONTYPE", "TRANSACTIONDATE", "PERCENTAGE", "SYSTEMUSER_ID", "TIMESTAMP", "INVOICELINE_ID", "REMARK", "LANGUAGECODE", "INVOICEHEADER_ID", "OVERAMOUNT", "REPLACEMENTPRICE", "PRODUCTDESCRIPTION", "REGISTRATIONUNITDESCRIPTION", "ADJUSTMENTREASON_CODE", "INVOICELINE_SEQUENCENUMBER", "SUPRESSPRINTING", "ADJUSTMENTDELIVEREDQTY", "PRICEFACTOR") AS 
  select ih.invoicedate, ih.invoicenumber, il.linenumber,
       (case when ilt.type = 1 and il.invoicelinesubtype = 13
             then 1.6
             else ilt.type end) invoicelinetype,
       (select iltd.description
          from invoicelinetype_desc iltd
         where iltd.invoicelinetype_id = il.invoicelinetype_id
           and iltd.language_id = lan.language_id) invoicelinetypedesc,
       (select ilstd.description
          from invoicelinesubtype ilst
          join invoicelinesubtype_desc ilstd on ilst.invoicelinesubtype_id = ilstd.invoicelinesubtype_id
                                             and ilstd.language_id = lan.language_id
         where ilst.invoicelinetype_id = il.invoicelinetype_id
           and ilst.subtype = il.invoicelinesubtype) invoicelinesubtypedesc,
       il.code, il.description, il.adjustedamount, il.adjustedprice, il.adjustmentbilledqty,
       cast(fsget_taxcode(ih.invoicenumber, il.linenumber) as varchar2(255)) taxcode,
       il.extend, il.amount, il.discountpercentage, il.price, il.billedqty, il.taxgroupcode, il.taxtype, il.subjecttominimum,
       (select tg.code from turnovergroup tg where tg.turnovergroup_id = il.turnovergroup_id) turnovergroupcode,
       (select tgd.description
          from turnovergroup_desc tgd
         where tgd.turnovergroup_id = il.turnovergroup_id
           and tgd.language_id = lan.language_id) turnovergroupdescription,
       il.invoicelinesubtype, ilp.productgroupcode, ilp.productgroupdescription, ilp.productshortdescription,
       cast(fsget_code(ih.invoicenumber, il.linenumber) as varchar2(255)) shortdescription, ilp.sizecode, ilp.sizedescription,
       ilp.finishingmethodcode, ilp.finishingmethoddescription, ilp.invoiceqtycolumn, ilp.inventoryqty, ilp.deliveredqty, ilp.abusedquantity, ilp.soilquantity,
       ilp.soilcountmethod, ilp.billingmethod, ilp.wearernumber, ilp.wearername, ilp.weareradminnr, ilp.wearerbank, ilp.wearerlocker, ilv.transactiontype,
       ilv.transactiondate, ilv.percentage, il.systemuser_id, il.timestamp, il.invoiceline_id, il.remark, lan.code languagecode, il.invoiceheader_id,
       ilv.overamount, ilp.replacementprice,
       (select pd.description
          from product_link_desc pd
         where pd.product_link_id = ilp.product_link_id
           and pd.language_id = lan.language_id) productdescription,
       (select pd.registrationunitdescription
          from product_link_desc pd
         where pd.product_link_id = ilp.product_link_id
           and pd.language_id = lan.language_id) registrationunitdescription,
       (select rc.code from reasoncode rc where rc.reasoncode_id = il.adjustmentreason_id) adjustmentreason_code,
       (select pilt.sequencenumber
          from plantinvoicelinetype pilt
         where pilt.plant_id = bu.plant_id
           and pilt.invoicelinetype_id = il.invoicelinetype_id) invoiceline_sequencenumber,
       case (select pilt.suppressprinting
               from plantinvoicelinetype pilt
              where bu.plant_id = pilt.plant_id
                and pilt.invoicelinetype_id = il.invoicelinetype_id)
          when 0 then 0
          when 1 then 1
          when 2 then 2
          else ilt.supressprinting end supressprinting,
       ilp.adjustmentdeliveredqty, ilp.pricefactor
  from invoiceline il
       left join invoicelineproduct ilp on il.invoiceline_id = ilp.invoiceline_id
       left join invoicelinevarious ilv on il.invoiceline_id = ilv.invoiceline_id
       join invoicelinetype ilt on il.invoicelinetype_id = ilt.invoicelinetype_id
       join invoiceheader ih on il.invoiceheader_id = ih.invoiceheader_id
       join businessunit bu on ih.invoicebusinessunit_id = bu.businessunit_id,
       languages lan
 where ih.documenttype in (1, 8)
/

  CREATE OR REPLACE VIEW "V_INVOICELINETYPE" ("TYPE", "FACTORYDESCRIPTION", "INVOICELINETYPE_DESC", "DEFINETURNOVERGROUP", "DEFINESPECIALCHARGE", "INCLUDEINMINIMUMCALC", "TURNOVERGROUPCODE", "TURNOVERGROUPDESCRIPTION", "TIMESTAMP", "SYSTEMUSER_ID", "INVOICELINETYPE_ID", "LANGUAGECODE") AS 
  select a.type, a.factorydescription,
( SELECT description FROM INVOICELINETYPE_DESC B WHERE B.INVOICELINETYPE_ID = A.INVOICELINETYPE_ID AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) INVOICELINETYPE_DESC,
 a.defineturnovergroup, a.definespecialcharge,
 a.includeinminimumcalc, c.code turnovergroupcode,
 ( SELECT  DESCRIPTION FROM TURNOVERGROUP_DESC  T WHERE T.TURNOVERGROUP_ID = A.TURNOVERGROUP_ID AND T.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) turnovergroupdescription,
 a.timestamp, a.systemuser_id, a.invoicelinetype_id, LANGUAGES.CODE LANGUAGECODE
from invoicelinetype a
LEFT OUTER JOIN turnovergroup c ON (a.turnovergroup_id = c.turnovergroup_id), LANGUAGES
/

  CREATE OR REPLACE VIEW "V_ISSUEHISTORYCC" ("YEAR", "WEEK", "UNIQUEITEM_LINK_ID", "DISTRIBUTIONPOINT_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "CUSTOMER_LINK_ID", "DEPARTMENT_LINK_ID", "WEARERNUMBER", "WEARERNAME", "PRODUCTCODE", "PRODUCTDESC", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESC", "QUANTITY", "PREPCHARGE", "INVOICEHEADER_ID", "LANGUAGECODE", "CC_CODE_DESC") AS 
  select
 a.assignyear year, a.assignweek week, a.uniqueitem_link_id, d.distributionpoint_id,
 e.departmentnumber, e.description departmentdesc, e.customer_link_id, e.department_link_id,
 w.wearernumber, w.wearername,
 p.code productcode,
 (select description from product_link_desc z where z.product_link_id = a.product_link_id
  and z.language_id = languages.language_id) productdesc, s.code sizedefinitionCode,
 (select description from sizedefinition_link_desc k where k.sizedefinition_link_id = s.sizedefinition_link_id
 and k.language_id = languages.language_id ) sizedefinitionDesc,
 a.quantity, coalesce(a.prepcharge, 0) prepcharge, a.invoiceheader_id, languages.code languagecode,
(SELECT coc.code || ' ' || coc.description
FROM Costcenter coc
WHERE coc.Costcenter_Id IN
 COALESCE((SELECT cc1.Costcenter_Id FROM distributionpoint dp, Costcenter cc1 WHERE d.distributionpoint_id = dp.distributionpoint_id
 AND dp.costcenter_id = cc1.Costcenter_Id),
 (SELECT min(cc2.Costcenter_Id) FROM customer_link cl, Costcenter cc2 WHERE e.customer_link_id = cl.customer_id
 AND cl.customer_id = cc2.customer_id ))) CC_Code_Desc
from issuehistory a
 left outer join weareremployment_link w on (a.weareremployment_link_id = w.weareremployment_link_id),
 distributionpoint_link d, department_link e, product_link p, languages, sizedefinition_link s
where a.distributionpoint_link_id = d.distributionpoint_link_id
 and d.department_link_id = e.department_link_id
 and a.product_link_id = p.product_link_id
 and a.sizedefinition_link_id = s.sizedefinition_link_id
 and a.issuestatus = 0 -- todo 3876
/

  CREATE OR REPLACE VIEW "V_KONTOCOSTS_AUX" ("INVOICEHEADER_ID", "INVOICENUMBER", "ENDMONTH", "ENDYEAR", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "SPLITUPCODE", "SPLITUPDESCRIPTION", "KONTO_NR", "AMOUNT") AS 
  select
  ih.invoiceheader_id, ih.invoicenumber, ih.endmonth, ih.endyear, ih.deltocustomernumber, ih.deltocustomername
, ih.splitupcode, ih.splitupdescription
, ( case prd.shortdescription when '681105' then '681105'
                              when '681125' then '681125'
                              when '685045' then '685045'
                              when '680805' then '680805'
                              when '680885' then '680885'
                              when '661715' then '661715' else '999999' end
    ) Konto_Nr
, (il_p.amount --* (case spc.code when '11' then 1.11 else 1 end) -- 11% are cumulated in last UNION
)amount
from
  invoiceheader ih
 /*   left outer join
         ( customerspecialcharge csc
                        join specialcharge spc on spc.specialcharge_id = csc.specialcharge_id
                                                  and spc.code = '11'
         ) on ih.deltocustomer_link_id = csc.customer_id */
, status, invoiceline il_p, product prd
where
    ih.invoicefrequency_id = 110 -- monthly
and ih.status_id = status.status_id
and status.Statustype = 'IN' -- and status.Code = '2' -- Settled (US) / Final Invoice (EU)
and ih.invoiceheader_id = il_p.invoiceheader_id and il_p.invoicelinetype_id in (1,2,5)
and il_p.code = prd.code
and coalesce(il_p.turnovergroup_id , -1)
       not in ( select spc.turnovergroup_id from customerspecialcharge csc,  specialcharge spc
                    where ih.deltocustomer_link_id = csc.customer_id
                          and csc.specialcharge_id = spc.specialcharge_id
                              and spc.code = '11'  )
UNION ALL
select
  ih.invoiceheader_id, ih.invoicenumber, ih.endmonth, ih.endyear, ih.deltocustomernumber, ih.deltocustomername
, ih.splitupcode, ih.splitupdescription
, ( case wgh.legacyweighingcategorycode when '681105' then '681105'
                                        when '681125' then '681125'
                                        when '685045' then '685045'
                                        when '680805' then '680805'
                                        when '680885' then '680885'
                                        when '661715' then '661715' else '999999' end
    ) Konto_Nr
, (il_w.amount --* (case spc.code when '11' then 1.11 else 1 end)-- 11% are cumulated in last UNION
)amount
from
  invoiceheader ih
  /*  left outer join
         ( customerspecialcharge csc
                        join specialcharge spc on spc.specialcharge_id = csc.specialcharge_id
                                                  and spc.code = '11'
         ) on ih.deltocustomer_link_id = csc.customer_id */
, status, invoiceline il_w, weighingcategory wgh
where
    ih.invoicefrequency_id = 110 -- monthly
and ih.status_id = status.status_id
and status.Statustype = 'IN' -- and status.Code = '2' -- Settled (US) / Final Invoice (EU)
and ih.invoiceheader_id = il_w.invoiceheader_id and il_w.invoicelinetype_id in (3,4)
and il_w.code = wgh.code
and coalesce(il_w.turnovergroup_id , -1)
       not in ( select spc.turnovergroup_id from customerspecialcharge csc,  specialcharge spc
                    where ih.deltocustomer_link_id = csc.customer_id
                          and csc.specialcharge_id = spc.specialcharge_id
                              and spc.code = '11'  )
UNION ALL
select
  ih.invoiceheader_id, ih.invoicenumber, ih.endmonth, ih.endyear, ih.deltocustomernumber, ih.deltocustomername
, ih.splitupcode, ih.splitupdescription
, --case when spc.code = '11' then '681125' else
  '999999' Konto_Nr
, (il.amount --* (case spc.code when '11' then 1.11 else 1 end)
)amount
from
  invoiceheader ih
/*   left outer join
         ( customerspecialcharge csc
                        join specialcharge spc on spc.specialcharge_id = csc.specialcharge_id
                                                  and spc.code = '11'
         ) on ih.deltocustomer_link_id = csc.customer_id */
, status, invoiceline il
where
    ih.invoicefrequency_id = 110 -- monthly
and ih.status_id = status.status_id
and status.Statustype = 'IN' -- and status.Code = '2' -- Settled (US) / Final Invoice (EU)
and ih.invoiceheader_id = il.invoiceheader_id and il.invoicelinetype_id not in (1,2,3,4,5)
and coalesce(il.turnovergroup_id , -1)
       not in ( select spc.turnovergroup_id from customerspecialcharge csc,  specialcharge spc
                    where ih.deltocustomer_link_id = csc.customer_id
                          and csc.specialcharge_id = spc.specialcharge_id
                              and spc.code = '11'  )
/

  CREATE OR REPLACE VIEW "V_LASTPAYMENT" ("LASTPAYMENTDATE", "BILLTOCUSTOMER_LINK_ID", "BUSINESSUNIT_ID") AS 
  select MAX(y1.artransactiondate ) lastpaymentdate, y1.billtocustomer_link_id, Y1.BUSINESSUNIT_ID
from artransaction y1 inner join artransactiontype x21 on y1.artransactiontype_id = x21.artransactiontype_id
where x21.typenumber = 5 and y1.debitcredit = 'C'
group by y1.billtocustomer_link_id, y1.businessunit_id
/

  CREATE OR REPLACE VIEW "V_LASTPAYMENTD" ("BILLTOCUSTOMER_LINK_ID", "BUSINESSUNIT_ID", "LASTPAYMENTDATE") AS 
  select y.billtocustomer_link_id, y.businessunit_id, min(y.artransactiondate) lastpaymentdate
from artransaction y
where y.debitcredit = 'D'
      and (y.parentartransaction_id is null or y.parentartransaction_id = y.artransaction_id)
      and y.closingtransaction_id is null
group by y.billtocustomer_link_id, y.businessunit_id
/

  CREATE OR REPLACE VIEW "V_LOSTBUSINESS_PRODNR" ("CUSTOMER_ID", "DATEINACTIVE", "ACTIVITYCODE", "PRODUCTCODE", "COMPETITORCODE", "REPORTPARAM_ID") AS 
  select /*version 1.0*/
       distinct plpc.customer_id, plpc.dateinactive, ac.code activitycode,
       pr.code productcode, co.code competitorcode, rp.reportparam_id
  from productlistpercustomer plpc
       left join competitor co on plpc.lostcompetitor_id = co.competitor_id
       left join gainlostreason gl on plpc.lostreason_id = gl.gainlostreason_id
       join product pr on plpc.product_id = pr.product_id
       join productgroup pg on pr.productgroup_id = pg.productgroup_id
       join customeractivities ca
            join businessunitsperusergroup bug on ca.invoicebusinessunit_id = bug.businessunit_id
            join activity ac on ca.activity_id = ac.activity_id
       on plpc.customer_id = ca.customer_id and pg.activity_id = ca.activity_id
       cross join reportparam rp
 where bug.usergroup_id = rp.number_value1
   and plpc.dateinactive >= rp.date_value1
   and plpc.dateinactive <= rp.date_value2
   and ((co.code between rp.string_value5 and rp.string_value6) or co.code is null)
   and ((gl.code between rp.string_value7 and rp.string_value8) or gl.code is null)
/

  CREATE OR REPLACE VIEW "V_MACHINECOMPARTMENTS" ("PLANT_ID", "TYPE", "COMPARTMENT") AS 
  select distinct m.plant_id, mt.code type, mc.code compartment
 from machine m  inner join machinetype mt on m.machinetype_id=mt.machinetype_id inner join machinecompartment mc on m.machine_id=mc.machine_id where mt.code='1' and m.active='Y'
/

  CREATE OR REPLACE VIEW "V_MACHINETYPES" ("PLANT_ID", "TYPE", "MACHINE") AS 
  select distinct m.plant_id, mt.code type, m.code machine
from  machine m
inner join machinetype mt on m.machinetype_id=mt.machinetype_id
where m.active='Y'
/

  CREATE OR REPLACE VIEW "V_MAXINVOICEDATE" ("MAX_INVDATE", "DELTOCUSTOMERNUMBER") AS 
  select max(ih.invoicedate) max_invdate, cu.customernumber deltocustomernumber
  from customer cu
  left outer join(invoiceheader ih
  join status
    on ih.status_id = status.status_id
   and status.statustype = 'IN' -- Settled (US) / Final Invoice (EU)
   and status.code <> '3') on ih.deltocustomer_link_id = cu.customer_id and ih.documenttype = 1 -- invoice
 and ih.invoicetype = 1
 group by cu.customernumber
/

  CREATE OR REPLACE VIEW "V_MINCUSTOMERROUTE" ("CUSTOMER_ID", "MIN_ROUTENUMBER", "MIN_ROUTE_ID") AS 
  select rs.customer_id, r.routenumber min_routenumber
, min (r.route_id) min_route_id
from routestop rs, route r
where rs.route_id = r.route_id and r.routenumber in
(select min(r1.routenumber)
from routestop rs1, route r1
where rs1.route_id = r1.route_id and rs1.customer_id=rs.customer_id
group by rs1.customer_id)
group by rs.customer_id, r.routenumber
/

  CREATE OR REPLACE VIEW "V_MIN_DAY_ROUTE_STOP" ("DAY", "ROUTE", "CUSTOMER_ID", "STOPNUMBER", "DRIVER_ID") AS 
  select --+ index(r xpkroute)
min(r.drivingday_id) day, min(r.routenumber) route,
s.customer_id customer_id, min(s.stopnumber) stopnumber, min(r.driver_id) driver_id
from routestop s inner join route r on r.route_id = s.route_id
where r.active = 'Y' and s.dateactive <= sysdate and s.dateinactive >= sysdate
group by s.customer_id
/

  CREATE OR REPLACE VIEW "V_NOTRECEIVEDCUSTOMERORDERS_C" ("CUSTOMER_ID", "REPORTPARAM_ID", "EXISTSDV") AS 
  select /*version 2.0*/
       cu.customer_id,  rp.reportparam_id,
       sum(f_existsdelivery(plpd.productlistperdistribpoint_id, rp.number_value1, rp.date_value1)) existsdv
from customer cu
     join department de on cu.customer_id = de.customer_id
     join distributionpoint dip on de.department_id = dip.department_id
     join productlistperdistribpoint plpd on dip.distributionpoint_id = plpd.distributionpoint_id
     join product pr on plpd.product_id = pr.product_id
     join productgroup pg on pr.productgroup_id = pg.productgroup_id
     , reportparam rp
where pr.typeofmerchandise <= 3
  and plpd.orderingmethod = 2
  and cu.customernumber between rp.number_value2 and rp.number_value3
  and de.departmentnumber between rp.number_value4 and rp.number_value5
  and dip.distributionpointnumber between rp.number_value6 and rp.number_value7
  and pg.code between rp.string_value1 and rp.string_value2
  and pr.code between rp.string_value3 and rp.string_value4
  and not exists (select nb.nonbusinessday_id -- check nonbusinessday
                    from nonbusinessday nb
                   where nb.nonbusinessday = rp.date_value1
                     and ((nb.customer_id = cu.customer_id and nb.department_id is null) or (nb.customer_id = cu.customer_id and nb.department_id = de.department_id)))
  and ((cu.defaultbusinessunit_id = rp.number_value) or exists (select ca.processbusinessunit_id
                                                                  from customeractivities ca
                                                                 where ca.activity_id = pg.activity_id
                                                                   and ca.customer_id = cu.customer_id
                                                                   and ca.processbusinessunit_id = rp.number_value2))
 group by cu.customer_id,  rp.reportparam_id
/

  CREATE OR REPLACE VIEW "V_NOTRECEIVEDCUSTOMERORDERS_D" ("CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CONTACTPERSON_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINT_ID", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "REPORTPARAM_ID", "PRODUCTLISTPERDISTRIBPOINT_ID", "DEPARTMENT_ID") AS 
  select distinct /*version 2.0*/
       cu.customer_id, cu.customernumber, cu.name customername, de.contactperson_id, de.departmentnumber, de.description departmentdesc,
       dip.distributionpoint_id, dip.distributionpointnumber, dip.description distributionpointdesc, rp.reportparam_id, plpd.productlistperdistribpoint_id, de.department_id
from customer cu
     join department de on cu.customer_id = de.customer_id
     join distributionpoint dip on de.department_id = dip.department_id
     join productlistperdistribpoint plpd on dip.distributionpoint_id = plpd.distributionpoint_id
     join product pr on plpd.product_id = pr.product_id
     join productgroup pg on pr.productgroup_id = pg.productgroup_id
     , reportparam rp
where pr.typeofmerchandise <= 3
  and plpd.orderingmethod = 2
  and cu.customernumber between rp.number_value2 and rp.number_value3
  and de.departmentnumber between rp.number_value4 and rp.number_value5
  and dip.distributionpointnumber between rp.number_value6 and rp.number_value7
  and pg.code between rp.string_value1 and rp.string_value2
  and pr.code between rp.string_value3 and rp.string_value4
  and not exists (select nb.nonbusinessday_id -- check nonbusinessday
                    from nonbusinessday nb
                   where nb.nonbusinessday = rp.date_value1
                     and ((nb.customer_id = cu.customer_id and nb.department_id is null) or (nb.customer_id = cu.customer_id and nb.department_id = de.department_id)))
  and ((cu.defaultbusinessunit_id = rp.number_value) or exists (select ca.processbusinessunit_id
                                                                  from customeractivities ca
                                                                 where ca.activity_id = pg.activity_id
                                                                   and ca.customer_id = cu.customer_id
                                                                   and ca.processbusinessunit_id = rp.number_value2))
/

  CREATE OR REPLACE VIEW "V_NOTSCANNEDITEMSRV_LINE" ("UNIQUEITEM_ID", "BUSINESSUNIT_ID", "BU_CODE", "BU_DESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "WEARERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "CUSTOMERLANGUAGEID", "LOCKER", "BANK", "WASHESTOTAL", "ROUTEFILTER", "CHAIN_CODE") AS 
  select uq.uniqueitem_id, uq.businessunit_id, bu.code BU_code, bu.description BU_desc
, cu.customernumber, cu.name customerName, we.wearernumber, we.fullname wearerName, department.departmentnumber
, department.description departmentDescription, distributionpoint.distributionpointnumber
, distributionpoint.description distributionpointDescription, cu.language_id customerLanguageID
, lo.locker, lo.bank--, F_ROUTEFILTER(cu.customer_id, distributionpoint.deliverypoint_id, rp.number_value1, rp.number_value2)
, uq.washestotal, 1 routefilter--, rp.reportparam_id
, (select ch.code from chain ch where ch.chain_id = cu.chain_id) chain_code
from
  uniqueitem uq, customer cu
  , wearer we, weareremployment wemp
  left outer join locker lo on wemp.locker_id = lo.locker_id
  , distributionpoint, department, uniqueitemnonpool uqnoo--, reportparam rp
  , businessunit bu
where uq.businessunit_id = bu.businessunit_id and
    uq.poolitem = 2
and uq.uniqueitem_id = uqnoo.uniqueitem_id
    and uqnoo.weareremployment_id = wemp.weareremployment_id
             and wemp.distributionpoint_id = distributionpoint.distributionpoint_id
                 and distributionpoint.department_id = department.department_id
                     and department.customer_id = cu.customer_id
        and wemp.wearer_id = we.wearer_id
UNION ALL
select uq.uniqueitem_id, uq.businessunit_id, bu.code BU_code, bu.description BU_desc
, cu.customernumber, cu.name customerName, -1 wearernumber, null wearerName, department.departmentnumber
, department.description departmentDescription, distributionpoint.distributionpointnumber
, distributionpoint.description distributionpointDescription, cu.language_id customerLanguageID
, '' locker, '' bank--, F_ROUTEFILTER(cu.customer_id, -1, rp.number_value1, rp.number_value2)
, uq.washestotal, 1 routefilter--, rp.reportparam_id
, (select ch.code from chain ch where ch.chain_id = cu.chain_id) chain_code
from
  uniqueitem uq, customer cu
  , distributionpoint, department --, reportparam rp
  , businessunit bu
where uq.businessunit_id = bu.businessunit_id and
    uq.poolitem = 1
and uq.distributionpoint_id is not null
and uq.distributionpoint_id = distributionpoint.distributionpoint_id
    and distributionpoint.department_id = department.department_id
        and department.customer_id = cu.customer_id
UNION ALL
select uq.uniqueitem_id, uq.businessunit_id, bu.code BU_code, bu.description BU_desc
, cu.customernumber, cu.name customerName, -1 wearernumber, null wearerName, null departmentnumber
, null departmentDescription, null distributionpointnumber
, null distributionpointDescription, cu.language_id customerLanguageID
, '' locker, '' bank
, uq.washestotal, 1 routefilter--, rp.reportparam_id
, (select ch.code from chain ch where ch.chain_id = cu.chain_id) chain_code
from
  uniqueitem uq, customer cu--  , reportparam rp
  , businessunit bu
where uq.businessunit_id = bu.businessunit_id and
    uq.poolitem = 1
and uq.distributionpoint_id is null
AND uq.relatedcustomer_id = cu.customer_id
UNION ALL
select uq.uniqueitem_id, uq.businessunit_id, bu.code BU_code, bu.description BU_desc
, -1 customernumber, '' customerName, -1 wearernumber, '' wearerName, -1 departmentnumber
, '' departmentDescription, -1 distributionpointnumber, '' distributionpointDescription
, -1 customerLanguageID
, '' locker, '' bank
, uq.washestotal, 1 routefilter--, rp.reportparam_id
, '' chain_code
from
  uniqueitem uq--, reportparam rp
  , businessunit bu
where uq.businessunit_id = bu.businessunit_id and
    uq.poolitem = 0
/

  CREATE OR REPLACE VIEW "V_NOTSCANNEDITEMS_AUX" ("UNIQUEITEM_ID", "PRODUCTGROUPCODE", "PRODUCTGROUPDESC", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESCRIPTION", "PRIMARYID", "LASTSCANDATE", "ISSUEDATE", "STATUSCODE", "STATUSDESCRIPTION", "STAYNUMBER", "STAYDESCRIPTION", "LANGUAGELANGUAGEID", "LANGUAGECODE") AS 
  select uq.uniqueitem_id, pg.code productGroupCode
, (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pg.productgroup_id
  and pgd.language_id = lan.language_id) productGroupDesc
, prd.code productCode
, (select prde.description from product_desc prde where prde.product_id = prd.product_id
  and prde.language_id = lan.language_id) productDescription
, sd.code sizedefinitionCode
, (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sd.sizedefinition_id
  and sdd.language_id = lan.language_id) sizedefinitionDescription
, uq.primaryid, uq.lastscandate LastScanDate, uqfix.lastissuedate issuedate
, st.code statusCode
, (select std.description from status_desc std where std.status_id = st.status_id
  and std.language_id = lan.language_id) statusdescription
, sy.staynr stayNumber
, (select syd.description from stay_desc syd where syd.stay_id = sy.stay_id
  and syd.language_id = lan.language_id ) StayDescription
, lan.language_id languageLanguageID, lan.code languageCode
from  uniqueitem uq
      inner join product prd
            inner join productgroup pg on prd.productgroup_id = pg.productgroup_id
      on uq.product_id = prd.product_id
      inner join uniqueitemfixedinfo uqfix on uq.uniqueitem_id = uqfix.uniqueitem_id
      inner join sizedefinition sd on uq.sizedefinition_id = sd.sizedefinition_id
      inner join status st on uq.status_id = st.status_id and st.statustype = 'UI'
      inner join stay sy on uq.stay_id = sy.stay_id
      , languages lan
/

  CREATE OR REPLACE VIEW "V_NOTSCANNEDITEMS_LINE" ("LINETYPE", "UNIQUEITEM_ID", "BUSINESSUNIT_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "WEARERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "CUSTOMERLANGUAGEID", "LOCKER", "BANK", "ROUTEFILTER", "REPORTPARAM_ID", "RESIDUALVALUE", "CHAIN_CODE") AS 
  select 1 linetype, uq.uniqueitem_id, uq.businessunit_id
, cu.customernumber, cu.name customerName, we.wearernumber, we.fullname wearerName, department.departmentnumber
, department.description departmentDescription, distributionpoint.distributionpointnumber
, distributionpoint.description distributionpointDescription, cu.language_id customerLanguageID
, lo.locker, lo.bank
, F_ROUTEFILTER(cu.customer_id, distributionpoint.deliverypoint_id, rp.number_value1, rp.number_value2) routefilter
, rp.reportparam_id, rp.number_value3 ResidualValue
, (select ch.code from chain ch where ch.chain_id = cu.chain_id) chain_code
from
  uniqueitem uq, customer cu
  , wearer we, weareremployment wemp
  left outer join locker lo on wemp.locker_id = lo.locker_id
  , distributionpoint, department, uniqueitemnonpool uqnoo, reportparam rp
where
    uq.poolitem = 2
and uq.uniqueitem_id = uqnoo.uniqueitem_id
    and uqnoo.weareremployment_id = wemp.weareremployment_id
             and wemp.distributionpoint_id = distributionpoint.distributionpoint_id
                 and distributionpoint.department_id = department.department_id
                     and department.customer_id = cu.customer_id
        and wemp.wearer_id = we.wearer_id and uq.uniqueitem_id = rp.number_value
UNION ALL
select 2 linetype, uq.uniqueitem_id, uq.businessunit_id
, cu.customernumber, cu.name customerName, -1 wearernumber, null wearerName, department.departmentnumber
, department.description departmentDescription, distributionpoint.distributionpointnumber
, distributionpoint.description distributionpointDescription, cu.language_id customerLanguageID
, '' locker, '' bank
, 1 routefilter
, rp.reportparam_id, rp.number_value3 ResidualValue
, (select ch.code from chain ch where ch.chain_id = cu.chain_id) chain_code
from
  uniqueitem uq, customer cu
  , distributionpoint, department
  , reportparam rp
where
    uq.poolitem = 1
and uq.distributionpoint_id is not null
and uq.distributionpoint_id = distributionpoint.distributionpoint_id
    and distributionpoint.department_id = department.department_id
        and department.customer_id = cu.customer_id and rp.number_value = -1--uq.uniqueitem_id
UNION ALL
select 3 linetype, uq.uniqueitem_id, uq.businessunit_id
, cu.customernumber, cu.name customerName, -1 wearernumber, null wearerName, null departmentnumber
, null departmentDescription, null distributionpointnumber
, null distributionpointDescription, cu.language_id customerLanguageID
, '' locker, '' bank
, 1 routefilter
, rp.reportparam_id, rp.number_value3 ResidualValue
, (select ch.code from chain ch where ch.chain_id = cu.chain_id) chain_code
from
  uniqueitem uq, customer cu
  , reportparam rp
where
    uq.poolitem = 1
and uq.distributionpoint_id is null
AND uq.relatedcustomer_id = cu.customer_id and rp.number_value = -1--uq.uniqueitem_id
UNION ALL
select 4 linetype, uq.uniqueitem_id, uq.businessunit_id
, -1 customernumber, '' customerName, -1 wearernumber, '' wearerName, -1 departmentnumber
, '' departmentDescription, -1 distributionpointnumber, '' distributionpointDescription
, -1 customerLanguageID
, '' locker, '' bank
, 1 routefilter
, rp.reportparam_id, rp.number_value3 ResidualValue
, '' chain_code
from
  uniqueitem uq, reportparam rp
where
    uq.poolitem = 0 and rp.number_value = -1--uq.uniqueitem_id
/

  CREATE OR REPLACE VIEW "V_NOTSCANNEDITEMS_OUTER" ("UNIQUEITEM_ID", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "FLAGCODE", "LANGUAGELANGUAGEID") AS 
  select uq.uniqueitem_id
, finishingmethod.code finishingmethodCode
, (select finishingmethod_desc.description from finishingmethod_desc
where finishingmethod_desc.finishingmethod_id =  finishingmethod.finishingmethod_id
and finishingmethod_desc.language_id = languages.language_id) finishingmethodDescription
, flag.code flagCode, languages.language_id languageLanguageID
from
  uniqueitem uq
   left outer join finishingmethod  on finishingmethod.finishingmethod_id = uq.finishingmethod_id
   left outer join (uniqueitemflag uqf join flag on uqf.flag_id = flag.flag_id    )
                  on uq.uniqueitem_id = uqf.uniqueitem_id
, languages
/

  CREATE OR REPLACE VIEW "V_OUTOFCIRCULATIONHISTORYCC" ("OUTOFCIRCYEAR", "OUTOFCIRCWEEK", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DEPARTMENT_LINK_ID", "WEARERNUMBER", "WEARERNAME", "DISTRIBUTIONPOINT_ID", "CUSTOMER_LINK_ID", "PRODUCTCODE", "PRODUCTDESC", "REASONCODE", "REASONDESC", "INCIRCDATE", "OUTOFCIRCDATE", "TOBECHARGEDPERCENTAGE", "RESIDUALVALUE", "INVOICEHEADER_ID", "CHARGETYPE", "STATUS", "INVOICECATEGORY", "LANGUAGECODE", "CC_CODE_DESC", "PRIMARYID", "SIZECODE", "SIZEDESC", "TIMESTAMP", "TIMESTAMP_TRUNC", "LASTOUTSCANDATE", "RAGREASONDESC", "RAGREASONCODE") AS 
  select
 a.outofcircyear, a.outofcircweek,
 e.departmentnumber, e.description departmentdesc, e.department_link_id,
 w.wearernumber, w.wearername, d.distributionpoint_id, e.customer_link_id,
 p.code productcode,
 (select description from product_link_desc z where z.product_link_id = a.product_link_id
  and z.language_id = languages.language_id) productdesc,
 b.code reasoncode,
 (select description from reasoncode_desc x where x.reasoncode_id = a.reasoncode_id
  and x.language_id = languages.language_id) reasondesc,
 a.incircdate, a.outofcircdate, a.tobechargedpercentage, a.amount residualvalue,--coalesce(a.residualvalue,0) residualvalue,
 a.invoiceheader_id, a.chargetype, a.status, b.invoicecategory, languages.code languagecode,
(SELECT coc.code || ' ' || coc.description
FROM Costcenter coc
WHERE coc.Costcenter_Id IN
 COALESCE((SELECT cc1.Costcenter_Id FROM distributionpoint dp, Costcenter cc1 WHERE d.distributionpoint_id = dp.distributionpoint_id
 AND dp.costcenter_id = cc1.Costcenter_Id),
 (SELECT min(cc2.Costcenter_Id) FROM customer_link cl, Costcenter cc2 WHERE e.customer_link_id = cl.customer_id
 AND cl.customer_id = cc2.customer_id ))) CC_Code_Desc,
 nvl((select ui.primaryid from uniqueitem ui, uniqueitem_link uil where ui.uniqueitem_id = uil.uniqueitem_id
  and uil.uniqueitem_link_id = a.uniqueitem_link_id),
  (select ri.primaryid from raggeditem ri, uniqueitem_link uil where ri.raggeditem_id = uil.raggeditem_id
  and uil.uniqueitem_link_id = a.uniqueitem_link_id)) primaryid,
 (select sz.code from sizedefinition sz where sz.sizedefinition_id = a.sizedefinition_link_id) sizecode,
 (select szd.description from sizedefinition_desc szd where szd.sizedefinition_id = a.sizedefinition_link_id
  and szd.language_id = languages.language_id) sizedesc, a.timestamp, trunc(a.timestamp) timestamp_trunc,
 coalesce((select ui.lastoutscandate from uniqueitem ui, uniqueitem_link uil where ui.uniqueitem_id = uil.uniqueitem_id
  and uil.uniqueitem_link_id = a.uniqueitem_link_id), getabsmaxdate()) lastoutscandate,
  (select description from ragreason_desc rd where rd.ragreason_id = a.ragreason_id
  and rd.language_id = languages.language_id) ragreasondesc,
   (select rr.code from ragreason rr where rr.ragreason_id = a.ragreason_id) ragreasoncode
FROM outofcirculationhistory a
 left outer join ragreason c on (a.ragreason_id = c.ragreason_id)
 left outer join weareremployment_link w on (a.weareremployment_link_id = w.weareremployment_link_id),
 reasoncode b, distributionpoint_link d, department_link e, product_link p, languages
where a.reasoncode_id = b.reasoncode_id
 and a.distributionpoint_link_id = d.distributionpoint_link_id
 and d.department_link_id = e.department_link_id
 and a.product_link_id = p.product_link_id -- and a.status=0
/

  CREATE OR REPLACE VIEW "V_PBAPERCUSTOMERYEARWEEK_AUX" ("CUSTOMERNUMBER", "CUSTOMERNAME", "YEAR", "WEEK", "CUSTOMER_ID", "CURRENCY_ID", "MERCHANDISECOSTS", "PROCESSINGCOSTS", "PURCHASINGCOSTS", "RESIDUALVALUE", "REPORTPARAM_ID", "NUMBER_VALUE5", "NUMBER_VALUE6", "INVOICEAMOUNTDECIMALS") AS 
  select
  cu.customernumber, cu.name customerName, sqh.year, sqh.week
, cu.customer_id, currency.currency_id
, sum( sqpba.circulatinginventory*sqpba.merchandisecostprice/
    (case when sqpba.pricefactor > 1 then sqpba.pricefactor else 1 end) ) merchandiseCosts
, sum( sqpba.processedqty*sqpba.processingcostprice /
    (case when sqpba.pricefactor > 1 then sqpba.pricefactor else 1 end) ) processingCosts
, sum( sqpba.soldqty*sqpba.purchasecostprice*(100+ ( case when prd.typeofmerchandise = 1 then cssp.linnenpercentage -- linen
                                                 when prd.typeofmerchandise = 2 then cssp.garmentpercentage -- garments
                                                 when prd.typeofmerchandise = 3 then cssp.salespercentage -- sales only itemsm
                                                 when prd.typeofmerchandise = 4 then cssp.emblempercentage end ))  -- emblems
  /100*(case when sqpba.pricefactor > 1 then sqpba.pricefactor else 1 end)) purchasingCosts
, sum( sqpba.residualvalue ) residualvalue
, rp.reportparam_id, rp.number_value5, rp.number_value6
, currency.invoiceamountdecimals
from
  sqcostspba sqpba, customer cu, statusquoheader sqh
, businessunit invoiceBu, costsettingsperplant cssp
, product prd, plant, country
, reportparam rp
, currency
where
    sqpba.customer_link_id = cu.customer_id
and sqpba.statusquoheader_id = sqh.statusquoheader_id
    and sqh.invoicebusinessunit_id = invoiceBu.Businessunit_Id
        and invoiceBu.Plant_Id = cssp.plant_id
        and invoiceBu.Plant_Id = plant.plant_id
            and plant.country_id = country.country_id
                and country.defaultcurrency_id = currency.currency_id
and sqpba.product_link_id = prd.product_id
--and cu.customernumber between cast(rp.string_value1 as numeric) and cast(rp.string_value2 as numeric)
and cu.customernumber between rp.number_value7 and rp.number_value8
and (sqh.year*100+sqh.week) between (rp.number_value1*100+rp.number_value2) and (rp.number_value3*100+rp.number_value4)
--and sqh.invoicebusinessunit_id  = cast(rp.string_value3 as numeric)
and sqh.invoicebusinessunit_id  = rp.number_value9
group by
  cu.customernumber, cu.Name, sqh.year, sqh.week, cu.customer_id, currency.currency_id
, rp.reportparam_id, rp.number_value5, rp.number_value6
, currency.invoiceamountdecimals
/

  CREATE OR REPLACE VIEW "V_PBAPERCUSTOMERYEARWEEK_DET" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_ID", "YEAR", "WEEK", "INVOICEAMOUNTDECIMALS", "MERCHANDISECOSTS", "MERCHANDISEONINVOICE", "PROCESSINGCOSTS", "PROCESSINGONINVOICE", "PURCHASINGCOSTS", "PURCHASINGONINVOICE", "OTHERCOSTS", "OTHERCOSTSONINVOICE", "RESIDUALVALUE", "REPORTPARAM_ID", "NUMBER_VALUE5", "NUMBER_VALUE6") AS 
  select
cu.customernumber, cu.name customerName, cu.customer_id,
sqh.year, sqh.week, currency.invoiceamountdecimals
, sum( coalesce(( sqpba.circulatinginventory * sqpba.merchandisecostprice
  / (case when sqpba.pricefactor > 1 then sqpba.pricefactor else 1 end)  ---Only from 7.46
  ), 0)) merchandiseCosts
, 0 merchandiseOnInvoice
, sum( coalesce(( sqpba.processedqty * sqpba.processingcostprice
   / (case when sqpba.pricefactor > 1 then sqpba.pricefactor else 1 end)  ---Only from 7.46
   ), 0)) processingCosts
, 0 processingOnInvoice
, sum( coalesce(sqpba.soldqty * sqpba.purchasecostprice * (100 +( case when prd.typeofmerchandise = 1 then cssp.linnenpercentage -- linen
                                                 when prd.typeofmerchandise = 2 then cssp.garmentpercentage -- garments
                                                 when prd.typeofmerchandise = 3 then cssp.salespercentage -- sales only itemsm
                                                 when prd.typeofmerchandise = 4 then cssp.emblempercentage end ))  -- emblems
  /(100 * (case when sqpba.pricefactor > 1 then sqpba.pricefactor else 1 end)  ---Only from 7.46
  ), 0)) purchasingCosts
, 0 purchasingOnInvoice
, 0 otherCosts
, 0 otherCostsOnInvoice
, sum( sqpba.residualvalue) residualvalue
, rp.reportparam_id, rp.number_value5, rp.number_value6
from
  sqcostspba sqpba, customer_link cu, statusquoheader sqh
, businessunit invoiceBu, costsettingsperplant cssp
, product prd, plant, country
, reportparam rp
, currency
where
    sqpba.customer_link_id = cu.customer_link_id
and sqpba.statusquoheader_id = sqh.statusquoheader_id
    and sqh.invoicebusinessunit_id = invoiceBu.Businessunit_Id
        and invoiceBu.Plant_Id = cssp.plant_id
        and invoiceBu.Plant_Id = plant.plant_id
            and plant.country_id = country.country_id
                and country.defaultcurrency_id = currency.currency_id
and sqpba.product_link_id = prd.product_id
--and cu.customernumber between cast(rp.string_value1 as numeric) and cast(rp.string_value2 as numeric)
and cu.customernumber between rp.number_value7 and rp.number_value8
and (sqh.year * 100 + sqh.week) between (rp.number_value1 * 100 + rp.number_value2) and (rp.number_value3 * 100 + rp.number_value4)
--and sqh.invoicebusinessunit_id  = cast(rp.string_value3 as numeric)
and sqh.invoicebusinessunit_id  = rp.number_value9
group by
rp.reportparam_id, cu.customernumber, cu.name , cu.customer_id,
sqh.year, sqh.week, currency.invoiceamountdecimals,
rp.number_value5, rp.number_value6
union all
select
ih.deltocustomernumber customernumber, ih.deltocustomername customername, ih.deltocustomer_link_id customer_id,
ih.invoiceyear year, ih.invoiceweek week, cr.invoiceamountdecimals
, 0 merchandiseCosts
, sum(coalesce(( case when ilty.type in (01, 09, 10, 11, 12, 19, 22, 23) then
       (case when il.amount = 0 or il.adjustmentreason_id is not null then il.adjustedamount
       else il.amount end)
       else 0 end ), 0)) merchandiseOnInvoice
, 0 processingCosts
, sum(coalesce(( case when ilty.type in (02, 03, 04, 06) then
       (case when il.amount = 0 or il.adjustmentreason_id is not null then il.adjustedamount
       else il.amount end)
       else 0 end ), 0)) processingOnInvoice
, 0 purchasingCosts
, sum(coalesce(( case when ilty.type in (05, 07, 08) then
       (case when il.amount = 0 or il.adjustmentreason_id is not null then il.adjustedamount
       else il.amount end)
       else 0 end ), 0)) purchasingOnInvoice
, 0 otherCosts
, sum(coalesce(( case when ilty.type in (13, 15, 16, 17, 20, 21) then
       (case when il.amount = 0 or il.adjustmentreason_id is not null then il.adjustedamount
       else il.amount end)
       else 0 end ), 0)) otherCostsOnInvoice
, 0 residualvalue
, rp.reportparam_id, rp.number_value5, rp.number_value6
from
  invoiceheader ih, invoicefrequency ifq
, invoiceline il, invoicelinetype ilty
, reportparam rp, currency cr
where
    ih.invoicefrequency_id = ifq.invoicefrequency_id
    and ifq.invoicefrequencynumber in (0, 200)
and ih.invoiceheader_id = il.invoiceheader_id
    and il.invoicelinetype_id = ilty.invoicelinetype_id
--and ih.deltocustomernumber between cast(rp.string_value1 as numeric) and cast(rp.string_value2 as numeric)
and ih.deltocustomernumber between rp.number_value7 and rp.number_value8
and (ih.invoiceyear * 100 + ih.invoiceweek) between (rp.number_value1 * 100 + rp.number_value2) and (rp.number_value3 * 100 + rp.number_value4)
--and ih.invoicebusinessunit_id = cast(rp.string_value3 as numeric )
and ih.invoicebusinessunit_id = rp.number_value9
and ih.currency_id=cr.currency_id
group by
rp.reportparam_id, ih.deltocustomernumber, ih.deltocustomername, ih.deltocustomer_link_id,
ih.invoiceyear, ih.invoiceweek, cr.invoiceamountdecimals
, rp.number_value5, rp.number_value6
/

  CREATE OR REPLACE VIEW "V_PBAPERCUSTOMERYEARWEEK_INV" ("DELTOCUSTOMER_LINK_ID", "MERCHANDISEONINVOICE", "PROCESSINGONINVOICE", "PURCHASINGONINVOICE", "OTHERCOSTSONINVOICE", "REPORTPARAM_ID", "CURRENCY_ID", "IH_YEAR", "IH_WEEK", "INVOICEAMOUNTDECIMALS", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME") AS 
  select
  ih.deltocustomer_link_id
, sum( case when ilty.type in (01, 09, 10, 11, 12, 19, 22, 23) then --GET_InvoiceLine_Amount(il.invoiceline_id)
       (case when il.amount=0 or il.adjustmentreason_id is not null then il.adjustedamount
       else il.amount end)
       else 0 end ) merchandiseOnInvoice
, sum( case when ilty.type in (02, 03, 04, 06) then
       (case when il.amount=0 or il.adjustmentreason_id is not null then il.adjustedamount
       else il.amount end)
       else 0 end ) processingOnInvoice
, sum( case when ilty.type in (05, 07, 08) then
       (case when il.amount=0 or il.adjustmentreason_id is not null then il.adjustedamount
       else il.amount end)
       else 0 end ) purchasingOnInvoice
, sum( case when ilty.type in (13, 15, 16, 17, 20, 21) then
       (case when il.amount=0 or il.adjustmentreason_id is not null then il.adjustedamount
       else il.amount end)
       else 0 end ) otherCostsOnInvoice
, rp.reportparam_id, ih.currency_id, ih.invoiceyear ih_year, ih.invoiceweek ih_week
, cr.invoiceamountdecimals, ih.deltocustomernumber, ih.deltocustomername
from
  invoiceheader ih, invoicefrequency ifq
, invoiceline il, invoicelinetype ilty
, reportparam rp, currency cr
where
    ih.invoicefrequency_id = ifq.invoicefrequency_id
    and ifq.invoicefrequencynumber in (0, 200)
and ih.invoiceheader_id = il.invoiceheader_id
    and il.invoicelinetype_id = ilty.invoicelinetype_id
--and ih.deltocustomernumber between cast(rp.string_value1 as numeric) and cast(rp.string_value2 as numeric)
and ih.deltocustomernumber between rp.number_value7 and rp.number_value8
and (ih.invoiceyear*100+ih.invoiceweek) between (rp.number_value1*100+rp.number_value2) and (rp.number_value3*100+rp.number_value4)
--and ih.invoicebusinessunit_id = cast(rp.string_value3 as numeric )
and ih.invoicebusinessunit_id = rp.number_value9
and ih.currency_id=cr.currency_id
group by
  ih.deltocustomer_link_id, ih.invoiceyear, ih.invoiceweek
, rp.reportparam_id
, ih.currency_id
, cr.invoiceamountdecimals, ih.deltocustomernumber, ih.deltocustomername
/

  CREATE OR REPLACE VIEW "V_POUND_AND_DOLLAR_VOLUME" ("CODE", "MARKETSEGMENT_ID", "POUNDS", "PAYTHISAMOUNT", "DELIVERYDATE", "INVOICEDATE", "BUSINESSUNIT_ID") AS 
  select ms.code, cu.marketsegment_id, (dh.amountdelivered * p.theoreticalweight) pounds, 0 paythisamount,
  dh.deliverydate, null invoicedate, dh.invoicebusinessunit_id businessunit_id
from deliveryhistory dh, customer cu, marketsegment ms, product p
where dh.customer_link_id = cu.customer_id
  and cu.marketsegment_id = ms.marketsegment_id
  and dh.product_link_id = p.product_id
union all
select ms.code, cu.marketsegment_id, 0 pounds, ih.paythisamount,
  null deliverydate, ih.invoicedate, ih.invoicebusinessunit_id businessunit_id
from invoiceheader ih, customer cu, marketsegment ms, status s
where ih.deltocustomer_link_id = cu.customer_id
  and cu.marketsegment_id = ms.marketsegment_id
  and ih.status_id = s.status_id
  and s.code = '2'
/

  CREATE OR REPLACE VIEW "V_PURCHASEORDERLINE_CUSTOMER" ("LINETYPE", "PURCHASEORDERHEADER_ID", "PURCHASEORDERLINE_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "PRODUCTCODE", "SIZECODE", "LANGUAGECODE", "PRODUCTDESC", "QTYPURCHASED", "QTYORDEREDPROD", "EMBLEMDESC", "QTYORDEREDEMBL") AS 
  select 1 linetype, pol.purchaseorderheader_id, pol.purchaseorderline_id, c.customernumber, c.name customername,
       p.code productcode, sz.code sizecode, lan.code languagecode,
       (select pd.description from product_link_desc pd where pd.product_link_id = pol.product_link_id and pd.language_id = lan.language_id) productdesc,
       (pol.quantityordered - pol.quantitycancelled) qtypurchased,
       (wol.quantityordered - wol.quantitycancelled - wol.quantityfilled) qtyorderedprod,
       '' emblemdesc,
       0 qtyorderedembl --this is the total quantity, not per garment
from purchaseorderline pol
      , workorder wo left outer join customer c on wo.customer_link_id=c.customer_id
     , product_link p,  sizedefinition_link sz, languages lan
     , workorderline wol
where wol.purchaseorderline_id = pol.purchaseorderline_id
and wo.workorder_id = wol.workorder_id
and p.product_link_id = pol.product_link_id
and sz.sizedefinition_link_id = pol.sizedefinition_link_id
union all
select 1 linetype, pol.purchaseorderheader_id, pol.purchaseorderline_id, c.customernumber, c.name customername,
       p.code productcode, sz.code sizecode, lan.code languagecode,
       (select pd.description from product_link_desc pd where pd.product_link_id = pol.product_link_id and pd.language_id = lan.language_id) productdesc,
       (pol.quantityordered - pol.quantitycancelled) qtypurchased,
       (wol.quantityordered - wol.quantitycancelled - wol.quantityfilled) qtyorderedprod,
       '' emblemdesc,
       0 qtyorderedembl --this is the total quantity, not per garment
from purchaseorderline pol
      , workorder wo left outer join customer c on wo.customer_link_id=c.customer_id
     , product_link p,  sizedefinition_link sz, languages lan
     , workorderline wol, workorderlinepurchordline wolpol
where pol.purchaseorderline_id=wolpol.workorderlinepurchordline_id and wol.workorderline_id=wolpol.workorderline_id
and wo.workorder_id = wol.workorder_id
and p.product_link_id = pol.product_link_id
and sz.sizedefinition_link_id = pol.sizedefinition_link_id
union all
select 2 linetype, pol.purchaseorderheader_id, pol.purchaseorderline_id, c.customernumber, c.name customername,
       case
          when wole.emblemtemplateline_id is not null then ''
              when wole.product_id is not null then
               (select pd.code
                from product pd
                where wole.product_id = pd.product_id)
          end productcode,
       case
          when wole.emblemtemplateline_id is not null then --''
             (select sd.code from emblemtemplateline etl,sizedefinition sd
                     where wole.emblemtemplateline_id = etl.emblemtemplateline_id
                     and etl.sizedefinition_id=sd.sizedefinition_id)
             when wole.product_id is not null then
               (select sd.code
                from sizedefinition sd
                where wole.sizedefinition_id = sd.sizedefinition_id)
          end sizecode,
        l.code  languagecode,
        '' productdesc,
       (pol.quantityordered - pol.quantitycancelled) qtypurchased,
       0 qtyorderedprod,
        case
          when wole.emblemtemplateline_id is not null then
            (select etl.description from emblemtemplateline etl where wole.emblemtemplateline_id = etl.emblemtemplateline_id)
              when wole.product_id is not null then
               (select pd.description
                from product_desc pd, purchaseorderheader poh, businessunit bu, plant p
                where wole.product_id =pd.product_id
                      and pd.language_id = p.language_id
                      and bu.plant_id = p.plant_id
                      and poh.businessunit_id = bu.businessunit_id
                      and poh.purchaseorderheader_id = pol.purchaseorderheader_id)
          end emblemdesc,
       (wole.qtyrequested-wole.qtyissued ) qtyorderedembl --this is the total quantity, not per garment
from purchaseorderline pol,
     workorderlineemblem wole,
     workorder wo left outer join customer c on wo.customer_link_id=c.customer_id
     , workorderline wol, languages l
where pol.purchaseorderline_id=wole.purchaseorderline_id
and wo.workorder_id = wol.workorder_id
and wole.workorderline_id = wol.workorderline_id
union all
select 2 linetype, pol.purchaseorderheader_id, pol.purchaseorderline_id, c.customernumber, c.name customername,
       case
          when wole.emblemtemplateline_id is not null then ''
              when wole.product_id is not null then
               (select pd.code
                from product pd
                where wole.product_id = pd.product_id)
          end productcode,
       case
          when wole.emblemtemplateline_id is not null then --''
             (select sd.code from emblemtemplateline etl,sizedefinition sd
                     where wole.emblemtemplateline_id = etl.emblemtemplateline_id
                     and etl.sizedefinition_id=sd.sizedefinition_id)
             when wole.product_id is not null then
               (select sd.code
                from sizedefinition sd
                where wole.sizedefinition_id = sd.sizedefinition_id)
          end sizecode,
        l.code  languagecode,
        '' productdesc,
       (pol.quantityordered - pol.quantitycancelled) qtypurchased,
       0 qtyorderedprod,
        case
          when wole.emblemtemplateline_id is not null then
            (select etl.description from emblemtemplateline etl where wole.emblemtemplateline_id = etl.emblemtemplateline_id)
              when wole.product_id is not null then
               (select pd.description
                from product_desc pd, purchaseorderheader poh, businessunit bu, plant p
                where wole.product_id =pd.product_id
                      and pd.language_id = p.language_id
                      and bu.plant_id = p.plant_id
                      and poh.businessunit_id = bu.businessunit_id
                      and poh.purchaseorderheader_id = pol.purchaseorderheader_id)
          end emblemdesc,
       (wole.qtyrequested-wole.qtyissued ) qtyorderedembl --this is the total quantity, not per garment
from purchaseorderline pol, workorderlinepurchordline wolpol,
     workorderlineemblem wole,
     workorder wo left outer join customer c on wo.customer_link_id=c.customer_id
     , workorderline wol, languages l
where pol.purchaseorderline_id=wolpol.workorderlinepurchordline_id and wol.workorderline_id=wolpol.workorderline_id
and wolpol.workorderlinepurchordline_id=wole.purchaseorderline_id
and wo.workorder_id = wol.workorder_id
and wole.workorderline_id = wolpol.workorderline_id
/

  CREATE OR REPLACE VIEW "V_PURCHASEORDERLINE_STOCK" ("PURCHASEORDERHEADER_ID", "PURCHASEORDERLINE_ID", "PRODUCTCODE", "SIZECODE", "QTYORDERED", "PRODUCTDESC", "QTYPURCHASED") AS 
  select pol.purchaseorderheader_id, pol.purchaseorderline_id, p.code productcode, sz.code sizecode,
       sum(wol.quantityordered - wol.quantitycancelled - wol.quantityfilled) qtyordered,
       (select pd.description
			  from product_link_desc pd, purchaseorderheader poh, businessunit bu, plant pl
			  where pd.product_link_id = pol.product_link_id
			        and poh.purchaseorderheader_id = pol.purchaseorderheader_id
              and poh.businessunit_id = bu.businessunit_id
              and bu.plant_id = pl.plant_id
				  		and pd.language_id = pl.language_id) productdesc,
			(pol.quantityordered - pol.quantitycancelled) qtypurchased
from purchaseorderline pol, product_link p, sizedefinition_link sz, workorderline wol
where p.product_link_id = pol.product_link_id
and sz.sizedefinition_link_id = pol.sizedefinition_link_id
and wol.purchaseorderline_id = pol.purchaseorderline_id
and wol.product_link_id = p.product_link_id
and wol.sizedefinition_link_id = sz.sizedefinition_link_id
group by pol.purchaseorderheader_id, pol.purchaseorderline_id, p.code, sz.code, pol.product_link_id, pol.quantityordered, pol.quantitycancelled
union
select pol.purchaseorderheader_id, pol.purchaseorderline_id, p.code productcode, sz.code sizecode,
       sum(wol.quantityordered - wol.quantitycancelled - wol.quantityfilled) qtyordered,
       (select pd.description
			  from product_link_desc pd, purchaseorderheader poh, businessunit bu, plant pl
			  where pd.product_link_id = pol.product_link_id
			        and poh.purchaseorderheader_id = pol.purchaseorderheader_id
              and poh.businessunit_id = bu.businessunit_id
              and bu.plant_id = pl.plant_id
				  		and pd.language_id = pl.language_id) productdesc,
			(pol.quantityordered - pol.quantitycancelled) qtypurchased
from purchaseorderline pol, product_link p, sizedefinition_link sz, workorderline wol, workorderlinepurchordline wolpol
where p.product_link_id = pol.product_link_id
and sz.sizedefinition_link_id = pol.sizedefinition_link_id
and pol.purchaseorderline_id=wolpol.workorderlinepurchordline_id and wol.workorderline_id=wolpol.workorderline_id
and wol.product_link_id = p.product_link_id
and wol.sizedefinition_link_id = sz.sizedefinition_link_id
group by pol.purchaseorderheader_id, pol.purchaseorderline_id, p.code, sz.code, pol.product_link_id, pol.quantityordered, pol.quantitycancelled
/

  CREATE OR REPLACE VIEW "V_PURCHASEORDER_MOD_DESC" ("WORKORDER_ID", "PURCHASEORDERLINE_ID", "MODIFICATIONS", "LANGUAGE_ID") AS 
  select distinct wl.workorder_id, wl.purchaseorderline_id,
  CAST(F_GETMODIFICATIONS(wl.purchaseorderline_id, wl.workorder_id, languages.language_id) as varchar2(255)) modifications,
  languages.language_id
from workorderline wl, languages
--where exists (select wm.workorderline_id from workorderlinemodification wm
--  where wm.workorderline_id = wl.workorderline_id)
/

  CREATE OR REPLACE VIEW "V_PURCHASEORDER_MOD_QTY" ("WORKORDER_ID", "PURCHASEORDERLINE_ID", "QUANTITY") AS 
  select wl.workorder_id, wl.purchaseorderline_id,
  sum(wl.quantityordered - wl.quantitycancelled - wl.quantityfilled) quantity
from workorderline wl
--where exists (select wm.workorderline_id from workorderlinemodification wm where wm.workorderline_id = wl.workorderline_id)
group by wl.workorder_id, wl.purchaseorderline_id
/

  CREATE OR REPLACE VIEW "V_QUITSERVICESUMMARY_ROUTE" ("ROUTENUMBER", "ROUTEDESC", "PLANT_ID", "CUSTOMER_ID", "DEPOTCODE", "DEPOTDESC") AS 
  SELECT DISTINCT ro.routenumber, ro.description RouteDesc, ro.plant_id, rs.customer_id
       , de.code DepotCode, de.description DepotDesc
FROM routestop rs, route ro
     LEFT OUTER JOIN depot de ON ro.depot_id = de.depot_id
WHERE rs.route_id = ro.route_id
AND ro.routenumber IN
(SELECT MIN(ro1.routenumber) routenumber FROM routestop rs1, route ro1
WHERE rs1.route_id = ro1.route_id AND ro1.plant_id = ro.plant_id AND rs1.customer_id = rs.customer_id)
/

  CREATE OR REPLACE VIEW "V_RELOAD_PN" ("ROUTECONTROL_ID", "PRODUCT_ID", "SIZEDEFINITION_ID", "DELIVERED", "TOBEDELIVERED") AS 
  SELECT RC.ROUTECONTROL_ID, PNL.PRODUCT_ID,PNL.SIZEDEFINITION_ID,
  SUM(PNL.DELIVEREDAMOUNT) DELIVERED,
  SUM(PNL.TOBEDELIVEREDAMOUNT) TOBEDELIVERED
FROM ROUTECONTROL RC, PACKINGNOTE PN, STATUS ST, PACKINGNOTELINE PNL
WHERE RC.TRUCKRELOADCALCULATED = 'N'
  AND PN.ROUTECONTROL_ID = RC.ROUTECONTROL_ID
  AND ST.STATUS_ID = PN.STATUS_ID
  AND ST.STATUSTYPE = 'PN'
  AND ST.CODE = '30'
  AND PNL.PACKINGNOTE_ID = PN.PACKINGNOTE_ID
GROUP BY RC.ROUTECONTROL_ID, PNL.PRODUCT_ID, PNL.SIZEDEFINITION_ID
/

  CREATE OR REPLACE VIEW "V_RELOAD_SN" ("ROUTECONTROL_ID", "PRODUCT_ID", "SIZEDEFINITION_ID", "DELIVERED", "TOBEDELIVERED") AS 
  SELECT RC.ROUTECONTROL_ID, WOL.PRODUCT_LINK_ID PRODUCT_ID,WOL.SIZEDEFINITION_LINK_ID SIZEDEFINITION_ID,
  SUM(WOL.QUANTITYFILLED) DELIVERED,
  SUM(WOL.QUANTITYORDERED - WOL.QUANTITYCANCELLED) TOBEDELIVERED
FROM ROUTECONTROL RC, WORKORDER WO, STATUS ST, WORKORDERLINE WOL
WHERE RC.TRUCKRELOADCALCULATED = 'N'
  AND WO.ROUTE_ID = RC.ROUTE_ID
  AND WO.ORIGIN = '6'
  AND WO.MOUNTINGORDERSALES = 'N'
  AND ST.STATUS_ID = WO.STATUS_ID
  AND ST.STATUSTYPE = 'WO'
  AND ST.CODE = '30'
  AND WOL.WORKORDER_ID = WO.WORKORDER_ID
GROUP BY RC.ROUTECONTROL_ID, WOL.PRODUCT_LINK_ID, WOL.SIZEDEFINITION_LINK_ID
/

  CREATE OR REPLACE VIEW "V_RENTALAGREEMENTS" ("DEPARTMENTNUMBER", "DEP_DESP", "DISTRIBUTIONPOINTNUMBER", "DISTRIBPOINT_DESC", "PRODUCTCODE", "DSCODE", "DATEACTIVE", "DATEINACTIVE", "CUSTOMER_ID", "PRODUCT_ID", "SIZEDEFINITION_ID", "FINISHINGMETHOD_ID", "LAGUAGECODE", "BILLINGMETHOD", "LANGUAGE_ID", "PRICE", "PRODUCTDESC", "RENTINGPERIOD", "LASTINVOICESTARTDATE", "LASTINVOICEENDDATE", "AMOUNT", "QUANTITY", "CURRENCYDECIMALS") AS 
  select /*version 2.1*/
       dep.departmentnumber, dep.description dep_desp, dp.distributionpointnumber, dp.description distribpoint_desc, p.code productcode,
       ds.code dscode, sdl.dateactive, sdl.dateinactive, cu.customer_id, plpd.product_id, plpd.sizedefinition_id, plpd.finishingmethod_id,
       lan.code laguagecode, plpc.billingmethod, lan.language_id,
       pack_price.rent_price(cu.customer_id, p.product_id, plpd.sizedefinition_id, plpd.finishingmethod_id, null, ds.frequency) price,
       (select pd.description
          from product_desc pd
         where p.product_id = pd.product_id
           and pd.language_id = lan.language_id) productdesc,
       (select max(ifd.description)
          from invoicefrequency_desc ifd
         where ifd.language_id = lan.language_id
           and ifd.invoicefrequency_id = cu.invoicefrequency_id) rentingperiod,
       (select coalesce(ih.nextperiodstartdate, ih.startdate)
          from invoiceheader ih
         where ih.invoiceheader_id = (select max(ih.invoiceheader_id)
                                        from invoiceheader ih
                                             join invoiceline il
                                                  join invoicelineproduct ilp on il.invoiceline_id = ilp.invoiceline_id
                                             on ih.invoiceheader_id = il.invoiceheader_id
                                             join status st on ih.status_id = st.status_id
                                       where st.statustype = 'IN'
                                         and st.code = '2'
                                         and ih.documenttype = 1
                                         and il.invoicelinetype_id = 1
                                         and ih.deltocustomer_link_id = cu.customer_id
                                         and ilp.product_link_id = plpd.product_id
                                         and ilp.sizedefinition_link_id = plpd.sizedefinition_id
                                         and ilp.finishingmethod_id = plpd.finishingmethod_id
                                       group by ih.deltocustomer_link_id, ilp.product_link_id, ilp.sizedefinition_link_id, ilp.finishingmethod_id)) lastinvoicestartdate,
       (select coalesce(ih.nextperiodenddate, ih.enddate)
          from invoiceheader ih
         where ih.invoiceheader_id = (select max(ih.invoiceheader_id)
                                        from invoiceheader ih
                                             join invoiceline il
                                                  join invoicelineproduct ilp on il.invoiceline_id = ilp.invoiceline_id
                                             on ih.invoiceheader_id = il.invoiceheader_id
                                             join status st on ih.status_id = st.status_id
                                       where st.statustype = 'IN'
                                         and st.code = '2'
                                         and ih.documenttype = 1
                                         and il.invoicelinetype_id = 1
                                         and ih.deltocustomer_link_id = cu.customer_id
                                         and ilp.product_link_id = plpd.product_id
                                         and ilp.sizedefinition_link_id = plpd.sizedefinition_id
                                         and ilp.finishingmethod_id = plpd.finishingmethod_id
                                       group by ih.deltocustomer_link_id, ilp.product_link_id, ilp.sizedefinition_link_id, ilp.finishingmethod_id)) lastinvoiceenddate,
       (select sum(il.amount)
          from invoiceheader ih
               join invoiceline il
                    join invoicelineproduct ilp on il.invoiceline_id = ilp.invoiceline_id
               on ih.invoiceheader_id = il.invoiceheader_id
         where il.invoicelinetype_id = 1
           and ilp.product_link_id = plpd.product_id
           and ilp.sizedefinition_link_id = plpd.sizedefinition_id
           and ilp.finishingmethod_id = plpd.finishingmethod_id
           and ih.invoiceheader_id = (select max(ih.invoiceheader_id)
                                        from invoiceheader ih
                                             join invoiceline il
                                                  join invoicelineproduct ilp on il.invoiceline_id = ilp.invoiceline_id
                                             on ih.invoiceheader_id = il.invoiceheader_id
                                             join status st on ih.status_id = st.status_id
                                       where st.statustype = 'IN'
                                         and st.code = '2'
                                         and ih.documenttype = 1
                                         and il.invoicelinetype_id = 1
                                         and ih.deltocustomer_link_id = cu.customer_id
                                         and ilp.product_link_id = plpd.product_id
                                         and ilp.sizedefinition_link_id = plpd.sizedefinition_id
                                         and ilp.finishingmethod_id = plpd.finishingmethod_id
                                       group by ih.deltocustomer_link_id, ilp.product_link_id, ilp.sizedefinition_link_id, ilp.finishingmethod_id)) amount,
       case when plpc.billingmethod = 1 then sdl.fixedrentquantity
            when plpc.billingmethod = 3 then (select sum(rqa.quantity)
                                                from rentalqtyadjustment rqa
                                               where rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
                                                 and rqa.adjustmentdate <= trunc(sysdate))
        end quantity,
       (select cur.decimals
          from currency cur
         where cur.currency_id = cu.currency_id) currencydecimals
  from standarddeliveryline sdl
       join deliveryscheme ds on sdl.deliveryscheme_id = ds.deliveryscheme_id
       join productlistpercustomer plpc
            join product p on plpc.product_id = p.product_id
       on sdl.productlistpercustomer_id = plpc.productlistpercustomer_id
       join productlistperdistribpoint plpd
            join distributionpoint dp
                 join department dep
                      join customer cu on dep.customer_id = cu.customer_id
                 on dp.department_id = dep.department_id
            on plpd.distributionpoint_id = dp.distributionpoint_id
       on sdl.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
       cross join languages lan
 where plpc.billingmethod in (1, 3)
/

  CREATE OR REPLACE VIEW "V_REPAIRHISTORYCC" ("YEAR", "WEEK", "PRODUCT_LINK_ID", "PRIMARYID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DEPARTMENT_LINK_ID", "WEARERNUMBER", "WEARERNAME", "DISTRIBUTIONPOINT_ID", "CUSTOMER_LINK_ID", "REPAIRCODE", "REPAIRDESC", "MINUTES", "UNITPRICE", "PRICEPERMINUTE", "AMOUNT", "INVOICEHEADER_ID", "LANGUAGECODE", "CC_CODE_DESC", "QUANTITY") AS 
  select
 a.year, a.week, a.product_link_id, a.primaryid,
 e.departmentnumber, e.description departmentdesc, e.department_link_id,
 w.wearernumber, w.wearername, d.distributionpoint_id, e.customer_link_id,
 p.code repaircode,
 (select description from repairtype_desc z where z.repairtype_id = a.repairtype_id
  and z.language_id = languages.language_id) repairdesc,
 a.minutes, a.unitprice, a.priceperminute, a.amount,
 a.invoiceheader_id, languages.code languagecode,
(SELECT coc.code || ' ' || coc.description
FROM Costcenter coc
WHERE coc.Costcenter_Id IN
 COALESCE((SELECT cc1.Costcenter_Id FROM distributionpoint dp, Costcenter cc1 WHERE d.distributionpoint_id = dp.distributionpoint_id
 AND dp.costcenter_id = cc1.Costcenter_Id),
 (SELECT min(cc2.Costcenter_Id) FROM customer_link cl, Costcenter cc2 WHERE e.customer_link_id = cl.customer_id
 AND cl.customer_id = cc2.customer_id ))) CC_Code_Desc, a.quantity
from repairhistory a
 left outer join weareremployment_link w on (a.weareremployment_link_id = w.weareremployment_link_id),
 distributionpoint_link d, department_link e, repairtype p, languages
where a.distributionpoint_link_id = d.distributionpoint_link_id
 and d.department_link_id = e.department_link_id
 and a.repairtype_id = p.repairtype_id-- and a.status <> 1    todo 3876
 and a.status = 0
/

  CREATE OR REPLACE VIEW "V_REVENUEMAINTENANCE15_AUX" ("DELTOCUSTOMER_LINK_ID", "MININVOICEDATE", "MAXINVOICEDATE") AS 
  select ih1.deltocustomer_link_id, min(ih1.invoicedate) MinInvoicedate, max(ih1.invoicedate) MaxInvoicedate
from invoiceheader ih1
where ih1.prebillamount <> 0
      and ih1.invoicedate >= trunc(sysdate)-14 and ih1.invoicedate <= trunc(sysdate)
group by ih1.deltocustomer_link_id
/

  CREATE OR REPLACE VIEW "V_REVENUEMAINTENANCE8_AUX" ("DELTOCUSTOMER_LINK_ID", "MININVOICEDATE", "MAXINVOICEDATE") AS 
  select ih1.deltocustomer_link_id, min(ih1.invoicedate) MinInvoicedate, max(ih1.invoicedate) MaxInvoicedate
from invoiceheader ih1
where ih1.prebillamount <> 0
      and ih1.invoicedate >= trunc(sysdate)-7 and ih1.invoicedate <= trunc(sysdate)
group by ih1.deltocustomer_link_id
/

  CREATE OR REPLACE VIEW "V_REVENUEMAINTENANCE_AUX" ("DELTOCUSTOMER_LINK_ID", "MAXINVOICEDATE", "SECONDINVOICEDATE") AS 
  select distinct ih1.deltocustomer_link_id
, (select max(ih2.invoicedate) from invoiceheader ih2
  where ih1.deltocustomer_link_id = ih2.deltocustomer_link_id and ih2.prebillamount <> 0 and ih2.invoicedate <= trunc(sysdate)
  ) MaxInvoicedate
, (select max(ih3.invoicedate) from invoiceheader ih3
  where ih1.deltocustomer_link_id = ih3.deltocustomer_link_id and ih3.prebillamount <> 0 and ih3.invoicedate <= trunc(sysdate)
      and ih3.invoicedate <> (select max(ih4.invoicedate) from invoiceheader ih4
          where ih1.deltocustomer_link_id = ih4.deltocustomer_link_id and ih4.prebillamount <> 0 and ih4.invoicedate <= trunc(sysdate))
  ) SecondInvoicedate
from invoiceheader ih1
where ih1.prebillamount <> 0 and ih1.invoicedate <= trunc(sysdate)
/

  CREATE OR REPLACE VIEW "V_ROWCOUNT" ("COUNTER") AS 
  select rownum counter
from systemsetting
/

  CREATE OR REPLACE VIEW "V_SEASONWEEK_AUX" ("SEASONTYPECODE", "SEASON_ID", "REPORTPARAM_ID") AS 
  select
  st.code seasontypeCode, ss.season_id, rp.reportparam_id --, rp.number_value1 startweek, rp.number_value2 endweek
from
  season ss, seasontype st, reportparam rp
where
    ss.seasontype_id = st.seasontype_id
and ( exists
         ( select sw1.weeknumber + 1
              from seasonweek sw1
                 where sw1.season_id = ss.season_id and sw1.weeknumber + 1 >= rp.number_value1 and
                       sw1.weeknumber + 1 <= rp.number_value2 and
                       sw1.weeknumber + 1 not in
                       ( select sw.weeknumber
                         from seasonweek sw
                         where sw.season_id = ss.season_id and sw.weeknumber >= rp.number_value1 and
                               sw.weeknumber <= rp.number_value2 ))
    or
      not exists
          ( select sw2.weeknumber
                from seasonweek sw2
                         where sw2.season_id = ss.season_id and sw2.weeknumber >= rp.number_value1 and
                               sw2.weeknumber <= rp.number_value2 )
   or
      exists
          ( select sw3.weeknumber - 1
              from seasonweek sw3
                 where sw3.season_id = ss.season_id and sw3.weeknumber - 1 >= rp.number_value1 and
                       sw3.weeknumber - 1 <= rp.number_value2 and
                       sw3.weeknumber - 1 not in
                       ( select sw4.weeknumber
                         from seasonweek sw4
                         where sw4.season_id = ss.season_id and sw4.weeknumber >= rp.number_value1 and
                               sw4.weeknumber <= rp.number_value2 ))
)
/

  CREATE OR REPLACE VIEW "V_SENDTOLAUNDRYIDS" ("PRIMARYID", "CUSTOMER_ID") AS 
  select s.primaryid, de.customer_id
from containerscan s, distributionpoint dp, department de
where s.transactiontype_id =549  --(send to laundry for containers, new transactiontype introduced by ABS-27609)
     and s.scantimestamp >= trunc(sysdate)
     and dp.distributionpoint_id = s.distributionpoint_link_id
     and de.department_id = dp.department_id
/

  CREATE OR REPLACE VIEW "V_SOILREASONABILITY_CURR" ("ROUTECONTROL_ID", "REPORTPARAM_ID", "CUSTOMER_ID", "PRODUCT_ID", "SIZEDEFINITION_ID", "FINISHINGMETHOD_ID", "STOPNUMBER", "COUNTDATE", "SOILTICKETNUMBER", "CURRENTQTY", "NULLQTY", "MISSED", "INVENTORYQTY") AS 
  select s.routecontrol_id, rp.reportparam_id, s.customer_id, sl.product_id, sl.sizedefinition_id, sl.finishingmethod_id, s.routestopnumber stopnumber,
       min(s.countdate) countdate, min(s.soilticketnumber) soilticketnumber,
       case when sum(coalesce(sl.countconverted, -1) + coalesce(sl.countkeypad, -1) + coalesce(sl.countlightframe, -1) + coalesce(sl.countabused, -1)) < 0
             and mod(sum(coalesce(sl.countconverted, -1) + coalesce(sl.countkeypad, -1) + coalesce(sl.countlightframe, -1) + coalesce(sl.countabused, -1)), 3) = 0
            then null
            else sum(coalesce(sl.countconverted, 0) + coalesce(sl.countkeypad, 0) + coalesce(sl.countlightframe, 0) + coalesce(sl.countabused, 0))
       end currentqty,
       case when sum(coalesce(sl.countconverted, -1) + coalesce(sl.countkeypad, -1) + coalesce(sl.countlightframe, -1) + coalesce(sl.countabused, -1)) < 0
             and mod(sum(coalesce(sl.countconverted, -1) + coalesce(sl.countkeypad, -1) + coalesce(sl.countlightframe, -1) + coalesce(sl.countabused, -1)), 3) = 0
            then -1
            else 0
       end nullqty,
       case when min(s.countdate) = getABSMaxDate()
            then 1
            else 0
       end missed,
       case when sl.unrelatedloan = 'Y'
            then 0
            else min(sl.inventory)
       end inventoryqty
  from reportparam rp
       join soilticket s on rp.number_value = s.routecontrol_id
       join soilticketline sl on s.soilticket_id = sl.soilticket_id
 group by rp.reportparam_id, s.routecontrol_id, s.customer_id, sl.product_id,
          sl.sizedefinition_id, sl.finishingmethod_id, s.routestopnumber, sl.unrelatedloan
/

  CREATE OR REPLACE VIEW "V_SOILREASONABILITY_HIST" ("REPORTPARAM_ID", "ROUTECONTROL_ID", "CUSTOMER_ID", "PRODUCT_ID", "SIZEDEFINITION_ID", "FINISHINGMETHOD_ID", "PICKUPQTY1", "PICKUPQTY2", "PICKUPQTY3", "PICKUPQTY4", "PICKUPQTY5", "PICKUPQTY6", "PICKUPQTY7", "PICKUPQTY8", "PICKUPQTY9", "PICKUPQTY10", "PICKUPQTY11", "PICKUPQTY12", "PICKUPQTY13", "NR_OF_COLUMNS") AS 
  select aaa.reportparam_id, aaa.mainroutecontrol_id routecontrol_id, aaa.customer_id,
       aaa.product_id, aaa.sizedefinition_id, aaa.finishingmethod_id,
       sum(aaa.col1) pickupqty1, sum(aaa.col2) pickupqty2, sum(aaa.col3) pickupqty3, sum(aaa.col4) pickupqty4,
       sum(aaa.col5) pickupqty5, sum(aaa.col6) pickupqty6, sum(aaa.col7) pickupqty7, sum(aaa.col8) pickupqty8,
       sum(aaa.col9) pickupqty9, sum(aaa.col10) pickupqty10, sum(aaa.col11) pickupqty11, sum(aaa.col12) pickupqty12,
       sum(aaa.col13) pickupqty13, max(aaa.columnnr) nr_of_columns
  from (select aa.reportparam_id, aa.mainroutecontrol_id, aa.customer_id,
               aa.product_id,  aa.sizedefinition_id, aa.finishingmethod_id, aa.columnnr,
               case when aa.columnnr = 1  then sum(aa.qty) else 0 end col1,
               case when aa.columnnr = 2  then sum(aa.qty) else 0 end col2,
               case when aa.columnnr = 3  then sum(aa.qty) else 0 end col3,
               case when aa.columnnr = 4  then sum(aa.qty) else 0 end col4,
               case when aa.columnnr = 5  then sum(aa.qty) else 0 end col5,
               case when aa.columnnr = 6  then sum(aa.qty) else 0 end col6,
               case when aa.columnnr = 7  then sum(aa.qty) else 0 end col7,
               case when aa.columnnr = 8  then sum(aa.qty) else 0 end col8,
               case when aa.columnnr = 9  then sum(aa.qty) else 0 end col9,
               case when aa.columnnr = 10 then sum(aa.qty) else 0 end col10,
               case when aa.columnnr = 11 then sum(aa.qty) else 0 end col11,
               case when aa.columnnr = 12 then sum(aa.qty) else 0 end col12,
               case when aa.columnnr = 13 then sum(aa.qty) else 0 end col13
          from (select a.reportparam_id, a.number_value4, a.mainroutecontrol_id, a.customer_id, a.drivingdate,
                       a.product_id, a.sizedefinition_id, a.finishingmethod_id, a.qty,
                       row_number() over(partition by a.reportparam_id, a.mainroutecontrol_id, a.customer_id,
                                                      a.product_id, a.sizedefinition_id, a.finishingmethod_id
                                             order by a.drivingdate desc) columnnr
                  from (select rp.reportparam_id, rp.number_value4, rcmain.routecontrol_id mainroutecontrol_id, rc.drivingdate,
                               st.customer_id, l.product_id, l.sizedefinition_id, l.finishingmethod_id,
                               sum(nvl(l.countlightframe, 0) + nvl(l.countkeypad, 0) + nvl(l.countconverted, 0) + nvl(l.countabused, 0)) qty
                          from soilticketline l
                               join soilticket st on l.soilticket_id = st.soilticket_id
                               join routecontrol rc on st.routecontrol_id = rc.routecontrol_id
                               join route ro on rc.route_id = ro.route_id,
                               reportparam rp
                               join routecontrol rcmain on rp.number_value = rcmain.routecontrol_id
                               join route romain on rcmain.route_id = romain.route_id
                         where rc.drivingdate < rcmain.drivingdate
                           and ro.drivingday_id = romain.drivingday_id
                           and st.countdate <> getabsmaxdate() -- only include counted soil tickets
                           and st.customer_id in (select s.customer_link_id
                                                    from stop s
                                                   where s.routecontrol_id = rcmain.routecontrol_id)
                         group by rp.reportparam_id, rp.number_value4, rcmain.routecontrol_id, rc.drivingdate,
                                  st.customer_id, l.product_id, l.sizedefinition_id, l.finishingmethod_id
                         order by rcmain.routecontrol_id, st.customer_id, rc.drivingdate desc) a
                   order by a.customer_id, a.drivingdate desc, columnnr) aa
         where aa.columnnr <= aa.number_value4
         group by aa.reportparam_id, aa.mainroutecontrol_id, aa.customer_id, aa.product_id, aa.sizedefinition_id, aa.finishingmethod_id, aa.columnnr
         order by aa.mainroutecontrol_id, aa.customer_id, aa.columnnr) aaa
 group by aaa.reportparam_id, aaa.mainroutecontrol_id, aaa.customer_id, aaa.product_id, aaa.sizedefinition_id, aaa.finishingmethod_id
/

  CREATE OR REPLACE VIEW "V_SORTBATCHPREPARATION_AUX" ("SORTBATCHDEFINITION_ID", "PRIMARYID", "ROUTESTOP_ID", "CUSTOMER_ID", "EXPECTATIONLEVEL", "UNIQUEITEM_ID", "PLANT_ID") AS 
  select rs.specificsortbatchdefinition_id,
				ui.primaryid, rs.routestop_id, c.customer_id, (case when c.inscanbasedforecast = 'N' then 1 else 0 end),
				ui.uniqueitem_id, r.plant_id
	from route r, routestop rs, customer c, department dep, distributionpoint dip,
				weareremployment we, wearerinventory wi, uniqueitemnonpool uinp, uniqueitem ui
	where
				rs.specificsortbatchdefinition_id is not null and
				r.route_id = rs.route_id and
				rs.customer_id = c.customer_id and
				c.customer_id = dep.customer_id and
				dep.department_id = dip.department_id and
				dip.distributionpoint_id = we.distributionpoint_id and
				we.weareremployment_id = wi.weareremployment_id and
				wi.wearerinventory_id = uinp.wearerinventory_id and
				uinp.uniqueitem_id = ui.uniqueitem_id and
				rs.stoptype != 2 and
				(rs.deliverypoint_id is null or
					(we.deliverypoint_id = rs.deliverypoint_id) or
					(we.locker_id is not null and exists (select l.locker_id from locker l where l.deliverypoint_id = rs.deliverypoint_id and we.locker_id = l.locker_id)) or
					(we.garmentdispenser_id is not null and exists (select gd.garmentdispenser_id from garmentdispenser gd where gd.deliverypoint_id = rs.deliverypoint_id and we.garmentdispenser_id = gd.garmentdispenser_id))
				)
union
select r.sortbatchdefinition_id,
				ui.primaryid, rs.routestop_id, c.customer_id, (case when c.inscanbasedforecast = 'N' then 1 else 0 end),
				ui.uniqueitem_id, r.plant_id
	from route r, routestop rs, customer c, department dep, distributionpoint dip,
				weareremployment we, wearerinventory wi, uniqueitemnonpool uinp, uniqueitem ui
	where
				rs.specificsortbatchdefinition_id is null and r.sortbatchdefinition_id is not null and
				r.route_id = rs.route_id and
				rs.customer_id = c.customer_id and
				c.customer_id = dep.customer_id and
				dep.department_id = dip.department_id and
				dip.distributionpoint_id = we.distributionpoint_id and
				we.weareremployment_id = wi.weareremployment_id and
				wi.wearerinventory_id = uinp.wearerinventory_id and
				uinp.uniqueitem_id = ui.uniqueitem_id and
				rs.stoptype != 2 and
				(rs.deliverypoint_id is null or
					(we.deliverypoint_id = rs.deliverypoint_id) or
					(we.locker_id is not null and exists (select l.locker_id from locker l where l.deliverypoint_id = rs.deliverypoint_id and we.locker_id = l.locker_id)) or
					(we.garmentdispenser_id is not null and exists (select gd.garmentdispenser_id from garmentdispenser gd where gd.deliverypoint_id = rs.deliverypoint_id and we.garmentdispenser_id = gd.garmentdispenser_id))
				)
/

  CREATE OR REPLACE VIEW "V_SPECIFICTURNOVERDEF_CUST" ("REPORTPARAM_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_ID") AS 
  select rp.reportparam_id, bill.customernumber, bill.name customername, bill.customer_id
from customer bill, customer del, reportparam rp
where bill.customer_id = del.debtor_id
  and bill.customernumber between rp.number_value2 and rp.number_value3
  and del.customernumber between rp.number_value4 and rp.number_value5
  and exists (select * from customeractivities ca
      where ca.customer_id = del.customer_id
        and ca.processbusinessunit_id = rp.number_value1)
  and exists (select * from customeractivities ca
      where ca.customer_id = bill.customer_id
        and ca.processbusinessunit_id = rp.number_value1)
  and rp.number_value6 = 1
union all
-- rest
select rp.reportparam_id, del.customernumber, del.name customername, del.customer_id
from customer del, reportparam rp
where del.customernumber between rp.number_value4 and rp.number_value5
  and exists (select * from customeractivities ca
      where ca.customer_id = del.customer_id
        and ca.processbusinessunit_id = rp.number_value1)
  and rp.number_value6 = 2
/

  CREATE OR REPLACE VIEW "V_STOCKRECEPTIONPERDATE_AUX" ("CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "FULLNAME", "WORKORDERNUMBER", "WONEEDEDDATE", "REFERENCENUMBER", "QTYDIFF", "QTYRECEIVED", "PURCHASEORDERNUMBER", "SUPPLIERNUMBER", "SUPPLIERNAME", "STOCKROOM_ID", "CUSTOMER_ID", "PRODUCT_LINK_ID", "SIZEDEFINITION_LINK_ID", "PURCHASEORDERLINE_ID") AS 
  Select
  cu.customernumber, cu.name customerName, we.wearernumber, we.wearername fullname
, coalesce(wok.workordernumber, -1) workordernumber
, wok.neededdate woneededdate
, wok.referencenumber
, ( SELECT
SUM (coalesce((WORKORDERLINE.quantityordered - WORKORDERLINE.quantitycancelled),0)) -- WORKORDERLINE.quantityfilled
FROM WORKORDERLINE WHERE WORKORDERLINE.WORKORDER_ID = WOK.WORKORDER_ID AND WORKORDERLINE.PURCHASEORDERLINE_ID = PHLI.PURCHASEORDERLINE_ID
GROUP BY WOK.WORKORDER_ID
  ) QtyDiff,
(select
SUM (coalesce((WORKORDERLINE.Quantityfilled),0))
FROM WORKORDERLINE WHERE WORKORDERLINE.WORKORDER_ID = WOK.WORKORDER_ID AND WORKORDERLINE.PURCHASEORDERLINE_ID = PHLI.PURCHASEORDERLINE_ID
GROUP BY WOK.WORKORDER_ID
  ) QtyReceived
, ph.purchaseordernumber, supplier.suppliernumber, supplier.name suppliername
, ph.stockroom_id, coalesce(cu.customer_id, -1) customer_id
, phli.product_link_id, phli.sizedefinition_link_id
, phli.purchaseorderline_id
from
  purchaseorderheader ph, purchaseorderline phli left outer join  workorderline wokli on phli.purchaseorderline_id = wokli.purchaseorderline_id
  left outer join  workorder wok on wokli.workorder_id = wok.workorder_id
    left outer join customer_link cu on wok.customer_link_id = cu.customer_link_id
    left outer join weareremployment_link we on wok.weareremployment_link_id = we.weareremployment_link_id
, supplier
where
    ph.supplier_id = supplier.supplier_id
and ph.purchaseorderheader_id = phli.purchaseorderheader_id
union
Select
  cu.customernumber, cu.name customerName, we.wearernumber, we.wearername fullname
, coalesce(wok.workordernumber, -1) workordernumber
, wok.neededdate woneededdate
, wok.referencenumber
, ( SELECT
SUM (coalesce((WORKORDERLINE.quantityordered - WORKORDERLINE.quantitycancelled),0)) -- WORKORDERLINE.quantityfilled
FROM WORKORDERLINE WHERE WORKORDERLINE.WORKORDER_ID = WOK.WORKORDER_ID AND WORKORDERLINE.PURCHASEORDERLINE_ID = PHLI.PURCHASEORDERLINE_ID
GROUP BY WOK.WORKORDER_ID
  ) QtyDiff,
(select
SUM (coalesce((WORKORDERLINE.Quantityfilled),0))
FROM WORKORDERLINE WHERE WORKORDERLINE.WORKORDER_ID = WOK.WORKORDER_ID AND WORKORDERLINE.PURCHASEORDERLINE_ID = PHLI.PURCHASEORDERLINE_ID
GROUP BY WOK.WORKORDER_ID
  ) QtyReceived
, ph.purchaseordernumber, supplier.suppliernumber, supplier.name suppliername
, ph.stockroom_id, coalesce(cu.customer_id, -1) customer_id
, phli.product_link_id, phli.sizedefinition_link_id
, phli.purchaseorderline_id
from
  purchaseorderheader ph, purchaseorderline phli, workorderlinepurchordline wolpol, workorderline wokli
  left outer join  workorder wok on wokli.workorder_id = wok.workorder_id
  left outer join customer_link cu on wok.customer_link_id = cu.customer_link_id
  left outer join weareremployment_link we on wok.weareremployment_link_id = we.weareremployment_link_id
, supplier
where
    ph.supplier_id = supplier.supplier_id
and ph.purchaseorderheader_id = phli.purchaseorderheader_id
and phli.purchaseorderline_id=wolpol.workorderlinepurchordline_id and wokli.workorderline_id=wolpol.workorderline_id
/

  CREATE OR REPLACE VIEW "V_STOCKRECEPTION_AUX" ("CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "FULLNAME", "WORKORDERNUMBER", "QTYDIFF", "PURCHASEORDERNUMBER", "SUPPLIERNUMBER", "STOCKROOM_ID", "CUSTOMER_ID", "PRODUCT_LINK_ID", "SIZEDEFINITION_LINK_ID") AS 
  Select
  cu.customernumber, cu.name customerName, we.wearernumber, we.wearername fullname
, coalesce(wok.workordernumber, -1) workordernumber
, ( SELECT
SUM (coalesce((WORKORDERLINE.quantityordered - WORKORDERLINE.quantityfilled - WORKORDERLINE.quantitycancelled),0))
FROM WORKORDERLINE WHERE WORKORDERLINE.WORKORDER_ID = WOK.WORKORDER_ID AND WORKORDERLINE.PURCHASEORDERLINE_ID = PHLI.PURCHASEORDERLINE_ID
GROUP BY WOK.WORKORDER_ID
  ) QtyDiff
, ph.purchaseordernumber, supplier.suppliernumber
, ph.stockroom_id, coalesce(cu.customer_id, -1) customer_id
, phli.product_link_id, phli.sizedefinition_link_id
from
  purchaseorderheader ph, purchaseorderline phli
, workorderline wokli
, workorder wok
    left outer join customer_link cu on wok.customer_link_id = cu.customer_link_id
    left outer join weareremployment_link we on wok.weareremployment_link_id = we.weareremployment_link_id
, supplier
where
    ph.supplier_id = supplier.supplier_id
and ph.purchaseorderheader_id = phli.purchaseorderheader_id
and phli.purchaseorderline_id = wokli.purchaseorderline_id
   and wokli.workorder_id = wok.workorder_id
union
Select
  cu.customernumber, cu.name customerName, we.wearernumber, we.wearername fullname
, coalesce(wok.workordernumber, -1) workordernumber
, ( SELECT
SUM (coalesce((WORKORDERLINE.quantityordered - WORKORDERLINE.quantityfilled - WORKORDERLINE.quantitycancelled),0))
FROM WORKORDERLINE WHERE WORKORDERLINE.WORKORDER_ID = WOK.WORKORDER_ID AND WORKORDERLINE.PURCHASEORDERLINE_ID = PHLI.PURCHASEORDERLINE_ID
GROUP BY WOK.WORKORDER_ID
  ) QtyDiff
, ph.purchaseordernumber, supplier.suppliernumber
, ph.stockroom_id, coalesce(cu.customer_id, -1) customer_id
, phli.product_link_id, phli.sizedefinition_link_id
from
  purchaseorderheader ph, purchaseorderline phli
, workorderline wokli
, workorder wok
    left outer join customer_link cu on wok.customer_link_id = cu.customer_link_id
    left outer join weareremployment_link we on wok.weareremployment_link_id = we.weareremployment_link_id
, supplier, workorderlinepurchordline wolpol
where ph.supplier_id = supplier.supplier_id
and ph.purchaseorderheader_id = phli.purchaseorderheader_id
and phli.purchaseorderline_id=wolpol.workorderlinepurchordline_id and wokli.workorderline_id=wolpol.workorderline_id
and wokli.workorder_id = wok.workorder_id
/

  CREATE OR REPLACE VIEW "V_STOCKUNIQUEQTY" ("STOCKRESERVATIONPERGRADE_ID", "QTYUNIQUE", "QTYUNIQUEWITHMODIFICATIONS", "QTYNONUNIQUE") AS 
  select sq.stockreservationpergrade_id,
  sum(sq.qtyunique) qtyunique, sum(sq.qtyuniquewithmodifications) qtyuniquewithmodifications,
  sum(sq.qtynonunique) qtynonunique
from stockroomlocation srl, stockquantity sq
where srl.stockroomlocation_id = sq.stockroomlocation_id
group by srl.stockroom_id, sq.stockreservationpergrade_id
/

  CREATE OR REPLACE VIEW "V_TASKATTACHEMENT" ("ID", "TASKID", "VERSION", "ATTACHEMENTTYPE", "SUBTYPE", "CONTENT", "REFERENCE", "UNITOFMEASURE", "QUANTITY", "BINARYCONTENT", "FORMAT", "CREATEDON", "CREATEDBY", "DEVICE", "EXTRA", "ORDERREFENCE", "PROCESSLOGIC", "DRIVINGDATE", "TIMESTAMP", "PLANTDEPARTMENTCODE", "PLANTDEPARTMENTDESCRIPTION", "STOP_ID") AS 
  select to_char(pkl.packingnoteline_id) id,
       case nvl(pk.stop_id, 0)
          when 0 then
           'DN' || to_char(pk.packingnote_id)
          else
           to_char(pk.stop_id)
        end taskid, 1 version, 6 attachementtype, 'ItemsPlanned' subtype,
       (select pd.description
         from   product_desc pd
         where  pd.language_id = pt.language_id
         and    pd.product_id = pkl.product_id) content, p.code reference,
       (select un.code from registrationunit un where un.registrationunit_id = p.registrationunit_id) unitofmeasure,
       pkl.deliveredamount quantity, null binarycontent,
       productgroupformat(p.productgroup_id) format,
       to_char(pkl.timestamp, 'YYYY-MM-DD HH24:MI:SS') createdon, null createdby, null device,
       (select sd.description
         from   sizedefinition_desc sd
         where  pkl.sizedefinition_id = sd.sizedefinition_id
         and    sd.language_id = pt.language_id) extra, pk.notenumber orderrefence,
       case pk.straightevenreturn
          when 'Y' then
           'Update'
          else
           'Fixed'
        end processlogic, rc.drivingdate,
       case
         when pk.timestamp < rc.timestamp then
          rc.timestamp
         else
          pk.timestamp
       end timestamp, ptd.code plantdepartmentcode, ptd.description plantdepartmentdescription,
       pk.stop_id
from   packingnote pk
join   packingnoteline pkl
on     pk.packingnote_id = pkl.packingnote_id
left   outer join routecontrol rc
on     (pk.routecontrol_id = rc.routecontrol_id and rc.pocketpcstatus <> 0 and
       rc.pocketpcstatus <> 2)
join   product p
on     pkl.product_id = p.product_id
join   plantdepartment ptd
on     ptd.plantdepartment_id = pk.plantdepartment_id
join   plant pt
on     pt.plant_id = ptd.plant_id
where  (exists (select 1
                from   status st
                where  pk.status_id = st.status_id
                and    st.code = '30' --(processed)
                and    st.statustype = 'PN') or pk.straightevenreturn = 'Y')
and    (pk.stop_id is null or rc.routecontrol_id is not null)
union
select 'SR' || to_char(str.straightevenreturn_id) id, to_char(str.stop_id) taskid, 1 version,
       6 attachementtype, null subtype,
       (select pd.description
         from   product_desc pd
         where  pd.language_id = pt.language_id
         and    pd.product_id = str.product_id) content, p.code reference,
       (select un.code from registrationunit un where un.registrationunit_id = p.registrationunit_id) unitofmeasure,
       (str.qtyexpected - str.qtyreturned) quantity, null binarycontent,
       productgroupformat(p.productgroup_id) format,
       to_char(str.timestamp, 'YYYY-MM-DD HH24:MI:SS') createdon, null createdby, null device,
       (select sd.description
         from   sizedefinition_desc sd
         where  str.sizedefinition_id = sd.sizedefinition_id
         and    sd.language_id = pt.language_id) extra, null orderrefence, null processlogic,
       null drivingdate,
       case
          when str.timestamp < rc.timestamp then
           rc.timestamp
          else
           str.timestamp
        end timestamp, ptd.code plantdepartmentcode, ptd.description plantdepartmentdescription,
       stp.stop_id
from   straightevenreturn str
join   stop stp
on     stp.stop_id = str.stop_id
join   routecontrol rc
on     (rc.routecontrol_id = stp.routecontrol_id)
join   status st
on     (st.status_id = str.status_id and st.code = '10' and st.statustype = 'ST')
join   product p
on     p.product_id = str.product_id
join   plant pt
on     rc.plant_id = pt.plant_id
left   outer join(standarddelivery std
join   plantdepartment ptd
on     ptd.plantdepartment_id = std.plantdepartment_id) on (std.distributionpoint_id = str.distributionpoint_id and std.sequencenumber = 1)
/

  CREATE OR REPLACE VIEW "V_TURNOVERGROUP" ("TURNOVERGROUPCODE", "TURNOVERGROUPDESCRIPTION", "LEGACYCODE", "ACTIVE", "SALESJOURNALGROUPCODE", "SALESJOURNALGROUPDESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP", "TURNOVERGROUP_ID", "LANGUAGECODE") AS 
  select a.code turnovergroupcode,
 (SELECT description FROM turnovergroup_desc d WHERE d.turnovergroup_id = a.turnovergroup_id
  AND d.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) turnovergroupdescription,
 a.legacycode, a.active,
 c.code salesjournalgroupcode,
 (SELECT description FROM salesjournalgroup_DESC e WHERE e.salesjournalgroup_id = a.salesjournalgroup_id
  AND e.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) salesjournalgroupdescription,
 a.systemuser_id, a.timestamp,
 a.turnovergroup_id, languages.code languagecode
from turnovergroup a,  salesjournalgroup c, languages
where a.salesjournalgroup_id = c.salesjournalgroup_id
/

  CREATE OR REPLACE VIEW "V_UNIQUEORPACK" ("UNIQUEITEM_ID", "BUSINESSUNIT_ID", "PRIMARYID", "PRODUCT_ID", "SIZEDEFINITION_ID", "FINISHINGMETHOD_ID", "FMCOLOR", "STATUS_ID", "STAY_ID", "TREATMENTTYPE_ID", "EXPIRATIONDATE", "STOCKEXPIRATIONDATE", "CREATIONTIMESTAMP", "CREATIONEMPLOYEE_ID", "LABELLAYOUT_ID", "ASSEMBLETIMESTAMP", "ASSEMBLEEMPLOYEE_ID", "LOADTIMESTAMP", "LOADEMPLOYEE_ID", "CART_ID", "CHARGENUMBER", "STERILIZER_ID", "REJECTREASONCODE_ID", "STERILIZATIONTIMESTAMP", "STERILIZATIONEMPLOYEE_ID", "DELIVERYTIMESTAMP", "DELIVERYEMPLOYEE_ID", "DISTRIBUTIONPOINT_ID", "CUSTOMER_ID", "PACKINGNOTE_ID", "DELIVERYBUSINESSUNIT_ID", "CANCELTIMESTAMP", "CANCELEMPLOYEE_ID", "CANCELREASONCODE_ID", "RECALLTIMESTAMP", "RECALLEMPLOYEE_ID", "RECALLREASONCODE_ID", "LASTDISTRIBUTIONPOINT_ID", "INTERNALPROCESSINGBU_ID", "PLANTDEPARTMENT_ID") AS 
  select uorp.uniqueitem_id uniqueitem_id,
       ui.businessunit_id businessunit_id,
       ui.primaryid primaryid,
       ui.product_id product_id,
       ui.sizedefinition_id sizedefinition_id ,
       ui.finishingmethod_id finishingmethod_id,
       (select fm.color from finishingmethod fm where fm.finishingmethod_id=ui.finishingmethod_id)fmcolor,
       ui.status_id status_id,
       ui.stay_id stay_id,
       uorp.treatmenttype_id treatmenttype_id,
       ui.expirationdate expirationdate,
       uorp.stockexpirationdate stockexpirationdate,
       uorp.creationtimestamp creationtimestamp,
       uorp.creationemployee_id creationemployee_id,
       uorp.labellayout_id labellayout_id,
       uorp.assembletimestamp assembletimestamp,
       uorp.assembleemployee_id assembleemployee_id,
       uorp.loadtimestamp loadtimestamp,
       uorp.loademployee_id loademployee_id,
       uorpc.cart_id cart_id,
       sr.chargenumber,
       sr.sterilizer_id,
       sr.rejectreasoncode_id,
       uorps.sterilizationtimestamp sterilizationtimestamp,
       uorps.sterilizationemployee_id sterilizationemployee_id,
       uorp.deliverytimestamp deliverytimestamp,
       uorp.deliveryemployee_id deliveryemployee_id,
       nvl(ui.distributionpoint_id, ds.distributionpoint_link_id) distributionpoint_id,
       case nvl(ui.distributionpoint_id,0) when 0 then null
       else d.customer_id
       end customer_id,
       ds.packingnote_id packingnote_id,
       ds.businessunit_id deliverybusinessunit_id,
       uorp.canceltimestamp canceltimestamp,
       uorp.cancelemployee_id cancelemployee_id,
       case nvl(uorp.canceltimestamp, to_date('31-12-2099', 'dd-mm-yyyy')) when to_date('31-12-2099', 'dd-mm-yyyy') then null
       else uorp.reasoncode_id
       end cancelreasoncode_id,
       uorp.recalltimestamp recalltimestamp,
       uorp.recallemployee_id recallemployee_id,
       case nvl(uorp.recalltimestamp, to_date('31-12-2099', 'dd-mm-yyyy')) when to_date('31-12-2099', 'dd-mm-yyyy') then null
       else uorp.reasoncode_id
       end recallreasoncode_id,
       nvl(ui.lastdistributionpoint_link_id, distributionpoint_link_id) LastDistributionPoint_ID,
       (select pn.internalprocessingbu_id from packingnote pn where ds.packingnote_id=pn.packingnote_id)internalprocessingbu_id,
       (select pn.plantdepartment_id from packingnote pn where ds.packingnote_id=pn.packingnote_id) plantdepartment_id
from uniqueorpack uorp
left outer join uniqueorpackcart uorpc on uorp.uniqueitem_id = uorpc.uniqueitem_id
left outer join deliveryscan ds on uorp.uniqueitem_id = ds.uniqueitem_link_id
left outer join (uniqueorpacksterile uorps
 join sterilizationrun sr on uorps.sterilizationrun_id = sr.sterilizationrun_id and uorps.sterilizationtimestamp =
                                 (select max(sterilizationtimestamp)
                                    from uniqueorpacksterile uorps1 where uorps1.uniqueitem_id = uorps.uniqueitem_id))on uorp.uniqueitem_id = uorps.uniqueitem_id,
 uniqueitem ui
  left outer join (distributionpoint dp
  left outer join department d on dp.department_id = d.department_id) on ui.distributionpoint_id = dp.distributionpoint_id
where
uorp.uniqueitem_id = ui.uniqueitem_id
/

  CREATE OR REPLACE VIEW "V_UNIQUETRUCKLOADLISTORIGINAS" ("PICKLIST_ID", "ORDERNUMBER", "CONSUMPTIONPOINT_ID", "BASELINETYPE", "REQUESTEDDELIVERYDATE") AS 
  select pl.picklist_id, wo.workordernumber ordernumber, wo.distributionpoint_link_id consumptionpoint_id, ploa.baselinetype, wo.neededdate requesteddeliverydate
from picklist pl, picklistlineas plla, picklistlineoriginas ploa,
     workorderline wol, workorder wo
where plla.picklist_id = pl.picklist_id
and ploa.picklistlineas_id = plla.picklistlineas_id
and upper(ploa.baselinetable) = 'WORKORDERLINE'
and ploa.baselinetable_link_id = wol.workorderline_id
and ploa.baselinetype = wo.origin
and wo.workorder_id = wol.workorder_id
and wo.origin = 10
--group by pl.picklist_id, wo.workordernumber, wo.neededdate, wo.distributionpoint_link_id, ploa.baselinetype
union all
select pl.picklist_id, wo.workordernumber ordernumber, wo.distributionpoint_link_id consumptionpoint_id, ploa.baselinetype, wo.neededdate requesteddeliverydate
from picklist pl, picklistlineas plla, picklistlineoriginas ploa,
     workorderline wol, workorder wo
where plla.picklist_id = pl.picklist_id
and ploa.picklistlineas_id = plla.picklistlineas_id
and upper(ploa.baselinetable) = 'WORKORDERLINE'
and ploa.baselinetable_link_id = wol.workorderline_id
and ploa.baselinetype = wo.origin
and wo.workorder_id = wol.workorder_id
and wo.origin = 6
and wo.driversales = 'N'
and wo.mountingordersales = 'N'
--group by pl.picklist_id, wo.workordernumber, wo.neededdate, wo.distributionpoint_link_id, ploa.baselinetype
union all
select pl.picklist_id, pn.notenumber ordernumber, pn.distributionpoint_id consumptionpoint_id, ploa.baselinetype, pn.deliverydate requesteddeliverydate
from picklist pl, picklistlineas plla, picklistlineoriginas ploa,
     packingnoteline pnl, packingnote pn
where plla.picklist_id = pl.picklist_id
and ploa.picklistlineas_id = plla.picklistlineas_id
and upper(ploa.baselinetable) = 'PACKINGNOTELINE'
and ploa.baselinetable_link_id = pnl.packingnoteline_id
and ploa.baselinetype = 90
and pn.packingnote_id = pnl.packingnote_id
--group by pl.picklist_id, pn.notenumber, pn.distributionpoint_id, ploa.baselinetype
/

  CREATE OR REPLACE VIEW "V_UNIQUETRUCKLOADLISTORIGINPS" ("PICKLIST_ID", "ORDERNUMBER", "CONSUMPTIONPOINT_ID", "BASELINETYPE", "REQUESTEDDELIVERYDATE") AS 
  select pl.picklist_id, wo.workordernumber ordernumber, wo.distributionpoint_link_id consumptionpoint_id, plo.baselinetype, wo.neededdate requesteddeliverydate
from picklist pl, picklistline pll, picklistlineorigin plo,
     workorderline wol, workorder wo
where pll.picklist_id = pl.picklist_id
and plo.picklistline_id = pll.picklistline_id
and upper(plo.baselinetable) = 'WORKORDERLINE'
and plo.baselinetable_link_id = wol.workorderline_id
and plo.baselinetype = wo.origin
and wo.workorder_id = wol.workorder_id
and wo.origin = 10
--group by pl.picklist_id, wo.workordernumber, wo.neededdate, wo.distributionpoint_link_id, plo.baselinetype
union all
select pl.picklist_id, wo.workordernumber ordernumber, wo.distributionpoint_link_id consumptionpoint_id, plo.baselinetype, wo.neededdate requesteddeliverydate
from picklist pl, picklistline pll, picklistlineorigin plo,
     workorderline wol, workorder wo
where pll.picklist_id = pl.picklist_id
and plo.picklistline_id = pll.picklistline_id
and upper(plo.baselinetable) = 'WORKORDERLINE'
and plo.baselinetable_link_id = wol.workorderline_id
and plo.baselinetype = wo.origin
and wo.workorder_id = wol.workorder_id
and wo.origin = 6
and wo.driversales = 'N'
and wo.mountingordersales = 'N'
--group by pl.picklist_id, wo.workordernumber, wo.neededdate, wo.distributionpoint_link_id, plo.baselinetype
union all
select pl.picklist_id, pn.notenumber ordernumber, pn.distributionpoint_id consumptionpoint_id, plo.baselinetype, pn.deliverydate requesteddeliverydate
from picklist pl, picklistline pll, picklistlineorigin plo,
     packingnoteline pnl, packingnote pn
where pll.picklist_id = pl.picklist_id
and plo.picklistline_id = pll.picklistline_id
and upper(plo.baselinetable) = 'PACKINGNOTELINE'
and plo.baselinetable_link_id = pnl.packingnoteline_id
and plo.baselinetype = 90
and pn.packingnote_id = pnl.packingnote_id
--group by pl.picklist_id, pn.notenumber, pn.deliverydate, pn.distributionpoint_id, plo.baselinetype
/

  CREATE OR REPLACE VIEW "V_WORKORDERLINE" ("WORKORDERLINE_ID", "WORKORDER_ID", "PRODNR", "FINMETHCODE", "SIZECODE", "UNIQUEYN", "QUANTITYORDERED", "QUANTITYCANCELLED", "QORDER", "QDONE", "QOPEN", "MODIFICATIONCODE", "INSTRUCTIONS", "LANGUAGECODE", "SALESEMPLOYEE1NUMBER", "SALESEMPLOYEE1NAME", "SALESEMPLOYEE2NUMBER", "SALESEMPLOYEE2NAME", "QUALITYGRADE_CODE", "REASONCODE_ID", "RENTALQTYADJUSTMENT_ID", "EXECUTEDBY", "SEQUENCENUMBER", "PRODDESCRIPTION", "PRODLONGDESCRIPTION", "QUALITYGRADE", "MODIFICATIONGROUPCODE", "MODIFICATIONDESC") AS 
  select /*version 2.0*/
       wokli.workorderline_id, wokli.workorder_id, prdlk.code prodnr, fm.code finmethcode, szlk.code sizecode, wokli.codeuniquely uniqueyn,
       wokli.quantityordered, wokli.quantitycancelled, (wokli.quantityordered - wokli.quantitycancelled) qorder, wokli.quantityfilled qdone,
       (wokli.quantityordered - wokli.quantityfilled - wokli.quantitycancelled) qopen, mo.code modificationcode, wokli.instructions,
       lan.code languagecode, e1.employeenumber salesemployee1number, e1.name salesemployee1name, e2.employeenumber salesemployee2number,
       e2.name salesemployee2name, qg.code qualitygrade_code, wokli.reasoncode_id, wokli.rentalqtyadjustment_id, wokli.executedby, pds.sequencenumber,
       (select prde.description
          from product_desc prde
         where prde.product_id = prdlk.product_id
           and prde.language_id = lan.language_id) proddescription,
       (select prde.longdescription
          from product_desc prde
         where prdlk.product_id = prde.product_id
           and prde.language_id = lan.language_id) prodlongdescription,
       (select qgd.description
          from qualitygrade_desc qgd
         where qgd.qualitygrade_id = qg.qualitygrade_id
           and qgd.language_id = lan.language_id) qualitygrade,
       (select mdgr.code
          from productmodificationgroup prdmspg
               join modificationspergroup mdspg on prdmspg.modificationgroup_id = mdspg.modificationgroup_id
                                                and mdspg.modification_id = mo.modification_id
               join modificationgroup mdgr on mdspg.modificationgroup_id = mdgr.modificationgroup_id
         where prdmspg.product_id = wokli.product_link_id
           and prdmspg.sequencenumber = wolm.sequencenumber) modificationgroupcode,
       (select modesc.description
          from modification_desc modesc
         where modesc.modification_id = mo.modification_id
           and modesc.language_id = lan.language_id) modificationdesc
  from workorderline wokli
       left join qualitygrade qg on wokli.requestedgrade_id = qg.qualitygrade_id
       left join product_link prdlk on wokli.product_link_id = prdlk.product_link_id
       left join sizedefinition_link szlk on wokli.sizedefinition_link_id = szlk.sizedefinition_link_id
       left join finishingmethod fm on wokli.finishingmethod_id = fm.finishingmethod_id
       left join productsize pds on wokli.product_link_id = pds.product_id and wokli.sizedefinition_link_id = pds.sizedefinition_id
       left join workorderlinemodification wolm
            join modification mo on wolm.modification_id = mo.modification_id
       on wokli.workorderline_id = wolm.workorderline_id
       left join employee e1 on wokli.salesemployee1_id = e1.employee_id
       left join employee e2 on wokli.salesemployee2_id = e2.employee_id
       cross join languages lan
/

  CREATE OR REPLACE VIEW "XV_TEST_CIRC_INVENTORY" ("WEARERINVENTORY_ID", "COUNTUI", "COUNTNUI") AS 
  select wi.wearerinventory_id, count(ui.uniqueitem_id) countUI, 0
	from wearerinventory wi, uniqueitem ui, uniqueitemnonpool uinp, status s
	where ui.uniqueitem_id = uinp.uniqueitem_id and ui.status_id = s.status_id and s.code = '20' and
		wi.wearerinventory_id = uinp.wearerinventory_id
	group by wi.wearerinventory_id
union
select wi.wearerinventory_id, 0, count(nui.nonuniqueitem_id) countNUI
	from wearerinventory wi, nonuniqueitem nui
	where wi.wearerinventory_id = nui.wearerinventory_id
	group by wi.wearerinventory_id
/

  CREATE OR REPLACE VIEW "VR_COMPLETENESSCUSTOMER" ("REPORTPARAM_ID", "BUSINESSUNIT_ID", "LANGUAGECODE", "PLANNEDDELIVERYDATE", "LASTINSCANDATE", "STATUS_ID", "PRODUCTCODE", "PRODUCTDESC", "ROUTENUMBER", "ROUTEDESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DAY_ID", "CUSTOMERADDRES", "IDCODE", "STAY", "FLAG_NO", "MAXCOMPLETENESSDAYS", "INTERNALBU") AS 
  select rp.reportparam_id, b.businessunit_id businessunit_id, languages.code languagecode,
       case when c.staynr = 36 then getabsmindate() else b.planneddeliverydate end planneddeliverydate,
       b.lastinscandate, b.status_id, ce.code productcode,
       (select w.description from product_desc w where w.product_id = ce.product_id and w.language_id = languages.language_id) productdesc,
       1 routenumber, '' routedesc, cg.customernumber, cg.name customername, ch.departmentnumber, ch.description departmentdesc, -1 day_id,
       cast(concatenatewithblank3(ci.street, ci.zipcode, ci.city) as varchar2(255)) customeraddres, b.primaryid idcode,
       case when c.staynr = 30 and (st.code = '20' or st.code = '30') then 1
         when c.staynr = 32 and (st.code = '20' or st.code = '30') then 2
         when c.staynr = 31 and (st.code = '20' or st.code = '30') then 3
         when (c.staynr between 33 and 99 and c.staynr <> 36) and (st.code = '20' or st.code = '30') then 4
         when c.staynr = 36 and (st.code = '20' or st.code = '30') then 5
         when c.staynr = 10 and st.code = '30' then 6
         when c.staynr = 10 and st.code = '20' then 6.1 -- lss/lst customization based on module lstcustom
       end "STAY", 0 flag_no, getdatediff(trunc(sysdate), b.lastinscandate) maxcompletenessdays,
       coalesce((select ca.internalprocessingbu_id from customeractivities ca, productgroup pg
                        where ca.customer_id = cg.customer_id and ce.productgroup_id = pg.productgroup_id
                        and pg.activity_id = ca.activity_id and b.businessunit_id=ca.processbusinessunit_id), -1) internalbu
from stay c,reportparam rp, uniqueitemnonpool e, weareremployment f
  left outer join flag f2 on f2.flag_id = f.flag_id and f2.includeincompletnesscheck = 'N',
 distributionpoint g, wearer h
  left outer join flag f1 on f1.flag_id = h.flag_id and f1.includeincompletnesscheck = 'N',
 uniqueitem b, status st, product ce, department ch, address ci, customer cg, languages
where b.poolitem = 2
   and b.stay_id = c.stay_id
   and c.staytype = 1
   and e.weareremployment_id = f.weareremployment_id
   and f.distributionpoint_id = g.distributionpoint_id
   and f.wearer_id = h.wearer_id
   and b.status_id = st.status_id
   and st.statustype = 'UI'
   and b.product_id = ce.product_id
   and h.customer_id = cg.customer_id
   and g.department_id = ch.department_id
   and cg.visitaddress_id = ci.address_id
   and b.uniqueitem_id = e.uniqueitem_id
   and (b.planneddeliverydate <= rp.date_value1 or c.staynr = 36)
   and (((select count(1) from customerdeliveryday cdd where cdd.customer_id = cg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
        and cdd.day_id = rp.number_value1 and rp.number_value4 = 0) > 0)
     or (( (select count(1) from customerdeliveryday cdd where cdd.customer_id = cg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
                  and cdd.day_id = rp.number_value1) > 0)
        or ((select count(1) from routecontrol rc, stop where stop.customer_link_id = cg.customer_id and stop.routestop_id is not null
           and stop.stoptype = 3 and stop.routecontrol_id = rc.routecontrol_id and rc.drivingdate = rp.date_value1 and rp.number_value4 = 1) > 0)))
  and c.staynr not in (20, 22, 23, 24, 25)
  and (( rp.number_value2 = 1 and c.staynr <> '37') or rp.number_value2 = 0)
--  and rp.number_value=cg.customer_id
  and cg.customernumber >= rp.number_value8 and cg.customernumber <= rp.number_value9
  and rp.date_value1>= coalesce(b.planneddeliverydate, b.lastscandate)
  and (f1.flag_id is null or h.flagstartdate > rp.date_value1)
  and (f2.flag_id is null or f.flagstartdate > rp.date_value1)
  and not exists ( select 1 from vr_uniqueitemflag uf where uf.uniqueitem_id = b.uniqueitem_id and uf.uniqueitemflagdate < rp.date_value1)
union all
select rp.reportparam_id, ds.businessunit_id, languages.code languagecode,
 getabsmindate() planneddeliverydate, b.lastinscandate lastinscan_date, b.status_id, p.code productcode,
 (select w.description from product_desc w where w.product_id = p.product_id and w.language_id = languages.language_id) productdesc,
 1 routenumber, '' routedesc, cg.customernumber, cg.name customername, ch.departmentnumber, ch.description departmentdesc,
 -1 day_id, ci.street customeraddres, b.primaryid idcode, 7 "STAY", 0 flag_no, 0 maxcompletenessdays, ds.internalprocessingbu_id internalbu
from product p, uniqueitem  b,
  deliveryscan ds left outer join weareremployment f
               inner join  wearer h on f.wearer_id = h.wearer_id
  on ds.weareremployment_link_id = f.weareremployment_id
  , distributionpoint g, customer cg, department ch, address ci, stay c,sizedefinition ck, languages, reportparam rp
where p.product_id = b.product_id
 and b.sizedefinition_id = ck.sizedefinition_id
 and b.stay_id = c.stay_id and c.staynr = 20
 and ds.uniqueitem_link_id = b.uniqueitem_id
 and ds.outscannodelivery in (0,2)
 and ( nvl(ds.packingnote_id, 0) in
             (select 0 from dual   union all
              select pn2.packingnote_id from packingnote pn2
              where pn2.origin = 2
                    and pn2.status_id = 6
                    and pn2.distributionpoint_id = ds.distributionpoint_link_id
                    and pn2.deliverypoint_id = ds.deliverypoint_link_id
                    and pn2.deliverydate = rp.date_value1)
      )
 and coalesce(h.customer_id, cg.customer_id) = cg.customer_id
 and ds.customer_link_id = cg.customer_id
 and cg.visitaddress_id = ci.address_id
 and ds.distributionpoint_link_id = g.distributionpoint_id
 and g.department_id = ch.department_id
 and ch.customer_id = cg.customer_id
 and (( (select count(1) from customerdeliveryday cdd where cdd.customer_id = cg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
        and cdd.day_id = rp.number_value1 and rp.number_value4 = 0) > 0)
     or (( (select count(1) from customerdeliveryday cdd where cdd.customer_id = cg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
                  and cdd.day_id = rp.number_value1) > 0 )
        or ((select count(1) from routecontrol rc, stop where stop.customer_link_id = cg.customer_id and stop.routestop_id is not null
           and stop.stoptype = 3 and stop.routecontrol_id = rc.routecontrol_id and rc.drivingdate = rp.date_value1 and rp.number_value4 = 1) > 0)))
-- and rp.number_value=cg.customer_id
 and cg.customernumber >= rp.number_value8 and cg.customernumber <= rp.number_value9
 and coalesce(ds.planneddeliverydate, rp.date_value1) <= rp.date_value1
 and ( (rp.number_value5 > 0 and rp.number_value5=ds.plantdepartment_id )
     or ( rp.number_value6 > 0 and rp.number_value6 = ( select a.plant_id from plantdepartment a where a.plantdepartment_id = ds.plantdepartment_id ) )
     or ( rp.number_value7 > 0 and rp.number_value7 <> ( select a.plant_id from plantdepartment a where a.plantdepartment_id = ds.plantdepartment_id ) )
     or ( rp.number_value5 = -1 and rp.number_value6 = -1 and rp.number_value7 = -1)--all pldep
     )
/

  CREATE OR REPLACE VIEW "VR_COMPLETENESSCUSTOMERDETAILS" ("LINETYPE", "REPORTPARAM_ID", "BUSINESSUNIT_ID", "STAY", "IDCODE", "UNIQUEITEM_ID", "LANGUAGECODE", "PLANNEDDELIVERYDATE", "LASTINSCAN_DATE", "LASTSCAN_DATE", "LASTINSCANDATE", "LASTSCANDATE", "STATUS_ID", "PRODUCTCODE", "PRODUCTDESC", "ROUTENUMBER", "ROUTEDESC", "FINISHINGMETHODDESC", "SIZEDEFINITIONCODE", "FLAG", "FLAG_NO", "WEARERNUMBER", "WEARERNAME", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DAY_ID", "CUSTOMERADDRES", "CUSTOMERADDRES2", "MAXCOMPLETENESSDAYS", "INTERNALBU", "COMPCHECKNONUNIQUE", "NONUNIQUEQTY", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINT_DESC", "BANKLOCKER", "NODELIVERYOFREJECTS_VALUE", "DV_ORIGIN", "DV_SOILCOUNTSUBTYPE") AS 
  select --stays 1 to 6
 1 linetype, rp.reportparam_id, b.businessunit_id,
 case when c.staynr in (30, 41) and (st.code = '20' or st.code = '30') then 1
   when c.staynr = 32 and (st.code = '20' or st.code = '30') then 2
   when c.staynr = 31 and (st.code = '20' or st.code = '30') then 3
   --when(c.staynr between 30 and 99 and c.staynr <> 36) and (st.code = '20' or st.code = '30') then 4
   when c.staynr = 36 and (st.code = '20' or st.code = '30') then 5
   when c.staynr in (10, 11) and st.code = '30' then 6
   when c.staynr = 10 and st.code = '20' then 6.1 -- lss/lst customization based on module lstcustom
 else 4 end stay, b.primaryid idcode, b.uniqueitem_id, lan.code languagecode,
 case when c.staynr = 36 then getabsmindate()
   else b.planneddeliverydate end planneddeliverydate,
 b.lastinscandate lastinscan_date, b.lastscandate lastscan_date,
 to_char(b.lastinscandate, 'MM/DD/YYYY HH:MI:SS AM') lastinscandate,
 to_char(b.lastscandate, 'MM/DD/YYYY HH:MI:SS AM') lastscandate,
 b.status_id, ce.code productcode,
 (select w.description from product_desc w where w.product_id = ce.product_id and w.language_id = lan.language_id) productdesc,
 1 routenumber, '' routedesc,
 (select y.description from finishingmethod_desc y where y.finishingmethod_id = j.finishingmethod_id
  and y.language_id = lan.language_id) finishingmethoddesc,
 ck.code sizedefinitioncode,
 (select count(1) from uniqueitemflag z, flag fl where z.uniqueitem_id = b.uniqueitem_id
   and z.flag_id = fl.flag_id and fl.includeincompletnesscheck = 'Y') flag,
 0 flag_no,
 h.wearernumber, h.fullname wearername,
 cg.customernumber, cg.name customername, ch.departmentnumber, ch.description departmentdesc, -1 day_id,
 ci.street customeraddres
 , cast(concatenatewithblank(ci.zipcode, ci.city) as varchar2(255)) customeraddres2,
 getdatediff(trunc(sysdate), b.lastinscandate) maxcompletenessdays,
 coalesce((select ca.internalprocessingbu_id from customeractivities ca, productgroup pg
 where ca.customer_id = cg.customer_id and ce.productgroup_id = pg.productgroup_id
 and pg.activity_id = ca.activity_id and b.businessunit_id = ca.processbusinessunit_id), -1)internalbu,
 cast(sst.value as varchar2(1)) compchecknonunique
 , 1 nonuniqueqty, g.distributionpointnumber, g.description distributionpoint_desc
 , (select concat(concat(lc.bank,'/'),lc.locker) from locker lc where lc.locker_id = f.locker_id) banklocker,
 to_number((select sstt.value from systemsetting sstt where sstt.plant_id = bu.plant_id and sstt.name = 'NODELIVERYOFREJECTS')) nodeliveryofrejects_value,
 0 dv_origin, 0 dv_soilcountsubtype
from uniqueitem b
   inner join uniqueitemnonpool e
         inner join weareremployment f
               inner join distributionpoint g
                     inner join department ch on g.department_id = ch.department_id
               on f.distributionpoint_id = g.distributionpoint_id
               inner join wearer h
                     inner join customer cg
                           inner join address ci on cg.visitaddress_id = ci.address_id
                     on h.customer_id = cg.customer_id
                     left outer join flag f1 on f1.flag_id = h.flag_id and f1.includeincompletnesscheck = 'N'
               on f.wearer_id = h.wearer_id
               left outer join flag f2 on f.flag_id = f2.flag_id and f2.includeincompletnesscheck = 'N'
         on e.weareremployment_id = f.weareremployment_id
   on b.uniqueitem_id = e.uniqueitem_id
   inner join status st on b.status_id = st.status_id and st.statustype = 'UI'
   inner join stay c on b.stay_id = c.stay_id and c.staytype = 1
   inner join product ce on b.product_id = ce.product_id
   inner join sizedefinition ck on b.sizedefinition_id = ck.sizedefinition_id
   left outer join finishingmethod j on b.finishingmethod_id = j.finishingmethod_id
   inner join businessunit bu
         left outer join systemsetting sst on sst.plant_id = bu.plant_id and sst.name = 'COMPCHECKNONUNIQUE'
   on b.businessunit_id = bu.businessunit_id
   , languages lan, reportparam rp
where b.poolitem = 2
 and (( (select count(1) from customerdeliveryday cdd where cdd.customer_id = cg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
        and cdd.day_id = rp.number_value1 and rp.number_value4 = 0) > 0)
     or (( (select count(1) from customerdeliveryday cdd where cdd.customer_id = cg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
        and cdd.day_id = rp.number_value1) > 0)
        or ( (select /*+index(rc xie7routecontrol)*/ count(1) from routecontrol rc, stop where stop.customer_link_id = cg.customer_id and nvl(stop.routestop_id, 0) <> 0
        and stop.stoptype = 3 and stop.routecontrol_id = rc.routecontrol_id and rc.drivingdate = rp.date_value1 and rp.number_value4 = 1) > 0)))
 and c.staynr not in (20, 22, 23, 24, 25)
 and (b.planneddeliverydate <= rp.date_value1 or c.staynr = 36)
 and (( rp.number_value2 = 1 and c.staynr <> '37') or rp.number_value2 = 0)
 and cg.customernumber >= rp.number_value8 and cg.customernumber <= rp.number_value9
 and ( f1.flag_id is null or h.flagstartdate > rp.date_value1)
 and ( f2.flag_id is null or f.flagstartdate > rp.date_value1)
 and ( select count(1) from vr_uniqueitemflag uf where uf.uniqueitem_id = b.uniqueitem_id and uf.uniqueitemflagdate < rp.date_value1) = 0
union all --stay 7 outscan
select 2 linetype, rp.reportparam_id, ds.businessunit_id,
 7 stay, b.primaryid idcode, b.uniqueitem_id, lan.code languagecode,
 getabsmindate() planneddeliverydate, b.lastinscandate lastinscan_date, b.lastscandate lastscan_date,
 to_char(b.lastinscandate, 'MM/DD/YYYY HH:MI:SS AM') lastinscandate,
 to_char(b.lastscandate, 'MM/DD/YYYY HH:MI:SS AM') lastscandate,
 b.status_id, p.code productcode,
 (select w.description from product_desc w where w.product_id = p.product_id and w.language_id = lan.language_id) productdesc,
 1 routenumber, '' routedesc,
 (select y.description from finishingmethod_desc y where y.finishingmethod_id = b.finishingmethod_id
  and y.language_id = lan.language_id) finishingmethoddesc,
  ck.code sizedefinitioncode,
 (select count(1) from uniqueitemflag z, flag fl where z.uniqueitem_id = b.uniqueitem_id
   and z.flag_id = fl.flag_id and fl.includeincompletnesscheck = 'Y') flag,
 0 flag_no, h.wearernumber, h.fullname wearername,
 cg.customernumber, cg.name customername, ch.departmentnumber, ch.description departmentdesc, -1 day_id,
 ci.street customeraddres
 , cast(concatenatewithblank(ci.zipcode, ci.city) as varchar2(255)) customeraddres2,
 0 maxcompletenessdays,
 ds.internalprocessingbu_id internalbu,
 cast(sst.value as varchar2(1)) compchecknonunique
 , 1 nonuniqueqty, g.distributionpointnumber, g.description distributionpoint_desc
 , (select concat(concat(lc.bank,'/'),lc.locker) from locker lc where lc.locker_id = f.locker_id) banklocker,
 to_number((select sstt.value from systemsetting sstt where sstt.plant_id = bu.plant_id and sstt.name = 'NODELIVERYOFREJECTS')) nodeliveryofrejects_value,
 0 dv_origin, 0 dv_soilcountsubtype
from uniqueitem b
   inner join stay c on b.stay_id = c.stay_id and c.staynr = 20
   inner join product p on b.product_id = p.product_id
   inner join sizedefinition ck on b.sizedefinition_id = ck.sizedefinition_id
   inner join businessunit bu
         left outer join systemsetting sst on sst.plant_id = bu.plant_id and sst.name = 'COMPCHECKNONUNIQUE'
   on b.businessunit_id = bu.businessunit_id
   inner join deliveryscan ds
         left outer join weareremployment f
                inner join wearer h on f.wearer_id = h.wearer_id
         on ds.weareremployment_link_id = f.weareremployment_id
         inner join distributionpoint g
               inner join department ch on g.department_id = ch.department_id
         on ds.distributionpoint_link_id = g.distributionpoint_id
         inner join customer cg
               inner join address ci on cg.visitaddress_id = ci.address_id
         on ds.customer_link_id = cg.customer_id
   on b.uniqueitem_id = ds.uniqueitem_link_id --and b.lastscandate = ds.scantimestamp
   and ds.outscannodelivery in (0,2)
   , languages lan, reportparam rp
where (nvl(ds.packingnote_id, 0) in
             (select 0 from dual union all
              select pn2.packingnote_id from packingnote pn2
              where pn2.origin = 2 and pn2.status_id = 6
                    and pn2.distributionpoint_id = ds.distributionpoint_link_id
                    and pn2.deliverypoint_id = ds.deliverypoint_link_id
                    and pn2.deliverydate = rp.date_value1))
 and coalesce(h.customer_id, cg.customer_id) = cg.customer_id
 and ch.customer_id = cg.customer_id
 and (((select count(1) from customerdeliveryday cdd where cdd.customer_id = cg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
          and cdd.day_id = rp.number_value1 and rp.number_value4 = 0) > 0)
       or (((select count(1) from customerdeliveryday cdd where cdd.customer_id = cg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
                  and cdd.day_id = rp.number_value1) > 0)
         or ((select /*+index(rc xie7routecontrol)*/ count(1) from routecontrol rc, stop where stop.customer_link_id = cg.customer_id and nvl(stop.routestop_id, 0) <> 0
           and stop.stoptype = 3 and stop.routecontrol_id = rc.routecontrol_id and rc.drivingdate = rp.date_value1 and rp.number_value4 = 1) > 0)))
 and cg.customernumber >= rp.number_value8 and cg.customernumber <= rp.number_value9
 and coalesce(ds.planneddeliverydate, rp.date_value1) <= rp.date_value1
 and ( (rp.number_value5 > 0 and rp.number_value5 = ds.plantdepartment_id )
     or ( rp.number_value6 > 0 and rp.number_value6 = ( select a.plant_id from plantdepartment a where a.plantdepartment_id = ds.plantdepartment_id))
     or ( rp.number_value7 > 0 and rp.number_value7 <> ( select a.plant_id from plantdepartment a where a.plantdepartment_id = ds.plantdepartment_id))
     or ( rp.number_value5 = -1 and rp.number_value6 = -1 and rp.number_value7 = -1)--all pldep
     )
union all --only stay 1 inscan
select 3 linetype, rp.reportparam_id, b.businessunit_id,
 1 stay, '' idcode, 0 uniqueitem_id, lan.code languagecode,
 dv.deliverydate planneddeliverydate, null lastinscan_date, dv.deliverydate lastscan_date,
 to_char(dv.deliverydate, 'MM/DD/YYYY HH:MI:SS AM') lastinscandate,
 to_char(dv.deliverydate, 'MM/DD/YYYY HH:MI:SS AM') lastscandate,
 -1 status_id,
 ce.code productcode,
 (select w.description from product_desc w where w.product_id = ce.product_id
  and w.language_id = lan.language_id) productdesc,
 1 routenumber, '' routedesc,
 (select y.description from finishingmethod_desc y where y.finishingmethod_id = j.finishingmethod_id
  and y.language_id = lan.language_id) finishingmethoddesc,
 ck.code sizedefinitioncode,
 0 flag,
 0 flag_no,
 -1 wearernumber, '' wearername,
 cg.customernumber, cg.name customername, ch.departmentnumber, ch.description departmentdesc, -1 day_id,
 ci.street customeraddres
 , cast(concatenatewithblank(ci.zipcode, ci.city) as varchar2(255)) customeraddres2,
 0 maxcompletenessdays,
 coalesce((select ca.internalprocessingbu_id from customeractivities ca, productgroup pg
 where ca.customer_id = cg.customer_id and ce.productgroup_id = pg.productgroup_id
 and pg.activity_id = ca.activity_id and b.businessunit_id = ca.processbusinessunit_id), -1) internalbu,
 cast(sst.value as varchar2(1)) compchecknonunique
 , dv.amount nonuniqueqty, g.distributionpointnumber, g.description distributionpoint_desc, '' banklocker,
 to_number((select sstt.value from systemsetting sstt where sstt.plant_id = b.plant_id and sstt.name = 'NODELIVERYOFREJECTS')) nodeliveryofrejects_value,
 dv.origin dv_origin, dv.soilcountsubtype dv_soilcountsubtype
from deliveryvariations dv
  inner join distributionpoint g
        inner join department ch
              inner join customer cg
                    inner join address ci on cg.visitaddress_id = ci.address_id
              on ch.customer_id = cg.customer_id
        on g.department_id = ch.department_id
  on dv.distributionpoint_id = g.distributionpoint_id
  inner join product ce on dv.product_id = ce.product_id
  inner join sizedefinition ck on dv.sizedefinition_id = ck.sizedefinition_id
  inner join finishingmethod j on dv.finishingmethod_id = j.finishingmethod_id
  , businessunit b
         left outer join systemsetting sst on sst.plant_id = b.plant_id and sst.name = 'COMPCHECKNONUNIQUE'
  , languages lan, reportparam rp
where cg.customernumber >= rp.number_value8 and cg.customernumber <= rp.number_value9
 and (dv.packingnote_id is null or (select count(1) from packingnote pn, status stat where dv.packingnote_id = pn.packingnote_id
          and pn.status_id = stat.status_id and stat.statustype = 'PN' and stat.code = '20' and pn.deliverydate <= rp.date_value1) > 0)
 and dv.origin in (1, 5)
 and b.businessunit_id = (select min(ca.processbusinessunit_id) from customeractivities ca, productgroup pg
    where ca.customer_id = cg.customer_id and ce.productgroup_id = pg.productgroup_id and pg.activity_id = ca.activity_id)
 and (((select count(1) from customerdeliveryday cdd where cdd.customer_id = cg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
        and cdd.day_id = rp.number_value1 and rp.number_value4 = 0) > 0)
     or (( (select count(1) from customerdeliveryday cdd where cdd.customer_id = cg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
        and cdd.day_id = rp.number_value1) > 0)
        or ( (select /*+index(rc xie7routecontrol)*/ count(1) from routecontrol rc, stop where stop.customer_link_id = cg.customer_id and nvl(stop.routestop_id, 0) <> 0
        and stop.stoptype = 3 and stop.routecontrol_id = rc.routecontrol_id and rc.drivingdate = rp.date_value1 and rp.number_value4 = 1) > 0)))
 and dv.deliverydate <= rp.date_value1
 and ((rp.number_value5 > 0 and rp.number_value5 = dv.plantdepartment_id)
     or (rp.number_value6 > 0 and rp.number_value6 = (select a.plant_id from plantdepartment a where a.plantdepartment_id = dv.plantdepartment_id))
     or (rp.number_value7 > 0 and rp.number_value7 <> (select a.plant_id from plantdepartment a where a.plantdepartment_id = dv.plantdepartment_id))
     or (rp.number_value5 = -1 and rp.number_value6 = -1 and rp.number_value7 = -1)--all pldep
     )
 and sst.value = '0' and dv.amount > 0
union all --stay 7 outscan
select 4 linetype, rp.reportparam_id, b.businessunit_id,
 7 stay, '' idcode, 0 uniqueitem_id, lan.code languagecode,
 cc.deliverydate planneddeliverydate, null lastinscan_date, cc.deliverydate lastscan_date,
 to_char(cc.deliverydate, 'MM/DD/YYYY HH:MI:SS AM') lastinscandate,
 to_char(cc.deliverydate, 'MM/DD/YYYY HH:MI:SS AM') lastscandate,
 -1 status_id,
 ce.code productcode,
 (select w.description from product_desc w where w.product_id = ce.product_id
  and w.language_id = lan.language_id) productdesc,
 1 routenumber, '' routedesc,
 (select y.description from finishingmethod_desc y where y.finishingmethod_id = j.finishingmethod_id
  and y.language_id = lan.language_id) finishingmethoddesc,
 ck.code sizedefinitioncode,
 0 flag,
 0 flag_no,
 -1 wearernumber, '' wearername,
 cg.customernumber, cg.name customername, ch.departmentnumber, ch.description departmentdesc, -1 day_id,
 ci.street customeraddres
 , cast(concatenatewithblank(ci.zipcode, ci.city) as varchar2(255)) customeraddres2,
 0 maxcompletenessdays,
 coalesce((select ca.internalprocessingbu_id from customeractivities ca, productgroup pg
 where ca.customer_id = cg.customer_id and ce.productgroup_id = pg.productgroup_id
 and pg.activity_id = ca.activity_id and b.businessunit_id = ca.processbusinessunit_id), -1) internalbu,
 cast(sst.value as varchar2(1)) compchecknonunique
 , (cc.quantity + cc.quantitycog) nonuniqueqty, g.distributionpointnumber, g.description distributionpoint_desc, '' banklocker,
 to_number((select sstt.value from systemsetting sstt where sstt.plant_id = b.plant_id and sstt.name = 'NODELIVERYOFREJECTS')) nodeliveryofrejects_value,
 0 dv_origin, 0 dv_soilcountsubtype
from cleancountdelivery cc
  inner join distributionpoint g
        inner join department ch
              inner join customer cg
                    inner join address ci on cg.visitaddress_id = ci.address_id
              on ch.customer_id = cg.customer_id
        on g.department_id = ch.department_id
  on cc.distributionpoint_id = g.distributionpoint_id
  inner join product ce on cc.product_id = ce.product_id
  inner join sizedefinition ck on cc.sizedefinition_id = ck.sizedefinition_id
  inner join finishingmethod j on cc.finishingmethod_id = j.finishingmethod_id
  , businessunit b
  left outer join systemsetting sst on sst.plant_id = b.plant_id and sst.name = 'COMPCHECKNONUNIQUE'
  , languages lan, reportparam rp
where cg.customernumber >= rp.number_value8 and cg.customernumber <= rp.number_value9
 and (cc.packingnote_id is null or (select count(1) from packingnote pn, status stat where cc.packingnote_id = pn.packingnote_id
      and pn.status_id = stat.status_id and stat.statustype = 'PN' and stat.code = '20' and pn.deliverydate <= rp.date_value1) > 0)
 and b.businessunit_id = (select min(ca.processbusinessunit_id) from customeractivities ca, productgroup pg
    where ca.customer_id=cg.customer_id and ce.productgroup_id = pg.productgroup_id and pg.activity_id = ca.activity_id)
 and (((select count(1) from customerdeliveryday cdd where cdd.customer_id = cg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
        and cdd.day_id = rp.number_value1 and rp.number_value4 = 0) > 0)
     or (((select count(1) from customerdeliveryday cdd where cdd.customer_id = cg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
        and cdd.day_id = rp.number_value1) > 0)
        or ((select /*+index(rc xie7routecontrol)*/ count(1) from routecontrol rc, stop where stop.customer_link_id = cg.customer_id and nvl(stop.routestop_id, 0) <> 0
        and stop.stoptype = 3 and stop.routecontrol_id = rc.routecontrol_id and rc.drivingdate = rp.date_value1 and rp.number_value4 = 1) > 0)))
 and cc.deliverydate <= rp.date_value1
 and sst.value = '0'
/

  CREATE OR REPLACE VIEW "VR_SALESJOURNAL" ("SALESJOURNALCODE", "PLANTCODE", "PLANTNAME", "BUSINESSUNITCODE", "BUSINESSUNITDESC", "PRCBUSINESSUNITCODE", "PRCBUSINESSUNITDESC", "DEPOTCODE", "DEPOTDESC", "ROUTENUMBER", "ROUTEDESC", "TURNOVERGROUPCODE", "ARTRANSACTIONDATE", "CASHAMOUNT", "CHARGEAMOUNT", "CURRENCYCODE", "LANGUAGECODE", "LANGUAGE_ID", "SALESJOURNALDESC", "TURNOVERGROUPDESC") AS 
  select /*version 2.0*/
       sjg.code salesjournalcode, pt.code plantcode, pt.name plantname, bu.code businessunitcode,
       bu.description businessunitdesc, pbu.code prcbusinessunitcode, pbu.description prcbusinessunitdesc,
       dep.code depotcode, dep.description depotdesc, ro.routenumber, ro.description routedesc,
       tv.code turnovergroupcode, sj.artransactiondate artransactiondate, sj.cashamount, sj.chargeamount,
       sj.currencycode, lan.code languagecode, lan.language_id,
       (select description
          from salesjournalgroup_desc x
         where x.salesjournalgroup_id = sj.salesjournalgroup_id
           and x.language_id = lan.language_id) salesjournaldesc,
       (select description
          from turnovergroup_desc y
         where y.turnovergroup_id = sj.turnovergroup_id
           and y.language_id = lan.language_id) turnovergroupdesc
  from vr_salesjournalamount sj
       left join route ro
                 left join depot dep on ro.depot_id = dep.depot_id
       on sj.route_id = ro.route_id
       join businessunit bu
            join plant pt on bu.plant_id = pt.plant_id
       on sj.businessunit_id = bu.businessunit_id
       join businessunit pbu on sj.processbusinessunit_id = pbu.businessunit_id
       join salesjournalgroup sjg on sj.salesjournalgroup_id = sjg.salesjournalgroup_id
       join turnovergroup tv on sj.turnovergroup_id = tv.turnovergroup_id
       cross join languages lan
/

  CREATE OR REPLACE VIEW "VTEST_2_SOIL" ("WEIGHINGDATE", "CUSTOMER_ID", "DEPARTMENT_ID", "DISTRIBUTIONPOINT_ID", "WEIGHINGCATEGORY_ID", "BU_ID", "NET_TICKET", "NET_HIST") AS 
  select weighingdate, customer_id, department_id, distributionpoint_id, weighingcategory_id, bu_id, sum(net_ticket), sum(net_hist)
	from vtest_1_soil
	group by weighingdate, customer_id, department_id, distributionpoint_id, weighingcategory_id, bu_id
/

  CREATE OR REPLACE VIEW "V_ACTIVESTOCKLOCATION" ("LINETYPE", "UNIQUEITEM_ID", "PRIMARYID", "ACTIVESTOCKLOCATION_ID", "BUSINESSUNIT_ID", "SECTION", "LOCATION", "UNIQUEID", "PRODUCT_ID", "PRODUCTCODE", "SIZEDEFINITION_ID", "SIZECODE", "CUSTOMERNUMBER", "CUSTOMERNNAME", "CUSTOMER_ID", "RELATEDCUSTOMER_ID", "COUNTER", "ASL_LINE") AS 
  select /*version 2.0*/
       1 linetype, asl.uniqueitem_id, asl.primaryid, asl.activestocklocation_id, asl.businessunit_id, asl.section, asl.location, asl.uniqueid,
       pr.product_id, pr.code productcode, sd.sizedefinition_id, sd.code sizecode, cu.customernumber, cu.name customernname, cu.customer_id,
       asl.relatedcustomer_id, rc.counter, coalesce(asl.asl_line, 0) asl_line
  from productsize ps
       join product pr on ps.product_id = pr.product_id
       join sizedefinition sd on ps.sizedefinition_id = sd.sizedefinition_id
       cross join customer cu
       cross join v_rowcount rc
                  join v_activestocklocation_det asl on ps.product_id = asl.product_id
                                    and ps.sizedefinition_id = asl.sizedefinition_id
                                    and asl.asl_line = rc.counter
 where coalesce(asl.relatedcustomer_id, cu.customer_id) = cu.customer_id
union all
select 2 linetype, null uniqueitem_id, null primaryid, null activestocklocation_id, null businessunit_id, null section, null location, null uniqueid,
       pr.product_id, pr.code productcode, sd.sizedefinition_id, sd.code sizecode, cu.customernumber, cu.name customernname, cu.customer_id,
       null relatedcustomer_id, rc.counter, 0 asl_line
  from productsize ps
       join product pr on ps.product_id = pr.product_id
       join sizedefinition sd on ps.sizedefinition_id = sd.sizedefinition_id
       cross join customer cu
       cross join v_rowcount rc
 where not exists (select 1
          from v_activestocklocation_det asl
         where ps.product_id = asl.product_id
           and ps.sizedefinition_id = asl.sizedefinition_id
           and asl.asl_line = rc.counter
           and coalesce(asl.relatedcustomer_id, cu.customer_id) = cu.customer_id)
/

  CREATE OR REPLACE VIEW "V_AGEANALYSIS_CUSTOMERROUTE" ("CUSTOMER_ID", "EXPDATE", "ROUTENUMBER", "ROUTEDESC", "REPORTPARAM_ID") AS 
  select /*version 2.0*/
       v.customer_id, v.expdate, r.routenumber, r.description routedesc, v.reportparam_id
  from v_ageanalysis_route v
  left join route r on v.route_id = r.route_id
/

  CREATE OR REPLACE VIEW "V_ARTRIALBALANCE" ("PLANTCODE", "PLANTNAME", "BUCODE", "BUDESCRIPTION", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMERPHONENO", "PAYMENTMETHOD", "DELINQUENTMARKAFTER", "CREDITLIMIT", "STREET", "STREET2", "ZIPCODE", "CITY", "STATE", "CHAINCODE", "CHAINNAME", "COLLECTIONRESPNUMBER", "CURRENT_AMOUNT", "AMOUNT_30", "AMOUNT_60", "AMOUNT_90", "AMOUNT_120", "AMOUNT_CREDIT", "AMOUNT_DUE", "DAY", "ROUTE", "STOPNUMBER", "DRIVERNUMBER", "LASTPAYMENTDATE", "LASTPAYMENT", "BUSINESSUNIT_ID", "CUSTOMER_ID", "DISTRICTCODE", "DISTRICTDESC", "ROUTEMANAGERNO", "ROUTEMANAGERNAME", "BILLTOCUSTOMER_LINK_ID", "INVOICEHEADER_ID", "INVOICENUMBER", "ARTRANSACTIONDATE", "CURRENTDATE", "DUEDATE") AS 
  select /*version 3.0*/
       p.code plantcode, p.name plantname, bu.code bucode, bu.description budescription,
       c.customernumber, c.name customername, c.phoneno customerphoneno,
       c.paymentmethod, b.delinquentmarkafter, b.creditlimit, d.street,
       d.street2, d.zipcode, d.city, d.state, i.code chaincode,
       i.name chainname, e1.employeenumber collectionrespnumber,
       case when ss.value = '1' and ar.debitcredit = 'D' and trunc(sysdate) - ar.artransactiondate < 30
            then (ar.amount - ar.totalappliedamount)
            when ss.value = '2' and ar.debitcredit = 'D' and (cast(to_char(trunc(sysdate), 'YYYYMM') as numeric) = cast(to_char(ar.artransactiondate, 'YYYYMM') as numeric)
                                                             or cast(to_char(trunc(sysdate-30), 'YYYYMM') as numeric) = cast(to_char(ar.artransactiondate, 'YYYYMM') as numeric))
            then (ar.amount - ar.totalappliedamount)
            when ss.value = '3' and ar.debitcredit = 'D' and trunc(sysdate) - nvl(ihe.paymenttermsduedate, ar.artransactiondate) < 30
            then (ar.amount - ar.totalappliedamount)
       else 0 end current_amount,
       case when ss.value = '1' and ar.debitcredit = 'D' and trunc(sysdate) - ar.artransactiondate >= 30 and trunc(sysdate) - ar.artransactiondate < 60
            then (ar.amount - ar.totalappliedamount)
            when ss.value = '2' and ar.debitcredit = 'D' and cast(to_char(trunc(sysdate-60), 'YYYYMM') as numeric) = cast(to_char(ar.artransactiondate, 'YYYYMM') as numeric)
            then (ar.amount - ar.totalappliedamount)
            when ss.value = '3' and ar.debitcredit = 'D' and trunc(sysdate) - nvl(ihe.paymenttermsduedate, ar.artransactiondate) >= 30
             and trunc(sysdate) - nvl(ihe.paymenttermsduedate, ar.artransactiondate) < 60
            then (ar.amount - ar.totalappliedamount)
       else 0 end amount_30,
       case when ss.value = '1' and ar.debitcredit = 'D' and trunc(sysdate) - ar.artransactiondate >= 60 and trunc(sysdate) - ar.artransactiondate < 90
            then (ar.amount - ar.totalappliedamount)
            when ss.value = '2' and ar.debitcredit = 'D' and cast(to_char(trunc(sysdate-90), 'YYYYMM') as numeric) = cast(to_char(ar.artransactiondate, 'YYYYMM') as numeric)
            then (ar.amount - ar.totalappliedamount)
            when ss.value = '3' and ar.debitcredit = 'D' and trunc(sysdate) - nvl(ihe.paymenttermsduedate, ar.artransactiondate) >= 60
             and trunc(sysdate) - nvl(ihe.paymenttermsduedate, ar.artransactiondate) < 90
            then (ar.amount - ar.totalappliedamount)
       else 0 end amount_60,
       case when ss.value = '1' and ar.debitcredit = 'D' and trunc(sysdate) - ar.artransactiondate >= 90 and trunc(sysdate) - ar.artransactiondate < 120
            then (ar.amount - ar.totalappliedamount)
            when ss.value = '2' and ar.debitcredit = 'D' and cast(to_char(trunc(sysdate-120), 'YYYYMM') as numeric) = cast(to_char(ar.artransactiondate, 'YYYYMM') as numeric)
            then (ar.amount - ar.totalappliedamount)
            when ss.value = '3' and ar.debitcredit = 'D' and trunc(sysdate) - nvl(ihe.paymenttermsduedate, ar.artransactiondate) >= 90
             and trunc(sysdate) - nvl(ihe.paymenttermsduedate, ar.artransactiondate) < 120
            then (ar.amount - ar.totalappliedamount)
       else 0 end amount_90,
       case when ss.value = '1' and ar.debitcredit = 'D' and trunc(sysdate) - ar.artransactiondate >= 120
            then (ar.amount - ar.totalappliedamount)
            when ss.value = '2' and ar.debitcredit = 'D' and cast(to_char(trunc(sysdate-150), 'YYYYMM') as numeric) >= cast(to_char(ar.artransactiondate, 'YYYYMM') as numeric)
            then (ar.amount - ar.totalappliedamount)
            when ss.value = '3' and ar.debitcredit = 'D' and trunc(sysdate) - nvl(ihe.paymenttermsduedate, ar.artransactiondate) >= 120
            then (ar.amount - ar.totalappliedamount)
       else 0 end amount_120,
       case when ar.debitcredit = 'C'
            then (ar.amount - ar.totalappliedamount)
       else 0 end amount_credit,
       (select sum(artot.amount - artot.totalappliedamount)
          from artransaction artot, artransactiontype artott
         where artot.billtocustomer_link_id = c.customer_id
           and artot.debitcredit = 'D'
           and artot.isopen_yn = 'Y'
           and artot.artransactiontype_id = artott.artransactiontype_id
           and artott.typenumber <> 2
           and coalesce(artot.parentartransaction_id, artot.artransaction_id) = artot.artransaction_id) amount_due,
       coalesce(v1.day, 0) day, v1.route route, v1.stopnumber stopnumber, e2.employeenumber drivernumber,
       v2.lastpaymentdate, get_lastpayment(bu.businessunit_id, c.customer_id, v2.lastpaymentdate) lastpayment,
       bu.businessunit_id, c.customer_id,
       (select dt.code
          from district dt, route ro
         where ro.routenumber = v1.route
           and ro.drivingday_id = v1.day
           and ro.plant_id = p.plant_id
           and ro.district_id = dt.district_id) districtcode,
       (select dt1.description
          from district dt1, route ro
         where ro.routenumber = v1.route
           and ro.drivingday_id = v1.day
           and ro.plant_id = p.plant_id
           and ro.district_id = dt1.district_id) districtdesc,
       (select rm.employeenumber
          from employee rm, route ro
         where ro.routenumber = v1.route
           and ro.drivingday_id = v1.day
           and ro.plant_id = p.plant_id
           and ro.routemanager_id = rm.employee_id) routemanagerno,
       (select rm1.name
          from employee rm1, route ro
         where ro.routenumber = v1.route
           and ro.drivingday_id = v1.day
           and ro.plant_id = p.plant_id
           and ro.routemanager_id = rm1.employee_id) routemanagername,
       ar.billtocustomer_link_id, ar.invoiceheader_id, ar.invoicenumber,
       ar.artransactiondate, sysdate currentdate, ihe.paymenttermsduedate duedate
  from customer c
       left join chain i on c.chain_id = i.chain_id
       left join v_lastpayment v2 on (c.customer_id = v2.billtocustomer_link_id and c.defaultbusinessunit_id = v2.businessunit_id)
       left join v_min_day_route_stop v1
            left join employee e2 on v1.driver_id = e2.employee_id
       on c.customer_id = v1.customer_id
       join customerbillinginfo b
            left join employee e1 on b.collectionresponsible_id = e1.employee_id
       on c.debtor_id = b.customer_id
       join address d on c.visitaddress_id = d.address_id
       join businessunit bu
            join plant p
                 join systemsetting ss on p.plant_id = ss.plant_id and ss.name = 'ARAGINGMETHOD'
            on bu.plant_id = p.plant_id
       on c.defaultbusinessunit_id = bu.businessunit_id
       left join artransaction ar
            left join invoiceheaderextrainfo ihe on ar.invoiceheader_id = ihe.invoiceheader_id
            join artransactiontype art on ar.artransactiontype_id = art.artransactiontype_id
       on c.customer_id = ar.billtocustomer_link_id
 where coalesce(ar.isopen_yn, 'Y') = 'Y'
   and coalesce(art.typenumber, 0) <> 2
   and coalesce(ar.parentartransaction_id, ar.artransaction_id, 0) = coalesce(ar.artransaction_id, 0)
/

  CREATE OR REPLACE VIEW "V_ARTRIALBALANCE_TEST" ("PLANTCODE", "PLANTNAME", "BUCODE", "BUDESCRIPTION", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMERPHONENO", "DELINQUENTMARKAFTER", "CREDITLIMIT", "STREET", "STREET2", "ZIPCODE", "CITY", "STATE", "CHAINCODE", "CHAINNAME", "COLLECTIONRESPNUMBER", "CURRENT_AMOUNT", "AMOUNT_30", "AMOUNT_60", "AMOUNT_90", "AMOUNT_120", "AMOUNT_CREDIT", "DAY", "ROUTE", "STOPNUMBER", "DRIVERNUMBER", "LASTPAYMENTDATE", "LASTPAYMENT", "LASTDEBITDATE") AS 
  select
  p.code plantcode, p.name plantname,
  bu.code bucode, bu.description budescription,
  c.customernumber, c.name customername, c.phoneno customerphoneno, b.delinquentmarkafter, b.creditlimit,
  d.street, d.street2, d.zipcode, d.city, d.state,
  i.code chaincode, i.name chainname,
  e1.employeenumber collectionrespnumber,
  coalesce(GET_AR_AMOUNT(bu.businessunit_id,c.customer_id, 0, null, null),0) current_amount,
  coalesce(GET_AR_AMOUNT(bu.businessunit_id,c.customer_id, 30, null, null),0) amount_30,
  coalesce(GET_AR_AMOUNT(bu.businessunit_id,c.customer_id, 60, null, null),0) amount_60,
  coalesce(GET_AR_AMOUNT(bu.businessunit_id,c.customer_id, 90, null, null),0) amount_90,
  coalesce(GET_AR_AMOUNT(bu.businessunit_id,c.customer_id, 120, null, null),0) amount_120,
  coalesce(GET_AR_AMOUNT(bu.businessunit_id,c.customer_id, -1, null, null),0) amount_credit,
  coalesce(v1.day,0) day, v1.route route, v1.stopnumber stopnumber, e2.employeenumber drivernumber,
  v2.lastpaymentdate, GET_LASTPAYMENT(bu.businessunit_id,c.customer_id,v2.lastpaymentdate) lastpayment,
  COALESCE(v3.lastpaymentdate, trunc(sysdate)) lastdebitdate
from customerbillinginfo b
    LEFT OUTER JOIN employee e1 ON (b.collectionresponsible_id = e1.employee_id),
  customer c
    LEFT OUTER JOIN chain i ON (c.chain_id = i.chain_id)
    LEFT OUTER JOIN v_lastpayment v2 ON (c.customer_id = v2.billtocustomer_link_id
      and c.defaultbusinessunit_id = v2.businessunit_id)
    LEFT OUTER JOIN (v_min_day_route_stop v1 LEFT OUTER JOIN employee e2 on (v1.driver_id = e2.employee_id))
        ON (c.customer_id = v1.customer_id)
    LEFT OUTER JOIN v_lastpaymentd v3 ON (c.customer_id = v3.billtocustomer_link_id and c.defaultbusinessunit_id = v3.businessunit_id),
  address d,
  businessunit bu, plant p
--  , v_lastpaymentd v3
where c.customer_id = b.customer_id
  and c.visitaddress_id = d.address_id
  and bu.plant_id = p.plant_id
  and c.defaultbusinessunit_id = bu.businessunit_id
--  and c.customer_id = v3.billtocustomer_link_id
--  and c.defaultbusinessunit_id = v3.businessunit_id
/

  CREATE OR REPLACE VIEW "V_AVAILABLEBUNDLES_PN" ("TOBEDELIVEREDAMOUNT1", "TOBEDELIVEREDAMOUNT2", "TOBEDELIVEREDAMOUNT3", "TOBEDELIVEREDAMOUNT4", "TOBEDELIVEREDAMOUNT5", "TOBEDELIVEREDAMOUNT6", "TOBEDELIVEREDAMOUNT7", "ACTIVITYCODE", "BUSINESSUNIT_ID", "PLANTDEPARTMENTCODE", "PLANTDEPARTMENTDESC", "ACTIVITYDESC", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTDESC", "PRODUCTGROUPCODE", "PRODUCTGROUPDESC", "SIZECODE", "SIZEDEFINITION_ID", "FINMETHCODE", "FINISHINGMETHOD_ID", "LANGUAGECODE", "REPORTPARAM_ID") AS 
  select
  sum (x.tobedeliveredamount1) tobedeliveredamount1,
  sum (x.tobedeliveredamount2) tobedeliveredamount2,
  sum (x.tobedeliveredamount3) tobedeliveredamount3,
  sum (x.tobedeliveredamount4) tobedeliveredamount4,
  sum (x.tobedeliveredamount5) tobedeliveredamount5,
  sum (x.tobedeliveredamount6) tobedeliveredamount6,
  sum (x.tobedeliveredamount7) tobedeliveredamount7,
  x.activitycode, x.businessunit_id, x.plantdepartmentcode, x.plantdepartmentdesc,
  x.activitydesc, x.product_id, x.productcode, x.productdesc, x.productgroupcode,
  x.productgroupdesc, x.sizecode, x.sizedefinition_id, x.finmethcode, x.finishingmethod_id,
  x.languagecode, x.reportparam_id
from v_availablebundles_pnd x
group by  x.businessunit_id, x.plantdepartmentcode, x.plantdepartmentdesc,
  x.activitydesc, x.product_id, x.productcode, x.productdesc, x.productgroupcode,
  x.productgroupdesc, x.sizecode, x.sizedefinition_id, x.finmethcode, x.finishingmethod_id,
  x.languagecode, x.reportparam_id, x.activitycode
/

  CREATE OR REPLACE VIEW "V_BATCHCARD" ("BATCH_ID", "CUSTOMERNUMBER", "NAME", "LEGACYCUSTOMERNUMBER", "BATCHNUMBER", "DELIVERYDATE", "DELIVERYDATEWEEKNO", "YEAR", "WEEK", "BATCHCODE", "SEQUENCENUMBER", "INFECTION", "REMARK", "DAY_DESCRIPTION", "QUANTITY", "WASHINGPROCESSCODE", "BATCHCARDPIECES", "WASHINGPROCESS_DESC", "LANGUAGE_ID", "LANGUAGE_CODE", "NO_CLIENTS", "BATCH_QUANTITY", "WASHPROC_QUANTITY", "LINETYPE") AS 
  select ba.batch_id, c.customernumber, c.name, c.legacycustomernumber, ba.batchnumber, ba.deliverydate, getisoweek(ba.deliverydate) deliverydateWeekNo, ba.year, ba.week,
       ba.batchcode, ba.sequencenumber, ba.infection, ba.remark,
       (select dd.description
         from   day_desc dd
         where  dd.day_id = getabsdaynumber(ba.deliverydate)
         and    dd.language_id = lg.language_id) Day_Description, x.quantity,
       wp.code washingprocesscode, wp.batchcardpieces,
       (select wpd.description
         from   washingprocess_desc wpd
         where  wpd.washingprocess_id = x.washingprocess_id
         and    wpd.language_id = lg.language_id) washingprocess_desc,
       lg.language_id, lg.code language_code,
       (select count( distinct x3.clientid) from v_batchcard_aux x3 where x3.batch_id = ba.batch_id) no_clients,
       (select sum(x1.quantity) from v_batchcard_aux x1 where x1.batch_id = ba.batch_id and x1.linetype in (1, 2)) batch_quantity,
       (select sum(x2.quantity) from v_batchcard_aux x2 where x2.batch_id = ba.batch_id and x2.washingprocess_id = wp.washingprocess_id and x2.linetype in (1, 2)) washproc_quantity
       , x.linetype
from   v_batchcard_aux x
join   batch ba
on     ba.batch_id = x.batch_id
join   washingprocess wp
on     wp.washingprocess_id = x.washingprocess_id
join   customer c
on     c.customer_id = x.customer_link_id, languages lg
where x.linetype in (1, 2)
union all
select gba.garmentbatch_id batch_id, c.customernumber, c.name, c.legacycustomernumber, gba.garmentbatchnumber batchnumber,
       gba.deliverydate, getisoweek(gba.deliverydate) deliverydateWeekNo, gba.year, gba.week,
       ' ' batchcode, gba.sequencenumber, gba.infection,gba.remark,
       (select dd.description
         from   day_desc dd
         where  dd.day_id = getabsdaynumber(gba.deliverydate)
         and    dd.language_id = lg.language_id) Day_Description, x.quantity,
       wp.code washingprocesscode, wp.batchcardpieces,
       (select wpd.description
         from   washingprocess_desc wpd
         where  wpd.washingprocess_id = x.washingprocess_id
         and    wpd.language_id = lg.language_id) washingprocess_desc,
       lg.language_id, lg.code language_code,
              (select count( distinct x3.clientid) from v_batchcard_aux x3 where x3.batch_id = gba.garmentbatch_id) no_clients,
       (select sum(x1.quantity) from v_batchcard_aux x1 where x1.batch_id = gba.garmentbatch_id and x1.linetype = x.linetype) batch_quantity,
       (select sum(x2.quantity) from v_batchcard_aux x2 where x2.batch_id = gba.garmentbatch_id and x2.washingprocess_id = wp.washingprocess_id and x2.linetype = x.linetype) washproc_quantity
       , x.linetype
from   v_batchcard_aux x
join   garmentbatch gba
on     gba.garmentbatch_id = x.batch_id
join   washingprocess wp
on     wp.washingprocess_id = x.washingprocess_id
join   customer c
on     c.customer_id = x.customer_link_id, languages lg
where x.linetype = 3
/

  CREATE OR REPLACE VIEW "V_BILLTO_DELTO_CUSTOMER" ("REPORTPARAM_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_ID") AS 
  select rp.reportparam_id, bill.customernumber, bill.name customername, bill.customer_id
from customer bill, customer del, reportparam rp
where bill.customer_id = del.debtor_id
  and bill.customernumber between rp.number_value2 and rp.number_value3 -- bill_to
  and del.customernumber between rp.number_value4 and rp.number_value5 -- del_to
  and exists (select v.customer_id from v_customersperbusinessunitdp v
              where v.customer_id = del.customer_id and v.businessunit_id = rp.number_value1)
  and exists (select v.customer_id from v_customersperbusinessunitdp v
              where v.customer_id = bill.customer_id and v.businessunit_id = rp.number_value1)
/*  and exists (select * from customeractivities ca
      where ca.customer_id = del.customer_id
        and ca.processbusinessunit_id = rp.number_value1)
  and exists (select * from customeractivities ca
      where ca.customer_id = bill.customer_id
        and ca.processbusinessunit_id = rp.number_value1) */
  and rp.number_value6 = 1 -- selection type - filter on del_to and bill_to
union all
-- selection for all del_to
select rp.reportparam_id, del.customernumber, del.name customername, del.customer_id
from customer del, reportparam rp
where del.customernumber between rp.number_value4 and rp.number_value5 -- del_to
  and exists (select v.customer_id from v_customersperbusinessunitdp v
              where v.customer_id = del.customer_id and v.businessunit_id = rp.number_value1)
/*  and exists (select * from customeractivities ca
      where ca.customer_id = del.customer_id
        and ca.processbusinessunit_id = rp.number_value1)*/
  and rp.number_value6 = 2 -- selection type - filter only on del_to
/

  CREATE OR REPLACE VIEW "V_CIRCULATIONSPEEDCIRCINV" ("REPORTPARAM_ID", "AMOUNTDELIVERED", "CIRCINVENTORY", "MAXDELIVERY", "MINDELIVERY", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "DEPARTMENTNUMBER", "DEPARTMENT_DESC", "DISTRIBUTIONPOINT_ID", "DISTRIBUTIONPOINTNUMBER", "DISTRIBPOINT_DESC", "PRODUCTGROUPCODE", "PRODUCTGROUPDESC", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "FINISHINGMETHODCODE", "NOOFWEEKS", "PRODUCTLISTPERDISTRIBPOINT_ID", "LANGUAGECODE") AS 
  select rp.reportparam_id,
       (select sum(dh.amountdelivered)
         from   deliveryhistory dh
         where  dh.customer_link_id = cu.customer_id and
                dh.product_link_id = pr.product_id and
                dh.sizedefinition_link_id = plpd.sizedefinition_id and
                dh.finishingmethod_id = plpd.finishingmethod_id and
                dh.deliverydate between rp.date_value1 and rp.date_value2) amountdelivered,
       sum(coalesce(rqa.quantity, 0)) circinventory,
       (select max(v.amountdelivered) from V_CIRCULATIONSPEED_DELIV v where v.reportparam_id = rp.reportparam_id and
       v.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id and v.customer_id = cu.customer_id) MaxDelivery,
       (select min(v.amountdelivered) from V_CIRCULATIONSPEED_DELIV v where v.reportparam_id = rp.reportparam_id and
       v.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id and v.customer_id = cu.customer_id) MinDelivery,
       cu.customer_id, cu.customernumber, cu.name customername,
       (select ad2.city
         from   address ad2
         where  cu.visitaddress_id = ad2.address_id) city,
       de.departmentnumber, de.description Department_desc,
       dp.distributionpoint_id, dp.distributionpointnumber, dp.description DistribPoint_desc,
       (select pg.code from productgroup pg where pr.productgroup_id = pg.productgroup_id) productgroupcode,
       (select pgd.description
         from   productgroup_desc pgd
         where  pr.productgroup_id = pgd.productgroup_id and
                languages.language_id = pgd.language_id) productgroupdesc,
       pr.code productcode,
       (select prd.description
         from   product_desc prd
         where  pr.product_id = prd.product_id and
                languages.language_id = prd.language_id) productdesc,
       (select sz2.code
         from   sizedefinition sz2
         where  plpd.sizedefinition_id = sz2.sizedefinition_id) sizecode,
       (select f2.code
         from   finishingmethod f2
         where  plpd.finishingmethod_id = f2.finishingmethod_id) finishingmethodcode,
       rp.number_value noofweeks,  plpd.productlistperdistribpoint_id,
       languages.code languagecode
from   productlistperdistribpoint plpd, rentalqtyadjustment rqa
       , distributionpoint dp, department de, customer cu, product pr
       , reportparam rp, languages
where  rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id and plpd.distributionpoint_id = dp.distributionpoint_id
       and dp.department_id = de.department_id and de.customer_id = cu.customer_id
       and plpd.product_id = pr.product_id
       and rqa.adjustmentdate <= rp.date_value2
       and cu.customernumber between rp.number_value5 and rp.number_value6
       and pr.code between rp.string_value1 and rp.string_value2-- and sz2.code between rp.string_value3 and rp.string_value4 and f2.code between rp.string_value5 and rp.string_value6
group by rp.reportparam_id, rp.number_value, rp.date_value1, rp.date_value2
         , dp.distributionpoint_id, dp.distributionpointnumber, dp.description, de.departmentnumber, de.description
         , cu.customer_id, cu.customernumber, cu.name, cu.visitaddress_id, plpd.productlistperdistribpoint_id
         , pr.product_id, pr.productgroup_id, pr.code, plpd.sizedefinition_id, plpd.finishingmethod_id
         , languages.language_id, languages.code
/

  CREATE OR REPLACE VIEW "V_CLEANROOMBATCHCARDS" ("CLEANROOMBATCH_ID", "LANGUAGECODE", "PLANTCODE", "PLANTNAME", "BUCODE", "BUDESC", "BATCHNUMBER", "CREATIONDATE", "WASHINGCODE", "WASHINGPR_DESC", "CREATIONTIMESTAMP", "CARTNUMBER", "EMPLOYEE_PRINTED", "EMPLOYEE_CREATION", "BATCHCARDPRINTEDDATE", "BATCHCARDTIMESTAMP", "WASHMACHINES", "WASHMACHINES_COMPART", "DRYINGMACHINES", "FINISHMACHINES", "FINISHINGPROGRAMS", "RETENTION", "APPROVALDATE", "VERSIONDATE") AS 
  select cb.cleanroombatch_id, languages.code languagecode, p.code plantcode, p.name plantname, bu.code bucode, bu.description budesc,
cb.cleanroombatchnumber batchnumber, trunc(cb.creationdate) creationdate, wp.code washingcode,
(select wd.description from washingprocess_desc wd where wd.washingprocess_id = wp.washingprocess_id and wd.language_id = languages.language_id)washingpr_desc,
cb.creationdate creationtimestamp, cart.cartnumber, em.searchname employee_printed, em2.searchname employee_creation,
trunc(cb.batchcardprinteddate) batchcardprinteddate, cb.batchcardprinteddate batchcardtimestamp,
(select listagg(v.machine, '  ') WITHIN GROUP (ORDER BY v.machine) from v_machinetypes v where v.type = '1' and v.plant_id = p.plant_id) washmachines,
(select listagg(v2.compartment, '  ') WITHIN GROUP (ORDER BY v2.compartment) from v_machinecompartments v2 where v2.plant_id = p.plant_id) washmachines_compart,
(select listagg(v.machine, '  ') WITHIN GROUP (ORDER BY v.machine) from v_machinetypes v where v.type = '2' and v.plant_id = p.plant_id) dryingmachines,
(select listagg(v.machine, '  ') WITHIN GROUP (ORDER BY v.machine) from v_machinetypes v where v.type = '3' and v.plant_id = p.plant_id) finishmachines,
(select listagg(v3.finishprog, '  ') within group(order by v3.finishprog) from v_finishingprograms v3 where v3.plant_id = p.plant_id) finishingprograms,
 (select dff.stringvalue from dialogflexfields dff, characteristic ch, dialogs di where dff.characteristic_id = ch.characteristic_id
 and dff.entity_id = bu.businessunit_id and dff.dialog_id = ch.dialog_id and ch.dialog_id = di.dialog_id and di.code = 'BusinessUnit' and ch.code = 'RET') retention,
  (select dff.datevalue from dialogflexfields dff, characteristic ch, dialogs di where dff.characteristic_id = ch.characteristic_id
 and dff.entity_id = bu.businessunit_id and dff.dialog_id = ch.dialog_id and ch.dialog_id = di.dialog_id and di.code = 'BusinessUnit' and ch.code = 'REV') approvaldate,
  (select dff.stringvalue from dialogflexfields dff, characteristic ch, dialogs di where dff.characteristic_id = ch.characteristic_id
 and dff.entity_id = bu.businessunit_id and dff.dialog_id = ch.dialog_id and ch.dialog_id = di.dialog_id and di.code = 'BusinessUnit' and ch.code = 'VER') versiondate
from cleanroombatch cb
    left outer join washingprocess wp on cb.washingprocess_id = wp.washingprocess_id
    left outer join cart on cb.internalcart_id = cart.cart_id
    left outer join employee em on cb.batchcardprintedemployee_id = em.employee_id
    left outer join employee em2 on cb.creationemployee_id = em2.employee_id
    inner join businessunit bu
          inner join plant p on bu.plant_id = p.plant_id
    on cb.businessunit_id = bu.businessunit_id
    cross join languages
/

  CREATE OR REPLACE VIEW "V_CLIENTDELIVERYNOTE" ("LINETYPE", "PRINTPRICEONDELNOTE", "PRICEDECIMALS", "AMOUNTDECIMALS", "PRICE", "PRICEONDELNOTE", "WEIGHTPRICE", "SPECIALCHARGEINVAMOUNT", "SPECIALCHARGEAMOUNT", "LABELSAMOUNT", "TAXAMOUNT", "NOOFSPECCHARGE", "NOOFLABELS", "NOOFTAXES", "CLIENTDELIVERYNOTE_ID", "PROCESSBUSINESSUNIT_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "CLIENTNUMBER", "CLIENTNAME", "ROOM", "STREET", "ZIPCODE_CITY", "CLIENTDELIVERYNOTENUMBER", "CLOSINGDATE", "DELIVERYDATE", "BOXNUMBER", "BATCHCODE", "BATCHNUMBER", "BATCHYEAR", "BATCHWEEK", "BATCHCOLORDESC", "BATCH_CODENUMBER", "DAYDESC", "ROUTENUMBER", "ROUTEDESC", "STOPNUMBER", "GROSSWEIGHT", "WEIGHTDECIMALS", "WEIGHTUNIT", "PACKINGSEQUENCE", "PRODUCTCODE", "SIZECODE", "FINISHINGMETHODCODE", "PRODUCTDESC", "FINISHINGMETHODDESC", "QTYRECEIVED", "QTYDELIVERED", "PRIMARYID", "PRINTWEIGHT", "PRINT_V_CDN_DELAYEDDELIVERY", "PRINT_V_CDN_DELIVEREDAFTER", "PRINT_V_CDN_SENDTOOWNER", "PRINT_V_CDN_RECEIVEFROMOWNER", "CUSTOMERCLIENTS", "PRINTIDCODE", "PRINTLATEPIECES", "ACCEPTOTHERCLIENTS", "PRINTQTYRECEIVED", "SYSTEMSETTINGVALUE", "EMPLOYEENUMBER", "EMPLOYEENAME", "RECORDEMPLCLIENTDELNOTE", "LANGUAGECODE", "PRODCUSTOM_CODE", "PRODCUSTOM_DESC", "UNIQUERESIDENTIALITEM_LINK_ID", "OUTSCANTIMESTAMP", "SEQUENCENUMBER", "DEPTDELSTREET", "DEPTDELZIPCODE", "DEPTDELCITY", "LOCATION", "ADDITIONALTONOTE_ID", "ADDITIONALCDNNUMBER", "CLIENTDELNOTEFORMLAYOUT", "WORKSTATION_ID", "WORKSTATION_CODE", "EMPTIED", "LANGUAGEID", "LEGACYCODE", "CORRECTIONCLIENTDELNOTE_ID", "CORRECTIONCLIENTDELIVERYNOTE", "REMARKS", "FLAGCODE", "FLAGDESC", "ADDITIONALNOTENUMBERS", "ALLOW_REPAIRS_CUST", "ALLOW_REPAIRS_CLIENT", "CURRENTNR", "TOTALNR") AS 
  select -- +index(cds xie2clientdelnotelinescan)
  case when pdfm.finishingmethod_id is null then 1 else 2 end linetype
, crs.printpriceondelnote, crr.decimals pricedecimals, crr.invoiceamountdecimals amountdecimals
, cdl.price, cdl.priceondelnote, cdn.weightprice
, coalesce((select sum(cds.quantity*cds.price) from clientdeliverynotespeccharge cds
             where cds.clientdeliverinote_id = cdn.clientdeliverynote_id),0) specialchargeinvamount
, coalesce((select sum(cds.quantity*cds.priceondelnote) from clientdeliverynotespeccharge cds
             where cds.clientdeliverinote_id = cdn.clientdeliverynote_id),0) specialchargeamount
, coalesce((select sum(pqr.quantity*pqr.price) from printqueueresidentialitem pqr
             where pqr.clientdeliverynote_id = cdn.clientdeliverynote_id),0) labelsamount
, coalesce((select sum(cdt.taxamount) from clientdeliverynotetax cdt, taxgroup tg
             where cdt.taxgroup_id = tg.taxgroup_id and cdt.clientdeliverinote_id = cdn.clientdeliverynote_id),0) taxamount
, (select count(*) from clientdeliverynotespeccharge cds
                  where cds.clientdeliverinote_id = cdn.clientdeliverynote_id) noofspeccharge
, (select count(*) from printqueueresidentialitem pqr
                  where pqr.clientdeliverynote_id = cdn.clientdeliverynote_id) nooflabels
, (select count(*) from clientdeliverynotetax cdt
                  where cdt.clientdeliverinote_id = cdn.clientdeliverynote_id) nooftaxes
, cdn.clientdeliverynote_id, cdn.processbusinessunit_id, cu.customer_id, cu.customernumber, cu.name customername
, de.departmentnumber, de.description departmentdesc
, client.clientnumber, coalesce(cdn.name, client.name) clientname
, case when cdn.closingdate is null then dr.roomnumber else cdn.roomnumber end room
, case when cdn.street is null then address.street else cdn.street end street
, cast(( case when cdn.street is null then concatenatewithsign(address.zipcode, ' / ', address.city)
              else concatenatewithsign(cdn.zipcode, ' / ', cdn.city) end) as varchar2(255))  zipcode_city
, cdn.clientdeliverynotenumber, cdn.closingdate, cdn.deliverydate, cdn.boxnumber
, batch.batchcode, batch.batchnumber, batch.year batchyear, batch.week batchweek, bc.description batchcolordesc
, cast(( case
  when ss.value = '-2' then concatenate(getsubstringonlength(batch.batchcode, 1, 2), cast(batch.batchnumber as varchar2(255)))
  when ss.value = '-1' then concatenate(getsubstringonlength(batch.batchcode, 1, 1), cast(batch.batchnumber as varchar2(255)))
  when ss.value =  '0' then cast(batch.batchnumber as varchar2(255))
  when ss.value =  '1' then concatenate(cast(batch.batchnumber as varchar2(255)), getsubstringonlength(batch.batchcode, 1, 1))
  when ss.value =  '2' then concatenate(cast(batch.batchnumber as varchar2(255)), getsubstringonlength(batch.batchcode, 1, 2))
  end) as varchar2(255)) batch_codenumber
, ( select dd.description
      from day_desc dd
     where batch.day_id = dd.day_id
       and dd.language_id = lan.language_id ) daydesc
, route.routenumber, route.description routedesc, cdn.stopnumber
, cdn.grossweight, cdn.weightdecimals
, ( select systemsetting.value
      from systemsetting
     where systemsetting.plant_id = bu.plant_id
       and systemsetting.name = 'WEIGHTUNIT' ) weightunit
, pr.packingsequence, pr.code productcode, sz.code sizecode, fm.code finishingmethodcode
, ( select prd.description
      from product_desc prd
     where prd.product_id = pr.product_id
       and prd.language_id = lan.language_id ) productdesc
, ( select fmd.description
      from finishingmethod_desc fmd
     where fmd.finishingmethod_id = fm.finishingmethod_id
       and fmd.language_id = lan.language_id ) finishingmethoddesc
, ( cdl.qtyscannedin + cdl.qtycountedin ) qtyreceived
, ( cdl.qtyscannedout + cdl.qtycountedout ) qtydelivered
, (   select uri.primaryid
        from uniqueresidentialitem uri
       where cds.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id  ) primaryid
, case when exists ( select 1 from weighingcategpercustomer wghc where wghc.weighingcategory_id = cdn.weighingcategory_link_id
        and wghc.customer_id = cu.customer_id
        and wghc.invoicemethod = 2 -- invoice soil weight
        and trunc(sysdate) between wghc.dateactive and wghc.dateinactive ) then 1
       else 0
   end printweight
, case when exists ( select 1 from v_cdn_delayeddelivery where v_cdn_delayeddelivery.clientdeliverynote_id = cdn.clientdeliverynote_id ) then 1
       else 0
   end print_v_cdn_delayeddelivery
, case when exists ( select 1 from v_cdn_deliveredafter where v_cdn_deliveredafter.clientdeliverynote_id = cdn.clientdeliverynote_id ) then 1
       else 0
        end print_v_cdn_deliveredafter
, case when crs.acceptotherclients = 2 then 1
       else 0
   end print_v_cdn_sendtoowner
, case when crs.acceptotherclients = 2 then 1
       else 0
   end print_v_cdn_receivefromowner
, crs.customerclients, crs.printidcode, crs.printlatepieces, crs.acceptotherclients, crs.printqtyreceived
, ss.value systemsettingvalue
, emp.employeenumber, emp.name employeename
, (select cast(systemsetting.value as varchar2(5))
     from systemsetting
    where systemsetting.plant_id = bu.plant_id
      and systemsetting.name = 'RECORDEMPLCLIENTDELNOTE' ) recordemplclientdelnote
, lan.code languagecode
, (select plpc.customcode
     from productlistpercustomer plpc
    where plpc.productlistpercustomer_id = f_getidcolumnfromactiveplpc (cu.customer_id, pr.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) prodcustom_code
, (select plpc.customdescription
     from productlistpercustomer plpc
    where plpc.productlistpercustomer_id = f_getidcolumnfromactiveplpc (cu.customer_id, pr.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) prodcustom_desc
, cds.uniqueresidentialitem_link_id, trunc(cds.outscantimestamp) outscantimestamp
, cdn.sequencenumber
, address2.street deptdelstreet
, address2.zipcode deptdelzipcode
, address2.city deptdelcity
,(select coalesce((lc.rowcode || ' - ' ||lc.positioncode),'')
    from ltxsortsessionloccontents lcc
    join ltxsortsessionlocation lc on lcc.ltxsortsessionlocation_id = lc.ltxsortsessionlocation_id
   where lcc.clientdeliverynote_id = cdn.clientdeliverynote_id) location
, cdn.additionaltonote_id
, (select cdn_add.clientdeliverynotenumber
     from clientdeliverynote cdn_add
    where cdn_add.clientdeliverynote_id = cdn.additionaltonote_id) additionalcdnnumber
, (select fl.code
     from formlayout fl
    where fl.formlayout_id = crs.clientdelnoteformlayout_id) clientdelnoteformlayout
, ws.workstation_id, ws.code workstation_code
, cdn.emptied, lan.language_id languageid, client.legacycode
, cdn.correctionclientdelnote_id, cdn1.clientdeliverynotenumber correctionclientdeliverynote,
 (select listagg(ccdnr.remark,',') within group(order by ccdnr.startdate)
    from customerclientdelnoteremark ccdnr
   where ccdnr.customer_id = cu.customer_id
     and cdn.deliverydate >= ccdnr.startdate
     and cdn.deliverydate <= ccdnr.enddate) remarks,
 case crs.printidcode when 'Y'
 then (select f.code from flag f
        where f.flag_id = (select max(flag.flag_id)
                             from flag
                             join residentialitemscanflag risf on flag.flag_id = risf.flag_id
                             join residentialitemscan ris on risf.residentialitemscan_id = ris.residentialitemscan_id
                            where cds.uniqueresidentialitem_link_id = ris.uniqueresidentialitem_link_id
                              and trunc(cds.outscantimestamp) = trunc(ris.scantimestamp)
                              and ris.transactiontype_id = 2))
 else null
 end flagcode
,case crs.printidcode when 'Y'
 then (select flag_desc.description from flag_desc
        where flag_desc.flag_id = (select max(flag.flag_id)
                                     from flag
                                     join residentialitemscanflag risf on flag.flag_id = risf.flag_id
                                     join residentialitemscan ris on risf.residentialitemscan_id = ris.residentialitemscan_id
                                    where cds.uniqueresidentialitem_link_id = ris.uniqueresidentialitem_link_id
                                      and trunc(cds.outscantimestamp) = trunc(ris.scantimestamp)
                                      and ris.transactiontype_id = 2)
          and flag_desc.language_id = lan.language_id)
 else null
 end flagdesc
,(select rtrim(xmlagg(xmlelement(x,clientdeliverynotenumber,',').extract('//text()')).getclobval(),',')--workaround for ora 01489 thrown by listagg when null data selected
    from (select cda.clientdeliverynotenumber
            from clientdeliverynote cda
           where cda.additionaltonote_id = cdn.clientdeliverynote_id) x) additionalnotenumbers
,crs.allowrepair allow_repairs_cust, client.allowrepair allow_repairs_client
,(select x.rownr
    from (select rownum rownr, cdn2.clientdeliverynotenumber
            from clientdeliverynote cdn2
           where cdn2.batch_id = cdn.batch_id and cdn2.client_link_id = cdn.client_link_id
           order by cdn2.sequencenumber) x
   where x.clientdeliverynotenumber = cdn.clientdeliverynotenumber) currentnr
,(select count(1)
    from clientdeliverynote cdn2
   where cdn2.batch_id = cdn.batch_id
     and cdn2.client_link_id = cdn.client_link_id) totalnr
from clientdeliverynote cdn
     left join route on cdn.route_id = route.route_id
     left join clientdeliverynoteline cdl
          join product pr
               join productgroup pg on pr.productgroup_id = pg.productgroup_id
          on cdl.product_link_id = pr.product_id
          join sizedefinition sz on cdl.sizedefinition_link_id = sz.sizedefinition_id
          join finishingmethod fm on cdl.finishingmethod_id = fm.finishingmethod_id
               left join plantdepartmentfinmethod pdfm
                    join workstation ws on pdfm.plantdepartment_id = ws.plantdepartment_id
               on pdfm.finishingmethod_id = fm.finishingmethod_id
          left join clientdelnotelinescan cds on (cdl.clientdeliverynoteline_id = cds.outscanclientdelnoteline_id and cds.deliveryexception not in (1, 3))
     on cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
     join customer cu
          join customerresidentialsettings crs on cu.customer_id = crs.customer_id
          join currency crr on cu.currency_id = crr.currency_id
     on cdn.customer_link_id = cu.customer_id
     join client
          left join clientresident cr
               join departmentroom dr
                    join department de on dr.department_id = de.department_id
                    join distributionpoint dip
                         join deliverypoint devp
                              join address address2 on devp.deliveryaddress_id = address2.address_id
                         on dip.deliverypoint_id = devp.deliverypoint_id
                    on dr.distributionpoint_id = dip.distributionpoint_id
               on cr.departmentroom_id = dr.departmentroom_id
          on client.client_id = cr.client_id
          left join clientprivateperson cpp
               join deliverypoint delvp
                    join address on delvp.deliveryaddress_id = address.address_id
               on cpp.deliverypoint_id = delvp.deliverypoint_id
          on client.client_id = cpp.client_id
     on cdn.client_link_id = client.client_id
     join batch
          left join employee emp on batch.employee_id = emp.employee_id
          join batchcolor bc on batch.batchcolor_id = bc.batchcolor_id
     on cdn.batch_id = batch.batch_id
     join businessunit bu
          join systemsetting ss on bu.plant_id = ss.plant_id and ss.name = 'BATCHCODEUSAGE'
     on cdn.processbusinessunit_id = bu.businessunit_id
     left join clientdeliverynote cdn1 on cdn.correctionclientdelnote_id = cdn1.clientdeliverynote_id
     ,languages lan
/

  CREATE OR REPLACE VIEW "V_CLIENTDELIVERYNOTE2" ("PRINTPRICEONDELNOTE", "PRICEDECIMALS", "AMOUNTDECIMALS", "PRICE", "PRICEONDELNOTE", "WEIGHTPRICE", "SPECIALCHARGEINVAMOUNT", "SPECIALCHARGEAMOUNT", "LABELSAMOUNT", "TAXAMOUNT", "NOOFSPECCHARGE", "NOOFLABELS", "NOOFTAXES", "CLIENTDELIVERYNOTE_ID", "PROCESSBUSINESSUNIT_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "CLIENTNUMBER", "CLIENTNAME", "ROOM", "STREET", "ZIPCODE_CITY", "CLIENTDELIVERYNOTENUMBER", "CLOSINGDATE", "DELIVERYDATE", "BOXNUMBER", "BATCHCODE", "BATCHNUMBER", "BATCHYEAR", "BATCHWEEK", "BATCHCOLORDESC", "BATCH_CODENUMBER", "DAYDESC", "ROUTENUMBER", "ROUTEDESC", "STOPNUMBER", "GROSSWEIGHT", "WEIGHTDECIMALS", "WEIGHTUNIT", "PACKINGSEQUENCE", "PRODUCTCODE", "SIZECODE", "FINISHINGMETHODCODE", "PRODUCTDESC", "QTYRECEIVED", "QTYDELIVERED", "PRIMARYID", "FLAGCODE", "FLAGDESC", "PRINTWEIGHT", "PRINT_V_CDN_DELAYEDDELIVERY", "PRINT_V_CDN_DELIVEREDAFTER", "PRINT_V_CDN_SENDTOOWNER", "PRINT_V_CDN_RECEIVEFROMOWNER", "CUSTOMERCLIENTS", "PRINTIDCODE", "PRINTLATEPIECES", "ACCEPTOTHERCLIENTS", "PRINTQTYRECEIVED", "SYSTEMSETTINGVALUE", "EMPLOYEENUMBER", "EMPLOYEENAME", "RECORDEMPLCLIENTDELNOTE", "LANGUAGECODE") AS 
  select
  crs.printpriceondelnote, crr.decimals pricedecimals, crr.invoiceamountdecimals amountdecimals
, cdl.price, cdl.priceondelnote, cdn.weightprice
/*, coalesce((select sum(cds.quantity*GETROUND(cds.price,crr.decimals)) from clientdeliverynotespeccharge cds
   where cds.clientdeliverinote_id = cdn.clientdeliverynote_id),0) specialchargeinvamount
, coalesce((select sum(cds.quantity*GETROUND(cds.priceondelnote,crr.decimals)) from clientdeliverynotespeccharge cds
   where cds.clientdeliverinote_id = cdn.clientdeliverynote_id),0) specialchargeamount
, coalesce((select sum(pqr.quantity*GETROUND(pqr.price,crr.decimals)) from printqueueresidentialitem pqr
   where pqr.clientdeliverynote_id = cdn.clientdeliverynote_id),0) labelsamount
, coalesce((select sum(GETROUND(cdt.taxamount,crr.decimals)) from clientdeliverynotetax cdt, taxgroup tg
   where cdt.taxgroup_id = tg.taxgroup_id and cdt.clientdeliverinote_id = cdn.clientdeliverynote_id),0) taxamount*/
, coalesce((select sum(cds.quantity*cds.price) from clientdeliverynotespeccharge cds
   where cds.clientdeliverinote_id = cdn.clientdeliverynote_id),0) specialchargeinvamount
, coalesce((select sum(cds.quantity*cds.priceondelnote) from clientdeliverynotespeccharge cds
   where cds.clientdeliverinote_id = cdn.clientdeliverynote_id),0) specialchargeamount
, coalesce((select sum(pqr.quantity*pqr.price) from printqueueresidentialitem pqr
   where pqr.clientdeliverynote_id = cdn.clientdeliverynote_id),0) labelsamount
, coalesce((select sum(cdt.taxamount) from clientdeliverynotetax cdt, taxgroup tg
   where cdt.taxgroup_id = tg.taxgroup_id and cdt.clientdeliverinote_id = cdn.clientdeliverynote_id),0) taxamount
, (select count(*) from clientdeliverynotespeccharge cds
   where cds.clientdeliverinote_id = cdn.clientdeliverynote_id) noofspeccharge
, (select count(*) from printqueueresidentialitem pqr
   where pqr.clientdeliverynote_id = cdn.clientdeliverynote_id) nooflabels
, (select count(*) from clientdeliverynotetax cdt
   where cdt.clientdeliverinote_id = cdn.clientdeliverynote_id) nooftaxes
, cdn.clientdeliverynote_id, cdn.processbusinessunit_id, cu.customer_id, cu.customernumber, cu.name customerName
, de.departmentnumber, de.description departmentDesc
, client.clientnumber, coalesce(cdn.name, client.name) clientName
, case when cdn.closingdate is null then dr.roomnumber else cdn.roomnumber end room
, case when cdn.street is null then address.street else cdn.street end street
, cast(( case when cdn.street is null then CONCATENATEWITHSIGN(address.zipcode, ' / ', address.city)
              else CONCATENATEWITHSIGN(cdn.zipcode, ' / ', cdn.city) end) as varchar2(255))  zipcode_city
, cdn.clientdeliverynotenumber, cdn.closingdate, cdn.deliverydate, cdn.boxnumber
, batch.batchcode, batch.batchnumber, batch.year batchYear, batch.week batchWeek, batchcolor.description batchcolorDesc
, cast(( case
  when ss.value = '-2' then CONCATENATE(GETSUBSTRINGONLENGTH(batch.batchcode, 1, 2), cast(batch.batchnumber as varchar2(255)))
  when ss.value = '-1' then CONCATENATE(GETSUBSTRINGONLENGTH(batch.batchcode, 1, 1), cast(batch.batchnumber as varchar2(255)))
  when ss.value =  '0' then cast(batch.batchnumber as varchar2(255))
  when ss.value =  '1' then CONCATENATE(cast(batch.batchnumber as varchar2(255)), GETSUBSTRINGONLENGTH(batch.batchcode, 1, 1))
  when ss.value =  '2' then CONCATENATE(cast(batch.batchnumber as varchar2(255)), GETSUBSTRINGONLENGTH(batch.batchcode, 1, 2))
  end) as varchar2(255)) batch_CodeNumber
, ( select day_desc.description from day_desc where batch.day_id = day_desc.day_id and day_desc.language_id = languages.language_id ) dayDesc
, route.routenumber, route.description routeDesc, cdn.stopnumber
, cdn.grossweight, cdn.weightdecimals
, ( select systemsetting.value from systemsetting where systemsetting.plant_id = bu.plant_id and systemsetting.name = 'WEIGHTUNIT' ) WEIGHTUNIT
, prd.packingsequence, prd.code productCode, sz.code sizeCode, fm.code finishingmethodCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( cdl.qtyscannedin + cdl.qtycountedin ) qtyReceived
, ( cdl.qtyscannedout + cdl.qtycountedout ) qtyDelivered
, uri.primaryid, flag.code flagCode
, ( select flag_desc.description from flag_desc where flag.flag_id = flag_desc.flag_id and flag_desc.language_id = languages.language_id ) flagDesc
, ( select count(*) from weighingcategpercustomer wghc where wghc.weighingcategory_id = cdn.weighingcategory_link_id
  and wghc.customer_id = cu.customer_id
      and wghc.invoicemethod = 2 -- invoice soil weight
          and trunc(sysdate) between wghc.dateactive and wghc.dateinactive ) PrintWeight
, ( select count(*) from v_cdn_DelayedDelivery where v_cdn_DelayedDelivery.clientdeliverynote_id = cdn.clientdeliverynote_id ) Print_v_cdn_DelayedDelivery
, ( select count(*) from v_cdn_DeliveredAfter where v_cdn_DeliveredAfter.clientdeliverynote_id = cdn.clientdeliverynote_id ) Print_v_cdn_DeliveredAfter
, ( select count(*) from v_cdn_SendToOwner where v_cdn_SendToOwner.clientdeliverynote_id = cdn.clientdeliverynote_id
     and v_cdn_SendToOwner.ownerNumber <> client.clientnumber) Print_v_cdn_SendToOwner
, ( select count(*) from v_cdn_ReceiveFromOwner where v_cdn_ReceiveFromOwner.clientdeliverynote_id = cdn.clientdeliverynote_id ) Print_v_cdn_ReceiveFromOwner --, cdr.remark
, crs.customerclients, crs.printidcode, crs.printlatepieces, crs.acceptotherclients, crs.printqtyreceived
, ss.value systemsettingValue
, emp.employeenumber, emp.name employeeName
, ( select systemsetting.value from systemsetting where systemsetting.plant_id = bu.plant_id and systemsetting.name = 'RECORDEMPLCLIENTDELNOTE' ) RECORDEMPLCLIENTDELNOTE
, languages.code languageCode
from
  clientdeliverynote cdn
    left outer join route on cdn.route_id = route.route_id
--    left outer join customerclientdelnoteremark cdr on cdn.customer_link_id = cdr.customer_id
--                                            and cdn.deliverydate between cdr.startdate and cdr.enddate
, customer cu, currency crr
, batch
    left outer join employee emp on batch.employee_id = emp.employee_id
, batchcolor
, client
    left outer join
      ( clientresident cr join ( departmentroom dr join department de on dr.department_id = de.department_id )
                            on cr.departmentroom_id = dr.departmentroom_id
      ) on client.client_id = cr.client_id
    left outer join
      ( clientprivateperson cpp join ( deliverypoint delvp join address on delvp.deliveryaddress_id = address.address_id )
                                  on cpp.deliverypoint_id = delvp.deliverypoint_id
      ) on client.client_id = cpp.client_id
, clientdeliverynoteline cdl
    left outer join
      ( clientdelnotelinescan cds
          join uniqueresidentialitem uri on cds.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id
          join ( residentialitemscan ris
                  left outer join ( residentialitemscanflag risf join flag on risf.flag_id = flag.flag_id )
                    on ris.residentialitemscan_id = risf.residentialitemscan_id
          ) on cds.uniqueresidentialitem_link_id = ris.uniqueresidentialitem_link_id
               and trunc(cds.outscantimestamp) = trunc(ris.scantimestamp)
                   and ris.transactiontype_id = 2 -- out scan
      ) on cdl.clientdeliverynoteline_id = cds.outscanclientdelnoteline_id
, product prd, sizedefinition sz, finishingmethod fm
, customerresidentialsettings crs, businessunit bu, systemsetting ss
, languages
where
    cdn.customer_link_id = cu.customer_id
    and cu.customer_id = crs.customer_id
and cdn.client_link_id = client.client_id
and cdn.batch_id = batch.batch_id
    and batch.batchcolor_id = batchcolor.batchcolor_id
and cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
    and cdl.product_link_id = prd.product_id
    and cdl.sizedefinition_link_id = sz.sizedefinition_id
    and cdl.finishingmethod_id = fm.finishingmethod_id
and cdn.processbusinessunit_id = bu.businessunit_id
    and bu.plant_id = ss.plant_id
        AND ss.name = 'BATCHCODEUSAGE'
and cu.currency_id = crr.currency_id
/

  CREATE OR REPLACE VIEW "V_CLIENTDELIVERYNOTE_INI" ("PRINTPRICEONDELNOTE", "PRICEDECIMALS", "AMOUNTDECIMALS", "PRICE", "PRICEONDELNOTE", "WEIGHTPRICE", "SPECIALCHARGEINVAMOUNT", "SPECIALCHARGEAMOUNT", "LABELSAMOUNT", "TAXAMOUNT", "NOOFSPECCHARGE", "NOOFLABELS", "NOOFTAXES", "CLIENTDELIVERYNOTE_ID", "PROCESSBUSINESSUNIT_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "CLIENTNUMBER", "CLIENTNAME", "ROOM", "STREET", "ZIPCODE_CITY", "CLIENTDELIVERYNOTENUMBER", "CLOSINGDATE", "DELIVERYDATE", "BOXNUMBER", "BATCHCODE", "BATCHNUMBER", "BATCHYEAR", "BATCHWEEK", "BATCHCOLORDESC", "BATCH_CODENUMBER", "DAYDESC", "ROUTENUMBER", "ROUTEDESC", "STOPNUMBER", "GROSSWEIGHT", "WEIGHTDECIMALS", "WEIGHTUNIT", "PACKINGSEQUENCE", "PRODUCTCODE", "SIZECODE", "FINISHINGMETHODCODE", "PRODUCTDESC", "QTYRECEIVED", "QTYDELIVERED", "PRIMARYID", "FLAGCODE", "FLAGDESC", "PRINTWEIGHT", "PRINT_V_CDN_DELAYEDDELIVERY", "PRINT_V_CDN_DELIVEREDAFTER", "PRINT_V_CDN_SENDTOOWNER", "PRINT_V_CDN_RECEIVEFROMOWNER", "CUSTOMERCLIENTS", "PRINTIDCODE", "PRINTLATEPIECES", "ACCEPTOTHERCLIENTS", "PRINTQTYRECEIVED", "SYSTEMSETTINGVALUE", "EMPLOYEENUMBER", "EMPLOYEENAME", "RECORDEMPLCLIENTDELNOTE", "LANGUAGECODE") AS 
  select
  crs.printpriceondelnote, crr.decimals pricedecimals, crr.invoiceamountdecimals amountdecimals
, cdl.price, cdl.priceondelnote, cdn.weightprice
/*, coalesce((select sum(cds.quantity*GETROUND(cds.price,crr.decimals)) from clientdeliverynotespeccharge cds
   where cds.clientdeliverinote_id = cdn.clientdeliverynote_id),0) specialchargeinvamount
, coalesce((select sum(cds.quantity*GETROUND(cds.priceondelnote,crr.decimals)) from clientdeliverynotespeccharge cds
   where cds.clientdeliverinote_id = cdn.clientdeliverynote_id),0) specialchargeamount
, coalesce((select sum(pqr.quantity*GETROUND(pqr.price,crr.decimals)) from printqueueresidentialitem pqr
   where pqr.clientdeliverynote_id = cdn.clientdeliverynote_id),0) labelsamount
, coalesce((select sum(GETROUND(cdt.taxamount,crr.decimals)) from clientdeliverynotetax cdt, taxgroup tg
   where cdt.taxgroup_id = tg.taxgroup_id and cdt.clientdeliverinote_id = cdn.clientdeliverynote_id),0) taxamount*/
, coalesce((select sum(cds.quantity*cds.price) from clientdeliverynotespeccharge cds
   where cds.clientdeliverinote_id = cdn.clientdeliverynote_id),0) specialchargeinvamount
, coalesce((select sum(cds.quantity*cds.priceondelnote) from clientdeliverynotespeccharge cds
   where cds.clientdeliverinote_id = cdn.clientdeliverynote_id),0) specialchargeamount
, coalesce((select sum(pqr.quantity*pqr.price) from printqueueresidentialitem pqr
   where pqr.clientdeliverynote_id = cdn.clientdeliverynote_id),0) labelsamount
, coalesce((select sum(cdt.taxamount) from clientdeliverynotetax cdt, taxgroup tg
   where cdt.taxgroup_id = tg.taxgroup_id and cdt.clientdeliverinote_id = cdn.clientdeliverynote_id),0) taxamount
, (select count(*) from clientdeliverynotespeccharge cds
   where cds.clientdeliverinote_id = cdn.clientdeliverynote_id) noofspeccharge
, (select count(*) from printqueueresidentialitem pqr
   where pqr.clientdeliverynote_id = cdn.clientdeliverynote_id) nooflabels
, (select count(*) from clientdeliverynotetax cdt
   where cdt.clientdeliverinote_id = cdn.clientdeliverynote_id) nooftaxes
, cdn.clientdeliverynote_id, cdn.processbusinessunit_id, cu.customer_id, cu.customernumber, cu.name customerName
, de.departmentnumber, de.description departmentDesc
, client.clientnumber, coalesce(cdn.name, client.name) clientName
, case when cdn.closingdate is null then dr.roomnumber else cdn.roomnumber end room
, case when cdn.street is null then address.street else cdn.street end street
, cast(( case when cdn.street is null then CONCATENATEWITHSIGN(address.zipcode, ' / ', address.city)
              else CONCATENATEWITHSIGN(cdn.zipcode, ' / ', cdn.city) end) as varchar2(255))  zipcode_city
, cdn.clientdeliverynotenumber, cdn.closingdate, cdn.deliverydate, cdn.boxnumber
, batch.batchcode, batch.batchnumber, batch.year batchYear, batch.week batchWeek, batchcolor.description batchcolorDesc
, cast(( case
  when ss.value = '-2' then CONCATENATE(GETSUBSTRINGONLENGTH(batch.batchcode, 1, 2), cast(batch.batchnumber as varchar2(255)))
  when ss.value = '-1' then CONCATENATE(GETSUBSTRINGONLENGTH(batch.batchcode, 1, 1), cast(batch.batchnumber as varchar2(255)))
  when ss.value =  '0' then cast(batch.batchnumber as varchar2(255))
  when ss.value =  '1' then CONCATENATE(cast(batch.batchnumber as varchar2(255)), GETSUBSTRINGONLENGTH(batch.batchcode, 1, 1))
  when ss.value =  '2' then CONCATENATE(cast(batch.batchnumber as varchar2(255)), GETSUBSTRINGONLENGTH(batch.batchcode, 1, 2))
  end) as varchar2(255)) batch_CodeNumber
, ( select day_desc.description from day_desc where batch.day_id = day_desc.day_id and day_desc.language_id = languages.language_id ) dayDesc
, route.routenumber, route.description routeDesc, cdn.stopnumber
, cdn.grossweight, cdn.weightdecimals
, ( select systemsetting.value from systemsetting where systemsetting.plant_id = bu.plant_id and systemsetting.name = 'WEIGHTUNIT' ) WEIGHTUNIT
, prd.packingsequence, prd.code productCode, sz.code sizeCode, fm.code finishingmethodCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( cdl.qtyscannedin + cdl.qtycountedin ) qtyReceived
, ( cdl.qtyscannedout + cdl.qtycountedout ) qtyDelivered
, uri.primaryid, flag.code flagCode
, ( select flag_desc.description from flag_desc where flag.flag_id = flag_desc.flag_id and flag_desc.language_id = languages.language_id ) flagDesc
, ( select count(*) from weighingcategpercustomer wghc where wghc.weighingcategory_id = cdn.weighingcategory_link_id
  and wghc.customer_id = cu.customer_id
      and wghc.invoicemethod = 2 -- invoice soil weight
          and trunc(sysdate) between wghc.dateactive and wghc.dateinactive ) PrintWeight
, ( select count(*) from v_cdn_DelayedDelivery where v_cdn_DelayedDelivery.clientdeliverynote_id = cdn.clientdeliverynote_id ) Print_v_cdn_DelayedDelivery
, ( select count(*) from v_cdn_DeliveredAfter where v_cdn_DeliveredAfter.clientdeliverynote_id = cdn.clientdeliverynote_id ) Print_v_cdn_DeliveredAfter
, ( select count(*) from v_cdn_SendToOwner where v_cdn_SendToOwner.clientdeliverynote_id = cdn.clientdeliverynote_id
     and v_cdn_SendToOwner.ownerNumber <> client.clientnumber) Print_v_cdn_SendToOwner
, ( select count(*) from v_cdn_ReceiveFromOwner where v_cdn_ReceiveFromOwner.clientdeliverynote_id = cdn.clientdeliverynote_id ) Print_v_cdn_ReceiveFromOwner
--, cdr.remark
, crs.customerclients, crs.printidcode, crs.printlatepieces, crs.acceptotherclients, crs.printqtyreceived
, ss.value systemsettingValue
, emp.employeenumber, emp.name employeeName
, ( select systemsetting.value from systemsetting where systemsetting.plant_id = bu.plant_id and systemsetting.name = 'RECORDEMPLCLIENTDELNOTE' ) RECORDEMPLCLIENTDELNOTE
, languages.code languageCode
from
  clientdeliverynote cdn
    left outer join route on cdn.route_id = route.route_id
--    left outer join customerclientdelnoteremark cdr on cdn.customer_link_id = cdr.customer_id
--                                            and cdn.deliverydate between cdr.startdate and cdr.enddate
, customer cu, currency crr
, batch
    left outer join employee emp on batch.employee_id = emp.employee_id
, batchcolor
, client
    left outer join
      ( clientresident cr join ( departmentroom dr join department de on dr.department_id = de.department_id )
                            on cr.departmentroom_id = dr.departmentroom_id
      ) on client.client_id = cr.client_id
    left outer join
      ( clientprivateperson cpp join ( deliverypoint delvp join address on delvp.deliveryaddress_id = address.address_id )
                                  on cpp.deliverypoint_id = delvp.deliverypoint_id
      ) on client.client_id = cpp.client_id
, clientdeliverynoteline cdl
    left outer join
      ( clientdelnotelinescan cds
          join uniqueresidentialitem uri on cds.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id
          join ( residentialitemscan ris
                  left outer join ( residentialitemscanflag risf join flag on risf.flag_id = flag.flag_id )
                    on ris.residentialitemscan_id = risf.residentialitemscan_id
          ) on cds.uniqueresidentialitem_link_id = ris.uniqueresidentialitem_link_id
               and trunc(cds.outscantimestamp) = trunc(ris.scantimestamp)
                   and ris.transactiontype_id = 2 -- out scan
      ) on cdl.clientdeliverynoteline_id = cds.outscanclientdelnoteline_id
, product prd, sizedefinition sz, finishingmethod fm
, customerresidentialsettings crs, businessunit bu, systemsetting ss
, languages
where
    cdn.customer_link_id = cu.customer_id
    and cu.customer_id = crs.customer_id
and cdn.client_link_id = client.client_id
and cdn.batch_id = batch.batch_id
    and batch.batchcolor_id = batchcolor.batchcolor_id
and cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
    and cdl.product_link_id = prd.product_id
    and cdl.sizedefinition_link_id = sz.sizedefinition_id
    and cdl.finishingmethod_id = fm.finishingmethod_id
and cdn.processbusinessunit_id = bu.businessunit_id
    and bu.plant_id = ss.plant_id
        AND ss.name = 'BATCHCODEUSAGE'
and cu.currency_id = crr.currency_id
/

  CREATE OR REPLACE VIEW "V_CLIENTDELIVERYNOTE_TEST" ("PRINTPRICEONDELNOTE", "PRICEDECIMALS", "AMOUNTDECIMALS", "PRICE", "PRICEONDELNOTE", "WEIGHTPRICE", "SPECIALCHARGEINVAMOUNT", "SPECIALCHARGEAMOUNT", "LABELSAMOUNT", "TAXAMOUNT", "NOOFSPECCHARGE", "NOOFLABELS", "NOOFTAXES", "CLIENTDELIVERYNOTE_ID", "PROCESSBUSINESSUNIT_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "CLIENTNUMBER", "CLIENTNAME", "ROOM", "STREET", "ZIPCODE_CITY", "CLIENTDELIVERYNOTENUMBER", "CLOSINGDATE", "DELIVERYDATE", "BOXNUMBER", "BATCHCODE", "BATCHNUMBER", "BATCHYEAR", "BATCHWEEK", "BATCHCOLORDESC", "BATCH_CODENUMBER", "DAYDESC", "ROUTENUMBER", "ROUTEDESC", "STOPNUMBER", "GROSSWEIGHT", "WEIGHTDECIMALS", "WEIGHTUNIT", "PACKINGSEQUENCE", "PRODUCTCODE", "SIZECODE", "FINISHINGMETHODCODE", "PRODUCTDESC", "QTYRECEIVED", "QTYDELIVERED", "PRIMARYID", "FLAGCODE", "FLAGDESC", "PRINTWEIGHT", "PRINT_V_CDN_DELAYEDDELIVERY", "PRINT_V_CDN_DELIVEREDAFTER", "PRINT_V_CDN_SENDTOOWNER", "PRINT_V_CDN_RECEIVEFROMOWNER", "CUSTOMERCLIENTS", "PRINTIDCODE", "PRINTLATEPIECES", "ACCEPTOTHERCLIENTS", "PRINTQTYRECEIVED", "SYSTEMSETTINGVALUE", "EMPLOYEENUMBER", "EMPLOYEENAME", "RECORDEMPLCLIENTDELNOTE", "LANGUAGECODE") AS 
  select
  crs.printpriceondelnote, crr.decimals pricedecimals, crr.invoiceamountdecimals amountdecimals
, cdl.price, cdl.priceondelnote, cdn.weightprice
, coalesce((select sum(cds.quantity*cds.price) from clientdeliverynotespeccharge cds
   where cds.clientdeliverinote_id = cdn.clientdeliverynote_id),0) specialchargeinvamount
, coalesce((select sum(cds.quantity*cds.priceondelnote) from clientdeliverynotespeccharge cds
   where cds.clientdeliverinote_id = cdn.clientdeliverynote_id),0) specialchargeamount
, coalesce((select sum(pqr.quantity*pqr.price) from printqueueresidentialitem pqr
   where pqr.clientdeliverynote_id = cdn.clientdeliverynote_id),0) labelsamount
, coalesce((select sum(cdt.taxamount) from clientdeliverynotetax cdt, taxgroup tg
   where cdt.taxgroup_id = tg.taxgroup_id and cdt.clientdeliverinote_id = cdn.clientdeliverynote_id),0) taxamount
, (select count(*) from clientdeliverynotespeccharge cds
   where cds.clientdeliverinote_id = cdn.clientdeliverynote_id) noofspeccharge
, (select count(*) from printqueueresidentialitem pqr
   where pqr.clientdeliverynote_id = cdn.clientdeliverynote_id) nooflabels
, (select count(*) from clientdeliverynotetax cdt
   where cdt.clientdeliverinote_id = cdn.clientdeliverynote_id) nooftaxes
, cdn.clientdeliverynote_id, cdn.processbusinessunit_id, cu.customer_id, cu.customernumber, cu.name customerName
, de.departmentnumber, de.description departmentDesc
, client.clientnumber, coalesce(cdn.name, client.name) clientName
, case when cdn.closingdate is null then dr.roomnumber else cdn.roomnumber end room
, case when cdn.street is null then address.street else cdn.street end street
, cast(( case when cdn.street is null then CONCATENATEWITHSIGN(address.zipcode, ' / ', address.city)
              else CONCATENATEWITHSIGN(cdn.zipcode, ' / ', cdn.city) end) as varchar2(255))  zipcode_city
, cdn.clientdeliverynotenumber, cdn.closingdate, cdn.deliverydate, cdn.boxnumber
, batch.batchcode, batch.batchnumber, batch.year batchYear, batch.week batchWeek, batchcolor.description batchcolorDesc
, cast(( case
  when ss.value = '-2' then CONCATENATE(GETSUBSTRINGONLENGTH(batch.batchcode, 1, 2), cast(batch.batchnumber as varchar2(255)))
  when ss.value = '-1' then CONCATENATE(GETSUBSTRINGONLENGTH(batch.batchcode, 1, 1), cast(batch.batchnumber as varchar2(255)))
  when ss.value =  '0' then cast(batch.batchnumber as varchar2(255))
  when ss.value =  '1' then CONCATENATE(cast(batch.batchnumber as varchar2(255)), GETSUBSTRINGONLENGTH(batch.batchcode, 1, 1))
  when ss.value =  '2' then CONCATENATE(cast(batch.batchnumber as varchar2(255)), GETSUBSTRINGONLENGTH(batch.batchcode, 1, 2))
  end) as varchar2(255)) batch_CodeNumber
, ( select day_desc.description from day_desc where batch.day_id = day_desc.day_id and day_desc.language_id = languages.language_id ) dayDesc
, route.routenumber, route.description routeDesc, cdn.stopnumber
, cdn.grossweight, cdn.weightdecimals
, ( select systemsetting.value from systemsetting where systemsetting.plant_id = bu.plant_id and systemsetting.name = 'WEIGHTUNIT' ) WEIGHTUNIT
, prd.packingsequence, prd.code productCode, sz.code sizeCode, fm.code finishingmethodCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( cdl.qtyscannedin + cdl.qtycountedin ) qtyReceived
, ( cdl.qtyscannedout + cdl.qtycountedout ) qtyDelivered
, uri.primaryid, flag.code flagCode
, ( select flag_desc.description from flag_desc where flag.flag_id = flag_desc.flag_id and flag_desc.language_id = languages.language_id ) flagDesc
, ( select count(*) from weighingcategpercustomer wghc where wghc.weighingcategory_id = cdn.weighingcategory_link_id
  and wghc.customer_id = cu.customer_id
      and wghc.invoicemethod = 2 -- invoice soil weight
          and trunc(sysdate) between wghc.dateactive and wghc.dateinactive ) PrintWeight
, ( select count(*) from v_cdn_DelayedDelivery where v_cdn_DelayedDelivery.clientdeliverynote_id = cdn.clientdeliverynote_id ) Print_v_cdn_DelayedDelivery
, ( select count(*) from v_cdn_DeliveredAfter where v_cdn_DeliveredAfter.clientdeliverynote_id = cdn.clientdeliverynote_id ) Print_v_cdn_DeliveredAfter
, ( select count(*) from v_cdn_SendToOwner where v_cdn_SendToOwner.clientdeliverynote_id = cdn.clientdeliverynote_id
     and v_cdn_SendToOwner.ownerNumber <> client.clientnumber) Print_v_cdn_SendToOwner
, ( select count(*) from v_cdn_ReceiveFromOwner where v_cdn_ReceiveFromOwner.clientdeliverynote_id = cdn.clientdeliverynote_id ) Print_v_cdn_ReceiveFromOwner
--, cdr.remark
, crs.customerclients, crs.printidcode, crs.printlatepieces, crs.acceptotherclients, crs.printqtyreceived
, ss.value systemsettingValue
, emp.employeenumber, emp.name employeeName
, ( select systemsetting.value from systemsetting where systemsetting.plant_id = bu.plant_id and systemsetting.name = 'RECORDEMPLCLIENTDELNOTE' ) RECORDEMPLCLIENTDELNOTE
, languages.code languageCode
from
  clientdeliverynote cdn
    left outer join route on cdn.route_id = route.route_id
    left outer join ( clientdeliverynoteline cdl
      join product prd on cdl.product_link_id = prd.product_id
      join sizedefinition sz on cdl.sizedefinition_link_id = sz.sizedefinition_id
      join  finishingmethod fm on cdl.finishingmethod_id = fm.finishingmethod_id
      left outer join ( clientdelnotelinescan cds
         join uniqueresidentialitem uri on cds.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id
         join ( residentialitemscan ris
              left outer join ( residentialitemscanflag risf join flag on risf.flag_id = flag.flag_id )
                 on ris.residentialitemscan_id = risf.residentialitemscan_id
            ) on cds.uniqueresidentialitem_link_id = ris.uniqueresidentialitem_link_id
                 and trunc(cds.outscantimestamp) = trunc(ris.scantimestamp)
                     and ris.transactiontype_id = 2 -- out scan
        ) on cdl.clientdeliverynoteline_id = cds.outscanclientdelnoteline_id
      ) on cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
, customer cu, currency crr
, batch
    left outer join employee emp on batch.employee_id = emp.employee_id
, batchcolor
, client
    left outer join
      ( clientresident cr join ( departmentroom dr join department de on dr.department_id = de.department_id )
                            on cr.departmentroom_id = dr.departmentroom_id
      ) on client.client_id = cr.client_id
    left outer join
      ( clientprivateperson cpp join ( deliverypoint delvp join address on delvp.deliveryaddress_id = address.address_id )
                                  on cpp.deliverypoint_id = delvp.deliverypoint_id
      ) on client.client_id = cpp.client_id
--, product prd, sizedefinition sz, finishingmethod fm
, customerresidentialsettings crs, businessunit bu, systemsetting ss
, languages
where
    cdn.customer_link_id = cu.customer_id
    and cu.customer_id = crs.customer_id
and cdn.client_link_id = client.client_id
and cdn.batch_id = batch.batch_id
    and batch.batchcolor_id = batchcolor.batchcolor_id
--and cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
--    and cdl.product_link_id = prd.product_id
--    and cdl.sizedefinition_link_id = sz.sizedefinition_id
--    and cdl.finishingmethod_id = fm.finishingmethod_id
and cdn.processbusinessunit_id = bu.businessunit_id
    and bu.plant_id = ss.plant_id
        AND ss.name = 'BATCHCODEUSAGE'
and cu.currency_id = crr.currency_id
/

  CREATE OR REPLACE VIEW "V_COMPLETENESSOVERVIEW" ("PLANTCODE", "PLANTNAME", "ROUTENUMBER", "ROUTEDESCRIPTION", "DAYCODE", "DAYDESC", "RCDATE", "ROUTEYEAR", "ROUTEMONTH", "DAY_OF_MONTH", "STOPNUMBER", "DEPOTCODE", "DEPOTDESCRIPTION", "CUSTOMERNUMBER", "CUSTNAME", "DELIVERYPOINT_ID", "DELPSTOPCODE", "DELPSTOPDESCR", "DELPCUSTCODE", "DELPCUSTDESCR", "CUSTADDRESS", "DELPSTOPADDRESS", "PRODCODE", "PRODDESCR", "SUMQTYIN", "SUMQTYOUT", "INTERNALPLANTCODE", "INTERNALPLANTNAME", "LANGUAGECODE") AS 
  select
s.plantcode,
s.plantname, s.routenumber, s.routedescription,
s.Daycode,s.Daydesc,s.RCDate,s.Routeyear, s.RouteMonth, s.Day_of_month,
s.stopnumber,s.depotcode,s.depotdescription,s.customernumber, s.custname,
s.deliverypoint_id, s.delpstopcode, s.delpstopdescr,
s.delpcustcode, s.delpcustdescr,
s.custaddress,s.delpstopaddress,s.prodcode,
s.proddescr,
(case when (select ss.value from systemsetting ss where ss.name = 'COMPCHECKNONUNIQUE'
            and ss.plant_id = (select p.plant_id from plant p where p.code = s.plantcode)) = 0 then sum(s.qtyIN_val0)
      when (select ss.value from systemsetting ss where ss.name = 'COMPCHECKNONUNIQUE'
            and ss.plant_id = (select p.plant_id from plant p where p.code = s.plantcode)) = 1 then sum(s.qtyIN_val0) - sum(s.qtyIN_val2)
 else sum(s.qtyIN_val2) end) sumQtyIn,
coalesce (( select vout.qtyOUT from v_completenessoverviewout vout where s.plantcode=vout.plantcode and s.RCDate=vout.RCDate
and s.route_id=vout.route_id and s.stop_id=vout.stop_id and s.customernumber=vout.customernumber and nvl(s.deliverypoint_id,0)=nvl(vout.deliverypoint_id,0)
and s.prodcode=vout.prodcleancode and s.languagecode=vout.languagecode),0)  sumQtyOut,
s.internalplantcode,
s.internalplantname,
s.languagecode
from v_completenessoverview_aux s
group by s.plantcode, s.plantname, s.internalplantcode, s.internalplantname,s.RCDate,s.Routeyear, s.RouteMonth, s.Day_of_month,
s.Daycode, s.Daydesc, s.routenumber, s.route_id,s.routedescription, s.stop_id,s.stopnumber, s.customernumber, s.custname
,s.delpstopcode, s.delpcustcode, s.prodcode, s.proddescr,s.languagecode, s.depotcode, s.depotdescription,
s.deliverypoint_id, s.delpstopdescr, s.delpcustdescr, s.custaddress,s.delpstopaddress
/

  CREATE OR REPLACE VIEW "V_CONTACTDETAILS" ("NEWDATE", "CUSTOMERNUMBER", "CUSTOMERNAME", "PLANT_ID", "CATEGORYCODE", "ACTIONDATE", "CATEGORYDESC", "EVALDATE", "CALLNUMBER", "STATUS", "PRIORITY", "CREATEDBYUSERNAME", "FOLLOWUPBYUSERNAME", "CONTACTNOTES", "FOLLOWUPNOTES", "LANGUAGECODE") AS 
  select
  ct.newdate, cu.customernumber, cu.name customername, vx.plant_id
, cty.code categorycode, ct.followupdate actiondate
, ( select contactcategory_desc.description from contactcategory_desc where contactcategory_desc.contactcategory_id = cty.contactcategory_id
  and contactcategory_desc.language_id = languages.language_id ) categorydesc
, case ct.status when 1 then ct.newdate
                -- when 2 then ct.followupdate abs-109750
                 when 3 then ct.inprogressdate
                 when 4 then ct.completeddate
                 when 5 then ct.reviewdate
                 when 6 then ct.closedate end evaldate
, ct.callnumber, ct.status, ct.priority --  1 = low, 2 = medium, 3 = high
, csy.username createdbyusername, fsy.username followupbyusername
, ct.contactnotes, ct.followupnotes
, languages.code languagecode
from contact ct
     inner join contactcategory cty on ct.contactcategory_id = cty.contactcategory_id
     left outer join systemuser csy on ct.createdbyuser_id = csy.systemuser_id
     inner join customer cu on ct.customer_link_id = cu.customer_id
     inner join v_contactpercategory_aux vx on cu.customer_id = vx.customer_id
     left outer join systemuser fsy on ct.followupbyuser_id = fsy.systemuser_id
, languages
/

  CREATE OR REPLACE VIEW "V_CONTACTPERCATEGORY" ("CALLNUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "PLANT_ID", "BUSINESSUNIT_ID", "STATUS", "PRIORITY", "EVALDATE", "CATEGORYCODE", "CATEGORYDESC", "QUANTITY", "NEWDATE", "LANGUAGECODE") AS 
  select distinct -- 1 --
  ct.callnumber,cu.customernumber, cu.name customername, address.city, vx.plant_id, vx.businessunit_id
, ct.status, ct.priority --  1 = low, 2 = medium, 3 = high
, case ct.status when 1 then ct.newdate
                -- when 2 then ct.followupdate abs-109750
                 when 3 then ct.inprogressdate
                 when 4 then ct.completeddate
                 when 5 then ct.reviewdate
                 when 6 then ct.closedate end evaldate
,  cty.code categorycode
, ( select contactcategory_desc.description from contactcategory_desc where contactcategory_desc.contactcategory_id = cty.contactcategory_id
  and contactcategory_desc.language_id = languages.language_id ) categorydesc
, count(cty.code) quantity, ct.newdate
, languages.code languagecode
from contact ct
     inner join contactcategory cty on ct.contactcategory_id = cty.contactcategory_id
     inner join v_contactpercategory_aux vx on ct.businessunit_id = vx.businessunit_id
     inner join customer cu on (ct.customer_link_id = cu.customer_id and cu.customer_id = vx.customer_id)
     inner join address on  cu.visitaddress_id = address.address_id
     , languages
group by
  cu.customernumber, cu.name,address.city, vx.plant_id, vx.businessunit_id
, ct.status, ct.priority, ct.newdate, ct.inprogressdate, ct.completeddate, ct.reviewdate, ct.closedate
, cty.code, cty.contactcategory_id
, languages.language_id, languages.code, ct.callnumber
/

  CREATE OR REPLACE VIEW "V_CONTRACTEXPIRATIONROUTE" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMERACTIVEYN", "STREET", "STREET2", "DRIVINGDAY_ID", "CITY", "STATE", "ZIPCODE", "PHONENO", "ROUTENUMBER", "ROUTEDESC", "DAYDESC", "STOPANDDELSCHEME", "CONTRACTCODE", "CONTRACTDATEACTIVE", "STARTSIGNALINGDATE", "CONTRACTDATEINACTIVE", "MAXCONTRACTDATEACTIVE", "MINCONTRACTDATEINACTIVE", "SIGNALINGWEEKS", "CONTINUESERVICE", "ESTIMATEDWEEKLYSALES", "CONTACTPERSONNAME", "CONTACTPERSONPHONE", "HAVECONTINUE", "BUSINESSUNITCODE", "LANGUAGECODE") AS 
  select
  cu.customernumber, cu.name CustomerName, cu.active CustomerActiveYN, address.street, address.street2
, cu.drivingday_id
, address.city, address.state, address.zipcode, cu.phoneno
, cu.routenumber, cu.routedesc
, (select dd.description from day_desc dd where dd.day_id = cu.drivingday_id
     and dd.language_id = l.language_id) daydesc
, CAST(F_GETSTOPANDDELSCHEME(cu.customer_id, cu.route_id) as varchar(255)) stopanddelscheme
, kcu.code ContractCode, kcu.dateactive Contractdateactive
, (kcu.dateinactive- 7*kcu.signalingweeks) StartSignalingDate, kcu.dateinactive Contractdateinactive
, (select max(contractspercustomer.dateactive) from  contractspercustomer
          where contractspercustomer.customer_id = cu.customer_id) MaxContractdateactive
, (select max(contractspercustomer.dateinactive) from  contractspercustomer
          where contractspercustomer.customer_id = cu.customer_id) MinContractdateinactive
, kcu.signalingweeks
, kcu.continueservice, kcu.estimatedweeklysales, contactperson.name contactpersonName
, contactperson.phone contactpersonPhone
, coalesce((select sum(1)from contractspercustomer k where
      k.customer_id = kcu.customer_id
  and kcu.dateinactive>=k.dateactive and kcu.dateinactive<k.dateinactive
  and k.code<>kcu.code ),0) HaveContinue,
  bu.code businessunitcode, l.code languagecode
from --  customer cu,
  v_contractexpiration_rc cu, address, businessunit bu,
  contractspercustomer kcu
    left outer join contactperson on contactperson.contactperson_id=kcu.contactperson_id,
  languages l
where cu.mailaddress_id = address.address_id
  and cu.customer_id = kcu.customer_id
  and cu.defaultbusinessunit_id = bu.businessunit_id
/

  CREATE OR REPLACE VIEW "V_CONTRACTPRICEUPDATE" ("LINETYPE", "AGREED", "CONTRACTCODE", "CONTRACTDESC", "STARTDATE", "ENDDATE", "NEXTSCHEDULEPRICEINCREASE", "PRODUCTCODE", "TYPEOFMERCHANDISE", "SIZECODE", "FINISHCODE", "SIZE_SEQUENCE", "PRODUCTDESC", "SIZEDESC", "FINISHDESC", "PRICEINDEXCODE", "PRICEINDEXDESC", "PRICEINDEXSTART", "PIHPERCENT", "CURRENCYCODE", "CURRENCYDESC", "DECIMALS", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE", "GPLCODE", "GPLDESC", "PRICE", "VOLUMEPRICE", "SOIL") AS 
  select 1 linetype, v1.agreed, v1.contractcode, v1.contractdesc, v1.startdate, v1.enddate, v1.nextschedulepriceincrease,
       v1.productcode, v1.typeofmerchandise, v1.sizecode, v1.finishcode, v1.size_sequence, v1.productdesc,
       v1.sizedesc, v1.finishdesc, v1.priceindexcode, v1.priceindexdesc, v1.priceindexstart,
       v1.pihpercent, v1.currencycode, v1.currencydesc, v1.decimals, v1.invoiceamountdecimals,
       v1.languagecode, v1.gplcode, v1.gpldesc, v1.price, v1.volumeprice, v1.soil
  from v_contractpriceupdate_wash v1
 union all
select 2 linetype, v2.agreed, v2.contractcode, v2.contractdesc, v2.startdate, v2.enddate, v2.nextschedulepriceincrease,
       v2.productcode, v2.typeofmerchandise, v2.sizecode, v2.finishcode, v2.size_sequence, v2.productdesc,
       v2.sizedesc, v2.finishdesc, v2.priceindexcode, v2.priceindexdesc, v2.priceindexstart,
       v2.pihpercent, v2.currencycode, v2.currencydesc, v2.decimals, v2.invoiceamountdecimals,
       v2.languagecode, v2.gplcode, v2.gpldesc, v2.price, v2.volumeprice, v2.soil
  from v_contractpriceupdate_washcog v2
 union all
select 3 linetype, v3.agreed, v3.contractcode, v3.contractdesc, v3.startdate, v3.enddate, v3.nextschedulepriceincrease,
       v3.productcode, v3.typeofmerchandise, v3.sizecode, v3.finishcode, v3.size_sequence, v3.productdesc,
       v3.sizedesc, v3.finishdesc, v3.priceindexcode, v3.priceindexdesc, v3.priceindexstart,
       v3.pihpercent, v3.currencycode, v3.currencydesc, v3.decimals, v3.invoiceamountdecimals,
       v3.languagecode, v3.gplcode, v3.gpldesc, v3.price, v3.volumeprice, v3.soil
  from v_contractpriceupdate_rent v3
 union all
select 4 linetype, v4.agreed, v4.contractcode, v4.contractdesc, v4.startdate, v4.enddate, v4.nextschedulepriceincrease,
       v4.productcode, v4.typeofmerchandise, v4.sizecode, v4.finishcode, v4.size_sequence, v4.productdesc,
       v4.sizedesc, v4.finishdesc, v4.priceindexcode, v4.priceindexdesc, v4.priceindexstart,
       v4.pihpercent, v4.currencycode, v4.currencydesc, v4.decimals, v4.invoiceamountdecimals,
       v4.languagecode, v4.gplcode, v4.gpldesc, v4.price, v4.volumeprice, v4.soil
  from v_contractpriceupdate_sales v4
 union all
select 5 linetype, v5.agreed, v5.contractcode, v5.contractdesc, v5.startdate, v5.enddate, v5.nextschedulepriceincrease,
       v5.productcode, v5.typeofmerchandise, v5.sizecode, v5.finishcode, v5.size_sequence, v5.productdesc,
       v5.sizedesc, v5.finishdesc, v5.priceindexcode, v5.priceindexdesc, v5.priceindexstart,
       v5.pihpercent, v5.currencycode, v5.currencydesc, v5.decimals, v5.invoiceamountdecimals,
       v5.languagecode, v5.gplcode, v5.gpldesc, v5.price, v5.volumeprice, v5.soil
  from v_contractpriceupdate_replacement v5
 union all
select 6 linetype, v6.agreed, v6.contractcode, v6.contractdesc, v6.startdate, v6.enddate, v6.nextschedulepriceincrease,
       v6.productcode, v6.typeofmerchandise, v6.sizecode, v6.finishcode, v6.size_sequence, v6.productdesc,
       v6.sizedesc, v6.finishdesc, v6.priceindexcode, v6.priceindexdesc, v6.priceindexstart,
       v6.pihpercent, v6.currencycode, v6.currencydesc, v6.decimals, v6.invoiceamountdecimals,
       v6.languagecode, v6.gplcode, v6.gpldesc, v6.price, v6.volumeprice, v6.soil
  from v_contractpriceupdate_weight v6
 union all
select 7 linetype, v7.agreed, v7.contractcode, v7.contractdesc, v7.startdate, v7.enddate, v7.nextschedulepriceincrease,
       v7.productcode, v7.typeofmerchandise, v7.sizecode, v7.finishcode, v7.size_sequence, v7.productdesc,
       v7.sizedesc, v7.finishdesc, v7.priceindexcode, v7.priceindexdesc, v7.priceindexstart,
       v7.pihpercent, v7.currencycode, v7.currencydesc, v7.decimals, v7.invoiceamountdecimals,
       v7.languagecode, v7.gplcode, v7.gpldesc, v7.price, v7.volumeprice, v7.soil
  from v_contractpriceupdate_repair v7
 union all
select 8 linetype, v8.agreed, v8.contractcode, v8.contractdesc, v8.startdate, v8.enddate, v8.nextschedulepriceincrease,
       v8.productcode, v8.typeofmerchandise, v8.sizecode, v8.finishcode, v8.size_sequence, v8.productdesc,
       v8.sizedesc, v8.finishdesc, v8.priceindexcode, v8.priceindexdesc, v8.priceindexstart,
       v8.pihpercent, v8.currencycode, v8.currencydesc, v8.decimals, v8.invoiceamountdecimals,
       v8.languagecode, v8.gplcode, v8.gpldesc, v8.price, v8.volumeprice, v8.soil
  from v_contractpriceupdate_emblem v8
 union all
select 9 linetype, v9.agreed, v9.contractcode, v9.contractdesc, v9.startdate, v9.enddate, v9.nextschedulepriceincrease,
       v9.productcode, v9.typeofmerchandise, v9.sizecode, v9.finishcode, v9.size_sequence, v9.productdesc,
       v9.sizedesc, v9.finishdesc, v9.priceindexcode, v9.priceindexdesc, v9.priceindexstart,
       v9.pihpercent, v9.currencycode, v9.currencydesc, v9.decimals, v9.invoiceamountdecimals,
       v9.languagecode, v9.gplcode, v9.gpldesc, v9.price, v9.volumeprice, v9.soil
  from v_contractpriceupdate_insurance v9
 union all
select 10 linetype, v10.agreed, v10.contractcode, v10.contractdesc, v10.startdate, v10.enddate, v10.nextschedulepriceincrease,
       v10.productcode, v10.typeofmerchandise, v10.sizecode, v10.finishcode, v10.size_sequence, v10.productdesc,
       v10.sizedesc, v10.finishdesc, v10.priceindexcode, v10.priceindexdesc, v10.priceindexstart,
       v10.pihpercent, v10.currencycode, v10.currencydesc, v10.decimals, v10.invoiceamountdecimals,
       v10.languagecode, v10.gplcode, v10.gpldesc, v10.price, v10.volumeprice, v10.soil
  from v_contractpriceupdate_budgetprot v10
 union all
select 11 linetype, v11.agreed, v11.contractcode, v11.contractdesc, v11.startdate, v11.enddate, v11.nextschedulepriceincrease,
       v11.productcode, v11.typeofmerchandise, v11.sizecode, v11.finishcode, v11.size_sequence, v11.productdesc,
       v11.sizedesc, v11.finishdesc, v11.priceindexcode, v11.priceindexdesc, v11.priceindexstart,
       v11.pihpercent, v11.currencycode, v11.currencydesc, v11.decimals, v11.invoiceamountdecimals,
       v11.languagecode, v11.gplcode, v11.gpldesc, v11.price, v11.volumeprice, v11.soil
  from v_contractpriceupdate_speccharge v11
 union all
select 12 linetype, v12.agreed, v12.contractcode, v12.contractdesc, v12.startdate, v12.enddate, v12.nextschedulepriceincrease,
       v12.productcode, v12.typeofmerchandise, v12.sizecode, v12.finishcode, v12.size_sequence, v12.productdesc,
       v12.sizedesc, v12.finishdesc, v12.priceindexcode, v12.priceindexdesc, v12.priceindexstart,
       v12.pihpercent, v12.currencycode, v12.currencydesc, v12.decimals, v12.invoiceamountdecimals,
       v12.languagecode, v12.gplcode, v12.gpldesc, v12.price, v12.volumeprice, v12.soil
  from v_contractpriceupdate_specsizecharge v12
/

  CREATE OR REPLACE VIEW "V_COSTREPORTINFO" ("INVOICELINE_ID", "COSTCENTER_LINK_ID", "QUANTITY", "AMOUNT") AS 
  select CCI.INVOICELINE_ID, CCI.COSTCENTER_LINK_ID, CCI.QUANTITY,
       GETROUND(CCI.QUANTITY * IL.PRICE, CURRENCY.INVOICEAMOUNTDECIMALS) AMOUNT
from V_COSTREPORTINFOHELP CCI, INVOICELINE IL, INVOICEHEADER IH, CURRENCY
where CCI.INVOICELINE_ID = IL.INVOICELINE_ID and
      IL.INVOICEHEADER_ID = IH.INVOICEHEADER_ID and
      IH.CURRENCY_ID = CURRENCY.CURRENCY_ID
/

  CREATE OR REPLACE VIEW "V_COSTSSPECIFICATIONPERCLIENT" ("LINE_TYPE", "LABELLAYOUT_ID", "L_INVOICELINE_ID", "INVOICEHEADER_ID", "L_INVOICENUMBER", "L_DOCUMENTTYPE", "H_INVOICELINE_ID", "H_INVOICENUMBER", "H_DOCUMENTTYPE", "IHINVOICEBUSINESSUNIT_ID", "CDNINVOICEBUSINESSUNIT_ID", "PROCESSBUSINESSUNIT_ID", "CUSTOMER_ID", "DELIVERYDATE", "INVOICEAMOUNTDECIMALS", "PRICEDECIMALS", "CLOSINGDATE", "CUSTOMERCLIENTS", "LAUNDRYSERVICESPARTICIPANT", "DEPARTMENTNUMBER", "DEP_DESC", "ROOMNUMBER", "CLIENTDELIVERYNOTENUMBER", "CLIENTNUMBER", "SEARCHNAME", "CLIENT_NAME", "CLIENT_FIRSTNAME", "CUSTOMER_NAME", "CUSTOMERNUMBER", "CITY", "PROD_CODE", "PROD_DESC", "SIZEDEF_DESC", "FINISH_DESC", "QUANTITY", "AMOUNT", "DURATION", "WEIGHTDECIMALS", "GENERALPRICELISTCODE", "GENERALPRICELISTDESCR", "IL_PRICE", "GWP_PRICE", "GENERALPRICELISTCODE_BILLTO", "GENERALPRICELISTDESCR_BILLTO", "GWP_PRICE_BILLTO", "PRICE", "LINEINVOICEBUSINESSUNIT_ID", "LANGUAGE_CODE", "SIZE_CODE", "FINISHING_CODE", "FMWASHTYPE", "TAXPERCENTAGE", "TAXAMOUNT", "TAXGROUP_CODE", "TAXGROUP_DESC", "BATCHDATE", "CLIENTINVOICEDBASEDON", "TAXRATE") AS 
  select 1 line_type, null labellayout_id
, il.invoiceline_id l_invoiceline_id, ih.invoiceheader_id invoiceheader_id, ih.invoicenumber l_invoicenumber, ih.documenttype l_documenttype
, ilh.invoiceline_id h_invoiceline_id, ihh.invoicenumber h_invoicenumber, ihh.documenttype h_documenttype
, ih.invoicebusinessunit_id ihinvoicebusinessunit_id, cdn.invoicebusinessunit_id cdninvoicebusinessunit_id
, cdn.processbusinessunit_id, cdn.customer_link_id Customer_Id, cdn.deliverydate
, crr.invoiceamountdecimals invoiceamountdecimals, crr.decimals pricedecimals
, cdn.closingdate
, crs.customerclients, cr.laundryservicesparticipant
, v.departmentnumber, v.Dep_desc
, cdn.roomnumber, cdn.clientdeliverynotenumber, cli.clientnumber
, cli.searchname, cli.name Client_name, cli.firstname Client_FirstName
, cus.name Customer_name, cus.customernumber, a.city
, coalesce((select plpc.customcode from productlistpercustomer plpc where plpc.productlistpercustomer_id=F_GETIDCOLUMNFROMACTIVEPLPC(cus.customer_id, p.product_id, s.sizedefinition_id, f.finishingmethod_id, s.sizedefinition_id, cdn.deliverydate, 0)), p.code) Prod_code
, coalesce((select plpc.customdescription from productlistpercustomer plpc where plpc.productlistpercustomer_id=F_GETIDCOLUMNFROMACTIVEPLPC(cus.customer_id, p.product_id, s.sizedefinition_id, f.finishingmethod_id, s.sizedefinition_id, cdn.deliverydate, 0)),(select pd.description from product_desc pd where pd.product_id=p.product_id and pd.language_id = l.language_id)) Prod_Desc
, (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id=s.sizedefinition_id and sdd.language_id = l.language_id) Sizedef_Desc
, (select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id=f.finishingmethod_id and fmd.language_id = l.language_id) Finish_Desc
, case when '1' in (select max(cast(sst.value as varchar2(60))) from systemsetting sst, businessunit bu where sst.plant_id = bu.plant_id and sst.name = 'CLIENTINVOICEDBASEDON' and (bu.businessunit_id = ih.invoicebusinessunit_id OR bu.businessunit_id =cdn.processbusinessunit_id))
  then (cdl.qtyscannedin + cdl.qtycountedin)
  else (cdl.qtyscannedout + cdl.qtycountedout) end Quantity, 0 amount, 0 duration, 0 weightdecimals
, gpl.code generalpricelistcode
, gpl.description generalpricelistdescr
, il.price Il_Price
, nvl((select gwp.price from generalwashprice gwp
   where gwp.generalpricelist_id = gpl.generalpricelist_id
        and gwp.product_id = cdl.product_link_id
         and gwp.sizedefinition_id = cdl.sizedefinition_link_id
          and gwp.finishingmethod_id = cdl.finishingmethod_id
           and gwp.pricetype = 1
           and gwp.startdate <= cdn.deliverydate
        and not exists (select 1
                          from generalwashprice gwp2
                         where gwp2.generalpricelist_id = gwp.generalpricelist_id
                           and gwp2.product_id = gwp.product_id
                           and gwp2.startdate <= cdn.deliverydate
                           and gwp2.startdate > gwp.startdate)), 0) gwp_price
, gpl_billto.code generalpricelistcode_billto
, gpl_billto.description generalpricelistdescr_billto
, nvl((select gwp_billto.price from generalwashprice gwp_billto
   where gwp_billto.generalpricelist_id = gpl_billto.generalpricelist_id
        and gwp_billto.product_id = cdl.product_link_id
         and gwp_billto.sizedefinition_id = cdl.sizedefinition_link_id
          and gwp_billto.finishingmethod_id = cdl.finishingmethod_id
           and gwp_billto.pricetype = 1
           and gwp_billto.startdate <= cdn.deliverydate
        and not exists (select 1
                          from generalwashprice gwp_billto2
                         where gwp_billto2.generalpricelist_id = gwp_billto.generalpricelist_id
                           and gwp_billto2.product_id = gwp_billto.product_id
                           and gwp_billto2.startdate <= cdn.deliverydate
                           and gwp_billto2.startdate > gwp_billto.startdate)), 0) gwp_price_billto
, cdl.price
, cdl.invoicebusinessunit_id LineInvoicebusinessunit_id
, l.code Language_code
, s.code Size_code, f.code Finishing_code, f.washtype FMwashtype
, ctx.TAXPERCENTAGE, ctx.TAXAMOUNT
, txg.code taxgroup_code, txg.description taxgroup_desc
, (select ba.batchdate from batch ba where ba.batch_id = cdn.batch_id) batchdate
, (select max(cast(sst.value as varchar2(60))) from systemsetting sst, businessunit bu where sst.plant_id = bu.plant_id and sst.name = 'CLIENTINVOICEDBASEDON' and (bu.businessunit_id = ih.invoicebusinessunit_id OR bu.businessunit_id =cdn.processbusinessunit_id)) CLIENTINVOICEDBASEDON
, coalesce((select case when cdn.deliverydate < tg.startdatetaxrate then tg.oldtaxrate else tg.taxrate end
      from taxgroup tg where tg.code = il.taxgroupcode and tg.country_id = cus.country_id), ctx.TAXPERCENTAGE, 0) TaxRate
from clientdeliverynoteline cdl
     left outer join invoiceline il
         inner join invoiceheader ih
               inner join Customerresidentialsettings crs_dellto
                  left outer join generalpricelist gpl_billto on crs_dellto.enduserpricelist_id = gpl_billto.generalpricelist_id
               on ih.deltocustomer_link_id = crs_dellto.customer_id
         on ih.invoiceheader_id = il.invoiceheader_id
     on cdl.invoiceline_id = il.invoiceline_id
     inner join clientdeliverynote cdn
           left outer join invoiceline ilh
                inner join invoiceheader ihh on ihh.invoiceheader_id = ilh.invoiceheader_id
           on cdn.invoiceline_id = ilh.invoiceline_id
           left outer join clientdeliverynotetax ctx
                inner join taxgroup txg on ctx.taxgroup_id = txg.taxgroup_id
           ON ctx.CLIENTDELIVERINOTE_ID = cdn.ClientDeliveryNote_ID
           inner join customer cus
                 left outer join Customerresidentialsettings crs
                      left outer join generalpricelist gpl on crs.enduserpricelist_id = gpl.generalpricelist_id
                 on cus.customer_id = crs.customer_id
                 inner join languages l on cus.language_id = l.language_id
                 inner join address a on cus.visitaddress_id = a.address_id
                 inner join currency crr on cus.currency_id = crr.currency_id
           on cdn.customer_link_id = cus.customer_id
           inner join client cli
                 left outer join clientresident cr on cli.client_id = cr.client_id
                 inner join v_ClientDepartment v on cli.client_id = v.client_id
           on cdn.client_link_id = cli.client_id
     on cdl.clientdeliverinote_id = cdn.clientdeliverynote_id
     inner join product p on cdl.product_link_id = p.product_id
     inner join sizedefinition s on cdl.sizedefinition_link_id = s.sizedefinition_id
     inner join finishingmethod f on cdl.finishingmethod_id = f.finishingmethod_id
where cdn.closingdate is not null
union all
select 2 line_type, null labellayout_id
, il.invoiceline_id l_invoiceline_id, ih.invoiceheader_id invoiceheader_id, ih.invoicenumber l_invoicenumber, ih.documenttype l_documenttype
, ilh.invoiceline_id h_invoiceline_id, ihh.invoicenumber h_invoicenumber, ihh.documenttype h_documenttype
, ih.invoicebusinessunit_id ihinvoicebusinessunit_id, cdn.invoicebusinessunit_id cdninvoicebusinessunit_id
, cdn.processbusinessunit_id, cdn.customer_link_id Customer_Id, cdn.deliverydate
, crr.invoiceamountdecimals invoiceamountdecimals, crr.decimals pricedecimals
, cdn.closingdate
, crs.customerclients, cr.laundryservicesparticipant
, v.departmentnumber, v.Dep_desc
, cdn.roomnumber, cdn.clientdeliverynotenumber, cli.clientnumber
, cli.searchname, cli.name Client_name, cli.firstname Client_FirstName
, cus.name Customer_name, cus.customernumber, a.city
, sc.code Prod_code
, (select scd.description from specialcharge_desc scd where sc.specialcharge_id = scd.specialcharge_id and scd.language_id = l.language_id) Prod_Desc
, '1' Sizedef_Desc
, '11' Finish_desc
, cdc.quantity, 0 amount, 0 duration, 0 weightdecimals
, '' generalpricelistcode
, '' generalpricelistdescr
, il.price Il_Price
, 0 gwp_price
, '' generalpricelistcode_billto
, '' generalpricelistdescr_billto
, 0 gwp_price_billto
, cdc.price
, -2 LineInvoicebusinessunit_id
, l.code Language_code
, '' Size_code, '' Finishing_code,  -1 FMwashtype
, ctx.TAXPERCENTAGE, ctx.TAXAMOUNT
, txg.code taxgroup_code, txg.description taxgroup_desc
, (select ba.batchdate from batch ba where ba.batch_id = cdn.batch_id) batchdate
, (select max(cast(sst.value as varchar2(60))) from systemsetting sst, businessunit bu where sst.plant_id = bu.plant_id and sst.name = 'CLIENTINVOICEDBASEDON' and (bu.businessunit_id = ih.invoicebusinessunit_id OR bu.businessunit_id =cdn.processbusinessunit_id)) CLIENTINVOICEDBASEDON
, coalesce((select case when cdn.deliverydate < tg.startdatetaxrate then tg.oldtaxrate else tg.taxrate end
      from taxgroup tg where tg.code = il.taxgroupcode and tg.country_id = cus.country_id), ctx.TAXPERCENTAGE, 0) TaxRate
from clientdeliverynotespeccharge cdc
     left outer join invoiceline il
         join invoiceheader ih on ih.invoiceheader_id=il.invoiceheader_id
     on cdc.invoiceline_id = il.invoiceline_id
     inner join clientdeliverynote cdn
           left outer join invoiceline ilh
                inner join invoiceheader ihh on ihh.invoiceheader_id = ilh.invoiceheader_id
           on cdn.invoiceline_id = ilh.invoiceline_id
           left outer join clientdeliverynotetax ctx
                inner join taxgroup txg on ctx.taxgroup_id = txg.taxgroup_id
           ON ctx.CLIENTDELIVERINOTE_ID = cdn.ClientDeliveryNote_ID
           inner join customer cus
                 left outer join Customerresidentialsettings crs on cus.customer_id = crs.customer_id
                 inner join languages l on cus.language_id = l.language_id
                 inner join address a on cus.visitaddress_id = a.address_id
                 inner join currency crr on cus.currency_id = crr.currency_id
           on cdn.customer_link_id = cus.customer_id
           inner join client cli
                 left outer join clientresident cr on cli.client_id = cr.client_id
                 inner join v_ClientDepartment v on cli.client_id = v.client_id
           on cdn.client_link_id = cli.client_id
     on cdc.clientdeliverinote_id = cdn.clientdeliverynote_id
     inner join specialcharge sc on cdc.specialcharge_id = sc.specialcharge_id
where cdn.closingdate is not null
union all
select 3 line_type, null labellayout_id
, il.invoiceline_id l_invoiceline_id, ih.invoiceheader_id invoiceheader_id, ih.invoicenumber l_invoicenumber, ih.documenttype l_documenttype
, il.invoiceline_id h_invoiceline_id, ih.invoicenumber h_invoicenumber, ih.documenttype h_documenttype
, ih.invoicebusinessunit_id ihinvoicebusinessunit_id, cdn.invoicebusinessunit_id cdninvoicebusinessunit_id
, cdn.processbusinessunit_id, cdn.customer_link_id Customer_Id, cdn.deliverydate
, crr.invoiceamountdecimals invoiceamountdecimals, crr.decimals pricedecimals
, cdn.closingdate
, crs.customerclients, cr.laundryservicesparticipant
, v.departmentnumber, v.Dep_desc
, cdn.roomnumber, cdn.clientdeliverynotenumber, cli.clientnumber
, cli.searchname, cli.name Client_name, cli.firstname Client_FirstName
, cus.name Customer_name, cus.customernumber, a.city
, wc.code Prod_code
, (select wcd.description from weighingcategory_desc wcd where wcd.weighingcategory_id = wc.weighingcategory_id and wcd.language_id = l.language_id) Prod_Desc
, '1' Sizedef_Desc
, '11' Finish_desc
, cdn.invoiceweight Quantity, 0 amount, 0 duration, cdn.weightdecimals
, '' generalpricelistcode
, '' generalpricelistdescr
, il.price Il_Price
, 0 gwp_price
, '' generalpricelistcode_billto
, '' generalpricelistdescr_billto
, 0 gwp_price_billto
, cdn.weightprice Price
, -3 LineInvoicebusinessunit_id
, l.code Language_code
, '' Size_code, '' Finishing_code,  -1 FMwashtype
, ctx.TAXPERCENTAGE, ctx.TAXAMOUNT
, txg.code taxgroup_code, txg.description taxgroup_desc
, (select ba.batchdate from batch ba where ba.batch_id = cdn.batch_id) batchdate
, (select max(cast(sst.value as varchar2(60))) from systemsetting sst, businessunit bu where sst.plant_id = bu.plant_id and sst.name = 'CLIENTINVOICEDBASEDON' and (bu.businessunit_id = ih.invoicebusinessunit_id OR bu.businessunit_id =cdn.processbusinessunit_id)) CLIENTINVOICEDBASEDON
, coalesce((select case when cdn.deliverydate < tg.startdatetaxrate then tg.oldtaxrate else tg.taxrate end
      from taxgroup tg where tg.code = il.taxgroupcode and tg.country_id = cus.country_id), ctx.TAXPERCENTAGE, 0) TaxRate
from clientdeliverynote cdn
     left outer join invoiceline il
          inner join invoiceheader ih on ih.invoiceheader_id = il.invoiceheader_id
     on cdn.invoiceline_id = il.invoiceline_id
     left outer join clientdeliverynotetax ctx
          inner join taxgroup txg on ctx.taxgroup_id = txg.taxgroup_id
     ON cdn.ClientDeliveryNote_ID = ctx.CLIENTDELIVERINOTE_ID
     inner join customer cus
           left outer join Customerresidentialsettings crs on cus.customer_id=crs.customer_id
           inner join languages l on cus.language_id = l.language_id
           inner join address a on cus.visitaddress_id = a.address_id
           inner join currency crr on cus.currency_id = crr.currency_id
     on cdn.customer_link_id = cus.customer_id
     inner join client cli
           left outer join clientresident cr on cli.client_id = cr.client_id
           inner join v_ClientDepartment v on cli.client_id = v.client_id
     on cdn.client_link_id = cli.client_id
     inner join weighingcategory wc on cdn.weighingcategory_link_id = wc.weighingcategory_id
where cdn.closingdate is not null
union all
select 4 line_type, ll.labellayout_id
, il.invoiceline_id l_invoiceline_id,ih.invoiceheader_id invoiceheader_id,ih.invoicenumber l_invoicenumber, ih.documenttype l_documenttype
, ilh.invoiceline_id h_invoiceline_id, ihh.invoicenumber h_invoicenumber, ihh.documenttype h_documenttype
, ih.invoicebusinessunit_id ihinvoicebusinessunit_id, cdn.invoicebusinessunit_id cdninvoicebusinessunit_id
, cdn.processbusinessunit_id, cdn.customer_link_id Customer_Id, cdn.deliverydate
, crr.invoiceamountdecimals, crr.decimals pricedecimals
, cdn.closingdate
, crs.customerclients, cr.laundryservicesparticipant
, v.departmentnumber, v.Dep_desc
, cdn.roomnumber, cdn.clientdeliverynotenumber, cli.clientnumber
, cli.searchname, cli.name Client_name, cli.firstname Client_FirstName
, cus.name Customer_name, cus.customernumber, a.city
, ll.code Prod_code
, (select ilstd.description
 from invoicelinesubtype_desc ilstd, invoicelinesubtype ilst
 where ilstd.invoicelinesubtype_id = ilst.invoicelinesubtype_id
       and ilst.invoicelinetype_id = il.invoicelinetype_id
       and ilst.subtype = il.invoicelinesubtype
       and ilstd.language_id = l.language_id) Prod_Desc
, pqr.preprinted Sizedef_Desc
, 'N' Finish_desc
, count(1) quantity, 0 amount, 0 duration, 0 weightdecimals
, '' generalpricelistcode
, '' generalpricelistdescr
, il.price Il_Price
, 0 gwp_price
, '' generalpricelistcode_billto
, '' generalpricelistdescr_billto
, 0 gwp_price_billto
, pqr.price
, pqr.invoicebusinessunit_id LineInvoicebusinessunit_id
, l.code Language_code
, '' Size_code, '' Finishing_code, -1 FMwashtype
, ctx.TAXPERCENTAGE, ctx.TAXAMOUNT
, txg.code taxgroup_code, txg.description taxgroup_desc
, (select ba.batchdate from batch ba where ba.batch_id = cdn.batch_id) batchdate
, (select max(cast(sst.value as varchar2(60))) from systemsetting sst, businessunit bu where sst.plant_id = bu.plant_id and sst.name = 'CLIENTINVOICEDBASEDON' and (bu.businessunit_id = ih.invoicebusinessunit_id OR bu.businessunit_id =cdn.processbusinessunit_id)) CLIENTINVOICEDBASEDON
, coalesce((select case when cdn.deliverydate < tg.startdatetaxrate then tg.oldtaxrate else tg.taxrate end
      from taxgroup tg where tg.code = il.taxgroupcode and tg.country_id = cus.country_id), ctx.TAXPERCENTAGE, 0) TaxRate
from printqueueresidentialitem pqr
     left outer join invoiceline il
          inner join invoiceheader ih on ih.invoiceheader_id = il.invoiceheader_id
     on pqr.invoiceline_id = il.invoiceline_id
     inner join clientdeliverynote cdn
           left outer join invoiceline ilh
                inner join invoiceheader ihh on ihh.invoiceheader_id = ilh.invoiceheader_id
           on cdn.invoiceline_id = ilh.invoiceline_id
           left outer join clientdeliverynotetax ctx
                inner join taxgroup txg on ctx.taxgroup_id = txg.taxgroup_id
           ON cdn.ClientDeliveryNote_ID = ctx.CLIENTDELIVERINOTE_ID
           inner join customer cus
                 left outer join Customerresidentialsettings crs on cus.customer_id = crs.customer_id
                 inner join languages l on cus.language_id = l.language_id
                 inner join address a on cus.visitaddress_id = a.address_id
                 inner join currency crr on cus.currency_id = crr.currency_id
           on cdn.customer_link_id = cus.customer_id
           inner join client cli
                 left outer join clientresident cr on cli.client_id = cr.client_id
                 inner join v_ClientDepartment v on cli.client_id = v.client_id
           on cdn.client_link_id = cli.client_id
     on pqr.clientdeliverynote_id = cdn.clientdeliverynote_id
     inner join labellayout ll on pqr.labellayout_id = ll.labellayout_id
where cdn.closingdate is not null
      and not (pqr.invoiceline_id is null and pqr.patchinginvoiceline_id is not null)-- this case is selected in next branch
group by ll.labellayout_id, il.invoiceline_id, pqr.chargeable, pqr.preprinted
        , ih.invoiceheader_id , ih.invoicenumber, ih.invoicebusinessunit_id
        , cdn.processbusinessunit_id, cdn.customer_link_id, cdn.deliverydate
        , cdn.closingdate, v.departmentnumber, v.Dep_desc
        , cdn.roomnumber, cdn.clientdeliverynotenumber, cli.clientnumber
        , cli.searchname, cli.name, cli.firstname
        , cus.name, cus.customernumber, a.city
        , ll.code, il.invoicelinetype_id, il.invoicelinesubtype, il.price, pqr.price, cdn.invoicebusinessunit_id, l.code
        , ih.documenttype, ilh.invoiceline_id, ihh.invoicenumber, ihh.documenttype
        , crr.invoiceamountdecimals, crr.decimals, crs.customerclients, cr.laundryservicesparticipant
        , pqr.invoicebusinessunit_id, ctx.TAXPERCENTAGE, ctx.TAXAMOUNT, txg.code, txg.description, cdn.batch_id
        , l.language_id, cus.country_id, il.taxgroupcode
union all
select 4 line_type, ll.labellayout_id
, il.invoiceline_id l_invoiceline_id,ih.invoiceheader_id invoiceheader_id,ih.invoicenumber l_invoicenumber, ih.documenttype l_documenttype
, ilh.invoiceline_id h_invoiceline_id, ihh.invoicenumber h_invoicenumber, ihh.documenttype h_documenttype
, ih.invoicebusinessunit_id ihinvoicebusinessunit_id, cdn.invoicebusinessunit_id cdninvoicebusinessunit_id
, cdn.processbusinessunit_id, cdn.customer_link_id Customer_Id, cdn.deliverydate
, crr.invoiceamountdecimals, crr.decimals pricedecimals
, cdn.closingdate
, crs.customerclients, cr.laundryservicesparticipant
, v.departmentnumber, v.Dep_desc
, cdn.roomnumber, cdn.clientdeliverynotenumber, cli.clientnumber
, cli.searchname, cli.name Client_name, cli.firstname Client_FirstName
, cus.name Customer_name, cus.customernumber, a.city
, ll.code Prod_code
, (select ilstd.description
 from invoicelinesubtype_desc ilstd, invoicelinesubtype ilst
 where ilstd.invoicelinesubtype_id = ilst.invoicelinesubtype_id
       and ilst.invoicelinetype_id = il.invoicelinetype_id
       and ilst.subtype = il.invoicelinesubtype
       and ilstd.language_id = l.language_id) Prod_Desc
, pqr.preprinted Sizedef_Desc
, 'Y' Finish_desc
, count(1) quantity, 0 amount, 0 duration, 0 weightdecimals
, '' generalpricelistcode
, '' generalpricelistdescr
, il.price Il_Price
, 0 gwp_price
, '' generalpricelistcode_billto
, '' generalpricelistdescr_billto
, 0 gwp_price_billto
, pqr.patchprice price
, pqr.invoicebusinessunit_id LineInvoicebusinessunit_id
, l.code Language_code
, '' Size_code, '' Finishing_code, -1 FMwashtype
, ctx.TAXPERCENTAGE, ctx.TAXAMOUNT
, txg.code taxgroup_code, txg.description taxgroup_desc
, (select ba.batchdate from batch ba where ba.batch_id = cdn.batch_id) batchdate
, (select max(cast(sst.value as varchar2(60))) from systemsetting sst, businessunit bu where sst.plant_id = bu.plant_id and sst.name = 'CLIENTINVOICEDBASEDON' and (bu.businessunit_id = ih.invoicebusinessunit_id OR bu.businessunit_id =cdn.processbusinessunit_id)) CLIENTINVOICEDBASEDON
, coalesce((select case when cdn.deliverydate < tg.startdatetaxrate then tg.oldtaxrate else tg.taxrate end
      from taxgroup tg where tg.code = il.taxgroupcode and tg.country_id = cus.country_id), ctx.TAXPERCENTAGE, 0) TaxRate
from printqueueresidentialitem pqr
     inner join invoiceline il
          inner join invoiceheader ih on ih.invoiceheader_id = il.invoiceheader_id
     on pqr.patchinginvoiceline_id = il.invoiceline_id
     inner join clientdeliverynote cdn
           left outer join invoiceline ilh
                inner join invoiceheader ihh on ihh.invoiceheader_id = ilh.invoiceheader_id
           on cdn.invoiceline_id = ilh.invoiceline_id
           left outer join clientdeliverynotetax ctx
                inner join taxgroup txg on ctx.taxgroup_id = txg.taxgroup_id
           ON cdn.ClientDeliveryNote_ID = ctx.CLIENTDELIVERINOTE_ID
           inner join customer cus
                 left outer join Customerresidentialsettings crs on cus.customer_id = crs.customer_id
                 inner join languages l on cus.language_id = l.language_id
                 inner join address a on cus.visitaddress_id = a.address_id
                 inner join currency crr on cus.currency_id = crr.currency_id
           on cdn.customer_link_id = cus.customer_id
           inner join client cli
                 left outer join clientresident cr on cli.client_id = cr.client_id
                 inner join v_ClientDepartment v on cli.client_id = v.client_id
           on cdn.client_link_id = cli.client_id
     on pqr.clientdeliverynote_id = cdn.clientdeliverynote_id
     inner join labellayout ll on pqr.labellayout_id = ll.labellayout_id
where cdn.closingdate is not null
group by ll.labellayout_id, il.invoiceline_id, pqr.chargeable, pqr.preprinted
        , ih.invoiceheader_id , ih.invoicenumber, ih.invoicebusinessunit_id
        , cdn.processbusinessunit_id, cdn.customer_link_id, cdn.deliverydate
        , cdn.closingdate, v.departmentnumber, v.Dep_desc
        , cdn.roomnumber, cdn.clientdeliverynotenumber, cli.clientnumber
        , cli.searchname, cli.name, cli.firstname
        , cus.name, cus.customernumber, a.city
        , ll.code, il.invoicelinetype_id, il.invoicelinesubtype, il.price, pqr.patchprice, cdn.invoicebusinessunit_id, l.code
        , ih.documenttype, ilh.invoiceline_id, ihh.invoicenumber, ihh.documenttype
        , crr.invoiceamountdecimals, crr.decimals, crs.customerclients, cr.laundryservicesparticipant
        , pqr.invoicebusinessunit_id, ctx.TAXPERCENTAGE, ctx.TAXAMOUNT, txg.code, txg.description, cdn.batch_id
        , l.language_id, cus.country_id, il.taxgroupcode
union all
select 5 line_type, null labellayout_id, il.invoiceline_id l_invoiceline_id, ih.invoiceheader_id
, ih.invoicenumber l_invoicenumber, ih.documenttype l_documenttype, null h_invoiceline_id
, ih.invoicenumber h_invoicenumber, ih.documenttype h_documenttype
, ih.invoicebusinessunit_id ihinvoicebusinessunit_id, cdn.invoicebusinessunit_id cdninvoicebusinessunit_id
, cdn.processbusinessunit_id, cdn.customer_link_id Customer_Id, cdn.deliverydate
, (select crr.invoiceamountdecimals from currency crr where crr.currency_id = c.currency_id ) invoiceamountdecimals
, (select crr.decimals from currency crr where crr.currency_id = c.currency_id ) pricedecimals
, cdn.closingdate, 0 customerclients, cr.laundryservicesparticipant
, v.departmentnumber, v.Dep_desc
, cdn.roomnumber, cdn.clientdeliverynotenumber, cll.clientnumber
, cli.searchname, cll.name Client_name, coalesce(cli.firstname, ' ') Client_FirstName
, c.name customer_name, c.customernumber, '' city
, rt.code Prod_code
, (select rtd.description from repairtype_desc rtd where rtd.repairtype_id = rt.repairtype_id and rtd.language_id = lan.language_id) Prod_Desc
, '' Sizedef_Desc
, '' Finish_desc
, sum(rr.quantity) quantity, sum(rr.amount) amount, sum(rr.duration) duration
, 0 weightdecimals
, '' generalpricelistcode
, '' generalpricelistdescr
, (SUM(rr.amount)/SUM(rr.quantity)) Il_Price
, 0 gwp_price
, '' generalpricelistcode_billto
, '' generalpricelistdescr_billto
, 0 gwp_price_billto
, 0 price
, null LineInvoicebusinessunit_id
, lan.code Language_code
, '' Size_code, '' Finishing_code, -1 FMwashtype
, ctx.TAXPERCENTAGE, ctx.TAXAMOUNT
, txg.code taxgroup_code, txg.description taxgroup_desc
, (select ba.batchdate from batch ba where ba.batch_id = cdn.batch_id) batchdate
, (select max(cast(sst.value as varchar2(60))) from systemsetting sst, businessunit bu where sst.plant_id = bu.plant_id and sst.name = 'CLIENTINVOICEDBASEDON' and (bu.businessunit_id = ih.invoicebusinessunit_id OR bu.businessunit_id =cdn.processbusinessunit_id)) CLIENTINVOICEDBASEDON
, 0 taxrate
from residentialrepair rr
     join clientdeliverynote cdn on cdn.clientdeliverynote_id = rr.clientdeliverynote_id
          left outer join invoiceheader ih
               inner join invoiceline il on il.invoiceheader_id = ih.invoiceheader_id and il.invoicelinesubtype = 10
          on ih.invoiceheader_id = rr.invoiceheader_id
          left outer join clientdeliverynotetax ctx
                inner join taxgroup txg on ctx.taxgroup_id = txg.taxgroup_id
           ON cdn.ClientDeliveryNote_ID = ctx.CLIENTDELIVERINOTE_ID
     inner join client_link cll
                 left outer join client cli on cll.client_id = cli.client_id
                 left outer join clientresident cr on cll.client_id = cr.client_id
                 left outer join v_ClientDepartment v on cll.client_id = v.client_id
           on cdn.client_link_id = cll.client_link_id
     join repairtype rt on rt.repairtype_id = rr.repairtype_id
     join customer c on c.customer_id = cdn.customer_link_id
     join languages lan on lan.language_id = c.language_id
where rt.repairusage <> 1
group by  ih.invoiceheader_id, il.invoiceline_id, ih.parentinvoiceheader_id, ih.invoicenumber, ih.documenttype
, ih.startdate, ih.startmonth, ih.startyear, ih.enddate, ih.endmonth, ih.endyear, ih.invoiceyear, ih.invoiceweek, ih.invoicedate
, ih.nextperiodstartdate, ih.nextperiodenddate, ih.invoicebusinessunit_id, cdn.invoicebusinessunit_id
, cdn.processbusinessunit_id, cdn.customer_link_id, cdn.deliverydate, c.currency_id, cdn.closingdate, cr.laundryservicesparticipant, v.departmentnumber, v.Dep_desc
, cdn.roomnumber, cdn.clientdeliverynotenumber, cll.clientnumber, cr.laundryservicesparticipant, v.departmentnumber, v.Dep_desc
, cdn.roomnumber, cdn.clientdeliverynotenumber, cll.clientnumber, cli.searchname, cll.name, cli.firstname
, c.name, c.customernumber, lan.code, lan.language_id, ctx.TAXPERCENTAGE, ctx.TAXAMOUNT
, txg.code, txg.description, cdn.batch_id, c.printtaxonappendix, cll.client_id, ih.status_id
, cdn.clientdeliverynote_id, rr.status, rt.code, rt.repairtype_id, lan.language_id
/

  CREATE OR REPLACE VIEW "V_DECREASEINVANALYSIS_S1" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DATEACTIVE", "TOTALCIRCINV", "CNTCIRCINV", "CIRCINVWEEK", "ADDITION", "DELETIONS", "PRC", "AVGCIRCINV", "CHNG", "REPORTPARAM_ID") AS 
  select v.customernumber, v.customername, v.dateactive,
  v.totalcircinv, v.cntcircinv, v.circinvweek, v.addition, v.deletions,
  (case when v.totalcircinv <> 0 then 100*v.cntcircinv*(v.addition-v.deletions)/v.totalcircinv
  else 0 end) prc,
  (CASE WHEN v.cntcircinv <> 0 then v.totalcircinv/v.cntcircinv
  else 0 end) avgcircinv,
  (v.addition - v.deletions) CHNG,
  v.reportparam_id
from v_decreaseinvanalysis_1 v
/

  CREATE OR REPLACE VIEW "V_DECREASEINVANALYSIS_S2" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DATEACTIVE", "TOTALCIRCINV", "CNTCIRCINV", "CIRCINVWEEK", "ADDITION", "DELETIONS", "PRC", "AVGCIRCINV", "CHNG", "REPORTPARAM_ID") AS 
  select v.customernumber, v.customername, v.dateactive,
  v.totalcircinv, v.cntcircinv, v.circinvweek, v.addition, v.deletions,
  (case when v.totalcircinv <> 0 then 100*v.cntcircinv*(v.addition-v.deletions)/v.totalcircinv
  else 0 end) prc,
  (CASE WHEN v.cntcircinv <> 0 then v.totalcircinv/v.cntcircinv
  else 0 end) avgcircinv,
  (v.addition - v.deletions) chng,
  v.reportparam_id
from v_decreaseinvanalysis_2 v
/

  CREATE OR REPLACE VIEW "V_DECREASEINVANALYSIS_S3" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DATEACTIVE", "TOTALCIRCINV", "CNTCIRCINV", "CIRCINVWEEK", "ADDITION", "DELETIONS", "PRC", "AVGCIRCINV", "CHNG", "REPORTPARAM_ID") AS 
  select v.customernumber, v.customername, v.dateactive,
  v.totalcircinv, v.cntcircinv, v.circinvweek, v.addition, v.deletions,
  (case when v.totalcircinv <> 0 then 100*v.cntcircinv*(v.addition-v.deletions)/v.totalcircinv
  else 0 end) prc,
  (CASE WHEN v.cntcircinv <> 0 then v.totalcircinv/v.cntcircinv
  else 0 end) avgcircinv,
  (v.addition - v.deletions) chng,
  v.reportparam_id
from v_decreaseinvanalysis_3 v
/

  CREATE OR REPLACE VIEW "V_DECREASEINVANALYSIS_S4" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DATEACTIVE", "TOTALCIRCINV", "CNTCIRCINV", "CIRCINVWEEK", "ADDITION", "DELETIONS", "PRC", "AVGCIRCINV", "CHNG", "REPORTPARAM_ID") AS 
  select v.customernumber, v.customername, v.dateactive,
  v.totalcircinv, v.cntcircinv, v.circinvweek, v.addition, v.deletions,
  (case when v.totalcircinv <> 0 then 100*v.cntcircinv*(v.addition-v.deletions)/v.totalcircinv
  else 0 end) prc,
  (CASE WHEN v.cntcircinv <> 0 then v.totalcircinv/v.cntcircinv
  else 0 end) avgcircinv,
  (v.addition - v.deletions) chng,
  v.reportparam_id
from v_decreaseinvanalysis_4 v
/

  CREATE OR REPLACE VIEW "V_DECREASEINVANALYSIS_S5" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DATEACTIVE", "TOTALCIRCINV", "CNTCIRCINV", "CIRCINVWEEK", "ADDITION", "DELETIONS", "PRC", "AVGCIRCINV", "CHNG", "REPORTPARAM_ID") AS 
  select v.customernumber, v.customername, v.dateactive,
  v.totalcircinv, v.cntcircinv, v.circinvweek, v.addition, v.deletions,
  (case when v.totalcircinv <> 0 then 100*v.cntcircinv*(v.addition-v.deletions)/v.totalcircinv
  else 0 end) prc,
  (CASE WHEN v.cntcircinv <> 0 then v.totalcircinv/v.cntcircinv
  else 0 end) avgcircinv,
  (v.addition - v.deletions) chng,
  v.reportparam_id
from v_decreaseinvanalysis_5 v
/

  CREATE OR REPLACE VIEW "V_DELINQUENCYLETTER" ("DELINQUENCY_GROUP", "DELINQUENTAMOUNT", "LASTSTATEMENTAMOUNT", "UNNAPLIEDCREDIT", "CUSTOMERNUMBER", "CUSTOMERNAME", "SENDSTATEMENT", "CUSTOMER_ID", "CONTACTPERSONNAME", "CCONTACTPERSONNUMBER", "STREET", "STREET2", "HOUSENUMBER", "CITY", "STATE", "ZIPCODE", "CURRENTDATE", "STARTDATE", "ENDDATE", "INVOICEAMOUNTDECIMALS", "REPORTPARAM_ID", "COLLECTIONRESPONSIBLE", "PLANTCODE", "PLANTNAME", "PLANTPHONE", "PLANTFAX", "PLANTEMAIL", "PLANTWEBSITE", "PLANTLOGO", "PLANTSTREET", "PLANTSTREET2", "PLANTHOUSENUMBER", "PLANTCITY", "PLANTSTATE", "PLANTZIPCODE") AS 
  SELECT RP.NUMBER_VALUE2 DELINQUENCY_GROUP,
  COALESCE(RP.NUMBER_VALUE6, 0) + COALESCE(RP.NUMBER_VALUE7, 0) + COALESCE(RP.NUMBER_VALUE8, 0) + COALESCE(RP.NUMBER_VALUE9, 0) DELINQUENTAMOUNT,
  CASE WHEN CBI.SENDSTATEMENT IN (1, 2)
    THEN COALESCE((SELECT SUM(IH.PREBILLAMOUNT) FROM V_DELINQUENCYLETTER_IH DIH, INVOICEHEADER IH
                    WHERE DIH.INVOICEDATE = IH.INVOICEDATE
                      AND DIH.CUSTOMER_ID = IH.BILLTOCUSTOMER_LINK_ID
                      AND IH.BILLTOCUSTOMER_LINK_ID = CU.CUSTOMER_ID),0)
  ELSE 0 END LASTSTATEMENTAMOUNT,
  COALESCE((SELECT SUM(AR.AMOUNT - AR.TOTALAPPLIEDAMOUNT) FROM ARTRANSACTION AR, ARTRANSACTIONTYPE ART
    WHERE AR.BILLTOCUSTOMER_LINK_ID = CU.CUSTOMER_ID
      AND AR.DEBITCREDIT = 'C'--      AND AR.CLOSINGTRANSACTION_ID IS NULL
      AND AR.ISOPEN_YN = 'Y' AND AR.ARTRANSACTIONTYPE_ID = ART.ARTRANSACTIONTYPE_ID AND ART.TYPENUMBER <> 2),0) UNNAPLIEDCREDIT,
  CU.CUSTOMERNUMBER, CU.NAME CUSTOMERNAME, CBI.SENDSTATEMENT, CU.CUSTOMER_ID,
  CP.NAME CONTACTPERSONNAME,
  CP.CONTACTPERSONNUMBER CCONTACTPERSONNUMBER,
  CAD.STREET, CAD.STREET2, CAD.HOUSENUMBER,
  CAD.CITY, CAD.STATE, CAD.ZIPCODE,
  TRUNC(SYSDATE) CURRENTDATE,
  RP.DATE_VALUE1 STARTDATE, RP.DATE_VALUE2 ENDDATE,
  CR.INVOICEAMOUNTDECIMALS,
  RP.REPORTPARAM_ID,
 (SELECT E.NAME FROM EMPLOYEE E WHERE E.EMPLOYEE_ID = CBI.COLLECTIONRESPONSIBLE_ID) COLLECTIONRESPONSIBLE,
  P.CODE PLANTCODE, P.NAME PLANTNAME, P.PHONENO PLANTPHONE, P.FAXNO PLANTFAX,
  P.EMAIL PLANTEMAIL, P.WEBSITE PLANTWEBSITE, P.LOGO PLANTLOGO,
  PAD.STREET PLANTSTREET, PAD.STREET2 PLANTSTREET2, PAD.HOUSENUMBER PLANTHOUSENUMBER,
  PAD.CITY PLANTCITY, PAD.STATE PLANTSTATE, PAD.ZIPCODE PLANTZIPCODE
FROM REPORTPARAM RP
     INNER JOIN CUSTOMER CU
           LEFT OUTER JOIN CONTACTPERSON CP ON CU.CUSTOMER_ID = CP.CUSTOMER_ID AND CP.INVOICECONTACTPERSON = 'Y'
           INNER JOIN CUSTOMERBILLINGINFO CBI ON CU.CUSTOMER_ID = CBI.CUSTOMER_ID
           INNER JOIN CURRENCY CR ON CU.CURRENCY_ID = CR.CURRENCY_ID
           INNER JOIN ADDRESS CAD ON CU.INVOICEADDRESS_ID = CAD.ADDRESS_ID
     ON RP.NUMBER_VALUE = CU.CUSTOMER_ID
     INNER JOIN PLANT P
           INNER JOIN ADDRESS PAD ON P.ADDRESS_ID = PAD.ADDRESS_ID
     ON RP.NUMBER_VALUE3 = P.PLANT_ID
/

  CREATE OR REPLACE VIEW "V_DELIVERYDETAILSNETID_GROUPED" ("CUSTOMER_ID", "DEPARTMENTNUMBER", "DISTRIBUTIONPOINTNUMBER", "BUSINESSUNIT_ID", "DELIVERYDATE", "STAY_DESC", "LANGUAGE_CODE", "TOTAL") AS 
  select v.customer_id, v.departmentnumber, v.distributionpointnumber,v.businessunit_id, v.deliverydate, v.stay_desc, v.Language_code, count(*) Total
from v_deliverydetailsnetid v
group by v.customer_id, v.departmentnumber, v.distributionpointnumber,
         v.businessunit_id, v.deliverydate,
         v.stay_desc, v.Language_code
/

  CREATE OR REPLACE VIEW "V_DEPARTMENT" ("CUSTOMERNUMBER", "NAME", "DEPARTMENTNUMBER", "DESCRIPTION", "COSTCENTERCODE", "COSTCENTERDESCRIPTION", "OCCUPANCY", "STANDARDPACKAMOUNT", "ACTIVE", "CONTACTPERSONNUMBER", "CONTACTPERSONNAME", "DELNOTETOEMAIL", "DELIVERY_MO", "DELIVERY_TU", "DELIVERY_WE", "DELIVERY_TH", "DELIVERY_FR", "DELIVERY_SA", "DELIVERY_SU", "LEGACYDEPARTMENTCODE", "USERNAME", "TIMESTAMP") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION,
COSTCENTER.CODE COSTCENTERCODE, COSTCENTER.DESCRIPTION COSTCENTERDESCRIPTION, DEPARTMENT.OCCUPANCY, DEPARTMENT.STANDARDPACKAMOUNT,
 DEPARTMENT.ACTIVE, CONTACTPERSON.CONTACTPERSONNUMBER,
CONTACTPERSON.NAME CONTACTPERSONNAME,
DEPARTMENT.DELNOTETOEMAIL,
F_DELIVERYDAY(V_DELIVERYDAY_F.DELIVERY_MO) DELIVERY_MO,
F_DELIVERYDAY(V_DELIVERYDAY_F.DELIVERY_TU) DELIVERY_TU,
F_DELIVERYDAY(V_DELIVERYDAY_F.DELIVERY_WE) DELIVERY_WE,
F_DELIVERYDAY(V_DELIVERYDAY_F.DELIVERY_TH) DELIVERY_TH,
F_DELIVERYDAY(V_DELIVERYDAY_F.DELIVERY_FR) DELIVERY_FR,
F_DELIVERYDAY(V_DELIVERYDAY_F.DELIVERY_SA) DELIVERY_SA,
F_DELIVERYDAY(V_DELIVERYDAY_F.DELIVERY_SU) DELIVERY_SU,
DEPARTMENT.LEGACYDEPARTMENTCODE, SYSTEMUSER.USERNAME, DEPARTMENT.TIMESTAMP
	FROM
DEPARTMENT
  left outer join CONTACTPERSON on DEPARTMENT.CONTACTPERSON_ID = CONTACTPERSON.CONTACTPERSON_ID
, CUSTOMER, COSTCENTER, SYSTEMUSER, V_DELIVERYDAY_F
	WHERE DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
and
DEPARTMENT.COSTCENTER_ID = COSTCENTER.COSTCENTER_ID
and
DEPARTMENT.SYSTEMUSER_ID = SYSTEMUSER.SYSTEMUSER_ID
and
DEPARTMENT.DEPARTMENT_ID = V_DELIVERYDAY_F.DEPARTMENT_ID
/

  CREATE OR REPLACE VIEW "V_DETAILCOSTSPERPATIENT_BC" ("CUSTOMERNUMBER", "COSTCENTERCODE", "YEAR", "WEEK", "REPORTPARAM_ID", "INVOICED_AMOUNT", "PATIENTS") AS 
  select cs.customernumber, cc.code costcentercode,
  cri.year, cri.week, rp.reportparam_id,
  /*sum(
  cri.quantity * coalesce(il.price, 0) * coalesce((select max(ilp.pricefactor) from invoicelineproduct ilp where ilp.invoiceline_id=il.invoiceline_id), 1) +
    (case when coalesce(il.price, 0) = 0 then cri.amount else 0 end)
    +
  coalesce(((cri.quantity * coalesce(il.price, 0) * coalesce((select max(ilp.pricefactor) from invoicelineproduct ilp where ilp.invoiceline_id=il.invoiceline_id), 1)) +
    (case when coalesce(il.price, 0) = 0 then cri.amount else 0 end))*
    (select tg.taxrate from taxgroup tg
      where il.taxgroupcode = tg.code
        and tg.country_id = cs.country_id)/100, 0)
        )*/sum(cri.amount) invoiced_amount
, (select max(v.patients) from v_detailcostsperpatient_pd v where v.customer_id = cs.customer_id and v.costcenter_id = cc.costcenter_id
and v.reportparam_id = rp.reportparam_id and v.year = cri.year and v.week = cri.week) patients
from invoiceheader ih, invoiceline il, costreportinfo cri, costcenter cc,
  customer cs,  status st, reportparam rp
where ih.invoiceheader_id = il.invoiceheader_id
  and il.invoiceline_id = cri.invoiceline_id
  and cri.costcenter_link_id = cc.costcenter_id
  and cs.customer_id = ih.deltocustomer_link_id
  and ih.status_id = st.status_id
  and st.code = '2'
  and cc.code >= rp.string_value1
  and cc.code <= rp.string_value2
  and cri.year >= rp.number_value
  and cri.year <= rp.number_value3
  and cri.week >= rp.number_value1
  and cri.week <= rp.number_value2
  group by rp.reportparam_id, cs.customer_id, cc.costcenter_id, cs.customernumber, cc.code,
  cri.year, cri.week
/

  CREATE OR REPLACE VIEW "V_DETAILCOSTSPERPATIENT_BC_QF" ("CUSTOMERNUMBER", "COSTCENTERCODE", "YEAR", "WEEK", "REPORTPARAM_ID", "INVOICED_AMOUNT", "PATIENTS") AS 
  select cs.customernumber, cc.code costcentercode,
  cri.year, cri.week, 0 reportparam_id,
  sum(cri.amount) invoiced_amount
, (select max(v.patients) from v_detailcostsperpatient_pd_qf v where v.customer_id = cs.customer_id and v.costcenter_id = cc.costcenter_id
and v.reportparam_id = 0 and v.year = cri.year and v.week = cri.week) patients
from invoiceheader ih, invoiceline il, costreportinfo cri, costcenter cc,
  customer cs,  status st--, reportparam rp
where ih.invoiceheader_id = il.invoiceheader_id
  and il.invoiceline_id = cri.invoiceline_id
  and cri.costcenter_link_id = cc.costcenter_id
  and cs.customer_id = ih.deltocustomer_link_id
  and ih.status_id = st.status_id
  and st.code = '2'
--  and cc.code >= rp.string_value1
--  and cc.code <= rp.string_value2
  and cri.year >= year(sysdate)-2
  and cri.year <= year(sysdate)
--  and cri.week >= rp.number_value1
--  and cri.week <= rp.number_value2
  group by --rp.reportparam_id,
  cs.customer_id, cc.costcenter_id, cs.customernumber, cc.code, cri.year, cri.week
/

  CREATE OR REPLACE VIEW "V_DETAILCOSTSPERPATIENT_LG" ("REPORTPARAM_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "YEAR", "WEEK", "INVOICED_AMOUNT", "PATIENTS") AS 
  select s.reportparam_id, s.customer_id, s.customernumber, s.year, s.week,
       sum(s.invoiced_amount) invoiced_amount, sum(coalesce(p.patients, 0)) patients
from v_detailcostsperpatient_sum s
        left outer join v_detailcostsperpatient_pd p
        on s.costcenter_id = p.costcenter_id and s.customer_id = p.customer_id and s.reportparam_id = p.reportparam_id
           and s.week = p.week and s.year = p.year
group by s.reportparam_id, s.customer_id, s.customernumber, s.year, s.week
/

  CREATE OR REPLACE VIEW "V_DETAILCOSTSPERPATIENT_LG_QF" ("REPORTPARAM_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "YEAR", "WEEK", "INVOICED_AMOUNT", "PATIENTS") AS 
  select s.reportparam_id, s.customer_id, s.customernumber, s.year, s.week,
       sum(s.invoiced_amount) invoiced_amount, sum(coalesce(p.patients, 0)) patients
from v_detailcostsperpatient_sum_qf s
        left outer join v_detailcostsperpatient_pd_qf p
        on s.costcenter_id = p.costcenter_id and s.customer_id = p.customer_id and s.reportparam_id = p.reportparam_id
           and s.week = p.week and s.year = p.year
group by s.reportparam_id, s.customer_id, s.customernumber, s.year, s.week
/

  CREATE OR REPLACE VIEW "V_DEVIATEDCIRCINV_SUM" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "WEARERNUMBER", "WEARERNAME", "WEARERDATEINACTIVE", "WEARERINVENTORYDATEINACTIVE", "SEQUENCENUMBER", "FUNCTIONCODE", "ACTIVE", "DATEACTIVE", "DATEINACTIVE", "PRODUCTCODE", "SIZECODE", "PRODUCTDESC", "SIZEDESC", "DEFAULTBUSINESSUNIT_ID", "PROCESSBUSINESSUNIT_ID", "INTERNALPROCESSINGBU_ID", "MAXINVENTORY", "CIRCINVENTORY", "LANGUAGECODE", "QTYTOBERETURNED", "OUTSTANDINGQTY", "TOOLESSMUCH") AS 
  select /*version 1.0*/
       d.customernumber, d.customername, d.city, d.departmentnumber, d.departmentdesc,
       d.wearernumber, d.wearername, d.wearerdateinactive, d.wearerinventorydateinactive,
       d.sequencenumber, d.functioncode, d.active, d.dateactive, d.dateinactive, d.productcode,
       d.sizecode, d.productdesc, d.sizedesc, d.defaultbusinessunit_id, d.processbusinessunit_id,
       d.internalprocessingbu_id, d.maxinventory, d.circinventory, d.languagecode,
       coalesce(d.qtytobereturned + d.qtytobereturnedreplacement + d.qtytobereturneddecreasemax, 0) qtytobereturned,
       coalesce((dx.outstandingqty), 0) outstandingqty,
       (coalesce(d.maxinventory, 0) + coalesce(d.qtytobereturned, 0) +
        d.qtytobereturnedreplacement + d.qtytobereturneddecreasemax -
        coalesce(d.circinventory, 0) - coalesce(dx.outstandingqty, 0)
       ) toolessmuch
  from v_deviatedcircinv d
       left join v_deviatedcircinv_aux dx on d.weareremployment_id = dx.weareremployment_link_id
                                         and d.product_id = dx.product_link_id
                                         and d.sizedefinition_id = dx.sizedefinition_link_id
/

  CREATE OR REPLACE VIEW "V_EMBLEMPICKLIST" ("SUPPLIERNUMBER", "SUPPLIERNAME", "SUPPLIERSTREET", "SUPPLIERZIP", "SUPPLIERCITY", "SUPPLIERPHONE", "SUPPLIERFAX", "BUSINESSUNITCODE", "BUSINESSUNITDESC", "PLANTSTREET", "PLANTZIP", "PLANTCITY", "PLANTPHONE", "PLANTFAX", "PLANTCODE", "STOCKROOMCODE", "STOCKROOMDESC", "ROUTENUMBER", "DAYNUMBER", "DAYDESC", "NAMEONLABEL", "WORKORDERNUMBER", "REQUESTDATE", "CUSTOMERNUMBER", "CUSTOMERSEARCHNAME", "CUSTOMERNAME", "WEARERNUMBER", "WEARERNAME", "ROWCODE", "LOCATIONCODE", "EMBLEMNR", "EMBLEMDESCRIPTION", "EMBLEMTYPE", "SIZESHAPE", "FABRIC", "EMBLEM_FONT", "BACKGROUND", "TEXT", "BORDER", "QUANTITYREQUESTED", "LANGUAGECODE", "EMBLEMTEMPLATELINE_DESC") AS 
  select /*version 2.0*/
       sup.suppliernumber, sup.name suppliername, addresssuplier.street supplierstreet,
       addresssuplier.zipcode supplierzip, addresssuplier.city suppliercity,
       sup.phone supplierphone, sup.fax supplierfax,
       nvl(v_sk.businessunitcode, v_sk2.businessunitcode) businessunitcode,
       nvl(v_sk.businessunitdesc, v_sk2.businessunitdesc) businessunitdesc,
       nvl(v_sk.plantstreet, v_sk2.plantstreet) plantstreet,
       nvl(v_sk.plantzip, v_sk2.plantzip) plantzip,
       nvl(v_sk.plantcity, v_sk2.plantcity) plantcity,
       nvl(v_sk.plantphone, v_sk2.plantphone) plantphone,
       nvl(v_sk.plantfax, v_sk2.plantfax) plantfax,
       nvl(v_sk.plantcode, v_sk2.plantcode) plantcode,
       nvl(v_sk.stockroomcode, v_sk2.stockroomcode) stockroomcode,
       nvl(v_sk.stockroomdesc, v_sk2.stockroomdesc) stockroomdesc, route.routenumber, day.daynumber,
       (select dd.description from day_desc dd where dd.day_id = day.day_id
               and dd.language_id = l.language_id) daydesc,
       w.emblemname nameonlabel, wo.workordernumber, wo.neededdate requestdate,
       nvl(cuwe.customernumber, cudep.customernumber) customernumber,
       nvl(cuwe.searchname, cudep.searchname) customersearchname,
       nvl(cuwe.name, cudep.name) customername, w.wearernumber, w.fullname wearername,
       v_sk.rowcode, v_sk.locationcode, nvl(p.code, empt.code) emblemnr,
       coalesce((select prd.description from product_desc prd where  prd.product_id = p.product_id
                        and prd.language_id = l.language_id),
                 empl.description,
                 (txtcol.code || ' ' || fab2.code)) emblemdescription,
       empl.emblemtype, s.code sizeshape, nvl(fab.code, fab2.code) fabric,
       nvl(ef2.description, ef.description) emblem_font,
       nvl(prodcol.code, bkgcol.code) background, nvl(text.code, txtcol.code) text,
       nvl(border.code, bordercol.code) border, woem.qtyrequested quantityrequested,
       l.code languagecode, empl.description emblemtemplateline_desc
 from workorderlineemblem woem
      left join emblemtemplateline empl
                join emblemtemplate empt on empl.emblemtemplate_id = empt.emblemtemplate_id
                join sizedefinition s on empl.sizedefinition_id = s.sizedefinition_id
                join fabric fab2 on empl.fabric_id = fab2.fabric_id
                left join emblemfont ef on empl.emblemfont_id = ef.emblemfont_id
                left join color bkgcol on empl.bkgcolor_id = bkgcol.color_id
                left join color bordercol on empl.bordercolor_id = bordercol.color_id
                left join color txtcol on empl.textcolor_id = txtcol.color_id
      on woem.emblemtemplateline_id = empl.emblemtemplateline_id
      join workorderline wol
           join workorder wo
                left join route
                          join day on route.drivingday_id = day.day_id
                on wo.route_id = route.route_id
                left join distributionpoint dp
                          join department dep
                               join customer cudep on dep.customer_id = cudep.customer_id
                          on dp.department_id = dep.department_id
                on wo.distributionpoint_link_id = dp.distributionpoint_id
                left join weareremployment we
                          join wearer w
                               join customer cuwe on w.customer_id = cuwe.customer_id
                          on we.wearer_id = w.wearer_id
                on wo.weareremployment_link_id = we.weareremployment_id
                left join v_emblempicklist_stock_userdef v_sk2 on wo.processingstockroom_id = v_sk2.stockroom_id
            on wol.workorder_id = wo.workorder_id
      on woem.workorderline_id = wol.workorderline_id
      left join product p
                join fabric fab on p.fabric_id = fab.fabric_id
                join color prodcol on p.color_id = prodcol.color_id
                join supplier sup
                     join address addresssuplier on sup.address_id = addresssuplier.address_id
                on p.supplier_id = sup.supplier_id
                join emblemproduct emp
                     left join color text on emp.textcolor_id = text.color_id
                     left join color border on emp.bordercolor_id = border.color_id
                     left join emblemfont ef2 on emp.emblemfont_id = ef2.emblemfont_id
                on p.product_id = emp.product_id
      on nvl(woem.product_id, empl.product_id) = p.product_id
      left join v_emblempicklist_stock v_sk on (v_sk.product_id = p.product_id and v_sk.sizedefinition_id = empl.sizedefinition_id)
      cross join languages l
/

  CREATE OR REPLACE VIEW "V_GARMENTINSURANCERAGGED_AUX" ("BU_CODE", "BILLTONR", "DELTONR", "REPORTPARAM_ID", "SYSTEMUSER_ID", "LANGUAGE_CODE", "PERCENTAGECUST") AS 
  select v.bu_code, v.BillToNr, v.DelToNr, v.reportparam_id, v.SystemUser_ID, v.Language_Code,
       case when sum(v.maxinventory) = 0 then 0
         else case when r.string_value1 = 'true' and r.string_value2 = 'true' and r.string_value3 = 'true'
                   then sum(v.LostItems + v.DamagedItems + v.RepairedItems) / sum(v.maxinventory) * 100--1
                   when r.string_value1 = 'true' and r.string_value2 = 'true' and r.string_value3 <> 'true'
                   then sum(v.LostItems + v.DamagedItems) / sum(v.maxinventory) * 100--2
                   when r.string_value1 <> 'true' and r.string_value2 = 'true' and r.string_value3 = 'true'
                   then sum(v.DamagedItems + v.RepairedItems) / sum(v.maxinventory) * 100--3
                   when r.string_value1 = 'true' and r.string_value2 <> 'true' and r.string_value3 = 'true'
                   then sum(v.LostItems + v.RepairedItems) / sum(v.maxinventory) * 100--4
                   when r.string_value1 <> 'true' and r.string_value2 = 'true' and r.string_value3 <> 'true'
                   then sum(v.DamagedItems) / sum(v.maxinventory) * 100--5
                   when r.string_value1 = 'true' and r.string_value2 <> 'true' and r.string_value3 <> 'true'
                   then sum(v.LostItems) / sum(v.maxinventory) * 100 --6
                   when r.string_value1 <> 'true' and r.string_value2 <> 'true' and r.string_value3 = 'true'
                   then sum(v.RepairedItems) / sum(v.maxinventory) * 100 --7
            else 0 end end PercentageCust
from V_GARMENTINSURANCERAGGED v, reportparam r
where v.reportparam_id = r.reportparam_id
group by v.bu_code, v.BillToNr, v.DelToNr, v.reportparam_id, v.SystemUser_ID, v.Language_Code, r.string_value1, r.string_value2, r.string_value3
/

  CREATE OR REPLACE VIEW "V_INVOICEAPPENDIXCONSIGNOTE" ("INVOICEHEADER_ID", "CONSIGNMENTNOTENUMBER", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "DELTOSTREET", "DELTOZIPCODE", "DELTOCITY", "INVOICENUMBER", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "INVOICEDATE", "STARTMONTH", "STARTYEAR", "CONSIGNMENTNOTE_ID", "DELIVERYDATE", "TOTALAMOUNTEXCLUDINGVAT", "TOTALAMOUNTEXCLVAT", "PAYTHISAMOUNT", "CURRENCY", "PAYMENTTERMSDESCRIPTION", "DISCOUNTDAYS", "PAYMENTDISCOUNT", "CREDITSQUEEZEAMOUNT", "DISCOUNTDAYS2", "PAYMENTDISCOUNT2", "CREDITSQUEEZEPERC", "TAX") AS 
  select distinct ih.invoiceheader_id, cn.consignmentnotenumber, ih.deltocustomernumber, ih.deltocustomername
       , ih.deltostreet, ih.deltozipcode, ih.deltocity, ih.invoicenumber, ih.billtocustomernumber
       , ih.billtocustomername, ih.invoicedate, ih.startmonth, ih.startyear, cn.consignmentnote_id
       , cn.deliverydate, pn.totalamountexcludingvat, ih.totalamountexclvat, ih.paythisamount
       , (select crr.code from currency crr where ih.currency_id = crr.currency_id) Currency
       , ihei.paymenttermsdescription, ihei.discountdays, ihei.paymentdiscount, ih.creditsqueezeamount
       , ihei.discountdays2, ihei.paymentdiscount2, ih.creditsqueezeperc
, coalesce((select sum(v.amount) from v_invoiceappendixcntax v where v.invoiceheader_id = ih.invoiceheader_id), 0) Tax
from invoiceheader ih, invoiceheaderextrainfo ihei, consignmentnote cn
     , packingnote pn, packingnoteline pnl
where pnl.invoiceheader_id = ih.invoiceheader_id and pn.consignmentnote_id = cn.consignmentnote_id
      and ihei.invoiceheader_id = ih.invoiceheader_id and pnl.packingnote_id = pn.packingnote_id
/

  CREATE OR REPLACE VIEW "V_INVOICELINETYPECHARGE" ("INVOICELINETYPE", "INVOICELINETYPEDESC", "SPECIALCHARGECODE", "SPECIALCHARGEDESCRIPTION", "TIMESTAMP", "SYSTEMUSER_ID", "LANGUAGECODE") AS 
  select b.type invoicelinetype, b.invoicelinetype_desc invoicelinetypedesc,
c.code specialchargecode,
( select description from specialcharge_desc x where  x.specialcharge_id = a.specialcharge_id and x.language_id = languages.language_id) specialchargedescription,
a.timestamp, a.systemuser_id, languages.code languagecode
from invoicelinetypecharge a, V_invoicelinetype b, specialcharge c, languages
where a.invoicelinetype_id = b.invoicelinetype_id
and a.specialcharge_id = c.specialcharge_id
and b.languagecode = languages.code
/

  CREATE OR REPLACE VIEW "V_INVOICELINETYPETAX" ("INVOICELINETYPE", "INVOICELINETYPEDESC", "COUNTRYCODE", "COUNTRYDESCRIPTION", "TAXGROUPCODE", "TAXGROUPDESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  select b.type invoicelinetype, b.invoicelinetype_desc invoicelinetypedesc, c.code countrycode, c.description countrydescription,
d.code taxgroupcode, d.description taxgroupdescription, A.SYSTEMUSER_ID, a.timestamp, LANGUAGES.CODE LANGUAGECODE
from invoicelinetypetax a
LEFT OUTER JOIN taxgroup d ON(a.taxgroup_id = d.taxgroup_id),
 V_invoicelinetype b, country c, LANGUAGES
where a.invoicelinetype_id = b.invoicelinetype_id
and a.country_id = c.country_id
AND B.LANGUAGECODE = LANGUAGES.CODE
/

  CREATE OR REPLACE VIEW "V_KONTOCOSTS" ("INVOICEHEADER_ID", "INVOICENUMBER", "ENDMONTH", "ENDYEAR", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "SPLITUPCODE", "SPLITUPDESCRIPTION", "KONTO_NR", "AMOUNT") AS 
  select
  k.invoiceheader_id, k.invoicenumber,  k.endmonth,  k.endyear
, k.deltocustomernumber, k.deltocustomername, k.splitupcode, k.splitupdescription
, k.konto_nr konto_nr, sum(k.amount) amount
from v_KontoCosts_aux k
WHERE K.endmonth BETWEEN 1 AND 12
group by
  k.invoiceheader_id, k.invoicenumber,  k.endmonth,  k.endyear
, k.deltocustomernumber, k.deltocustomername, k.splitupcode, k.splitupdescription
, k.konto_nr
/

  CREATE OR REPLACE VIEW "V_LOSTBUSINESS" ("ROUTENUMBER", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "PAYMENTMETHOD", "DATEACTIVE", "DATEINACTIVE", "PHONENO", "CITY", "SEARCHNAME_CUST", "SEARCHNAME", "COMPETITORCODE", "LOSTREASONCODE", "LOSTREASONDESC", "LASTAMOUNT", "AVGAMOUNT", "BUSINESSUNITCODE", "DIVISIONCODE", "REGIONCODE", "MARKETSEGMENTCODE", "SALESAREACODE", "CHAINCODE", "DEPOTCODE", "NO_OF_PRODUCTS", "LANGUAGECODE", "REPORTPARAM_ID", "ROUTESTOPDATEINACTIVE") AS 
  select /*version 1.1*/
       distinct (case when rp.number_value2 = 0 then 1 else r.routenumber end) routenumber,
       cu.customer_id, cu.customernumber, cu.name customername, cu.paymentmethod,
       cu.dateactive, cu.dateinactive, cu.phoneno, ad.city, cu.searchname searchname_cust,
       coalesce(em.searchname, em1.searchname, plpcend.searchname) searchname,
       coalesce(co.code, co1.code, plpcend.comcode) competitorcode,
       coalesce(gr.code, gr1.code, plpcend.lostreasoncode) lostreasoncode,
       (select grd.description from gainlostreason_desc grd
         where grd.gainlostreason_id = coalesce(gr.gainlostreason_id, gr1.gainlostreason_id, plpcend.gainlostreason_id)
           and grd.language_id = l.language_id)  lostreasondesc,
       f_getinvoiceamount(cu.customer_id, 1) lastamount,
       f_getinvoiceamount(cu.customer_id, 0) avgamount, buc.code businessunitcode,
       di.code divisioncode, re.code regioncode, ms.code marketsegmentcode,
       sa.code salesareacode, ch.code chaincode, dp.code depotcode,
       (select count(1)
          from v_lostbusiness_prodnr v
         where v.reportparam_id = rp.reportparam_id
           and v.customer_id = cu.customer_id) no_of_products,
       l.code languagecode, rp.reportparam_id, rs.dateinactive routestopdateinactive
  from customer cu
       left join chain ch on cu.chain_id = ch.chain_id
       left join routestop rs
            join route r
                 left join depot dp on r.depot_id = dp.depot_id
            on rs.route_id = r.route_id
       on cu.customer_id = rs.customer_id
       left join contractspercustomer cpc
                 left join gainlostreason gr on cpc.lostreason_id = gr.gainlostreason_id
                 left join competitor co on cpc.lostcompetitor_id = co.competitor_id
                 left join employee em on cpc.salesemployee_id = em.employee_id
       on cu.customer_id = cpc.customer_id
       left join contractcustomer coc
                 left join contract con
                           left join gainlostreason gr1 on con.lostreason_id = gr1.gainlostreason_id
                           left join competitor co1 on con.lostcompetitor_id = co1.competitor_id
                           left join employee em1 on con.salesemployee_id = em1.employee_id
                 on coc.contract_id = con.contract_id
       on cu.customer_id = coc.customer_link_id
       left join (select plpc.customer_id, max(em2.searchname) searchname, max(co2.code) comcode,
                         max(gr2.code) lostreasoncode, max(gr2.gainlostreason_id) gainlostreason_id
                    from productlistpercustomer plpc
                         left join gainlostreason gr2 on plpc.lostreason_id = gr2.gainlostreason_id
                         left join competitor co2 on plpc.lostcompetitor_id = co2.competitor_id
                         left join employee em2 on plpc.salesemployee_id = em2.employee_id
                   group by plpc.customer_id) plpcend
       on cu.customer_id = plpcend.customer_id
       join marketsegment ms on cu.marketsegment_id = ms.marketsegment_id
       join salesarea sa on cu.salesarea_id = sa.salesarea_id
       join address ad on cu.visitaddress_id = ad.address_id
       join businessunit buc
            join division di on buc.division_id = di.division_id
            join region re on buc.region_id = re.region_id
       on cu.defaultbusinessunit_id = buc.businessunit_id
       cross join languages l
       cross join reportparam rp
 where (co.code is null or (co.code between rp.string_value5 and rp.string_value6) or rp.string_value5 is null)
   and (gr.code is null or (gr.code between rp.string_value7 and rp.string_value8) or rp.string_value7 is null)
   and (co1.code is null or (co1.code between rp.string_value5 and rp.string_value6) or rp.string_value5 is null)
   and (gr1.code is null or (gr1.code between rp.string_value7 and rp.string_value8) or rp.string_value7 is null)
   and (plpcend.comcode is null or (plpcend.comcode between rp.string_value5 and rp.string_value6) or rp.string_value5 is null)
   and (plpcend.lostreasoncode is null or (plpcend.lostreasoncode between rp.string_value7 and rp.string_value8) or rp.string_value7 is null)
   and nvl(cpc.dateactive, cu.dateactive) = nvl((select max(cpc2.dateactive) from contractspercustomer cpc2 where cpc2.customer_id = cu.customer_id), cu.dateactive)
   and nvl(coc.startdate, cu.dateactive) = nvl((select max(coc2.startdate) from contractcustomer coc2 where coc2.customer_link_id = cu.customer_id), cu.dateactive)
   and exists
       (select ca.customer_id
          from customeractivities ca
               join activity ac on ca.activity_id = ac.activity_id
               join businessunit bu
                    join businessunitsperusergroup bug on bu.businessunit_id = bug.businessunit_id
               on ca.invoicebusinessunit_id = bu.businessunit_id
         where cu.customer_id = ca.customer_id
           and bug.usergroup_id = rp.number_value1
           and ac.code between rp.string_value1 and rp.string_value2
           and bu.code between rp.string_value3 and rp.string_value4)
/

  CREATE OR REPLACE VIEW "V_MISSINGINVOICES" ("LINETYPE", "BUSINESSUNITID", "BUSINESSUNITCODE", "BUSINESSUNITDESC", "CLUSTERCODE", "CLUSTERID", "CLUSTERDESC", "INVOICEFREQUENCYNUMBER", "INVOICEFREQUENCYID", "INVOICEFREQUENCYDESC", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "CITY", "INVOICENUMBER", "INVOICEDATE", "STARTDATE", "ENDDATE", "ACTIVITYCODE", "ACTIVITYDESC", "PROCESSBUCODE", "PROCESSBUDESC", "CUTOFFDATE", "PLANTCODE", "CUSTOMERDATEACTIVE", "CUSTOMERDATEINACTIVE", "LANGUAGECODE", "MAX_INVDATE") AS 
  select 1 linetype,
  Ibu.Businessunit_Id BusinessunitID, Ibu.code businessunitCode, Ibu.description businessunitDesc
, cucl.code ClusterCode, cucl.cluster_id ClusterID, cucl.description ClusterDesc
, ifq.invoicefrequencynumber, ifq.invoicefrequency_id invoicefrequencyID
, (select invoicefrequency_desc.description from invoicefrequency_desc where invoicefrequency_desc.invoicefrequency_id = ifq.invoicefrequency_id
and invoicefrequency_desc.language_id = languages.language_id) invoicefrequencyDesc
, cu.customernumber deltocustomernumber, cu.name deltocustomername
, address.city
, coalesce(ih.invoicenumber, -1) invoicenumber , ih.invoicedate
, ih.startdate, ih.enddate, activity.code activityCode
, (select activity_desc.description from activity_desc where activity.activity_id = activity_desc.activity_id
and activity_desc.language_id = languages.language_id) activityDesc
, Pbu.Code processbuCode, Pbu.Description processbuDesc
, cua.cutoffdate, plant.code PlantCode, cu.dateactive CustomerDateActive, cu.dateinactive CustomerDateInactive
, languages.code languageCode
, coalesce(VMAX.max_invdate, to_date('01/01/1900','dd/mm/yyyy')) max_invdate
from
customer cu
  left outer join
       ( invoiceheader ih join status
                           on ih.status_id = status.status_id
                               and status.statustype = 'IN' -- Settled (US) / Final Invoice (EU)
                                 and status.code <> '3' )
       on ih.deltocustomer_link_id = cu.customer_id
          and ih.documenttype = 1  -- invoice
          and ih.invoicetype = 1   -- generated
, invoicefrequency ifq, customeractivities cua , activity, businessunit Pbu, businessunit Ibu
, plant, address, languages
, customerspercluster cpc, customercluster cucl
, V_MAXINVOICEDATE VMAX
where
    cu.active = 'Y' and
    cu.invoicefrequency_id = ifq.invoicefrequency_id
    and ifq.invoicefrequencynumber <> 0 -- 0:DirectInvoice
and cu.customer_id = cua.customer_id
    and cua.activity_id = activity.activity_id
    and cua.processbusinessunit_id = Pbu.Businessunit_Id
    and cua.invoicebusinessunit_id = Ibu.businessunit_id
        and Ibu.Plant_Id = plant.plant_id
            and plant.language_id = languages.language_id
and coalesce(cu.invoiceaddress_id, (select customer.invoiceaddress_id
                                    from customer
                                    where customer.customer_id = cu.debtor_id ))
            = address.address_id
and cpc.customer_id = cu.customer_id and cpc.cluster_id = cucl.cluster_id
AND VMAX.deltocustomernumber = CU.CUSTOMERNUMBER
AND (VMAX.max_invdate = IH.INVOICEDATE or VMAX.max_invdate is null)
union all
select 2 linetype,
  Ibu.Businessunit_Id BusinessunitID, Ibu.code businessunitCode, Ibu.description businessunitDesc
--, cucl.code ClusterCode, cucl.cluster_id ClusterID, cucl.description ClusterDesc
, '' ClusterCode, -1 ClusterID, '' ClusterDesc
, ifq.invoicefrequencynumber, ifq.invoicefrequency_id invoicefrequencyID
, (select invoicefrequency_desc.description from invoicefrequency_desc where invoicefrequency_desc.invoicefrequency_id = ifq.invoicefrequency_id
and invoicefrequency_desc.language_id = languages.language_id) invoicefrequencyDesc
, cu.customernumber deltocustomernumber, cu.name deltocustomername
, address.city
, coalesce(ih.invoicenumber, -1) invoicenumber , ih.invoicedate
, ih.startdate, ih.enddate, activity.code activityCode
, (select activity_desc.description from activity_desc where activity.activity_id = activity_desc.activity_id
and activity_desc.language_id = languages.language_id) activityDesc
, Pbu.Code processbuCode, Pbu.Description processbuDesc
, cua.cutoffdate, plant.code PlantCode, cu.dateactive CustomerDateActive, cu.dateinactive CustomerDateInactive
, languages.code languageCode
, coalesce(VMAX.max_invdate, to_date('01/01/1900','dd/mm/yyyy')) max_invdate
from
customer cu
  left outer join
       ( invoiceheader ih join status
                           on ih.status_id = status.status_id
                               and status.statustype = 'IN' -- Settled (US) / Final Invoice (EU)
                                 and status.code <> '3' )
       on ih.deltocustomer_link_id = cu.customer_id
          and ih.documenttype = 1  -- invoice
          and ih.invoicetype = 1   -- generated
, invoicefrequency ifq, customeractivities cua , activity, businessunit Pbu, businessunit Ibu
, plant, address, languages
, V_MAXINVOICEDATE VMAX
where
    cu.active = 'Y' and
    cu.invoicefrequency_id = ifq.invoicefrequency_id
    and ifq.invoicefrequencynumber <> 0 -- 0:DirectInvoice
and cu.customer_id = cua.customer_id
    and cua.activity_id = activity.activity_id
    and cua.processbusinessunit_id = Pbu.Businessunit_Id
    and cua.invoicebusinessunit_id = Ibu.businessunit_id
        and Ibu.Plant_Id = plant.plant_id
            and plant.language_id = languages.language_id
and coalesce(cu.invoiceaddress_id, (select customer.invoiceaddress_id
                                    from customer
                                    where customer.customer_id = cu.debtor_id ))
            = address.address_id
AND VMAX.deltocustomernumber = CU.CUSTOMERNUMBER
AND (VMAX.max_invdate = IH.INVOICEDATE or VMAX.max_invdate is null)
/

  CREATE OR REPLACE VIEW "V_MULTIPLECHARGES" ("LINETYPE", "INVOICEHEADER_ID", "CC_CODE", "WEARERNUMBER", "WEARERNAME", "PRODUCTCODE", "PRODUCTDESC", "AMOUNT", "LANGUAGECODE") AS 
  select /*version 3.0*/
       1 linetype, vi.invoiceheader_id, --PrepCharges
       (select coc.code from costcenter coc join distributionpoint dp on dp.costcenter_id = coc.costcenter_id
                                            where dp.distributionpoint_id = vi.distributionpoint_id) cc_code,
       vi.wearernumber, vi.wearername, vi.productcode, vi.productdesc,
       vi.prepcharge amount, vi.languagecode
from v_issuehistorycc vi
union all
select 2 linetype, ve.invoiceheader_id, --Emblems
       (select coc.code from costcenter coc join distributionpoint dp on dp.costcenter_id = coc.costcenter_id
                                            where dp.distributionpoint_id = ve.distributionpoint_id) cc_code,
       ve.wearernumber, ve.wearername, ve.productcode, ve.productdesc,
       ve.amount, ve.languagecode
from v_emblemhistorycc ve
union all
select 3 linetype, vl.invoiceheader_id, --labels
       (select coc.code from costcenter coc join distributionpoint dp on dp.costcenter_id = coc.costcenter_id
                                            where dp.distributionpoint_id = vl.distributionpoint_id) cc_code,
       vl.wearernumber, vl.wearername, vl.productcode, vl.productdesc, vl.amount, vl.languagecode
from v_invoicedgarmentlabels vl
union all
select 4 linetype,  vo.invoiceheader_id, --residual value
       (select coc.code from costcenter coc join distributionpoint dp on dp.costcenter_id = coc.costcenter_id
                                            where dp.distributionpoint_id = vo.distributionpoint_id) cc_code,
       vo.wearernumber, vo.wearername, vo.productcode, vo.productdesc, vo.residualvalue amount, vo.languagecode
from v_outofcirculationhistorycc vo
where vo.chargetype = 1 and vo.status = 0 --chargeable
union all
select 5 linetype,  vo.invoiceheader_id, --restocking fee
       (select coc.code from costcenter coc join distributionpoint dp on dp.costcenter_id = coc.costcenter_id
                                            where dp.distributionpoint_id = vo.distributionpoint_id) cc_code,
       vo.wearernumber, vo.wearername, vo.productcode, vo.productdesc, vo.residualvalue amount, vo.languagecode
from v_outofcirculationhistorycc vo
where vo.chargetype = 2
union all
select 6 linetype, vr.invoiceheader_id, --repairs
       (select coc.code from costcenter coc join distributionpoint dp on dp.costcenter_id = coc.costcenter_id
                                            where dp.distributionpoint_id = vr.distributionpoint_id) cc_code,
       vr.wearernumber, vr.wearername,
       (select plk.code from product_link plk where plk.product_link_id = vr.product_link_id) productcode,
       (select plkd.description from product_link_desc plkd where plkd.product_link_id = vr.product_link_id and plkd.language_id = (select lan.language_id from languages lan where lan.code = vr.languagecode)) productdesc,
       vr.amount, vr.languagecode
from v_repairhistorycc vr
union all
select 7 linetype, vg.invoiceheader_id, --garmentsales
       (select coc.code from costcenter coc join distributionpoint dp on dp.costcenter_id = coc.costcenter_id
                                            where dp.distributionpoint_id = vg.distributionpoint_id) cc_code,
       vg.wearernumber, vg.wearername, vg.productcode, vg.productdesc, vg.amount, vg.languagecode
from v_garmenthistorycc vg
/

  CREATE OR REPLACE VIEW "V_NEWSTOCKVALUATION" ("REPORTPARAM_ID", "BUSINESSUNITCODE", "BUSINESSUNITDESC", "PLANTCODE", "STOCKROOMCODE", "STOCKROOMDESC", "PRODUCTGROUPCODE", "PRODUCTGROUPDESC", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "STOCKQTY", "CUSTOMER_ID", "CUSTOMEROWNED", "PRICE", "LANGUAGECODE") AS 
  select rp.reportparam_id, bu.code businessunitcode, bu.description businessunitdesc,
  (select plt.code from plant plt where plt.plant_id = bu.plant_id) plantcode,
  sr.code stockroomcode, sr.name stockroomdesc,
  (select pg.code from productgroup pg where pg.productgroup_id = p.productgroup_id) productgroupcode,
  (select pgd.description from productgroup_desc pgd join productgroup pg
    on pgd.productgroup_id = pg.productgroup_id where pg.productgroup_id = p.productgroup_id and pgd.language_id = lg.language_id) productgroupdesc,
  p.code productcode,
  (select pd.description from product_desc pd
     where pd.product_id = p.product_id and pd.language_id = lg.language_id) productdesc,
  (select sd.code from sizedefinition sd where sd.sizedefinition_id = sdi.sizedefinition_id) sizecode,
  coalesce(sqq.qtyunique,0) + coalesce(sqq.qtyuniquewithmodifications,0) + coalesce(sqq.qtynonunique, 0) stockqty,
  sdi.customer_id, sdi.customerowned,
  F_STOCKPRICE(rp.number_value, p.product_id, sdi.sizedefinition_id, rp.number_value1, rp.date_value1) price,
  lg.code languagecode
from stockroom sr, stockreservationpergrade srg
    left outer join v_stockuniqueqty sqq on (sqq.stockreservationpergrade_id = srg.stockreservationpergrade_id),
  stockdefinitionperitem sdi, qualitygrade q, product p, businessunit bu, languages lg, reportparam rp
where bu.businessunit_id = sr.managedbybu_id
  and sr.stockroom_id = sdi.stockroom_id
  and srg.stockdefinitionperitem_id = sdi.stockdefinitionperitem_id
  and sdi.product_id = p.product_id
  and srg.qualitygrade_id = q.qualitygrade_id
  and q.newgarment = 'Y'
/

  CREATE OR REPLACE VIEW "V_NORMSTOCKLEVEL" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "COUNTINGSEQUENCE", "AMOUNT_MO", "AMOUNT_TU", "AMOUNT_WE", "AMOUNT_TH", "AMOUNT_FR", "AMOUNT_SA", "AMOUNT_SU", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION,
DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION,
PRODUCT.CODE,
( select description from product_desc x where x.product_id = productlistperdistribpoint.product_id and x.language_id = languages.language_id) PRODUCTDESCRIPTION,
SIZEDEFINITION.CODE,
( select description from SIZEDEFINITION_desc y where y.SIZEDEFINITION_id = productlistperdistribpoint.SIZEDEFINITION_id and y.language_id = languages.language_id) SIZEDEFINITIONDESC,
FINISHINGMETHOD.CODE,
( select description from FINISHINGMETHOD_desc z where z.FINISHINGMETHOD_id = productlistperdistribpoint.FINISHINGMETHOD_id and z.language_id = languages.language_id) FINISHINGMETHODDESC,
PRODUCTLISTPERDISTRIBPOINT.COUNTSEQUENCE,
V_NORMSTOCKAMOUNT.AMOUNT_MO, V_NORMSTOCKAMOUNT.AMOUNT_TU, V_NORMSTOCKAMOUNT.AMOUNT_WE,
V_NORMSTOCKAMOUNT.AMOUNT_TH, V_NORMSTOCKAMOUNT.AMOUNT_FR, V_NORMSTOCKAMOUNT.AMOUNT_SA,
V_NORMSTOCKAMOUNT.AMOUNT_SU, PRODUCTLISTPERDISTRIBPOINT.SYSTEMUSER_ID, PRODUCTLISTPERDISTRIBPOINT.TIMESTAMP, languages.code languagecode
	FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT, PRODUCTLISTPERDISTRIBPOINT,
   PRODUCT, SIZEDEFINITION, FINISHINGMETHOD,V_NORMSTOCKAMOUNT V_NORMSTOCKAMOUNT, languages
	WHERE PRODUCTLISTPERDISTRIBPOINT.DISTRIBUTIONPOINT_ID =  DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
and DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
and DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
and PRODUCTLISTPERDISTRIBPOINT.PRODUCT_ID = PRODUCT.PRODUCT_ID
and PRODUCTLISTPERDISTRIBPOINT.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
and PRODUCTLISTPERDISTRIBPOINT.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
and PRODUCTLISTPERDISTRIBPOINT.PRODUCTLISTPERDISTRIBPOINT_ID = V_NORMSTOCKAMOUNT.PRODUCTLISTPERDISTRIBPOINT_ID
/

  CREATE OR REPLACE VIEW "V_NOTRECEIVEDCUSTOMERORDERS" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CONTACTPERSONNUMBER", "CONTACTPERSONNAME", "PHONE", "EMAIL", "FUNCTIONCODE", "FUNCTIONDESC", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "LASTDELIVERYDATE", "REPORTPARAM_ID", "LANGUAGECODE") AS 
  select /*version 2.0*/
       v.customernumber, v.customername,
       (case when v.contactperson_id is null then cp.contactpersonnumber
        else cpde.contactpersonnumber end) contactpersonnumber,
       (case when v.contactperson_id is null then cp.name
        else cpde.name end) contactpersonname,
       (case when v.contactperson_id is null then cp.phone
        else cpde.phone end) phone,
       (case when v.contactperson_id is null then cp.email
        else cpde.email end) email,
       (case when v.contactperson_id is null then cpf.code
        else cpfde.code end) functioncode,
       (select cpfd.description
          from contactpersonfunction_desc cpfd
         where cpfd.contactpersonfunction_id = cpf.contactpersonfunction_id
           and cpfd.language_id = l.language_id) functiondesc,
       v.departmentnumber, v.departmentdesc, v.distributionpointnumber, v.distributionpointdesc,
       trunc(sysdate) lastdeliverydate, v.reportparam_id, l.code languagecode
from contactperson cp
     join contactpersonfunction cpf on cp.contactpersonfunction_id = cpf.contactpersonfunction_id
     join v_notreceivedcustomerorders_d v on v.customer_id = cp.customer_id
          left join contactperson cpde
               left join contactpersonfunction cpfde on cpde.contactpersonfunction_id = cpfde.contactpersonfunction_id
          on v.contactperson_id = cpde.contactperson_id
     join v_notreceivedcustomerorders_c cu on v.customer_id = cu.customer_id
     join reportparam rp on v.reportparam_id = rp.reportparam_id and cu.reportparam_id = rp.reportparam_id
     , languages l
where f_checkfordelivery(v.productlistperdistribpoint_id, cu.customer_id, v.department_id, rp.date_value1) = 1
  and cu.existsdv = 0
  and cp.contactperson_id = (select cp.contactperson_id
                               from contactperson cp
                              where cp.contactpersonnumber in (select min(cp2.contactpersonnumber) from contactperson cp2 where cp2.customer_id = cp.customer_id)
                                and cp.customer_id = v.customer_id)
/

  CREATE OR REPLACE VIEW "V_NOTSCANNEDITEMS" ("CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "WEARERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "CUSTOMERLANGUAGEID", "BUSINESSUNIT_ID", "PRODUCTGROUPCODE", "PRODUCTGROUPDESC", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESCRIPTION", "PRIMARYID", "LASTSCANDATE", "ISSUEDATE", "STATUSCODE", "STATUSDESCRIPTION", "STAYNUMBER", "STAYDESCRIPTION", "LANGUAGELANGUAGEID", "LANGUAGECODE", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "FLAGCODE", "BANK", "LOCKER", "REPORTPARAM_ID", "RESIDUALVALUE", "CHAIN_CODE", "LINETYPE") AS 
  select vl.customernumber, vl.customerName, vl.wearernumber, vl.wearerName, vl.departmentnumber
, vl.departmentDescription, vl.distributionpointnumber, vl.distributionpointDescription
, vl.customerLanguageID, vl.businessunit_id, vx.productGroupCode, vx.productGroupDesc
, vx.productCode, vx.productDescription, vx.sizedefinitionCode, vx.sizedefinitionDescription, vx.primaryid
, vx.lastscandate, vx.issuedate, vx.statusCode, vx.statusdescription, vx.stayNumber, vx.StayDescription
, vx.languageLanguageID, vx.languageCode
, vo.finishingmethodCode, vo.finishingmethodDescription, vo.flagCode
, vl.bank, vl.locker, vl.reportparam_id, vl.ResidualValue, vl.chain_code, vl.linetype
from v_notscanneditems_line vl
     inner join v_notscanneditems_aux vx
           inner join v_notscanneditems_outer vo on vx.uniqueitem_id = vo.uniqueitem_id and vx.languageLanguageID = vo.languageLanguageID
     on vl.uniqueitem_id = vx.uniqueitem_id
where vl.routefilter = 1
/

  CREATE OR REPLACE VIEW "V_NOTSCANNEDITEMSRV" ("LINETYPE", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "WEARERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "CUSTOMERLANGUAGEID", "BUSINESSUNIT_ID", "BU_CODE", "BU_DESC", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESCRIPTION", "PRIMARYID", "IDCOUNTER", "LASTSCANDATE", "ISSUEDATE", "STATUSCODE", "STATUSDESCRIPTION", "STAYNUMBER", "STAYDESCRIPTION", "LANGUAGELANGUAGEID", "LANGUAGECODE", "WASHESTOTAL", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "RESIDUALVALUE", "RVPERCENTAGE", "CHAIN_CODE", "SIZESEQUENCENR", "BANK", "LOCKER", "REPORTPARAM_ID") AS 
  select /*version 2.0*/
       --showing ID code, detailed layout
       1 linetype, vl.customernumber, vl.customername, vl.wearernumber, vl.wearername,
       vl.departmentnumber, vl.departmentdescription, vl.distributionpointnumber, vl.distributionpointdescription,
       vl.customerlanguageid, vl.businessunit_id, vl.bu_code, vl.bu_desc, pr.code productcode,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdescription, sz.code sizedefinitioncode,
       (select szd.description
          from sizedefinition_desc szd
         where szd.sizedefinition_id = sz.sizedefinition_id
           and szd.language_id = lan.language_id) sizedefinitiondescription,
       uq.primaryid, 1 idcounter, uq.lastscandate, uqfix.lastissuedate issuedate,
       sta.code statuscode,
       (select stad.description
          from status_desc stad
         where stad.status_id = sta.status_id
           and stad.language_id = lan.language_id) statusdescription, sty.staynr staynumber,
       (select styd.description
          from stay_desc styd
         where styd.stay_id = sty.stay_id
           and styd.language_id = lan.language_id) staydescription,
       lan.language_id languagelanguageid, lan.code languagecode, vl.washestotal, fm.code finishingmethodcode,
       (select fmd.description
          from finishingmethod_desc fmd
         where fmd.finishingmethod_id = fm.finishingmethod_id
           and fmd.language_id = lan.language_id) finishingmethoddescription,
       rp.number_value3 residualvalue, rp.number_value5 rvpercentage, vl.chain_code,
       nvl((select ps.sequencenumber
              from productsize ps
             where ps.product_id = pr.product_id
               and ps.sizedefinition_id = sz.sizedefinition_id), sz.sizedefinition_id) sizesequencenr,
       vl.bank, vl.locker, rp.reportparam_id
  from reportparam rp
       join uniqueitem uq
            left join finishingmethod fm on uq.finishingmethod_id = fm.finishingmethod_id
            join uniqueitemfixedinfo uqfix on uq.uniqueitem_id = uqfix.uniqueitem_id
            join product pr on uq.product_id = pr.product_id
            join sizedefinition sz on uq.sizedefinition_id = sz.sizedefinition_id
            join status sta on uq.status_id = sta.status_id and sta.statustype = 'UI'
            join stay sty on uq.stay_id = sty.stay_id
            join v_notscanneditemsrv_line vl on uq.uniqueitem_id = vl.uniqueitem_id
       on rp.number_value = uq.uniqueitem_id,
       languages lan
 where ((rp.string_value1 = ' ' and rp.string_value2 = 'ZZZZZZ')
        or
       (exists (select 1
                  from uniqueitemflag uqf
                       join flag on uqf.flag_id = flag.flag_id
                 where uq.uniqueitem_id = uqf.uniqueitem_id
                   and rp.string_value1 <= flag.code
                   and rp.string_value2 >= flag.code)))
 union all --not show ID code, condensed layout
select 2 linetype, vl.customernumber, vl.customername, vl.wearernumber, vl.wearername,
       vl.departmentnumber, vl.departmentdescription, vl.distributionpointnumber, vl.distributionpointdescription,
       vl.customerlanguageid, vl.businessunit_id, vl.bu_code, vl.bu_desc, pr.code productcode,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdescription, sz.code sizedefinitioncode,
       (select szd.description
          from sizedefinition_desc szd
         where szd.sizedefinition_id = sz.sizedefinition_id
           and szd.language_id = lan.language_id) sizedefinitiondescription,
       '' primaryid, count(uq.primaryid) idcounter, uq.lastscandate, trunc(sysdate) issuedate, sta.code statuscode,
       (select stad.description
          from status_desc stad
         where stad.status_id = sta.status_id
           and stad.language_id = lan.language_id) statusdescription, 1 staynumber,
       ' ' staydescription, lan.language_id languagelanguageid, lan.code languagecode,
       sum(vl.washestotal) washestotal, fm.code finishingmethodcode,
       (select fmd.description
          from finishingmethod_desc fmd
         where fmd.finishingmethod_id = fm.finishingmethod_id
           and fmd.language_id = lan.language_id) finishingmethoddescription,
       sum(rp.number_value3) residualvalue, sum(rp.number_value5) rvpercentage, vl.chain_code,
       nvl((select ps.sequencenumber
              from productsize ps
             where ps.product_id = pr.product_id
               and ps.sizedefinition_id = sz.sizedefinition_id), sz.sizedefinition_id) sizesequencenr,
       vl.bank, vl.locker, rp.reportparam_id
  from reportparam rp
       join uniqueitem uq
            left join finishingmethod fm on uq.finishingmethod_id = fm.finishingmethod_id
            join uniqueitemfixedinfo uqfix on uq.uniqueitem_id = uqfix.uniqueitem_id
            join product pr on uq.product_id = pr.product_id
            join sizedefinition sz on uq.sizedefinition_id = sz.sizedefinition_id
            join status sta on uq.status_id = sta.status_id and sta.statustype = 'UI'
            join v_notscanneditemsrv_line vl on uq.uniqueitem_id = vl.uniqueitem_id
       on rp.number_value = uq.uniqueitem_id,
       languages lan
 where ((rp.string_value1 = ' ' and rp.string_value2 = 'ZZZZZZ')
        or
       (exists (select 1
                  from uniqueitemflag uqf
                       join flag on uqf.flag_id = flag.flag_id
                 where uq.uniqueitem_id = uqf.uniqueitem_id
                   and rp.string_value1 <= flag.code
                   and rp.string_value2 >= flag.code)))
 group by vl.customernumber, vl.customername, vl.wearernumber, vl.wearername, vl.departmentnumber,
          vl.departmentdescription, vl.distributionpointnumber, vl.distributionpointdescription,
          vl.customerlanguageid, vl.businessunit_id, vl.bu_code, vl.bu_desc, pr.code, pr.product_id,
          lan.language_id, sz.code, sz.sizedefinition_id, uq.lastscandate, sta.code, sta.status_id,
          lan.code, fm.code, fm.finishingmethod_id, vl.chain_code, pr.sizetype_id, vl.bank, vl.locker, rp.reportparam_id
/

  CREATE OR REPLACE VIEW "V_NOTSCANNEDITEMS_AUXRV" ("UNIQUEITEM_ID", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESCRIPTION", "PRIMARYID", "LASTSCANDATE", "ISSUEDATE", "STATUSCODE", "STATUSDESCRIPTION", "STAYNUMBER", "STAYDESCRIPTION", "LANGUAGELANGUAGEID", "LANGUAGECODE", "RESIDUALVALUE", "RVPERCENTAGE", "REPORTPARAM_ID", "SIZESEQUENCENR", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "WEARERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "CUSTOMERLANGUAGEID", "BUSINESSUNIT_ID", "BU_CODE", "BU_DESC", "WASHESTOTAL", "BANK", "LOCKER", "CHAIN_CODE") AS 
  select uq.uniqueitem_id, prd.code productCode
, (select product_desc.description from product_desc where product_desc.product_id = prd.product_id
and product_desc.language_id = languages.language_id) productDescription
, sizedef.code sizedefinitionCode
, (select sizedefinition_desc.description from sizedefinition_desc
where sizedefinition_desc.sizedefinition_id = sizedef.sizedefinition_id
and sizedefinition_desc.language_id = languages.language_id) sizedefinitionDescription
, uq.primaryid, uq.lastscandate LastScanDate, uqfix.lastissuedate issuedate
, status.code statusCode
, (select status_desc.description from status_desc where status_desc.status_id = status.status_id
and status_desc.language_id = languages.language_id) statusdescription
, stay.staynr stayNumber
, (select stay_desc.description from stay_desc where stay_desc.stay_id = stay.stay_id
and stay_desc.language_id = languages.language_id ) StayDescription
, languages.language_id languageLanguageID , languages.code languageCode
,rp.number_value3 residualvalue, rp.number_value5 rvpercentage
, rp.reportparam_id
, (select sp.sequencenumber from sizespersizetype sp
          where sp.sizetype_id = prd.sizetype_id and sp.sizedefinition_id = sizedef.sizedefinition_id) SizeSequenceNr,
vl.customernumber,
vl.customerName,
vl.wearernumber,
vl.wearerName,
vl.departmentnumber ,
vl.departmentDescription,
vl.distributionpointnumber,
vl.distributionpointDescription ,
vl.customerLanguageID,
vl.businessunit_id,
vl.BU_code,
vl.BU_desc ,
vl.washestotal ,
vl.bank,
vl.locker,
vl.chain_code
from
  uniqueitem uq
, product prd, uniqueitemfixedinfo uqfix, sizedefinition sizedef, status, stay, languages
, v_notscanneditemsRV_line vl
, reportparam rp
where uq.product_id = prd.product_id
and uq.uniqueitem_id = uqfix.uniqueitem_id
and uq.sizedefinition_id = sizedef.sizedefinition_id
and uq.status_id = status.status_id
and status.statustype = 'UI'
and uq.stay_id = stay.stay_id
and vl.uniqueitem_id    = uq.uniqueitem_id
and uq.uniqueitem_id=rp.number_value
/

  CREATE OR REPLACE VIEW "V_ORDERFORM" ("REPORTPARAM_ID", "COPY_NUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "ADDRESS", "ZIPCODE", "CITY", "DEPARTMENTNUMBER", "DEPARTMENTNAME", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTNUMBERNAME", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESC", "FINISHINGMETHODCODE", "FINISHINGMETHODDESC", "PRODUCTCODE", "PRODUCTDESC", "CUSTOMCODE", "CUSTOMDESCRIPTION", "CUSTOMER_ID", "AMOUNT", "DELIVERIES", "ORDERINGMETHOD", "STREET", "STREET2", "SEQUENCENUMBER", "PACKINGSEQUENCE", "DELIVERYPOINT_ID") AS 
  select A.REPORTPARAM_ID, a.copy_number, a.CUSTOMERNUMBER, a.CUSTOMERNAME, a.ADDRESS, a.ZIPCODE, a.CITY, a.DEPARTMENTNUMBER, a.DEPARTMENTNAME,
  a.DISTRIBUTIONPOINTNUMBER, a.DISTRIBUTIONPOINTNUMBERNAME, a.SIZEDEFINITIONCODE,a.SIZEDEFINITIONDESC,
  a.FINISHINGMETHODCODE, a.FINISHINGMETHODDESC,a.PRODUCTCODE, a.PRODUCTDESC, a.CUSTOMCODE, a.CUSTOMDESCRIPTION,
  a.CUSTOMER_ID, sum(coalesce(a.amount, 0)) amount, sum(coalesce(a.deliveries, 0)) deliveries
, a.orderingmethod, a.STREET, a.STREET2
, a.sequencenumber, a.packingsequence, a.deliverypoint_id
from V_ORDERFORM_AUX a
where a.DepActive='Y' or a.DistribActive='Y'
group by A.REPORTPARAM_ID, a.CUSTOMERNUMBER, a.CUSTOMERNAME, a.ADDRESS, a.ZIPCODE, a.CITY, a.DEPARTMENTNUMBER, a.DEPARTMENTNAME,
  a.DISTRIBUTIONPOINTNUMBER, a.DISTRIBUTIONPOINTNUMBERNAME, a.SIZEDEFINITIONCODE,a.SIZEDEFINITIONDESC,
  a.FINISHINGMETHODCODE, a.FINISHINGMETHODDESC,a.PRODUCTCODE, a.PRODUCTDESC, a.CUSTOMCODE, a.CUSTOMDESCRIPTION,
  a.CUSTOMER_ID
, a.orderingmethod, a.copy_number, a.sequencenumber, a.packingsequence, a.STREET, a.STREET2,a.deliverypoint_id
/

  CREATE OR REPLACE VIEW "V_PBAPERCUSTOMERYEARWEEK" ("CUSTOMERNUMBER", "CUSTOMERNAME", "YEAR", "WEEK", "MERCHANDISEONINV", "PROCESSINGONINVO", "PURCHASINGONINVO", "OTHERCOSTSONINV", "MERCHANDISECOSTS", "PROCESSINGCOSTS", "PURCHASINGCOSTS", "M_INVCOSTS", "M_COSTS", "M_MARGIN", "M_DIFF", "RESIDUALVALUE", "REPORTPARAM_ID", "INVOICEAMOUNTDECIMALS") AS 
  select
  vx.customernumber, vx.customerName, vx.year, vx.week
, ROUND( coalesce(vi.merchandiseOnInvoice, 0), vx.invoiceamountdecimals ) merchandiseOnInv
, ROUND( coalesce(vi.processingOnInvoice, 0), vx.invoiceamountdecimals )  processingOnInvo
, ROUND( coalesce(vi.purchasingOnInvoice, 0), vx.invoiceamountdecimals )  purchasingOnInvo
, ROUND( coalesce(vi.otherCostsOnInvoice, 0), vx.invoiceamountdecimals ) otherCostsOnInv
, ROUND( vx.merchandiseCosts, vx.invoiceamountdecimals ) merchandiseCosts
, ROUND( vx.processingCosts, vx.invoiceamountdecimals ) processingCosts
, ROUND( vx.purchasingCosts, vx.invoiceamountdecimals ) purchasingCosts
, ROUND( coalesce(vi.merchandiseOnInvoice + vi.processingOnInvoice + vi.purchasingOnInvoice + vi.otherCostsOnInvoice, 0)
  , vx.invoiceamountdecimals ) m_InvCosts
, ROUND( vx.merchandiseCosts + vx.processingCosts + vx.purchasingCosts
  , vx.invoiceamountdecimals ) m_Costs
, case when coalesce( vi.merchandiseOnInvoice + vi.processingOnInvoice + vi.purchasingOnInvoice + vi.otherCostsOnInvoice, 0) = 0
       then 0 else
  ROUND( 100*( 1- (vx.merchandiseCosts + vx.processingCosts + vx.purchasingCosts)
  / (vi.merchandiseOnInvoice + vi.processingOnInvoice + vi.purchasingOnInvoice + vi.otherCostsOnInvoice)
  ), vx.invoiceamountdecimals ) end m_Margin
, ROUND( coalesce( vi.merchandiseOnInvoice + vi.processingOnInvoice + vi.purchasingOnInvoice + vi.otherCostsOnInvoice, 0)
  - vx.merchandiseCosts - vx.processingCosts - vx.purchasingCosts, vx.invoiceamountdecimals ) m_Diff
, ROUND( vx.residualvalue ,  0) residualValue
, vx.reportparam_id
, vx.invoiceamountdecimals
from
  v_pbapercustomeryearweek_aux vx
    --left outer
    join v_pbapercustomeryearweek_inv vi
           on vx.customer_id = vi.deltocustomer_link_id
              and vx.reportparam_id = vi.reportparam_id
              and vx.currency_id = vi.currency_id
              and vx.year = vi.ih_year
              and vx.week = vi.ih_week
where
  case when coalesce( vi.merchandiseOnInvoice + vi.processingOnInvoice + vi.purchasingOnInvoice + vi.otherCostsOnInvoice, 0 ) = 0
       then 0 else
  100*( 1- ( vx.merchandiseCosts + vx.processingCosts + vx.purchasingCosts )
  / ( vi.merchandiseOnInvoice + vi.processingOnInvoice + vi.purchasingOnInvoice + vi.otherCostsOnInvoice )
  ) end
  between vx.number_value6 and vx.number_value5
union ---NULL invoice data
select
  vx.customernumber, vx.customerName, vx.year, vx.week
, 0 merchandiseOnInv
, 0 processingOnInvo
, 0 purchasingOnInvo
, 0 otherCostsOnInv
, ROUND( vx.merchandiseCosts, vx.invoiceamountdecimals ) merchandiseCosts
, ROUND( vx.processingCosts, vx.invoiceamountdecimals ) processingCosts
, ROUND( vx.purchasingCosts, vx.invoiceamountdecimals ) purchasingCosts
, 0 m_InvCosts
, ROUND( vx.merchandiseCosts + vx.processingCosts + vx.purchasingCosts
  , vx.invoiceamountdecimals ) m_Costs
, 0 m_Margin
, ROUND( 0  - vx.merchandiseCosts - vx.processingCosts - vx.purchasingCosts, vx.invoiceamountdecimals ) m_Diff
, ROUND( vx.residualvalue ,  0) residualValue
, vx.reportparam_id
, vx.invoiceamountdecimals
from
  v_pbapercustomeryearweek_aux vx
where
  not exists ( select * from v_pbapercustomeryearweek_inv vi
           where vx.customer_id = vi.deltocustomer_link_id
              and vx.reportparam_id = vi.reportparam_id
              and vx.currency_id = vi.currency_id
              and vx.year = vi.ih_year
              and vx.week = vi.ih_week) and
  0  between vx.number_value6 and vx.number_value5
union ---NULL Cost data
select
  vi.deltocustomernumber customernumber, vi.deltocustomername customerName, vi.ih_year year, vi.ih_week week
, ROUND( coalesce(vi.merchandiseOnInvoice, 0), vi.invoiceamountdecimals ) merchandiseOnInv
, ROUND( coalesce(vi.processingOnInvoice, 0), vi.invoiceamountdecimals )  processingOnInvo
, ROUND( coalesce(vi.purchasingOnInvoice, 0), vi.invoiceamountdecimals )  purchasingOnInvo
, ROUND( coalesce(vi.otherCostsOnInvoice, 0), vi.invoiceamountdecimals ) otherCostsOnInv
, 0 merchandiseCosts
, 0 processingCosts
, 0 purchasingCosts
, ROUND( coalesce(vi.merchandiseOnInvoice + vi.processingOnInvoice + vi.purchasingOnInvoice + vi.otherCostsOnInvoice, 0)
  , vi.invoiceamountdecimals ) m_InvCosts
, 0 m_Costs
, case when coalesce( vi.merchandiseOnInvoice + vi.processingOnInvoice + vi.purchasingOnInvoice + vi.otherCostsOnInvoice, 0) = 0
       then 0 else 100
  end m_Margin
, ROUND( coalesce( vi.merchandiseOnInvoice + vi.processingOnInvoice + vi.purchasingOnInvoice + vi.otherCostsOnInvoice, 0)
  , vi.invoiceamountdecimals ) m_Diff
, 0 residualValue
, vi.reportparam_id
, vi.invoiceamountdecimals
from
  v_pbapercustomeryearweek_inv vi, reportparam rp
where
  not exists (select * from v_pbapercustomeryearweek_aux vx
             where vx.customer_id = vi.deltocustomer_link_id
              and vx.reportparam_id = vi.reportparam_id
              and vx.currency_id = vi.currency_id
              and vx.year = vi.ih_year
              and vx.week = vi.ih_week)
  and
  vi.reportparam_id=rp.reportparam_id
  and
  case when coalesce( vi.merchandiseOnInvoice + vi.processingOnInvoice + vi.purchasingOnInvoice + vi.otherCostsOnInvoice, 0 ) = 0
       then 0 else 100 end
  between rp.number_value6 and rp.number_value5
/

  CREATE OR REPLACE VIEW "V_PBAPERCUSTOMERYEARWEEK_SRT" ("CUSTOMERNUMBER", "M_MARGIN_TOTAL", "M_DIFF_TOTAL", "REPORTPARAM_ID") AS 
  select
  vx.customernumber
, case
      when
  sum(
  ROUND( coalesce(vi.merchandiseOnInvoice + vi.processingOnInvoice + vi.purchasingOnInvoice + vi.otherCostsOnInvoice, 0)
  , vx.invoiceamountdecimals )
  ) = 0 then 0
             else
  sum(
  ROUND( coalesce( vi.merchandiseOnInvoice + vi.processingOnInvoice + vi.purchasingOnInvoice + vi.otherCostsOnInvoice, 0)
  - vx.merchandiseCosts - vx.processingCosts - vx.purchasingCosts, vx.invoiceamountdecimals )
  ) * 100 /
  sum(
  ROUND( coalesce(vi.merchandiseOnInvoice + vi.processingOnInvoice + vi.purchasingOnInvoice + vi.otherCostsOnInvoice, 0)
  , vx.invoiceamountdecimals )
  ) end m_Margin_total
, sum(
  ROUND( coalesce( vi.merchandiseOnInvoice + vi.processingOnInvoice + vi.purchasingOnInvoice + vi.otherCostsOnInvoice, 0)
  - vx.merchandiseCosts - vx.processingCosts - vx.purchasingCosts, vx.invoiceamountdecimals )
  ) m_Diff_total
, vx.reportparam_id
from
  v_pbapercustomeryearweek_aux vx
    left outer join v_pbapercustomeryearweek_inv vi
           on vx.customer_id = vi.deltocustomer_link_id
              and vx.reportparam_id = vi.reportparam_id
              and vx.currency_id = vi.currency_id
              and vx.year = vi.ih_year
              and vx.week = vi.ih_week
group by
  vx.customernumber, vx.reportparam_id, vx.number_value5, vx.number_value6, vx.invoiceamountdecimals
having
 case
     when
  sum(
  ROUND( coalesce(vi.merchandiseOnInvoice + vi.processingOnInvoice + vi.purchasingOnInvoice + vi.otherCostsOnInvoice, 0)
  , vx.invoiceamountdecimals )
  ) = 0 then 0
             else
  sum(
  ROUND( coalesce( vi.merchandiseOnInvoice + vi.processingOnInvoice + vi.purchasingOnInvoice + vi.otherCostsOnInvoice, 0)
  - vx.merchandiseCosts - vx.processingCosts - vx.purchasingCosts, vx.invoiceamountdecimals )
  ) * 100 /
  sum(
  ROUND( coalesce(vi.merchandiseOnInvoice + vi.processingOnInvoice + vi.purchasingOnInvoice + vi.otherCostsOnInvoice, 0)
  , vx.invoiceamountdecimals )
  ) end
  between vx.number_value6 and vx.number_value5
/

  CREATE OR REPLACE VIEW "V_PBAPERCUSTOMERYEARWEEK_TOT" ("CUSTOMERNUMBER", "CUSTOMERNAME", "INVOICEAMOUNTDECIMALS", "MERCHANDISECOSTS", "MERCHANDISEONINVOICE", "PROCESSINGCOSTS", "PROCESSINGONINVOICE", "PURCHASINGCOSTS", "PURCHASINGONINVOICE", "OTHERCOSTS", "OTHERCOSTSONINVOICE", "RESIDUALVALUE", "M_COSTS", "M_INVCOSTS", "M_MARGIN_TOTAL", "M_DIFF_TOTAL", "REPORTPARAM_ID") AS 
  select v.customernumber, v.customerName, v.invoiceamountdecimals
, sum(v.merchandiseCosts) merchandiseCosts
, sum(v.merchandiseOnInvoice) merchandiseOnInvoice
, sum(v.processingCosts) processingCosts
, sum(v.processingOnInvoice) processingOnInvoice
, sum(v.purchasingCosts) purchasingCosts
, sum(v.purchasingOnInvoice) purchasingOnInvoice
, sum(v.otherCosts) otherCosts
, sum(v.otherCostsOnInvoice) otherCostsOnInvoice
, sum(v.residualvalue) residualvalue
, sum(v.merchandiseCosts + v.purchasingCosts + v.processingCosts + v.otherCosts) m_Costs
, sum(v.merchandiseOnInvoice + v.processingOnInvoice + v.purchasingOnInvoice + v.otherCostsOnInvoice ) m_InvCosts
, case
 when
  sum(v.merchandiseOnInvoice + v.processingOnInvoice + v.purchasingOnInvoice + v.otherCostsOnInvoice)
 = 0 then 0
  else
  sum( v.merchandiseOnInvoice + v.processingOnInvoice + v.purchasingOnInvoice + v.otherCostsOnInvoice
  - v.merchandiseCosts - v.processingCosts - v.purchasingCosts - v.otherCosts
  ) * 100 /
  sum( v.merchandiseOnInvoice + v.processingOnInvoice + v.purchasingOnInvoice + v.otherCostsOnInvoice
  ) end m_Margin_total
, sum( v.merchandiseOnInvoice + v.processingOnInvoice + v.purchasingOnInvoice + v.otherCostsOnInvoice
  - v.merchandiseCosts - v.processingCosts - v.purchasingCosts - v.otherCosts
  ) m_Diff_total
, v.reportparam_id
from v_pbapercustomeryearweek_det v
group by
v.reportparam_id, v.customernumber, v.customerName, v.number_value5, v.number_value6
, v.invoiceamountdecimals
having
case
 when
  sum(v.merchandiseOnInvoice + v.processingOnInvoice + v.purchasingOnInvoice + v.otherCostsOnInvoice
  ) = 0 then 0
             else
  sum(v.merchandiseOnInvoice + v.processingOnInvoice + v.purchasingOnInvoice + v.otherCostsOnInvoice
  - v.merchandiseCosts - v.processingCosts - v.purchasingCosts - v.otherCosts
  ) * 100 /
  sum(v.merchandiseOnInvoice + v.processingOnInvoice + v.purchasingOnInvoice + v.otherCostsOnInvoice
  ) end
  between v.number_value6 and v.number_value5
/

  CREATE OR REPLACE VIEW "V_PICKORDER" ("WORKORDER_ID", "WORKORDERNUMBER", "ORDERREMARK", "DELIVERYDATE", "PICKORDERDATE", "PICKORDERTIMESTAMP", "CREATIONTIMESTAMP", "SYSTEMUSERFULLNAME", "CUSTOMERNUMBER", "NAME", "LEGALNAME", "WCUSTOMERNUMBER", "WCUSTOMERNAME", "WCUSTOMERLEGALNAME", "WEARERNR", "WEARERNAME", "EMPLNR", "CUPBOARD", "LOCKER", "DEPARTMENT", "DEPARTMENTNUMBER", "CONSPOINT", "ROUTENUMBER", "ROUTEDESCRIPTION", "COUNTWORKORDERLINEEMBLEM", "PLANT_CODE", "PLANT_NAME", "LANGUAGE_CODE", "TOTALROWS", "WOREFERENCENUMBER_ID", "WOREFERENCENR", "WOREFNR_DESC", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZECODE", "FINISHINGMETHODCODE", "QTYORDERED", "QTYCANCELLED", "QTYFULLFILLED", "QTYOPEN", "QTYPICKED", "WOL_REMARK", "WORKORDERLINEID", "INTPROCESSBU_CODE", "INTPROCESSBU_DESC", "PROCESSBU_CODE", "PROCESSBU_DESC", "REASON_CODE", "REASONCODE_DESC", "ROWCODE", "LOCATIONCODE", "PROCESSINGSTOCKROOM_ID", "MODIFICATIONS", "QUALITYGRADE_CODE", "QUALITYGRADE") AS 
  select
  wok.workorder_id, wok.workordernumber
, wok.remark OrderRemark, wok.neededdate DeliveryDate
, to_char(wok.externalprinttimestamp) pickorderdate
, to_char(wok.externalprinttimestamp,'fmhh24fm:MI:ss') pickordertimestamp
, wok.creationtimestamp
, su.fullname systemuserfullname
, cu.customernumber, cu.name, cu.legalname
, null wcustomernumber, '' wcustomername, '' wcustomerlegalname
, w.wearernumber WearerNr
, w.fullname WearerName
, we.sequencenumber EmplNr, lo.bank CupBoard, lo.locker
, department.description Department
, department.departmentnumber
, distributionpoint.description ConsPoint
, route.routenumber, route.description RouteDescription
, coalesce( ( select count(wokem.workorderlineemblem_id) from workorderline wokli, workorderlineemblem wokem
            where wok.workorder_id = wokli.workorder_id and wokli.workorderline_id = wokem.workorderline_id)
            , 0) countWorkorderLineEmblem
, plant.code plant_code, plant.name plant_name
, lan.code Language_code
, (SELECT COUNT(DISTINCT v.workorderline_id) FROM v_workorderline v WHERE v.workorder_id = wok.workorder_id AND v.languagecode = lan.code) TotalRows
, wok.woreferencenumber_id
, worefnr.referencenumber woreferencenr
, worefnr.description worefnr_desc
, (select product_link.code from product_link where wol.product_link_id = product_link.product_link_id) productcode
, (select pd.description from product_link,product_desc pd where wol.product_link_id = product_link.product_link_id and pd.product_id = product_link.product_id and pd.language_id = lan.language_id) productdescription
, (select sizedefinition_link.code from sizedefinition_link where wol.sizedefinition_link_id = sizedefinition_link.sizedefinition_link_id) sizecode
, (select fm.code from finishingmethod fm where wol.finishingmethod_id = fm.finishingmethod_id) finishingmethodcode
, wol.quantityordered qtyordered
, wol.quantitycancelled qtycancelled
, wol.quantityfilled qtyfullfilled
, (wol.quantityordered - wol.quantitycancelled - wol.quantityfilled) qtyopen
, wol.quantitypicked qtypicked
, wol.instructions wol_remark
, wol.workorderline_id workorderlineid
,(select bu.code from businessunit bu where bu.businessunit_id=wok.internalprocessingbu_id) intprocessbu_code
, (select bu.description from businessunit bu where bu.businessunit_id=wok.internalprocessingbu_id) intprocessbu_desc
, (select bup.code from businessunit bup, stockroom sr where wok.processingstockroom_id = sr.stockroom_id
          and bup.businessunit_id = sr.managedbybu_id) processbu_code
, (select bup.description from businessunit bup, stockroom sr where wok.processingstockroom_id = sr.stockroom_id
          and bup.businessunit_id = sr.managedbybu_id) processbu_desc
, (select rc.code from reasoncode rc where rc.reasoncode_id = wok.reasoncode_id) reason_code
, (select rcd.description from reasoncode rc, reasoncode_desc rcd where rc.reasoncode_id = wok.reasoncode_id and rc.reasoncode_id = rcd.reasoncode_id and rcd.language_id = lan.language_id) reasoncode_desc
, f_getrowcode_smg(wol.product_link_id,wol.sizedefinition_link_id,wol.requestedgrade_id,wok.processingstockroom_id) rowcode
, f_getrowlocation_smg(wol.product_link_id, wol.sizedefinition_link_id, wol.requestedgrade_id, wok.processingstockroom_id) locationcode
, wok.processingstockroom_id
, cast(F_MODIFICATIONCODE(wol.workorderline_id) as varchar2(1000)) MODIFICATIONS
, qualitygrade.code qualitygrade_code
,(SELECT qualitygrade_desc.description
        FROM   qualitygrade_desc
        WHERE  qualitygrade_desc.qualitygrade_id =
               qualitygrade.qualitygrade_id
               AND qualitygrade_desc.language_id = lan.language_id) QualityGrade
from workorder wok
            join weareremployment we  on wok.weareremployment_link_id = we.weareremployment_id
            join wearer w on w.wearer_id = we.wearer_id
                left outer join locker lo on we.locker_id=lo.locker_id
                join distributionpoint on distributionpoint.distributionpoint_id = we.distributionpoint_id
                      join department on distributionpoint.department_id = department.department_id
                       join customer cu on cu.customer_id = department.customer_id
   left outer join route on wok.route_id = route.route_id
   left outer join Systemuser su on wok.creationuser_id=su.systemuser_id
   left outer join woreferencenumber worefnr on wok.woreferencenumber_id = worefnr.woreferencenumber_id
   left outer join (workorderline wol left outer join qualitygrade ON wol.requestedgrade_id = qualitygrade.qualitygrade_id) on wok.workorder_id = wol.workorder_id
, businessunit bu, plant
, languages lan
where wok.businessunit_id = bu.businessunit_id
    and bu.plant_id = plant.plant_id
    and wok.origin <> 7 and wok.origin <> 11
UNION
select
  wok.workorder_id, wok.workordernumber
, wok.remark OrderRemark, wok.neededdate DeliveryDate
, to_char(wok.externalprinttimestamp) pickorderdate
, to_char(wok.externalprinttimestamp,'fmhhfm:MI:AM') pickordertimestamp
, wok.creationtimestamp
, su.fullname systemuserfullname
, cu.customernumber, cu.name, cu.legalname
, cus.customernumber wcustomernumber, cus.name wname, cus.legalname
, null WearerNr
, null WearerName
, null EmplNr, null CupBoard, null
, department.description Department
, department.departmentnumber
, distributionpoint.description ConsPoint
, route.routenumber, route.description RouteDescription
, coalesce( ( select count(wokem.workorderlineemblem_id) from workorderline wokli, workorderlineemblem wokem
            where wok.workorder_id = wokli.workorder_id and wokli.workorderline_id = wokem.workorderline_id)
            , 0) countWorkorderLineEmblem
, plant.code plant_code, plant.name plant_name
, lan.code Language_code
, (SELECT COUNT(DISTINCT v.workorderline_id) FROM v_workorderline v WHERE v.workorder_id = wok.workorder_id AND v.languagecode = lan.code) TotalRows
, wok.woreferencenumber_id
, worefnr.referencenumber woreferencenr
, worefnr.description worefnr_desc
, (select product_link.code from product_link where wol.product_link_id = product_link.product_link_id) productcode
, (select pd.description from product_link,product_desc pd where wol.product_link_id = product_link.product_link_id and pd.product_id = product_link.product_id and pd.language_id = lan.language_id) productdescription
, (select sizedefinition_link.code from sizedefinition_link where wol.sizedefinition_link_id = sizedefinition_link.sizedefinition_link_id) sizecode
, (select fm.code from finishingmethod fm where wol.finishingmethod_id = fm.finishingmethod_id) finishingmethodcode
, wol.quantityordered qtyordered
, wol.quantitycancelled qtycancelled
, wol.quantityfilled qtyfullfilled
, (wol.quantityordered - wol.quantitycancelled - wol.quantityfilled) qtyopen
, wol.quantitypicked qtypicked
, wol.instructions wol_remark
, wol.workorderline_id workorderlineid
,(select bu.code from businessunit bu where bu.businessunit_id=wok.internalprocessingbu_id) intprocessbu_code
, (select bu.description from businessunit bu where bu.businessunit_id=wok.internalprocessingbu_id) intprocessbu_desc
, (select bup.code from businessunit bup, stockroom sr where wok.processingstockroom_id = sr.stockroom_id
          and bup.businessunit_id = sr.managedbybu_id) processbu_code
, (select bup.description from businessunit bup, stockroom sr where wok.processingstockroom_id = sr.stockroom_id
          and bup.businessunit_id = sr.managedbybu_id) processbu_desc
, (select rc.code from reasoncode rc where rc.reasoncode_id = wok.reasoncode_id) reason_code
, (select rcd.description from reasoncode rc, reasoncode_desc rcd where rc.reasoncode_id = wok.reasoncode_id and rc.reasoncode_id = rcd.reasoncode_id and rcd.language_id = lan.language_id) reasoncode_desc
, f_getrowcode_smg(wol.product_link_id,wol.sizedefinition_link_id,wol.requestedgrade_id,wok.processingstockroom_id) rowcode
, f_getrowlocation_smg(wol.product_link_id, wol.sizedefinition_link_id, wol.requestedgrade_id, wok.processingstockroom_id) locationcode
, wok.processingstockroom_id
, cast(F_MODIFICATIONCODE(wol.workorderline_id) as varchar2(1000)) MODIFICATIONS
, qualitygrade.code qualitygrade_code
,(SELECT qualitygrade_desc.description
        FROM   qualitygrade_desc
        WHERE  qualitygrade_desc.qualitygrade_id =
               qualitygrade.qualitygrade_id
               AND qualitygrade_desc.language_id = lan.language_id) QualityGrade
from workorder wok
   left outer join distributionpoint on distributionpoint.distributionpoint_id=wok.distributionpoint_link_id
        left outer join department on distributionpoint.department_id = department.department_id
             left outer join customer cu on cu.customer_id = department.customer_id
   left outer join route on wok.route_id = route.route_id
   left outer join customer cus on cus.customer_id = wok.customer_link_id
   left outer join Systemuser su on wok.creationuser_id=su.systemuser_id
   left outer join woreferencenumber worefnr on wok.woreferencenumber_id = worefnr.woreferencenumber_id
   left outer join (workorderline wol left outer join qualitygrade ON wol.requestedgrade_id = qualitygrade.qualitygrade_id) on wok.workorder_id = wol.workorder_id
, businessunit bu, plant
, languages lan
where wok.businessunit_id = bu.businessunit_id
    and bu.plant_id = plant.plant_id
    and wok.weareremployment_link_id is null
    and wok.origin <> 7 and wok.origin <> 11
/

  CREATE OR REPLACE VIEW "V_POUNDANDDOLLARVOLUME" ("DELIVERYDATE", "INVOICEDATE", "BUSINESSUNIT_ID", "MARKETSEGMENTCODE", "MARKETSEGMENTCDESC", "POUNDS", "AMOUNT", "LANGUAGECODE") AS 
  select pa.deliverydate, pa.invoicedate, pa.businessunit_id,
  pa.code marketsegmentcode,
  (select msd.description from marketsegment_desc msd where ms.marketsegment_id = msd.marketsegment_id
     and msd.language_id = l.language_id) marketsegmentcdesc,
  pa.pounds, pa.paythisamount amount,
  l.code languagecode
from V_POUND_AND_DOLLAR_VOLUME pa, marketsegment ms,
languages l
where pa.marketsegment_id = ms.marketsegment_id
/

  CREATE OR REPLACE VIEW "V_PRICESPERCUSTOMER" ("CUSTOMER_ID", "DEFAULTBUSINESSUNIT_ID", "DEFAULTINVOICEBUSINESSUNIT_ID", "REPORTPARAM_ID", "TIMESTAMP", "DATE_VALUE1", "CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "CURRENCYCODE", "DECIMALS", "WASH", "WEIGHT", "REPAIR", "INSURANCE", "BUSINESSUNIT_ID", "BU_CODE", "BU_DESC") AS 
  select
  cu.customer_id, cu.defaultbusinessunit_id,cu.defaultinvoicebusinessunit_id, rp.reportparam_id, rp.timestamp, rp.date_value1
, cu.customernumber, cu.name customerName
, address.city
, currency.code currencyCode, currency.decimals
, ( select count(pripc.pricelistpercustomer_id) from pricelistpercustomer pripc where cu.customer_id = pripc.customer_id
  and rp.date_value1 between pripc.dateactive and pripc.dateinactive
      and pripc.pricetype in (1, 2, 3, 4) ) wash -- wash, rent, replacement, sales
, ( select count(pripc.pricelistpercustomer_id) from pricelistpercustomer pripc where cu.customer_id = pripc.customer_id
  and rp.date_value1 between pripc.dateactive and pripc.dateinactive
      and pripc.pricetype = 5 ) weight -- weight
, ( select count(pripc.pricelistpercustomer_id) from pricelistpercustomer pripc where cu.customer_id = pripc.customer_id
  and rp.date_value1 between pripc.dateactive and pripc.dateinactive
      and pripc.pricetype = 6 ) repair -- repair
, ( select count(pripc.pricelistpercustomer_id) from pricelistpercustomer pripc where cu.customer_id = pripc.customer_id
  and rp.date_value1 between pripc.dateactive and pripc.dateinactive
      and pripc.pricetype = 9 ) insurance -- garment insurance
, bu.businessunit_id, bu.code Bu_code, bu.description Bu_desc
from
  customer cu
, address, currency,  reportparam rp, businessunit bu
where
    cu.visitaddress_id = address.address_id
and cu.currency_id = currency.currency_id
and cu.defaultbusinessunit_id = bu.businessunit_id
and ((rp.number_value1 = 0 and rp.number_value2 = 999999)
    or exists (select * from v_customerinroutes v where v.customer_id = cu.customer_id
                   and v.routenumber >= rp.number_value1 and v.routenumber <= rp.number_value2))
/

  CREATE OR REPLACE VIEW "V_PROFITABILITYDASHBOARD" ("BU_CODE", "BU_DESC", "BUSINESSUNIT_ID", "ACTIVITYCODE", "PRODUCTCODE", "PRODUCTGROUPCODE", "WEIGHCATEGCODE", "ACTIVITYDESC", "PRODUCTDESC", "PRODUCTGROUPDESC", "WEIGHCATEGDESC", "PLPCDATEACTIVE", "PLPCDATEINACTIVE", "PRODUCTACTIVE", "WEIGHCATEGDATEACTIVE", "WEIGHCATEGDATEINACTIVE", "SEQUENCENUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "PHONENO", "FAXNO", "MINIMUMINVOICEAMOUNT", "TAXABLE", "STREET", "STREET2", "CITY", "ZIPCODE", "STATE", "MARKETSEGMENTCODE", "MARKETSEGMENTDESC", "CHAINCODE", "CHAINNAME", "STATETAXAUTHCODE", "COUNTYTAXAUTHCODE", "CITYTAXAUTHCODE", "INVOICEFREQNUMBER", "INVOICEFREQDESC", "PAYMENTTERMSCODE", "PAYMENTTERMSDESC", "LASTWASHPRICEINCREASE", "LASTRENTPRICEINCREASE", "LASTWEIGHTPRICEINCREASE", "CUSTOMER_ID", "WEIGHTPRICESOIL", "WEIGHTPRICECLEAN", "BILLINGMETHOD", "MINIMUMQUANTITY", "MINIMUMTURNAROUND", "SRCMETHOD", "SRCPERCENTAGESOILCOUNT", "SRCPERCENTAGEINVENTORY", "SRCQUANTITY", "SIZECODE", "CIRCINVENTORY", "RENTPRICE", "WASHPRICE", "REPLACEMENTPRICE", "SALESPRICE", "LANGUAGECODE") AS 
  SELECT bu.code BU_code, bu.description BU_desc, bu.businessunit_id
       , ac.code ActivityCode, pr.code ProductCode, pg.code ProductGroupCode, wc.code WeighCategCode
       , (SELECT acd.description FROM activity_desc acd WHERE acd.activity_id = ac.activity_id AND acd.language_id = lan.language_id) ActivityDesc
       , (SELECT prd.description FROM product_desc prd WHERE prd.product_id = pr.product_id AND prd.language_id = lan.language_id) ProductDesc
       , (SELECT pgd.description FROM productgroup_desc pgd WHERE pgd.productgroup_id = pg.productgroup_id AND pgd.language_id = lan.language_id) ProductGroupDesc
       , (SELECT wcd.description FROM weighingcategory_desc wcd WHERE wcd.weighingcategory_id = wc.weighingcategory_id AND wcd.language_id = lan.language_id) WeighCategDesc
       , plpc.dateactive plpcdateactive, plpc.dateinactive plpcdateinactive, pr.active ProductActive
       , wcpc.dateactive weighcategdateactive, wcpc.dateinactive weighcategdateinactive
       , (SELECT max(ps.sequencenumber) FROM productsize ps WHERE ps.product_id = pr.product_id) sequencenumber
       , cu.customernumber, cu.name customername, cu.phoneno, cu.faxno, cu.minimuminvoiceamount, cu.taxable
       , madd.street, madd.street2, madd.city, madd.zipcode, madd.state
       , (SELECT ms.code FROM marketsegment ms WHERE ms.marketsegment_id=cu.marketsegment_id) MarketSegmentCode
       , (SELECT msd.description FROM marketsegment_desc msd WHERE msd.marketsegment_id=cu.marketsegment_id AND msd.language_id = lan.language_id) MarketSegmentDesc
       , (SELECT ch.code FROM Chain ch WHERE ch.chain_id=cu.chain_id) ChainCode
       , (SELECT chd.name FROM Chain chd WHERE chd.chain_id=cu.chain_id) ChainName
       , CASE WHEN cu.taxable <> 'N' THEN (SELECT st.taxauthoritycode FROM states st WHERE cu.states_id = st.states_id)
       ELSE ''
       END StateTaxAuthCode
       , CASE WHEN cu.taxable <> 'N' THEN (SELECT cic.taxauthoritycode FROM citycounty cic WHERE cu.countytaxauthority_id=cic.citycounty_id )
       ELSE ''
       END CountyTaxAuthCode
       , CASE WHEN cu.taxable <> 'N' THEN (SELECT cit.taxauthoritycode FROM citycounty cit WHERE cu.citytaxauthority_id=cit.citycounty_id )
       ELSE ''
       END CityTaxAuthCode
       , (SELECT inf.invoicefrequencynumber FROM invoicefrequency inf WHERE inf.invoicefrequency_id=cu.invoicefrequency_id) InvoiceFreqNumber
       , (SELECT infd.description FROM invoicefrequency_desc infd WHERE infd.invoicefrequency_id=cu.invoicefrequency_id AND infd.language_id = lan.language_id) InvoiceFreqDesc
       , (SELECT pt.code FROM customerbillinginfo cbi, paymentterms pt WHERE cbi.customer_id = cu.debtor_id AND cbi.paymentterms_id = pt.paymentterms_id) PaymentTermsCode
       , (SELECT ptd.description FROM customerbillinginfo cbi, paymentterms_desc ptd WHERE cbi.customer_id = cu.debtor_id AND cbi.paymentterms_id = ptd.paymentterms_id AND ptd.language_id = lan.language_id) PaymentTermsDesc
       , substr(F_LastWashPriceIncrease(cu.customer_id, trunc(sysdate)), 1, 15) LastWashPriceIncrease
       , substr(F_LastRentPriceIncrease(cu.customer_id, trunc(sysdate)), 1, 15) LastRentPriceIncrease
       , substr(F_LastWeightPriceIncrease(cu.customer_id, trunc(sysdate)), 1, 15) LastWeightPriceIncrease
       , cu.customer_id
       , pack_price.Weight_Price(cu.customer_id, pr.weighingcategory_id, 'Y', trunc(sysdate)) WeightPriceSoil
       , pack_price.Weight_Price(cu.customer_id, pr.weighingcategory_id, 'N', trunc(sysdate)) WeightPriceClean
       , plpc.billingmethod, plpc.minimumquantity, plpc.minimumturnaround, plpc.srcmethod
       , plpc.srcpercentagesoilcount, plpc.srcpercentageinventory, plpc.srcquantity
       , (select sd.description from sizedefinition_desc sd where plpc.sizedefinition_id = sd.sizedefinition_id and sd.language_id=lan.language_id) SizeCode
       , CASE WHEN pr.typeofmerchandise = 1 THEN (SELECT SUM(rqa.quantity)
                   FROM rentalqtyadjustment rqa, productlistperdistribpoint plpd, distributionpoint dp, department de
                   WHERE rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id AND plpd.product_id = pr.product_id
                         AND plpd.sizedefinition_id = plpc.sizedefinition_id AND plpd.finishingmethod_id = plpc.finishingmethod_id
                         AND plpd.distributionpoint_id = dp.distributionpoint_id AND dp.department_id = de.department_id
                         AND de.customer_id = cu.customer_id AND rqa.adjustmentdate <= trunc(sysdate))
         WHEN (pr.typeofmerchandise = 2 AND plpc.billingmethod = 3 AND plpc.inventorybillingtype = 0) THEN (SELECT SUM(rqa.quantity)
                   FROM rentalqtyadjustment rqa, productlistperdistribpoint plpd, distributionpoint dp, department de
                   WHERE rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id AND plpd.product_id = pr.product_id
                         AND plpd.sizedefinition_id = plpc.sizedefinition_id AND plpd.finishingmethod_id = plpc.finishingmethod_id
                         AND plpd.distributionpoint_id = dp.distributionpoint_id AND dp.department_id = de.department_id
                         AND de.customer_id = cu.customer_id AND rqa.adjustmentdate <= trunc(sysdate))
         WHEN (pr.typeofmerchandise = 2 AND (plpc.billingmethod <> 3 OR plpc.inventorybillingtype <> 0)) THEN
              (SELECT SUM(wi.circinventory+wi.freeofchargeqty)  FROM wearerinventory wi WHERE wi.product_id = pr.product_id
                      AND wi.sizedefinition_id = plpc.sizedefinition_id AND wi.finishingmethod_id = plpc.finishingmethod_id
                      AND wi.dateactive <= trunc(sysdate))
         ELSE 0 END CircInventory
       , pack_price.Rent_Price(cu.customer_id,pr.product_id,plpc.sizedefinition_id,plpc.finishingmethod_id,NULL, 0) RentPrice
       , pack_price.Wash_Price(cu.customer_id, pr.product_id, plpc.sizedefinition_id, plpc.finishingmethod_id, trunc(sysdate), 1) WashPrice
       , pack_price.Replacement_Price(cu.customer_id, pr.product_id, plpc.sizedefinition_id,NULL, trunc(sysdate)) ReplacementPrice
       , pack_price.Sales_Price(cu.customer_id, pr.product_id, plpc.sizedefinition_id, trunc(sysdate)) SalesPrice
       , lan.code LanguageCode
FROM customer cu
       LEFT OUTER JOIN weighingcategpercustomer wcpc
            JOIN weighingcategory wc ON wcpc.weighingcategory_id = wc.weighingcategory_id
       ON wcpc.customer_id = cu.customer_id
     , productlistpercustomer plpc
     , businessunit bu,  product pr
       LEFT OUTER JOIN productgroup pg
            JOIN activity ac ON pg.activity_id = ac.activity_id
       ON pr.product_id = pg.productgroup_id
     , address madd, languages lan
WHERE cu.customer_id = plpc.customer_id AND cu.mailaddress_id = madd.address_id
      AND plpc.product_id = pr.product_id AND COALESCE(wc.weighingcategory_id, 0) = COALESCE(pr.weighingcategory_id, 0)
      AND EXISTS (SELECT v.customer_id FROM v_customersperbusinessunitdp v
            WHERE v.customer_id=cu.customer_id AND v.businessunit_id=bu.businessunit_id)
/

  CREATE OR REPLACE VIEW "V_PROFITABILITYDASHBOARD_PLPC" ("LINETYPE", "BU_CODE", "BU_DESC", "BUSINESSUNIT_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_ID", "PRODUCTDESC", "ACTIVITYDESC", "PRODUCTGROUPDESC", "ACTIVITYCODE", "PRODUCTCODE", "PRODUCTGROUPCODE", "PRTHEORETICALWEIGHT", "SIZECODE", "PSTHEORETICALWEIGHT", "INVOICENUMBER", "INVOICEDATE", "PRICE", "AMOUNT", "ADJUSTEDAMOUNT", "ADJUSTMENTREASON_ID", "INVOICEHEADER_ID", "PAYTHISAMOUNT", "BILLEDQTY", "INVOICELINETYPE", "LANGUAGECODE", "DELIVEREDQTY", "DATEACTIVE", "DATEINACTIVE", "PRODUCTACTIVE") AS 
  select 1 linetype, bu.code bu_code, bu.description bu_desc, bu.businessunit_id, cu.customernumber, cu.name customername, cu.customer_id
			 , (select prd.description from product_desc prd where prd.product_id = pr.product_id and prd.language_id = lan.language_id) productdesc
       , (select acd.description from activity_desc acd where acd.activity_id = ac.activity_id and acd.language_id = lan.language_id) activitydesc
			 , (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pg.productgroup_id and pgd.language_id = lan.language_id) productgroupdesc
			 , ac.code activitycode, pr.code productcode, pg.code productgroupcode, pr.theoreticalweight prtheoreticalweight
			 , (select sd.description from sizedefinition_desc sd where ilp.sizedefinition_link_id = sd.sizedefinition_id and sd.language_id=lan.language_id) sizecode
			 , (select ps.theoreticalweight from productsize ps where pr.product_id = ps.product_id and ps.sizedefinition_id = ilp.sizedefinition_link_id) pstheoreticalweight
       , ih.invoicenumber, ih.invoicedate, il.price, il.amount, il.adjustedamount, ih.adjustmentreason_id, ih.invoiceheader_id
			 , ih.paythisamount, il.billedqty
			 , (select ilt.type from invoicelinetype ilt where ilt.invoicelinetype_id = il.invoicelinetype_id) invoicelinetype
			 , lan.code languagecode
			 , 0 deliveredqty--coalesce(ilp.deliveredqty, 0) deliveredqty
			 , ih.invoicedate dateactive, ih.invoicedate dateinactive, coalesce(pr.active, 'Y') productactive
from customer cu, businessunit bu,
     invoiceheader ih, invoiceline il
		   left outer join invoicelineproduct ilp
			      left outer join product pr on ilp.product_link_id = pr.product_id
								 left outer join productgroup pg
											join activity ac on pg.activity_id = ac.activity_id
								 on pr.productgroup_id = pg.productgroup_id
			 on ilp.invoiceline_id = il.invoiceline_id
		 , status sta,
		 languages lan
where ih.invoiceheader_id = il.invoiceheader_id
			and ih.deltocustomer_link_id = cu.customer_id and ih.status_id = sta.status_id and sta.code = '2' and ih.documenttype = 1
			and exists (select v.customer_id from v_customersperbusinessunitdp v
            where v.customer_id=cu.customer_id and v.businessunit_id=bu.businessunit_id)
union all
select 2 linetype, bu.code bu_code, bu.description bu_desc, bu.businessunit_id, cu.customernumber, cu.name customername, cu.customer_id
			 , (select prd.description from product_desc prd where prd.product_id = pr.product_id and prd.language_id = lan.language_id) productdesc
       , (select acd.description from activity_desc acd where acd.activity_id = ac.activity_id and acd.language_id = lan.language_id) activitydesc
			 , (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pg.productgroup_id and pgd.language_id = lan.language_id) productgroupdesc
			 , ac.code activitycode, pr.code productcode, pg.code productgroupcode, pr.theoreticalweight prtheoreticalweight
			 , (select sd.description from sizedefinition_desc sd where dh.sizedefinition_link_id = sd.sizedefinition_id and sd.language_id=lan.language_id) sizecode
			 , (select ps.theoreticalweight from productsize ps where pr.product_id = ps.product_id and ps.sizedefinition_id = dh.sizedefinition_link_id) pstheoreticalweight
       , 0 invoicenumber, dh.deliverydate invoicedate, 0 price, 0 amount, 0 adjustedamount, null adjustmentreason_id, 0 invoiceheader_id
			 , 0 paythisamount, 0 billedqty
			 , 0 invoicelinetype
			 , lan.code languagecode
			 , coalesce(dh.amountdelivered, 0) deliveredqty
			 , dh.deliverydate dateactive, dh.deliverydate dateinactive, pr.active productactive
from customer_link cu, businessunit bu, distributionpoint_link dp, department_link de
     , product pr
						left outer join productgroup pg
											join activity ac on pg.activity_id = ac.activity_id
						on pr.productgroup_id = pg.productgroup_id
		 , deliveryhistory dh, languages lan
where dh.distributionpoint_link_id = dp.distributionpoint_link_id and dp.department_link_id = de.department_link_id and
      de.customer_link_id = cu.customer_link_id and
			pr.product_id = dh.product_link_id and
      exists (select v.customer_id from v_customersperbusinessunitdp v
            where v.customer_id=cu.customer_link_id and v.businessunit_id=bu.businessunit_id)
union all
select 3 linetype, bu.code bu_code, bu.description bu_desc, bu.businessunit_id, cu.customernumber, cu.name customername, cu.customer_id
			 , (select wcd.description from weighingcategory_desc wcd where wc.weighingcategory_id = wcd.weighingcategory_id and wcd.language_id = lan.language_id) productdesc
       , '' activitydesc
			 , '' productgroupdesc
			 , null activitycode, wc.code productcode, null productgroupcode, 0 prtheoreticalweight, '' sizecode
			 , 0 pstheoreticalweight
       , 0 invoicenumber, wh.weighingdate invoicedate, 0 price, 0 amount, 0 adjustedamount, null adjustmentreason_id, 0 invoiceheader_id
			 , 0 paythisamount, 0 billedqty
			 , 0 invoicelinetype
			 , lan.code languagecode
			 , wh.soilweight deliveredqty
			 , wcpc.dateactive dateactive, wcpc.dateinactive dateinactive, 'Y' productactive
from customer cu, businessunit bu, weighingcategpercustomer wcpc, weighinghistory wh, weighingcategory wc, languages lan
where cu.customer_id = wcpc.customer_id and wcpc.weighingcategory_id = wc.weighingcategory_id and
      wh.weighingcategory_link_id = wc.weighingcategory_id and wh.customer_link_id = cu.customer_id and wcpc.weightsoiled = 'Y' and
      exists (select v.customer_id from v_customersperbusinessunitdp v
            where v.customer_id=cu.customer_id and v.businessunit_id=bu.businessunit_id)
union all
select 4 linetype, bu.code bu_code, bu.description bu_desc, bu.businessunit_id, cu.customernumber, cu.name customername, cu.customer_id
			 , (select wcd.description from weighingcategory_desc wcd where wc.weighingcategory_id = wcd.weighingcategory_id and wcd.language_id = lan.language_id) productdesc
       , '' activitydesc
			 , '' productgroupdesc
			 , null activitycode, wc.code productcode, null productgroupcode, 0 prtheoreticalweight, '' sizecode
			 , 0 pstheoreticalweight
       , 0 invoicenumber, wh.weighingdate invoicedate, 0 price, 0 amount, 0 adjustedamount, null adjustmentreason_id, 0 invoiceheader_id
			 , 0 paythisamount, 0 billedqty
			 , 0 invoicelinetype
			 , lan.code languagecode
			 , wh.cleanweight deliveredqty
			 , wcpc.dateactive dateactive, wcpc.dateinactive dateinactive, 'Y' productactive
from customer cu, businessunit bu, weighingcategpercustomer wcpc, weighinghistory wh, weighingcategory wc, languages lan
where cu.customer_id = wcpc.customer_id and wcpc.weighingcategory_id = wc.weighingcategory_id and
      wh.weighingcategory_link_id = wc.weighingcategory_id and wh.customer_link_id = cu.customer_id and wcpc.weightclean = 'Y' and
      exists (select v.customer_id from v_customersperbusinessunitdp v
            where v.customer_id=cu.customer_id and v.businessunit_id=bu.businessunit_id)
/

  CREATE OR REPLACE VIEW "V_PURCHASEORDER" ("SUPPNUMBER", "SUPPNAME", "SUPPSTREET", "SUPPSTREET2", "SUPPZIPCODE", "SUPPCITY", "SUPPPHONE", "SUPPFAX", "SUPPEMAIL", "SUPPLIERTYPE", "BUYERCODE", "STOCKCODE", "STOCKNAME", "PLANTBUNAME", "STOCKSTREET", "STOCKZIPCODE", "STOCKCITY", "STOCKSTATECOUNTY", "STOCKSTATE", "STOCKCOUNTY", "PLANTBUPHONE", "PLANTBUFAX", "PLANTBUEMAIL", "PLANTCOMPANY_ID", "PLANTCOMPANYCODE", "PLANTCOMPANYNAME", "PCYSTREET", "PCYSTREET2", "PCYZIPCODE", "PCYCITY", "PCYSTATECOUNTY", "PCYSTATE", "PCYCOUNTY", "POAYSTATECOUNTY", "POAYSTATE", "POAYCOUNTY", "PLANTCOMPANYPHONE", "PLANTCOMPANYFAX", "PLANTCOMPANYEMAIL", "PLANTCOMPANYVAT", "PURCHASEORDERNUMBER", "ORDERDATE", "REQUESTEDDATE", "DISCOUNTPERCOVERALL", "DISCOUNTPERCDAYS", "DISCOUNTWITHINDAYS", "PAYMENTTERMS", "DELIVERYTERMS", "PHREMARK", "PHREMARK_NULL", "PHINTERNALREMARK", "SUPPSTATECOUNTY", "SUPPSTATE", "SUPPCOUNTY", "PRODUCTLINKCODE", "SUPPLIERPRODUCTCODE", "SUPPLIERSIZECODE", "SUPPLIERPRODUCTDESC", "UNIQUEITEM", "QUANTITYORDERED", "PRINTPRICEONPO", "PURCHASEPRICE", "AMOUNT", "PLIREMARK", "PLIREMARK_NULL", "CURRENCYCODE", "PRICEDECIMALS", "AMOUNTDECIMALS", "PURCHASEORDERHEADER_ID", "PURCHASEORDERLINE_ID", "STATUSCODE", "ORIGIN", "APPROVALDATE", "APPROVALUSER_ID", "STATUSDESC", "QUANTITYRECEIVED", "QUANTITYCANCELLED", "QUANTITYCONFIRMED", "LANGUAGECODE", "LAUNDRYSIZECODE", "QUALITYGRADECODE", "ADDRESSINAME", "ADDRESSISTREET1", "ADDRESSIZIPCODE", "ADDRESSICITY", "POSTOCKLINES", "POCUSTOMERLINES", "EMBLEMPO", "PLANTLOGO", "PADSTREET", "PADSTREET2", "PADCITY", "PADSTATE", "PADZIPCODE", "PADCOUNTY", "PADSTATECOUNTY", "PRODUCTLINKDESC", "EXPORTBATCHNUMBER") AS 
  select /*version 2.2*/
       supp.suppliernumber suppnumber, supp.name suppname, suad.street suppstreet, suad.street2 suppstreet2, suad.zipcode suppzipcode, suad.city suppcity,
       supp.phone suppphone, supp.fax suppfax, supp.email suppemail, supp.suppliertype, sksp.buyercode, sk.code stockcode, sk.name stockname,
       plantbu.name plantbuname, concatenatewithblank(skad.street, skad.street2) stockstreet, skad.zipcode stockzipcode, skad.city stockcity,
       concatenatewithblank3(skad.state, '/', skad.county) stockstatecounty, skad.state stockstate, skad.county stockcounty, plantbu.phoneno plantbuphone,
       plantbu.faxno plantbufax, plantbu.email plantbuemail, pcy.plantcompany_id, pcy.code plantcompanycode, pcy.name plantcompanyname,
       pcad.street pcystreet, pcad.street2 pcystreet2, pcad.zipcode pcyzipcode, pcad.city pcycity, concatenatewithblank3(pcad.state, '/', pcad.county) pcystatecounty,
       pcad.state pcystate, pcad.county pcycounty, concatenatewithblank3(poai.state, '/', poai.county) poaystatecounty, poai.state poaystate,
       poai.county poaycounty, pcy.phone plantcompanyphone, pcy.fax plantcompanyfax, pcy.email plantcompanyemail, pcy.vatnumber plantcompanyvat,
       ph.purchaseordernumber, ph.orderdate, ph.requesteddate, supp.discountpercoverall, supp.discountpercdays, supp.discountwithindays, supp.paymentterms,
       supp.deliveryterms, ph.remark phremark,
       case when ph.remark is null then 'Y'
            else 'N'
       end phremark_null, ph.internalremark phinternalremark, cast(concatenatewithblank3(suad.state, '/', suad.county) as varchar2(255)) suppstatecounty,
       suad.state suppstate, suad.county suppcounty,
       (select prl.code
          from product_link prl
         where pol.product_link_id = prl.product_link_id) productlinkcode,
       pol.supplierproductcode, pol.suppliersizecode,
       coalesce((select v.supplierproductdescription
                   from (select sp.supplierproductdescription
                           from supplierproduct sp
                           join productsizepersupproduct psp on sp.supplierproduct_id = psp.supplierproduct_id
                           join supplierproductprice spp on sp.supplierproduct_id = spp.supplierproduct_id
                          where sp.supplier_id = ph.supplier_id
                            and pol.product_link_id = psp.product_id
                            and pol.sizedefinition_link_id = psp.sizedefinition_id
                            and spp.startdate <= ph.orderdate
                            and sp.active = 'Y' order by spp.startdate desc, sp.supplierproduct_id desc) v
                  where rownum = 1),
         (select prd.description
            from product_desc prd
           where prd.product_id = pol.product_link_id
             and prd.language_id = lan.language_id)) supplierproductdesc, pol.uniqueitem, pol.quantityordered, supp.printpriceonpo,
       pol.purchaseprice, (pol.quantityordered * pol.purchaseprice) amount, pol.remark pliremark,
       case when pol.remark is null then 'Y'
            else 'N'
       end pliremark_null, curr.code currencycode, curr.decimals pricedecimals, curr.invoiceamountdecimals amountdecimals, ph.purchaseorderheader_id,
       pol.purchaseorderline_id, sta.code statuscode, ph.origin, ph.approvaldate, ph.approvaluser_id,
       (select stad.description
          from status_desc stad
         where stad.status_id = sta.status_id
           and stad.language_id = lan.language_id) statusdesc, pol.quantityreceived, pol.quantitycancelled, pol.quantityconfirmed, lan.code languagecode,
       (select sdl.code
          from sizedefinition_link sdl
         where pol.sizedefinition_link_id = sdl.sizedefinition_link_id) laundrysizecode,
       (select qg.code
          from qualitygrade qg
         where pol.requestedgrade_id = qg.qualitygrade_id) qualitygradecode,
       poai.name addressiname, poai.street1 addressistreet1, poai.zipcode addressizipcode, poai.city addressicity,
       (case when exists (select 1
                            from v_purchaseorderline_stock vs
                           where vs.purchaseorderheader_id = ph.purchaseorderheader_id
                             and (vs.qtypurchased - vs.qtyordered) > 0) then 'Y'
             else 'N'
       end) postocklines,
       (case when exists (select 1
                            from v_purchaseorderline_customer vsc
                           where vsc.purchaseorderheader_id = ph.purchaseorderheader_id
                             and vsc.languagecode = lan.code) then 'Y'
             else 'N'
       end) pocustomerlines,
       coalesce((select case when p.typeofmerchandise = 4 then 1
                             else 0
                        end
                   from product p
                  where pol.product_link_id = p.product_id), 0) emblempo, plantbu.logo plantlogo,
       pad.street padstreet, pad.street2 padstreet2, pad.city padcity,
       pad.state padstate, pad.zipcode padzipcode, pad.county padcounty,
       concatenatewithblank3(pad.state, '/', pad.county) padstatecounty,
       (select prld.description
          from product_link_desc prld
         where prld.product_link_id = pol.product_link_id
           and prld.language_id = lan.language_id) productlinkdesc,
       ph.exportbatchnumber
  from purchaseorderheader ph
       left join plantcompany pcy
            join address pcad on pcy.address_id = pcad.address_id
       on ph.plantcompany_id = pcy.plantcompany_id
       left join stockroomsupplier sksp on ph.stockroom_id = sksp.stockroom_id and ph.supplier_id = sksp.supplier_id
       left join stockroom sk
            join businessunit bu
                 join plant plantbu
                      join address pad on plantbu.address_id = pad.address_id
                 on bu.plant_id = plantbu.plant_id
            on sk.managedbybu_id = bu.businessunit_id
            join address skad on sk.deliveryaddress_id = skad.address_id
       on ph.stockroom_id = sk.stockroom_id
       left join purchaseorderline pol on ph.purchaseorderheader_id = pol.purchaseorderheader_id
       left join purchaseorderaddressinfo poai on ph.purchaseorderheader_id = poai.purchaseorderheader_id
       join supplier supp
            join address suad on supp.address_id = suad.address_id
       on ph.supplier_id = supp.supplier_id
       join status sta on ph.status_id = sta.status_id
       join currency curr on ph.currency_id = curr.currency_id
       cross join languages lan
/

  CREATE OR REPLACE VIEW "V_PURCHASEORDER_MOD" ("WORKORDER_ID", "PURCHASEORDERLINE_ID", "MODIFICATIONS", "QUANTITY", "LANGUAGECODE") AS 
  select wl.workorder_id, wl.purchaseorderline_id,
  vd.modifications, vq.quantity,
  l.code languagecode
from workorderline wl, v_purchaseorder_mod_desc vd, v_purchaseorder_mod_qty vq, languages l
where wl.workorder_id = vd.workorder_id
  and wl.purchaseorderline_id = vd.purchaseorderline_id
  and wl.workorder_id = vq.workorder_id
  and wl.purchaseorderline_id = vq.purchaseorderline_id
  and l.language_id = vd.language_id
union
select wl.workorder_id, wl.purchaseorderline_id,
  vd.modifications, vq.quantity,
  l.code languagecode
from workorderline wl, v_purchaseorder_mod_desc vd, v_purchaseorder_mod_qty vq, languages l, workorderlinepurchordline wolpol
where wl.workorder_id = vd.workorder_id
  and vd.purchaseorderline_id=wolpol.workorderlinepurchordline_id and wl.workorderline_id=wolpol.workorderline_id
  and wl.workorder_id = vq.workorder_id
  and wl.purchaseorderline_id = vq.purchaseorderline_id
  and l.language_id = vd.language_id
/

  CREATE OR REPLACE VIEW "V_QUITSERVICESUMMARY" ("DATEACTIVE", "DATEINACTIVE", "PLANTCODE", "PLANTNAME", "ROUTENUMBER", "ROUTEDESC", "DEPOTCODE", "DEPOTDESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "SYSTEMUSER_ID", "ISSUEDQUIT", "RETURNEDQTY") AS 
  SELECT w.dateactive, w.dateinactive, pl.code PlantCode, pl.name PlantName,
       v.routenumber, v.RouteDesc, v.DepotCode, v.DepotDesc,
       cu.customernumber, cu.name CustomerName, su.systemuser_id,
       wi.issuedquit,
       case when (wi.issuedquit-WI.CircInventory-WI.FreeOfChargeQty) <= 0 then 0
            else (wi.issuedquit-WI.CircInventory-WI.FreeOfChargeQty)
       end as returnedqty
FROM wearer w, customer cu, businessunit bu, plant pl, V_QuitServiceSummary_Route v
     , weareremployment we, wearerinventory wi, Systemuser su, businessunitsperusergroup bug
WHERE w.customer_id = cu.customer_id AND cu.defaultbusinessunit_id = bu.businessunit_id
      AND bu.plant_id = pl.plant_id AND v.plant_id = pl.plant_id AND v.customer_id = cu.customer_id
      AND we.wearer_id = w.wearer_id AND we.weareremployment_id = wi.weareremployment_id
      AND bug.usergroup_id = su.usergroup_id AND bug.businessunit_id = bu.businessunit_id
/

  CREATE OR REPLACE VIEW "V_RECALLORPACK" ("PRIMARYID", "PRODUCTCODE", "PRODUCTDESC", "ASSEMBLYEMP_NAME", "STERILIZATIONEMP_NAME", "DELIVERYEMP_NAME", "DELIVERYTIMESTAMP", "CUSTOMERNUMBER1", "CUSTOMERNAME1", "VISITADDRESS_ID", "CUSTSTREET1", "CUSTSTREET2", "CUSTZIPCODE", "CUSTCITY", "CHARGENUMBER", "RECALLEMP_NR", "RECALLEMP_NAME", "EMPLOYEE_ID", "RECALL_REASONCODE", "RECALLRC_DESC", "PACKINGNOTE_ID", "NOTENUMBER", "PRODUCTIONDATE", "REPORTPARAM_ID", "LANGUAGECODE", "BUSINESSUNIT_ID", "PLANTCODE", "PLANTNAME", "PLANTSTREET", "PLANTZIPCODE", "PLANTCITY", "PLANTPHONE", "PLANTFAX", "RECALLREASONCODE_ID") AS 
  select vup.primaryid,
       pr.code productcode,
			 (select pd.description from product_desc pd where pd.product_id = pr.product_id and pd.language_id = languages.language_id) productdesc,
			 (select e1.name from employee e1 where vup.assembleemployee_id = e1.employee_id) assemblyemp_name,
			 (select e2.name from employee e2 where vup.sterilizationemployee_id = e2.employee_id) sterilizationemp_name,
			 (select e3.name from employee e3 where vup.deliveryemployee_id = e3.employee_id) deliveryemp_name,
			 vup.deliverytimestamp,
			 cust1.customernumber customernumber1,
			 cust1.name customername1,
			 cust1.visitaddress_id,
			 adrcust.street custstreet1,
			 adrcust.street2 custstreet2,
			 adrcust.zipcode custzipcode,
			 adrcust.city custcity,
			 vup.chargenumber,
			 emp.employeenumber recallemp_nr,
			 emp.name recallemp_name,
			 emp.employee_id,
			 rc.code recall_reasoncode,
			 (select rcd.description from reasoncode_desc rcd where rcd.reasoncode_id = rc.reasoncode_id and rcd.language_id = languages.language_id) recallrc_desc,
			 vup.packingnote_id, pn.notenumber,
			 vup.recalltimestamp productiondate,
			 rp.reportparam_id,
			 languages.code languageCode,
			 vup.businessunit_id,
			 p.code plantcode,
			 p.name plantname,
			 adr.street plantstreet,
			 adr.zipcode plantzipcode,
			 adr.city plantcity,
			 p.phoneno plantphone,
			 p.faxno plantfax,
			 vup.recallreasoncode_id
from v_uniqueorpack vup
                    left outer join packingnote pn on vup.packingnote_id = pn.packingnote_id
                    left outer join customer cust1
										     join address adrcust on cust1.visitaddress_id = adrcust.address_id
										on vup.customer_id = cust1.customer_id
     , reportparam rp, product pr,  employee emp, reasoncode rc, businessunit b, plant p, address adr,  languages
where vup.uniqueitem_id = rp.number_value
      and vup.product_id = pr.product_id
			and vup.recallemployee_id = emp.employee_id
			and vup.recallreasoncode_id = rc.reasoncode_id
			and vup.businessunit_id = b.businessunit_id
			and b.plant_id = p.plant_id
			and p.address_id = adr.address_id
/

  CREATE OR REPLACE VIEW "V_REJECTEDORPACKS" ("PRIMARYID", "UNIQUEITEM_ID", "STATUS_ID", "STATUSCODE", "STATUSDESC", "VREASONCODE_ID", "CANCELREASONCODE_ID", "CANCELRC_CODE", "CANCELRC_DESC", "RECALLREASONCODE_ID", "RECALLRC_CODE", "RECALLRC_DESC", "VRC_CODE", "VRC_DESC", "VEMPLOYEE_ID", "EMPLOYEENAME", "EMPLOYEENUMBER", "CANCELEMPLOYEE_ID", "CANCELEMPLOYEENAME", "CANCELEMPLOYEENR", "RECALLEMPLOYEE_ID", "RECALLEMPLOYEENAME", "RECALLEMPLOYEENR", "VTIMESTAMP", "RECALLTIMESTAMP", "CANCELTIMESTAMP", "VPRICE", "PRODUCTCODE", "PRODUCTDESC", "STERILIZERCODE", "ASSEMBLYEMPLOYEE", "STERILIZATIONEMPLOYEE", "BUSINESSUNIT_ID", "UIBU_CODE", "UIBU_DESC", "LANGUAGE_CODE") AS 
  select vuop.primaryid, vuop.uniqueitem_id,
       vuop.status_id,
       s.code statuscode,
       (select sd.description from status_desc sd where s.status_id = sd.status_id and sd.language_id = languages.language_id) statusdesc,
       coalesce(vuop.cancelreasoncode_id, vuop.recallreasoncode_id) vreasoncode_id,
       vuop.cancelreasoncode_id,
       (select rc.code from reasoncode rc where rc.reasoncode_id = vuop.cancelreasoncode_id)cancelrc_code,
       (select rcd.description from reasoncode_desc rcd where rcd.reasoncode_id = vuop.cancelreasoncode_id and rcd.language_id = languages.language_id)cancelrc_desc,
       vuop.recallreasoncode_id,
       (select rc.code from reasoncode rc where rc.reasoncode_id = vuop.recallreasoncode_id)recallrc_code,
       (select rcd.description from reasoncode_desc rcd where rcd.reasoncode_id = vuop.cancelreasoncode_id and rcd.language_id = languages.language_id)recallrc_desc,
       (select rc.code from reasoncode rc where rc.reasoncode_id = coalesce(vuop.cancelreasoncode_id, vuop.recallreasoncode_id) )vrc_code,
       (select rcd.description from reasoncode_desc rcd where rcd.reasoncode_id = coalesce(vuop.cancelreasoncode_id, vuop.recallreasoncode_id) and rcd.language_id = languages.language_id) vrc_desc,
       case coalesce(vuop.cancelreasoncode_id, 0) when 0 then vuop.recallemployee_id
       else vuop.cancelemployee_id
       end vemployee_id,
       (select em.name from employee em where (case coalesce(vuop.cancelreasoncode_id, 0) when 0 then vuop.recallemployee_id
       else vuop.cancelemployee_id
       end) = em.employee_id) employeename,
       (select em.employeenumber from employee em where (case coalesce(vuop.cancelreasoncode_id, 0) when 0 then vuop.recallemployee_id
       else vuop.cancelemployee_id
       end) = em.employee_id) employeenumber,
       vuop.cancelemployee_id,
       (select em.name from employee em where vuop.cancelemployee_id = em.employee_id) cancelemployeename,
       (select em.employeenumber from employee em where vuop.cancelemployee_id = em.employee_id) cancelemployeenr,
       vuop.recallemployee_id,
       (select em.name from employee em where vuop.recallemployee_id = em.employee_id) recallemployeename,
       (select em.employeenumber from employee em where vuop.recallemployee_id = em.employee_id) recallemployeenr,
       case coalesce(vuop.cancelreasoncode_id, 0) when 0 then vuop.recalltimestamp
       else vuop.canceltimestamp
       end vtimestamp,
       vuop.recalltimestamp,
       vuop.canceltimestamp,
       case coalesce(vuop.customer_id, 0) when 0 then 0.00
       else pack_price.Replacement_Price(vuop.customer_id, vuop.product_id, vuop.sizedefinition_id,NULL, sysdate)
			 --f_pricereplacement((select pricelpc.generalpricelist_id from customer c, pricelistpercustomer pricelpc where pricelpc.customer_id = c.customer_id and vuop.customer_id = c.customer_id and pricelpc.pricetype = 3), vuop.product_id, vuop.sizedefinition_id, sysdate)
       end vprice,
       pr.code productcode,
       (select pd.description from product_desc pd where pd.product_id = pr.product_id and pd.language_id = languages.language_id) productdesc,
       st.code sterilizercode,
       (select e1.name from employee e1 where e1.employee_id = vuop.assembleemployee_id) assemblyemployee,
       (select e2.name from employee e2 where e2.employee_id = vuop.sterilizationemployee_id) sterilizationemployee,
       bu.businessunit_id, bu.code uibu_code, bu.description uibu_desc,
       languages.code language_code
from v_uniqueORpack vuop left outer join sterilizer st on vuop.sterilizer_id = st.sterilizer_id
     ,  product pr, languages, businessunit bu, status s
where  vuop.product_id = pr.product_id
     and vuop.status_id = s.status_id
/

  CREATE OR REPLACE VIEW "V_RELOAD_TOTALS" ("ROUTECONTROL_ID", "PRODUCT_ID", "SIZEDEFINITION_ID", "DELIVERED", "TOBEDELIVERED", "TRUCK_ID", "CODE", "DESCRIPTION", "STOCKROOMLOCATION_ID", "NAME", "EMPLOYEENUMBER", "ROUTE_ID", "DRIVINGDATE", "STOCKROOM_ID") AS 
  (SELECT V1."ROUTECONTROL_ID",V1."PRODUCT_ID",V1."SIZEDEFINITION_ID",V1."DELIVERED",V1."TOBEDELIVERED" ,
 TR.TRUCK_ID, TR.CODE, TR.DESCRIPTION, TR.STOCKROOMLOCATION_ID,
 E.NAME, E.EMPLOYEENUMBER,
 RC.ROUTE_ID ,RC.DRIVINGDATE, TR.STOCKROOM_ID
        FROM V_RELOAD_PN V1, ROUTECONTROL RC, TRUCK TR,EMPLOYEE E
        WHERE RC.ROUTECONTROL_ID = V1.ROUTECONTROL_ID
          AND TR.PLANT_ID = RC.PLANT_ID
          AND TR.CODE = RC.TRUCKCODE
       AND RC.DRIVERNUMBER = E.EMPLOYEENUMBER
				 AND RC.PLANT_ID = E.PLANT_ID
)
UNION ALL
(SELECT V2."ROUTECONTROL_ID",V2."PRODUCT_ID",V2."SIZEDEFINITION_ID",V2."DELIVERED",V2."TOBEDELIVERED",
 TR2.TRUCK_ID, TR2.CODE, TR2.DESCRIPTION, TR2.STOCKROOMLOCATION_ID,
E2.NAME, E2.EMPLOYEENUMBER,
 RC2.ROUTE_ID ,RC2.DRIVINGDATE, TR2.STOCKROOM_ID
        FROM V_RELOAD_SN V2, ROUTECONTROL RC2, TRUCK TR2,EMPLOYEE E2
        WHERE RC2.ROUTECONTROL_ID = V2.ROUTECONTROL_ID
            AND TR2.PLANT_ID = RC2.PLANT_ID
            AND TR2.CODE = RC2.TRUCKCODE
                AND RC2.DRIVERNUMBER = E2.EMPLOYEENUMBER
		  AND RC2.PLANT_ID = E2.PLANT_ID
)
/

  CREATE OR REPLACE VIEW "V_REPORTMATRENTAL" ("CODE", "PRODGRP", "PRODUCTCODE", "PRODUCTDESC", "DSCODE", "SIZECODE", "QUANTITY", "DATEACTIVE", "DATEINACTIVE") AS 
  SELECT bu.code,
            prg.code prodgrp,
            t.productCode,
            t.ProductDesc,
            t.dscode,
            (SELECT sdef.code
               FROM sizedefinition sdef
              WHERE t.sizedefinition_id = sdef.sizedefinition_id)
               sizecode,
            SUM (t.quantity) quantity,
            t.dateactive,
            t.dateinactive
FROM v_rentalagreements t
     inner join customer cu
           inner join businessunit bu on cu.defaultbusinessunit_id = bu.businessunit_id
     on t.customer_id = cu.customer_id and t.language_id = cu.language_id
     inner join product p
           inner join productgroup prg on p.productgroup_id = prg.productgroup_id
     on t.product_id = p.product_id
WHERE t.billingmethod = 1
/*AND cu.defaultbusinessunit_id IN (19, 11, 4, 9, 5, 15, 7, 14, 81, 122, 123)
and t.dateactive <= to_date('31-01-2008','dd-mm-yyyy') and t.dateinactive >= to_date('31-01-2008','dd-mm-yyyy')*/
GROUP BY bu.code,
            prg.code,
            t.productCode,
            t.ProductDesc,
            t.dscode,
            t.sizedefinition_id,
            t.dateactive,
            t.dateinactive
ORDER BY bu.code,
            prg.code,
            t.productCode,
            t.ProductDesc,
            t.dscode,
            sizecode,
            t.dateactive,
            t.dateinactive
/

  CREATE OR REPLACE VIEW "V_REVENUEMAINTENANCE" ("BU_CODE", "BU_DESC", "ROUTENUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "DATEINACTIVE", "SEARCHNAME", "DATEACTIVE", "LOSTREASON", "GAINREASON", "INVOICENUMBER", "INVOICEDATE", "NEWINVOICENUMBER", "NEWINVOICEDATE", "INVLINECODE", "INVLINEDESC", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "CHAINCODE", "BILLEDQTY", "PRICE", "AMOUNT", "WEARERNUMBER", "WEARERNAME", "SIZECODE", "NEWBILLEDQTY", "NEWPRICE", "NEWAMOUNT", "SECONDINVOICEDATE", "MAXINVOICEDATE", "DELTOCUSTOMER_LINK_ID", "ROUTE_ID", "COMEOFFCREDIT") AS 
  select bu.code BU_code, bu.description BU_desc, ro.routenumber
, cu.customernumber, cu.name customername, cu.dateinactive, cu.searchname
, (select max(cpc.dateactive) from contractspercustomer cpc
where cpc.customer_id = cu.customer_id and cpc.dateactive <= trunc(sysdate) and cpc.dateinactive >= trunc(sysdate)
) dateactive
, (select lr.code from contractspercustomer cpc, gainlostreason lr
where cpc.customer_id = cu.customer_id and cpc.dateactive <= trunc(sysdate) and cpc.dateinactive >= trunc(sysdate)
and cpc.lostreason_id = lr.gainlostreason_id) LostReason
, (select gr.code from contractspercustomer cpc, gainlostreason gr
where cpc.customer_id = cu.customer_id and cpc.dateactive <= trunc(sysdate) and cpc.dateinactive >= trunc(sysdate)
and cpc.gainreason_id = gr.gainlostreason_id) GainReason
, ih.invoicenumber, ih.invoicedate
, ih1.invoicenumber newinvoicenumber, ih1.invoicedate newinvoicedate
, il.code InvLineCode, il.description InvLineDesc
, ilp.finishingmethodcode, ilp.finishingmethoddescription
, (select Chain.Code from Chain where Chain.Chain_Id = cu.chain_id) ChainCode
, il.billedqty
, il.price
, il.amount
, ilp.wearernumber, ilp.wearername, ilp.sizecode
, ( select max(il1.billedqty) from invoiceline il1, invoicelineproduct ilp1
    where ih1.invoiceheader_id = il1.invoiceheader_id and il1.invoicelinetype_id = 1
      and il1.invoiceline_id = ilp1.invoiceline_id
      and ilp.product_link_id = ilp1.product_link_id and ilp.sizedefinition_link_id = ilp1.sizedefinition_link_id
      and ilp.finishingmethod_id = ilp1.finishingmethod_id and il.code = il1.code
      and coalesce(ilp.wearernumber, -1) = coalesce(ilp1.wearernumber, -1)) newbilledqty
, ( select max(il2.price) from invoiceline il2, invoicelineproduct ilp2
    where ih1.invoiceheader_id = il2.invoiceheader_id and il2.invoicelinetype_id = 1
      and il2.invoiceline_id = ilp2.invoiceline_id
      and ilp.product_link_id = ilp2.product_link_id and ilp.sizedefinition_link_id = ilp2.sizedefinition_link_id
      and ilp.finishingmethod_id = ilp2.finishingmethod_id and il.code = il2.code
      and coalesce(ilp.wearernumber, -1) = coalesce(ilp2.wearernumber, -1)) newprice
, ( select max(il2.amount) from invoiceline il2, invoicelineproduct ilp2
    where ih1.invoiceheader_id = il2.invoiceheader_id and il2.invoicelinetype_id = 1
      and il2.invoiceline_id = ilp2.invoiceline_id
      and ilp.product_link_id = ilp2.product_link_id and ilp.sizedefinition_link_id = ilp2.sizedefinition_link_id
      and ilp.finishingmethod_id = ilp2.finishingmethod_id and il.code = il2.code
      and coalesce(ilp.wearernumber, -1) = coalesce(ilp2.wearernumber, -1)) newamount
, v.secondinvoicedate, v.maxinvoicedate
, ih.deltocustomer_link_id, ro.route_id
, (select count(1) from contractspercustomer cpc, gainlostreason lr2
where cpc.customer_id = cu.customer_id and cpc.dateactive >= add_months(sysdate, -1) and cpc.dateactive <= sysdate
and cpc.lostreason_id = lr2.gainlostreason_id and lpad(lr2.code, 1)='C') ComeOffCredit
from businessunit bu, route ro, customer cu, invoiceheader ih, invoiceline il, invoicelineproduct ilp, V_RevenueMaintenance_Aux v
, invoiceheader ih1
where cu.defaultbusinessunit_id = bu.businessunit_id and ih.route_id = ro.route_id and ih.deltocustomer_link_id = cu.customer_id
      and ih.invoiceheader_id = il.invoiceheader_id and il.invoiceline_id = ilp.invoiceline_id
      and il.invoicelinetype_id = 1 and v.deltocustomer_link_id = cu.customer_id
      and ih.invoicedate = v.secondinvoicedate
      and ih1.invoicedate = v.maxinvoicedate
      and ih1.route_id = ro.route_id and ih1.deltocustomer_link_id = cu.customer_id
      and ih.prebillamount > 0 and ih1.prebillamount>0
/

  CREATE OR REPLACE VIEW "V_REVENUEMAINTENANCE15D" ("BU_CODE", "BU_DESC", "ROUTENUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "DATEINACTIVE", "SEARCHNAME", "DATEACTIVE", "LOSTREASON", "GAINREASON", "INVOICENUMBER", "INVOICEDATE", "NEWINVOICENUMBER", "NEWINVOICEDATE", "INVLINECODE", "INVLINEDESC", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "CHAINCODE", "BILLEDQTY", "PRICE", "AMOUNT", "WEARERNUMBER", "WEARERNAME", "SIZECODE", "NEWBILLEDQTY", "NEWPRICE", "NEWAMOUNT", "MININVOICEDATE", "MAXINVOICEDATE", "DELTOCUSTOMER_LINK_ID", "ROUTE_ID", "STATUS") AS 
  select bu.code BU_code, bu.description BU_desc, ro.routenumber
, cu.customernumber, cu.name customername, cu.dateinactive, cu.searchname
, (select max(cpc.dateactive) from contractspercustomer cpc
where cpc.customer_id = cu.customer_id and cpc.dateactive <= trunc(sysdate) and cpc.dateinactive >= trunc(sysdate)
) dateactive
, (select lr.code from contractspercustomer cpc, gainlostreason lr
where cpc.customer_id = cu.customer_id and cpc.dateactive <= trunc(sysdate) and cpc.dateinactive >= trunc(sysdate)
and cpc.lostreason_id = lr.gainlostreason_id) LostReason
, (select gr.code from contractspercustomer cpc, gainlostreason gr
where cpc.customer_id = cu.customer_id and cpc.dateactive <= trunc(sysdate) and cpc.dateinactive >= trunc(sysdate)
and cpc.gainreason_id = gr.gainlostreason_id) GainReason
, ih.invoicenumber, ih.invoicedate
, ih1.invoicenumber newinvoicenumber, ih1.invoicedate newinvoicedate
, il.code InvLineCode, il.description InvLineDesc
, ilp.finishingmethodcode, ilp.finishingmethoddescription
, (select Chain.Code from Chain where Chain.Chain_Id = cu.chain_id) ChainCode
, case when ih.invoicenumber = ih1.invoicenumber then
       case when getdatediff(ih.invoicedate, trunc(sysdate)-14) < getdatediff(trunc(sysdate), ih.invoicedate)
         then il.billedqty
         else 0 end
  else il.billedqty end billedqty
, case when ih.invoicenumber = ih1.invoicenumber then
       case when getdatediff(ih.invoicedate, trunc(sysdate)-14) < getdatediff(trunc(sysdate), ih.invoicedate)
         then il.price
         else 0 end
  else il.price end price
, case when ih.invoicenumber = ih1.invoicenumber then
       case when getdatediff(ih.invoicedate, trunc(sysdate)-14) < getdatediff(trunc(sysdate), ih.invoicedate)
         then il.amount
         else 0 end
  else il.amount end amount
, ilp.wearernumber, ilp.wearername, ilp.sizecode
, ( select case when ih.invoicenumber = ih1.invoicenumber then
       case when getdatediff(ih1.invoicedate, trunc(sysdate)-14) < getdatediff(trunc(sysdate), ih1.invoicedate)
         then 0
         else max(il1.billedqty) end
  else max(il1.billedqty) end from invoiceline il1, invoicelineproduct ilp1
    where ih1.invoiceheader_id = il1.invoiceheader_id and il1.invoicelinetype_id = 1
      and il1.invoiceline_id = ilp1.invoiceline_id
      and ilp.product_link_id = ilp1.product_link_id and ilp.sizedefinition_link_id = ilp1.sizedefinition_link_id
      and ilp.finishingmethod_id = ilp1.finishingmethod_id and il.code = il1.code
      and coalesce(ilp.wearernumber, -1) = coalesce(ilp1.wearernumber, -1)) newbilledqty
, ( select case when ih.invoicenumber = ih1.invoicenumber then
       case when getdatediff(ih1.invoicedate, trunc(sysdate)-14) < getdatediff(trunc(sysdate), ih1.invoicedate)
         then 0
         else max(il2.price)  end
  else max(il2.price) end from invoiceline il2, invoicelineproduct ilp2
    where ih1.invoiceheader_id = il2.invoiceheader_id and il2.invoicelinetype_id = 1
      and il2.invoiceline_id = ilp2.invoiceline_id
      and ilp.product_link_id = ilp2.product_link_id and ilp.sizedefinition_link_id = ilp2.sizedefinition_link_id
      and ilp.finishingmethod_id = ilp2.finishingmethod_id and il.code = il2.code
      and coalesce(ilp.wearernumber, -1) = coalesce(ilp2.wearernumber, -1)) newprice
, ( select case when ih.invoicenumber = ih1.invoicenumber then
       case when getdatediff(ih1.invoicedate, trunc(sysdate)-14) < getdatediff(trunc(sysdate), ih1.invoicedate)
         then 0
         else max(il2.amount)  end
  else max(il2.amount) end from invoiceline il2, invoicelineproduct ilp2
    where ih1.invoiceheader_id = il2.invoiceheader_id and il2.invoicelinetype_id = 1
      and il2.invoiceline_id = ilp2.invoiceline_id
      and ilp.product_link_id = ilp2.product_link_id and ilp.sizedefinition_link_id = ilp2.sizedefinition_link_id
      and ilp.finishingmethod_id = ilp2.finishingmethod_id and il.code = il2.code
      and coalesce(ilp.wearernumber, -1) = coalesce(ilp2.wearernumber, -1)) newamount
, v.mininvoicedate, v.maxinvoicedate
, ih.deltocustomer_link_id, ro.route_id
, case when v.mininvoicedate=v.maxinvoicedate then
(select count(1) from invoiceheader i where i.deltocustomer_link_id = cu.customer_id and i.invoicedate < v.MinInvoicedate)
  else -1 end Status
from businessunit bu, route ro, customer cu, invoiceheader ih, invoiceline il, invoicelineproduct ilp, V_RevenueMaintenance15_Aux v
, invoiceheader ih1
where cu.defaultbusinessunit_id = bu.businessunit_id and ih.route_id = ro.route_id and ih.deltocustomer_link_id = cu.customer_id
      and ih.invoiceheader_id = il.invoiceheader_id and il.invoiceline_id = ilp.invoiceline_id
      and il.invoicelinetype_id = 1 and v.deltocustomer_link_id = cu.customer_id
      and ih.invoicedate = v.mininvoicedate
      and ih1.invoicedate = v.maxinvoicedate
      and ih1.route_id = ro.route_id and ih1.deltocustomer_link_id = cu.customer_id
      and ih.prebillamount > 0 and ih1.prebillamount>0
/

  CREATE OR REPLACE VIEW "V_REVENUEMAINTENANCE8D" ("BU_CODE", "BU_DESC", "ROUTENUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "DATEINACTIVE", "SEARCHNAME", "DATEACTIVE", "LOSTREASON", "GAINREASON", "INVOICENUMBER", "INVOICEDATE", "NEWINVOICENUMBER", "NEWINVOICEDATE", "INVLINECODE", "INVLINEDESC", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "CHAINCODE", "BILLEDQTY", "PRICE", "AMOUNT", "WEARERNUMBER", "WEARERNAME", "SIZECODE", "NEWBILLEDQTY", "NEWPRICE", "NEWAMOUNT", "MININVOICEDATE", "MAXINVOICEDATE", "DELTOCUSTOMER_LINK_ID", "ROUTE_ID", "STATUS") AS 
  select bu.code BU_code, bu.description BU_desc, ro.routenumber
, cu.customernumber, cu.name customername, cu.dateinactive, cu.searchname
, (select max(cpc.dateactive) from contractspercustomer cpc
where cpc.customer_id = cu.customer_id and cpc.dateactive <= trunc(sysdate) and cpc.dateinactive >= trunc(sysdate)
) dateactive
, (select lr.code from contractspercustomer cpc, gainlostreason lr
where cpc.customer_id = cu.customer_id and cpc.dateactive <= trunc(sysdate) and cpc.dateinactive >= trunc(sysdate)
and cpc.lostreason_id = lr.gainlostreason_id) LostReason
, (select gr.code from contractspercustomer cpc, gainlostreason gr
where cpc.customer_id = cu.customer_id and cpc.dateactive <= trunc(sysdate) and cpc.dateinactive >= trunc(sysdate)
and cpc.gainreason_id = gr.gainlostreason_id) GainReason
, ih.invoicenumber, ih.invoicedate
, ih1.invoicenumber newinvoicenumber, ih1.invoicedate newinvoicedate
, il.code InvLineCode, il.description InvLineDesc
, ilp.finishingmethodcode, ilp.finishingmethoddescription
, (select Chain.Code from Chain where Chain.Chain_Id = cu.chain_id) ChainCode
, case when ih.invoicenumber = ih1.invoicenumber then
       case when getdatediff(ih.invoicedate, trunc(sysdate)-7) < getdatediff(trunc(sysdate), ih.invoicedate)
         then il.billedqty
         else 0 end
  else il.billedqty end billedqty
, case when ih.invoicenumber = ih1.invoicenumber then
       case when getdatediff(ih.invoicedate, trunc(sysdate)-7) < getdatediff(trunc(sysdate), ih.invoicedate)
         then il.price
         else 0 end
  else il.price end price
, case when ih.invoicenumber = ih1.invoicenumber then
       case when getdatediff(ih.invoicedate, trunc(sysdate)-7) < getdatediff(trunc(sysdate), ih.invoicedate)
         then il.amount
         else 0 end
  else il.amount end amount
, ilp.wearernumber, ilp.wearername, ilp.sizecode
, ( select case when ih.invoicenumber = ih1.invoicenumber then
       case when getdatediff(ih.invoicedate, trunc(sysdate)-7) < getdatediff(trunc(sysdate), ih.invoicedate)
         then 0
         else max(il1.billedqty) end
  else max(il1.billedqty) end from invoiceline il1, invoicelineproduct ilp1
    where ih1.invoiceheader_id = il1.invoiceheader_id and il1.invoicelinetype_id = 1
      and il1.invoiceline_id = ilp1.invoiceline_id
      and ilp.product_link_id = ilp1.product_link_id and ilp.sizedefinition_link_id = ilp1.sizedefinition_link_id
      and ilp.finishingmethod_id = ilp1.finishingmethod_id and il.code = il1.code
      and coalesce(ilp.wearernumber, -1) = coalesce(ilp1.wearernumber, -1)) newbilledqty
, ( select case when ih.invoicenumber = ih1.invoicenumber then
       case when getdatediff(ih.invoicedate, trunc(sysdate)-7) < getdatediff(trunc(sysdate), ih.invoicedate)
         then 0
         else max(il2.price)  end
  else max(il2.price) end from invoiceline il2, invoicelineproduct ilp2
    where ih1.invoiceheader_id = il2.invoiceheader_id and il2.invoicelinetype_id = 1
      and il2.invoiceline_id = ilp2.invoiceline_id
      and ilp.product_link_id = ilp2.product_link_id and ilp.sizedefinition_link_id = ilp2.sizedefinition_link_id
      and ilp.finishingmethod_id = ilp2.finishingmethod_id and il.code = il2.code
      and coalesce(ilp.wearernumber, -1) = coalesce(ilp2.wearernumber, -1)) newprice
, ( select case when ih.invoicenumber = ih1.invoicenumber then
       case when getdatediff(ih.invoicedate, trunc(sysdate)-7) < getdatediff(trunc(sysdate), ih.invoicedate)
         then 0
         else max(il2.amount)  end
  else max(il2.amount) end from invoiceline il2, invoicelineproduct ilp2
    where ih1.invoiceheader_id = il2.invoiceheader_id and il2.invoicelinetype_id = 1
      and il2.invoiceline_id = ilp2.invoiceline_id
      and ilp.product_link_id = ilp2.product_link_id and ilp.sizedefinition_link_id = ilp2.sizedefinition_link_id
      and ilp.finishingmethod_id = ilp2.finishingmethod_id and il.code = il2.code
      and coalesce(ilp.wearernumber, -1) = coalesce(ilp2.wearernumber, -1)) newamount
, v.mininvoicedate, v.maxinvoicedate
, ih.deltocustomer_link_id, ro.route_id
, case when v.mininvoicedate=v.maxinvoicedate then
(select count(1) from invoiceheader i where i.deltocustomer_link_id = cu.customer_id and i.invoicedate < v.MinInvoicedate)
  else -1 end Status
from businessunit bu, route ro, customer cu, invoiceheader ih, invoiceline il, invoicelineproduct ilp, V_RevenueMaintenance8_Aux v
, invoiceheader ih1
where cu.defaultbusinessunit_id = bu.businessunit_id and ih.route_id = ro.route_id and ih.deltocustomer_link_id = cu.customer_id
      and ih.invoiceheader_id = il.invoiceheader_id and il.invoiceline_id = ilp.invoiceline_id
      and il.invoicelinetype_id = 1 and v.deltocustomer_link_id = cu.customer_id
      and ih.invoicedate = v.mininvoicedate
      and ih1.invoicedate = v.maxinvoicedate
      and ih1.route_id = ro.route_id and ih1.deltocustomer_link_id = cu.customer_id
      and ih.prebillamount > 0 and ih1.prebillamount>0
/

  CREATE OR REPLACE VIEW "V_REVENUEMAINTENANCEMON" ("BU_CODE", "BU_DESC", "ROUTENUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "DATEINACTIVE", "SEARCHNAME", "DATEACTIVE", "LOSTREASON", "GAINREASON", "INVOICENUMBER", "INVOICEDATE", "NEWINVOICENUMBER", "NEWINVOICEDATE", "INVLINECODE", "INVLINEDESC", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "CHAINCODE", "BILLEDQTY", "PRICE", "AMOUNT", "WEARERNUMBER", "WEARERNAME", "SIZECODE", "NEWBILLEDQTY", "NEWPRICE", "NEWAMOUNT", "MININVOICEDATE", "MAXINVOICEDATE", "DELTOCUSTOMER_LINK_ID", "ROUTE_ID", "STATUS") AS 
  select bu.code BU_code, bu.description BU_desc, ro.routenumber
, cu.customernumber, cu.name customername, cu.dateinactive, cu.searchname
, (select max(cpc.dateactive) from contractspercustomer cpc
where cpc.customer_id = cu.customer_id and cpc.dateactive <= trunc(sysdate) and cpc.dateinactive >= trunc(sysdate)
) dateactive
, (select lr.code from contractspercustomer cpc, gainlostreason lr
where cpc.customer_id = cu.customer_id and cpc.dateactive <= trunc(sysdate) and cpc.dateinactive >= trunc(sysdate)
and cpc.lostreason_id = lr.gainlostreason_id) LostReason
, (select gr.code from contractspercustomer cpc, gainlostreason gr
where cpc.customer_id = cu.customer_id and cpc.dateactive <= trunc(sysdate) and cpc.dateinactive >= trunc(sysdate)
and cpc.gainreason_id = gr.gainlostreason_id) GainReason
, ih.invoicenumber, ih.invoicedate
, ih1.invoicenumber newinvoicenumber, ih1.invoicedate newinvoicedate
, il.code InvLineCode, il.description InvLineDesc
, ilp.finishingmethodcode, ilp.finishingmethoddescription
, (select Chain.Code from Chain where Chain.Chain_Id = cu.chain_id) ChainCode
, case when ih.invoicenumber = ih1.invoicenumber then
       case when getdatediff(ih.invoicedate, trunc(sysdate)-28) < getdatediff(trunc(sysdate), ih.invoicedate)
         then il.billedqty
         else 0 end
  else il.billedqty end billedqty
, case when ih.invoicenumber = ih1.invoicenumber then
       case when getdatediff(ih.invoicedate, trunc(sysdate)-28) < getdatediff(trunc(sysdate), ih.invoicedate)
         then il.price
         else 0 end
  else il.price end price
, case when ih.invoicenumber = ih1.invoicenumber then
       case when getdatediff(ih.invoicedate, trunc(sysdate)-28) < getdatediff(trunc(sysdate), ih.invoicedate)
         then il.amount
         else 0 end
  else il.amount end amount
, ilp.wearernumber, ilp.wearername, ilp.sizecode
, ( select case when ih.invoicenumber = ih1.invoicenumber then
       case when getdatediff(ih1.invoicedate, trunc(sysdate)-28) < getdatediff(trunc(sysdate), ih1.invoicedate)
         then 0
         else max(il1.billedqty) end
  else max(il1.billedqty) end from invoiceline il1, invoicelineproduct ilp1
    where ih1.invoiceheader_id = il1.invoiceheader_id and il1.invoicelinetype_id = 1
      and il1.invoiceline_id = ilp1.invoiceline_id
      and ilp.product_link_id = ilp1.product_link_id and ilp.sizedefinition_link_id = ilp1.sizedefinition_link_id
      and ilp.finishingmethod_id = ilp1.finishingmethod_id and il.code = il1.code
      and coalesce(ilp.wearernumber, -1) = coalesce(ilp1.wearernumber, -1)) newbilledqty
, ( select case when ih.invoicenumber = ih1.invoicenumber then
       case when getdatediff(ih1.invoicedate, trunc(sysdate)-28) < getdatediff(trunc(sysdate), ih1.invoicedate)
         then 0
         else max(il2.price)  end
  else max(il2.price) end from invoiceline il2, invoicelineproduct ilp2
    where ih1.invoiceheader_id = il2.invoiceheader_id and il2.invoicelinetype_id = 1
      and il2.invoiceline_id = ilp2.invoiceline_id
      and ilp.product_link_id = ilp2.product_link_id and ilp.sizedefinition_link_id = ilp2.sizedefinition_link_id
      and ilp.finishingmethod_id = ilp2.finishingmethod_id and il.code = il2.code
      and coalesce(ilp.wearernumber, -1) = coalesce(ilp2.wearernumber, -1)) newprice
, ( select case when ih.invoicenumber = ih1.invoicenumber then
       case when getdatediff(ih1.invoicedate, trunc(sysdate)-28) < getdatediff(trunc(sysdate), ih1.invoicedate)
         then 0
         else max(il2.amount)  end
  else max(il2.amount) end from invoiceline il2, invoicelineproduct ilp2
    where ih1.invoiceheader_id = il2.invoiceheader_id and il2.invoicelinetype_id = 1
      and il2.invoiceline_id = ilp2.invoiceline_id
      and ilp.product_link_id = ilp2.product_link_id and ilp.sizedefinition_link_id = ilp2.sizedefinition_link_id
      and ilp.finishingmethod_id = ilp2.finishingmethod_id and il.code = il2.code
      and coalesce(ilp.wearernumber, -1) = coalesce(ilp2.wearernumber, -1)) newamount
, v.mininvoicedate, v.maxinvoicedate
, ih.deltocustomer_link_id, ro.route_id
, case when v.mininvoicedate=v.maxinvoicedate then
(select count(1) from invoiceheader i where i.deltocustomer_link_id = cu.customer_id and i.invoicedate < v.MinInvoicedate)
  else -1 end Status
from businessunit bu, route ro, customer cu, invoiceheader ih, invoiceline il, invoicelineproduct ilp, V_RevenueMaintenance15_Aux v
, invoiceheader ih1
where cu.defaultbusinessunit_id = bu.businessunit_id and ih.route_id = ro.route_id and ih.deltocustomer_link_id = cu.customer_id
      and ih.invoiceheader_id = il.invoiceheader_id and il.invoiceline_id = ilp.invoiceline_id
      and il.invoicelinetype_id = 1 and v.deltocustomer_link_id = cu.customer_id
      and ih.invoicedate = v.mininvoicedate
      and ih1.invoicedate = v.maxinvoicedate
      and ih1.route_id = ro.route_id and ih1.deltocustomer_link_id = cu.customer_id
      and ih.prebillamount > 0 and ih1.prebillamount>0
/

  CREATE OR REPLACE VIEW "V_REVENUEMAINTENANCEQT" ("BU_CODE", "BU_DESC", "ROUTENUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "DATEINACTIVE", "SEARCHNAME", "DATEACTIVE", "LOSTREASON", "GAINREASON", "INVOICENUMBER", "INVOICEDATE", "NEWINVOICENUMBER", "NEWINVOICEDATE", "INVLINECODE", "INVLINEDESC", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "CHAINCODE", "BILLEDQTY", "PRICE", "AMOUNT", "WEARERNUMBER", "WEARERNAME", "SIZECODE", "NEWBILLEDQTY", "NEWPRICE", "NEWAMOUNT", "MININVOICEDATE", "MAXINVOICEDATE", "DELTOCUSTOMER_LINK_ID", "ROUTE_ID", "STATUS") AS 
  select bu.code BU_code, bu.description BU_desc, ro.routenumber
, cu.customernumber, cu.name customername, cu.dateinactive, cu.searchname
, (select max(cpc.dateactive) from contractspercustomer cpc
where cpc.customer_id = cu.customer_id and cpc.dateactive <= trunc(sysdate) and cpc.dateinactive >= trunc(sysdate)
) dateactive
, (select lr.code from contractspercustomer cpc, gainlostreason lr
where cpc.customer_id = cu.customer_id and cpc.dateactive <= trunc(sysdate) and cpc.dateinactive >= trunc(sysdate)
and cpc.lostreason_id = lr.gainlostreason_id) LostReason
, (select gr.code from contractspercustomer cpc, gainlostreason gr
where cpc.customer_id = cu.customer_id and cpc.dateactive <= trunc(sysdate) and cpc.dateinactive >= trunc(sysdate)
and cpc.gainreason_id = gr.gainlostreason_id) GainReason
, ih.invoicenumber, ih.invoicedate
, ih1.invoicenumber newinvoicenumber, ih1.invoicedate newinvoicedate
, il.code InvLineCode, il.description InvLineDesc
, ilp.finishingmethodcode, ilp.finishingmethoddescription
, (select Chain.Code from Chain where Chain.Chain_Id = cu.chain_id) ChainCode
, case when ih.invoicenumber = ih1.invoicenumber then
       case when getdatediff(ih.invoicedate, trunc(sysdate)-91) < getdatediff(trunc(sysdate), ih.invoicedate)
         then il.billedqty
         else 0 end
  else il.billedqty end billedqty
, case when ih.invoicenumber = ih1.invoicenumber then
       case when getdatediff(ih.invoicedate, trunc(sysdate)-91) < getdatediff(trunc(sysdate), ih.invoicedate)
         then il.price
         else 0 end
  else il.price end price
, case when ih.invoicenumber = ih1.invoicenumber then
       case when getdatediff(ih.invoicedate, trunc(sysdate)-91) < getdatediff(trunc(sysdate), ih.invoicedate)
         then il.amount
         else 0 end
  else il.amount end amount
, ilp.wearernumber, ilp.wearername, ilp.sizecode
, ( select case when ih.invoicenumber = ih1.invoicenumber then
       case when getdatediff(ih1.invoicedate, trunc(sysdate)-91) < getdatediff(trunc(sysdate), ih1.invoicedate)
         then 0
         else max(il1.billedqty) end
  else max(il1.billedqty) end from invoiceline il1, invoicelineproduct ilp1
    where ih1.invoiceheader_id = il1.invoiceheader_id and il1.invoicelinetype_id = 1
      and il1.invoiceline_id = ilp1.invoiceline_id
      and ilp.product_link_id = ilp1.product_link_id and ilp.sizedefinition_link_id = ilp1.sizedefinition_link_id
      and ilp.finishingmethod_id = ilp1.finishingmethod_id and il.code = il1.code
      and coalesce(ilp.wearernumber, -1) = coalesce(ilp1.wearernumber, -1)) newbilledqty
, ( select case when ih.invoicenumber = ih1.invoicenumber then
       case when getdatediff(ih1.invoicedate, trunc(sysdate)-91) < getdatediff(trunc(sysdate), ih1.invoicedate)
         then 0
         else max(il2.price)  end
  else max(il2.price) end from invoiceline il2, invoicelineproduct ilp2
    where ih1.invoiceheader_id = il2.invoiceheader_id and il2.invoicelinetype_id = 1
      and il2.invoiceline_id = ilp2.invoiceline_id
      and ilp.product_link_id = ilp2.product_link_id and ilp.sizedefinition_link_id = ilp2.sizedefinition_link_id
      and ilp.finishingmethod_id = ilp2.finishingmethod_id and il.code = il2.code
      and coalesce(ilp.wearernumber, -1) = coalesce(ilp2.wearernumber, -1)) newprice
, ( select case when ih.invoicenumber = ih1.invoicenumber then
       case when getdatediff(ih1.invoicedate, trunc(sysdate)-91) < getdatediff(trunc(sysdate), ih1.invoicedate)
         then 0
         else max(il2.amount)  end
  else max(il2.amount) end from invoiceline il2, invoicelineproduct ilp2
    where ih1.invoiceheader_id = il2.invoiceheader_id and il2.invoicelinetype_id = 1
      and il2.invoiceline_id = ilp2.invoiceline_id
      and ilp.product_link_id = ilp2.product_link_id and ilp.sizedefinition_link_id = ilp2.sizedefinition_link_id
      and ilp.finishingmethod_id = ilp2.finishingmethod_id and il.code = il2.code
      and coalesce(ilp.wearernumber, -1) = coalesce(ilp2.wearernumber, -1)) newamount
, v.mininvoicedate, v.maxinvoicedate
, ih.deltocustomer_link_id, ro.route_id
, case when v.mininvoicedate=v.maxinvoicedate then
(select count(1) from invoiceheader i where i.deltocustomer_link_id = cu.customer_id and i.invoicedate < v.MinInvoicedate)
  else -1 end Status
from businessunit bu, route ro, customer cu, invoiceheader ih, invoiceline il, invoicelineproduct ilp, V_RevenueMaintenance15_Aux v
, invoiceheader ih1
where cu.defaultbusinessunit_id = bu.businessunit_id and ih.route_id = ro.route_id and ih.deltocustomer_link_id = cu.customer_id
      and ih.invoiceheader_id = il.invoiceheader_id and il.invoiceline_id = ilp.invoiceline_id
      and il.invoicelinetype_id = 1 and v.deltocustomer_link_id = cu.customer_id
      and ih.invoicedate = v.mininvoicedate
      and ih1.invoicedate = v.maxinvoicedate
      and ih1.route_id = ro.route_id and ih1.deltocustomer_link_id = cu.customer_id
      and ih.prebillamount > 0 and ih1.prebillamount>0
/

  CREATE OR REPLACE VIEW "V_ROUTELIST" ("LINETYPE", "ROUTESTOP_ID", "DRIVINGYEAR", "DRIVINGWEEK", "NOTENUMBER", "CUSTOMER_ID", "SHOWSTOP", "ROUTECONTROL_ID", "STOP_DELIVERYPOINT_ID", "PN_DELIVERYPOINT_ID", "PLANTCODE", "ROUTENUMBER", "ROUTEDESCRIPTION", "DRIVINGDATE", "DEPOTCODE", "DEPOTDESCRIPTION", "LOADINGDOCK", "STARTTIME", "DRIVERNAME", "TRUCKCODE", "TRUCKDESCRIPTION", "VATNUMBER", "STOPNUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTNR", "DELIVERYADDRESS1", "DELIVERYADDRESS2", "CITY", "STATE", "ZIPCODE", "HOUSENUMBER", "HOUSENUMBEREXT", "C_DELIVERYADDRESS1", "C_DELIVERYADDRESS2", "C_CITY", "C_STATE", "C_ZIPCODE", "C_HOUSENUMBER", "C_HOUSENUMBEREXT", "ROUTELISTINSTRUCTIONS", "CONTACTPERSONNAME", "CONTACTPERSONPHONE", "MOBILEPHONE", "CUSTOMERPHONE", "STOP_ID", "DEPARTMENTNUMBER", "DISTRIBUTIONPOINTNUMBER", "DELIVERYPOINTCODE", "DEPARTMENTDESC", "DISTRIBUTIONPOINTDESC", "DELIVERYPOINTDESC", "PRODUCTCODE", "SIZECODE", "FINISHINGMETHODCODE", "DELIVERYSCHEMECODE", "PRODUCTDESCRIPTION", "DELIVERYSCHEMESTARTDATE", "QTYDELIVERED", "QTYEXPECTED", "ENDCONTRACT", "LANGUAGECODE", "DETAIL", "MOVEDROUTENUMBER", "MOVEDROUTEDESCRIPTION", "STATUS", "CUSTOMERCOUNTRYID", "COUNTRY", "PLANTCOUNTRYID", "TYPEOFMERCHADISE", "ROUTE_ID", "STOPTYPE", "REPORTPARAM_ID", "SHOWLOCKERONROUTELIST", "PUTUPTYPE_PRODUCT", "PUTUPTYPE_PLPC", "STRAIGHTEVENEXCHANGE", "QTYDELIVERED_PNL", "DELNOTEFORBULKPUTUPITEMS", "DEL_POINT_START_TIME", "DEL_POINT_END_TIME", "BREAKSTARTTIME", "BREAKENDTIME", "ROUTE_START_TIME", "STOP_TRAVELMINUTES", "STOP_SERVICEMINUTES", "DATEACTIVE", "DATEINACTIVE", "DEL_POINT_START_TIMECH", "DEL_POINT_END_TIMECH", "BREAKSTARTTIMECH", "BREAKENDTIMECH", "ROUTE_START_TIMECH", "ROUTE_START_TIMECH24", "STARTTIMECH", "SHOWONROUTELIST", "CONTACTNOTES", "CONTACTSTATUS", "PLANT_ID", "PLANTEMAIL", "DRIVINGINSTRUCTIONS", "COUNTCONTAINER", "DISTRIBUTIONPOINT_ID", "NUMBEROFCOLLI", "INTERNALPROCESSINGBU_ID", "DEFAULTBUSINESSUNIT_ID", "PROCESSINGPLANT_ID") AS 
  select 1 linetype, --packing notes
  st.routestop_id, getyearofweek(rc.drivingdate) drivingyear, getisoweek(rc.drivingdate) drivingweek,
  pn.notenumber, cu.customer_id,
  f_show_routestop_std(st.stop_id, st.routestop_id, st.stoptype, pl.plant_id) showstop,
  rc.routecontrol_id, st.deliverypoint_id stop_deliverypoint_id, delp.deliverypoint_id pn_deliverypoint_id,
  pl.code plantcode, ru.routenumber, ru.description routedescription, rc.drivingdate,
  d.code depotcode,d.description depotdescription, rc.loadingdock, rc.starttime,
  (case when rc.drivernumber = 0 then em.name
        else (select employee.name from employee where employee.employeenumber = rc.drivernumber
             and employee.plant_id = pl.plant_id)
   end) drivername,
   coalesce (rc.truckcode, tr.code) truckcode,
  (case when rc.truckcode is null then tr.description
        else (select truck.description from truck where truck.code = rc.truckcode
             and truck.plant_id = pl.plant_id)
   end) truckdescription, cu.vatnumber,
  st.stopnumber, cu.customernumber, cu.name customername,insertspace_after_x_characters(to_char(cu.customernumber),3) custnr,
  ad.street deliveryaddress1, ad.street2 deliveryaddress2, ad.city, ad.state, ad.zipcode, ad.housenumber, ad.housenumberext,
  '' c_deliveryaddress1, '' c_deliveryaddress2, '' c_city, '' c_state, '' c_zipcode, null c_housenumber, null c_housenumberext,
  st.routelistinstructions,
  cp.name contactpersonname, cp.phone contactpersonphone, cp.mobilephone, cu.phoneno customerphone, st.stop_id,
  dep.departmentnumber, disp.distributionpointnumber, delp.code deliverypointcode,
  dep.description departmentdesc, disp.description distributionpointdesc, delp.description deliverypointdesc,
  pr.code productcode, sd.code sizecode, fm.code finishingmethodcode, ds.code deliveryschemecode,
  (select pd.description from product_desc pd where pr.product_id = pd.product_id and pd.language_id = languages.language_id) productdescription,
  h.startdate deliveryschemestartdate,
  h.deliveredqty qtydelivered, 0 qtyexpected, 'P' endcontract,
  languages.code languagecode, 1 detail, v.routenumber movedroutenumber, v.description movedroutedescription, st.status,
  cu.country_id customercountryid, co.description country, pl.country_id plantcountryid,
  (select sum(cdd.typeofmerchadise) from customerdeliveryday cdd where cu.customer_id = cdd.customer_id
     and coalesce((select rm.drivingday_id from route rm where rs.route_id=rm.route_id), ru.drivingday_id) = cdd.day_id
     and cdd.typeofmerchadise >=1 and cdd.typeofmerchadise <=2) typeofmerchadise,
  ru.route_id, coalesce(st.stoptype, 0) stoptype, rp.reportparam_id,
  coalesce(clm.showlockeronroutelist, 'N') showlockeronroutelist,
  pr.putuptype putuptype_product, pnl.putuptype putuptype_plpc,
  case when h.packingnoteline_id is null then 0 else 1 end straightevenexchange,
  pnl.deliveredamount qtydelivered_pnl, cu.delnoteforbulkputupitems
  , (select hh.starttime from deliverypointopeninghour hh
            where hh.deliverypoint_id = delp.deliverypoint_id and hh.day_id = ru.drivingday_id) del_point_start_time
  , (select hh.endtime from deliverypointopeninghour hh
            where hh.deliverypoint_id = delp.deliverypoint_id and hh.day_id = ru.drivingday_id) del_point_end_time
  , delp.breakstarttime breakstarttime, delp.breakendtime breakendtime
  , ru.starttime route_start_time, rs.travelminutes stop_travelminutes, rs.serviceminutes stop_serviceminutes
  , cu.dateactive, cu.dateinactive
  , (select to_char(hh.starttime,'fmhhfm:MI:AM') from deliverypointopeninghour hh
            where hh.deliverypoint_id = delp.deliverypoint_id and hh.day_id = ru.drivingday_id) del_point_start_timech
  , (select to_char(hh.endtime,'fmhhfm:MI:AM') from deliverypointopeninghour hh
            where hh.deliverypoint_id = delp.deliverypoint_id and hh.day_id = ru.drivingday_id) del_point_end_timech
  , to_char(delp.breakstarttime,'fmHH:MI:AM') breakstarttimech, to_char(delp.breakendtime,'fmHH:MI:AM') breakendtimech
  , to_char(ru.starttime,'fmhhfm:MI:AM') route_start_timech
  , to_char(ru.starttime,'fmhh24fm:MI') route_start_timech24
  , to_char(rc.starttime,'fmhhfm:MI:AM') starttimech
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, rc.plant_id
 , cast(getsubstringonlength(pl.email,0,40) as varchar2(40)) plantemail
 , (select cri.routedescription from customerrouteinfo cri where cri.customer_id = cu.customer_id) drivinginstructions
 , (select sum(v2.countContainer) from V_ROUTECONTAINERS v2 where v2.STOP_ID = st.stop_id and v2.route_id = ru.route_id) CountContainer
 , disp.distributionpoint_id, pn.numberofcolli
 , pn.internalprocessingbu_id, cu.defaultbusinessunit_id
 , (select pbu.plant_id from businessunit pbu where pbu.businessunit_id = pn.processbusinessunit_id) processingplant_id
from reportparam rp
     inner join routecontrol rc
           inner join  route ru
                 left outer join depot d on ru.depot_id =d.depot_id
                 left outer join employee em on ru.driver_id = em.employee_id
                 left outer join truck tr on ru.truck_id = tr.truck_id
           on rc.route_id = ru.route_id
           inner join stop st
                 left outer join v_movedoutstops v on st.stop_id = v.movedtostop_id
                 left outer join contactperson cp on st.contactperson_id = cp.contactperson_id
                 left outer join routestop rs on st.routestop_id = rs.routestop_id
                 inner join packingnote pn
                       inner join packingnoteline pnl
                             left outer join v_packingnotelineperdelsch_ext h
                                  left outer join deliveryscheme ds on h.deliveryscheme_id = ds.deliveryscheme_id
                             on pnl.packingnoteline_id = h.packingnoteline_id
                             inner join product pr on pnl.product_id = pr.product_id
                             inner join sizedefinition sd on pnl.sizedefinition_id = sd.sizedefinition_id
                             inner join finishingmethod fm on pnl.finishingmethod_id = fm.finishingmethod_id
                       on pn.packingnote_id = pnl.packingnote_id
                       inner join distributionpoint disp
                             inner join department dep on disp.department_id = dep.department_id
                       on pn.distributionpoint_id = disp.distributionpoint_id
                       inner join deliverypoint delp
                             inner join address ad on delp.deliveryaddress_id = ad.address_id
                       on pn.deliverypoint_id = delp.deliverypoint_id
                       inner join status stat on pn.status_id = stat.status_id
                 on st.stop_id = pn.stop_id
                 inner join customer cu
                       left outer join customerlockermanagement clm on cu.customer_id = clm.customer_id
                       left outer join contact cont on cont.contact_id = coalesce(f_getcontactonroutelist(cu.customer_id), -1)
                       inner join country co on cu.country_id = co.country_id
                 on st.customer_link_id = cu.customer_id
           on rc.routecontrol_id = st.routecontrol_id
           inner join plant pl on rc.plant_id = pl.plant_id
     on rp.number_value = rc.routecontrol_id
     , languages
where stat.statustype = 'PN' and stat.code <> '40' and st.status in (0, 3, 4)
      and (nvl(rp.number_value5, -1) = -1 or (rp.number_value5 <> -1 and exists (select 1 from customeractivities ca
                                    where ca.customer_id = cu.customer_id and ca.internalprocessingbu_id = rp.number_value5)))
      and (nvl(rp.number_value6, -1) = -1 or (rp.number_value6 <> -1 and exists (select 1 from customeractivities ca, businessunit bu
                                    where ca.customer_id = cu.customer_id and ca.processbusinessunit_id = bu.businessunit_id
                                          and bu.plant_id = rp.number_value6)))
union all          -- 2 --
select 2 linetype, -- straight even return
  st.routestop_id, getyearofweek(rc.drivingdate) drivingyear, getisoweek(rc.drivingdate) drivingweek,
  0 notenumber, cu.customer_id,
  f_show_routestop_std(st.stop_id, st.routestop_id, st.stoptype, pl.plant_id) showstop,
  rc.routecontrol_id, st.deliverypoint_id stopdeliverypoint_id, delp.deliverypoint_id pn_deliverypoint_id,
  pl.code plantcode, ru.routenumber, ru.description routedescription, rc.drivingdate,
  d.code depotcode,d.description depotdescription, rc.loadingdock, rc.starttime,
  (case when rc.drivernumber = 0 then em.name
        else (select employee.name from employee where employee.employeenumber = rc.drivernumber
             and employee.plant_id = pl.plant_id)
   end) drivername,
  coalesce (rc.truckcode, tr.code) truckcode,
  (case when rc.truckcode is null then tr.description
        else (select truck.description from truck where truck.code = rc.truckcode
             and truck.plant_id = pl.plant_id)
   end) truckdescription, cu.vatnumber,
  st.stopnumber, cu.customernumber, cu.name customername,insertspace_after_x_characters(to_char(cu.customernumber),3) custnr,
  ad.street deliveryaddress1, ad.street2 deliveryaddress2, ad.city, ad.state, ad.zipcode, ad.housenumber, ad.housenumberext,
  '' c_deliveryaddress1, '' c_deliveryaddress2, '' c_city, '' c_state, '' c_zipcode, null c_housenumber, null c_housenumberext,
  st.routelistinstructions,
  cp.name contactpersonname, cp.phone contactpersonphone, cp.mobilephone,cu.phoneno customerphone,  st.stop_id,
  dep.departmentnumber, disp.distributionpointnumber, delp.code deliverypointcode,
  dep.description departmentdesc, disp.description distributionpointdesc, delp.description deliverypointdesc,
  pr.code productcode, sd.code sizecode, fm.code finishingmethodcode, ds.code deliveryschemecode,
  (select description from product_desc pd where pr.product_id = pd.product_id and pd.language_id = languages.language_id) productdescription,
  null deliveryschemestartdate,
  0 qtydelivered, ser.qtyexpected qtyexpected, ser.endcontract,
  languages.code languagecode, 1 detail, v.routenumber movedroutenumber, v.description movedroutedescription, st.status,
  cu.country_id customercountryid, co.description country, pl.country_id plantcountryid,
  (select sum(cdd.typeofmerchadise) from customerdeliveryday cdd where cu.customer_id = cdd.customer_id
     and coalesce((select rm.drivingday_id from route rm where rs.route_id=rm.route_id), ru.drivingday_id) = cdd.day_id
     and cdd.typeofmerchadise >=1 and cdd.typeofmerchadise <=2) typeofmerchadise,
  ru.route_id, coalesce(st.stoptype, 0) stoptype, rp.reportparam_id,
  coalesce(clm.showlockeronroutelist, 'N') showlockeronroutelist,
  pr.putuptype putuptype_product, 0 putuptype_plpc, 1 straightevenexchange,
  0 qtydelivered_pnl, cu.delnoteforbulkputupitems
  , (select hh.starttime from deliverypointopeninghour hh
            where hh.deliverypoint_id = delp.deliverypoint_id and hh.day_id = ru.drivingday_id) del_point_start_time
  , (select hh.endtime  from deliverypointopeninghour hh
            where hh.deliverypoint_id = delp.deliverypoint_id and hh.day_id = ru.drivingday_id) del_point_end_time
  ,  delp.breakstarttime breakstarttime, delp.breakendtime breakendtime
  , ru.starttime route_start_time, rs.travelminutes stop_travelminutes, rs.serviceminutes stop_serviceminutes
  , cu.dateactive, cu.dateinactive
  , (select to_char(hh.starttime,'fmHHfm:MI:AM') from deliverypointopeninghour hh
            where hh.deliverypoint_id = delp.deliverypoint_id and hh.day_id = ru.drivingday_id) del_point_start_timech
  , (select to_char(hh.endtime,'fmHHfm:MI:AM') from deliverypointopeninghour hh
            where hh.deliverypoint_id = delp.deliverypoint_id and hh.day_id = ru.drivingday_id) del_point_end_timech
  , to_char(delp.breakstarttime,'fmHHfm:MI:AM') breakstarttimech, to_char(delp.breakendtime,'fmHH:MI:AM') breakendtimech
  , to_char(ru.starttime,'fmHHfm:MI:AM') route_start_timech
  , to_char(ru.starttime,'fmHH24fm:MI') route_start_timech24
  , to_char(rc.starttime,'fmHHfm:MI:AM') starttimech
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, rc.plant_id
 , cast(getsubstringonlength(pl.email,0,40) as varchar2(40)) plantemail
 , (select cri.routedescription from customerrouteinfo cri where cri.customer_id = cu.customer_id) drivinginstructions
 , (select sum(v2.countContainer) from V_ROUTECONTAINERS v2 where v2.STOP_ID = st.stop_id and v2.route_id = ru.route_id) CountContainer
 , disp.distributionpoint_id, null numberofcolli
 , -1 internalprocessingbu_id, cu.defaultbusinessunit_id
 , (select pbu.plant_id from businessunit pbu where pbu.businessunit_id = ser.processbusinessunit_id) processingplant_id
from reportparam rp
     inner join routecontrol rc
           inner join route ru
                 left outer join depot d on ru.depot_id =d.depot_id
                 left outer join employee em on ru.driver_id = em.employee_id
                 left outer join truck tr on ru.truck_id = tr.truck_id
           on rc.route_id = ru.route_id
           inner join stop st
                 left outer join v_movedoutstops v on st.stop_id = v.movedtostop_id
                 left outer join contactperson cp on st.contactperson_id = cp.contactperson_id
                 left outer join routestop rs on st.routestop_id = rs.routestop_id
                 inner join straightevenreturn ser
                       inner join product pr on ser.product_id = pr.product_id
                       inner join sizedefinition sd on ser.sizedefinition_id = sd.sizedefinition_id
                       inner join finishingmethod fm on ser.finishingmethod_id = fm.finishingmethod_id
                       inner join deliveryscheme ds on ser.deliveryscheme_id = ds.deliveryscheme_id
                       inner join distributionpoint disp
                             inner join deliverypoint delp
                                   inner join address ad on delp.deliveryaddress_id = ad.address_id
                             on disp.deliverypoint_id = delp.deliverypoint_id
                             inner join department dep on  disp.department_id = dep.department_id
                       on ser.distributionpoint_id = disp.distributionpoint_id
                       inner join status stat on ser.status_id = stat.status_id
                 on st.stop_id = ser.stop_id
                 inner join customer cu
                       left outer join customerlockermanagement clm on cu.customer_id = clm.customer_id
                       left outer join contact cont on cont.contact_id = coalesce(f_getcontactonroutelist(cu.customer_id), -1)
                       inner join country co on cu.country_id = co.country_id
                 on st.customer_link_id = cu.customer_id
           on rc.routecontrol_id = st.routecontrol_id
           inner join plant pl on rc.plant_id = pl.plant_id
     on rp.number_value = rc.routecontrol_id
     , languages
where stat.statustype = 'SR' and stat.code <> '30' and st.status in (0, 3, 4)
      and (nvl(rp.number_value5, -1) = -1 or (rp.number_value5 <> -1 and exists (select 1 from customeractivities ca
                                    where ca.customer_id = cu.customer_id and ca.internalprocessingbu_id = rp.number_value5)))
      and (nvl(rp.number_value6, -1) = -1 or (rp.number_value6 <> -1 and exists (select 1 from customeractivities ca, businessunit bu
                                    where ca.customer_id = cu.customer_id and ca.processbusinessunit_id = bu.businessunit_id
                                          and bu.plant_id = rp.number_value6)))
union all  -- 3 --
select 3 linetype, -- no packing notes - used only for header in rpt
  st.routestop_id, getyearofweek(rc.drivingdate) drivingyear, getisoweek(rc.drivingdate) drivingweek,
  0 notenumber, cu.customer_id,
  f_show_routestop_std(st.stop_id, st.routestop_id, st.stoptype, pl.plant_id) showstop,
  rc.routecontrol_id, st.deliverypoint_id stopdeliverypoint_id, 0 pn_deliverypoint_id,
  pl.code plantcode, ru.routenumber, ru.description routedescription, rc.drivingdate,
 d.code depotcode,d.description depotdescription, rc.loadingdock, rc.starttime,
  (case when rc.drivernumber = 0 then em.name
        else (select employee.name from employee where employee.employeenumber = rc.drivernumber
             and employee.plant_id = pl.plant_id)
   end) drivername,
  coalesce (rc.truckcode, tr.code) truckcode,
  (case when rc.truckcode is null then tr.description
        else (select truck.description from truck where truck.code = rc.truckcode
             and truck.plant_id = pl.plant_id)
   end) truckdescription, cu.vatnumber,
  st.stopnumber, cu.customernumber, cu.name customername,insertspace_after_x_characters(to_char(cu.customernumber),3) custnr,
  ad.street deliveryaddress1, ad.street2 deliveryaddress2, ad.city, ad.state, ad.zipcode, ad.housenumber, ad.housenumberext,
  add2.street c_deliveryaddress1, add2.street2 c_deliveryaddress2, add2.city c_city, add2.state c_state, add2.zipcode c_zipcode,
  add2.housenumber c_housenumber, add2.housenumberext c_housenumberext, st.routelistinstructions,
  cp.name contactpersonname, cp.phone contactpersonphone,cp.mobilephone, cu.phoneno customerphone, st.stop_id,
  -1 departmentnumber, -1 distributionpointnumber, dp.code deliverypointcode,
  '' departmentdesc, '' distributionpointdesc, dp.description deliverypointdesc,
  '' productcode,'' sizecode,'' finishingmethodcode,'' deliveryschemecode,'' productdescription,null deliveryschemestartdate,0 qtydelivered,0 qtyexpected,'A' endcontract,
  languages.code languagecode, 0 detail, v.routenumber movedroutenumber, v.description movedroutedescription, st.status,
  cu.country_id customercountryid, co.description country, pl.country_id plantcountryid,
  (select sum(cdd.typeofmerchadise) from customerdeliveryday cdd where cu.customer_id = cdd.customer_id
     and coalesce((select rm.drivingday_id from route rm where rs.route_id=rm.route_id), ru.drivingday_id) = cdd.day_id
     and cdd.typeofmerchadise >= 1 and cdd.typeofmerchadise <= 2) typeofmerchadise,
  ru.route_id, coalesce(st.stoptype, 0) stoptype, rp.reportparam_id,
  coalesce(clm.showlockeronroutelist, 'N') showlockeronroutelist,
  0 putuptype_product, 0 putuptype_plpc, 0 straightevenexchange,
  0 qtydelivered_pnl, cu.delnoteforbulkputupitems
  , (select hh.starttime from deliverypointopeninghour hh
            where hh.deliverypoint_id = dp.deliverypoint_id and hh.day_id = ru.drivingday_id) del_point_start_time
  , (select hh.endtime  from deliverypointopeninghour hh
            where hh.deliverypoint_id = dp.deliverypoint_id and hh.day_id = ru.drivingday_id) del_point_end_time
             ,dp.breakstarttime breakstarttime, dp.breakendtime breakendtime
  , ru.starttime route_start_time, rs.travelminutes routestop_travelminutes, rs.serviceminutes routestop_serviceminutes
  , cu.dateactive, cu.dateinactive
  , (select to_char(hh.starttime,'fmHHfm:MI:AM') from deliverypointopeninghour hh
            where hh.deliverypoint_id = dp.deliverypoint_id and hh.day_id = ru.drivingday_id) del_point_start_timech
  , (select to_char(hh.endtime,'fmHHfm:MI:AM') from deliverypointopeninghour hh
            where hh.deliverypoint_id = dp.deliverypoint_id and hh.day_id = ru.drivingday_id) del_point_end_timech
  , to_char(dp.breakstarttime,'fmHHfm:MI:AM') breakstarttimech, to_char(dp.breakendtime,'fmHH:MI:AM') breakendtimech
  , to_char(ru.starttime,'fmHHfm:MI:AM') route_start_timech
  , to_char(ru.starttime,'fmHH24fm:MI') route_start_timech24
  , to_char(rc.starttime,'fmHHfm:MI:AM') starttimech
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, rc.plant_id
 , cast(getsubstringonlength(pl.email,0,40) as varchar2(40)) plantemail
 , (select cri.routedescription from customerrouteinfo cri where cri.customer_id = cu.customer_id) drivinginstructions
 , (select sum(v2.countContainer) from V_ROUTECONTAINERS v2 where v2.STOP_ID = st.stop_id and v2.route_id = ru.route_id) CountContainer
 , null distributionpoint_id, null numberofcolli
 , -1 internalprocessingbu_id, cu.defaultbusinessunit_id, -1 processingplant_id
from reportparam rp
     inner join routecontrol rc
           inner join route ru
                 left outer join depot d on ru.depot_id =d.depot_id
                 left outer join employee em on ru.driver_id = em.employee_id
                 left outer join truck tr on ru.truck_id = tr.truck_id
           on rc.route_id = ru.route_id
           inner join stop st
                 left outer join v_movedoutstops v on st.stop_id = v.movedtostop_id
                 left outer join contactperson cp on st.contactperson_id = cp.contactperson_id
                 left outer join routestop rs on st.routestop_id = rs.routestop_id
                 left outer join deliverypoint dp
                      inner join address ad on dp.deliveryaddress_id = ad.address_id
                 on st.deliverypoint_id = dp.deliverypoint_id
                 inner join customer cu
                       left outer join customerlockermanagement clm on cu.customer_id = clm.customer_id
                       left outer join contact cont on cont.contact_id = coalesce(f_getcontactonroutelist(cu.customer_id), -1)
                       inner join country co on cu.country_id = co.country_id
                       inner join address add2 on cu.visitaddress_id = add2.address_id
                 on st.customer_link_id = cu.customer_id
           on rc.routecontrol_id = st.routecontrol_id
           inner join plant pl on rc.plant_id = pl.plant_id
     on rp.number_value = rc.routecontrol_id
     , languages
where st.status in (0, 3, 4)
      and (nvl(rp.number_value5, -1) = -1 or (rp.number_value5 <> -1 and exists (select 1 from customeractivities ca
                                    where ca.customer_id = cu.customer_id and ca.internalprocessingbu_id = rp.number_value5)))
      and (nvl(rp.number_value6, -1) = -1 or (rp.number_value6 <> -1 and exists (select 1 from customeractivities ca, businessunit bu
                                    where ca.customer_id = cu.customer_id and ca.processbusinessunit_id = bu.businessunit_id
                                          and bu.plant_id = rp.number_value6)))
union all --4--
select v.linetype, v.routestop_id, v.drivingyear, v.drivingweek, v.notenumber, v.customer_id, v.showstop, v.routecontrol_id, v.stop_deliverypoint_id,
       v.pn_deliverypoint_id, v.plantcode, v.routenumber, v.routedescription, v.drivingdate, v.depotcode, v.depotdescription, v.loadingdock, v.starttime,
       v.drivername, v.truckcode, v.truckdescription, v.vatnumber, v.stopnumber, v.customernumber, v.customername, v.custnr, v.deliveryaddress1,
       v.deliveryaddress2, v.city, v.state, v.zipcode, v.housenumber, v.housenumberext, v.c_deliveryaddress1, v.c_deliveryaddress2, v.c_city, v.c_state,
       v.c_zipcode, v.c_housenumber, v.c_housenumberext, v.routelistinstructions, v.contactpersonname, v.contactpersonphone, v.mobilephone, v.customerphone,
       v.stop_id, v.departmentnumber, v.distributionpointnumber, v.deliverypointcode, v.departmentdesc, v.distributionpointdesc, v.deliverypointdesc,
       v.productcode, v.sizecode, v.finishingmethodcode, v.deliveryschemecode, v.productdescription, v.deliveryschemestartdate, v.qtydelivered,
       v.qtyexpected, v.endcontract, v.languagecode, v.detail, v.movedroutenumber, v.movedroutedescription, v.status, v.customercountryid, v.country,
       v.plantcountryid, v.typeofmerchadise, v.route_id, v.stoptype, v.reportparam_id, v.showlockeronroutelist, v.putuptype_product, v.putuptype_plpc,
       v.straightevenexchange, v.qtydelivered_pnl, v.delnoteforbulkputupitems, v.del_point_start_time, v.del_point_end_time, v.breakstarttime,
       v.breakendtime, v.route_start_time, v.stop_travelminutes, v.stop_serviceminutes, v.dateactive, v.dateinactive, v.del_point_start_timech,
       v.del_point_end_timech, v.breakstarttimech, v.breakendtimech, v.route_start_timech, v.route_start_timech24, v.starttimech, v.showonroutelist,
       v.contactnotes, v.contactstatus, v.plant_id, v.plantemail, v.drivinginstructions, v.countcontainer, v.distributionpoint_id, v.numberofcolli,
       v.internalprocessingbu_id, v.defaultbusinessunit_id, v.processingplant_id
from v_virtualroutes v
/

  CREATE OR REPLACE VIEW "V_ROUTELISTLST" ("LINENUMBER", "ROUTESTOP_ID", "DRIVINGYEAR", "DRIVINGWEEK", "NOTENUMBER", "CUSTOMER_ID", "SHOWSTOP", "ROUTECONTROL_ID", "STOP_DELIVERYPOINT_ID", "PN_DELIVERYPOINT_ID", "PLANTCODE", "ROUTENUMBER", "ROUTEDESCRIPTION", "DRIVINGDATE", "DEPOTCODE", "DEPOTDESCRIPTION", "LOADINGDOCK", "STARTTIME", "DRIVERNAME", "TRUCKCODE", "TRUCKDESCRIPTION", "STOPNUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "EXTRANAME1", "DELIVERYADDRESS1", "DELIVERYADDRESS2", "CITY", "STATE", "ZIPCODE", "HOUSENUMBER", "HOUSENUMBEREXT", "C_DELIVERYADDRESS1", "C_DELIVERYADDRESS2", "C_CITY", "C_STATE", "C_ZIPCODE", "C_HOUSENUMBER", "C_HOUSENUMBEREXT", "ROUTELISTINSTRUCTIONS", "CONTACTPERSONNAME", "CONTACTPERSONPHONE", "CUSTOMERPHONE", "STOP_ID", "DEPARTMENTNUMBER", "DISTRIBUTIONPOINTNUMBER", "DELIVERYPOINTCODE", "DEPARTMENTDESC", "DISTRIBUTIONPOINTDESC", "DELIVERYPOINTDESC", "PRODUCTCODE", "SIZECODE", "FINISHINGMETHODCODE", "DELIVERYSCHEMECODE", "PRODUCTDESCRIPTION", "DELIVERYSCHEMESTARTDATE", "QTYDELIVERED", "QTYEXPECTED", "ENDCONTRACT", "LANGUAGECODE", "DETAIL", "MOVEDROUTENUMBER", "MOVEDROUTEDESCRIPTION", "STATUS", "CUSTOMERCOUNTRYID", "COUNTRY", "PLANTCOUNTRYID", "TYPEOFMERCHADISE", "ROUTE_ID", "STOPTYPE", "REPORTPARAM_ID", "SHOWLOCKERONROUTELIST", "PUTUPTYPE_PRODUCT", "PUTUPTYPE_PLPC", "STRAIGHTEVENEXCHANGE", "QTYDELIVERED_PNL", "DELNOTEFORBULKPUTUPITEMS", "DEL_POINT_START_TIME", "DEL_POINT_END_TIME", "BREAKSTARTTIME", "BREAKENDTIME", "ROUTE_START_TIME", "STOP_TRAVELMINUTES", "STOP_SERVICEMINUTES", "DATEINACTIVE") AS 
  SELECT 0 LINENUMBER,
 D.ROUTESTOP_ID, GETYEAROFWEEK(A.DRIVINGDATE) DRIVINGYEAR, GETISOWEEK(A.DRIVINGDATE) DRIVINGWEEK,
 F.NOTENUMBER, P.CUSTOMER_ID,
 F_SHOW_ROUTESTOP_STD(D.STOP_ID, D.ROUTESTOP_ID, D.STOPTYPE, S.PLANT_ID) SHOWSTOP,
 A.ROUTECONTROL_ID, D.DELIVERYPOINT_ID STOP_DELIVERYPOINT_ID, N.DELIVERYPOINT_ID PN_DELIVERYPOINT_ID,
 S.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, A.DRIVINGDATE,
 C.CODE DEPOTCODE, C.DESCRIPTION DEPOTDESCRIPTION, A.LOADINGDOCK, A.STARTTIME,
 (CASE WHEN A.DRIVERNUMBER = 0 THEN X.NAME
       ELSE (SELECT EMPLOYEE.NAME FROM EMPLOYEE WHERE EMPLOYEE.EMPLOYEENUMBER = A.DRIVERNUMBER
            AND EMPLOYEE.PLANT_ID = S.PLANT_ID)
  END) DRIVERNAME,
 COALESCE (A.TRUCKCODE, Y.CODE) TRUCKCODE,
 (CASE WHEN A.TRUCKCODE IS NULL THEN Y.DESCRIPTION
       ELSE (SELECT TRUCK.DESCRIPTION FROM TRUCK WHERE TRUCK.CODE = A.TRUCKCODE
            AND TRUCK.PLANT_ID = S.PLANT_ID)
  END) TRUCKDESCRIPTION,
 D.STOPNUMBER, P.CUSTOMERNUMBER, P.NAME CUSTOMERNAME, P.Extraname1, -- add by wbo extraname1 110108
 T.STREET DELIVERYADDRESS1, T.STREET2 DELIVERYADDRESS2, T.CITY, T.STATE, T.ZIPCODE, T.HOUSENUMBER, T.HOUSENUMBEREXT,
 '' C_DELIVERYADDRESS1, '' C_DELIVERYADDRESS2, '' C_CITY, '' C_STATE, '' C_ZIPCODE, NULL C_HOUSENUMBER, NULL C_HOUSENUMBEREXT,
 D.ROUTELISTINSTRUCTIONS,
 Z.NAME CONTACTPERSONNAME, Z.PHONE CONTACTPERSONPHONE, P.PHONENO CUSTOMERPHONE, D.STOP_ID,
 O.DEPARTMENTNUMBER, M.DISTRIBUTIONPOINTNUMBER, N.CODE DELIVERYPOINTCODE,
 O.DESCRIPTION DEPARTMENTDESC, M.DESCRIPTION DISTRIBUTIONPOINTDESC, N.DESCRIPTION DELIVERYPOINTDESC,
 I.CODE PRODUCTCODE, J.CODE SIZECODE, R.CODE FINISHINGMETHODCODE, L.CODE DELIVERYSCHEMECODE,
 (SELECT DESCRIPTION FROM PRODUCT_DESC W WHERE I.PRODUCT_ID = W.PRODUCT_ID AND W.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
 H.STARTDATE DELIVERYSCHEMESTARTDATE,
 H.DELIVEREDQTY QTYDELIVERED, 0 QTYEXPECTED, 'P' ENDCONTRACT,
 LANGUAGES.CODE LANGUAGECODE, 1 DETAIL, V.ROUTENUMBER MOVEDROUTENUMBER, V.DESCRIPTION MOVEDROUTEDESCRIPTION, D.STATUS,
 P.COUNTRY_ID CUSTOMERCOUNTRYID, W.DESCRIPTION COUNTRY, S.COUNTRY_ID PLANTCOUNTRYID,
 (SELECT SUM(CDD.TYPEOFMERCHADISE) FROM CUSTOMERDELIVERYDAY CDD WHERE P.CUSTOMER_ID = CDD.CUSTOMER_ID
    AND coalesce((select rm.drivingday_id from route rm where E.Route_Id=rm.route_id), B.DRIVINGDAY_ID) = CDD.DAY_ID
    AND CDD.TYPEOFMERCHADISE >=1 AND CDD.TYPEOFMERCHADISE <=2) TYPEOFMERCHADISE,
 B.ROUTE_ID, COALESCE(D.STOPTYPE, 0) STOPTYPE, RP.REPORTPARAM_ID,
 COALESCE(CLM.SHOWLOCKERONROUTELIST, 'N') SHOWLOCKERONROUTELIST,
 I.PUTUPTYPE PUTUPTYPE_PRODUCT, G.PUTUPTYPE PUTUPTYPE_PLPC,
 ---CASE WHEN H.PACKINGNOTELINE_ID IS NULL THEN 0 ELSE 1 END
 1 STRAIGHTEVENEXCHANGE,
 G.DELIVEREDAMOUNT QTYDELIVERED_PNL, P.DELNOTEFORBULKPUTUPITEMS
 , (SELECT HH.STARTTIME FROM DELIVERYPOINTOPENINGHOUR HH
           WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_START_TIME
 , (SELECT HH.ENDTIME FROM DELIVERYPOINTOPENINGHOUR HH
           WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_END_TIME
 , N.BREAKSTARTTIME, N.BREAKENDTIME
 , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
 , P.DATEINACTIVE
FROM ROUTECONTROL A,
 ROUTE B
   LEFT OUTER JOIN DEPOT C ON (C.DEPOT_ID = B.DEPOT_ID)
   LEFT OUTER JOIN EMPLOYEE X ON (X.EMPLOYEE_ID = B.DRIVER_ID)
   LEFT OUTER JOIN TRUCK Y ON (Y.TRUCK_ID = B.TRUCK_ID),
 STOP D
   LEFT OUTER JOIN V_MOVEDOUTSTOPS V ON D.STOP_ID = V.MOVEDTOSTOP_ID-- ORDER 500713
   LEFT OUTER JOIN CONTACTPERSON Z ON D.CONTACTPERSON_ID = Z.CONTACTPERSON_ID
   LEFT OUTER JOIN ROUTESTOP E ON D.ROUTESTOP_ID = E.ROUTESTOP_ID,
 PACKINGNOTE F,
/*  PACKINGNOTELINE G
   LEFT OUTER JOIN (PACKINGNOTELINEPERDELSCHEME H
     LEFT OUTER JOIN DELIVERYSCHEME L ON H.DELIVERYSCHEME_ID = L.DELIVERYSCHEME_ID)
       ON G.PACKINGNOTELINE_ID = H.PACKINGNOTELINE_ID, */
 PACKINGNOTELINE G,
 PACKINGNOTELINEPERDELSCHEME H,
 DELIVERYSCHEME L,
 PRODUCT I,
 SIZEDEFINITION J,
 DISTRIBUTIONPOINT M, DELIVERYPOINT N, DEPARTMENT O,
 CUSTOMER P
   LEFT OUTER JOIN CUSTOMERLOCKERMANAGEMENT CLM ON (P.CUSTOMER_ID = CLM.CUSTOMER_ID),
 FINISHINGMETHOD R, PLANT S, ADDRESS T, STATUS U, LANGUAGES, COUNTRY W, REPORTPARAM RP
WHERE A.ROUTE_ID = B.ROUTE_ID AND
 A.ROUTECONTROL_ID = D.ROUTECONTROL_ID AND
 D.STOP_ID = F.STOP_ID AND
 F.PACKINGNOTE_ID = G.PACKINGNOTE_ID AND
 G.PRODUCT_ID = I.PRODUCT_ID AND
 G.SIZEDEFINITION_ID = J.SIZEDEFINITION_ID AND
 F.DISTRIBUTIONPOINT_ID = M.DISTRIBUTIONPOINT_ID AND
 F.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND
 M.DEPARTMENT_ID = O.DEPARTMENT_ID AND
 D.CUSTOMER_LINK_ID = P.CUSTOMER_ID AND
 G.FINISHINGMETHOD_ID = R.FINISHINGMETHOD_ID AND
 A.PLANT_ID = S.PLANT_ID AND
 N.DELIVERYADDRESS_ID = T.ADDRESS_ID AND
 F.STATUS_ID = U.STATUS_ID AND
 U.STATUSTYPE = 'PN' AND
 U.CODE <> '40' AND
 (D.STATUS IN (0, 3, 4) ) AND
 P.COUNTRY_ID = W.COUNTRY_ID AND
 RP.NUMBER_VALUE = A.ROUTECONTROL_ID AND
 G.PACKINGNOTELINE_ID = H.PACKINGNOTELINE_ID AND
 H.DELIVERYSCHEME_ID = L.DELIVERYSCHEME_ID
UNION ALL -- 1 --            NON-STRAIGHT EVEN EXCHANGE ITEMS
SELECT 1 LINENUMBER,
 D.ROUTESTOP_ID, GETYEAROFWEEK(A.DRIVINGDATE) DRIVINGYEAR, GETISOWEEK(A.DRIVINGDATE) DRIVINGWEEK,
 F.NOTENUMBER, P.CUSTOMER_ID,
 F_SHOW_ROUTESTOP_STD(D.STOP_ID, D.ROUTESTOP_ID, D.STOPTYPE, S.PLANT_ID) SHOWSTOP,
 A.ROUTECONTROL_ID, D.DELIVERYPOINT_ID STOP_DELIVERYPOINT_ID, N.DELIVERYPOINT_ID PN_DELIVERYPOINT_ID,
 S.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, A.DRIVINGDATE,
 C.CODE DEPOTCODE, C.DESCRIPTION DEPOTDESCRIPTION, A.LOADINGDOCK, A.STARTTIME,
 (CASE WHEN A.DRIVERNUMBER = 0 THEN X.NAME
       ELSE (SELECT EMPLOYEE.NAME FROM EMPLOYEE WHERE EMPLOYEE.EMPLOYEENUMBER = A.DRIVERNUMBER
            AND EMPLOYEE.PLANT_ID = S.PLANT_ID)
  END) DRIVERNAME,
 COALESCE (A.TRUCKCODE, Y.CODE) TRUCKCODE,
 (CASE WHEN A.TRUCKCODE IS NULL THEN Y.DESCRIPTION
       ELSE (SELECT TRUCK.DESCRIPTION FROM TRUCK WHERE TRUCK.CODE = A.TRUCKCODE
            AND TRUCK.PLANT_ID = S.PLANT_ID)
  END) TRUCKDESCRIPTION,
 D.STOPNUMBER, P.CUSTOMERNUMBER, P.NAME CUSTOMERNAME, P.Extraname1, -- add by wbo extraname1 110108
 T.STREET DELIVERYADDRESS1, T.STREET2 DELIVERYADDRESS2, T.CITY, T.STATE, T.ZIPCODE, T.HOUSENUMBER, T.HOUSENUMBEREXT,
 '' C_DELIVERYADDRESS1, '' C_DELIVERYADDRESS2, '' C_CITY, '' C_STATE, '' C_ZIPCODE, NULL C_HOUSENUMBER, NULL C_HOUSENUMBEREXT,
 D.ROUTELISTINSTRUCTIONS,
 Z.NAME CONTACTPERSONNAME, Z.PHONE CONTACTPERSONPHONE, P.PHONENO CUSTOMERPHONE, D.STOP_ID,
 O.DEPARTMENTNUMBER, M.DISTRIBUTIONPOINTNUMBER, N.CODE DELIVERYPOINTCODE,
 O.DESCRIPTION DEPARTMENTDESC, M.DESCRIPTION DISTRIBUTIONPOINTDESC, N.DESCRIPTION DELIVERYPOINTDESC,
 I.CODE PRODUCTCODE, J.CODE SIZECODE, R.CODE FINISHINGMETHODCODE, L.CODE DELIVERYSCHEMECODE,
 (SELECT DESCRIPTION FROM PRODUCT_DESC W WHERE I.PRODUCT_ID = W.PRODUCT_ID AND W.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
 H.STARTDATE DELIVERYSCHEMESTARTDATE,
 H.DELIVEREDQTY QTYDELIVERED, 0 QTYEXPECTED, 'P' ENDCONTRACT,
 LANGUAGES.CODE LANGUAGECODE, 1 DETAIL, V.ROUTENUMBER MOVEDROUTENUMBER, V.DESCRIPTION MOVEDROUTEDESCRIPTION, D.STATUS,
 P.COUNTRY_ID CUSTOMERCOUNTRYID, W.DESCRIPTION COUNTRY, S.COUNTRY_ID PLANTCOUNTRYID,
 (SELECT SUM(CDD.TYPEOFMERCHADISE) FROM CUSTOMERDELIVERYDAY CDD WHERE P.CUSTOMER_ID = CDD.CUSTOMER_ID
    AND coalesce((select rm.drivingday_id from route rm where E.Route_Id=rm.route_id), B.DRIVINGDAY_ID) = CDD.DAY_ID
    AND CDD.TYPEOFMERCHADISE >=1 AND CDD.TYPEOFMERCHADISE <=2) TYPEOFMERCHADISE,
 B.ROUTE_ID, COALESCE(D.STOPTYPE, 0) STOPTYPE, RP.REPORTPARAM_ID,
 COALESCE(CLM.SHOWLOCKERONROUTELIST, 'N') SHOWLOCKERONROUTELIST,
 I.PUTUPTYPE PUTUPTYPE_PRODUCT, G.PUTUPTYPE PUTUPTYPE_PLPC,
 --CASE WHEN H.PACKINGNOTELINE_ID IS NOT NULL THEN 0 ELSE 1 END STRAIGHTEVENEXCHANGE,
 1 STRAIGHTEVENEXCHANGE,
 G.DELIVEREDAMOUNT QTYDELIVERED_PNL, P.DELNOTEFORBULKPUTUPITEMS
 , (SELECT HH.STARTTIME FROM DELIVERYPOINTOPENINGHOUR HH
           WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_START_TIME
 , (SELECT HH.ENDTIME FROM DELIVERYPOINTOPENINGHOUR HH
           WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_END_TIME
 , N.BREAKSTARTTIME, N.BREAKENDTIME
 , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
 , P.DATEINACTIVE
FROM ROUTECONTROL A,
 ROUTE B
   LEFT OUTER JOIN DEPOT C ON (C.DEPOT_ID = B.DEPOT_ID)
   LEFT OUTER JOIN EMPLOYEE X ON (X.EMPLOYEE_ID = B.DRIVER_ID)
   LEFT OUTER JOIN TRUCK Y ON (Y.TRUCK_ID = B.TRUCK_ID),
 STOP D
   LEFT OUTER JOIN CONTACTPERSON Z ON D.CONTACTPERSON_ID = Z.CONTACTPERSON_ID
   LEFT OUTER JOIN V_MOVEDOUTSTOPS V ON D.STOP_ID = V.MOVEDTOSTOP_ID-- ORDER 500713
   LEFT OUTER JOIN ROUTESTOP E ON D.ROUTESTOP_ID = E.ROUTESTOP_ID,
 PACKINGNOTE F,
 PACKINGNOTELINE G,
   --LEFT OUTER JOIN (
   PNLINEPERDELSCHEMENONSEE H,
     --LEFT OUTER JOIN
     DELIVERYSCHEME L,-- ON H.DELIVERYSCHEME_ID = L.DELIVERYSCHEME_ID)
     --  ON G.PACKINGNOTELINE_ID = H.PACKINGNOTELINE_ID,
 PRODUCT I,
 SIZEDEFINITION J,
 DISTRIBUTIONPOINT M, DELIVERYPOINT N, DEPARTMENT O,
 CUSTOMER P
   LEFT OUTER JOIN CUSTOMERLOCKERMANAGEMENT CLM ON (P.CUSTOMER_ID = CLM.CUSTOMER_ID),
 FINISHINGMETHOD R, PLANT S, ADDRESS T, STATUS U, LANGUAGES, COUNTRY W, REPORTPARAM RP
WHERE A.ROUTE_ID = B.ROUTE_ID AND
 A.ROUTECONTROL_ID = D.ROUTECONTROL_ID AND
 D.STOP_ID = F.STOP_ID AND
 F.PACKINGNOTE_ID = G.PACKINGNOTE_ID AND
 G.PRODUCT_ID = I.PRODUCT_ID AND
 G.SIZEDEFINITION_ID = J.SIZEDEFINITION_ID AND
 F.DISTRIBUTIONPOINT_ID = M.DISTRIBUTIONPOINT_ID AND
 F.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND
 M.DEPARTMENT_ID = O.DEPARTMENT_ID AND
 D.CUSTOMER_LINK_ID = P.CUSTOMER_ID AND
 G.FINISHINGMETHOD_ID = R.FINISHINGMETHOD_ID AND
 A.PLANT_ID = S.PLANT_ID AND
 N.DELIVERYADDRESS_ID = T.ADDRESS_ID AND
 F.STATUS_ID = U.STATUS_ID AND
 U.STATUSTYPE = 'PN' AND
 U.CODE <> '40'AND
 (D.STATUS IN (0, 3, 4) )
 AND P.COUNTRY_ID = W.COUNTRY_ID
 AND RP.NUMBER_VALUE = A.ROUTECONTROL_ID
 AND H.DELIVERYSCHEME_ID = L.DELIVERYSCHEME_ID--
 AND G.PACKINGNOTELINE_ID = H.PACKINGNOTELINE_ID---
 /*AND NOT EXISTS (SELECT 1
                 FROM PACKINGNOTELINEPERDELSCHEME PNLDS
                 WHERE PNLDS.PACKINGNOTELINE_ID = G.PACKINGNOTELINE_ID)*/
UNION ALL          -- 2 --
SELECT 2 LINENUMBER,
 D.ROUTESTOP_ID, GETYEAROFWEEK(A.DRIVINGDATE) DRIVINGYEAR, GETISOWEEK(A.DRIVINGDATE) DRIVINGWEEK,
 0 NOTENUMBER, P.CUSTOMER_ID,
 F_SHOW_ROUTESTOP_STD(D.STOP_ID, D.ROUTESTOP_ID, D.STOPTYPE, S.PLANT_ID) SHOWSTOP,
 A.ROUTECONTROL_ID, D.DELIVERYPOINT_ID STOPDELIVERYPOINT_ID, N.DELIVERYPOINT_ID PN_DELIVERYPOINT_ID,
 S.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, A.DRIVINGDATE,
 C.CODE DEPOTCODE, C.DESCRIPTION DEPOTDESCRIPTION, A.LOADINGDOCK, A.STARTTIME,
 (CASE WHEN A.DRIVERNUMBER = 0 THEN X.NAME
       ELSE (SELECT EMPLOYEE.NAME FROM EMPLOYEE WHERE EMPLOYEE.EMPLOYEENUMBER = A.DRIVERNUMBER
            AND EMPLOYEE.PLANT_ID = S.PLANT_ID)
  END) DRIVERNAME,
 COALESCE (A.TRUCKCODE, Y.CODE) TRUCKCODE,
 (CASE WHEN A.TRUCKCODE IS NULL THEN Y.DESCRIPTION
       ELSE (SELECT TRUCK.DESCRIPTION FROM TRUCK WHERE TRUCK.CODE = A.TRUCKCODE
            AND TRUCK.PLANT_ID = S.PLANT_ID)
  END) TRUCKDESCRIPTION,
 D.STOPNUMBER, P.CUSTOMERNUMBER, P.NAME CUSTOMERNAME, P.Extraname1, -- add by wbo extraname1 110108
 T.STREET DELIVERYADDRESS1, T.STREET2 DELIVERYADDRESS2, T.CITY, T.STATE, T.ZIPCODE, T.HOUSENUMBER, T.HOUSENUMBEREXT,
 '' C_DELIVERYADDRESS1, '' C_DELIVERYADDRESS2, '' C_CITY, '' C_STATE, '' C_ZIPCODE, NULL C_HOUSENUMBER, NULL C_HOUSENUMBEREXT,
 D.ROUTELISTINSTRUCTIONS,
 Z.NAME CONTACTPERSONNAME, Z.PHONE CONTACTPERSONPHONE, P.PHONENO CUSTOMERPHONE,  D.STOP_ID,
 O.DEPARTMENTNUMBER, M.DISTRIBUTIONPOINTNUMBER, N.CODE DELIVERYPOINTCODE,
 O.DESCRIPTION DEPARTMENTDESC, M.DESCRIPTION DISTRIBUTIONPOINTDESC, N.DESCRIPTION DELIVERYPOINTDESC,
 I.CODE PRODUCTCODE, J.CODE SIZECODE, R.CODE FINISHINGMETHODCODE, L.CODE DELIVERYSCHEMECODE,
 (SELECT DESCRIPTION FROM PRODUCT_DESC W WHERE I.PRODUCT_ID = W.PRODUCT_ID AND W.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
 NULL DELIVERYSCHEMESTARTDATE,
 0 QTYDELIVERED, K.QTYEXPECTED QTYEXPECTED, K.ENDCONTRACT,
 LANGUAGES.CODE LANGUAGECODE, 1 DETAIL, V.ROUTENUMBER MOVEDROUTENUMBER, V.DESCRIPTION MOVEDROUTEDESCRIPTION, D.STATUS,
 P.COUNTRY_ID CUSTOMERCOUNTRYID, W.DESCRIPTION COUNTRY, S.COUNTRY_ID PLANTCOUNTRYID,
 (SELECT SUM(CDD.TYPEOFMERCHADISE) FROM CUSTOMERDELIVERYDAY CDD WHERE P.CUSTOMER_ID = CDD.CUSTOMER_ID
    AND coalesce((select rm.drivingday_id from route rm where E.Route_Id=rm.route_id), B.DRIVINGDAY_ID) = CDD.DAY_ID
    AND CDD.TYPEOFMERCHADISE >=1 AND CDD.TYPEOFMERCHADISE <=2) TYPEOFMERCHADISE,
 B.ROUTE_ID, COALESCE(D.STOPTYPE, 0) STOPTYPE, RP.REPORTPARAM_ID,
 COALESCE(CLM.SHOWLOCKERONROUTELIST, 'N') SHOWLOCKERONROUTELIST,
 I.PUTUPTYPE PUTUPTYPE_PRODUCT, 0 PUTUPTYPE_PLPC, 1 STRAIGHTEVENEXCHANGE,
 0 QTYDELIVERED_PNL, P.DELNOTEFORBULKPUTUPITEMS
 , (SELECT HH.STARTTIME FROM DELIVERYPOINTOPENINGHOUR HH
           WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_START_TIME
 , (SELECT HH.ENDTIME FROM DELIVERYPOINTOPENINGHOUR HH
           WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_END_TIME
 , N.BREAKSTARTTIME , N.BREAKENDTIME
 , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
 , P.DATEINACTIVE
FROM ROUTECONTROL A,
 ROUTE B
   LEFT OUTER JOIN DEPOT C ON (C.DEPOT_ID = B.DEPOT_ID)
   LEFT OUTER JOIN EMPLOYEE X ON (X.EMPLOYEE_ID = B.DRIVER_ID)
   LEFT OUTER JOIN TRUCK Y ON (Y.TRUCK_ID = B.TRUCK_ID),
 STOP D
   LEFT OUTER JOIN CONTACTPERSON Z ON D.CONTACTPERSON_ID = Z.CONTACTPERSON_ID
   LEFT OUTER JOIN V_MOVEDOUTSTOPS V ON D.STOP_ID = V.MOVEDTOSTOP_ID-- ORDER500701
   LEFT OUTER JOIN ROUTESTOP E ON D.ROUTESTOP_ID = E.ROUTESTOP_ID,
 STRAIGHTEVENRETURN K, PRODUCT I, SIZEDEFINITION J, DELIVERYSCHEME L,
 DISTRIBUTIONPOINT M, DELIVERYPOINT N, DEPARTMENT O,
 CUSTOMER P
   LEFT OUTER JOIN CUSTOMERLOCKERMANAGEMENT CLM ON (P.CUSTOMER_ID = CLM.CUSTOMER_ID),
 FINISHINGMETHOD R, PLANT S, ADDRESS T, STATUS U, LANGUAGES, COUNTRY W, REPORTPARAM RP
WHERE A.ROUTE_ID = B.ROUTE_ID AND
 A.ROUTECONTROL_ID = D.ROUTECONTROL_ID AND
 D.STOP_ID = K.STOP_ID AND
 K.PRODUCT_ID = I.PRODUCT_ID AND
 K.SIZEDEFINITION_ID = J.SIZEDEFINITION_ID AND
 K.DELIVERYSCHEME_ID = L.DELIVERYSCHEME_ID AND
 K.DISTRIBUTIONPOINT_ID = M.DISTRIBUTIONPOINT_ID AND
 M.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND
 M.DEPARTMENT_ID = O.DEPARTMENT_ID AND
 D.CUSTOMER_LINK_ID = P.CUSTOMER_ID AND
 K.FINISHINGMETHOD_ID = R.FINISHINGMETHOD_ID AND
 A.PLANT_ID = S.PLANT_ID AND
 N.DELIVERYADDRESS_ID = T.ADDRESS_ID AND
 K.STATUS_ID = U.STATUS_ID AND
 U.STATUSTYPE = 'SR' AND
 U.CODE <> '30' AND
 (D.STATUS IN (0, 3, 4) )
 AND P.COUNTRY_ID = W.COUNTRY_ID
AND RP.NUMBER_VALUE = A.ROUTECONTROL_ID
UNION ALL             -- 3 --
SELECT 3 LINENUMBER,
 D.ROUTESTOP_ID, GETYEAROFWEEK(A.DRIVINGDATE) DRIVINGYEAR, GETISOWEEK(A.DRIVINGDATE) DRIVINGWEEK,
 0 NOTENUMBER, P.CUSTOMER_ID,
 F_SHOW_ROUTESTOP_STD(D.STOP_ID, D.ROUTESTOP_ID, D.STOPTYPE, S.PLANT_ID) SHOWSTOP,
 A.ROUTECONTROL_ID, D.DELIVERYPOINT_ID STOPDELIVERYPOINT_ID, 0 PN_DELIVERYPOINT_ID,
 S.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, A.DRIVINGDATE,
 C.CODE DEPOTCODE, C.DESCRIPTION DEPOTDESCRIPTION, A.LOADINGDOCK, A.STARTTIME,
 (CASE WHEN A.DRIVERNUMBER = 0 THEN X.NAME
       ELSE (SELECT EMPLOYEE.NAME FROM EMPLOYEE WHERE EMPLOYEE.EMPLOYEENUMBER = A.DRIVERNUMBER
            AND EMPLOYEE.PLANT_ID = S.PLANT_ID)
  END) DRIVERNAME,
 COALESCE (A.TRUCKCODE, Y.CODE) TRUCKCODE,
 (CASE WHEN A.TRUCKCODE IS NULL THEN Y.DESCRIPTION
       ELSE (SELECT TRUCK.DESCRIPTION FROM TRUCK WHERE TRUCK.CODE = A.TRUCKCODE
            AND TRUCK.PLANT_ID = S.PLANT_ID)
  END) TRUCKDESCRIPTION,
 D.STOPNUMBER, P.CUSTOMERNUMBER, P.NAME CUSTOMERNAME,  P.Extraname1, -- add by wbo extraname1 110108
 T.STREET DELIVERYADDRESS1, T.STREET2 DELIVERYADDRESS2, T.CITY, T.STATE, T.ZIPCODE, T.HOUSENUMBER, T.HOUSENUMBEREXT,
 T2.STREET C_DELIVERYADDRESS1, T2.STREET2 C_DELIVERYADDRESS2, T2.CITY C_CITY, T2.STATE C_STATE, T2.ZIPCODE C_ZIPCODE,
 T2.HOUSENUMBER C_HOUSENUMBER, T2.HOUSENUMBEREXT C_HOUSENUMBEREXT,
 D.ROUTELISTINSTRUCTIONS,
 Z.NAME CONTACTPERSONNAME, Z.PHONE CONTACTPERSONPHONE, P.PHONENO CUSTOMERPHONE, D.STOP_ID,
 -1 DEPARTMENTNUMBER, -1 DISTRIBUTIONPOINTNUMBER, DP.CODE DELIVERYPOINTCODE,
 '' DEPARTMENTDESC, '' DISTRIBUTIONPOINTDESC, DP.DESCRIPTION DELIVERYPOINTDESC,
 '' PRODUCTCODE,'' SIZECODE,'' FINISHINGMETHODCODE,'' DELIVERYSCHEMECODE,'' PRODUCTDESCRIPTION,NULL DELIVERYSCHEMESTARTDATE,0 QTYDELIVERED,0 QTYEXPECTED,'A' ENDCONTRACT,
 LANGUAGES.CODE LANGUAGECODE, 0 DETAIL, V.ROUTENUMBER MOVEDROUTENUMBER, V.DESCRIPTION MOVEDROUTEDESCRIPTION, D.STATUS,
 P.COUNTRY_ID CUSTOMERCOUNTRYID, W.DESCRIPTION COUNTRY, S.COUNTRY_ID PLANTCOUNTRYID,
 (SELECT SUM(CDD.TYPEOFMERCHADISE) FROM CUSTOMERDELIVERYDAY CDD WHERE P.CUSTOMER_ID = CDD.CUSTOMER_ID
    AND coalesce((select rm.drivingday_id from route rm where E.Route_Id=rm.route_id), B.DRIVINGDAY_ID) = CDD.DAY_ID
    AND CDD.TYPEOFMERCHADISE >=1 AND CDD.TYPEOFMERCHADISE <=2) TYPEOFMERCHADISE,
 B.ROUTE_ID, COALESCE(D.STOPTYPE, 0) STOPTYPE, RP.REPORTPARAM_ID,
 COALESCE(CLM.SHOWLOCKERONROUTELIST, 'N') SHOWLOCKERONROUTELIST,
 0 PUTUPTYPE_PRODUCT, 0 PUTUPTYPE_PLPC, 0 STRAIGHTEVENEXCHANGE,
 0 QTYDELIVERED_PNL, P.DELNOTEFORBULKPUTUPITEMS
 , (SELECT HH.STARTTIME FROM DELIVERYPOINTOPENINGHOUR HH
           WHERE HH.DELIVERYPOINT_ID = DP.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_START_TIME
 , (SELECT HH.ENDTIME FROM DELIVERYPOINTOPENINGHOUR HH
           WHERE HH.DELIVERYPOINT_ID = DP.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_END_TIME
 , DP.BREAKSTARTTIME , DP.BREAKENDTIME
 , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES ROUTESTOP_TRAVELMINUTES, E.SERVICEMINUTES ROUTESTOP_SERVICEMINUTES
 , P.DATEINACTIVE
FROM ROUTECONTROL A,
 ROUTE B
   LEFT OUTER JOIN DEPOT C ON (C.DEPOT_ID = B.DEPOT_ID)
   LEFT OUTER JOIN EMPLOYEE X ON (X.EMPLOYEE_ID = B.DRIVER_ID)
   LEFT OUTER JOIN TRUCK Y ON (Y.TRUCK_ID = B.TRUCK_ID),
 STOP D
   LEFT OUTER JOIN CONTACTPERSON Z ON D.CONTACTPERSON_ID = Z.CONTACTPERSON_ID
   LEFT OUTER JOIN DELIVERYPOINT DP LEFT OUTER JOIN ADDRESS T ON DP.DELIVERYADDRESS_ID = T.ADDRESS_ID
                   ON D.DELIVERYPOINT_ID = DP.DELIVERYPOINT_ID
   LEFT OUTER JOIN V_MOVEDOUTSTOPS V ON D.STOP_ID = V.MOVEDTOSTOP_ID
   LEFT OUTER JOIN ROUTESTOP E ON D.ROUTESTOP_ID = E.ROUTESTOP_ID,
 CUSTOMER P
   LEFT OUTER JOIN CUSTOMERLOCKERMANAGEMENT CLM ON (P.CUSTOMER_ID = CLM.CUSTOMER_ID),
 PLANT S,
 LANGUAGES, ADDRESS T2, COUNTRY W, REPORTPARAM RP
WHERE A.ROUTE_ID = B.ROUTE_ID AND
 A.ROUTECONTROL_ID = D.ROUTECONTROL_ID AND
 D.CUSTOMER_LINK_ID = P.CUSTOMER_ID AND
 P.VISITADDRESS_ID = T2.ADDRESS_ID AND
 A.PLANT_ID = S.PLANT_ID AND
 D.ROUTECONTROL_ID = A.ROUTECONTROL_ID AND
 (D.STATUS IN (0, 3, 4) )
 AND P.COUNTRY_ID = W.COUNTRY_ID
 AND RP.NUMBER_VALUE = A.ROUTECONTROL_ID
/

  CREATE OR REPLACE VIEW "V_ROUTELISTNLI" ("ISLINENDELIVERY", "IS_DELIVERY", "PLANTNAME", "ROUTECONTROL_ID", "STOP_DELIVERYPOINT_ID", "PN_DELIVERYPOINT_ID", "PLANTCODE", "ROUTENUMBER", "ROUTEDESCRIPTION", "DRIVINGDATE", "DEPOTCODE", "DEPOTDESCRIPTION", "LOADINGDOCK", "STARTTIME", "DRIVERNAME", "TRUCKCODE", "TRUCKDESCRIPTION", "STOPNUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "DELIVERYADDRESS1", "DELIVERYADDRESS2", "CITY", "STATE", "ZIPCODE", "C_DELIVERYADDRESS1", "C_DELIVERYADDRESS2", "C_CITY", "C_STATE", "C_ZIPCODE", "ROUTELISTINSTRUCTIONS", "CONTACTPERSONNAME", "CONTACTPERSONPHONE", "CUSTOMERPHONE", "STOP_ID", "DEPARTMENTNUMBER", "DISTRIBUTIONPOINTNUMBER", "DELIVERYPOINTCODE", "DEPARTMENTDESC", "DISTRIBUTIONPOINTDESC", "DELIVERYPOINTDESC", "PRODUCTCODE", "SIZECODE", "FINISHINGMETHODCODE", "DELIVERYSCHEMECODE", "PRODUCTDESCRIPTION", "DELIVERYSCHEMESTARTDATE", "QTYDELIVERED", "QTYEXPECTED", "ENDCONTRACT", "LANGUAGECODE", "SHOW_DELIVERYNOTE", "DETAIL", "MOVEDROUTENUMBER", "MOVEDROUTEDESCRIPTION", "STATUS", "CUSTOMERCOUNTRYID", "COUNTRY", "PLANTCOUNTRYID", "TYPEOFMERCHADISE", "ROUTE_ID", "STOPTYPE", "REPORTPARAM_ID", "GARMENTSTYPE", "PRODUCTGROUPCODE") AS 
  SELECT  -- 1 --
  (select count(*)
     from packingnote pn, packingnoteline pnl, product p, productgroup pg
     where pn.stop_id = d.stop_id
       and pn.packingnote_id = pnl.packingnote_id
       and pnl.product_id = p.product_id
       and p.productgroup_id = pg.productgroup_id
       and pg.code >= '310'
       and pg.code <= '340') islinendelivery,
  F_SHOW_ROUTESTOP(d.stop_id, d.routestop_id, s.plant_id) is_delivery,
  S.NAME PLANTNAME,
  A.ROUTECONTROL_ID, D.DELIVERYPOINT_ID STOP_DELIVERYPOINT_ID, N.DELIVERYPOINT_ID PN_DELIVERYPOINT_ID,
  S.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, A.DRIVINGDATE,
  C.CODE DEPOTCODE, C.DESCRIPTION DEPOTDESCRIPTION, A.LOADINGDOCK, A.STARTTIME,
  X.NAME DRIVERNAME, Y.CODE TRUCKCODE, Y.DESCRIPTION TRUCKDESCRIPTION,
  D.STOPNUMBER, P.CUSTOMERNUMBER, P.NAME CUSTOMERNAME,
  T.STREET DELIVERYADDRESS1, T.STREET2 DELIVERYADDRESS2, T.CITY, T.STATE, T.ZIPCODE,
  '' C_DELIVERYADDRESS1, '' C_DELIVERYADDRESS2, '' C_CITY, '' C_STATE, '' C_ZIPCODE,
  case when d.routestop_id is null then d.routelistinstructions else E.ROUTELISTINSTRUCTIONS end ROUTELISTINSTRUCTIONS,
  Z.NAME CONTACTPERSONNAME, Z.PHONE CONTACTPERSONPHONE, P.PHONENO CUSTOMERPHONE, D.STOP_ID,
  O.DEPARTMENTNUMBER, M.DISTRIBUTIONPOINTNUMBER, N.CODE DELIVERYPOINTCODE,
  O.DESCRIPTION DEPARTMENTDESC, M.DESCRIPTION DISTRIBUTIONPOINTDESC, N.DESCRIPTION DELIVERYPOINTDESC,
  I.CODE PRODUCTCODE, J.CODE SIZECODE, R.CODE FINISHINGMETHODCODE, '' DELIVERYSCHEMECODE,
  (SELECT description FROM PRODUCT_DESC W WHERE I.PRODUCT_ID = W.PRODUCT_ID AND W.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
  NULL DELIVERYSCHEMESTARTDATE, G.TOBEDELIVEREDAMOUNT QTYDELIVERED, 0 QTYEXPECTED, 'P' endcontract,
  LANGUAGES.CODE LANGUAGECODE,
  (select count(pn1.stop_id) from packingnote pn1 where pn1.stop_id = d.stop_id) show_deliverynote,
  1 detail,
  V.routenumber movedroutenumber, V.description movedroutedescription, d.status,
  P.COUNTRY_ID CUSTOMERCOUNTRYID, W.DESCRIPTION COUNTRY, S.COUNTRY_ID PLANTCOUNTRYID,
  (select sum(cdd.typeofmerchadise) from CUSTOMERDELIVERYDAY CDD where P.CUSTOMER_ID = CDD.CUSTOMER_ID
     AND coalesce((select rm.drivingday_id from route rm where E.Route_Id=rm.route_id), B.DRIVINGDAY_ID) = CDD.DAY_ID
     and cdd.typeofmerchadise >= 1 and cdd.typeofmerchadise <= 2) typeofmerchadise,
  B.ROUTE_ID, coalesce(d.stoptype, 0) stoptype, rp.reportparam_id, I.TYPEOFMERCHANDISE garmentstype,
  prg.code productgroupcode
FROM ROUTECONTROL A,
  ROUTE B
    left outer join DEPOT C ON (C.DEPOT_ID = B.DEPOT_ID)
    left outer join EMPLOYEE X ON (X.EMPLOYEE_ID = B.DRIVER_ID)
    left outer join TRUCK Y ON (Y.TRUCK_ID = B.TRUCK_ID),
  STOP D
    left outer join V_MOVEDOUTSTOPS V on D.STOP_ID = V.movedtostop_id-- order 500713
    left outer join CONTACTPERSON Z ON D.CONTACTPERSON_ID = Z.CONTACTPERSON_ID
    left outer join ROUTESTOP E ON D.ROUTESTOP_ID = E.ROUTESTOP_ID,
  PACKINGNOTE F,
  PACKINGNOTELINE G,
  PRODUCT I, productgroup prg,
  SIZEDEFINITION J,
  DISTRIBUTIONPOINT M, DELIVERYPOINT N, DEPARTMENT O,
  CUSTOMER P, FINISHINGMETHOD R, PLANT S, ADDRESS T,
  LANGUAGES, COUNTRY W, reportparam rp
WHERE A.ROUTE_ID = B.ROUTE_ID AND
  A.ROUTECONTROL_ID = D.ROUTECONTROL_ID AND
  D.STOP_ID = F.STOP_ID AND
  F.PACKINGNOTE_ID = G.PACKINGNOTE_ID AND
  G.PRODUCT_ID = I.PRODUCT_ID AND
  G.SIZEDEFINITION_ID = J.SIZEDEFINITION_ID AND
  F.DISTRIBUTIONPOINT_ID = M.DISTRIBUTIONPOINT_ID AND
  F.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND
  M.DEPARTMENT_ID = O.DEPARTMENT_ID AND
  D.CUSTOMER_LINK_ID = P.CUSTOMER_ID AND
  G.FINISHINGMETHOD_ID = R.FINISHINGMETHOD_ID AND
  A.PLANT_ID = S.PLANT_ID AND
  N.DELIVERYADDRESS_ID = T.ADDRESS_ID AND
  (d.status = 0 or d.status = 3)--TNE order500701
  AND P.COUNTRY_ID = W.COUNTRY_ID --TNE ORDER 500713
  and rp.NUMBER_VALUE = a.ROUTECONTROL_ID
--  and I.CODE like 'HYG%'
--  and I.TYPEOFMERCHANDISE <> 2 -- Bog todo 3901
  and i.productgroup_id = prg.productgroup_id
  and I.TYPEOFMERCHANDISE <> 2 and prg.code in ('011', '021', '031', '032', '033', '034', '041', '101', '405', '412', '422', '437', '442', '452', '460', '472') -- only this hygiene
  and (d.stoptype is null or d.stoptype in (2, 3)) -- show only this reoutestops
UNION ALL             -- 2 --
SELECT
  (select count(*)
      from packingnote pn, packingnoteline pnl, product p, productgroup pg
      where pn.stop_id = d.stop_id
        and pn.packingnote_id = pnl.packingnote_id
        and pnl.product_id = p.product_id
        and p.productgroup_id = pg.productgroup_id
        and pg.code >= '310'
        and pg.code <= '340') islinendelivery,
  F_SHOW_ROUTESTOP(d.stop_id, d.routestop_id, s.plant_id) is_delivery,
  S.NAME PLANTNAME,
  A.ROUTECONTROL_ID, D.DELIVERYPOINT_ID STOPDELIVERYPOINT_ID, 0 PN_DELIVERYPOINT_ID,
  S.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, A.DRIVINGDATE,
  C.CODE DEPOTCODE, C.DESCRIPTION DEPOTDESCRIPTION, A.LOADINGDOCK, A.STARTTIME,
  X.NAME DRIVERNAME, Y.CODE TRUCKCODE, Y.DESCRIPTION TRUCKDESCRIPTION,
  D.STOPNUMBER, P.CUSTOMERNUMBER, P.NAME CUSTOMERNAME,
  T.STREET DELIVERYADDRESS1, T.STREET2 DELIVERYADDRESS2, T.CITY, T.STATE, T.ZIPCODE,
  T2.STREET C_DELIVERYADDRESS1, T2.STREET2 C_DELIVERYADDRESS2, T2.CITY C_CITY, T2.STATE C_STATE, T2.ZIPCODE C_ZIPCODE,
case when d.routestop_id is null then d.routelistinstructions else E.ROUTELISTINSTRUCTIONS end ROUTELISTINSTRUCTIONS,
  Z.NAME CONTACTPERSONNAME, Z.PHONE CONTACTPERSONPHONE, P.PHONENO CUSTOMERPHONE, D.STOP_ID,
  -1 departmentnumber, -1 distributionpointnumber, dp.code deliverypointcode,
  '' departmentdesc, '' DISTRIBUTIONPOINTDESC, '' DELIVERYPOINTDESC,
  '' PRODUCTCODE,'' SIZECODE,'' FINISHINGMETHODCODE,'' DELIVERYSCHEMECODE,'' PRODUCTDESCRIPTION,null deliveryschemestartdate,0 QTYDELIVERED,0 QTYEXPECTED,'A' endcontract,
  LANGUAGES.CODE LANGUAGECODE,
  (select count(pn1.stop_id) from packingnote pn1 where pn1.stop_id = d.stop_id) show_deliverynote,
  0 detail,
  V.routenumber movedroutenumber, V.description movedroutedescription, d.status,
  P.COUNTRY_ID CUSTOMERCOUNTRYID, W.DESCRIPTION COUNTRY, S.COUNTRY_ID PLANTCOUNTRYID,
  (select sum(cdd.typeofmerchadise) from CUSTOMERDELIVERYDAY CDD where P.CUSTOMER_ID = CDD.CUSTOMER_ID
     AND coalesce((select rm.drivingday_id from route rm where E.Route_Id=rm.route_id), B.DRIVINGDAY_ID) = CDD.DAY_ID
     and cdd.typeofmerchadise >=1 and cdd.typeofmerchadise <=2) typeofmerchadise, --
  B.ROUTE_ID, coalesce(d.stoptype, 0) stoptype, rp.reportparam_id, 2 garmentstype,
  '' productgroupcode
FROM ROUTECONTROL A,
  ROUTE B
    left outer join DEPOT C ON (C.DEPOT_ID = B.DEPOT_ID)
    left outer join EMPLOYEE X ON (X.EMPLOYEE_ID = B.DRIVER_ID)
    left outer join TRUCK Y ON (Y.TRUCK_ID = B.TRUCK_ID),
  STOP D
    left outer join V_MOVEDOUTSTOPS V on D.STOP_ID = V.movedtostop_id-- order500701
    left outer join CONTACTPERSON Z ON D.CONTACTPERSON_ID = Z.CONTACTPERSON_ID
    left outer join DELIVERYPOINT DP LEFT OUTER JOIN ADDRESS T ON DP.DELIVERYADDRESS_ID = T.ADDRESS_ID
                    ON D.DELIVERYPOINT_ID = DP.DELIVERYPOINT_ID
    left outer join ROUTESTOP E ON D.ROUTESTOP_ID = E.ROUTESTOP_ID,
  CUSTOMER P
    left outer join customerlockermanagement clm ON (p.customer_id = clm.customer_id),
  PLANT S,
  LANGUAGES, ADDRESS T2, COUNTRY W, reportparam rp
WHERE A.ROUTE_ID = B.ROUTE_ID AND
  A.ROUTECONTROL_ID = D.ROUTECONTROL_ID AND
  D.CUSTOMER_LINK_ID = P.CUSTOMER_ID AND
  P.VISITADDRESS_ID = T2.ADDRESS_ID AND
  A.PLANT_ID = S.PLANT_ID AND
  D.ROUTECONTROL_ID = A.ROUTECONTROL_ID and
  (d.status = 0 or d.status = 3)--TNE order500701
  AND P.COUNTRY_ID = W.COUNTRY_ID
  and rp.NUMBER_VALUE = a.ROUTECONTROL_ID
  and (d.stoptype is null or d.stoptype in (2, 3)) -- show only this reoutestops
/

  CREATE OR REPLACE VIEW "V_ROUTELISTRSV" ("NOTENUMBER", "SHOWSTOP", "ROUTECONTROL_ID", "STOP_DELIVERYPOINT_ID", "PN_DELIVERYPOINT_ID", "PLANTCODE", "ROUTENUMBER", "ROUTEDESCRIPTION", "DRIVINGDATE", "DEPOTCODE", "DEPOTDESCRIPTION", "LOADINGDOCK", "STARTTIME", "DRIVERNAME", "TRUCKCODE", "TRUCKDESCRIPTION", "STOPNUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "DELIVERYADDRESS1", "DELIVERYADDRESS2", "CITY", "STATE", "ZIPCODE", "C_DELIVERYADDRESS1", "C_DELIVERYADDRESS2", "C_CITY", "C_STATE", "C_ZIPCODE", "ROUTELISTINSTRUCTIONS", "CONTACTPERSONNAME", "CONTACTPERSONPHONE", "CUSTOMERPHONE", "STOP_ID", "DEPARTMENTNUMBER", "DISTRIBUTIONPOINTNUMBER", "DELIVERYPOINTCODE", "DEPARTMENTDESC", "DISTRIBUTIONPOINTDESC", "DELIVERYPOINTDESC", "PRODUCTCODE", "SIZECODE", "FINISHINGMETHODCODE", "DELIVERYSCHEMECODE", "PRODUCTDESCRIPTION", "DELIVERYSCHEMESTARTDATE", "QTYDELIVERED", "QTYEXPECTED", "ENDCONTRACT", "LANGUAGECODE", "DETAIL", "MOVEDROUTENUMBER", "MOVEDROUTEDESCRIPTION", "STATUS", "CUSTOMERCOUNTRYID", "COUNTRY", "PLANTCOUNTRYID", "TYPEOFMERCHADISE", "ROUTE_ID", "STOPTYPE", "REPORTPARAM_ID", "SHOWLOCKERONROUTELIST", "PUTUPTYPE_PRODUCT", "PUTUPTYPE_PLPC", "STRAIGHTEVENEXCHANGE", "QTYDELIVERED_PNL", "DELNOTEFORBULKPUTUPITEMS", "DEL_POINT_START_TIME", "DEL_POINT_END_TIME", "ROUTE_START_TIME", "STOP_TRAVELMINUTES", "STOP_SERVICEMINUTES") AS 
  SELECT  -- 1 --
f.notenumber,
  F_SHOW_ROUTESTOP(d.stop_id, d.routestop_id, s.plant_id) showstop,
  A.ROUTECONTROL_ID, D.DELIVERYPOINT_ID STOP_DELIVERYPOINT_ID, N.DELIVERYPOINT_ID PN_DELIVERYPOINT_ID,
  S.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, A.DRIVINGDATE,
  C.CODE DEPOTCODE, C.DESCRIPTION DEPOTDESCRIPTION, A.LOADINGDOCK, A.STARTTIME,
  X.NAME DRIVERNAME, Y.CODE TRUCKCODE, Y.DESCRIPTION TRUCKDESCRIPTION,
  D.STOPNUMBER, P.CUSTOMERNUMBER, P.NAME CUSTOMERNAME,
  T.STREET DELIVERYADDRESS1, T.STREET2 DELIVERYADDRESS2, T.CITY, T.STATE, T.ZIPCODE,
  '' C_DELIVERYADDRESS1, '' C_DELIVERYADDRESS2, '' C_CITY, '' C_STATE, '' C_ZIPCODE,
  case when d.routestop_id is null then d.routelistinstructions else E.ROUTELISTINSTRUCTIONS end ROUTELISTINSTRUCTIONS,
  Z.NAME CONTACTPERSONNAME, Z.PHONE CONTACTPERSONPHONE, P.PHONENO CUSTOMERPHONE, D.STOP_ID,
  O.DEPARTMENTNUMBER, M.DISTRIBUTIONPOINTNUMBER, N.CODE DELIVERYPOINTCODE,
  O.DESCRIPTION DEPARTMENTDESC, M.DESCRIPTION DISTRIBUTIONPOINTDESC, N.DESCRIPTION DELIVERYPOINTDESC,
  I.CODE PRODUCTCODE, J.CODE SIZECODE, R.CODE FINISHINGMETHODCODE, L.CODE DELIVERYSCHEMECODE,
  (SELECT description FROM PRODUCT_DESC W WHERE I.PRODUCT_ID = W.PRODUCT_ID AND W.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
  H.STARTDATE DELIVERYSCHEMESTARTDATE,
  H.DELIVEREDQTY QTYDELIVERED, 0 QTYEXPECTED, 'P' endcontract,
  LANGUAGES.CODE LANGUAGECODE, 1 detail, V.routenumber movedroutenumber, V.description movedroutedescription, d.status,
  P.COUNTRY_ID CUSTOMERCOUNTRYID, W.DESCRIPTION COUNTRY, S.COUNTRY_ID PLANTCOUNTRYID,
  (select sum(cdd.typeofmerchadise) from CUSTOMERDELIVERYDAY CDD where P.CUSTOMER_ID = CDD.CUSTOMER_ID
     AND coalesce((select rm.drivingday_id from route rm where E.Route_Id=rm.route_id), B.DRIVINGDAY_ID) = CDD.DAY_ID
     and cdd.typeofmerchadise >=1 and cdd.typeofmerchadise <=2) typeofmerchadise,
  B.ROUTE_ID, coalesce(d.stoptype, 0) stoptype, rp.reportparam_id,
  coalesce(clm.showlockeronroutelist, 'N') showlockeronroutelist,
  I.PUTUPTYPE PUTUPTYPE_PRODUCT, G.PUTUPTYPE PUTUPTYPE_PLPC,
  case when H.PACKINGNOTELINE_ID is null then 0 else 1 end STRAIGHTEVENEXCHANGE,
  G.DELIVEREDAMOUNT QTYDELIVERED_PNL, P.DELNOTEFORBULKPUTUPITEMS
  , (SELECT HH.STARTTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_START_TIME
  , (SELECT HH.ENDTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_END_TIME
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
FROM ROUTECONTROL A,
  ROUTE B
    left outer join DEPOT C ON (C.DEPOT_ID = B.DEPOT_ID)
    left outer join EMPLOYEE X ON (X.EMPLOYEE_ID = B.DRIVER_ID)
    left outer join TRUCK Y ON (Y.TRUCK_ID = B.TRUCK_ID),
  STOP D
    left outer join V_MOVEDOUTSTOPS V on D.STOP_ID = V.movedtostop_id-- order 500713
    left outer join CONTACTPERSON Z ON D.CONTACTPERSON_ID = Z.CONTACTPERSON_ID
    left outer join ROUTESTOP E ON D.ROUTESTOP_ID = E.ROUTESTOP_ID,
  PACKINGNOTE F,
  PACKINGNOTELINE G
    left outer join (PACKINGNOTELINEPERDELSCHEME H
      left outer join DELIVERYSCHEME L ON H.DELIVERYSCHEME_ID = L.DELIVERYSCHEME_ID)
        ON G.PACKINGNOTELINE_ID = H.PACKINGNOTELINE_ID,
  PRODUCT I,
  SIZEDEFINITION J,
  DISTRIBUTIONPOINT M, DELIVERYPOINT N, DEPARTMENT O,
  CUSTOMER P
    left outer join customerlockermanagement clm ON (p.customer_id = clm.customer_id),
  FINISHINGMETHOD R, PLANT S, ADDRESS T, STATUS U, LANGUAGES, COUNTRY W, reportparam rp
WHERE A.ROUTE_ID = B.ROUTE_ID AND
  A.ROUTECONTROL_ID = D.ROUTECONTROL_ID AND
  D.STOP_ID = F.STOP_ID AND
  F.PACKINGNOTE_ID = G.PACKINGNOTE_ID AND
  G.PRODUCT_ID = I.PRODUCT_ID AND
  G.SIZEDEFINITION_ID = J.SIZEDEFINITION_ID AND
  F.DISTRIBUTIONPOINT_ID = M.DISTRIBUTIONPOINT_ID AND
  F.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND
  M.DEPARTMENT_ID = O.DEPARTMENT_ID AND
  D.CUSTOMER_LINK_ID = P.CUSTOMER_ID AND
  G.FINISHINGMETHOD_ID = R.FINISHINGMETHOD_ID AND
  A.PLANT_ID = S.PLANT_ID AND
  N.DELIVERYADDRESS_ID = T.ADDRESS_ID AND
  F.STATUS_ID = U.STATUS_ID AND
  U.STATUSTYPE = 'PN' AND
  U.CODE <> '40'and
  (d.status = 0 or d.status = 3)--TNE order500701
  AND P.COUNTRY_ID = W.COUNTRY_ID --TNE ORDER 500713
and rp.NUMBER_VALUE = a.ROUTECONTROL_ID
UNION ALL          -- 2 --
SELECT
0 notenumber,
  F_SHOW_ROUTESTOP(d.stop_id, d.routestop_id, s.plant_id) showstop,
  A.ROUTECONTROL_ID, D.DELIVERYPOINT_ID STOPDELIVERYPOINT_ID, N.DELIVERYPOINT_ID PN_DELIVERYPOINT_ID,
  S.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, A.DRIVINGDATE,
  C.CODE DEPOTCODE, C.DESCRIPTION DEPOTDESCRIPTION, A.LOADINGDOCK, A.STARTTIME,
  X.NAME DRIVERNAME, Y.CODE TRUCKCODE, Y.DESCRIPTION TRUCKDESCRIPTION,
  D.STOPNUMBER, P.CUSTOMERNUMBER, P.NAME CUSTOMERNAME,
  T.STREET DELIVERYADDRESS1, T.STREET2 DELIVERYADDRESS2, T.CITY, T.STATE, T.ZIPCODE,
  '' C_DELIVERYADDRESS1, '' C_DELIVERYADDRESS2, '' C_CITY, '' C_STATE, '' C_ZIPCODE,
case when d.routestop_id is null then d.routelistinstructions else E.ROUTELISTINSTRUCTIONS end ROUTELISTINSTRUCTIONS,
  Z.NAME CONTACTPERSONNAME, Z.PHONE CONTACTPERSONPHONE, P.PHONENO CUSTOMERPHONE,  D.STOP_ID,
  O.DEPARTMENTNUMBER, M.DISTRIBUTIONPOINTNUMBER, N.CODE DELIVERYPOINTCODE,
  O.DESCRIPTION DEPARTMENTDESC, M.DESCRIPTION DISTRIBUTIONPOINTDESC, N.DESCRIPTION DELIVERYPOINTDESC,
  I.CODE PRODUCTCODE, J.CODE SIZECODE, R.CODE FINISHINGMETHODCODE, L.CODE DELIVERYSCHEMECODE,
  (SELECT description FROM PRODUCT_DESC W WHERE I.PRODUCT_ID = W.PRODUCT_ID AND W.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
  NULL DELIVERYSCHEMESTARTDATE,
  0 QTYDELIVERED, K.QTYEXPECTED QTYEXPECTED, k.endcontract,
  LANGUAGES.CODE LANGUAGECODE, 1 detail, V.routenumber movedroutenumber, V.description movedroutedescription, d.status,
  P.COUNTRY_ID CUSTOMERCOUNTRYID, W.DESCRIPTION COUNTRY, S.COUNTRY_ID PLANTCOUNTRYID,
  (select sum(cdd.typeofmerchadise) from CUSTOMERDELIVERYDAY CDD where P.CUSTOMER_ID = CDD.CUSTOMER_ID
     AND coalesce((select rm.drivingday_id from route rm where E.Route_Id=rm.route_id), B.DRIVINGDAY_ID) = CDD.DAY_ID
     and cdd.typeofmerchadise >=1 and cdd.typeofmerchadise <=2) typeofmerchadise,
  B.ROUTE_ID, coalesce(d.stoptype, 0) stoptype, rp.reportparam_id,
  coalesce(clm.showlockeronroutelist, 'N') showlockeronroutelist,
  I.PUTUPTYPE PUTUPTYPE_PRODUCT, 0 PUTUPTYPE_PLPC, 1 STRAIGHTEVENEXCHANGE,
  0 QTYDELIVERED_PNL, P.DELNOTEFORBULKPUTUPITEMS
  , (SELECT HH.STARTTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_START_TIME
  , (SELECT HH.ENDTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_END_TIME
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
FROM ROUTECONTROL A,
  ROUTE B
    left outer join DEPOT C ON (C.DEPOT_ID = B.DEPOT_ID)
    left outer join EMPLOYEE X ON (X.EMPLOYEE_ID = B.DRIVER_ID)
    left outer join TRUCK Y ON (Y.TRUCK_ID = B.TRUCK_ID),
  STOP D
    left outer join V_MOVEDOUTSTOPS V on D.STOP_ID = V.movedtostop_id-- order500701
    left outer join CONTACTPERSON Z ON D.CONTACTPERSON_ID = Z.CONTACTPERSON_ID
    left outer join ROUTESTOP E ON D.ROUTESTOP_ID = E.ROUTESTOP_ID,
  STRAIGHTEVENRETURN K, PRODUCT I, SIZEDEFINITION J, DELIVERYSCHEME L,
  DISTRIBUTIONPOINT M, DELIVERYPOINT N, DEPARTMENT O,
  CUSTOMER P
    left outer join customerlockermanagement clm ON (p.customer_id = clm.customer_id),
  FINISHINGMETHOD R, PLANT S, ADDRESS T, STATUS U, LANGUAGES, COUNTRY W, reportparam rp
WHERE A.ROUTE_ID = B.ROUTE_ID AND
  A.ROUTECONTROL_ID = D.ROUTECONTROL_ID AND
  D.STOP_ID = K.STOP_ID AND
  K.PRODUCT_ID = I.PRODUCT_ID AND
  K.SIZEDEFINITION_ID = J.SIZEDEFINITION_ID AND
  K.DELIVERYSCHEME_ID = L.DELIVERYSCHEME_ID AND
  K.DISTRIBUTIONPOINT_ID = M.DISTRIBUTIONPOINT_ID AND
  M.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND
  M.DEPARTMENT_ID = O.DEPARTMENT_ID AND
  D.CUSTOMER_LINK_ID = P.CUSTOMER_ID AND
  K.FINISHINGMETHOD_ID = R.FINISHINGMETHOD_ID AND
  A.PLANT_ID = S.PLANT_ID AND
  N.DELIVERYADDRESS_ID = T.ADDRESS_ID AND
  K.STATUS_ID = U.STATUS_ID AND
  U.STATUSTYPE = 'SR' AND
  U.CODE <> '30'and
  (d.status = 0 or d.status = 3)--TNE order500701
  AND P.COUNTRY_ID = W.COUNTRY_ID
and rp.NUMBER_VALUE = a.ROUTECONTROL_ID
UNION ALL             -- 3 --
SELECT
0 notenumber,
F_SHOW_ROUTESTOP(d.stop_id, d.routestop_id, s.plant_id) showstop,
  A.ROUTECONTROL_ID, D.DELIVERYPOINT_ID STOPDELIVERYPOINT_ID, 0 PN_DELIVERYPOINT_ID,
  S.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, A.DRIVINGDATE,
  C.CODE DEPOTCODE, C.DESCRIPTION DEPOTDESCRIPTION, A.LOADINGDOCK, A.STARTTIME,
  X.NAME DRIVERNAME, Y.CODE TRUCKCODE, Y.DESCRIPTION TRUCKDESCRIPTION,
  D.STOPNUMBER, P.CUSTOMERNUMBER, P.NAME CUSTOMERNAME,
  T.STREET DELIVERYADDRESS1, T.STREET2 DELIVERYADDRESS2, T.CITY, T.STATE, T.ZIPCODE,
  T2.STREET C_DELIVERYADDRESS1, T2.STREET2 C_DELIVERYADDRESS2, T2.CITY C_CITY, T2.STATE C_STATE, T2.ZIPCODE C_ZIPCODE,
case when d.routestop_id is null then d.routelistinstructions else E.ROUTELISTINSTRUCTIONS end ROUTELISTINSTRUCTIONS,
  Z.NAME CONTACTPERSONNAME, Z.PHONE CONTACTPERSONPHONE, P.PHONENO CUSTOMERPHONE, D.STOP_ID,
  -1 departmentnumber, -1 distributionpointnumber, dp.code deliverypointcode,
  '' departmentdesc, '' DISTRIBUTIONPOINTDESC, dp.description DELIVERYPOINTDESC,
  '' PRODUCTCODE,'' SIZECODE,'' FINISHINGMETHODCODE,'' DELIVERYSCHEMECODE,'' PRODUCTDESCRIPTION,null deliveryschemestartdate,0 QTYDELIVERED,0 QTYEXPECTED,'A' endcontract,
  LANGUAGES.CODE LANGUAGECODE, 0 detail, V.routenumber movedroutenumber, V.description movedroutedescription, d.status,
  P.COUNTRY_ID CUSTOMERCOUNTRYID, W.DESCRIPTION COUNTRY, S.COUNTRY_ID PLANTCOUNTRYID,
  (select sum(cdd.typeofmerchadise) from CUSTOMERDELIVERYDAY CDD where P.CUSTOMER_ID = CDD.CUSTOMER_ID
     AND coalesce((select rm.drivingday_id from route rm where E.Route_Id=rm.route_id), B.DRIVINGDAY_ID) = CDD.DAY_ID
     and cdd.typeofmerchadise >=1 and cdd.typeofmerchadise <=2) typeofmerchadise,
  B.ROUTE_ID, coalesce(d.stoptype, 0) stoptype, rp.reportparam_id,
  coalesce(clm.showlockeronroutelist, 'N') showlockeronroutelist,
  0 PUTUPTYPE_PRODUCT, 0 PUTUPTYPE_PLPC, 0 STRAIGHTEVENEXCHANGE,
  0 QTYDELIVERED_PNL, P.DELNOTEFORBULKPUTUPITEMS
  , (SELECT HH.STARTTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = DP.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_START_TIME
  , (SELECT HH.ENDTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = DP.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_END_TIME
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES ROUTESTOP_TRAVELMINUTES, E.SERVICEMINUTES ROUTESTOP_SERVICEMINUTES
FROM ROUTECONTROL A,
  ROUTE B
    left outer join DEPOT C ON (C.DEPOT_ID = B.DEPOT_ID)
    left outer join EMPLOYEE X ON (X.EMPLOYEE_ID = B.DRIVER_ID)
    left outer join TRUCK Y ON (Y.TRUCK_ID = B.TRUCK_ID),
  STOP D
    left outer join V_MOVEDOUTSTOPS V on D.STOP_ID = V.movedtostop_id-- order500701
    left outer join CONTACTPERSON Z ON D.CONTACTPERSON_ID = Z.CONTACTPERSON_ID
    left outer join DELIVERYPOINT DP LEFT OUTER JOIN ADDRESS T ON DP.DELIVERYADDRESS_ID = T.ADDRESS_ID
                    ON D.DELIVERYPOINT_ID = DP.DELIVERYPOINT_ID
    left outer join ROUTESTOP E ON D.ROUTESTOP_ID = E.ROUTESTOP_ID,
  CUSTOMER P
    left outer join customerlockermanagement clm ON (p.customer_id = clm.customer_id),
  PLANT S,
  LANGUAGES, ADDRESS T2, COUNTRY W, reportparam rp
WHERE A.ROUTE_ID = B.ROUTE_ID AND
  A.ROUTECONTROL_ID = D.ROUTECONTROL_ID AND
  D.CUSTOMER_LINK_ID = P.CUSTOMER_ID AND
  P.VISITADDRESS_ID = T2.ADDRESS_ID AND
  A.PLANT_ID = S.PLANT_ID AND
  D.ROUTECONTROL_ID = A.ROUTECONTROL_ID and
  (d.status = 0 or d.status = 3)--TNE order500701
  AND P.COUNTRY_ID = W.COUNTRY_ID
  and rp.NUMBER_VALUE = a.ROUTECONTROL_ID
/

  CREATE OR REPLACE VIEW "V_ROUTELISTSTK" ("NOTENUMBER", "SHOWSTOP", "ROUTECONTROL_ID", "STOP_DELIVERYPOINT_ID", "PN_DELIVERYPOINT_ID", "PLANTCODE", "ROUTENUMBER", "ROUTEDESCRIPTION", "DRIVINGDATE", "DEPOTCODE", "DEPOTDESCRIPTION", "LOADINGDOCK", "STARTTIME", "DRIVERNAME", "TRUCKCODE", "TRUCKDESCRIPTION", "STOPNUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "DELIVERYADDRESS1", "DELIVERYADDRESS2", "CITY", "STATE", "ZIPCODE", "C_DELIVERYADDRESS1", "C_DELIVERYADDRESS2", "C_CITY", "C_STATE", "C_ZIPCODE", "ROUTELISTINSTRUCTIONS", "CONTACTPERSONNAME", "CONTACTPERSONPHONE", "CUSTOMERPHONE", "STOP_ID", "DEPARTMENTNUMBER", "DISTRIBUTIONPOINTNUMBER", "DELIVERYPOINTCODE", "DEPARTMENTDESC", "DISTRIBUTIONPOINTDESC", "DELIVERYPOINTDESC", "PRODUCTCODE", "SIZECODE", "FINISHINGMETHODCODE", "DELIVERYSCHEMECODE", "PRODUCTDESCRIPTION", "DELIVERYSCHEMESTARTDATE", "QTYDELIVERED", "QTYEXPECTED", "ENDCONTRACT", "LANGUAGECODE", "DETAIL", "MOVEDROUTENUMBER", "MOVEDROUTEDESCRIPTION", "STATUS", "CUSTOMERCOUNTRYID", "COUNTRY", "PLANTCOUNTRYID", "TYPEOFMERCHADISE", "ROUTE_ID", "STOPTYPE", "REPORTPARAM_ID", "SHOWLOCKERONROUTELIST", "PUTUPTYPE_PRODUCT", "PUTUPTYPE_PLPC", "STRAIGHTEVENEXCHANGE", "QTYDELIVERED_PNL", "DELNOTEFORBULKPUTUPITEMS", "DEL_POINT_START_TIME", "DEL_POINT_END_TIME", "ROUTE_START_TIME", "STOP_TRAVELMINUTES", "STOP_SERVICEMINUTES") AS 
  SELECT  -- 1 --
f.notenumber,
  F_SHOW_ROUTESTOP(d.stop_id, d.routestop_id, s.plant_id) showstop,
  A.ROUTECONTROL_ID, D.DELIVERYPOINT_ID STOP_DELIVERYPOINT_ID, N.DELIVERYPOINT_ID PN_DELIVERYPOINT_ID,
  S.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, A.DRIVINGDATE,
  C.CODE DEPOTCODE, C.DESCRIPTION DEPOTDESCRIPTION, A.LOADINGDOCK, A.STARTTIME,
  X.NAME DRIVERNAME, Y.CODE TRUCKCODE, Y.DESCRIPTION TRUCKDESCRIPTION,
  D.STOPNUMBER, P.CUSTOMERNUMBER, P.NAME CUSTOMERNAME,
  T.STREET DELIVERYADDRESS1, T.STREET2 DELIVERYADDRESS2, T.CITY, T.STATE, T.ZIPCODE,
  '' C_DELIVERYADDRESS1, '' C_DELIVERYADDRESS2, '' C_CITY, '' C_STATE, '' C_ZIPCODE,
  case when d.routestop_id is null then d.routelistinstructions else E.ROUTELISTINSTRUCTIONS end ROUTELISTINSTRUCTIONS,
  Z.NAME CONTACTPERSONNAME, Z.PHONE CONTACTPERSONPHONE, P.PHONENO CUSTOMERPHONE, D.STOP_ID,
  O.DEPARTMENTNUMBER, M.DISTRIBUTIONPOINTNUMBER, N.CODE DELIVERYPOINTCODE,
  O.DESCRIPTION DEPARTMENTDESC, M.DESCRIPTION DISTRIBUTIONPOINTDESC, N.DESCRIPTION DELIVERYPOINTDESC,
  I.CODE PRODUCTCODE, J.CODE SIZECODE, R.CODE FINISHINGMETHODCODE, L.CODE DELIVERYSCHEMECODE,
  (SELECT description FROM PRODUCT_DESC W WHERE I.PRODUCT_ID = W.PRODUCT_ID AND W.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
  H.STARTDATE DELIVERYSCHEMESTARTDATE,
  H.DELIVEREDQTY QTYDELIVERED, 0 QTYEXPECTED, 'P' endcontract,
  LANGUAGES.CODE LANGUAGECODE, 1 detail, V.routenumber movedroutenumber, V.description movedroutedescription, d.status,
  P.COUNTRY_ID CUSTOMERCOUNTRYID, W.DESCRIPTION COUNTRY, S.COUNTRY_ID PLANTCOUNTRYID,
  (select sum(cdd.typeofmerchadise) from CUSTOMERDELIVERYDAY CDD where P.CUSTOMER_ID = CDD.CUSTOMER_ID
     AND coalesce((select rm.drivingday_id from route rm where E.Route_Id=rm.route_id), B.DRIVINGDAY_ID) = CDD.DAY_ID
     and cdd.typeofmerchadise >=1 and cdd.typeofmerchadise <=2) typeofmerchadise,
  B.ROUTE_ID, coalesce(d.stoptype, 0) stoptype, rp.reportparam_id,
  coalesce(clm.showlockeronroutelist, 'N') showlockeronroutelist,
  I.PUTUPTYPE PUTUPTYPE_PRODUCT, G.PUTUPTYPE PUTUPTYPE_PLPC,
  case when H.PACKINGNOTELINE_ID is null then 0 else 1 end STRAIGHTEVENEXCHANGE,
  G.DELIVEREDAMOUNT QTYDELIVERED_PNL, P.DELNOTEFORBULKPUTUPITEMS
  , (SELECT HH.STARTTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_START_TIME
  , (SELECT HH.ENDTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_END_TIME
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
FROM ROUTECONTROL A,
  ROUTE B
    left outer join DEPOT C ON (C.DEPOT_ID = B.DEPOT_ID)
    left outer join EMPLOYEE X ON (X.EMPLOYEE_ID = B.DRIVER_ID)
    left outer join TRUCK Y ON (Y.TRUCK_ID = B.TRUCK_ID),
  STOP D
    left outer join V_MOVEDOUTSTOPS V on D.STOP_ID = V.movedtostop_id-- order 500713
    left outer join CONTACTPERSON Z ON D.CONTACTPERSON_ID = Z.CONTACTPERSON_ID
    left outer join ROUTESTOP E ON D.ROUTESTOP_ID = E.ROUTESTOP_ID,
  PACKINGNOTE F,
  PACKINGNOTELINE G
    left outer join (PACKINGNOTELINEPERDELSCHEME H
      left outer join DELIVERYSCHEME L ON H.DELIVERYSCHEME_ID = L.DELIVERYSCHEME_ID)
        ON G.PACKINGNOTELINE_ID = H.PACKINGNOTELINE_ID,
  PRODUCT I,
  SIZEDEFINITION J,
  DISTRIBUTIONPOINT M, DELIVERYPOINT N, DEPARTMENT O,
  CUSTOMER P
    left outer join customerlockermanagement clm ON (p.customer_id = clm.customer_id),
  FINISHINGMETHOD R, PLANT S, ADDRESS T, STATUS U, LANGUAGES, COUNTRY W, reportparam rp
WHERE A.ROUTE_ID = B.ROUTE_ID AND
  A.ROUTECONTROL_ID = D.ROUTECONTROL_ID AND
  D.STOP_ID = F.STOP_ID AND
  F.PACKINGNOTE_ID = G.PACKINGNOTE_ID AND
  G.PRODUCT_ID = I.PRODUCT_ID AND
  G.SIZEDEFINITION_ID = J.SIZEDEFINITION_ID AND
  F.DISTRIBUTIONPOINT_ID = M.DISTRIBUTIONPOINT_ID AND
  F.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND
  M.DEPARTMENT_ID = O.DEPARTMENT_ID AND
  D.CUSTOMER_LINK_ID = P.CUSTOMER_ID AND
  G.FINISHINGMETHOD_ID = R.FINISHINGMETHOD_ID AND
  A.PLANT_ID = S.PLANT_ID AND
  N.DELIVERYADDRESS_ID = T.ADDRESS_ID AND
  F.STATUS_ID = U.STATUS_ID AND
  U.STATUSTYPE = 'PN' AND
  U.CODE <> '40'and
  (d.status = 0 or d.status = 3)--TNE order500701
  AND P.COUNTRY_ID = W.COUNTRY_ID --TNE ORDER 500713
and rp.NUMBER_VALUE = a.ROUTECONTROL_ID
UNION ALL          -- 2 --
SELECT
0 notenumber,
  F_SHOW_ROUTESTOP(d.stop_id, d.routestop_id, s.plant_id) showstop,
  A.ROUTECONTROL_ID, D.DELIVERYPOINT_ID STOPDELIVERYPOINT_ID, N.DELIVERYPOINT_ID PN_DELIVERYPOINT_ID,
  S.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, A.DRIVINGDATE,
  C.CODE DEPOTCODE, C.DESCRIPTION DEPOTDESCRIPTION, A.LOADINGDOCK, A.STARTTIME,
  X.NAME DRIVERNAME, Y.CODE TRUCKCODE, Y.DESCRIPTION TRUCKDESCRIPTION,
  D.STOPNUMBER, P.CUSTOMERNUMBER, P.NAME CUSTOMERNAME,
  T.STREET DELIVERYADDRESS1, T.STREET2 DELIVERYADDRESS2, T.CITY, T.STATE, T.ZIPCODE,
  '' C_DELIVERYADDRESS1, '' C_DELIVERYADDRESS2, '' C_CITY, '' C_STATE, '' C_ZIPCODE,
case when d.routestop_id is null then d.routelistinstructions else E.ROUTELISTINSTRUCTIONS end ROUTELISTINSTRUCTIONS,
  Z.NAME CONTACTPERSONNAME, Z.PHONE CONTACTPERSONPHONE, P.PHONENO CUSTOMERPHONE,  D.STOP_ID,
  O.DEPARTMENTNUMBER, M.DISTRIBUTIONPOINTNUMBER, N.CODE DELIVERYPOINTCODE,
  O.DESCRIPTION DEPARTMENTDESC, M.DESCRIPTION DISTRIBUTIONPOINTDESC, N.DESCRIPTION DELIVERYPOINTDESC,
  I.CODE PRODUCTCODE, J.CODE SIZECODE, R.CODE FINISHINGMETHODCODE, L.CODE DELIVERYSCHEMECODE,
  (SELECT description FROM PRODUCT_DESC W WHERE I.PRODUCT_ID = W.PRODUCT_ID AND W.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
  NULL DELIVERYSCHEMESTARTDATE,
  0 QTYDELIVERED, K.QTYEXPECTED QTYEXPECTED, k.endcontract,
  LANGUAGES.CODE LANGUAGECODE, 1 detail, V.routenumber movedroutenumber, V.description movedroutedescription, d.status,
  P.COUNTRY_ID CUSTOMERCOUNTRYID, W.DESCRIPTION COUNTRY, S.COUNTRY_ID PLANTCOUNTRYID,
  (select sum(cdd.typeofmerchadise) from CUSTOMERDELIVERYDAY CDD where P.CUSTOMER_ID = CDD.CUSTOMER_ID
     AND coalesce((select rm.drivingday_id from route rm where E.Route_Id=rm.route_id), B.DRIVINGDAY_ID) = CDD.DAY_ID
     and cdd.typeofmerchadise >=1 and cdd.typeofmerchadise <=2) typeofmerchadise,
  B.ROUTE_ID, coalesce(d.stoptype, 0) stoptype, rp.reportparam_id,
  coalesce(clm.showlockeronroutelist, 'N') showlockeronroutelist,
  I.PUTUPTYPE PUTUPTYPE_PRODUCT, 0 PUTUPTYPE_PLPC, 1 STRAIGHTEVENEXCHANGE,
  0 QTYDELIVERED_PNL, P.DELNOTEFORBULKPUTUPITEMS
  , (SELECT HH.STARTTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_START_TIME
  , (SELECT HH.ENDTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_END_TIME
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
FROM ROUTECONTROL A,
  ROUTE B
    left outer join DEPOT C ON (C.DEPOT_ID = B.DEPOT_ID)
    left outer join EMPLOYEE X ON (X.EMPLOYEE_ID = B.DRIVER_ID)
    left outer join TRUCK Y ON (Y.TRUCK_ID = B.TRUCK_ID),
  STOP D
    left outer join V_MOVEDOUTSTOPS V on D.STOP_ID = V.movedtostop_id-- order500701
    left outer join CONTACTPERSON Z ON D.CONTACTPERSON_ID = Z.CONTACTPERSON_ID
    left outer join ROUTESTOP E ON D.ROUTESTOP_ID = E.ROUTESTOP_ID,
  STRAIGHTEVENRETURN K, PRODUCT I, SIZEDEFINITION J, DELIVERYSCHEME L,
  DISTRIBUTIONPOINT M, DELIVERYPOINT N, DEPARTMENT O,
  CUSTOMER P
    left outer join customerlockermanagement clm ON (p.customer_id = clm.customer_id),
  FINISHINGMETHOD R, PLANT S, ADDRESS T, STATUS U, LANGUAGES, COUNTRY W, reportparam rp
WHERE A.ROUTE_ID = B.ROUTE_ID AND
  A.ROUTECONTROL_ID = D.ROUTECONTROL_ID AND
  D.STOP_ID = K.STOP_ID AND
  K.PRODUCT_ID = I.PRODUCT_ID AND
  K.SIZEDEFINITION_ID = J.SIZEDEFINITION_ID AND
  K.DELIVERYSCHEME_ID = L.DELIVERYSCHEME_ID AND
  K.DISTRIBUTIONPOINT_ID = M.DISTRIBUTIONPOINT_ID AND
  M.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND
  M.DEPARTMENT_ID = O.DEPARTMENT_ID AND
  D.CUSTOMER_LINK_ID = P.CUSTOMER_ID AND
  K.FINISHINGMETHOD_ID = R.FINISHINGMETHOD_ID AND
  A.PLANT_ID = S.PLANT_ID AND
  N.DELIVERYADDRESS_ID = T.ADDRESS_ID AND
  K.STATUS_ID = U.STATUS_ID AND
  U.STATUSTYPE = 'SR' AND
  U.CODE <> '30'and
  (d.status = 0 or d.status = 3)--TNE order500701
  AND P.COUNTRY_ID = W.COUNTRY_ID
and rp.NUMBER_VALUE = a.ROUTECONTROL_ID
UNION ALL             -- 3 --
SELECT
0 notenumber,
F_SHOW_ROUTESTOP(d.stop_id, d.routestop_id, s.plant_id) showstop,
  A.ROUTECONTROL_ID, D.DELIVERYPOINT_ID STOPDELIVERYPOINT_ID, 0 PN_DELIVERYPOINT_ID,
  S.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, A.DRIVINGDATE,
  C.CODE DEPOTCODE, C.DESCRIPTION DEPOTDESCRIPTION, A.LOADINGDOCK, A.STARTTIME,
  X.NAME DRIVERNAME, Y.CODE TRUCKCODE, Y.DESCRIPTION TRUCKDESCRIPTION,
  D.STOPNUMBER, P.CUSTOMERNUMBER, P.NAME CUSTOMERNAME,
  T.STREET DELIVERYADDRESS1, T.STREET2 DELIVERYADDRESS2, T.CITY, T.STATE, T.ZIPCODE,
  T2.STREET C_DELIVERYADDRESS1, T2.STREET2 C_DELIVERYADDRESS2, T2.CITY C_CITY, T2.STATE C_STATE, T2.ZIPCODE C_ZIPCODE,
case when d.routestop_id is null then d.routelistinstructions else E.ROUTELISTINSTRUCTIONS end ROUTELISTINSTRUCTIONS,
  Z.NAME CONTACTPERSONNAME, Z.PHONE CONTACTPERSONPHONE, P.PHONENO CUSTOMERPHONE, D.STOP_ID,
  -1 departmentnumber, -1 distributionpointnumber, dp.code deliverypointcode,
  '' departmentdesc, '' DISTRIBUTIONPOINTDESC, dp.description DELIVERYPOINTDESC,
  '' PRODUCTCODE,'' SIZECODE,'' FINISHINGMETHODCODE,'' DELIVERYSCHEMECODE,'' PRODUCTDESCRIPTION,null deliveryschemestartdate,0 QTYDELIVERED,0 QTYEXPECTED,'A' endcontract,
  LANGUAGES.CODE LANGUAGECODE, 0 detail, V.routenumber movedroutenumber, V.description movedroutedescription, d.status,
  P.COUNTRY_ID CUSTOMERCOUNTRYID, W.DESCRIPTION COUNTRY, S.COUNTRY_ID PLANTCOUNTRYID,
  (select sum(cdd.typeofmerchadise) from CUSTOMERDELIVERYDAY CDD where P.CUSTOMER_ID = CDD.CUSTOMER_ID
     AND coalesce((select rm.drivingday_id from route rm where E.Route_Id=rm.route_id), B.DRIVINGDAY_ID) = CDD.DAY_ID
     and cdd.typeofmerchadise >=1 and cdd.typeofmerchadise <=2) typeofmerchadise,
  B.ROUTE_ID, coalesce(d.stoptype, 0) stoptype, rp.reportparam_id,
  coalesce(clm.showlockeronroutelist, 'N') showlockeronroutelist,
  0 PUTUPTYPE_PRODUCT, 0 PUTUPTYPE_PLPC, 0 STRAIGHTEVENEXCHANGE,
  0 QTYDELIVERED_PNL, P.DELNOTEFORBULKPUTUPITEMS
  , (SELECT HH.STARTTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = DP.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_START_TIME
  , (SELECT HH.ENDTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = DP.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_END_TIME
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES ROUTESTOP_TRAVELMINUTES, E.SERVICEMINUTES ROUTESTOP_SERVICEMINUTES
FROM ROUTECONTROL A,
  ROUTE B
    left outer join DEPOT C ON (C.DEPOT_ID = B.DEPOT_ID)
    left outer join EMPLOYEE X ON (X.EMPLOYEE_ID = B.DRIVER_ID)
    left outer join TRUCK Y ON (Y.TRUCK_ID = B.TRUCK_ID),
  STOP D
    left outer join V_MOVEDOUTSTOPS V on D.STOP_ID = V.movedtostop_id-- order500701
    left outer join CONTACTPERSON Z ON D.CONTACTPERSON_ID = Z.CONTACTPERSON_ID
    left outer join DELIVERYPOINT DP LEFT OUTER JOIN ADDRESS T ON DP.DELIVERYADDRESS_ID = T.ADDRESS_ID
      ON D.DELIVERYPOINT_ID = DP.DELIVERYPOINT_ID
    left outer join ROUTESTOP E ON D.ROUTESTOP_ID = E.ROUTESTOP_ID,
  CUSTOMER P
    left outer join customerlockermanagement clm ON (p.customer_id = clm.customer_id),
  PLANT S,
  LANGUAGES, ADDRESS T2, COUNTRY W, reportparam rp
WHERE A.ROUTE_ID = B.ROUTE_ID AND
  A.ROUTECONTROL_ID = D.ROUTECONTROL_ID AND
  D.CUSTOMER_LINK_ID = P.CUSTOMER_ID AND
  P.VISITADDRESS_ID = T2.ADDRESS_ID AND
  A.PLANT_ID = S.PLANT_ID AND
  D.ROUTECONTROL_ID = A.ROUTECONTROL_ID and
  (d.status = 0 or d.status = 3)--TNE order500701
  AND P.COUNTRY_ID = W.COUNTRY_ID
  and rp.NUMBER_VALUE = a.ROUTECONTROL_ID
/

  CREATE OR REPLACE VIEW "V_ROUTELISTURZ" ("NOTENUMBER", "SHOWSTOP", "ROUTECONTROL_ID", "STOP_DELIVERYPOINT_ID", "PN_DELIVERYPOINT_ID", "PLANTCODE", "ROUTENUMBER", "ROUTEDESCRIPTION", "DRIVINGDATE", "DEPOTCODE", "DEPOTDESCRIPTION", "LOADINGDOCK", "STARTTIME", "DRIVERNAME", "TRUCKCODE", "TRUCKDESCRIPTION", "STOPNUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "DELIVERYADDRESS1", "DELIVERYADDRESS2", "CITY", "STATE", "ZIPCODE", "C_DELIVERYADDRESS1", "C_DELIVERYADDRESS2", "C_CITY", "C_STATE", "C_ZIPCODE", "ROUTELISTINSTRUCTIONS", "CONTACTPERSONNAME", "CONTACTPERSONPHONE", "CUSTOMERPHONE", "STOP_ID", "DEPARTMENTNUMBER", "DISTRIBUTIONPOINTNUMBER", "DELIVERYPOINTCODE", "DEPARTMENTDESC", "DISTRIBUTIONPOINTDESC", "DELIVERYPOINTDESC", "PRODUCTCODE", "SIZECODE", "FINISHINGMETHODCODE", "DELIVERYSCHEMECODE", "PRODUCTDESCRIPTION", "DELIVERYSCHEMESTARTDATE", "QTYDELIVERED", "QTYEXPECTED", "ENDCONTRACT", "LANGUAGECODE", "DETAIL", "MOVEDROUTENUMBER", "MOVEDROUTEDESCRIPTION", "STATUS", "CUSTOMERCOUNTRYID", "COUNTRY", "PLANTCOUNTRYID", "TYPEOFMERCHADISE", "ROUTE_ID", "STOPTYPE", "REPORTPARAM_ID", "SHOWLOCKERONROUTELIST", "PUTUPTYPE_PRODUCT", "PUTUPTYPE_PLPC", "STRAIGHTEVENEXCHANGE", "QTYDELIVERED_PNL", "DELNOTEFORBULKPUTUPITEMS", "DEL_POINT_START_TIME", "DEL_POINT_END_TIME", "ROUTE_START_TIME", "STOP_TRAVELMINUTES", "STOP_SERVICEMINUTES") AS 
  SELECT  -- 1 --
f.notenumber,
  F_SHOW_ROUTESTOP(d.stop_id, d.routestop_id, s.plant_id) showstop,
  A.ROUTECONTROL_ID, D.DELIVERYPOINT_ID STOP_DELIVERYPOINT_ID, N.DELIVERYPOINT_ID PN_DELIVERYPOINT_ID,
  S.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, A.DRIVINGDATE,
  C.CODE DEPOTCODE, C.DESCRIPTION DEPOTDESCRIPTION, A.LOADINGDOCK, A.STARTTIME,
  X.NAME DRIVERNAME, Y.CODE TRUCKCODE, Y.DESCRIPTION TRUCKDESCRIPTION,
  D.STOPNUMBER, P.CUSTOMERNUMBER, P.NAME CUSTOMERNAME,
  T.STREET DELIVERYADDRESS1, T.STREET2 DELIVERYADDRESS2, T.CITY, T.STATE, T.ZIPCODE,
  '' C_DELIVERYADDRESS1, '' C_DELIVERYADDRESS2, '' C_CITY, '' C_STATE, '' C_ZIPCODE,
  case when d.routestop_id is null then d.routelistinstructions else E.ROUTELISTINSTRUCTIONS end ROUTELISTINSTRUCTIONS,
  Z.NAME CONTACTPERSONNAME, Z.PHONE CONTACTPERSONPHONE, P.PHONENO CUSTOMERPHONE, D.STOP_ID,
  O.DEPARTMENTNUMBER, M.DISTRIBUTIONPOINTNUMBER, N.CODE DELIVERYPOINTCODE,
  O.DESCRIPTION DEPARTMENTDESC, M.DESCRIPTION DISTRIBUTIONPOINTDESC, N.DESCRIPTION DELIVERYPOINTDESC,
  I.CODE PRODUCTCODE, J.CODE SIZECODE, R.CODE FINISHINGMETHODCODE, L.CODE DELIVERYSCHEMECODE,
  (SELECT description FROM PRODUCT_DESC W WHERE I.PRODUCT_ID = W.PRODUCT_ID AND W.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
  H.STARTDATE DELIVERYSCHEMESTARTDATE,
  H.DELIVEREDQTY QTYDELIVERED, 0 QTYEXPECTED, 'P' endcontract,
  LANGUAGES.CODE LANGUAGECODE, 1 detail, V.routenumber movedroutenumber, V.description movedroutedescription, d.status,
  P.COUNTRY_ID CUSTOMERCOUNTRYID, W.DESCRIPTION COUNTRY, S.COUNTRY_ID PLANTCOUNTRYID,
  (select sum(cdd.typeofmerchadise) from CUSTOMERDELIVERYDAY CDD where P.CUSTOMER_ID = CDD.CUSTOMER_ID
     AND coalesce((select rm.drivingday_id from route rm where E.Route_Id=rm.route_id), B.DRIVINGDAY_ID) = CDD.DAY_ID
     and cdd.typeofmerchadise >=1 and cdd.typeofmerchadise <=2) typeofmerchadise,
  B.ROUTE_ID, coalesce(d.stoptype, 0) stoptype, rp.reportparam_id,
  coalesce(clm.showlockeronroutelist, 'N') showlockeronroutelist,
  I.PUTUPTYPE PUTUPTYPE_PRODUCT, G.PUTUPTYPE PUTUPTYPE_PLPC,
  case when H.PACKINGNOTELINE_ID is null then 0 else 1 end STRAIGHTEVENEXCHANGE,
  G.DELIVEREDAMOUNT QTYDELIVERED_PNL, P.DELNOTEFORBULKPUTUPITEMS
  , (SELECT HH.STARTTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_START_TIME
  , (SELECT HH.ENDTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_END_TIME
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
FROM ROUTECONTROL A,
  ROUTE B
    left outer join DEPOT C ON (C.DEPOT_ID = B.DEPOT_ID)
    left outer join EMPLOYEE X ON (X.EMPLOYEE_ID = B.DRIVER_ID)
    left outer join TRUCK Y ON (Y.TRUCK_ID = B.TRUCK_ID),
  STOP D
    left outer join V_MOVEDOUTSTOPS V on D.STOP_ID = V.movedtostop_id-- order 500713
    left outer join CONTACTPERSON Z ON D.CONTACTPERSON_ID = Z.CONTACTPERSON_ID
    left outer join ROUTESTOP E ON D.ROUTESTOP_ID = E.ROUTESTOP_ID,
  PACKINGNOTE F,
  PACKINGNOTELINE G
    left outer join (PACKINGNOTELINEPERDELSCHEME H
      left outer join DELIVERYSCHEME L ON H.DELIVERYSCHEME_ID = L.DELIVERYSCHEME_ID)
        ON G.PACKINGNOTELINE_ID = H.PACKINGNOTELINE_ID,
  PRODUCT I,
  SIZEDEFINITION J,
  DISTRIBUTIONPOINT M, DELIVERYPOINT N, DEPARTMENT O,
  CUSTOMER P
    left outer join customerlockermanagement clm ON (p.customer_id = clm.customer_id),
  FINISHINGMETHOD R, PLANT S, ADDRESS T, STATUS U, LANGUAGES, COUNTRY W, reportparam rp
WHERE A.ROUTE_ID = B.ROUTE_ID AND
  A.ROUTECONTROL_ID = D.ROUTECONTROL_ID AND
  D.STOP_ID = F.STOP_ID AND
  F.PACKINGNOTE_ID = G.PACKINGNOTE_ID AND
  G.PRODUCT_ID = I.PRODUCT_ID AND
  G.SIZEDEFINITION_ID = J.SIZEDEFINITION_ID AND
  F.DISTRIBUTIONPOINT_ID = M.DISTRIBUTIONPOINT_ID AND
  F.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND
  M.DEPARTMENT_ID = O.DEPARTMENT_ID AND
  D.CUSTOMER_LINK_ID = P.CUSTOMER_ID AND
  G.FINISHINGMETHOD_ID = R.FINISHINGMETHOD_ID AND
  A.PLANT_ID = S.PLANT_ID AND
  N.DELIVERYADDRESS_ID = T.ADDRESS_ID AND
  F.STATUS_ID = U.STATUS_ID AND
  U.STATUSTYPE = 'PN' AND
  U.CODE <> '40'and
  (d.status = 0 or d.status = 3)--TNE order500701
  AND P.COUNTRY_ID = W.COUNTRY_ID --TNE ORDER 500713
and rp.NUMBER_VALUE = a.ROUTECONTROL_ID
UNION ALL          -- 2 --
SELECT
0 notenumber,
  F_SHOW_ROUTESTOP(d.stop_id, d.routestop_id, s.plant_id) showstop,
  A.ROUTECONTROL_ID, D.DELIVERYPOINT_ID STOPDELIVERYPOINT_ID, N.DELIVERYPOINT_ID PN_DELIVERYPOINT_ID,
  S.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, A.DRIVINGDATE,
  C.CODE DEPOTCODE, C.DESCRIPTION DEPOTDESCRIPTION, A.LOADINGDOCK, A.STARTTIME,
  X.NAME DRIVERNAME, Y.CODE TRUCKCODE, Y.DESCRIPTION TRUCKDESCRIPTION,
  D.STOPNUMBER, P.CUSTOMERNUMBER, P.NAME CUSTOMERNAME,
  T.STREET DELIVERYADDRESS1, T.STREET2 DELIVERYADDRESS2, T.CITY, T.STATE, T.ZIPCODE,
  '' C_DELIVERYADDRESS1, '' C_DELIVERYADDRESS2, '' C_CITY, '' C_STATE, '' C_ZIPCODE,
case when d.routestop_id is null then d.routelistinstructions else E.ROUTELISTINSTRUCTIONS end ROUTELISTINSTRUCTIONS,
  Z.NAME CONTACTPERSONNAME, Z.PHONE CONTACTPERSONPHONE, P.PHONENO CUSTOMERPHONE,  D.STOP_ID,
  O.DEPARTMENTNUMBER, M.DISTRIBUTIONPOINTNUMBER, N.CODE DELIVERYPOINTCODE,
  O.DESCRIPTION DEPARTMENTDESC, M.DESCRIPTION DISTRIBUTIONPOINTDESC, N.DESCRIPTION DELIVERYPOINTDESC,
  I.CODE PRODUCTCODE, J.CODE SIZECODE, R.CODE FINISHINGMETHODCODE, L.CODE DELIVERYSCHEMECODE,
  (SELECT description FROM PRODUCT_DESC W WHERE I.PRODUCT_ID = W.PRODUCT_ID AND W.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
  NULL DELIVERYSCHEMESTARTDATE,
  0 QTYDELIVERED, K.QTYEXPECTED QTYEXPECTED, k.endcontract,
  LANGUAGES.CODE LANGUAGECODE, 1 detail, V.routenumber movedroutenumber, V.description movedroutedescription, d.status,
  P.COUNTRY_ID CUSTOMERCOUNTRYID, W.DESCRIPTION COUNTRY, S.COUNTRY_ID PLANTCOUNTRYID,
  (select sum(cdd.typeofmerchadise) from CUSTOMERDELIVERYDAY CDD where P.CUSTOMER_ID = CDD.CUSTOMER_ID
     AND coalesce((select rm.drivingday_id from route rm where E.Route_Id=rm.route_id), B.DRIVINGDAY_ID) = CDD.DAY_ID
     and cdd.typeofmerchadise >=1 and cdd.typeofmerchadise <=2) typeofmerchadise,
  B.ROUTE_ID, coalesce(d.stoptype, 0) stoptype, rp.reportparam_id,
  coalesce(clm.showlockeronroutelist, 'N') showlockeronroutelist,
  I.PUTUPTYPE PUTUPTYPE_PRODUCT, 0 PUTUPTYPE_PLPC, 1 STRAIGHTEVENEXCHANGE,
  0 QTYDELIVERED_PNL, P.DELNOTEFORBULKPUTUPITEMS
  , (SELECT HH.STARTTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_START_TIME
  , (SELECT HH.ENDTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_END_TIME
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
FROM ROUTECONTROL A,
  ROUTE B
    left outer join DEPOT C ON (C.DEPOT_ID = B.DEPOT_ID)
    left outer join EMPLOYEE X ON (X.EMPLOYEE_ID = B.DRIVER_ID)
    left outer join TRUCK Y ON (Y.TRUCK_ID = B.TRUCK_ID),
  STOP D
    left outer join V_MOVEDOUTSTOPS V on D.STOP_ID = V.movedtostop_id-- order500701
    left outer join CONTACTPERSON Z ON D.CONTACTPERSON_ID = Z.CONTACTPERSON_ID
    left outer join ROUTESTOP E ON D.ROUTESTOP_ID = E.ROUTESTOP_ID,
  STRAIGHTEVENRETURN K, PRODUCT I, SIZEDEFINITION J, DELIVERYSCHEME L,
  DISTRIBUTIONPOINT M, DELIVERYPOINT N, DEPARTMENT O,
  CUSTOMER P
    left outer join customerlockermanagement clm ON (p.customer_id = clm.customer_id),
  FINISHINGMETHOD R, PLANT S, ADDRESS T, STATUS U, LANGUAGES, COUNTRY W, reportparam rp
WHERE A.ROUTE_ID = B.ROUTE_ID AND
  A.ROUTECONTROL_ID = D.ROUTECONTROL_ID AND
  D.STOP_ID = K.STOP_ID AND
  K.PRODUCT_ID = I.PRODUCT_ID AND
  K.SIZEDEFINITION_ID = J.SIZEDEFINITION_ID AND
  K.DELIVERYSCHEME_ID = L.DELIVERYSCHEME_ID AND
  K.DISTRIBUTIONPOINT_ID = M.DISTRIBUTIONPOINT_ID AND
  M.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND
  M.DEPARTMENT_ID = O.DEPARTMENT_ID AND
  D.CUSTOMER_LINK_ID = P.CUSTOMER_ID AND
  K.FINISHINGMETHOD_ID = R.FINISHINGMETHOD_ID AND
  A.PLANT_ID = S.PLANT_ID AND
  N.DELIVERYADDRESS_ID = T.ADDRESS_ID AND
  K.STATUS_ID = U.STATUS_ID AND
  U.STATUSTYPE = 'SR' AND
  U.CODE <> '30'and
  (d.status = 0 or d.status = 3)--TNE order500701
  AND P.COUNTRY_ID = W.COUNTRY_ID
and rp.NUMBER_VALUE = a.ROUTECONTROL_ID
UNION ALL             -- 3 --
SELECT
0 notenumber,
F_SHOW_ROUTESTOP(d.stop_id, d.routestop_id, s.plant_id) showstop,
  A.ROUTECONTROL_ID, D.DELIVERYPOINT_ID STOPDELIVERYPOINT_ID, 0 PN_DELIVERYPOINT_ID,
  S.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, A.DRIVINGDATE,
  C.CODE DEPOTCODE, C.DESCRIPTION DEPOTDESCRIPTION, A.LOADINGDOCK, A.STARTTIME,
  X.NAME DRIVERNAME, Y.CODE TRUCKCODE, Y.DESCRIPTION TRUCKDESCRIPTION,
  D.STOPNUMBER, P.CUSTOMERNUMBER, P.NAME CUSTOMERNAME,
  T.STREET DELIVERYADDRESS1, T.STREET2 DELIVERYADDRESS2, T.CITY, T.STATE, T.ZIPCODE,
  T2.STREET C_DELIVERYADDRESS1, T2.STREET2 C_DELIVERYADDRESS2, T2.CITY C_CITY, T2.STATE C_STATE, T2.ZIPCODE C_ZIPCODE,
case when d.routestop_id is null then d.routelistinstructions else E.ROUTELISTINSTRUCTIONS end ROUTELISTINSTRUCTIONS,
  Z.NAME CONTACTPERSONNAME, Z.PHONE CONTACTPERSONPHONE, P.PHONENO CUSTOMERPHONE, D.STOP_ID,
  -1 departmentnumber, -1 distributionpointnumber, dp.code deliverypointcode,
  '' departmentdesc, '' DISTRIBUTIONPOINTDESC, dp.description DELIVERYPOINTDESC,
  '' PRODUCTCODE,'' SIZECODE,'' FINISHINGMETHODCODE,'' DELIVERYSCHEMECODE,'' PRODUCTDESCRIPTION,null deliveryschemestartdate,0 QTYDELIVERED,0 QTYEXPECTED,'A' endcontract,
  LANGUAGES.CODE LANGUAGECODE, 0 detail, V.routenumber movedroutenumber, V.description movedroutedescription, d.status,
  P.COUNTRY_ID CUSTOMERCOUNTRYID, W.DESCRIPTION COUNTRY, S.COUNTRY_ID PLANTCOUNTRYID,
  (select sum(cdd.typeofmerchadise) from CUSTOMERDELIVERYDAY CDD where P.CUSTOMER_ID = CDD.CUSTOMER_ID
     AND coalesce((select rm.drivingday_id from route rm where E.Route_Id=rm.route_id), B.DRIVINGDAY_ID) = CDD.DAY_ID
     and cdd.typeofmerchadise >=1 and cdd.typeofmerchadise <=2) typeofmerchadise,
  B.ROUTE_ID, coalesce(d.stoptype, 0) stoptype, rp.reportparam_id,
  coalesce(clm.showlockeronroutelist, 'N') showlockeronroutelist,
  0 PUTUPTYPE_PRODUCT, 0 PUTUPTYPE_PLPC, 0 STRAIGHTEVENEXCHANGE,
  0 QTYDELIVERED_PNL, P.DELNOTEFORBULKPUTUPITEMS
  , (SELECT HH.STARTTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = DP.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_START_TIME
  , (SELECT HH.ENDTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = DP.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_END_TIME
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES ROUTESTOP_TRAVELMINUTES, E.SERVICEMINUTES ROUTESTOP_SERVICEMINUTES
FROM ROUTECONTROL A,
  ROUTE B
    left outer join DEPOT C ON (C.DEPOT_ID = B.DEPOT_ID)
    left outer join EMPLOYEE X ON (X.EMPLOYEE_ID = B.DRIVER_ID)
    left outer join TRUCK Y ON (Y.TRUCK_ID = B.TRUCK_ID),
  STOP D
    left outer join V_MOVEDOUTSTOPS V on D.STOP_ID = V.movedtostop_id-- order500701
    left outer join CONTACTPERSON Z ON D.CONTACTPERSON_ID = Z.CONTACTPERSON_ID
    left outer join DELIVERYPOINT DP LEFT OUTER JOIN ADDRESS T ON DP.DELIVERYADDRESS_ID = T.ADDRESS_ID
                    ON D.DELIVERYPOINT_ID = DP.DELIVERYPOINT_ID
    left outer join ROUTESTOP E ON D.ROUTESTOP_ID = E.ROUTESTOP_ID,
  CUSTOMER P
    left outer join customerlockermanagement clm ON (p.customer_id = clm.customer_id),
  PLANT S,
  LANGUAGES, ADDRESS T2, COUNTRY W, reportparam rp
WHERE A.ROUTE_ID = B.ROUTE_ID AND
  A.ROUTECONTROL_ID = D.ROUTECONTROL_ID AND
  D.CUSTOMER_LINK_ID = P.CUSTOMER_ID AND
  P.VISITADDRESS_ID = T2.ADDRESS_ID AND
  A.PLANT_ID = S.PLANT_ID AND
  D.ROUTECONTROL_ID = A.ROUTECONTROL_ID and
  (d.status = 0 or d.status = 3)--TNE order500701
  AND P.COUNTRY_ID = W.COUNTRY_ID
  and rp.NUMBER_VALUE = a.ROUTECONTROL_ID
/

  CREATE OR REPLACE VIEW "V_SALESMONITORPERCUSTOMER" ("INVOICEHEADER_ID", "PARENTINVOICEHEADER_ID", "INVOICENUMBER", "ISCONSOLIDATEINV", "YEAR", "WEEK", "FREQUENCY", "PAYTHISAMOUNT", "TOTALAMOUNTEXCLVAT", "PROCESSINGBUSINESSUNIT_ID", "PROCBUCODE", "PROCBUDESC", "PLANT", "PLANTNAME", "INVOICINGBU_ID", "BUSINESSUNIT", "BUSINESSUNITDESC", "INVOICEDATE", "DEPOT", "DEPOTDESC", "ROUTENUMBER", "ROUTEDESC", "STATE", "MARKETSEGMENT", "MARKETSEGMENTDESC", "SICCODE", "MASTERACCOUNTCUST", "MASTERACCOUNTNUMBER", "MASTERACCOUNT", "CHAIN", "CHAINNAME", "CUSTOMERNUMBER", "CUSTOMERNAME", "LANGUAGECODE") AS 
  select /*version 2.0*/
       b.invoiceheader_id, b.parentinvoiceheader_id, b.invoicenumber, b.isconsolidateinv, b.year, b.week, b.frequency,
       (select sum(case when ili.adjustmentreason_id is not null then ili.adjustedamount
                        else ili.amount
                   end)
          from invoiceline ili
         where ili.invoiceheader_id = b.invoiceheader_id
           and coalesce(ili.processingbusinessunit_id, b.processingbusinessunit_id) = b.processingbusinessunit_id
           and ili.extend = 'Y') paythisamount,
       nvl((select sum(case when ili.adjustmentreason_id is not null then ili.adjustedamount
                        else ili.amount
                   end)
              from invoiceline ili
             where ili.invoiceheader_id = b.invoiceheader_id
               and ili.invoicelinetype_id <> 18
               and coalesce(ili.processingbusinessunit_id, b.processingbusinessunit_id) = b.processingbusinessunit_id
               and ili.extend = 'Y'), 0) totalamountexclvat,
       b.processingbusinessunit_id, b.procbucode, b. procbudesc, b.plant, b.plantname,b.invoicingbu_id,
       b.businessunit, b.businessunitdesc, b.invoicedate, b.depot, b.depotdesc, b.routenumber, b.routedesc,
       b.state,  b.marketsegment, b. marketsegmentdesc, b.siccode, b.masteraccountcust, b.masteraccountnumber,
       b.masteraccount, b.chain, b.chainname, b.customernumber,b.customername, b.languagecode
from v_salesmonitorpercustomer_aux b
group by b.invoiceheader_id, b.parentinvoiceheader_id, b.invoicenumber,b.isconsolidateinv, b.year, b.week, b.frequency,
         b.processingbusinessunit_id, b.procbucode, b. procbudesc, b. plant, b.plantname,b.invoicingbu_id, b.businessunit,
         b.businessunitdesc, b.invoicedate, b.depot, b.depotdesc, b.routenumber, b.routedesc,b.state,  b.marketsegment,
         b.marketsegmentdesc, b.siccode, b.masteraccountcust, b.masteraccountnumber, b.masteraccount, b.chain, b.chainname,
         b.customernumber, b.customername, b.languagecode
/

  CREATE OR REPLACE VIEW "V_SEASONWEEK" ("CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "FULLNAME", "DEPARTMENTNUMBER", "PRODUCTCODE", "SIZECODE", "FINMETHCODE", "PRODUCTDESC", "TEMPORARYRENTSTOPSTARTDATE", "TEMPORARYRENTSTOPENDDATE", "SEASONTYPECODE", "REPORTPARAM_ID", "CUSTOMERLANGUAGE_ID", "LANGUAGE_ID", "LANGUAGECODE") AS 
  select distinct
  cu.customernumber, cu.name customerName
, we.wearernumber, we.fullname, dep.departmentnumber
, prd.code productCode, sz.code sizeCode, fm.code finmethCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, wi.temporaryrentstopstartdate, wi.temporaryrentstopenddate
, ( select v.seasontypeCode from v_seasonweek_aux v where v.reportparam_id = rp.reportparam_id
  and v.season_id = wi.season_id ) seasontypeCode
, rp.reportparam_id
, cu.language_id customerlanguage_id, languages.language_id, languages.code languageCode
from
  customer cu
, wearer we, weareremployment wey, distributionpoint dip, department dep, wearerinventory wi
, product prd, sizedefinition sz, finishingmethod fm, businessunitsperusergroup bug, systemuser su
, reportparam rp, languages
where
    cu.customer_id = we.customer_id
and we.wearer_id = wey.wearer_id
    and wey.distributionpoint_id = dip.distributionpoint_id
        and dip.department_id = dep.department_id
    and wey.weareremployment_id = wi.weareremployment_id
and wi.product_id = prd.product_id
and wi.sizedefinition_id = sz.sizedefinition_id
and wi.finishingmethod_id = fm.finishingmethod_id
and cu.defaultbusinessunit_id = bug.businessunit_id
and rp.systemuser_id = su.systemuser_id
and su.usergroup_id = bug.usergroup_id
and    ( wi.temporaryrentstopSTARTdate between rp.date_value1 and rp.date_value2 -- intersection
        or
      wi.temporaryrentstopENDdate between rp.date_value1 and rp.date_value2  -- intersection
        or
      ( wi.temporaryrentstopSTARTdate <= rp.date_value1 and wi.temporaryrentstopENDdate >= rp.date_value2  ) -- included
        or
      exists
        ( select v.seasontypeCode from v_seasonweek_aux v
          where v.reportparam_id = rp.reportparam_id and v.season_id = wi.season_id )
    )
/

  CREATE OR REPLACE VIEW "V_SENDTOLAUNDRY" ("DEFAULTBUSINESSUNIT_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "STREET", "STREET2", "CITY", "ZIPCODE", "STATE", "PHONENO", "FAXNO", "EMAIL", "NROFCAGES", "WEARERNR", "PROD_CODE", "COLOR_CODE", "QTY", "PROD_DESC", "COLOR_DESC", "LANGUAGE_CODE", "LANGUAGE_ID") AS 
  select c.defaultbusinessunit_id, c.customer_id, c.customernumber, c.name customername,
ad.street, ad.street2, ad.city, ad.zipcode, ad.state, c.phoneno, c.faxno, c.email,
(select count(1) from V_SendToLaundryIDs v where v.customer_id = c.customer_id) NrOfCages,
(select wr.wearernumber from weareremployment we, wearer wr where we.weareremployment_id = s.weareremployment_link_id and wr.wearer_id = we.wearer_id) wearernr,
p.code prod_code, co.code color_code,  count(1) Qty,
(select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = lan.language_id) prod_desc,
(select cd.description from color_desc cd where cd.color_id = co.color_id and cd.language_id = lan.language_id) color_desc,
lan.code Language_Code, lan.language_id
from scan s, customer c, address ad, product p, color co, languages lan
where s.transactiontype_id = 68  --(send to laundry)
     and s.customer_link_id = c.customer_id
     and s.scantimestamp >= trunc(sysdate)
     and s.product_link_id = p.product_id
     and p.color_id = co.color_id
     and ad.address_id = c.visitaddress_id
     and c.language_id = lan.language_id
group by c.defaultbusinessunit_id, c.customer_id, c.customernumber,
c.name, c.phoneno, c.faxno, c.email,
ad.street, ad.street2, ad.city, ad.zipcode, ad.state,
s.weareremployment_link_id,
p.product_id, p.code, co.color_id, co.code,
lan.code, lan.language_id
/

  CREATE OR REPLACE VIEW "V_SKISSUENEWGARMENTS" ("LINETYPE", "TRANSACTIONDATE", "STOCKROOMCODE", "STOCKROOMNAME", "MANAGEDBYBU_ID", "REASONCODE", "FIRSTISSUE", "INVENTORYTRIGGER", "PRODUCTGROUPCODE", "PRODUCTCODE", "PRODUCTDESC", "REASONDESC", "ISSUEDNEW", "PURCHASEAMOUNT", "LANGUAGECODE", "DEPOT_CODE", "DEPOT_DESC", "ROUTENUMBER", "ROUTE_DESC") AS 
  select /*version 2.1*/
       1 linetype, trunc(ih.assigndate) transactiondate, sk.code stockroomcode, sk.name stockroomname,
       bu.businessunit_id managedbybu_id, rc.code reasoncode, rc.firstissue,
       rc.inventorytrigger, prdgr.code productgroupcode, prd.code productcode,
       (select pds.description
          from product_desc pds
         where pds.product_id = prd.product_id
           and pds.language_id = lan.language_id) productdesc,
       (select rds.description
          from reasoncode_desc rds
         where rds.reasoncode_id = rc.reasoncode_id
           and rds.language_id = lan.language_id) reasondesc,
       ih.quantity issuednew, uif.purchaseprice purchaseamount, lan.code languagecode,
       de.code depot_code, de.description depot_desc, r.routenumber, r.description route_desc
  from issuehistory ih
       left join stockroom sk on ih.stockroom_id = sk.stockroom_id
       left join uniqueitemfixedinfo uif on ih.uniqueitem_link_id = uif.uniqueitem_id
       join qualitygrade qg on ih.issuegrade_id = qg.qualitygrade_id
       join reasoncode rc on ih.reasoncode_id = rc.reasoncode_id
       join customer cu on ih.customer_link_id = cu.customer_id
       join product prd
            join productgroup prdgr on prd.productgroup_id = prdgr.productgroup_id
       on ih.product_link_id = prd.product_id
       join businessunit bu
            join route r
                 left join depot de on r.depot_id = de.depot_id
            on bu.plant_id = r.plant_id
       on ih.forbusinessunit_id = bu.businessunit_id
       cross join languages lan
 where qg.newgarment = 'Y'
   and rc.garmentreason = 'Y'
   and prd.typeofmerchandise = 2
   and r.route_id in (select v.min_route_id
                        from v_mincustomerroute v
                       where v.customer_id = cu.customer_id)
 union all
select 2 linetype, trunc(ih.assigndate) transactiondate, sk.code stockroomcode, sk.name stockroomname,
       bu.businessunit_id managedbybu_id, rc.code reasoncode, rc.firstissue,
       rc.inventorytrigger, prdgr.code productgroupcode, prd.code productcode,
       (select pds.description
          from product_desc pds
         where pds.product_id = prd.product_id
           and pds.language_id = lan.language_id) productdesc,
       (select rds.description
          from reasoncode_desc rds
         where rds.reasoncode_id = rc.reasoncode_id
           and rds.language_id = lan.language_id) reasondesc,
       ih.quantity issuednew, uif.purchaseprice purchaseamount, lan.code languagecode,
       null depot_code, null depot_desc, null routenumber, null route_desc
  from issuehistory ih
       left join stockroom sk on ih.stockroom_id = sk.stockroom_id
       left join uniqueitemfixedinfo uif on ih.uniqueitem_link_id = uif.uniqueitem_id
       join businessunit bu on ih.forbusinessunit_id = bu.businessunit_id
       join qualitygrade qg on ih.issuegrade_id = qg.qualitygrade_id
       join reasoncode rc on ih.reasoncode_id = rc.reasoncode_id
       join product prd
            join productgroup prdgr on prd.productgroup_id = prdgr.productgroup_id
       on ih.product_link_id = prd.product_id
       cross join languages lan
 where qg.newgarment = 'Y'
   and rc.garmentreason = 'Y'
   and prd.typeofmerchandise = 2
   and ih.customer_link_id not in (select cu.customer_id from customer cu)
 union all -- non uniqueitems
select 3 linetype, trunc(ih.assigndate) transactiondate, sk.code stockroomcode, sk.name stockroomname,
       bu.businessunit_id managedbybu_id, rc.code reasoncode, rc.firstissue,
       rc.inventorytrigger, prdgr.code productgroupcode, prd.code productcode,
       (select pds.description
          from product_desc pds
         where pds.product_id = prd.product_id
           and pds.language_id = lan.language_id) productdesc,
       (select rds.description
          from reasoncode_desc rds
         where rds.reasoncode_id = rc.reasoncode_id
           and rds.language_id = lan.language_id) reasondesc,
       ih.quantity issuednew,
       (f_getstockroomprice(ih.issuegrade_id, nvl(ih.stockroom_id,-1), ih.product_link_id, sizedefinition_link_id, ih.assigndate) * ih.quantity) purchaseamount,
       lan.code languagecode, null depot_code, null depot_desc, null routenumber, null route_desc
  from issuehistory ih
       left join stockroom sk on ih.stockroom_id = sk.stockroom_id
       join businessunit bu on ih.forbusinessunit_id = bu.businessunit_id
       join qualitygrade qg on ih.issuegrade_id = qg.qualitygrade_id
       join reasoncode rc on ih.reasoncode_id = rc.reasoncode_id
       join product prd
            join productgroup prdgr on prd.productgroup_id = prdgr.productgroup_id
       on ih.product_link_id = prd.product_id
       cross join languages lan
 where qg.newgarment = 'Y'
   and rc.garmentreason = 'Y'
   and prd.typeofmerchandise = 2
   and ih.uniqueitem_link_id is null
/

  CREATE OR REPLACE VIEW "V_SOILREASONABILITY" ("ROUTECONTROL_ID", "REPORTPARAM_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "PRODUCT_CODE", "PRODUCT_DESCRIPTION", "SIZEDEFINITION_CODE", "SIZEDEFINITION_DESCRIPTION", "FM", "PICKUPDATE", "DRIVINGDATE", "SOILTICKETNUMBER", "CURRENTQTY", "NULLQTY", "MISSED", "INVENTORYQTY", "PICKUPQTY1", "PICKUPQTY2", "PICKUPQTY3", "PICKUPQTY4", "PICKUPQTY5", "PICKUPQTY6", "PICKUPQTY7", "PICKUPQTY8", "PICKUPQTY9", "PICKUPQTY10", "PICKUPQTY11", "PICKUPQTY12", "PICKUPQTY13", "NR_OF_COLUMNS", "ROUTENUMBER", "ROUTE_ID", "STOPNUMBER", "LANGUAGECODE", "BILLINGMETHOD") AS 
  select vsr.routecontrol_id, rp.reportparam_id, c.customernumber, c.name customername, pr.code product_code,
       (select prd.description
          from product_link_desc prd
         where prd.product_link_id = pr.product_id
           and prd.language_id = l.language_id) product_description, sd.code sizedefinition_code,
       (select sdd.description
          from sizedefinition_link_desc sdd
         where sdd.sizedefinition_link_id = sd.sizedefinition_id
           and sdd.language_id = l.language_id) sizedefinition_description,
       fm.code fm, rc.drivingdate pickupdate, rc.drivingdate, vsr.soilticketnumber,
       vsr.currentqty, vsr.nullqty, vsr.missed, vsr.inventoryqty,
       vsh.pickupqty1, vsh.pickupqty2, vsh.pickupqty3, vsh.pickupqty4, vsh.pickupqty5, vsh.pickupqty6, vsh.pickupqty7,
       vsh.pickupqty8, vsh.pickupqty9, vsh.pickupqty10, vsh.pickupqty11, vsh.pickupqty12, vsh.pickupqty13,
       vsh.nr_of_columns, r.routenumber, r.route_id, vsr.stopnumber, l.code languagecode,
       (select min(plpc.billingmethod)
          from productlistpercustomer plpc
         where plpc.customer_id = vsr.customer_id
           and plpc.product_id = vsr.product_id
           and plpc.sizedefinition_id = vsr.sizedefinition_id
           and trunc(sysdate) between plpc.dateactive and plpc.dateinactive) billingmethod
  from v_soilreasonability_curr vsr
       left join v_soilreasonability_hist vsh on vsr.reportparam_id = vsh.reportparam_id
                                             and vsr.routecontrol_id = vsh.routecontrol_id
                                             and vsr.customer_id = vsh.customer_id
                                             and vsr.product_id = vsh.product_id
                                             and vsr.sizedefinition_id = vsh.sizedefinition_id
                                             and vsr.finishingmethod_id = vsh.finishingmethod_id
       join routecontrol rc
            join route r on rc.route_id = r.route_id
       on vsr.routecontrol_id = rc.routecontrol_id
       join customer c on vsr.customer_id = c.customer_id
       join product pr on vsr.product_id = pr.product_id
       join sizedefinition sd on vsr.sizedefinition_id = sd.sizedefinition_id
       join finishingmethod fm on vsr.finishingmethod_id = fm.finishingmethod_id
       join reportparam rp on vsr.reportparam_id = rp.reportparam_id
     , languages l
 where rp.number_value = rc.routecontrol_id
 order by c.customernumber, pr.code, sd.code, fm.code
/

  CREATE OR REPLACE VIEW "V_SORTBATCHPREPARATION" ("SORTBATCHDEFINITION_ID", "PRIMARYID", "ROUTESTOP_ID", "CUSTOMER_ID", "EXPECTATIONLEVEL", "UNIQUEITEM_ID", "PLANT_ID") AS 
  select v.sortbatchdefinition_id, v.primaryid, min(v.routestop_id), v.customer_id, v.expectationlevel, v.uniqueitem_id, v.plant_id
from v_sortbatchpreparation_aux v
group by v.sortbatchdefinition_id, v.customer_id, v.expectationlevel, v.primaryid, v.uniqueitem_id, v.plant_id
/

  CREATE OR REPLACE VIEW "V_SPECIALCHARGEPERINVLINE" ("INVOICEDATE", "INVOICENUMBER", "LINENUMBER", "SPECIALCHARGECODE", "TIMESTAMP", "SYSTEMUSER_ID", "LANGUAGECODE") AS 
  select b.invoicedate, b.invoicenumber, b.linenumber, a.specialchargecode, a.timestamp, a.systemuser_id, LANGUAGES.CODE LANGUAGECODE
from specialchargeperinvline a, V_invoiceline b, LANGUAGES
where a.invoiceline_id = b.invoiceline_id
AND B.LANGUAGECODE = LANGUAGES.CODE
--order by b.invoicedate, b.invoicenumber, b.linenumber
/

  CREATE OR REPLACE VIEW "V_SPECIFICTURNOVERDEF" ("CUSTOMERNUMBER", "CUSTOMERNAME", "TYPE", "ITEMCODE", "ITEMDESC", "TURNOVERGROUPCODE", "TURNOVERGROUPDESC", "PERCENTAGE", "REPORTPARAM_ID", "LANGUAGECODE") AS 
  select cu.customernumber, cu.customername,
  cp.type, -- 1-4 product
  pr.code itemcode,
  (select prd.description from product_desc prd where pr.product_id = prd.product_id
    and prd.language_id = languages.language_id) itemdesc,
  tg.code turnovergroupcode,
  (select tgd.description from turnovergroup_desc tgd where tg.turnovergroup_id = tgd.turnovergroup_id
    and tgd.language_id = languages.language_id) turnovergroupdesc,
  cp.percentage,
  cu.reportparam_id, languages.code languagecode
from v_specificturnoverdef_cust cu, turnovergroup tg, customerproducttogdef cp, product pr,
  languages
where cu.customer_id = cp.customer_id
  and cp.turnovergroup_id = tg.turnovergroup_id
  and cp.product_id = pr.product_id
union all
select cu.customernumber, cu.customername,
  10 type, -- weighingcategory
  wc.code itemcode,
  (select wcd.description from weighingcategory_desc wcd where wc.weighingcategory_id = wcd.weighingcategory_id
    and wcd.language_id = languages.language_id) itemdesc,
  tg.code turnovergroupcode,
  (select tgd.description from turnovergroup_desc tgd where tg.turnovergroup_id = tgd.turnovergroup_id
    and tgd.language_id = languages.language_id) turnovergroupdesc,
  cw.percentage,
  cu.reportparam_id, languages.code languagecode
from v_specificturnoverdef_cust cu, turnovergroup tg, customerweighingcategtogdef cw,
  weighingcategpercustomer wcc, weighingcategory wc,
  languages
where cu.customer_id = wcc.customer_id
  and cw.turnovergroup_id = tg.turnovergroup_id
  and cw.weighingcategpercustomer_id = wcc.weighingcategpercustomer_id
  and wcc.weighingcategory_id = wc.weighingcategory_id
union all
select cu.customernumber, cu.customername,
  11 type, -- 11 specialcharge
  sc.code itemcode,
  (select scd.description from specialcharge_desc scd where sc.specialcharge_id = scd.specialcharge_id
    and scd.language_id = languages.language_id) itemdesc,
  tg.code turnovergroupcode,
  (select tgd.description from turnovergroup_desc tgd where tg.turnovergroup_id = tgd.turnovergroup_id
    and tgd.language_id = languages.language_id) turnovergroupdesc,
  cs.percentage,
  cu.reportparam_id, languages.code languagecode
from v_specificturnoverdef_cust cu, turnovergroup tg, customerspecialchargetogdef cs, specialcharge sc,
  languages
where cu.customer_id = cs.customer_id
  and sc.turnovergroup_id = tg.turnovergroup_id
  and cs.specialcharge_id = sc.specialcharge_id
union all
select cu.customernumber, cu.customername,
  12 type, -- 12 invoiceline
  CAST(CASTNUMBERASVARCHARWITHFORMAT(it.type, '09') AS VARCHAR2(3)) itemcode,
  (select itd.description from invoicelinetype_desc itd where it.invoicelinetype_id = itd.invoicelinetype_id
    and itd.language_id = languages.language_id) itemdesc,
  tg.code turnovergroupcode,
  (select tgd.description from turnovergroup_desc tgd where tg.turnovergroup_id = tgd.turnovergroup_id
    and tgd.language_id = languages.language_id) turnovergroupdesc,
  ci.percentage,
  cu.reportparam_id, languages.code languagecode
from v_specificturnoverdef_cust cu, turnovergroup tg, customerinvlinetypetogdef ci, invoicelinetype it,
  languages
where cu.customer_id = ci.customer_id
  and ci.turnovergroup_id = tg.turnovergroup_id
  and ci.invoicelinetype_id = it.invoicelinetype_id
/

  CREATE OR REPLACE VIEW "V_STANDARDDELIVERYLINE" ("CUSTOMERNUMBER", "NAME", "DEPARTMENTNUMBER", "DESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "SIZEDEFINITION_DESC", "FINISHINGMETHODCODE", "FINISHINGMETHOD_DESC", "DELIVERYSCHEMECODE", "LOCATION", "REMARKFORPACKINGINSTRUCTIONS", "SEASONCODE", "STANDARDDELIVERYLINE_ID", "AMOUNT_MO", "AMOUNT_TU", "AMOUNT_WE", "AMOUNT_TH", "AMOUNT_FR", "AMOUNT_SA", "AMOUNT_SU", "SYSTEMUSER_ID", "TIMESTAMP", "STANDARDDELIVERY_ID", "LANGUAGECODE") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION,
DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION distributionpointdesc,
PRODUCT.CODE productcode,
( select DESCRIPTION from PRODUCT_DESC a where a.product_id = PRODUCTLISTPERDISTRIBPOINT.PRODUCT_ID and a.language_id = languages.language_id) productdesc,
 SIZEDEFINITION.CODE sizecode,
( select DESCRIPTION from SIZEDEFINITION_DESC b where b.SIZEDEFINITION_id = PRODUCTLISTPERDISTRIBPOINT.SIZEDEFINITION_ID and b.language_id = languages.language_id) SIZEDEFINITION_DESC,
FINISHINGMETHOD.CODE finishingmethodcode,
( select DESCRIPTION from FINISHINGMETHOD_DESC c where c.FINISHINGMETHOD_id = PRODUCTLISTPERDISTRIBPOINT.FINISHINGMETHOD_ID and c.language_id = languages.language_id) FINISHINGMETHOD_DESC,
  DELIVERYSCHEME.CODE deliveryschemecode,
 STANDARDDELIVERYLINE.LOCATION, STANDARDDELIVERYLINE.REMARKFORPACKINGINSTRUCTIONS,
--STANDARDDELIVERYLINE.TEMPORARYSTOPSTARTWEEK, STANDARDDELIVERYLINE.TEMPORARYSTOPENDWEEK, -- for 501956
--STANDARDDELIVERYLINE.TEMPORARYSTOPSTARTYEAR, STANDARDDELIVERYLINE.TEMPORARYSTOPENDYEAR,
--STANDARDDELIVERYLINE.TEMPSTOPRENTFORWEEK, STANDARDDELIVERYLINE.TEMPSTOPRENTFORYEARWEEK,
--STANDARDDELIVERYLINE.TEMPSTOPSTARTWEEKFORYEAR, STANDARDDELIVERYLINE.TEMPSTOPENDWEEKFORYEAR,
season.code seasoncode,
V_standarddeliveryamount."STANDARDDELIVERYLINE_ID",V_standarddeliveryamount."AMOUNT_MO",V_standarddeliveryamount."AMOUNT_TU",V_standarddeliveryamount."AMOUNT_WE",V_standarddeliveryamount."AMOUNT_TH",V_standarddeliveryamount."AMOUNT_FR",V_standarddeliveryamount."AMOUNT_SA",V_standarddeliveryamount."AMOUNT_SU",
STANDARDDELIVERYLINE.SYSTEMUSER_ID,
STANDARDDELIVERYLINE. TIMESTAMP, standarddeliveryline.standarddelivery_id, LANGUAGES.CODE languagecode
	FROM
CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT,
PRODUCT, SIZEDEFINITION,
FINISHINGMETHOD,
STANDARDDELIVERYLINE
  left outer join deliveryscheme on standarddeliveryline.deliveryscheme_id = deliveryscheme.deliveryscheme_id
  left outer join season on standarddeliveryline.season_id = season.season_id
, PRODUCTLISTPERDISTRIBPOINT,
STANDARDDELIVERY
,V_STANDARDDELIVERYAMOUNT,LANGUAGES
	WHERE
 STANDARDDELIVERY.STANDARDDELIVERY_ID = STANDARDDELIVERYLINE.STANDARDDELIVERY_ID
and STANDARDDELIVERYLINE.STANDARDDELIVERYLINE_ID = V_STANDARDDELIVERYAMOUNT.STANDARDDELIVERYLINE_ID
AND STANDARDDELIVERYLINE.PRODUCTLISTPERDISTRIBPOINT_ID = PRODUCTLISTPERDISTRIBPOINT.PRODUCTLISTPERDISTRIBPOINT_ID
and PRODUCTLISTPERDISTRIBPOINT.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
and DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
and DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
and PRODUCTLISTPERDISTRIBPOINT.PRODUCT_ID = PRODUCT.PRODUCT_ID
and PRODUCTLISTPERDISTRIBPOINT.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
and PRODUCTLISTPERDISTRIBPOINT.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
/

  CREATE OR REPLACE VIEW "V_STDELIVAGREEMENTS" ("CUSTOMERNUMBER", "NAME", "DEPARTMENTNUMBER", "DESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DELIVERYSCHEMECODE", "DISTRIBUTIONPOINTDESC", "PRODUCTCODE", "SIZECODE", "FINISHINGMETHODCODE", "DATEACTIVE", "DATEINACTIVE", "LOCATION", "REMARKFORPACKINGINSTRUCTIONS", "SEASONCODE", "AMOUNT_SU", "STANDARDDELIVERYLINE_ID", "AMOUNT_MO", "AMOUNT_TU", "AMOUNT_WE", "AMOUNT_TH", "AMOUNT_FR", "AMOUNT_SA", "SYSTEMUSER_ID", "TIMESTAMP", "STANDARDDELIVERY_ID", "LANGUAGECODE", "CUSTOMER_ID", "PRICE", "PRODUCTDESC", "SIZEDEFINITION_DESC", "FINISHINGMETHOD_DESC", "PREVIOUSDELIVERYDATE", "NEXTDELIVERYDATE", "CURRENCYDECIMALS") AS 
  select /*version 2.1*/
       cu.customernumber, cu.name, de.departmentnumber, de.description, dp.distributionpointnumber, ds.code deliveryschemecode,
       dp.description distributionpointdesc, pr.code productcode, sd.code sizecode, fm.code finishingmethodcode,
       sdl.dateactive, sdl.dateinactive, sdl.location, sdl.remarkforpackinginstructions, ses.code seasoncode, vsda.amount_su,
       vsda.standarddeliveryline_id, vsda.amount_mo, vsda.amount_tu, vsda.amount_we, vsda.amount_th, vsda.amount_fr, vsda.amount_sa,
       sdl.systemuser_id, sdl.timestamp, sdl.standarddelivery_id, lan.code languagecode, cu.customer_id,
       pack_price.wash_price(cu.customer_id, pr.product_id, sd.sizedefinition_id, fm.finishingmethod_id, trunc(sysdate)) price,
       (select pds.description
          from product_desc pds
         where pds.product_id = plpd.product_id
           and pds.language_id = lan.language_id) productdesc,
       (select szd.description
          from sizedefinition_desc szd
         where szd.sizedefinition_id = plpd.sizedefinition_id
           and szd.language_id = lan.language_id) sizedefinition_desc,
       (select fmd.description
          from finishingmethod_desc fmd
         where fmd.finishingmethod_id = plpd.finishingmethod_id
           and fmd.language_id = lan.language_id) finishingmethod_desc,
       case when sdl.dateactive > trunc(sysdate) then to_date('2099/12/31', 'yyyy/mm/dd')
            else (select max(dh.deliverydate)
                    from deliveryhistory dh
                   where dh.customer_link_id = cu.customer_id
                     and dh.department_link_id = de.department_id
                     and dh.distributionpoint_link_id = dp.distributionpoint_id
                     and dh.product_link_id = pr.product_id
                     and dh.sizedefinition_link_id = sd.sizedefinition_id
                     and dh.finishingmethod_id = fm.finishingmethod_id
                     and dh.amountstandard > 0
                     and dh.deliverydate <= trunc(sysdate))
        end previousdeliverydate,
       case when sdl.dateinactive < trunc(sysdate) then to_date('2099/12/31', 'yyyy/mm/dd')
            when sdl.dateactive > trunc(sysdate) then f_getnextdeliverydate(sdl.dateactive, cu.customer_id, pr.typeofmerchandise, sdl.deliveryscheme_id)
            when sdl.dateinactive < f_getnextdeliverydate(trunc(sysdate), cu.customer_id, pr.typeofmerchandise, sdl.deliveryscheme_id) then to_date('2099/12/31', 'yyyy/mm/dd')
            else f_getnextdeliverydate(trunc(sysdate), cu.customer_id, pr.typeofmerchandise, sdl.deliveryscheme_id)
        end nextdeliverydate,
       (select cur.decimals
          from currency cur
         where cur.currency_id = cu.currency_id) currencydecimals
  from standarddelivery sdd
            join standarddeliveryline sdl
                 left join deliveryscheme ds on sdl.deliveryscheme_id = ds.deliveryscheme_id
                 left join season ses on sdl.season_id = ses.season_id
                 join v_standarddeliveryamount vsda on sdl.standarddeliveryline_id = vsda.standarddeliveryline_id
       on sdd.standarddelivery_id = sdl.standarddelivery_id
       join productlistperdistribpoint plpd
            join product pr on plpd.product_id = pr.product_id
            join sizedefinition sd on plpd.sizedefinition_id = sd.sizedefinition_id
            join finishingmethod fm on plpd.finishingmethod_id = fm.finishingmethod_id
            join distributionpoint dp
                 join department de
                      join customer cu on de.customer_id = cu.customer_id
                 on dp.department_id = de.department_id
            on plpd.distributionpoint_id = dp.distributionpoint_id
       on sdl.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
       cross join languages lan
/

  CREATE OR REPLACE VIEW "V_STOCKCOUNTSCHEDULEPERDAY" ("COUNTDAY", "CUSTOMERNUMBER", "EMAIL") AS 
  select 'FRI' COUNTDAY, t.customernumber, (select c.email from customer c where c.customernumber=t.customernumber) email from V_STOCKCOUNTSCHEDULE t
 where count_fr = 'Y'
 union
  select 'THU' COUNTDAY, t.customernumber, (select c.email from customer c where c.customernumber=t.customernumber) email from V_STOCKCOUNTSCHEDULE t
 where count_th = 'Y'
  union
  select 'WED' COUNTDAY, t.customernumber, (select c.email from customer c where c.customernumber=t.customernumber) email from V_STOCKCOUNTSCHEDULE t
 where count_we = 'Y'
   union
  select 'TUE' COUNTDAY, t.customernumber,(select c.email from customer c where c.customernumber=t.customernumber) email from V_STOCKCOUNTSCHEDULE t
 where count_tu = 'Y'
   union
  select 'MON' COUNTDAY, t.customernumber,(select c.email from customer c where c.customernumber=t.customernumber) email from V_STOCKCOUNTSCHEDULE t
 where count_mo = 'Y'
   union
  select 'SAT' COUNTDAY, t.customernumber,(select c.email from customer c where c.customernumber=t.customernumber) email from V_STOCKCOUNTSCHEDULE t
 where count_sa = 'Y'
   union
  select 'SUN' COUNTDAY, t.customernumber,(select c.email from customer c where c.customernumber=t.customernumber) email from V_STOCKCOUNTSCHEDULE t
 where count_su = 'Y'
/

  CREATE OR REPLACE VIEW "V_STOCKRECEPTION" ("STOCKCODE", "STOCKNAME", "STOCKROOM_ID", "RECEIVEDATE", "RECEIVEDATETRUNC", "RECEIVEDATETIME", "PURCHASEORDERNUMBER", "PICKINGSEQUENCE", "ROWCODE", "LOCATIONCODE", "CUSTOMEROWNED", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "FULLNAME", "PRODUCTCODE", "SIZECODE", "PRODUCTDESC", "QUANTITY", "WORKORDERNUMBER", "QTYDIFF", "WORKSTATIONCODE", "CUSTOMER_ID", "CUSTOMER_LINK_ID", "SUPPLIERNUMBER", "PRDGRPCODE", "LANGUAGECODE") AS 
  select
  sk.code stockCode, sk.name stockName, sk.stockroom_id, recSkhis.Receivedate, trunc(recSkhis.Receivedate) ReceivedateTrunc
, GETTIMEASNUMERIC(recSkhis.Receivedate) ReceivedateTime
, coalesce(recSkhis.Purchaseordernumber, -1) Purchaseordernumber, coalesce(skl.pickingsequence, -1) pickingsequence
, recSkhis.rowcode, recSkhis.locationcode, recSkhis.Customerowned
, vsx.customernumber, vsx.customerName, vsx.wearernumber, vsx.fullname
, prd.code productCode, sz.code sizeCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc, recSkhis.Quantity
, vsx.workordernumber, vsx.QtyDiff
, recSkhis.WorkstationCode, vsx.Customer_Id, recSkhis.Customer_Link_Id, vsx.suppliernumber,pg.code prdgrpcode
, languages.code languageCode
from
  receiveinstockhistory recSkhis
left outer join
    v_stockreception_aux vsx
           on  recSkhis.Purchaseordernumber = vsx.purchaseordernumber
           and recSkhis.Stockroom_Id = vsx.stockroom_id
           and recSkhis.Product_Link_Id = vsx.product_link_id
           and recSkhis.sizedefinition_link_id = vsx.sizedefinition_link_id
              -- and coalesce(recSkhis.Customer_Link_Id, -1) = vsx.Customer_Id -- ! --
left outer join  stockroomlocation skl on recSkhis.Stockroom_Id = skl.stockroom_id
                                       and recSkhis.Rowcode = skl.rowcode
                                       and recSkhis.Locationcode = skl.locationcode
, stockroom sk
, product prd,productgroup pg, sizedefinition sz
, languages
where
    recSkhis.Stockroom_Id = sk.stockroom_id
and recSkhis.Product_Link_Id = prd.product_id
and recSkhis.Sizedefinition_Link_Id = sz.sizedefinition_id
and prd.productgroup_id=pg.productgroup_id
/

  CREATE OR REPLACE VIEW "V_STOCKRECEPTIONPERDATE" ("STOCKCODE", "STOCKNAME", "STOCKROOM_ID", "RECEIVEDATE", "RECEIVEDATETRUNC", "RECEIVEDATETIME", "PURCHASEORDERNUMBER", "WONEEDEDDATE", "REFERENCENUMBER", "ROWCODE", "LOCATIONCODE", "CUSTOMEROWNED", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "FULLNAME", "PRODUCTCODE", "SIZECODE", "PRODUCTDESC", "SIZEDESC", "QUANTITY", "WORKORDERNUMBER", "QTYDIFF", "QTYRECEIVED", "WORKSTATIONCODE", "CUSTOMER_ID", "CUSTOMER_LINK_ID", "SUPPLIERNUMBER", "SUPPLIERNAME", "PURCHASEORDERLINE_ID", "RECEIVEINSTOCKHISTORY_ID", "PRDGRPCODE", "LANGUAGECODE") AS 
  select
  sk.code stockCode, sk.name stockName, sk.stockroom_id, recSkhis.Receivedate, trunc(recSkhis.Receivedate) ReceivedateTrunc
, GETTIMEASNUMERIC(recSkhis.Receivedate) ReceivedateTime
, coalesce(recSkhis.Purchaseordernumber, -1) Purchaseordernumber
, vsx.woneededdate
, vsx.referencenumber
, recSkhis.rowcode, recSkhis.locationcode, recSkhis.Customerowned
, vsx.customernumber, vsx.customerName, vsx.wearernumber, vsx.fullname
, prd.code productCode, sz.code sizeCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( select sizedefinition_desc.description from sizedefinition_desc where sizedefinition_desc.sizedefinition_id = sz.sizedefinition_id
  and sizedefinition_desc.language_id = languages.language_id ) sizedesc
, recSkhis.Quantity
, vsx.workordernumber, vsx.QtyDiff, vsx.QtyReceived
, recSkhis.WorkstationCode, vsx.Customer_Id, recSkhis.Customer_Link_Id, vsx.suppliernumber, vsx.suppliername
, vsx.purchaseorderline_id
, recSkhis.Receiveinstockhistory_Id, pg.code prdgrpcode
, languages.code languageCode
from
  receiveinstockhistory recSkhis,V_STOCKRECEPTIONPERDATE_AUX vsx, stockroom sk, product prd,productgroup pg, sizedefinition sz, languages
where
    recSkhis.Stockroom_Id = sk.stockroom_id
and recSkhis.Product_Link_Id = prd.product_id
and recSkhis.Sizedefinition_Link_Id = sz.sizedefinition_id
and prd.productgroup_id=pg.productgroup_id
and recSkhis.Purchaseordernumber = vsx.purchaseordernumber
           and recSkhis.Stockroom_Id = vsx.stockroom_id
           and recSkhis.Product_Link_Id = vsx.product_link_id
           and recSkhis.sizedefinition_link_id = vsx.sizedefinition_link_id
/

  CREATE OR REPLACE VIEW "V_SUMMARYDELIVEREDPRODUCTS" ("DELIVERYDATE", "TYPEOFMERCHANDISE", "PRODUCTGROUPCODE", "PRODUCTCODE", "PRODUCTDESC", "FINMETHCODE", "SIZECODE", "SIZEDESC", "FINMETHDESC", "ROUTENUMBER", "ROUTEDESC", "ROUTEPLANT_ID", "DEPOTCODE", "DEPOTDESC", "PLANTDEPCODE", "PLANTDEPDESC", "DISTRIBUTIONPOINTNUMBER", "DISTRIBPOINTDESC", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "DELIVEREDAMOUNT", "BUSINESSUNIT_ID", "INTERNALBU", "LANGUAGECODE", "PLANT_ID", "PLANT_CODE", "PLANT_NAME") AS 
  select /*version 1.1*/
       pn.deliverydate, pr.typeofmerchandise, pg.code productgroupcode, pr.code productcode,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = l.language_id) productdesc,
       fm.code finmethcode, sz.code sizecode,
       (select szd.description
          from sizedefinition_desc szd
         where szd.sizedefinition_id = sz.sizedefinition_id
           and szd.language_id = l.language_id) sizedesc,
       (select fmd.description
          from finishingmethod_desc fmd
         where fmd.finishingmethod_id = fm.finishingmethod_id
           and fmd.language_id = l.language_id) finmethdesc,
       ro.routenumber, coalesce(ro.description, '') routedesc, coalesce(ro.plant_id, bu.plant_id) routeplant_id,
       coalesce(de.code, '-') depotcode, coalesce(de.description, '-') depotdesc,
       pld.code plantdepcode, pld.description plantdepdesc,
       dp.distributionpointnumber, dp.description distribpointdesc,
       dep.departmentnumber, dep.description departmentdesc,
       cu.customernumber, cu.name customername, pnl.deliveredamount,
       bu.businessunit_id, internalbu.businessunit_id internalbu, l.code languagecode,
       pl.plant_id, pl.code plant_code, pl.name plant_name
  from packingnoteline pnl
       join packingnote pn
            left join route ro
                 left join depot de on ro.depot_id = de.depot_id
            on pn.route_id = ro.route_id
            left join businessunit internalbu on pn.internalprocessingbu_id = internalbu.businessunit_id
            join status st on pn.status_id = st.status_id
            join businessunit bu
                 join plant pl on bu.plant_id = pl.plant_id
            on pn.processbusinessunit_id = bu.businessunit_id
            join plantdepartment pld on pn.plantdepartment_id = pld.plantdepartment_id
            join distributionpoint dp
                 join department dep
                      join customer cu on dep.customer_id = cu.customer_id
                 on dp.department_id = dep.department_id
            on pn.distributionpoint_id = dp.distributionpoint_id
       on pnl.packingnote_id = pn.packingnote_id
       join product pr
            join productgroup pg on pr.productgroup_id = pg.productgroup_id
       on pnl.product_id = pr.product_id
       join sizedefinition sz on pnl.sizedefinition_id = sz.sizedefinition_id
       join finishingmethod fm on pnl.finishingmethod_id = fm.finishingmethod_id
       cross join languages l
 where ((bu.plant_id = pld.plant_id and exists
        (select v.customer_id
           from v_customersperbusinessunitdp v, businessunit b
          where v.customer_id = cu.customer_id
            and v.businessunit_id = b.businessunit_id
            and b.plant_id = bu.plant_id))
       or (internalbu.plant_id = pld.plant_id and exists
        (select v.customer_id
           from v_customersperbusinessunitdp v, businessunit b
          where v.customer_id = cu.customer_id
            and v.businessunit_id = b.businessunit_id
            and b.plant_id = internalbu.plant_id)))
   and coalesce(de.plant_id, bu.plant_id) = bu.plant_id
   and st.code = '30'
   and pn.origin <> 6
/

  CREATE OR REPLACE VIEW "V_TASK" ("ID", "VERSION", "NAME", "ACCOUNTNUMBER", "BILLINGACCOUNTNUMBER", "BILLINGACCOUNTNAME", "TERRITORY", "DEPARTMENT", "STREET", "POSTALCODE", "CITY", "COUNTRY", "GEOCODES", "SKILL", "ESTIMATEDDURATION", "EARLIEST", "LATEST", "SCHEDULED", "SCHEDULEDFOR", "REQUIREDRESOURCE", "PREFERREDRESOURCE", "BACKUPRESOURCE", "FIXED", "STATUS", "ACTUALDATETIME", "ACTUALDURATION", "OPENINGSHOURSMON", "OPENINGSHOURSTUE", "OPENINGSHOURSWED", "OPENINGSHOURSTHU", "OPENINGSHOURSFRI", "OPENINGSHOURSSAT", "OPENINGSHOURSSUN", "REMARKS", "WEIGHT", "VOLUME", "LASTUPDATE", "MESSAGECONFIRMED", "CONTRACTTYPE", "REQUIRESPARTS", "HOLIDAYCALENDERID", "PLANAUTOMATICALLY", "ASSIGNEDDATETIME", "MINIMUMRESOURCES", "MAXIMUMRESOURCES", "TASKGROUPID", "RESCHEDULE", "RESCHEDULEFOR", "PROVINCE", "POSITIONINTRIP", "ACCEPTBEYONDLATEST", "PARKINGGEOCODE", "TASKTYPE", "FLOATING", "SUBGROUP", "ROUNDEARLIESTLATEST", "STANDBY", "RESOURCEREQUIRED", "AMOUNT", "IMAGEURL", "PHONE", "EMAIL", "PROCESSFLOW", "ROUTECONTROLTIMESTAMP") AS 
  select to_char(st.stop_id) id, 1 version,
       (select trim(l.name) from customer_link l where l.customer_link_id = st.customer_link_id) name,
       (select l.customernumber from customer_link l where l.customer_link_id = st.customer_link_id) accountnumber,
       (select l.customernumber from customer_link l where l.customer_link_id = c.debtor_id) billingaccountnumber,
       (select trim(l.name) from customer_link l where l.customer_link_id = c.debtor_id) billingaccountname,
       (select pt.name from plant pt where pt.plant_id = rc.plant_id) territory,
       (select max(cpd.name)
         from   contactperson cpd
         where  cpd.customer_id = c.customer_id
         and    cpd.contactpersonnumber = (select min(cp.contactpersonnumber)
                                           from   contactperson cp
                                           where  cp.customer_id = c.customer_id
                                           and    cp.podcontact <> 0)) department,
       case
         when adp.address_id is null then
          cva.street
         else
          adp.street
       end street,
       case
         when adp.address_id is null then
          cva.zipcode
         else
          adp.zipcode
       end postalcode,
       case
         when adp.address_id is null then
          cva.city
         else
          adp.city
       end city, (select ct.code from country ct where ct.country_id = c.country_id) country,
       '0_0_' || coalesce((select ds.gpswidth || '_' || ds.gpslength
                           from   deliverysignature ds
                           where  ds.stop_id = st.stop_id
                           and    ds.gpswidth is not null
                           and    ds.gpslength is not null),
                           (select max(dp.code || '_' || dp.description)
                             from   deliverypoint dp
                             where  dp.customer_id = c.customer_id
                             and    dp.active = 'N'
                             and    dp.sortaddress = 'GEOC'), '0_0') || ' 4' geocodes, null skill,
       case
         when rs.serviceminutes > 0 or rs.serviceminutes <> null then
          rs.serviceminutes
         else
          10
       end estimatedduration, to_char(rc.drivingdate, 'YYYY-MM-DD') || ' 00:00:00' earliest,
       to_char(rc.drivingdate + 1, 'YYYY-MM-DD') || ' 00:00:00' latest,
       case
         when st.stopnumber < 0 then
          null
         else
          to_date(to_char(rc.drivingdate, 'YYYY-MM-DD') || ' 06:00:00', 'YYYY-MM-DD HH24:MI:SS') +
          (.000694 * st.stopnumber)
       end scheduled,
       case
         when st.stopnumber < 0 then
          null
         else
          r.routenumber
       end scheduledfor,
       (select tk.code from truck tk where tk.truck_id = r.truck_id) requiredresource,
       null preferredresource, null backupresource, null fixed,
       case
         when st.stopnumber < 0 then
          'PL'
         else
          'IP'
       end status, null actualdatetime, null actualduration,
       coalesce((select case
                          when dph.starttime is not null and dph.endtime is not null then
                           case
                             when x.breakstarttime is not null and x.breakendtime is not null then
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(x.breakstarttime, 'HH24:MI') || ' ' ||
                              to_char(x.breakendtime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI')
                             else
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI') || ' 00:00-00:00'
                           end
                          else
                           '00:00-00:00 00:00-00:00'
                        end
                 from   deliverypointopeninghour dph, deliverypoint x
                 where  dph.deliverypoint_id = coalesce(dp.deliverypoint_id, dpc.deliverypoint_id)
                 and    dph.deliverypoint_id = x.deliverypoint_id
                 and    dph.day_id = 1), '00:00-00:00 00:00-00:00') openingshoursmon,
       coalesce((select case
                          when dph.starttime is not null and dph.endtime is not null then
                           case
                             when x.breakstarttime is not null and x.breakendtime is not null then
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(x.breakstarttime, 'HH24:MI') || ' ' ||
                              to_char(x.breakendtime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI')
                             else
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI') || ' 00:00-00:00'
                           end
                          else
                           '00:00-00:00 00:00-00:00'
                        end
                 from   deliverypointopeninghour dph, deliverypoint x
                 where  dph.deliverypoint_id = coalesce(dp.deliverypoint_id, dpc.deliverypoint_id)
                 and    dph.deliverypoint_id = x.deliverypoint_id
                 and    dph.day_id = 2), '00:00-00:00 00:00-00:00') openingshourstue,
       coalesce((select case
                          when dph.starttime is not null and dph.endtime is not null then
                           case
                             when x.breakstarttime is not null and x.breakendtime is not null then
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(x.breakstarttime, 'HH24:MI') || ' ' ||
                              to_char(x.breakendtime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI')
                             else
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI') || ' 00:00-00:00'
                           end
                          else
                           '00:00-00:00 00:00-00:00'
                        end
                 from   deliverypointopeninghour dph, deliverypoint x
                 where  dph.deliverypoint_id = coalesce(dp.deliverypoint_id, dpc.deliverypoint_id)
                 and    dph.deliverypoint_id = x.deliverypoint_id
                 and    dph.day_id = 3), '00:00-00:00 00:00-00:00') openingshourswed,
       coalesce((select case
                          when dph.starttime is not null and dph.endtime is not null then
                           case
                             when x.breakstarttime is not null and x.breakendtime is not null then
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(x.breakstarttime, 'HH24:MI') || ' ' ||
                              to_char(x.breakendtime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI')
                             else
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI') || ' 00:00-00:00'
                           end
                          else
                           '00:00-00:00 00:00-00:00'
                        end
                 from   deliverypointopeninghour dph, deliverypoint x
                 where  dph.deliverypoint_id = coalesce(dp.deliverypoint_id, dpc.deliverypoint_id)
                 and    dph.deliverypoint_id = x.deliverypoint_id
                 and    dph.day_id = 4), '00:00-00:00 00:00-00:00') openingshoursthu,
       coalesce((select case
                          when dph.starttime is not null and dph.endtime is not null then
                           case
                             when x.breakstarttime is not null and x.breakendtime is not null then
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(x.breakstarttime, 'HH24:MI') || ' ' ||
                              to_char(x.breakendtime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI')
                             else
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI') || ' 00:00-00:00'
                           end
                          else
                           '00:00-00:00 00:00-00:00'
                        end
                 from   deliverypointopeninghour dph, deliverypoint x
                 where  dph.deliverypoint_id = coalesce(dp.deliverypoint_id, dpc.deliverypoint_id)
                 and    dph.deliverypoint_id = x.deliverypoint_id
                 and    dph.day_id = 5), '00:00-00:00 00:00-00:00') openingshoursfri,
       coalesce((select case
                          when dph.starttime is not null and dph.endtime is not null then
                           case
                             when x.breakstarttime is not null and x.breakendtime is not null then
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(x.breakstarttime, 'HH24:MI') || ' ' ||
                              to_char(x.breakendtime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI')
                             else
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI') || ' 00:00-00:00'
                           end
                          else
                           '00:00-00:00 00:00-00:00'
                        end
                 from   deliverypointopeninghour dph, deliverypoint x
                 where  dph.deliverypoint_id = coalesce(dp.deliverypoint_id, dpc.deliverypoint_id)
                 and    dph.deliverypoint_id = x.deliverypoint_id
                 and    dph.day_id = 6), '00:00-00:00 00:00-00:00') openingshourssat,
       coalesce((select case
                          when dph.starttime is not null and dph.endtime is not null then
                           case
                             when x.breakstarttime is not null and x.breakendtime is not null then
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(x.breakstarttime, 'HH24:MI') || ' ' ||
                              to_char(x.breakendtime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI')
                             else
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI') || ' 00:00-00:00'
                           end
                          else
                           '00:00-00:00 00:00-00:00'
                        end
                 from   deliverypointopeninghour dph, deliverypoint x
                 where  dph.deliverypoint_id = coalesce(dp.deliverypoint_id, dpc.deliverypoint_id)
                 and    dph.deliverypoint_id = x.deliverypoint_id
                 and    dph.day_id = 7), '00:00-00:00 00:00-00:00') openingshourssun,
       dbms_lob.substr(st.routelistinstructions, 4000, 1) remarks, null weight, null volume,
       null lastupdate, null messageconfirmed, null contracttype, null requiresparts,
       null holidaycalenderid, null planautomatically, null assigneddatetime, 1 minimumresources,
       1 maximumresources, to_char(r.routenumber) || ' ' || r.description taskgroupid,
       null reschedule, null reschedulefor,
       case
         when adp.address_id is null then
          cva.county
         else
          adp.county
       end province, st.stopnumber positionintrip, null acceptbeyondlatest, null parkinggeocode,
       case st.stoptype
          when 1 then
           'Bring'
          when 2 then
           'Get'
          when 3 then
           'Mixed'
          else
           'Incidental'
        end tasktype, null floating, null subgroup, null roundearliestlatest, null standby,
       null resourcerequired, null amount, null imageurl,
       coalesce((select rtrim(max(cpd.phone) || ';' || max(cpd.mobilephone), ';')
                 from   contactperson cpd
                 where  cpd.customer_id = c.customer_id
                 and    cpd.contactpersonnumber =
                        (select min(cp.contactpersonnumber)
                          from   contactperson cp
                          where  cp.customer_id = c.customer_id
                          and    cp.podcontact <> 0)), c.phoneno) phone,
       (select max(cpd.email)
         from   contactperson cpd
         where  cpd.customer_id = c.customer_id
         and    cpd.contactpersonnumber = (select min(cp.contactpersonnumber)
                                           from   contactperson cp
                                           where  cp.customer_id = c.customer_id
                                           and    cp.podcontact <> 0)) email,
       case (select max(cp.podcontact) from contactperson cp where cp.customer_id = c.customer_id)
          when 2 then
           case c.signaturerequired
             when 'Y' then
              'SIGNSEND'
             else
              'NOSIGNSEND'
           end
          else
          --111 also when not exists
           case c.signaturerequired
             when 'Y' then
              'SIGNNOSEND'
             else
              'NOSIGNNOSEND'
           end
        end processflow,
       coalesce((select max(pkl.timestamp)
                 from   packingnote pk, packingnoteline pkl
                 where  pk.packingnote_id = pkl.packingnote_id
                 and    pk.stop_id = st.stop_id
                 and    pkl.timestamp > rc.timestamp), rc.timestamp) as routecontroltimestamp
from   stop st
left   outer join (deliverypoint dp
join   address adp
on     dp.deliveryaddress_id = adp.address_id) on st.deliverypoint_id = dp.deliverypoint_id
left   outer join routestop rs on (rs.routestop_id = st.routestop_id)
join   routecontrol rc
on     (st.routecontrol_id = rc.routecontrol_id and rc.pocketpcstatus <> 0 and
       rc.pocketpcstatus <> 2)
join   route r
on     rc.route_id = r.route_id
join   customer c
on     st.customer_link_id = c.customer_id
join   address cva
on     c.visitaddress_id = cva.address_id
join   deliverypoint dpc
on     (c.customer_id = dpc.customer_id and
       dpc.code = (select min(x.code) from deliverypoint x where x.customer_id = dpc.customer_id))
where  st.status <> 1 --(cancelled)
and    st.status <> 2 --(moved out)
and    rc.drivingdate between sysdate - 2 and sysdate + 6
and    (nvl(st.stoptype, 3) = 1 or exists
       (select 1 from v_taskattachement vta where vta.stop_id = st.stop_id))
union
select 'DN' || to_char(pkn.packingnote_id) id, 1 version,
       (select trim(l.name) from customer_link l where l.customer_link_id = c.customer_id) name,
       (select l.customernumber from customer_link l where l.customer_link_id = c.customer_id) accountnumber,
       (select l.customernumber from customer_link l where l.customer_link_id = c.debtor_id) billingaccountnumber,
       (select trim(l.name) from customer_link l where l.customer_link_id = c.debtor_id) billingaccountname,
       (select pt.name from plant pt where pt.plant_id = bu.plant_id) territory,
       (select max(cpd.name)
         from   contactperson cpd
         where  cpd.customer_id = c.customer_id
         and    cpd.contactpersonnumber = (select min(cp.contactpersonnumber)
                                           from   contactperson cp
                                           where  cp.customer_id = c.customer_id
                                           and    cp.podcontact <> 0)) department, cva.street,
       cva.zipcode postalcode, cva.city,
       (select ct.code from country ct where ct.country_id = c.country_id) country,
       '0_0_' || coalesce((select max(ds.gpswidth || '_' || ds.gpslength)
                           from   deliverysignature ds, stop st
                           where  st.customer_link_id = c.customer_id
                           and    ds.stop_id = st.stop_id
                           and    ds.gpswidth is not null
                           and    ds.gpslength is not null),
                           (select max(dp.code || '_' || dp.description)
                             from   deliverypoint dp
                             where  dp.customer_id = c.customer_id
                             and    dp.active = 'N'
                             and    dp.sortaddress = 'GEOC'), '0_0') || ' 4' geocodes, null skill,
       10 estimatedduration, to_char(pkn.deliverydate, 'YYYY-MM-DD') || ' 00:00:00' earliest,
       to_char(pkn.deliverydate + 1, 'YYYY-MM-DD') || ' 00:00:00' latest, null scheduled,
       null scheduledfor, null requiredresource, null preferredresource, null backupresource,
       null fixed, 'PL' status, null actualdatetime, null actualduration,
       coalesce((select case
                          when dph.starttime is not null and dph.endtime is not null then
                           case
                             when dp.breakstarttime is not null and dp.breakendtime is not null then
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(dp.breakstarttime, 'HH24:MI') || ' ' ||
                              to_char(dp.breakendtime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI')
                             else
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI') || ' 00:00-00:00'
                           end
                          else
                           '00:00-00:00 00:00-00:00'
                        end
                 from   deliverypointopeninghour dph
                 where  dph.deliverypoint_id = dp.deliverypoint_id
                 and    dph.day_id = 1), '00:00-00:00 00:00-00:00') openingshoursmon,
       coalesce((select case
                          when dph.starttime is not null and dph.endtime is not null then
                           case
                             when dp.breakstarttime is not null and dp.breakendtime is not null then
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(dp.breakstarttime, 'HH24:MI') || ' ' ||
                              to_char(dp.breakendtime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI')
                             else
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI') || ' 00:00-00:00'
                           end
                          else
                           '00:00-00:00 00:00-00:00'
                        end
                 from   deliverypointopeninghour dph
                 where  dph.deliverypoint_id = dp.deliverypoint_id
                 and    dph.day_id = 2), '00:00-00:00 00:00-00:00') openingshourstue,
       coalesce((select case
                          when dph.starttime is not null and dph.endtime is not null then
                           case
                             when dp.breakstarttime is not null and dp.breakendtime is not null then
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(dp.breakstarttime, 'HH24:MI') || ' ' ||
                              to_char(dp.breakendtime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI')
                             else
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI') || ' 00:00-00:00'
                           end
                          else
                           '00:00-00:00 00:00-00:00'
                        end
                 from   deliverypointopeninghour dph
                 where  dph.deliverypoint_id = dp.deliverypoint_id
                 and    dph.day_id = 3), '00:00-00:00 00:00-00:00') openingshourswed,
       coalesce((select case
                          when dph.starttime is not null and dph.endtime is not null then
                           case
                             when dp.breakstarttime is not null and dp.breakendtime is not null then
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(dp.breakstarttime, 'HH24:MI') || ' ' ||
                              to_char(dp.breakendtime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI')
                             else
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI') || ' 00:00-00:00'
                           end
                          else
                           '00:00-00:00 00:00-00:00'
                        end
                 from   deliverypointopeninghour dph
                 where  dph.deliverypoint_id = dp.deliverypoint_id
                 and    dph.day_id = 4), '00:00-00:00 00:00-00:00') openingshoursthu,
       coalesce((select case
                          when dph.starttime is not null and dph.endtime is not null then
                           case
                             when dp.breakstarttime is not null and dp.breakendtime is not null then
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(dp.breakstarttime, 'HH24:MI') || ' ' ||
                              to_char(dp.breakendtime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI')
                             else
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI') || ' 00:00-00:00'
                           end
                          else
                           '00:00-00:00 00:00-00:00'
                        end
                 from   deliverypointopeninghour dph
                 where  dph.deliverypoint_id = dp.deliverypoint_id
                 and    dph.day_id = 5), '00:00-00:00 00:00-00:00') openingshoursfri,
       coalesce((select case
                          when dph.starttime is not null and dph.endtime is not null then
                           case
                             when dp.breakstarttime is not null and dp.breakendtime is not null then
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(dp.breakstarttime, 'HH24:MI') || ' ' ||
                              to_char(dp.breakendtime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI')
                             else
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI') || ' 00:00-00:00'
                           end
                          else
                           '00:00-00:00 00:00-00:00'
                        end
                 from   deliverypointopeninghour dph
                 where  dph.deliverypoint_id = dp.deliverypoint_id
                 and    dph.day_id = 6), '00:00-00:00 00:00-00:00') openingshourssat,
       coalesce((select case
                          when dph.starttime is not null and dph.endtime is not null then
                           case
                             when dp.breakstarttime is not null and dp.breakendtime is not null then
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(dp.breakstarttime, 'HH24:MI') || ' ' ||
                              to_char(dp.breakendtime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI')
                             else
                              to_char(dph.starttime, 'HH24:MI') || '-' ||
                              to_char(dph.endtime, 'HH24:MI') || ' 00:00-00:00'
                           end
                          else
                           '00:00-00:00 00:00-00:00'
                        end
                 from   deliverypointopeninghour dph
                 where  dph.deliverypoint_id = dp.deliverypoint_id
                 and    dph.day_id = 7), '00:00-00:00 00:00-00:00') openingshourssun,
       pkn.remark remarks, null weight, null volume, null lastupdate, null messageconfirmed,
       null contracttype, null requiresparts, null holidaycalenderid, null planautomatically,
       null assigneddatetime, 1 minimumresources, 1 maximumresources, null taskgroupid,
       null reschedule, null creschedulefor, cva.county province, null positionintrip,
       null acceptbeyondlatest, null parkinggeocode, '1' tasktype, null floating, null subgroup,
       null roundearliestlatest, null standby, null resourcerequired, null amount, null imageurl,
       coalesce((select rtrim(max(cpd.phone) || ';' || max(cpd.mobilephone), ';')
                 from   contactperson cpd
                 where  cpd.customer_id = c.customer_id
                 and    cpd.contactpersonnumber =
                        (select min(cp.contactpersonnumber)
                          from   contactperson cp
                          where  cp.customer_id = c.customer_id
                          and    cp.podcontact <> 0)), c.phoneno) phone,
       (select max(cpd.email)
         from   contactperson cpd
         where  cpd.customer_id = c.customer_id
         and    cpd.contactpersonnumber = (select min(cp.contactpersonnumber)
                                           from   contactperson cp
                                           where  cp.customer_id = c.customer_id
                                           and    cp.podcontact <> 0)) email,
       case (select max(cp.podcontact) from contactperson cp where cp.customer_id = c.customer_id)
          when 2 then
           case c.signaturerequired
             when 'Y' then
              'SIGNSEND'
             else
              'NOSIGNSEND'
           end
          else
          --111 also when not exists
           case c.signaturerequired
             when 'Y' then
              'SIGNNOSEND'
             else
              'NOSIGNNOSEND'
           end
        end processflow,
       coalesce((select max(pkl.timestamp)
                 from   packingnoteline pkl
                 where  pkl.packingnote_id = pkn.packingnote_id
                 and    pkl.timestamp > pkn.timestamp), pkn.timestamp) as routecontroltimestamp
from   packingnote pkn
join   deliverypoint dp
on     dp.deliverypoint_id = pkn.deliverypoint_id
join   customer c
on     c.customer_id = dp.customer_id
join   address cva
on     c.visitaddress_id = cva.address_id
join   customer debtor
on     debtor.customer_id = c.debtor_id
join   businessunit bu
on     bu.businessunit_id = pkn.processbusinessunit_id
where  (pkn.status_id = (select status_id
                         from   status
                         where  code = '30'
                         and    statustype = 'PN') or (pkn.straightevenreturn = 'Y'))
and    nvl(pkn.stop_id, 0) = 0 -->might needs a special index...but thats why there's also a date selection next!
and    pkn.deliverydate between sysdate - 2 and sysdate + 6
/

  CREATE OR REPLACE VIEW "V_TAXGROUP" ("CODE", "DESCRIPTION", "TAXRATE", "OLDTAXRATE", "ACTIVE", "STARTDATETAXRATE", "COUNTRYCODE", "COUNTRYDESCRIPTION", "TURNOVERGROUPCODE", "TURNOVERGROUPDESCRIPTION", "SALESJOURNALGROUPCODE", "SALESJOURNALGROUPDESCRIPTION", "TIMESTAMP", "SYSTEMUSER_ID", "LANGUAGECODE") AS 
  select taxgroup.code, taxgroup.description, taxgroup.taxrate, taxgroup.oldtaxrate, taxgroup.active,
 taxgroup.startdatetaxrate, country.code , country.description ,
 V_turnovergroup.turnovergroupcode, V_turnovergroup.turnovergroupdescription,
 V_turnovergroup.salesjournalgroupcode, V_turnovergroup.salesjournalgroupdescription,
 taxgroup.timestamp, taxgroup.systemuser_id, V_turnovergroup.languagecode
from country, taxgroup, V_turnovergroup
where taxgroup.country_id = country.country_id
 and V_turnovergroup.turnovergroup_id = taxgroup.turnovergroup_id
union all
select taxgroup.code, taxgroup.description, taxgroup.taxrate, taxgroup.oldtaxrate, taxgroup.active,
 taxgroup.startdatetaxrate, country.code , country.description ,
 '', '', '', '',
 taxgroup.timestamp, taxgroup.systemuser_id, languages.code
from country, taxgroup, languages
where taxgroup.country_id = country.country_id
and taxgroup.turnovergroup_id is null
/

  CREATE OR REPLACE VIEW "V_TOTALAMOUNTEXCLVAT" ("INVOICEHEADER_ID", "COSTCENTER_CODE", "TOTALAMOUNTEXCLVAT", "LANGUAGECODE") AS 
  select  -- from view
c.invoiceheader_id, c.costcenter_code
, sum(c.costcenterinvoiceline_amount) TotalAmountExclVAT , c.languagecode
--, c.costcenter_link_id
from
V_costcenterinvoiceline c --, V_invoiceheader h
where
    -- and c.invoiceheader_id = h.invoiceheader_id
    c.costcenterinvoiceline_amount<>0
and c.invoicelinetype <>18
 group by
 c.invoiceheader_id--, c.costcenter_link_id
 , c.costcenter_code
 , c.languagecode
/*
 select  -- select from tabels is working more slow then select from view
         -- something like 3 second Vs. 9 second on abssolute database
 a.invoiceheader_id, cc.code costcenter_code
 ,sum(ccil.amount) TotalAmountExclVAT
from
invoiceline a, invoicelinetype e, invoiceheader f, costcenterinvoiceline ccil
, costcenter_link cc
where
    a.invoicelinetype_id = e.invoicelinetype_id
and a.invoiceheader_id = f.invoiceheader_id
and f.documenttype = 1
and ccil.invoiceline_id = a.invoiceline_id
and ccil.costcenter_link_id = cc.costcenter_link_id
and e.type <> 18
and ccil.amount <>0
    group by
    a.invoiceheader_id, cc.code*/
/

  CREATE OR REPLACE VIEW "V_UNIQUETRUCKLOADLISTORIGIN" ("PICKLIST_ID", "ORDERNUMBER", "CONSUMPTIONPOINT_ID", "BASELINETYPE", "REQUESTEDDELIVERYDATE", "DISTRIBUTIONPOINTNUMBER", "DESCRIPTION", "CUSTOMERNUMBER", "NAME") AS 
  select v1.picklist_id, v1.ordernumber, v1.consumptionpoint_id, v1.baselinetype,
v1.requesteddeliverydate, cpl.distributionpointnumber, cpl.description, cl.customernumber, cl.name
from v_uniquetruckloadlistoriginas v1, distributionpoint_link cpl, department_link dpl, customer_link cl
where cpl.distributionpoint_link_id = v1.consumptionpoint_id
and dpl.department_link_id = cpl.department_link_id
and cl.customer_link_id = dpl.customer_link_id
union --all
select v2.picklist_id, v2.ordernumber, v2.consumptionpoint_id, v2.baselinetype,
v2.requesteddeliverydate, cpl.distributionpointnumber, cpl.description, cl.customernumber, cl.name
from v_uniquetruckloadlistoriginps v2, distributionpoint_link cpl, department_link dpl, customer_link cl
where cpl.distributionpoint_link_id = v2.consumptionpoint_id
and dpl.department_link_id = cpl.department_link_id
and cl.customer_link_id = dpl.customer_link_id
/

  CREATE OR REPLACE VIEW "V_WEARERGARMENTSBUDGET" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_ID", "DEBTOR_ID", "CUSTOMERNUMBER_BILLTO", "WEARERNUMBER", "WEARERENAME", "SEQUENCENUMBER", "WEARERFUNCTIONCODE", "WEARERFUNCTIONDESC", "GARMENTSBUDGETCHANGEDATE", "ACTUAL_RESERVED_BUDGET", "ACTUALBUDGETVALUE", "ACTUALREASERVEDVALUE", "REPORTPARAM_ID") AS 
  select c.customernumber, c.name customername, c.customer_id, c.debtor_id,
  cbt.customernumber  customernumber_billto,
  w.wearernumber, w.fullname wearerename, we.sequencenumber,
  wf.code wearerfunctioncode, wf.description wearerfunctiondesc,
  we.garmentsbudgetchangedate,
--  cast(F_GETACTUALWEARERBUDGET(we.weareremployment_id, rp.date_value1, rp.date_value2) as varchar2(30)) actual_reserved_budget,
  '' actual_reserved_budget,
  GetActualWearerBudget(we.weareremployment_id, rp.date_value1, rp.date_value2).actualbudget actualBudgetValue,
  GetActualWearerBudget(we.weareremployment_id, rp.date_value1, rp.date_value2).actualreserved actualReaservedValue,
  rp.reportparam_id
from customer c, wearer w, customer cbt,
  weareremployment we
    left outer join wearerfunction wf on we.wearerfunction_id = wf.wearerfunction_id,
  reportparam rp
where c.usewearergarmentsbudget = 'Y'
  and c.customer_id = w.customer_id
  and w.wearer_id = we.wearer_id
/*  and ((c.defaultbusinessunit_id = rp.number_value)
    or exists (SELECT CUSTOMER_ID FROM CUSTOMERACTIVITIES CA
               WHERE ca.PROCESSBUSINESSUNIT_ID = rp.number_value  and c.customer_id = ca.customer_id))*/
  and exists (select v.customer_id from v_customersperbusinessunitdp v
              where v.customer_id = c.customer_id and v.businessunit_id = rp.number_value)
  and c.debtor_id = cbt.customer_id
  and exists (select v.customer_id from v_customersperbusinessunitdp v
              where v.customer_id = cbt.customer_id and v.businessunit_id = rp.number_value)
/

  CREATE OR REPLACE VIEW "V_WEARERGARMENTSBUDGETTRANS" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_ID", "DEBTOR_ID", "CUSTOMERNUMBER_BILLTO", "WEARERNUMBER", "WEARERENAME", "SEQUENCENUMBER", "WEARERFUNCTIONCODE", "WEARERFUNCTIONDESC", "GARMENTSBUDGETCHANGEDATE", "PRODUCTCODE", "PRODUCTDESC", "WEARERBUDGETTRANSACTION_ID", "BUDGETADJUSTMENT", "ACTUALBUDGET", "RESERVEDADJUSTMENT", "ACTUALRESERVED", "TRANSACTIONDATE", "ORIGIN", "REMARK", "WORKORDERNUMBER", "LANGUAGECODE", "BUSINESSUNIT_ID") AS 
  select c.customernumber, c.name customername, c.customer_id, c.debtor_id,
  cbt.customernumber customernumber_billto,
  w.wearernumber, w.fullname wearerename, we.sequencenumber,
  wf.code wearerfunctioncode, wf.description wearerfunctiondesc,
  we.garmentsbudgetchangedate,
  pl.code productcode,
  (select pld.description from product_link_desc pld where pld.product_link_id = pl.product_link_id
   and pld.language_id = l.language_id) productdesc,
  wbt.wearerbudgettransaction_id,
  wbt.budgetadjustment, wbt.actualbudget, wbt.reservedadjustment, wbt.actualreserved,
  wbt.transactiondate, wbt.origin, wbt.remark,  wbt.workordernumber,
  l.code languagecode, bu.businessunit_id
from customer c, wearer w, customer cbt,
  weareremployment we
    left outer join wearerfunction wf on we.wearerfunction_id = wf.wearerfunction_id,
  wearerbudgettransaction wbt
    left outer join product_link pl on wbt.product_link_id = pl.product_link_id,
  languages l, businessunit bu
where c.usewearergarmentsbudget = 'Y'
  and c.customer_id = w.customer_id
  and w.wearer_id = we.wearer_id
/*  and ((c.defaultbusinessunit_id = bu.businessunit_id)
    or exists (SELECT CUSTOMER_ID FROM CUSTOMERACTIVITIES CA
               WHERE ca.PROCESSBUSINESSUNIT_ID = rp.number_value  and c.customer_id = ca.customer_id))*/
  and exists (select v.customer_id from v_customersperbusinessunitdp v
              where v.customer_id = c.customer_id and v.businessunit_id = bu.businessunit_id)
  and we.weareremployment_id = wbt.weareremployment_id
  and c.debtor_id = cbt.customer_id
  and exists (select v.customer_id from v_customersperbusinessunitdp v
              where v.customer_id = cbt.customer_id and v.businessunit_id = bu.businessunit_id)
/

  CREATE OR REPLACE VIEW "V_WEBCLIENTDELIVERYNOTE" ("PRINTPRICEONDELNOTE", "PRICEDECIMALS", "AMOUNTDECIMALS", "PRICE", "PRICEONDELNOTE", "WEIGHTPRICE", "SPECIALCHARGEINVAMOUNT", "SPECIALCHARGEAMOUNT", "LABELSAMOUNT", "TAXAMOUNT", "NOOFSPECCHARGE", "NOOFLABELS", "NOOFTAXES", "CLIENTDELIVERYNOTE_ID", "PROCESSBUSINESSUNIT_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "CLIENTNUMBER", "CLIENTNAME", "ROOM", "STREET", "ZIPCODE_CITY", "CLIENTDELIVERYNOTENUMBER", "CLOSINGDATE", "DELIVERYDATE", "BOXNUMBER", "BATCHCODE", "BATCHNUMBER", "BATCHYEAR", "BATCHWEEK", "BATCHCOLORDESC", "BATCH_CODENUMBER", "DAYDESC", "ROUTENUMBER", "ROUTEDESC", "STOPNUMBER", "GROSSWEIGHT", "WEIGHTDECIMALS", "WEIGHTUNIT", "PACKINGSEQUENCE", "PRODUCT_ID", "PRODUCTCODE", "SIZECODE", "FINISHINGMETHOD_ID", "FINISHINGMETHODCODE", "PRODUCTDESC", "QTYRECEIVED", "QTYDELIVERED", "PRIMARYID", "FLAGCODE", "FLAGDESC", "PRINTWEIGHT", "PRINT_V_CDN_DELAYEDDELIVERY", "PRINT_V_CDN_DELIVEREDAFTER", "PRINT_V_CDN_SENDTOOWNER", "PRINT_V_CDN_RECEIVEFROMOWNER", "CUSTOMERCLIENTS", "PRINTIDCODE", "PRINTLATEPIECES", "ACCEPTOTHERCLIENTS", "PRINTQTYRECEIVED", "SYSTEMSETTINGVALUE", "EMPLOYEENUMBER", "EMPLOYEENAME", "RECORDEMPLCLIENTDELNOTE", "LANGUAGECODE", "PRODCUSTOM_CODE", "PRODCUSTOM_DESC", "UNIQUERESIDENTIALITEM_LINK_ID", "OUTSCANTIMESTAMP", "SEQUENCENUMBER", "DEPTDELSTREET", "DEPTDELZIPCODE", "DEPTDELCITY", "LOCATION", "REMARKS", "WEBUSERDEPARTMENT_ID", "WEBSESSION_ID", "WEBUSER_ID") AS 
  select -- +index(cds XIE2CLIENTDELNOTELINESCAN)
 crs.printpriceondelnote, crr.decimals pricedecimals,
 crr.invoiceamountdecimals amountdecimals, cdl.price, cdl.priceondelnote, cdn.weightprice,
 coalesce((select sum(cds.quantity * cds.price) from clientdeliverynotespeccharge cds
            where cds.clientdeliverinote_id = cdn.clientdeliverynote_id), 0) specialchargeinvamount,
 coalesce((select sum(cds.quantity * cds.priceondelnote) from clientdeliverynotespeccharge cds
            where cds.clientdeliverinote_id = cdn.clientdeliverynote_id), 0) specialchargeamount,
 coalesce((select sum(pqr.quantity * pqr.price) from printqueueresidentialitem pqr
            where pqr.clientdeliverynote_id = cdn.clientdeliverynote_id), 0) labelsamount,
 coalesce((select sum(cdt.taxamount) from clientdeliverynotetax cdt, taxgroup tg
            where cdt.taxgroup_id = tg.taxgroup_id and cdt.clientdeliverinote_id = cdn.clientdeliverynote_id), 0) taxamount,
 (select count(1) from clientdeliverynotespeccharge cds
    where cds.clientdeliverinote_id = cdn.clientdeliverynote_id) noofspeccharge,
 (select count(1) from printqueueresidentialitem pqr
    where pqr.clientdeliverynote_id = cdn.clientdeliverynote_id) nooflabels,
 (select count(1) from clientdeliverynotetax cdt
    where cdt.clientdeliverinote_id = cdn.clientdeliverynote_id) nooftaxes,
 cdn.clientdeliverynote_id, cdn.processbusinessunit_id, cu.customer_id,
 cu.customernumber, cu.name customername, de.department_id,
 de.departmentnumber, de.description departmentdesc, client.clientnumber,
 coalesce(cdn.name, client.name) clientname,
 case when cdn.closingdate is null then
    dr.roomnumber
   else cdn.roomnumber end room,
 case when cdn.street is null then
    address.street
   else cdn.street end street,
 cast((case when cdn.street is null then
         concatenatewithsign(address.zipcode, ' / ', address.city)
        else
         concatenatewithsign(cdn.zipcode, ' / ', cdn.city)
      end) as varchar2(255)) zipcode_city, cdn.clientdeliverynotenumber,
 cdn.closingdate, cdn.deliverydate, cdn.boxnumber, batch.batchcode,
 batch.batchnumber, batch.year batchyear, batch.week batchweek,
 batchcolor.description batchcolordesc,
 cast((case
        when ss.value = '-2' then
         concatenate(getsubstringonlength(batch.batchcode, 1, 2), cast(batch.batchnumber as varchar2(255)))
        when ss.value = '-1' then
         concatenate(getsubstringonlength(batch.batchcode, 1, 1), cast(batch.batchnumber as varchar2(255)))
        when ss.value = '0' then
         cast(batch.batchnumber as varchar2(255))
        when ss.value = '1' then
         concatenate(cast(batch.batchnumber as varchar2(255)), getsubstringonlength(batch.batchcode, 1, 1))
        when ss.value = '2' then
         concatenate(cast(batch.batchnumber as varchar2(255)), getsubstringonlength(batch.batchcode, 1, 2))
      end) as varchar2(255)) batch_codenumber,
 (select day_desc.description from day_desc
    where batch.day_id = day_desc.day_id
      and day_desc.language_id = languages.language_id) daydesc,
 route.routenumber, route.description routedesc, cdn.stopnumber,
 cdn.grossweight, cdn.weightdecimals,
 (select systemsetting.value from systemsetting
    where systemsetting.plant_id = bu.plant_id
      and systemsetting.name = 'WEIGHTUNIT') weightunit, pr.packingsequence,
 pr.product_id, pr.code productcode, sz.code sizecode,
 fm.finishingmethod_id, fm.code finishingmethodcode,
 (select prd.description from product_desc prd
    where prd.product_id = pr.product_id and prd.language_id = languages.language_id) productdesc,
 (cdl.qtyscannedin + cdl.qtycountedin) qtyreceived,
 (cdl.qtyscannedout + cdl.qtycountedout) qtydelivered,
 (select uri.primaryid from uniqueresidentialitem uri
    where cds.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id) primaryid,
 --null flagcode, null flagdesc
 case crs.printidcode when 'Y'
 then (select flag.code from flag, residentialitemscan ris, residentialitemscanflag risf
      where risf.flag_id = flag.flag_id and ris.residentialitemscan_id = risf.residentialitemscan_id
           and cds.uniqueresidentialitem_link_id = ris.uniqueresidentialitem_link_id
           and trunc(cds.outscantimestamp) = trunc(ris.scantimestamp) and ris.transactiontype_id = 2)
 else null
 end flagCode
 , case crs.printidcode when 'Y'
 then (select flag_desc.description from flag_desc, residentialitemscan ris, residentialitemscanflag risf
      where risf.flag_id = flag_desc.flag_id and ris.residentialitemscan_id = risf.residentialitemscan_id
           and cds.uniqueresidentialitem_link_id = ris.uniqueresidentialitem_link_id
           and trunc(cds.outscantimestamp) = trunc(ris.scantimestamp)
           and ris.transactiontype_id = 2 and flag_desc.language_id = languages.language_id )
 else null
 end flagDesc,
 (select count(1) from weighingcategpercustomer wghc
    where wghc.weighingcategory_id = cdn.weighingcategory_link_id
      and wghc.customer_id = cu.customer_id
      and wghc.invoicemethod = 2 -- invoice soil weight
      and trunc(sysdate) between wghc.dateactive and wghc.dateinactive) printweight,
 (select count(1) from v_cdn_delayeddelivery
    where v_cdn_delayeddelivery.clientdeliverynote_id =
          cdn.clientdeliverynote_id) print_v_cdn_delayeddelivery,
 (select count(1) from v_cdn_deliveredafter
    where v_cdn_deliveredafter.clientdeliverynote_id =
          cdn.clientdeliverynote_id) print_v_cdn_deliveredafter,
 (select count(1) from v_cdn_sendtoowner
    where v_cdn_sendtoowner.clientdeliverynote_id = cdn.clientdeliverynote_id
      and v_cdn_sendtoowner.ownernumber <> client.clientnumber) print_v_cdn_sendtoowner,
 (select count(1) from v_cdn_receivefromowner
    where v_cdn_receivefromowner.clientdeliverynote_id =
          cdn.clientdeliverynote_id) print_v_cdn_receivefromowner--, cdr.remark
, crs.customerclients, crs.printidcode, crs.printlatepieces,
 crs.acceptotherclients, crs.printqtyreceived, ss.value systemsettingvalue,
 emp.employeenumber, emp.name employeename,
 (select systemsetting.value from systemsetting
    where systemsetting.plant_id = bu.plant_id and systemsetting.name = 'RECORDEMPLCLIENTDELNOTE') recordemplclientdelnote,
 languages.code languagecode,
 (select plpc.customcode from productlistpercustomer plpc
    where plpc.productlistpercustomer_id = f_getidcolumnfromactiveplpc(cu.customer_id, pr.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) prodcustom_code,
 (select plpc.customdescription from productlistpercustomer plpc
    where plpc.productlistpercustomer_id = f_getidcolumnfromactiveplpc(cu.customer_id, pr.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) prodcustom_desc,
 cds.uniqueresidentialitem_link_id,
 trunc(cds.outscantimestamp) outscantimestamp,
 cdn.sequencenumber,
 (select ad1.street from address ad1
    where ad1.address_id =
          (select dep1.deliveryaddress_id from deliverypoint dep1
            where dep1.deliverypoint_id = (select dip1.deliverypoint_id from distributionpoint dip1
                                          where dip1.distributionpoint_id = dr.distributionpoint_id))) deptdelstreet,
 (select ad2.zipcode from address ad2
    where ad2.address_id =
          (select dep2.deliveryaddress_id from deliverypoint dep2
            where dep2.deliverypoint_id =
                  (select dip2.deliverypoint_id from distributionpoint dip2
                    where dip2.distributionpoint_id = dr.distributionpoint_id))) deptdelzipcode,
 (select ad3.city from address ad3
    where ad3.address_id = (select dep3.deliveryaddress_id from deliverypoint dep3
                         where dep3.deliverypoint_id =
                         (select dip3.deliverypoint_id from distributionpoint dip3
                         where dip3.distributionpoint_id = dr.distributionpoint_id))) deptdelcity,
 (select coalesce((lc.rowcode || ' - ' || lc.positioncode), '')
     from ltxsortsessionloccontents lcc, ltxsortsessionlocation lc
    where lcc.ltxsortsessionlocation_id = lc.ltxsortsessionlocation_id
      and lcc.clientdeliverynote_id = cdn.clientdeliverynote_id) location,
 (select listagg(ccdnr.remark,',') within group(order by ccdnr.startdate) from customerclientdelnoteremark ccdnr
   where ccdnr.customer_id = cu.customer_id and cdn.deliverydate >= ccdnr.startdate and cdn.deliverydate <= ccdnr.enddate) Remarks,
 wd.department_id webuserdepartment_id, wus.websession_id, wuc.webuser_id
from clientdeliverynote cdn
     left outer join route on cdn.route_id = route.route_id
     left outer join clientdeliverynoteline cdl
          inner join product pr
                inner join productgroup pg on pr.productgroup_id = pg.productgroup_id
          on cdl.product_link_id = pr.product_id
          inner join sizedefinition sz on cdl.sizedefinition_link_id = sz.sizedefinition_id
          inner join finishingmethod fm on cdl.finishingmethod_id = fm.finishingmethod_id
          left outer join clientdelnotelinescan cds on cdl.clientdeliverynoteline_id = cds.outscanclientdelnoteline_id
     on cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
     inner join customer cu
           inner join customerresidentialsettings crs on cu.customer_id = crs.customer_id
           inner join currency crr on cu.currency_id = crr.currency_id
           inner join webusercustomer wuc
                 left outer join webuserdepartment wd on wuc.webusercustomer_id = wd.webusercustomer_id
                 inner join webusersession wus on wuc.customer_id = wus.customer_id
           on cu.customer_id = wuc.customer_id
     on cdn.customer_link_id = cu.customer_id
     inner join client
           left outer join clientresident cr
                inner join departmentroom dr
                      inner join department de on dr.department_id = de.department_id
                      inner join distributionpoint dip
                            inner join deliverypoint devp
                                  inner join address address2 on devp.deliveryaddress_id = address2.address_id
                            on dip.deliverypoint_id = devp.deliverypoint_id
                      on dr.distributionpoint_id = dip.distributionpoint_id
                on cr.departmentroom_id = dr.departmentroom_id
          on client.client_id = cr.client_id
          left outer join clientprivateperson cpp
               inner join deliverypoint delvp
                     inner join address on delvp.deliveryaddress_id = address.address_id
               on cpp.deliverypoint_id = delvp.deliverypoint_id
          on client.client_id = cpp.client_id
     on cdn.client_link_id = client.client_id
     inner join batch
           left outer join employee emp on batch.employee_id = emp.employee_id
           inner join batchcolor on batch.batchcolor_id = batchcolor.batchcolor_id
     on cdn.batch_id = batch.batch_id
     inner join businessunit bu
           inner join plant
                 inner join address plantaddress on plant.address_id = plantaddress.address_id
                 left outer join systemsetting ss on plant.plant_id = ss.plant_id and ss.name = 'BATCHCODEUSAGE'
           on bu.plant_id = plant.plant_id
     on cdn.processbusinessunit_id = bu.businessunit_id
 , languages
 where pr.typeofmerchandise = 5 or pr.typeofmerchandise = 1
/

  CREATE OR REPLACE VIEW "V_WEBCOSTSSPECIFICPERCLIENT" ("LINE_TYPE", "LABELLAYOUT_ID", "L_INVOICELINE_ID", "INVOICEHEADER_ID", "L_INVOICENUMBER", "L_DOCUMENTTYPE", "H_INVOICELINE_ID", "H_INVOICENUMBER", "H_DOCUMENTTYPE", "IHINVOICEBUSINESSUNIT_ID", "CDNINVOICEBUSINESSUNIT_ID", "PROCESSBUSINESSUNIT_ID", "CUSTOMER_ID", "DELIVERYDATE", "INVOICEAMOUNTDECIMALS", "PRICEDECIMALS", "CLOSINGDATE", "CUSTOMERCLIENTS", "LAUNDRYSERVICESPARTICIPANT", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEP_DESC", "ROOMNUMBER", "CLIENTDELIVERYNOTENUMBER", "CLIENT_ID", "CLIENTNUMBER", "SEARCHNAME", "CLIENT_NAME", "CUSTOMER_NAME", "CUSTOMERNUMBER", "CITY", "PRODUCT_ID", "PROD_CODE", "PROD_DESC", "SIZEDEF_DESC", "FINISHINGMETHOD_ID", "FINISH_DESC", "QUANTITY", "WEIGHTDECIMALS", "IL_PRICE", "PRICE", "LINEINVOICEBUSINESSUNIT_ID", "LANGUAGE_CODE", "SIZE_CODE", "FINISHING_CODE", "FMWASHTYPE", "TAXPERCENTAGE", "TAXAMOUNT", "TAXGROUP_CODE", "TAXGROUP_DESC", "WEBUSERDEPARTMENT_ID", "WEBSESSION_ID", "WEBUSER_ID") AS 
  select 1 line_type, null labellayout_id
, il.invoiceline_id l_invoiceline_id, ih.invoiceheader_id invoiceheader_id, ih.invoicenumber l_invoicenumber, ih.documenttype l_documenttype
, ilh.invoiceline_id h_invoiceline_id, ihh.invoicenumber h_invoicenumber, ihh.documenttype h_documenttype
, ih.invoicebusinessunit_id ihinvoicebusinessunit_id, cdn.invoicebusinessunit_id cdninvoicebusinessunit_id
, cdn.processbusinessunit_id, cdn.customer_link_id Customer_Id, cdn.deliverydate
, crr.invoiceamountdecimals invoiceamountdecimals, crr.decimals pricedecimals
, cdn.closingdate
, crs.customerclients, cr.laundryservicesparticipant
, v.department_id,v.departmentnumber, v.Dep_desc
, cdn.roomnumber, cdn.clientdeliverynotenumber
, cli.client_id, cli.clientnumber
, cli.searchname, cli.name Client_name
, cus.name Customer_name, cus.customernumber, a.city
, p.product_id
, coalesce((select plpc.customcode from productlistpercustomer plpc where plpc.productlistpercustomer_id=F_GETIDCOLUMNFROMACTIVEPLPC(cus.customer_id, p.product_id, s.sizedefinition_id, f.finishingmethod_id, s.sizedefinition_id, cdn.deliverydate, 0)), p.code) Prod_code
, coalesce((select plpc.customdescription from productlistpercustomer plpc where plpc.productlistpercustomer_id=F_GETIDCOLUMNFROMACTIVEPLPC(cus.customer_id, p.product_id, s.sizedefinition_id, f.finishingmethod_id, s.sizedefinition_id, cdn.deliverydate, 0)),(select pd.description from product_desc pd where pd.product_id=p.product_id and pd.language_id = l.language_id)) Prod_Desc
, (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id=s.sizedefinition_id and sdd.language_id = l.language_id) Sizedef_Desc
, f.finishingmethod_id
, (select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id=f.finishingmethod_id and fmd.language_id = l.language_id) Finish_Desc
, case when '1' in (select cast(sst.value as varchar2(60)) from systemsetting sst, businessunit bu where sst.plant_id = bu.plant_id and sst.name = 'CLIENTINVOICEDBASEDON' and (bu.businessunit_id = ih.invoicebusinessunit_id OR bu.businessunit_id =cdn.processbusinessunit_id))
  then (cdl.qtyscannedin + cdl.qtycountedin)
  else (cdl.qtyscannedout + cdl.qtycountedout) end Quantity, 0 weightdecimals, il.price Il_Price, cdl.price
, cdl.invoicebusinessunit_id LineInvoicebusinessunit_id
, l.code Language_code
, s.code Size_code, f.code Finishing_code, f.washtype FMwashtype
, ctx.TAXPERCENTAGE, ctx.TAXAMOUNT
, txg.code taxgroup_code, txg.description taxgroup_desc
, wd.department_id webuserdepartment_id
, wus.websession_id
, wuc.webuser_id
from clientdeliverynoteline cdl
     left outer join invoiceline il
         inner join invoiceheader ih on ih.invoiceheader_id = il.invoiceheader_id
     on cdl.invoiceline_id = il.invoiceline_id
     inner join clientdeliverynote cdn
           left outer join invoiceline ilh
                inner join invoiceheader ihh on ihh.invoiceheader_id = ilh.invoiceheader_id
           on cdn.invoiceline_id = ilh.invoiceline_id
           left outer join clientdeliverynotetax ctx
                inner join taxgroup txg on ctx.taxgroup_id = txg.taxgroup_id
           ON ctx.CLIENTDELIVERINOTE_ID = cdn.ClientDeliveryNote_ID
           inner join customer cus
                 left outer join Customerresidentialsettings crs on cus.customer_id = crs.customer_id
                 inner join languages l on cus.language_id = l.language_id
                 inner join address a on cus.visitaddress_id = a.address_id
                 inner join currency crr on cus.currency_id = crr.currency_id
           on cdn.customer_link_id = cus.customer_id
           inner join client cli
                 left outer join clientresident cr on cli.client_id = cr.client_id
                 inner join v_ClientDepartment v on cli.client_id = v.client_id
                 inner join webusercustomer wuc
                       left outer join webuserdepartment wd on wuc.webusercustomer_id = wd.webusercustomer_id
                       inner join webusersession wus on wuc.customer_id = wus.customer_id
                 on cli.customer_id = wuc.customer_id
           on cdn.client_link_id = cli.client_id
     on cdl.clientdeliverinote_id = cdn.clientdeliverynote_id
     inner join product p on cdl.product_link_id = p.product_id
     inner join sizedefinition s on cdl.sizedefinition_link_id = s.sizedefinition_id
     inner join finishingmethod f on cdl.finishingmethod_id = f.finishingmethod_id
where cdn.closingdate is not null
      and (cdn.invoicebusinessunit_id = cus.defaultbusinessunit_id or
           cdn.processbusinessunit_id = cus.defaultbusinessunit_id)
      and p.typeofmerchandise = 5
union all
select 2 line_type, null labellayout_id
, il.invoiceline_id l_invoiceline_id, ih.invoiceheader_id invoiceheader_id, ih.invoicenumber l_invoicenumber, ih.documenttype l_documenttype
, ilh.invoiceline_id h_invoiceline_id, ihh.invoicenumber h_invoicenumber, ihh.documenttype h_documenttype
, ih.invoicebusinessunit_id ihinvoicebusinessunit_id, cdn.invoicebusinessunit_id cdninvoicebusinessunit_id
, cdn.processbusinessunit_id, cdn.customer_link_id Customer_Id, cdn.deliverydate
, crr.invoiceamountdecimals invoiceamountdecimals, crr.decimals pricedecimals
, cdn.closingdate
, crs.customerclients, cr.laundryservicesparticipant
, v.department_id, v.departmentnumber, v.Dep_desc
, cdn.roomnumber, cdn.clientdeliverynotenumber
, cli.client_id, cli.clientnumber
, cli.searchname, cli.name Client_name
, cus.name Customer_name, cus.customernumber, a.city
, null product_id
, sc.code Prod_code
, (select scd.description from specialcharge_desc scd where sc.specialcharge_id=scd.specialcharge_id and scd.language_id = l.language_id) Prod_Desc
, '1' Sizedef_Desc
, null finishingmethod_id
, '11' Finish_desc
, cdc.quantity, 0 weightdecimals, il.price Il_Price, cdc.price
, -2 LineInvoicebusinessunit_id
, l.code Language_code
, '' Size_code
, '' Finishing_code,  -1 FMwashtype
, ctx.TAXPERCENTAGE, ctx.TAXAMOUNT
, txg.code taxgroup_code, txg.description taxgroup_desc
, wd.department_id webuserdepartment_id
, wus.websession_id
, wuc.webuser_id
from clientdeliverynotespeccharge cdc
     left outer join invoiceline il
         join invoiceheader ih on ih.invoiceheader_id=il.invoiceheader_id
     on cdc.invoiceline_id = il.invoiceline_id
     inner join clientdeliverynote cdn
           left outer join invoiceline ilh
                inner join invoiceheader ihh on ihh.invoiceheader_id = ilh.invoiceheader_id
           on cdn.invoiceline_id = ilh.invoiceline_id
           left outer join clientdeliverynotetax ctx
                inner join taxgroup txg on ctx.taxgroup_id = txg.taxgroup_id
           ON ctx.CLIENTDELIVERINOTE_ID = cdn.ClientDeliveryNote_ID
           inner join customer cus
                 left outer join Customerresidentialsettings crs on cus.customer_id = crs.customer_id
                 inner join languages l on cus.language_id = l.language_id
                 inner join address a on cus.visitaddress_id = a.address_id
                 inner join currency crr on cus.currency_id = crr.currency_id
           on cdn.customer_link_id = cus.customer_id
           inner join client cli
                 left outer join clientresident cr on cli.client_id = cr.client_id
                 inner join v_ClientDepartment v on cli.client_id = v.client_id
                 inner join webusercustomer wuc
                       left outer join webuserdepartment wd on wuc.webusercustomer_id = wd.webusercustomer_id
                       inner join webusersession wus on wuc.customer_id = wus.customer_id
                 on cli.customer_id = wuc.customer_id
           on cdn.client_link_id = cli.client_id
     on cdc.clientdeliverinote_id = cdn.clientdeliverynote_id
     inner join specialcharge sc on cdc.specialcharge_id = sc.specialcharge_id
where cdn.closingdate is not null
      and (cdn.invoicebusinessunit_id = cus.defaultbusinessunit_id or
           cdn.processbusinessunit_id = cus.defaultbusinessunit_id)
union all
select 3 line_type, null labellayout_id
, il.invoiceline_id l_invoiceline_id, ih.invoiceheader_id invoiceheader_id,ih.invoicenumber l_invoicenumber, ih.documenttype l_documenttype
, il.invoiceline_id h_invoiceline_id, ih.invoicenumber h_invoicenumber, ih.documenttype h_documenttype
, ih.invoicebusinessunit_id ihinvoicebusinessunit_id, cdn.invoicebusinessunit_id cdninvoicebusinessunit_id
, cdn.processbusinessunit_id, cdn.customer_link_id Customer_Id, cdn.deliverydate
, crr.invoiceamountdecimals invoiceamountdecimals, crr.decimals pricedecimals
, cdn.closingdate
, crs.customerclients, cr.laundryservicesparticipant
, v.department_id, v.departmentnumber, v.Dep_desc
, cdn.roomnumber, cdn.clientdeliverynotenumber
, cli.client_id, cli.clientnumber
, cli.searchname, cli.name Client_name
, cus.name Customer_name, cus.customernumber, a.city
, null product_id
, wc.code Prod_code
, (select wcd.description from weighingcategory_desc wcd where wcd.weighingcategory_id=wc.weighingcategory_id and wcd.language_id = l.language_id) Prod_Desc
, '1' Sizedef_Desc
, null finishingmethod_id
, '11' Finish_desc
, cdn.invoiceweight Quantity, cdn.weightdecimals, il.price Il_Price, cdn.weightprice Price
, -3 LineInvoicebusinessunit_id
, l.code Language_code
, '' Size_code
, '' Finishing_code,  -1 FMwashtype
, ctx.TAXPERCENTAGE, ctx.TAXAMOUNT
, txg.code taxgroup_code, txg.description taxgroup_desc
, wd.department_id webuserdepartment_id
, wus.websession_id
, wuc.webuser_id
from clientdeliverynote cdn
     left outer join invoiceline il
          inner join invoiceheader ih on ih.invoiceheader_id = il.invoiceheader_id
     on cdn.invoiceline_id = il.invoiceline_id
     left outer join clientdeliverynotetax ctx
          inner join taxgroup txg on ctx.taxgroup_id = txg.taxgroup_id
     ON cdn.ClientDeliveryNote_ID = ctx.CLIENTDELIVERINOTE_ID
     inner join customer cus
           left outer join Customerresidentialsettings crs on cus.customer_id=crs.customer_id
           inner join languages l on cus.language_id = l.language_id
           inner join address a on cus.visitaddress_id = a.address_id
           inner join currency crr on cus.currency_id = crr.currency_id
     on cdn.customer_link_id = cus.customer_id
     inner join client cli
           left outer join clientresident cr on cli.client_id = cr.client_id
           inner join v_ClientDepartment v on cli.client_id = v.client_id
           inner join webusercustomer wuc
                 left outer join webuserdepartment wd on wuc.webusercustomer_id = wd.webusercustomer_id
                 inner join webusersession wus on wuc.customer_id = wus.customer_id
           on cli.customer_id = wuc.customer_id
     on cdn.client_link_id = cli.client_id
     inner join weighingcategory wc on cdn.weighingcategory_link_id = wc.weighingcategory_id
where cdn.closingdate is not null
      and (cdn.invoicebusinessunit_id = cus.defaultbusinessunit_id or
           cdn.processbusinessunit_id = cus.defaultbusinessunit_id)
union all
select 4 line_type, ll.labellayout_id
, il.invoiceline_id l_invoiceline_id,ih.invoiceheader_id invoiceheader_id,ih.invoicenumber l_invoicenumber, ih.documenttype l_documenttype
, ilh.invoiceline_id h_invoiceline_id, ihh.invoicenumber h_invoicenumber, ihh.documenttype h_documenttype
, ih.invoicebusinessunit_id ihinvoicebusinessunit_id, cdn.invoicebusinessunit_id cdninvoicebusinessunit_id
, cdn.processbusinessunit_id, cdn.customer_link_id Customer_Id, cdn.deliverydate
, crr.invoiceamountdecimals, crr.decimals pricedecimals
, cdn.closingdate
, crs.customerclients, cr.laundryservicesparticipant
, v.department_id, v.departmentnumber, v.Dep_desc
, cdn.roomnumber, cdn.clientdeliverynotenumber
, cli.client_id, cli.clientnumber
, cli.searchname, cli.name Client_name
, cus.name Customer_name, cus.customernumber, a.city
, null product_id
, ll.code Prod_code
, pqr.chargeable Prod_Desc
, pqr.preprinted Sizedef_Desc
, null finishingmethod_id
, 'N' Finish_desc
, count(*) quantity, 0 weightdecimals, il.price Il_Price, pqr.price
, pqr.invoicebusinessunit_id LineInvoicebusinessunit_id
, l.code Language_code
, '' Size_code
, '' Finishing_code,  -1 FMwashtype
, ctx.TAXPERCENTAGE, ctx.TAXAMOUNT
, txg.code taxgroup_code, txg.description taxgroup_desc
, wd.department_id webuserdepartment_id
,  wus.websession_id websession_id
,  wuc.webuser_id webuser_id
from printqueueresidentialitem pqr
     left outer join invoiceline il
          inner join invoiceheader ih on ih.invoiceheader_id = il.invoiceheader_id
     on pqr.invoiceline_id = il.invoiceline_id
     inner join clientdeliverynote cdn
           left outer join invoiceline ilh
                inner join invoiceheader ihh on ihh.invoiceheader_id = ilh.invoiceheader_id
           on cdn.invoiceline_id = ilh.invoiceline_id
           left outer join clientdeliverynotetax ctx
                inner join taxgroup txg on ctx.taxgroup_id = txg.taxgroup_id
           ON cdn.ClientDeliveryNote_ID = ctx.CLIENTDELIVERINOTE_ID
           inner join customer cus
                 left outer join Customerresidentialsettings crs on cus.customer_id = crs.customer_id
                 inner join languages l on cus.language_id = l.language_id
                 inner join address a on cus.visitaddress_id = a.address_id
                 inner join currency crr on cus.currency_id = crr.currency_id
           on cdn.customer_link_id = cus.customer_id
           inner join client cli
                 left outer join clientresident cr on cli.client_id = cr.client_id
                 inner join v_ClientDepartment v on cli.client_id = v.client_id
                 inner join webusercustomer wuc
                       left outer join webuserdepartment wd on wuc.webusercustomer_id = wd.webusercustomer_id
                       inner join webusersession wus on wuc.customer_id = wus.customer_id
                 on cli.customer_id = wuc.customer_id
           on cdn.client_link_id = cli.client_id
     on pqr.clientdeliverynote_id = cdn.clientdeliverynote_id
     inner join labellayout ll on pqr.labellayout_id = ll.labellayout_id
where cdn.closingdate is not null
      and (cdn.invoicebusinessunit_id = cus.defaultbusinessunit_id or
           cdn.processbusinessunit_id = cus.defaultbusinessunit_id)
      and not (pqr.invoiceline_id is null and pqr.patchinginvoiceline_id is not null)-- this case is selected in next branch
group by ll.labellayout_id, il.invoiceline_id, pqr.chargeable , pqr.preprinted
        , ih.invoiceheader_id , ih.invoicenumber, ih.invoicebusinessunit_id
        , cdn.processbusinessunit_id, cdn.customer_link_id, cdn.deliverydate, cdn.closingdate
        , v.department_id, v.departmentnumber, v.Dep_desc, cdn.roomnumber, cdn.clientdeliverynotenumber
        , cli.client_id, cli.clientnumber, cli.searchname, cli.name, cus.name , cus.customernumber, a.city
        , ll.code, il.price, pqr.price, cdn.invoicebusinessunit_id, l.code
        , ih.documenttype , ilh.invoiceline_id , ihh.invoicenumber , ihh.documenttype
        , crr.invoiceamountdecimals, crr.decimals, crs.customerclients, cr.laundryservicesparticipant
        , pqr.invoicebusinessunit_id, ctx.TAXPERCENTAGE, ctx.TAXAMOUNT, txg.code, txg.description
        , wd.department_id, wus.websession_id, wuc.webuser_id
union all
select 4 line_type, ll.labellayout_id
, il.invoiceline_id l_invoiceline_id,ih.invoiceheader_id invoiceheader_id,ih.invoicenumber l_invoicenumber, ih.documenttype l_documenttype
, ilh.invoiceline_id h_invoiceline_id, ihh.invoicenumber h_invoicenumber, ihh.documenttype h_documenttype
, ih.invoicebusinessunit_id ihinvoicebusinessunit_id, cdn.invoicebusinessunit_id cdninvoicebusinessunit_id
, cdn.processbusinessunit_id, cdn.customer_link_id Customer_Id, cdn.deliverydate
, crr.invoiceamountdecimals, crr.decimals pricedecimals
, cdn.closingdate
, crs.customerclients, cr.laundryservicesparticipant
, v.department_id, v.departmentnumber, v.Dep_desc
, cdn.roomnumber, cdn.clientdeliverynotenumber
, cli.client_id, cli.clientnumber
, cli.searchname, cli.name Client_name
, cus.name Customer_name, cus.customernumber, a.city
, null product_id
, ll.code Prod_code
, pqr.chargeable Prod_Desc
, pqr.preprinted Sizedef_Desc
, null finishingmethod_id
, 'Y' Finish_desc
, count(*) quantity, 0 weightdecimals, il.price Il_Price, pqr.patchprice price
, pqr.invoicebusinessunit_id LineInvoicebusinessunit_id
, l.code Language_code
, '' Size_code
, '' Finishing_code,  -1 FMwashtype
, ctx.TAXPERCENTAGE, ctx.TAXAMOUNT
, txg.code taxgroup_code, txg.description taxgroup_desc
, wd.department_id webuserdepartment_id
,  wus.websession_id websession_id
,  wuc.webuser_id webuser_id
from printqueueresidentialitem pqr
     inner join invoiceline il
          inner join invoiceheader ih on ih.invoiceheader_id = il.invoiceheader_id
     on pqr.patchinginvoiceline_id = il.invoiceline_id
     inner join clientdeliverynote cdn
           left outer join invoiceline ilh
                inner join invoiceheader ihh on ihh.invoiceheader_id = ilh.invoiceheader_id
           on cdn.invoiceline_id = ilh.invoiceline_id
           left outer join clientdeliverynotetax ctx
                inner join taxgroup txg on ctx.taxgroup_id = txg.taxgroup_id
           ON cdn.ClientDeliveryNote_ID = ctx.CLIENTDELIVERINOTE_ID
           inner join customer cus
                 left outer join Customerresidentialsettings crs on cus.customer_id = crs.customer_id
                 inner join languages l on cus.language_id = l.language_id
                 inner join address a on cus.visitaddress_id = a.address_id
                 inner join currency crr on cus.currency_id = crr.currency_id
           on cdn.customer_link_id = cus.customer_id
           inner join client cli
                 left outer join clientresident cr on cli.client_id = cr.client_id
                 inner join v_ClientDepartment v on cli.client_id = v.client_id
                 inner join webusercustomer wuc
                       left outer join webuserdepartment wd on wuc.webusercustomer_id = wd.webusercustomer_id
                       inner join webusersession wus on wuc.customer_id = wus.customer_id
                 on cli.customer_id = wuc.customer_id
           on cdn.client_link_id = cli.client_id
     on pqr.clientdeliverynote_id = cdn.clientdeliverynote_id
     inner join labellayout ll on pqr.labellayout_id = ll.labellayout_id
where cdn.closingdate is not null
      and (cdn.invoicebusinessunit_id = cus.defaultbusinessunit_id or
           cdn.processbusinessunit_id = cus.defaultbusinessunit_id)
group by ll.labellayout_id, il.invoiceline_id, pqr.chargeable, pqr.preprinted
        , ih.invoiceheader_id, ih.invoicenumber, ih.invoicebusinessunit_id
        , cdn.processbusinessunit_id, cdn.customer_link_id, cdn.deliverydate, cdn.closingdate
        , v.department_id, v.departmentnumber, v.Dep_desc, cdn.roomnumber, cdn.clientdeliverynotenumber
        , cli.client_id, cli.clientnumber, cli.searchname, cli.name, cus.name, cus.customernumber, a.city
        , ll.code, il.price, pqr.patchprice, cdn.invoicebusinessunit_id, l.code
        , ih.documenttype, ilh.invoiceline_id, ihh.invoicenumber , ihh.documenttype
        , crr.invoiceamountdecimals, crr.decimals, crs.customerclients, cr.laundryservicesparticipant
        , pqr.invoicebusinessunit_id, ctx.TAXPERCENTAGE, ctx.TAXAMOUNT, txg.code, txg.description
        , wd.department_id, wus.websession_id, wuc.webuser_id
/

  CREATE OR REPLACE VIEW "V_WORKORDER" ("WORKORDER_ID", "WORKORDERNUMBER", "ORDERDATE", "REFERENCENUMBER", "ORDERREMARK", "DELIVERYDATE", "SCHEDULEDDELIVERY", "ORIGIN", "DELIVERYDAY_DESC", "SCHEDULEDDELIVERY_DESC", "DOCKET", "CUSTOMERNUMBER", "NAME", "CUSTOMERMARKINGGARMENT", "STREET", "ZIPCODE", "CITY", "CUSTSTATE", "WCUSTOMERNUMBER", "WNAME", "WCUSTOMERMARKINGGARMENT", "WSTREET", "WZIPCODE", "WCITY", "WEARERNR", "WEARERNAME", "WEARERSEARCHNAME", "WEARERFIRSTNAME", "ADMIN", "EMPLNR", "CUPBOARD", "LOCKER", "LOCKER_DELPOINT", "GARMENTDISPENSER", "DELIVERYPOINT", "DEPARTMENT", "DEPARTMENTNUMBER", "NAMEONLABEL", "CONSPOINT", "FUNCTIONX", "WEARERREMARK", "ROUTENUMBER", "ROUTEDESCRIPTION", "NOTLAUNDRYOWNED", "STATUSCODE", "COUNTWORKORDERLINE", "COUNTWORKORDERLINEEMBLEM", "WORKORDER_DELIVERFROM", "PLANT_CODE", "PLANT_NAME", "PLANT_PHONENO", "PLANT_FAXNO", "PLANT_EMAIL", "PLANT_WEBSITE", "PLANT_STREET", "PLANT_STREET2", "PLANT_ZIPCODE", "PLANT_CITY", "PLANT_STATE", "PLANT_COUNTY", "SUBSTITUTION", "PRINT_BARCODE", "LANGUAGE_CODE", "PRINTREPLACEMENTSONWO", "TOTALROWS", "EMPLOYEENUMBER", "EMPLOYEE_NAME", "PHONENO", "MOBILENO", "FAXNO", "EMAIL", "REMARK", "CODE", "DESCRIPTION", "DELIVERYPOINT_STREET", "DELIVERYPOINT_ZIPCODE", "DELIVERYPOINT_CITY", "DAY_ID", "STARTTIME", "ENDTIME", "BREAKSTARTTIME", "BREAKENDTIME", "REPLACEMENT", "WOREFERENCENUMBER_ID", "WOREFERENCENR", "WOREFNR_DESC", "BUCODE", "REASONCODEDESC", "FROMSTOCK", "TOSTOCK", "IMAGE") AS 
  select
  wok.workorder_id, wok.workordernumber, wok.requestdate orderdate, wok.referencenumber
, wok.remark orderremark, wok.neededdate deliverydate, wok.expectedcompletedate scheduleddelivery, wok.origin origin--, cast (getdaydescription(wok.neededdate) as varchar2(30)) deliveryday_desc
, (select dd.description from day_desc dd where dd.day_id = getabsdaynumber(wok.neededdate)
 and dd.language_id = lan.language_id) deliveryday_desc--, cast (getdaydescription(wok.expectedcompletedate) as varchar2(30)) scheduleddelivery_desc
, (select dd.description from day_desc dd where dd.day_id = getabsdaynumber(wok.expectedcompletedate)
 and dd.language_id = lan.language_id) scheduleddelivery_desc
, wok.workordernumber docket
, coalesce(cu.customernumber, wdec.customernumber) customernumber
, coalesce(cu.name, wdec.name) name
, coalesce(cu.customermarkinggarment, wdec.customermarkinggarment) customermarkinggarment
, coalesce(cad.street, wdca.street) street
, coalesce(cad.zipcode, wdca.zipcode) zipcode
, coalesce(cad.city, wdca.city) city
, coalesce(cad.state, wdca.state) custstate
, wcu.customernumber wcustomernumber, wcu.name wname, wcu.customermarkinggarment wcustomermarkinggarment
, wcua.street wstreet, wcua.zipcode wzipcode, wcua.city wcity
, w.wearernumber wearernr, w.fullname wearername, w.searchname wearersearchname, w.firstname wearerfirstname
, w.customeremployeenumber admin, we.sequencenumber emplnr, lo.bank cupboard, lo.locker
, (select dp1.code from deliverypoint dp1 where dp1.deliverypoint_id = lo.deliverypoint_id) locker_delpoint
, ga.code garmentdispenser, delp.code deliverypoint
, de.description department, de.departmentnumber
, w.emblemname nameonlabel, dp.description conspoint--, wearerfunction.description functionx
, (select wf.description from wearerfunction wf where we.wearerfunction_id = wf.wearerfunction_id) functionx
, w.remark wearerremark, ro.routenumber, ro.description routedescription
, wok.customerowned notlaundryowned, sta.code statuscode
, coalesce( ( select count(wokli.workorderline_id) from workorderline wokli
            where wok.workorder_id = wokli.workorder_id )
            , 0) countworkorderline
, coalesce( ( select count(wokem.workorderlineemblem_id) from workorderline wokli, workorderlineemblem wokem
            where wok.workorder_id = wokli.workorder_id and wokli.workorderline_id = wokem.workorderline_id)
            , 0) countworkorderlineemblem
, wok.deliverfrom workorder_deliverfrom
, pl.code plant_code, pl.name plant_name, pl.phoneno plant_phoneno, pl.faxno plant_faxno
, pl.email plant_email, pl.website plant_website
, paddr.street plant_street, paddr.street2 plant_street2, paddr.zipcode plant_zipcode
, paddr.city plant_city, paddr.state plant_state, paddr.county plant_county
, case when (select sum(woli.quantitysubstitute) from workorderline woli where woli.workorder_id = wok.workorder_id) > 0
            then 'Y' else 'N' end substitution--, ss.value print_barcode
, lpad((select ss.value from systemsetting ss where ss.plant_id = pl.plant_id and ss.name = 'PRINTBARCODEONWORKORDER'), 1) print_barcode
, lan.code language_code
, lpad((select sy.value from systemsetting sy where sy.plant_id = pl.plant_id and sy.name = 'PRINTREPLACEMENTSONWO'), 1) printreplacementsonwo
, (select count(distinct v.workorderline_id) from v_workorderline v where v.workorder_id = wok.workorder_id and v.languagecode = lan.code) totalrows
, emp.employeenumber
, emp.name employee_name
, emp.phoneno
, emp.mobileno
, emp.faxno
, emp.email
, emp.remark
, delp.code
, delp.description
, adr.street deliverypoint_street
, adr.zipcode deliverypoint_zipcode
, adr.city deliverypoint_city
, getabsdaynumber(wok.neededdate) day_id
, (select dpoh.starttime from deliverypointopeninghour dpoh where delp.deliverypoint_id = dpoh.deliverypoint_id and dpoh.day_id = getabsdaynumber(wok.neededdate)) starttime
, (select dpoh.endtime from deliverypointopeninghour dpoh where delp.deliverypoint_id = dpoh.deliverypoint_id and dpoh.day_id = getabsdaynumber(wok.neededdate)) endtime
, delp.breakstarttime
, delp.breakendtime
, wok.replacement
, wok.woreferencenumber_id
, worefnr.referencenumber woreferencenr
, worefnr.description worefnr_desc
, bu.code bucode
, (select max(rc.code || '  ' || coalesce((select rcd.description from reasoncode_desc rcd where rcd.reasoncode_id = rc.reasoncode_id and rcd.language_id = lan.language_id), ''))
  from reasoncode rc, workorderline wokli where wokli.workorder_id = wok.workorder_id and rc.reasoncode_id = wokli.reasoncode_id) reasoncodedesc
, (select st.code ||'  ' ||st.name from stockroom st where wok.processingstockroom_id=st.stockroom_id) fromstock
, (select stt.code ||'  ' ||stt.name from stockroom stt where stt.stockroom_id=wcu.orderingstockroom_id and wcu.customertype=1) tostock
, (case when (select count(1) from workorderline wol where wol.workorder_id = wok.workorder_id) = 1
        then (select image.image from product p inner join image on p.image_id = image.image_id
                                                inner join workorderline wol on p.product_id = wol.product_link_id
                                                where wol.workorder_id = wok.workorder_id)
   else null end) Image
from workorder wok
           left outer join weareremployment we
                inner join wearer w on we.wearer_id = w.wearer_id
                left outer join locker lo on we.locker_id = lo.locker_id
                left outer join garmentdispenser ga on we.garmentdispenser_id = ga.garmentdispenser_id
                left outer join deliverypoint delp
                   left outer join address adr on delp.deliveryaddress_id = adr.address_id
                on we.deliverypoint_id = delp.deliverypoint_id
                inner join distributionpoint dp
                      inner join department de
                            inner join customer cu
                                 inner join address cad on cu.visitaddress_id = cad.address_id
                            on cu.customer_id = de.customer_id
                      on dp.department_id = de.department_id
                on we.distributionpoint_id = dp.distributionpoint_id
           on wok.weareremployment_link_id = we.weareremployment_id --left outer join wearerfunction on we.wearerfunction_id = wearerfunction.wearerfunction_id
          left outer join route ro on wok.route_id = ro.route_id
          left outer join systemuser su
               left outer join employee emp on su.employee_id = emp.employee_id
          on wok.creationuser_id = su.systemuser_id
          left outer join woreferencenumber worefnr on wok.woreferencenumber_id = worefnr.woreferencenumber_id
          inner join status sta on wok.status_id = sta.status_id
          inner join businessunit bu
                inner join plant pl
                      inner join address paddr on pl.address_id = paddr.address_id
                on bu.plant_id = pl.plant_id
          on wok.businessunit_id = bu.businessunit_id
         left outer join distributionpoint wdp
              left outer join department wde
                   left outer join customer wdec
                        left outer join address wdca on wdec.visitaddress_id = wdca.address_id
                   on wde.customer_id = wdec.customer_id
              on wdp.department_id = wde.department_id
         on wok.distributionpoint_link_id = wdp.distributionpoint_id
         left outer join customer wcu
              inner join address wcua on wcu.visitaddress_id = wcua.address_id
         on wok.customer_link_id = wcu.customer_id
, languages lan
/

  CREATE OR REPLACE VIEW "V_WORKORDER_CFC" ("WORKORDER_ID", "WORKORDERNUMBER", "ORDERDATE", "REFERENCENUMBER", "ORDERREMARK", "DELIVERYDATE", "SCHEDULEDDELIVERY", "ORIGIN", "DELIVERYDAY_DESC", "SCHEDULEDDELIVERY_DESC", "DOCKET", "ALLOWPHASEDELIVERY", "PONUMBER", "BUCODE", "BUDESC", "PRIORITYCODE", "ORDERTYPE", "PRIODESC", "RESCODE", "RCDESC", "POPRIOCODE", "POPRIODESC", "CUSTOMERNUMBER", "NAME", "CUSTOMERMARKINGGARMENT", "PREWASHFORGARMENTS", "STREET", "ZIPCODE", "CITY", "WCUSTOMERNUMBER", "WNAME", "WCUSTOMERMARKINGGARMENT", "WSTREET", "WZIPCODE", "WCITY", "WEARERNR", "WEARERNAME", "WEARERSEARCHNAME", "WEARERFIRSTNAME", "ADMIN", "EMPLNR", "CUPBOARD", "LOCKER", "GARMENTDISPENSER", "DELIVERYPOINT", "DELIVERYPOINTDESC", "DEPARTMENT", "DEPARTMENTNUMBER", "NAMEONLABEL", "CONSPOINT", "FUNCTIONX", "WEARERREMARK", "ROUTENUMBER", "ROUTEDESCRIPTION", "NOTLAUNDRYOWNED", "STATUSCODE", "COUNTWORKORDERLINE", "COUNTWORKORDERLINEEMBLEM", "WORKORDER_DELIVERFROM", "PLANT_CODE", "PLANT_NAME", "PLANT_PHONENO", "PLANT_FAXNO", "PLANT_EMAIL", "PLANT_WEBSITE", "PLANT_STREET", "PLANT_STREET2", "PLANT_ZIPCODE", "PLANT_CITY", "PLANT_STATE", "PLANT_COUNTY", "SUBSTITUTION", "PRINT_BARCODE", "LANGUAGE_CODE", "PRINTREPLACEMENTSONWO", "TOTALROWS", "EMPLOYEENUMBER", "EMPLOYEE_NAME", "PHONENO", "MOBILENO", "FAXNO", "EMAIL", "REMARK", "CODE", "DESCRIPTION", "DELIVERYPOINT_STREET", "DELIVERYPOINT_ZIPCODE", "DELIVERYPOINT_CITY", "DAY_ID", "STARTTIME", "ENDTIME", "BREAKSTARTTIME", "BREAKENDTIME", "REPLACEMENT", "WOREFERENCENUMBER_ID", "WOREFERENCENR", "WOREFNR_DESC", "REPORTPARAM_ID", "NATACC", "STOCKROOMNAME") AS 
  select wok.workorder_id, wok.workordernumber, wok.requestdate OrderDate, wok.referencenumber
, wok.remark OrderRemark, wok.neededdate DeliveryDate, wok.expectedcompletedate ScheduledDelivery, wok.origin origin
, (select dd.description from day_desc dd where dd.day_id = getabsdaynumber(wok.neededdate)
 and dd.language_id = lan.language_id) DeliveryDay_Desc
, (select dd.description from day_desc dd where dd.day_id = getabsdaynumber(wok.expectedcompletedate)
 and dd.language_id = lan.language_id) ScheduledDelivery_Desc
, wok.workordernumber Docket, wok.allowphasedelivery,
 (select min(poh.purchaseordernumber) from purchaseorderline pol, purchaseorderheader poh, workorderline wol
        left outer join workorderlinepurchordline wolpol on wolpol.workorderline_id = wol.workorderline_id
       where wol.workorder_id = wok.workorder_id
         and nvl(wol.purchaseorderline_id ,wolpol.purchaseorderline_id) = pol.purchaseorderline_id
         and pol.purchaseorderheader_id = poh.purchaseorderheader_id) POnumber
, bu.code bucode, bu.description budesc, op.prioritycode, op.ordertype
, (select od.description from orderpriority_desc od where od.orderpriority_id = op.orderpriority_id and od.language_id = lan.language_id) priodesc
, rc.code rescode,(select rcd.description from reasoncode_desc rcd where rcd.reasoncode_id = rc.reasoncode_id and rcd.language_id = lan.language_id) rcdesc
, (select opr.prioritycode from orderpriority opr where rc.purchaseorderpriority_id = opr.orderpriority_id and opr.ordertype = 2) POpriocode
, (select oprdesc.description from orderpriority_desc oprdesc where rc.purchaseorderpriority_id=oprdesc.orderpriority_id and oprdesc.language_id = lan.language_id) POpriodesc
, cu.customernumber, cu.name, cu.customermarkinggarment, cu.prewashforgarments, cua.street, cua.zipcode, cua.city
, wcu.customernumber wcustomernumber, wcu.name wname, wcu.customermarkinggarment wcustomermarkinggarment
, wcua.street wstreet, wcua.zipcode wzipcode, wcua.city wcity, w.wearernumber WearerNr
, w.fullname WearerName, w.searchname wearersearchname, W.FIRSTNAME WearerFIRSTNAME
, w.customeremployeenumber Admin, we.sequencenumber EmplNr, lo.bank CupBoard, lo.locker
, ga.code GarmentDispenser, de.code DeliveryPoint
, (select de.description from deliverypoint de where de.deliverypoint_id = dp.deliverypoint_id) DeliveryPointDesc
, dep.description Department, dep.departmentnumber
, w.emblemname NameOnLabel, dp.description ConsPoint--, wearerfunction.description FunctionX
, (select wf.description from wearerfunction wf where we.wearerfunction_id = wf.wearerfunction_id) FunctionX
, w.remark WearerRemark, ro.routenumber, ro.description RouteDescription
, wok.customerowned NotLaundryOwned, st.code StatusCode
, coalesce( ( select count(wokli.workorderline_id) from workorderline wokli
            where wok.workorder_id = wokli.workorder_id )
            , 0) countWorkorderLine
, coalesce( ( select count(wokem.workorderlineemblem_id) from workorderline wokli, workorderlineemblem wokem
            where wok.workorder_id = wokli.workorder_id and wokli.workorderline_id = wokem.workorderline_id)
            , 0) countWorkorderLineEmblem
, wok.deliverfrom workorder_deliverfrom
, pl.code plant_code, pl.name plant_name, pl.phoneno plant_phoneno, pl.faxno plant_faxno
, pl.email plant_email, pl.website plant_website
, paddr.street plant_street, paddr.street2 plant_street2, paddr.zipcode plant_zipcode
, paddr.city plant_city, paddr.state plant_state, paddr.county plant_county
, case when (select sum(woli.QUANTITYSUBSTITUTE) from workorderline woli where woli.workorder_id = wok.workorder_id) > 0
            then 'Y' else 'N' end SUBSTITUTION--, ss.value Print_Barcode
, lpad((select ss.value from systemsetting ss where ss.plant_id = pl.plant_id and ss.name = 'PRINTBARCODEONWORKORDER'), 1) Print_Barcode
, lan.code Language_code
, lpad((select sy.value from systemsetting sy where sy.plant_id = pl.plant_id and sy.name = 'PRINTREPLACEMENTSONWO'), 1) PRINTREPLACEMENTSONWO
, (SELECT COUNT(DISTINCT v.workorderline_id) FROM v_workorderline v WHERE v.workorder_id = wok.workorder_id AND v.languagecode = lan.code) TotalRows
, emp.employeenumber, emp.name employee_name, emp.phoneno, emp.mobileno, emp.faxno, emp.email, emp.remark
, de.code, de.description, adr.street deliverypoint_street, adr.zipcode deliverypoint_zipcode, adr.city deliverypoint_city
, dpoh.day_id, dpoh.starttime, dpoh.endtime, de.breakstarttime, de.breakendtime, wok.replacement, wok.woreferencenumber_id
, worefnr.referencenumber woreferencenr, worefnr.description worefnr_desc, rp.reportparam_id
, (select nt.code from nationalaccount nt where nt.nationalaccount_id = cu.nationalaccount_id) natacc
, (select sr.name from stockroom sr where sr.stockroom_id = wok.processingstockroom_id) StockRoomName
from reportparam rp
     inner join workorder wok
           left outer join weareremployment we
                inner join wearer w on we.wearer_id = w.wearer_id
                left outer join locker lo on we.locker_id = lo.locker_id
                left outer join garmentdispenser ga on we.garmentdispenser_id = ga.garmentdispenser_id
                left outer join deliverypoint de on we.deliverypoint_id = de.deliverypoint_id
           on wok.weareremployment_link_id = we.weareremployment_id
                left outer join deliverypoint dpl
                     inner join address adr on dpl.deliveryaddress_id = adr.address_id
                on coalesce(lo.deliverypoint_id, ga.deliverypoint_id, we.deliverypoint_id) = dpl.deliverypoint_id
                left outer join deliverypointopeninghour dpoh on dpl.deliverypoint_id = dpoh.deliverypoint_id and dpoh.day_id = getabsdaynumber(wok.neededdate)
                left outer join distributionpoint dp
                    inner join department dep
                           inner join customer cu
                                 inner join address cua on cu.visitaddress_id = cua.address_id
                           on cu.customer_id = dep.customer_id
                     on dp.department_id = dep.department_id
                on coalesce(we.distributionpoint_id, wok.distributionpoint_link_id) = dp.distributionpoint_id
           left outer join route ro on wok.route_id = ro.route_id
           left outer join Systemuser su
                left outer join employee emp on su.employee_id = emp.employee_id
           on wok.creationuser_id = su.systemuser_id
           left outer join woreferencenumber worefnr on wok.woreferencenumber_id = worefnr.woreferencenumber_id
           left outer join customer wcu
                inner join address wcua on wcu.visitaddress_id = wcua.address_id
           on wok.customer_link_id = wcu.customer_id
           inner join status st on wok.status_id = st.status_id
           inner join businessunit bu
                 inner join plant pl
                       inner join address paddr on pl.address_id = paddr.address_id
                 on bu.plant_id = pl.plant_id
           on wok.businessunit_id = bu.businessunit_id
           inner join orderpriority op on wok.orderpriority_id = op.orderpriority_id
           inner join reasoncode rc on wok.reasoncode_id = rc.reasoncode_id
     on rp.number_value = wok.workorder_id
, languages lan
where op.ordertype = 1
/

  CREATE OR REPLACE VIEW "V_WORKORDER_REP" ("WORKORDER_ID", "WORKORDERNUMBER", "ORDERDATE", "REFERENCENUMBER", "ORDERREMARK", "DELIVERYDATE", "SCHEDULEDDELIVERY", "ORIGIN", "WCUSTOMERNUMBER", "WNAME", "REPORTPARAM_ID", "WCUSTOMERMARKINGGARMENT", "WSTREET", "WZIPCODE", "WCITY", "WEARERNR", "WEARERNAME", "WEARERSEARCHNAME", "WEARERFIRSTNAME", "ADMIN", "EMPLNR", "EMBROIDERYLETTERINGLINE1", "EMBROIDERYLETTERINGLINE2", "EMBROIDERYLETTERINGLINE3", "CUPBOARD", "LOCKER", "GARMENTDISPENSER", "DELIVERYPOINT", "DEPARTMENT", "DEPARTMENTNUMBER", "DESCRIPTION", "NAMEONLABEL", "CONSPOINT", "WEARERREMARK", "ROUTENUMBER", "ROUTEDESCRIPTION", "STATUSCODE", "NOTLAUNDRYOWNED", "WORKORDER_DELIVERFROM", "PLANT_CODE", "PLANT_NAME", "PLANT_PHONENO", "CODE", "PLANT_FAXNO", "PLANT_EMAIL", "PLANT_WEBSITE", "PLANT_STREET", "PLANT_STREET2", "PLANT_ZIPCODE", "PLANT_CITY", "PLANT_STATE", "PLANT_COUNTY", "LANGUAGE_CODE", "EMPLOYEENUMBER", "EMPLOYEE_NAME", "PHONENO", "MOBILENO", "FAXNO", "EMAIL", "REMARK", "DELIVERYPOINT_STREET", "DELIVERYPOINT_ZIPCODE", "DELIVERYPOINT_CITY", "DAY_ID", "BREAKSTARTTIME", "BREAKENDTIME", "REPLACEMENT", "WOREFERENCENUMBER_ID", "WOREFERENCENR", "WOREFNR_DESC", "BUCODE", "DOCKET", "BU_DESC", "DISTRIBUTIONPOINTNUMBER", "CUSTOMERNUMBER", "NAME", "CUSTOMERMARKINGGARMENT", "STREET", "ZIPCODE", "CITY", "CUSTSTATE", "COUNTWORKORDERLINE", "COUNTWORKORDERLINEEMBLEM", "DELIVERYDAY_DESC", "SCHEDULEDDELIVERY_DESC", "LOCKER_DELPOINT", "FUNCTIONX", "TOTALROWS", "STARTTIME", "ENDTIME", "REASONCODEDESC", "SUBSTITUTION", "PRINT_BARCODE", "PRINTREPLACEMENTSONWO", "DEPOTDESC", "SYSTEMUSER_FULLNAME") AS 
  select /*version 2.4*/
       wok.workorder_id, wok.workordernumber, wok.requestdate orderdate, wok.referencenumber, wok.remark orderremark, wok.neededdate deliverydate,
       wok.expectedcompletedate scheduleddelivery, wok.origin origin, wcu.customernumber wcustomernumber, wcu.name wname, rp.reportparam_id,
       wcu.customermarkinggarment wcustomermarkinggarment, wcua.street wstreet, wcua.zipcode wzipcode, wcua.city wcity, w.wearernumber wearernr,
       w.fullname wearername, w.searchname wearersearchname, w.firstname wearerfirstname, w.customeremployeenumber admin, we.sequencenumber emplnr,
       we.embroideryletteringline1, we.embroideryletteringline2, we.embroideryletteringline3,
       lo.bank cupboard, lo.locker, ga.code garmentdispenser, delp.code deliverypoint, de.description department, de.departmentnumber, delp.description,
       w.emblemname nameonlabel, dp.description conspoint, w.remark wearerremark, ro.routenumber, ro.description routedescription, sta.code statuscode,
       wok.customerowned notlaundryowned, wok.deliverfrom workorder_deliverfrom, pl.code plant_code, pl.name plant_name, pl.phoneno plant_phoneno, delp.code,
       pl.faxno plant_faxno, pl.email plant_email, pl.website plant_website, paddr.street plant_street, paddr.street2 plant_street2, paddr.zipcode plant_zipcode,
       paddr.city plant_city, paddr.state plant_state, paddr.county plant_county, lan.code language_code, emp.employeenumber, emp.name employee_name, emp.phoneno,
       emp.mobileno, emp.faxno, emp.email, emp.remark, adr.street deliverypoint_street, adr.zipcode deliverypoint_zipcode, adr.city deliverypoint_city,
       getabsdaynumber(wok.neededdate) day_id, delp.breakstarttime, delp.breakendtime, wok.replacement, wok.woreferencenumber_id, worefnr.referencenumber woreferencenr,
       worefnr.description worefnr_desc, bu.code bucode, wok.workordernumber docket, bu.description bu_desc, dp.distributionpointnumber,
       coalesce(cu.customernumber, wdec.customernumber) customernumber,
       coalesce(cu.name, wdec.name) name,
       coalesce(cu.customermarkinggarment, wdec.customermarkinggarment) customermarkinggarment,
       coalesce(cad.street, wdca.street) street,
       coalesce(cad.zipcode, wdca.zipcode) zipcode,
       coalesce(cad.city, wdca.city) city,
       coalesce(cad.state, wdca.state) custstate,
       coalesce((select count(wokli.workorderline_id)
                   from workorderline wokli
                  where wok.workorder_id = wokli.workorder_id ), 0) countworkorderline,
       coalesce((select count(wokem.workorderlineemblem_id)
                   from workorderline wokli
                        join workorderlineemblem wokem on wokli.workorderline_id = wokem.workorderline_id
             where wok.workorder_id = wokli.workorder_id), 0) countworkorderlineemblem,
       (select dd.description
          from day_desc dd
         where dd.day_id = getabsdaynumber(wok.neededdate)
           and dd.language_id = lan.language_id) deliveryday_desc,
       (select dd.description
          from day_desc dd
         where dd.day_id = getabsdaynumber(wok.expectedcompletedate)
           and dd.language_id = lan.language_id) scheduleddelivery_desc,
       (select dp1.code
          from deliverypoint dp1
         where dp1.deliverypoint_id = lo.deliverypoint_id) locker_delpoint,
       coalesce((select wf.description
          from wearerfunction wf
         where we.wearerfunction_id = wf.wearerfunction_id), '-') functionx,
       (select count(distinct v.workorderline_id)
          from v_workorderline v
         where v.workorder_id = wok.workorder_id
           and v.languagecode = lan.code) totalrows,
       (select dpoh.starttime
          from deliverypointopeninghour dpoh
         where delp.deliverypoint_id = dpoh.deliverypoint_id
           and dpoh.day_id = getabsdaynumber(wok.neededdate)) starttime,
       (select dpoh.endtime from deliverypointopeninghour dpoh
         where delp.deliverypoint_id = dpoh.deliverypoint_id
           and dpoh.day_id = getabsdaynumber(wok.neededdate)) endtime,
       (select max(rc.code || '  ' || coalesce((select rcd.description
                                                  from reasoncode_desc rcd
                                                 where rcd.reasoncode_id = rc.reasoncode_id
                                                   and rcd.language_id = lan.language_id), ''))
          from reasoncode rc
               join workorderline wokli on rc.reasoncode_id = wokli.reasoncode_id
         where wokli.workorder_id = wok.workorder_id) reasoncodedesc,
       case when (select sum(woli.quantitysubstitute) from workorderline woli where woli.workorder_id = wok.workorder_id) > 0 then 'Y'
            else 'N'
        end substitution,
       lpad((select ss.value
               from systemsetting ss
              where ss.plant_id = pl.plant_id
                and ss.name = 'PRINTBARCODEONWORKORDER'), 1) print_barcode,
       lpad((select sy.value
               from systemsetting sy
              where sy.plant_id = pl.plant_id
                and sy.name = 'PRINTREPLACEMENTSONWO'), 1) printreplacementsonwo,
       (select d.description from depot d where d.depot_id = ro.depot_id) depotdesc,
       su.fullname systemuser_fullname
from reportparam rp
     join workorder wok
          left join weareremployment we
               join wearer w on we.wearer_id = w.wearer_id
               left join locker lo on we.locker_id = lo.locker_id
               left join garmentdispenser ga on we.garmentdispenser_id = ga.garmentdispenser_id
               left join deliverypoint delp
                         left join address adr on delp.deliveryaddress_id = adr.address_id
               on we.deliverypoint_id = delp.deliverypoint_id
               join distributionpoint dp
                    join department de
                         join customer cu
                              join address cad on cu.visitaddress_id = cad.address_id
                         on cu.customer_id = de.customer_id
                    on dp.department_id = de.department_id
               on we.distributionpoint_id = dp.distributionpoint_id
          on wok.weareremployment_link_id = we.weareremployment_id
          left join route ro on wok.route_id = ro.route_id
          left join systemuser su
                    left join employee emp on su.employee_id = emp.employee_id
          on wok.creationuser_id = su.systemuser_id
          left join woreferencenumber worefnr on wok.woreferencenumber_id = worefnr.woreferencenumber_id
          join status sta on wok.status_id = sta.status_id
          join businessunit bu
               join plant pl
                    join address paddr on pl.address_id = paddr.address_id
               on bu.plant_id = pl.plant_id
          on wok.businessunit_id = bu.businessunit_id
          left join distributionpoint wdp
                    left join department wde
                              left join customer wdec
                                        left join address wdca on wdec.visitaddress_id = wdca.address_id
                              on wde.customer_id = wdec.customer_id
                    on wdp.department_id = wde.department_id
         on wok.distributionpoint_link_id = wdp.distributionpoint_id
         left join customer wcu
                   join address wcua on wcu.visitaddress_id = wcua.address_id
         on wok.customer_link_id = wcu.customer_id
     on rp.number_value = wok.workorder_id
     cross join languages lan
/

  CREATE OR REPLACE VIEW "V_XML_PEPPOL_BILLING" ("INVOICEHEADER_ID", "INVOICEDATE", "INVOICENUMBER", "PAYTHISAMOUNT", "BILLTOCUSTOMER_LINK_ID", "TMC_XML") AS 
  select /*view v_xml_peppol_billing version 3.0*/
 invoiceheader_id, invoicedate, invoicenumber, paythisamount, billtocustomer_link_id, tmc_xml
from   v_xml_peppol_billing_debit --version 2
join   abs_view_version p on p.viewname = 'V_XML_PEPPOL_BILLING'
where  p.version = 2
union all
select invoiceheader_id, invoicedate, invoicenumber, paythisamount, billtocustomer_link_id, tmc_xml
from   v_xml_peppol_billing_credit --version 2
join   abs_view_version p on p.viewname = 'V_XML_PEPPOL_BILLING'
where  p.version = 2
union all
select invoiceheader_id, invoicedate, invoicenumber, paythisamount, billtocustomer_link_id, tmc_xml
from   v_xml_peppol_billing_debit_30 --version 3.0
join   abs_view_version p on p.viewname = 'V_XML_PEPPOL_BILLING'
where  p.version = 3
union all
select invoiceheader_id, invoicedate, invoicenumber, paythisamount, billtocustomer_link_id, tmc_xml
from   v_xml_peppol_billing_credit_30 --version 3.0
join   abs_view_version p on p.viewname = 'V_XML_PEPPOL_BILLING'
where  p.version = 3
/

  CREATE OR REPLACE VIEW "XV_TEST_CIRC_INVENTORY2" ("WEARERINVENTORY_ID", "COUNTUI", "COUNTNUI") AS 
  select v1.wearerinventory_id, sum(v1.countui), sum(v1.countnui)
	from xv_test_circ_inventory v1
	group by v1.wearerinventory_id
/

  CREATE OR REPLACE VIEW "EDI_TRANSACTION_LOG" ("EDI_TABLENAME", "TRANSFER_ID", "TRANSFER_STATUS", "TEXT", "PROCESS_STATUS", "TIMESTAMP") AS 
  select 'EDI_I_CUSTPURCHASEORDER_LOG' edi_tablename,
       transfer_id,
       transfer_status,
       text,
       process_status,
       timestamp
  from edi_i_custpurchaseorder_log
union all
select 'EDI_O_PURCHASEORDERACK_LOG' edi_tablename,
       transfer_id,
       transfer_status,
       text,
       process_status,
       timestamp
  from edi_o_Purchaseorderack_log
union all
select 'EDI_O_ADVSHIPNOTICE_LOG' edi_tablename,
       transfer_id,
       transfer_status,
       text,
       process_status,
       timestamp
  from edi_o_advshipnotice_log
union all
select 'EDI_O_INVOICE_810_LOG' edi_tablename,
       transfer_id,
       transfer_status,
       text,
       process_status,
       timestamp
  from edi_o_invoice_810_log
/

  CREATE OR REPLACE VIEW "REP_USERINSTRCUSTOMER_HEAD" ("CUSTOMER_ID", "CUSTOMERNUMBER", "TACODE", "FMCODE", "CUSTOMERNAME", "DEFAULTBUSINESSUNIT_ID", "BUCODE", "CITY", "ACTIVE", "TADESC", "FMDESC", "ROUTENUMBER", "STOPNUMBER", "DRIVINGDATE") AS 
  select c.customer_id, c.customernumber, ta.code tacode, fm.code fmcode,c.name customername, c.defaultbusinessunit_id, bu.code bucode, a.city, c.active,
(select max(tad.description) from transportarticle_desc  tad where tad.transportarticle_id=ta.transportarticle_id) tadesc,
(select max(fmd.description) from finishingmethod_desc fmd where fmd.finishingmethod_id=fm.finishingmethod_id) fmdesc
, r.routenumber, rs.stopnumber, rc.drivingdate
  from transportarticle  ta,
       standarddelivery  std,
       distributionpoint dip,
       deliverypoint     dlp,
       --customer          c,
       productlistpercustomer plc,
       finishingmethod fm,
       product pr --add WBO 29-11-2008
, customer c,  address a, businessunit bu, route r, routestop rs, routecontrol rc
 where ta.transportarticle_id = std.transportarticle_id
   and std.distributionpoint_id = dip.distributionpoint_id
   and dip.deliverypoint_id = dlp.deliverypoint_id
   and dlp.customer_id = c.customer_id
   and plc.customer_id=c.customer_id
   and plc.dateactive < sysdate  -- add KLO 09-03-2011
   and plc.dateinactive > sysdate   -- add KLO 09-03-2011
   and fm.code <> 'STD'             -- add KLO 09-03-2011
   and plc.finishingmethod_id=fm.finishingmethod_id
and pr.product_id=plc.product_id --add WBO 29-11-2008
and pr.code not in ('9033','9550') --add WBO 29-11-2008
and c.visitaddress_id = a.address_id
and c.defaultbusinessunit_id = bu.businessunit_id
and r.route_id=rs.route_id
and rs.customer_id=c.customer_id
--and rs.dateactive < sysdate -- add KLO 28-09-2010
and rs.dateinactive > sysdate -- add KLO 28-09-2010
and rc.route_id=r.route_id
and rc.plant_id=bu.plant_id
group by c.customer_id, c.customernumber, ta.code, fm.code,ta.transportarticle_id, fm.finishingmethod_id
,c.name,  c.defaultbusinessunit_id, bu.code, a.city, c.active,
 r.routenumber, rs.stopnumber, rc.drivingdate
   order by bu.code, r.routenumber, ta.code, rs.stopnumber, c.customernumber
/

  CREATE OR REPLACE VIEW "TESTDELIVERYSCHEME" ("SUMDELQTY", "SUMTOBEDEL", "PACKINGNOTELINE_ID") AS 
  select sum(a.deliveredqty) sumdelqty, sum(a.tobedeliveredqty) sumtobedel, a.packingnoteline_id from packingnotelineperdelscheme a
group by a.deliveryscheme_id, a.packingnoteline_id
/

  CREATE OR REPLACE VIEW "TEST_DELIVERYFREQUENCY" ("FREQUENCY", "CUSTOMER_ID") AS 
  select --a.deliveryscheme_id,a.code,
max(a.frequency)frequency, c.customer_id--, c.customernumber
from deliveryscheme a,customerdeliveryscheme b, customer c
where a.deliveryscheme_id = b.deliveryscheme_id
and b.customer_id = c.customer_id
GROUP by
--a.deliveryscheme_id,a.code, a.frequency,
 --b.day_id,
 c.customer_id--, c.customernumber
/

  CREATE OR REPLACE VIEW "V2" ("CUSTOMER_ID", "ROUTENUMBER", "ROUTEDESCRIPTION", "DRIVINGDAY_ID", "STOPNUMBER", "CODE", "DEPOTDESCRIPTION") AS 
  select c.customer_id, r.routenumber, r.description routedescription, r.drivingday_id,
rs.stopnumber, d.code, d.description depotdescription
 from  customer c, routestop rs, route r left outer join depot d on r.depot_id = d.depot_id and r.plant_id = d.plant_id
where rs.route_id = r.route_id
and rs.customer_id = c.customer_id
/

  CREATE OR REPLACE VIEW "VR_COMPLETENESSROUTE" ("LINETYPE", "REPORTPARAM_ID", "DEFAULTBUSINESSUNIT_ID", "BUSINESSUNIT_ID", "BU_CODE", "BU_DESC", "STAY", "IDCODE", "LANGUAGECODE", "PLANNEDDELIVERYDATE", "LASTINSCANDATE", "STATUS_ID", "PRODUCTCODE", "PRODUCTDESC", "ROUTENUMBER", "ROUTEDESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "CUSTOMERADDRES", "ROUTE_ID", "DAY_ID", "FLAG_NO", "MAXCOMPLETENESSDAYS", "INTERNALBU", "DRIVINGDATE") AS 
  select /*vr_completenessroute version 2.0  union split for packingnote*/
       1 linetype, rp.reportparam_id, cu.defaultbusinessunit_id,
       bu.businessunit_id, bu.code bu_code, bu.description bu_desc,
       case
         when s.staynr = 30 and (st.code = '20' or st.code = '30') then 1
         when s.staynr = 32 and (st.code = '20' or st.code = '30') then 2
         when s.staynr = 31 and (st.code = '20' or st.code = '30') then 3
         when (s.staynr between 33 and 99 and s.staynr <> 36) and (st.code = '20' or st.code = '30') then 4
         when s.staynr = 36 and (st.code = '20' or st.code = '30') then 5
         when s.staynr = 10 and st.code = '30' then 6
         when s.staynr = 10 and st.code = '20' then 6.1 -- lss/lst customization based on module lstcustom
       end "STAY",
       ui.primaryid idcode, lan.code languagecode,
       case
         when s.staynr = 36 then
          getabsmindate()
         else
          ui.planneddeliverydate
       end planneddeliverydate, ui.lastinscandate, ui.status_id, pr.code productcode,
       (select prd.description
           from product_desc prd
          where prd.product_id = pr.product_id
            and prd.language_id = lan.language_id) productdesc,
       ro.routenumber, ro.description routedesc, cu.customernumber,
       cu.name customername, dep.departmentnumber, dep.description departmentdesc,
       cast(concatenatewithblank3(ad.street, ad.zipcode, ad.city) as varchar2(255)) customeraddres,
       rc.route_id, ro.drivingday_id day_id, 0 flag_no,
       getdatediff(trunc(sysdate), ui.lastinscandate) maxcompletenessdays,
       coalesce((select ca.internalprocessingbu_id
                   from customeractivities ca, productgroup pg
                  where ca.customer_id = cu.customer_id
                    and pr.productgroup_id = pg.productgroup_id
                    and pg.activity_id = ca.activity_id
                    and ui.businessunit_id = ca.processbusinessunit_id), -1) internalbu, rc.drivingdate
  from uniqueitem ui
  join businessunit bu on ui.businessunit_id = bu.businessunit_id
  join product pr on ui.product_id = pr.product_id
  join stay s on ui.stay_id = s.stay_id
  join status st on ui.status_id = st.status_id
  join uniqueitemnonpool uinp on ui.uniqueitem_id = uinp.uniqueitem_id
  join weareremployment we on uinp.weareremployment_id = we.weareremployment_id
  left outer join flag f2 on we.flag_id = f2.flag_id
                         and f2.includeincompletnesscheck = 'N'
  join distributionpoint dp on we.distributionpoint_id = dp.distributionpoint_id
  join department dep on dp.department_id = dep.department_id
  join wearer w on we.wearer_id = w.wearer_id
  left outer join flag f1 on w.flag_id = f1.flag_id
                         and f1.includeincompletnesscheck = 'N'
  join customer cu on w.customer_id = cu.customer_id
  join address ad on cu.visitaddress_id = ad.address_id
  join stop on cu.customer_id = stop.customer_link_id
  join routecontrol rc on stop.routecontrol_id = rc.routecontrol_id
  join route ro on rc.route_id = ro.route_id,
  languages lan, reportparam rp
 where ui.poolitem = 2
   and s.staytype = 1
   and s.staynr not in (20, 22, 23, 24, 25)
   and st.statustype = 'UI'
   and (ui.planneddeliverydate <= rc.drivingdate or s.staynr = 36)
   and ro.active = 'Y'
   and (f1.flag_id is null or w.flagstartdate > rc.drivingdate)
   and (f2.flag_id is null or we.flagstartdate > rc.drivingdate)
   and not exists
       (select 1
          from uniqueitemflag uf, flag fl
         where uf.uniqueitem_id = ui.uniqueitem_id
           and uf.flag_id = fl.flag_id
           and fl.includeincompletnesscheck = 'N'
           and uf.startdate < rp.date_value1)
   and ((rp.number_value2 = 1 and s.staynr <> '37') or rp.number_value2 = 0)
   and (nvl(stop.deliverypoint_id, 0) = 0 or
       ((select locker.deliverypoint_id from locker where locker.locker_id = we.locker_id) = stop.deliverypoint_id) or
       we.deliverypoint_id = stop.deliverypoint_id)
   and stop.status in (0, 3)
   and ((exists (select 1
                   from customerdeliveryday cdd
                  where cdd.customer_id = cu.customer_id
                    and cdd.deliverytype <> 'P'
                    and cdd.typeofmerchadise = 2
                    and cdd.day_id = ro.drivingday_id
                    and rp.number_value4 = 0))
         or
        (exists (select 1
                    from routecontrol rc2, stop stop2
                   where stop2.customer_link_id = cu.customer_id
                     and stop2.routestop_id is not null
                     and stop2.stoptype = 3
                     and stop2.routecontrol_id = rc2.routecontrol_id
                     and rc2.drivingdate = rp.date_value1
                     and rp.number_value4 = 1)))
   and ro.routenumber >= rp.number_value8
   and ro.routenumber <= rp.number_value9
   and rp.date_value1 = rc.originaldrivingdate
union all
select 2 linetype, rp.reportparam_id, cu.defaultbusinessunit_id,
       bu.businessunit_id, bu.code bu_code, bu.description bu_desc,
       7 "STAY", ui.primaryid idcode, lan.code languagecode,
       getabsmindate() planneddeliverydate, ui.lastinscandate, ui.status_id, pr.code productcode,
       (select prd.description
           from product_desc prd
          where prd.product_id = pr.product_id
            and prd.language_id = lan.language_id) productdesc,
       ro.routenumber, ro.description routedesc, cu.customernumber,
       cu.name customername, dep.departmentnumber, dep.description departmentdesc,
       cast(concatenatewithblank3(ad.street, ad.zipcode, ad.city) as varchar2(255)) customeraddres,
       rc.route_id, ro.drivingday_id day_id, 0 flag_no,
       0 maxcompletenessdays, coalesce(ds.internalprocessingbu_id, -1) internalbu, rc.drivingdate
  from deliveryscan ds
  left outer join weareremployment we on ds.weareremployment_link_id = we.weareremployment_id
  join wearer w on we.wearer_id = w.wearer_id
  join distributionpoint dp on ds.distributionpoint_link_id = dp.distributionpoint_id
  join department dep on dp.department_id = dep.department_id
  join customer cu on ds.customer_link_id = cu.customer_id
  join address ad on cu.visitaddress_id = ad.address_id
  join routecontrol rc1 on ds.routecontrol_id = rc1.routecontrol_id
  join uniqueitem ui on ds.uniqueitem_link_id = ui.uniqueitem_id
  join businessunit bu on ui.businessunit_id = bu.businessunit_id
  join product pr on ui.product_id = pr.product_id
  join stay s on ui.stay_id = s.stay_id
  join status st on ui.status_id = st.status_id
  join stop on cu.customer_id = stop.customer_link_id
  join routecontrol rc on stop.routecontrol_id = rc.routecontrol_id
  join route ro on rc.route_id = ro.route_id,
  languages lan, reportparam rp
 where s.staytype = 1
   and s.staynr = 20
   and st.statustype = 'UI'
   and st.code in ('20', '30')
   and ro.active = 'Y'
   and ds.businessunit_id = ui.businessunit_id
   and ds.outscannodelivery in (0, 2)
   and rc1.drivingdate <= rc.drivingdate
   and stop.status in (0, 3)
   and (we.distributionpoint_id = dp.distributionpoint_id or (w.customer_id is null and ui.poolitem <> 2))
   and (w.customer_id = cu.customer_id or (w.customer_id is null and ui.poolitem <> 2))
   and (nvl(we.deliverypoint_id, ds.deliverypoint_link_id) = ds.deliverypoint_link_id or
       (w.customer_id is null and ui.poolitem <> 2 and dp.deliverypoint_id = ds.deliverypoint_link_id))
   and nvl(ds.packingnote_id, 0) in (select 0 from dual
                                     union all
                                     select pn.packingnote_id
                                        from packingnote pn, status st2
                                       where pn.routecontrol_id = rc.routecontrol_id
                                         and pn.status_id = st2.status_id
                                         and st2.statustype = 'PN'
                                         and st2.code = '20')
   and (nvl(stop.deliverypoint_id, 0) = 0 or ((select locker.deliverypoint_id from locker where locker.locker_id = we.locker_id) = stop.deliverypoint_id) or
       we.deliverypoint_id = stop.deliverypoint_id or (w.customer_id is null and ui.poolitem <> 2 and stop.deliverypoint_id = ds.deliverypoint_link_id))
   and ((exists (select 1
                   from customerdeliveryday cdd
                  where cdd.customer_id = cu.customer_id
                    and cdd.deliverytype <> 'P'
                    and cdd.typeofmerchadise = 2
                    and cdd.day_id = ro.drivingday_id
                    and rp.number_value4 = 0))
         or
        (exists (select 1
                    from routecontrol rc2, stop stop2
                   where stop2.customer_link_id = cu.customer_id
                     and stop2.routestop_id is not null
                     and stop2.stoptype = 3
                     and stop2.routecontrol_id = rc2.routecontrol_id
                     and rc2.drivingdate = rp.date_value1
                     and rp.number_value4 = 1)))
   and ro.routenumber >= rp.number_value8
   and ro.routenumber <= rp.number_value9
   and rp.date_value1 = rc.drivingdate
   and ((rp.number_value5 > 0 and rp.number_value5 = ds.plantdepartment_id) or
       (rp.number_value6 > 0 and rp.number_value6 = (select pd.plant_id from plantdepartment pd where pd.plantdepartment_id = ds.plantdepartment_id)) or
       (rp.number_value7 > 0 and rp.number_value7 <> (select pd.plant_id from plantdepartment pd where pd.plantdepartment_id = ds.plantdepartment_id)) or
       (rp.number_value5 = -1 and rp.number_value6 = -1 and rp.number_value7 = -1))
/

  CREATE OR REPLACE VIEW "VR_COMPLETENESSROUTEDETAILS" ("LINETYPE", "REPORTPARAM_ID", "DEFAULTBUSINESSUNIT_ID", "BUSINESSUNIT_ID", "BU_CODE", "BU_DESC", "STAY", "IDCODE", "UNIQUEITEM_ID", "LANGUAGECODE", "PLANNEDDELIVERYDATE", "LASTINSCAN_DATE", "LASTSCAN_DATE", "LASTINSCANDATE", "LASTSCANDATE", "STATUS_ID", "PRODUCTCODE", "PRODUCTDESC", "ROUTENUMBER", "ROUTEDESC", "FINISHINGMETHODDESC", "SIZEDEFINITIONCODE", "FLAG", "FLAG_NO", "WEARERNUMBER", "WEARERNAME", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "CUSTOMERADDRES", "CUSTOMERADDRES2", "ROUTE_ID", "DAY_ID", "MAXCOMPLETENESSDAYS", "INTERNALBU", "DRIVINGDATE", "COMPCHECKNONUNIQUE", "NONUNIQUEQTY", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINT_DESC", "BANKLOCKER", "NODELIVERYOFREJECTS_VALUE", "DV_ORIGIN", "DV_SOILCOUNTSUBTYPE") AS 
  select /*vr_completenessroutedetails version 2.0,extra union split for packingnote*/
--unique items inscans
 1 linetype, rp.reportparam_id, cu.defaultbusinessunit_id,
 bu.businessunit_id businessunit_id, bu.code bu_code, bu.description bu_desc,
 case
   when s.staynr = 30 and (st.code = '20' or st.code = '30') then 1
   when s.staynr = 32 and (st.code = '20' or st.code = '30') then 2
   when s.staynr = 31 and (st.code = '20' or st.code = '30') then 3
   when (s.staynr between 30 and 99 and s.staynr <> 36) and (st.code = '20' or st.code = '30') then 4
   when s.staynr = 36 and (st.code = '20' or st.code = '30') then 5
   when s.staynr = 10 and st.code = '30' then 6
   when s.staynr = 10 and st.code = '20' then 6.1 -- lss/lst customization based on module lstcustom
 end "STAY",
 ui.primaryid idcode, ui.uniqueitem_id, lan.code languagecode,
 case
   when s.staynr = 36 then
    getabsmindate()
   else
    ui.planneddeliverydate
 end planneddeliverydate, ui.lastinscandate lastinscan_date, ui.lastscandate lastscan_date,
 to_char(ui.lastinscandate, 'MM/DD/YYYY HH:MI:SS AM') lastinscandate,
 to_char(ui.lastscandate, 'MM/DD/YYYY HH:MI:SS AM') lastscandate,
 ui.status_id, pr.code productcode,
 (select prd.description
     from product_desc prd
    where prd.product_id = pr.product_id
      and prd.language_id = lan.language_id) productdesc,
 ro.routenumber, ro.description routedesc,
 (select fmd.description
     from finishingmethod_desc fmd
    where fmd.finishingmethod_id = ui.finishingmethod_id
      and fmd.language_id = lan.language_id) finishingmethoddesc, sd.code sizedefinitioncode,
 coalesce((select max(fl.flag_id)
             from uniqueitemflag z, flag fl
            where z.uniqueitem_id = ui.uniqueitem_id
              and z.flag_id = fl.flag_id
              and fl.includeincompletnesscheck = 'Y'), 0) flag,
 0 flag_no, w.wearernumber, w.fullname wearername, cu.customernumber, cu.name customername,
 dep.departmentnumber, dep.description departmentdesc, ad.street customeraddres,
 cast(concatenatewithblank(ad.zipcode, ad.city) as varchar2(255)) customeraddres2, ro.route_id, ro.drivingday_id day_id,
 getdatediff(trunc(sysdate), ui.lastinscandate) maxcompletenessdays,
 coalesce((select ca.internalprocessingbu_id
             from customeractivities ca, productgroup pg
            where ca.customer_id = cu.customer_id
              and pr.productgroup_id = pg.productgroup_id
              and pg.activity_id = ca.activity_id
              and ui.businessunit_id = ca.processbusinessunit_id), -1) internalbu, rc.drivingdate,
 (select cast(sst.value as varchar2(1))
     from systemsetting sst
    where sst.plant_id = bu.plant_id
      and sst.name = 'COMPCHECKNONUNIQUE') compchecknonunique,
 1 nonuniqueqty, dp.distributionpointnumber, dp.description distributionpoint_desc,
 (select concat(concat(lc.bank, '/'), lc.locker) from locker lc where lc.locker_id = we.locker_id) banklocker,
 To_Number((select sstt.value from systemsetting sstt where sstt.plant_id = bu.plant_id and sstt.name = 'NODELIVERYOFREJECTS')) nodeliveryofrejects_value,
 0 dv_origin, 0 dv_soilcountsubtype
  from uniqueitem ui
  join businessunit bu on ui.businessunit_id = bu.businessunit_id
  join product pr on ui.product_id = pr.product_id
  join sizedefinition sd on ui.sizedefinition_id = sd.sizedefinition_id
  join stay s on ui.stay_id = s.stay_id
  join status st on ui.status_id = st.status_id
  join uniqueitemnonpool uinp on ui.uniqueitem_id = uinp.uniqueitem_id
  join weareremployment we on uinp.weareremployment_id = we.weareremployment_id
  left outer join flag f2 on we.flag_id = f2.flag_id
                         and f2.includeincompletnesscheck = 'N'
  join distributionpoint dp on we.distributionpoint_id = dp.distributionpoint_id
  join department dep on dp.department_id = dep.department_id
  join wearer w on we.wearer_id = w.wearer_id
  left outer join flag f1 on w.flag_id = f1.flag_id
                         and f1.includeincompletnesscheck = 'N'
  join customer cu on w.customer_id = cu.customer_id
  join address ad on cu.visitaddress_id = ad.address_id
  join stop on cu.customer_id = stop.customer_link_id
  join routecontrol rc on stop.routecontrol_id = rc.routecontrol_id
  join route ro on rc.route_id = ro.route_id,
  languages lan, reportparam rp
 where ui.poolitem = 2
   and s.staytype = 1
   and s.staynr not in (20, 22, 23, 24, 25)
   and st.statustype = 'UI'
   and (ui.planneddeliverydate <= rc.drivingdate or s.staynr = 36)
   and ro.active = 'Y'
   and (f1.flag_id is null or w.flagstartdate > rc.drivingdate)
   and (f2.flag_id is null or we.flagstartdate > rc.drivingdate)
   and not exists
       (select 1
          from uniqueitemflag uf, flag fl
         where uf.uniqueitem_id = ui.uniqueitem_id
           and uf.flag_id = fl.flag_id
           and fl.includeincompletnesscheck = 'N'
           and uf.startdate < rp.date_value1)
   and ((rp.number_value2 = 1 and s.staynr <> '37') or rp.number_value2 = 0)
   and (nvl(stop.deliverypoint_id, 0) = 0 or ((select locker.deliverypoint_id from locker where locker.locker_id = we.locker_id) = stop.deliverypoint_id) or
       we.deliverypoint_id = stop.deliverypoint_id)
   and stop.status in (0, 3)
   and ((exists (select 1
                   from customerdeliveryday cdd
                  where cdd.customer_id = cu.customer_id
                    and cdd.deliverytype <> 'P'
                    and cdd.typeofmerchadise = 2
                    and cdd.day_id = ro.drivingday_id
                    and rp.number_value4 = 0))
         or
        (exists (select 1
                   from routecontrol rc2, stop stop2
                  where stop2.customer_link_id = cu.customer_id
                    and stop2.routestop_id is not null
                    and stop2.stoptype = 3
                    and stop2.routecontrol_id = rc2.routecontrol_id
                    and rc2.drivingdate = rp.date_value1
                    and rp.number_value4 = 1)))
   and ro.routenumber >= rp.number_value8
   and ro.routenumber <= rp.number_value9
   and rp.date_value1 = rc.originaldrivingdate
union all --unique items outscans
select 2 linetype, rp.reportparam_id, cu.defaultbusinessunit_id,
       bu.businessunit_id, bu.code bu_code, bu.description bu_desc,
       7 "STAY", ui.primaryid idcode,
       ui.uniqueitem_id, lan.code languagecode, getabsmindate() planneddeliverydate,
       ui.lastinscandate lastinscan_date, ui.lastscandate lastscan_date,
       to_char(ui.lastinscandate, 'MM/DD/YYYY HH:MI:SS AM') lastinscandate,
       to_char(ui.lastscandate, 'MM/DD/YYYY HH:MI:SS AM') lastscandate,
       ui.status_id, pr.code productcode,
       (select prd.description
           from product_desc prd
          where prd.product_id = pr.product_id
            and prd.language_id = lan.language_id) productdesc,
       ro.routenumber, ro.description routedesc,
       (select fmd.description
           from finishingmethod_desc fmd
          where fmd.finishingmethod_id = ui.finishingmethod_id
            and fmd.language_id = lan.language_id) finishingmethoddesc, sd.code sizedefinitioncode,
       coalesce((select max(fl.flag_id)
                   from uniqueitemflag z, flag fl
                  where z.uniqueitem_id = ui.uniqueitem_id
                    and z.flag_id = fl.flag_id
                    and fl.includeincompletnesscheck = 'Y'), 0) flag,
       0 flag_no, w.wearernumber, w.fullname wearername, cu.customernumber,
       cu.name customername, dep.departmentnumber, dep.description departmentdesc, ad.street customeraddres,
       cast(concatenatewithblank(ad.zipcode, ad.city) as varchar2(255)) customeraddres2,
       ro.route_id, ro.drivingday_id day_id, 0 maxcompletenessdays,
       coalesce(ds.internalprocessingbu_id, -1) internalbu, rc.drivingdate,
       (select cast(sst.value as varchar2(1))
           from systemsetting sst
          where sst.plant_id = bu.plant_id
            and sst.name = 'COMPCHECKNONUNIQUE') compchecknonunique,
       1 nonuniqueqty, dp.distributionpointnumber, dp.description distributionpoint_desc,
       (select concat(concat(lc.bank, '/'), lc.locker) from locker lc where lc.locker_id = we.locker_id) banklocker,
       To_Number((select sstt.value from systemsetting sstt where sstt.plant_id = bu.plant_id and sstt.name = 'NODELIVERYOFREJECTS')) nodeliveryofrejects_value,
       0 dv_origin, 0 dv_soilcountsubtype
  from deliveryscan ds
  left outer join weareremployment we on ds.weareremployment_link_id = we.weareremployment_id
  join wearer w on we.wearer_id = w.wearer_id
  join distributionpoint dp on ds.distributionpoint_link_id = dp.distributionpoint_id
  join department dep on dp.department_id = dep.department_id
  join customer cu on ds.customer_link_id = cu.customer_id
  join address ad on cu.visitaddress_id = ad.address_id
  join routecontrol rc1 on ds.routecontrol_id = rc1.routecontrol_id
  join uniqueitem ui on ds.uniqueitem_link_id = ui.uniqueitem_id
  join businessunit bu on ui.businessunit_id = bu.businessunit_id
  join product pr on ui.product_id = pr.product_id
  join sizedefinition sd on ui.sizedefinition_id = sd.sizedefinition_id
  join stay s on ui.stay_id = s.stay_id
  join status st on ui.status_id = st.status_id
  join stop on cu.customer_id = stop.customer_link_id
  join routecontrol rc on stop.routecontrol_id = rc.routecontrol_id
  join route ro on rc.route_id = ro.route_id, languages lan, reportparam rp
 where s.staytype = 1
   and s.staynr = 20
   and st.statustype = 'UI'
   and st.code in ('20', '30')
   and ro.active = 'Y'
   and ds.businessunit_id = ui.businessunit_id
   and ds.outscannodelivery in (0, 2)
   and rc1.drivingdate <= rc.drivingdate
   and stop.status in (0, 3)
   and (we.distributionpoint_id = dp.distributionpoint_id or (w.customer_id is null and ui.poolitem <> 2))
   and (w.customer_id = cu.customer_id or (w.customer_id is null and ui.poolitem <> 2))
   and (nvl(we.deliverypoint_id, ds.deliverypoint_link_id) = ds.deliverypoint_link_id or
       (w.customer_id is null and ui.poolitem <> 2 and dp.deliverypoint_id = ds.deliverypoint_link_id))
   and nvl(ds.packingnote_id, 0) in (select 0
                                       from dual
                                     union all
                                     select pn.packingnote_id
                                       from packingnote pn, status st2
                                      where pn.routecontrol_id = rc.routecontrol_id
                                        and pn.status_id = st2.status_id
                                        and st2.statustype = 'PN'
                                        and st2.code = '20')
   and (nvl(stop.deliverypoint_id, 0) = 0 or ((select locker.deliverypoint_id from locker where locker.locker_id = we.locker_id) = stop.deliverypoint_id) or
       we.deliverypoint_id = stop.deliverypoint_id or (w.customer_id is null and ui.poolitem <> 2 and stop.deliverypoint_id = ds.deliverypoint_link_id))
   and ((exists (select 1
                   from customerdeliveryday cdd
                  where cdd.customer_id = cu.customer_id
                    and cdd.deliverytype <> 'P'
                    and cdd.typeofmerchadise = 2
                    and cdd.day_id = ro.drivingday_id
                    and rp.number_value4 = 0))
         or
        (exists (select 1
                   from routecontrol rc2, stop stop2
                  where stop2.customer_link_id = cu.customer_id
                    and stop2.routestop_id is not null
                    and stop2.stoptype = 3
                    and stop2.routecontrol_id = rc2.routecontrol_id
                    and rc2.drivingdate = rp.date_value1
                    and rp.number_value4 = 1)))
   and ro.routenumber >= rp.number_value8
   and ro.routenumber <= rp.number_value9
   and rp.date_value1 = rc.drivingdate
   and ((rp.number_value5 > 0 and rp.number_value5 = ds.plantdepartment_id) or
       (rp.number_value6 > 0 and rp.number_value6 = (select pd.plant_id from plantdepartment pd where pd.plantdepartment_id = ds.plantdepartment_id)) or
       (rp.number_value7 > 0 and rp.number_value7 <> (select pd.plant_id from plantdepartment pd where pd.plantdepartment_id = ds.plantdepartment_id)) or
       (rp.number_value5 = -1 and rp.number_value6 = -1 and rp.number_value7 = -1))
union all --nonunique items in scans
select 3 linetype, rp.reportparam_id, cu.defaultbusinessunit_id,
       bu.businessunit_id, bu.code bu_code, bu.description bu_desc,
       1 "STAY", '' idcode, 0 uniqueitem_id, lan.code languagecode,
       dv.deliverydate planneddeliverydate, null lastinscan_date, dv.deliverydate lastscan_date,
       to_char(dv.deliverydate, 'MM/DD/YYYY HH:MI:SS AM') lastinscandate,
       to_char(dv.deliverydate, 'MM/DD/YYYY HH:MI:SS AM') lastscandate,
       -1 status_id, pr.code productcode,
       (select prd.description
           from product_desc prd
          where prd.product_id = pr.product_id
            and prd.language_id = lan.language_id) productdesc,
       ro.routenumber, ro.description routedesc,
       (select fmd.description
           from finishingmethod_desc fmd
          where fmd.finishingmethod_id = dv.finishingmethod_id
            and fmd.language_id = lan.language_id) finishingmethoddesc,
       sd.code sizedefinitioncode, 0 flag, 0 flag_no, -1 wearernumber, '' wearername,
       cu.customernumber, cu.name customername, dep.departmentnumber, dep.description departmentdesc,
       ad.street customeraddres, cast(concatenatewithblank(ad.zipcode, ad.city) as varchar2(255)) customeraddres2,
       ro.route_id, ro.drivingday_id day_id, 0 maxcompletenessdays,
       coalesce(ca.internalprocessingbu_id, -1) internalbu, rc.drivingdate,
       cast(sst.value as varchar2(1)) compchecknonunique, dv.amount nonuniqueqty,
       dp.distributionpointnumber, dp.description distributionpoint_desc, null banklocker,
       To_Number((select sstt.value from systemsetting sstt where sstt.plant_id = bu.plant_id and sstt.name = 'NODELIVERYOFREJECTS')) nodeliveryofrejects_value,
       dv.origin dv_origin, dv.soilcountsubtype dv_soilcountsubtype
  from deliveryvariations dv
  join distributionpoint dp on dv.distributionpoint_id = dp.distributionpoint_id
  join department dep on dp.department_id = dep.department_id
  join customer cu on dep.customer_id = cu.customer_id
  join address ad on cu.visitaddress_id = ad.address_id
  join sizedefinition sd on dv.sizedefinition_id = sd.sizedefinition_id
  join product pr on dv.product_id = pr.product_id
  join productgroup pg on pr.productgroup_id = pg.productgroup_id
  join customeractivities ca on pg.activity_id = ca.activity_id
                            and cu.customer_id = ca.customer_id
  join businessunit bu on ca.processbusinessunit_id = bu.businessunit_id
  join systemsetting sst on sst.plant_id = bu.plant_id
                        and sst.name = 'COMPCHECKNONUNIQUE'
  join stop on cu.customer_id = stop.customer_link_id
  join routecontrol rc on stop.routecontrol_id = rc.routecontrol_id
  join route ro on rc.route_id = ro.route_id, languages lan, reportparam rp
 where ro.active = 'Y'
   and stop.status in (0, 3)
   and ((exists (select 1
                   from customerdeliveryday cdd
                  where cdd.customer_id = cu.customer_id
                    and cdd.deliverytype <> 'P'
                    and cdd.typeofmerchadise = 2
                    and cdd.day_id = ro.drivingday_id
                    and rp.number_value4 = 0))
         or
        (exists (select 1
                   from routecontrol rc2, stop stop2
                  where stop2.customer_link_id = cu.customer_id
                    and stop2.routestop_id is not null
                    and stop2.stoptype = 3
                    and stop2.routecontrol_id = rc2.routecontrol_id
                    and rc2.drivingdate = rp.date_value1
                    and rp.number_value4 = 1)))
   and ro.routenumber >= rp.number_value8
   and ro.routenumber <= rp.number_value9
   and rp.date_value1 = rc.originaldrivingdate
   and coalesce(dv.packingnote_id, 0) in (select 0
                                            from dual
                                          union all
                                          select pn.packingnote_id
                                            from packingnote pn, status stat
                                           where pn.status_id = stat.status_id
                                             and stat.statustype = 'PN'
                                             and stat.code = '20'
                                             and pn.deliverydate <= rp.date_value1
                                             and pn.routecontrol_id = rc.routecontrol_id
                                             and pn.stop_id = stop.stop_id
                                             and pn.route_id = ro.route_id)
   and dv.origin in (1, 5) --soil count & delivery note
   and dv.deliverydate <= rp.date_value1
   and sst.value = '0'
   and dv.amount > 0
union all --non unique items outscans
select 4 linetype, rp.reportparam_id, cu.defaultbusinessunit_id,
       bu.businessunit_id, bu.code bu_code, bu.description bu_desc,
       7 "STAY", '' idcode,0 uniqueitem_id, lan.code languagecode,
       ccd.deliverydate planneddeliverydate, null lastinscan_date, ccd.deliverydate lastscan_date,
       to_char(ccd.deliverydate, 'MM/DD/YYYY HH:MI:SS AM') lastinscandate,
       to_char(ccd.deliverydate, 'MM/DD/YYYY HH:MI:SS AM') lastscandate,
       -1 status_id, pr.code productcode,
       (select prd.description
           from product_desc prd
          where prd.product_id = pr.product_id
            and prd.language_id = lan.language_id) productdesc,
       ro.routenumber, ro.description routedesc,
       (select fmd.description
           from finishingmethod_desc fmd
          where fmd.finishingmethod_id = ccd.finishingmethod_id
            and fmd.language_id = lan.language_id) finishingmethoddesc,
       sd.code sizedefinitioncode, 0 flag, 0 flag_no, -1 wearernumber, '' wearername,
       cu.customernumber, cu.name customername, dep.departmentnumber, dep.description departmentdesc,
       ad.street customeraddres, cast(concatenatewithblank(ad.zipcode, ad.city) as varchar2(255)) customeraddres2,
       ro.route_id, ro.drivingday_id day_id, 0 maxcompletenessdays,
       coalesce(ca.internalprocessingbu_id, -1) internalbu, rc.drivingdate,
       cast(sst.value as varchar2(1)) compchecknonunique, (ccd.quantity + ccd.quantitycog) nonuniqueqty,
       dp.distributionpointnumber, dp.description distributionpoint_desc, null banklocker,
       To_Number((select sstt.value from systemsetting sstt where sstt.plant_id = bu.plant_id and sstt.name = 'NODELIVERYOFREJECTS')) nodeliveryofrejects_value,
       0 dv_origin, 0 dv_soilcountsubtype
  from cleancountdelivery ccd
  join distributionpoint dp on ccd.distributionpoint_id = dp.distributionpoint_id
  join department dep on dp.department_id = dep.department_id
  join customer cu on dep.customer_id = cu.customer_id
  join address ad on cu.visitaddress_id = ad.address_id
  join sizedefinition sd on ccd.sizedefinition_id = sd.sizedefinition_id
  join product pr on ccd.product_id = pr.product_id
  join productgroup pg on pr.productgroup_id = pg.productgroup_id
  join customeractivities ca on pg.activity_id = ca.activity_id
                            and cu.customer_id = ca.customer_id
  join businessunit bu on ca.processbusinessunit_id = bu.businessunit_id
  join systemsetting sst on sst.plant_id = bu.plant_id
                        and sst.name = 'COMPCHECKNONUNIQUE'
  join stop on cu.customer_id = stop.customer_link_id
  join routecontrol rc on stop.routecontrol_id = rc.routecontrol_id
  join route ro on rc.route_id = ro.route_id, languages lan, reportparam rp
 where ro.active = 'Y'
   and stop.status in (0, 3)
   and ((exists (select 1
                   from customerdeliveryday cdd
                  where cdd.customer_id = cu.customer_id
                    and cdd.deliverytype <> 'P'
                    and cdd.typeofmerchadise = 2
                    and cdd.day_id = ro.drivingday_id
                    and rp.number_value4 = 0))
         or
        (exists (select 1
                   from routecontrol rc2, stop stop2
                  where stop2.customer_link_id = cu.customer_id
                    and stop2.routestop_id is not null
                    and stop2.stoptype = 3
                    and stop2.routecontrol_id = rc2.routecontrol_id
                    and rc2.drivingdate = rp.date_value1
                    and rp.number_value4 = 1)))
   and ro.routenumber >= rp.number_value8
   and ro.routenumber <= rp.number_value9
   and rc.drivingdate <= rp.date_value1
   and coalesce(ccd.packingnote_id, 0) in (select 0
                                             from dual
                                           union all
                                           select pn.packingnote_id
                                             from packingnote pn, status stat
                                            where pn.status_id = stat.status_id
                                              and stat.statustype = 'PN'
                                              and stat.code = '20'
                                              and pn.deliverydate <= rp.date_value1
                                              and pn.routecontrol_id = rc.routecontrol_id
                                              and pn.stop_id = stop.stop_id
                                              and pn.route_id = ro.route_id)
   and sst.value = '0'
/

  CREATE OR REPLACE VIEW "VR_COMPLETENESSWEARERDETAILS" ("STAY", "IDCODE", "LANGUAGECODE", "LASTSCANDATE", "PRODUCTCODE", "PRODUCTDESC", "FINISHINGMETHODCODE", "FINISHINGMETHODDESC", "SIZEDEFINITIONCODE", "FLAG", "WEARERNUMBER", "WEARERNAME", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "CUSTOMERADDRES", "CUSTOMERADDRES2", "REPORTPARAM_ID") AS 
  select CASE
   WHEN s.staynr = 30 and (st.code = '20' or st.code = '30') THEN 1 --Inscan
   WHEN s.staynr = 32 and (st.code = '20' or st.code = '30') THEN 2 --Repair
   WHEN s.staynr = 31 and (st.code = '20' or st.code = '30') THEN 3 --Rewash
   WHEN(s.staynr between 33 and 99 and s.staynr <> 36) and (st.code = '20' or st.code = '30') THEN 4 --Others
   WHEN s.staynr = 36 and (st.code = '20' or st.code = '30') THEN 5 --Late
   WHEN s.staynr = 10 and st.code = '30' THEN 6 --Stock
   when s.staynr = 20 and (st.code = '20' or st.code = '30') and
              exists (select ds.uniqueitem_link_id
                 from deliveryscan ds
                where ds.packingnote_id is null
                  and ds.uniqueitem_link_id = ui.uniqueitem_id
                  and ds.businessunit_id = ui.businessunit_id) then 7 --Outscan
   when s.staynr = 20 and (st.code = '20' or st.code = '30') and
              exists (select ds.uniqueitem_link_id
                 from deliveryscan ds
                where ds.packingnote_id is not null
                  and ds.uniqueitem_link_id = ui.uniqueitem_id
                  and ds.businessunit_id = ui.businessunit_id) then 8 --Outscan/At Customer
END "STAY",
 ui.primaryid idcode, lan.code languagecode,
 to_char(ui.lastscandate, 'MM/DD/YYYY HH:MI:SS AM') lastscandate,
 pr.code productcode,
 (SELECT pd.description FROM product_DESC pd WHERE pd.product_id = pr.product_id
  AND pd.LANGUAGE_ID = lan.LANGUAGE_ID) productdesc,
 (SELECT x.code FROM finishingmethod x WHERE x.finishingmethod_id = ui.finishingmethod_id) finishingmethodcode,
 (SELECT y.description FROM finishingmethod_DESC y WHERE y.finishingmethod_id = ui.finishingmethod_id
  AND y.LANGUAGE_ID = lan.LANGUAGE_ID) finishingmethoddesc,
 sd.code sizedefinitioncode,
 (SELECT COUNT(*) FROM UNIQUEITEMFLAG Z, flag fl WHERE Z.UNIQUEITEM_ID = ui.UNIQUEITEM_ID
   and z.flag_id = fl.flag_id
   and fl.includeincompletnesscheck = 'Y') FLAG,
 w.wearernumber, w.fullname wearername,
 c.customernumber, c.name customername, de.departmentnumber, de.description departmentdesc,
 a.street customeraddres
, cast(CONCATENATEWITHBLANK(a.zipcode, a.city) as varchar2(255)) customeraddres2
, rp.reportparam_id
from uniqueitem ui, status st, stay s, uniqueitemnonpool np, weareremployment we, distributionpoint dp,
department de, product pr, wearer w, customer c, address a, languages lan, sizedefinition sd, reportparam rp
where ui.primaryid = rp.string_value
 and ui.stay_id = s.stay_id
 and ui.uniqueitem_id = np.uniqueitem_id
 and np.weareremployment_id = we.weareremployment_id
 and we.distributionpoint_id = dp.distributionpoint_id
 and dp.department_id = de.department_id
 and ui.status_id = st.status_id --and st.statustype = 'UI'
 and ui.product_id = pr.product_id
 and c.visitaddress_id = a.address_id
 and ui.sizedefinition_id = sd.sizedefinition_id
 and we.wearer_id = w.wearer_id
 and w.customer_id = c.customer_id
/

  CREATE OR REPLACE VIEW "VR_DECREASENUMBERINCIRC" ("SQHEADER_ID", "CUST_ID", "WEAREREMPL_ID", "ADDITIONS", "DELETIONS") AS 
  select sha.statusquoheader_id,
       sa.customer_link_id cust_id,
       sa.weareremployment_link_id wearerempl_id,
       sum(case
             when sa.variationtotalcircinv > 0 then
              sa.variationtotalcircinv
             else
              0
           end) addit,
       sum(case
             when sa.variationtotalcircinv < 0 then
              - sa.variationtotalcircinv
             else
              0
           end) del
  from sqitemincirculation sa, statusquoheader sha
 where sa.statusquoheader_id = sha.statusquoheader_id
 group by sha.statusquoheader_id,
          sa.customer_link_id,
          sa.weareremployment_link_id
/

  CREATE OR REPLACE VIEW "VR_NOTES" ("NOTENUMBER", "NOTEDATE", "ORIGIN", "INVOICEHEADER_ID", "REMARK", "SHOWONINVOICEAPPENDIX", "TYPE") AS 
  select /*version 1.0*/
       distinct x.notenumber, x.deliverydate notedate, x.origin,
       x.invoiceheader_id, x.remark, x.showoninvoiceappendix, x.type
  from (select distinct cast(leftpad(pn.notenumber, 22, ' ') as varchar2(255)) notenumber,
               pn.deliverydate, pn.origin, pnl.invoiceheader_id, pn.remark, pn.showoninvoiceappendix,
               case when pn.origin in (0, 1, 2) then 1
                    when pn.origin = 6 then 2
               else pn.origin end type
          from packingnoteline pnl
               join packingnote pn on pnl.packingnote_id = pn.packingnote_id
         where pn.origin in (0, 1, 2, 3, 6) and pn.freeofchargereason_id is null
         union all
        select distinct cast(leftpad(pn.notenumber, 22, ' ') as varchar2(255)) notenumber,
               pn.deliverydate, pn.origin, pnc.invoiceheader_id, pn.remark, pn.showoninvoiceappendix,
               case when pn.origin in (0, 1, 2) then 1
                    when pn.origin = 6 then 2
               else pn.origin end type
          from packingnotecontainer pnc
               join packingnote pn on pnc.packingnote_id = pn.packingnote_id
         where pn.freeofchargereason_id is null
         union all
        select distinct cast(leftpad(wt.ticketnumber, 22, ' ') as varchar2(255)) notenumber,
               wt.weighingdate deliverydate, wt.origin, wtl.invoiceheader_id,
               wt.remark, 'Y' showoninvoiceappendix,
               case when wt.origin = 1 and wt.soilticket = 'Y' then 5
                    when wt.origin = 1 and wt.soilticket = 'N' then 6
                    when wt.origin = 2 and wt.soilticket = 'Y' then 7
                    when wt.origin = 2 and wt.soilticket = 'N' then 8
               else 9 end type
          from weighingticketline wtl
               join weighingticket wt on wtl.weighingticket_id = wt.weighingticket_id
         where wt.origin in (1, 2)) x
/

  CREATE OR REPLACE VIEW "VR_NOTES_OMD" ("NOTENUMBER", "NOTEDATE", "ORIGIN", "TYPE", "INVOICEHEADER_ID", "REMARK", "SHOWONINVOICEAPPENDIX", "PODNUMBER") AS 
  select distinct "NOTENUMBER","DELIVERYDATE","ORIGIN","TYPE","INVOICEHEADER_ID","REMARK","SHOWONINVOICEAPPENDIX","EXTERNALID" from
(
select distinct
cast(/*LEFTPAD(*/b.notenumber/*,22,' ')*/ as varchar2(255)) notenumber,b.deliverydate, b.origin,1 type, l.INVOICEHEADER_ID, CAST(b.remark AS VARCHAR2(255))REMARK
, b.showoninvoiceappendix, cast(/*LEFTPAD(*/pd.externalid/*,22,' ')*/ as varchar2(255)) externalid
from packingnote b, packingnoteline l,packingnotepod pd
where b.packingnote_id = l.packingnote_id and b.origin in (0,1,2) and b.freeofchargereason_id is null and b.packingnote_id=pd.packingnote_id
union all
select distinct
cast(/*LEFTPAD(*/b.notenumber/*,22,' ')*/ as varchar2(255)) notenumber,b.deliverydate, b.origin,2 type, l.INVOICEHEADER_ID,CAST(b.remark AS VARCHAR2(255))REMARK
, b.showoninvoiceappendix, cast(/*LEFTPAD(*/pd.externalid/*,22,' ')*/ as varchar2(255)) externalid
from packingnote b, packingnoteline l,packingnotepod pd
where b.packingnote_id = l.packingnote_id and b.origin = 6 and b.freeofchargereason_id is null and b.packingnote_id=pd.packingnote_id
union all
select distinct
cast(/*LEFTPAD(*/b.notenumber/*,22,' ')*/ as varchar2(255)) notenumber,b.deliverydate, b.origin, 3 type, l.INVOICEHEADER_ID, CAST(b.remark AS VARCHAR2(255))REMARK
, b.showoninvoiceappendix, cast(/*LEFTPAD(*/pd.externalid/*,22,' ')*/ as varchar2(255)) externalid
from packingnote b, packingnoteline l,packingnotepod pd
where b.packingnote_id = l.packingnote_id and b.origin = 3 and b.freeofchargereason_id is null and b.packingnote_id=pd.packingnote_id
union all
select distinct
cast(/*LEFTPAD(*/b.notenumber/*,22,' ')*/ as varchar2(255)) notenumber,b.deliverydate, b.origin
, case when b.origin in (0,1,2) then 1
  when b.origin = 6 then 2
  else b.origin end type
, l.INVOICEHEADER_ID, b.remark
, b.showoninvoiceappendix, cast(/*LEFTPAD(*/pd.externalid/*,22,' ')*/ as varchar2(255)) externalid
from packingnote b, packingnotecontainer l,packingnotepod pd
where b.packingnote_id = l.packingnote_id  and b.freeofchargereason_id is null and b.packingnote_id=pd.packingnote_id
union all
select distinct
cast(/*LEFTPAD(*/b.notenumber/*,22,' ')*/ as varchar2(255)) notenumber,b.deliverydate, b.origin, 4 type , l.INVOICEHEADER_ID,CAST(b.remark AS VARCHAR2(255))REMARK
, b.showoninvoiceappendix, cast(/*LEFTPAD(*/pd.externalid/*,22,' ')*/ as varchar2(255)) externalid
from packingnote b, packingnoteline l,packingnotepod pd
where b.packingnote_id = l.packingnote_id and b.origin = 4 and b.freeofchargereason_id is null and b.packingnote_id=pd.packingnote_id
union all
select distinct
cast(/*LEFTPAD(*/c.ticketnumber/*,22,' ')*/ as varchar2(255)) notenumber,c.weighingdate, c.origin, 5 type, t.INVOICEHEADER_ID, CAST(C.remark AS VARCHAR2(255))REMARK
, 'Y','' externalid
from weighingticket c, weighingticketline t
where c.weighingticket_id = t.weighingticket_id and origin = 1
and soilticket ='Y'
union all
select distinct
cast(/*LEFTPAD(*/c.ticketnumber/*,22,' ')*/ as varchar2(255)) notenumber,c.weighingdate, c.origin, 6 type, t.INVOICEHEADER_ID, CAST(C.remark AS VARCHAR2(255))REMARK
, 'Y','' externalid
from weighingticket c, weighingticketline t
where c.weighingticket_id = t.weighingticket_id and origin = 1
and soilticket ='N'
union all
select distinct
cast(/*LEFTPAD(*/c.ticketnumber/*,22,' ')*/ as varchar2(255)) notenumber,c.weighingdate, c.origin, 7 type, t.INVOICEHEADER_ID, CAST(C.remark AS VARCHAR2(255))REMARK
, 'Y','' externalid
from weighingticket c, weighingticketline t
where c.weighingticket_id = t.weighingticket_id and origin = 2
and soilticket ='Y'
union all
select distinct
cast(LEFTPAD(c.ticketnumber,22,' ') as varchar2(255)) notenumber,c.weighingdate, c.origin, 8 type, t.INVOICEHEADER_ID, CAST(C.remark AS VARCHAR2(255))REMARK
, 'Y','' externalid
from weighingticket c, weighingticketline t
where c.weighingticket_id = t.weighingticket_id and origin = 2
and soilticket ='N')
/

  CREATE OR REPLACE VIEW "VR_SQMAXITEMSINCIRC" ("YEARWEEK", "YEAR", "WEEK", "CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "FINMETHODCODE", "FINMETHODDESC", "LANGUAGECODE", "MIN_ACTIVITY_ID", "ACTIVITYBUSINESSUNIT_ID", "DEFAULTBUSINESSUNIT_ID", "INVOICEBUSINESSUNIT_ID", "COSTCENTER_CODE", "COSTCENTER_DESC", "QTYRENTEDPERPIECE", "QTYPLUSADJUST", "QTYMINADJUST") AS 
  select
  a.year * 100 + a.week yearweek, a.year, a.week, d.customernumber, d.name customername,
  (select adr.city from address adr where d.visitaddress_id = adr.address_id) city, g.code productcode,
  (SELECT description FROM product_link_DESC pd WHERE pd.product_link_id = g.product_link_id
    AND pd.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
  i.code sizecode,
  k.code finmethodcode,
  (SELECT description FROM finishingmethod_DESC kd WHERE kd.finishingmethod_id = k.finishingmethod_id
    AND kd.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finmethoddesc
, languages.code languagecode
, (select min(caa.activity_id) from customeractivities caa where caa.customer_id=d.customer_id and caa.invoicebusinessunit_id = abu.businessunit_id) min_ACTIVITY_ID
, abu.businessunit_id ACTIVITYBUSINESSUNIT_ID
, d.defaultbusinessunit_id, a.invoicebusinessunit_id
, cc.code CostCenter_code, cc.description CostCenter_desc
, (sqm.qtyrentedperpiece - sqm.qtyrentstop) qtyrentedperpiece
, (sqm.qtyplusadjust - sqm.qtyplusadjustrentstop) qtyplusadjust
, sqm.qtyminadjust
from statusquoheader a,  --sqitemincirculation b,
  sqmaxitemincirculation sqm,
  customer_link c
    left outer join customer d on (c.customer_id = d.customer_id)
, product_link g, sizedefinition_link i, finishingmethod k--, businessunit processBU, plant, systemsetting ss
, languages, businessunit abu
, costcenter_link cc
where
    a.statusquotype = 13
and a.statusquoheader_id = sqm.statusquoheader_id
and sqm.costcenter_link_id = cc.costcenter_id
and sqm.product_link_id = g.product_link_id
and sqm.sizedefinition_link_id = i.sizedefinition_link_id
and sqm.finishingmethod_id = k.finishingmethod_id
and cc.customer_link_id=c.customer_link_id
--and a.processbusinessunit_id = processBU.Businessunit_Id
--   and processBU.Plant_Id = plant.plant_id
--      and plant.plant_id = ss.plant_id
--          and ss.name = 'INVOICEREPLACEMENTS'
/

  CREATE OR REPLACE VIEW "VR_STATUSQUOITEMSINCIRC" ("YEARWEEK", "YEAR", "WEEK", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "PRODUCTCODE", "SIZECODE", "FINMETHODCODE", "QRENTCHANGES", "QMAXINV", "QTOTALINCIRC", "QFREEISSUED", "QFREECUSTOMEROWNED", "QFREESEASON", "QTYWEARERRENTSTOP", "QTYCUSTOMERRENTSTOP", "QTYRENTOTHERS", "QTYASSIGNED", "QTYREPLACEMENT", "VRENTCHANGES", "VMAXINV", "VTOTALINCIRC", "VFREEISSUED", "VFREECUSTOMEROWNED", "VFREESEASON", "VWEARERRENTSTOP", "VCUSTOMERRENTSTOP", "VRENTOTHERS", "VASSIGNED", "VREPLACEMENT", "CHARGEAFTERDEPRECIATION", "EMPLOYMENT_NR", "WEARERNUMBER", "WEARER_FULL_NAME", "LANGUAGECODE", "ACTIVITYBUSINESSUNIT_ID", "DEFAULTBUSINESSUNIT_ID", "INVOICEBUSINESSUNIT_ID", "QTYRENTEDRETURNRENT", "QTYRENTEDMINRENT", "QTYFULLYAMORTIZED", "VQTYFULLYAMORTIZED", "CITY", "PRODUCTDESC", "FINMETHODDESC", "MIN_ACTIVITY_ID", "QRENTPIECES", "QBEYONDLIFETIME", "QALLFREEQTY", "VRENTPIECES", "VBEYONDLIFETIME", "VALLFREEQTY") AS 
  select --+index(d xpkcustomer) index(k xpkfinishingmethod) index(i xpksizedefinition_link) index(g xpkproduct_link) index(e xpkdepartment_link)
       /*version 2.0*/
       sq.year*100 + sq.week yearweek, sq.year, sq.week, cu.customernumber, cu.name customername, dep.departmentnumber, dep.description departmentdesc,
       pr.code productcode, sd.code sizecode, fm.code finmethodcode, si.changesperweek qrentchanges, si.maxinv qmaxinv, si.totalcircinv qtotalincirc,
       si.freeissuedcircinv qfreeissued, si.cogcircinv qfreecustomerowned, si.freeseasoncircinv qfreeseason, si.qtyrentstop qtywearerrentstop,
       si.qtycustomerrentstop, si.qtyrentedother qtyrentothers, si.qtyassigned, si.qtyreplacement, si.variationchangesperweek vrentchanges,
       si.variationmaxinv vmaxinv, si.variationtotalcircinv vtotalincirc, si.variationfreeissuedcircinv vfreeissued,
       si.variationcogcircinv vfreecustomerowned, si.variationfreeseasoncircinv vfreeseason, si.variationqtyrentstop vwearerrentstop,
       si.variationqtycustomerrentstop vcustomerrentstop, si.variationrentedother vrentothers, si.variationqtyassigned vassigned,
       si.variationqtyreplacement vreplacement, si.chargeafterdepreciation, we.sequencenumber employment_nr, we.wearernumber wearernumber,
       we.wearername wearer_full_name, lan.code languagecode, abu.businessunit_id activitybusinessunit_id, cu.defaultbusinessunit_id,
       sq.invoicebusinessunit_id, si.qtyrentedreturnrent, si.qtyrentedminrent, si.qtyfullyamortized, si.variationqtyfullyamortized vqtyfullyamortized,
       (select adr.city
          from address adr
         where cu.visitaddress_id = adr.address_id) city,
       (select pcu.description
          from product_link_desc pcu
         where pcu.product_link_id = pr.product_link_id
           and pcu.language_id = lan.language_id) productdesc,
       (select kcu.description
          from finishingmethod_desc kcu
         where kcu.finishingmethod_id = fm.finishingmethod_id
           and kcu.language_id = lan.language_id) finmethoddesc,
       (select min(casq.activity_id)
          from customeractivities casq
         where casq.customer_id = cu.customer_id
           and casq.invoicebusinessunit_id = abu.businessunit_id) min_activity_id,
       case si.chargeafterdepreciation when 'Y' then (si.qtyrentedperpiece + si.beyondlifetimecirc)
       else si.qtyrentedperpiece
        end qrentpieces,
       case si.chargeafterdepreciation when 'Y' then 0
       else si.beyondlifetimecirc
        end qbeyondlifetime,
       case ss.value when 'N' then (si.qtyassigned + si.freeissuedcircinv + si.beyondlifetimecirc + si.qtyrentstop + si.qtycustomerrentstop + si.cogcircinv + si.freeseasoncircinv + si.qtyreplacement)
       else (si.qtyassigned + si.freeissuedcircinv + si.beyondlifetimecirc + si.qtyrentstop + si.qtycustomerrentstop + si.cogcircinv + si.freeseasoncircinv)
        end qallfreeqty,
       case si.chargeafterdepreciation when 'Y' then (si.variationrentedperpiece + si.variationbeyondlifetimecirc)
       else si.variationrentedperpiece
        end vrentpieces,
       case si.chargeafterdepreciation when 'Y' then 0
       else si.variationbeyondlifetimecirc
        end vbeyondlifetime,
       case ss.value when 'N' then (si.variationqtyassigned + si.variationfreeissuedcircinv + si.variationbeyondlifetimecirc + si.variationqtyrentstop + si.variationqtycustomerrentstop + si.variationcogcircinv + si.variationfreeseasoncircinv + si.variationqtyreplacement)
       else (si.variationqtyassigned + si.variationfreeissuedcircinv + si.variationbeyondlifetimecirc + si.variationqtyrentstop + si.variationqtycustomerrentstop + si.variationcogcircinv + si.variationfreeseasoncircinv)
        end vallfreeqty
  from statusquoheader sq
       join sqitemincirculation si
            left join weareremployment_link we on si.weareremployment_link_id = we.weareremployment_link_id
            join customer cu on si.customer_link_id = cu.customer_id
            join department_link dep on si.department_link_id = dep.department_link_id
            join product_link pr on si.product_link_id = pr.product_link_id
            join sizedefinition_link sd on si.sizedefinition_link_id = sd.sizedefinition_link_id
            join finishingmethod fm on si.finishingmethod_id = fm.finishingmethod_id
       on sq.statusquoheader_id = si.statusquoheader_id
       join businessunit processbu
            join plant plt
                 join systemsetting ss on plt.plant_id = ss.plant_id
            on processbu.plant_id = plt.plant_id
       on sq.processbusinessunit_id = processbu.businessunit_id
       cross join languages lan
       cross join businessunit abu
 where sq.statusquotype = 1
   and ss.name = 'INVOICEREPLACEMENTS'
   and sq.subtype in (0, 2)
   and cu.dateinactive > sysdate
/

  CREATE OR REPLACE VIEW "VR_STATUSQUOITEMSINCIRCHISTORY" ("YEARWEEK", "YEAR", "WEEK", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "PRODUCTCODE", "SIZECODE", "PRODUCTGROUPCODE", "QRENTCHANGES", "QMAXINV", "QTOTALINCIRC", "QFREEISSUED", "QFREECUSTOMEROWNED", "QFREESEASON", "QTYWEARERRENTSTOP", "QTYCUSTOMERRENTSTOP", "QTYRENTOTHERS", "QTYASSIGNED", "QTYREPLACEMENT", "VRENTCHANGES", "VMAXINV", "VTOTALINCIRC", "VFREEISSUED", "VFREECUSTOMEROWNED", "VFREESEASON", "QTYRENTEDMINRENT", "VBEYONDLIFETIME", "VREPLACEMENT", "EMPLOYMENT_NR", "WEARER_FULL_NAME", "VWEARERRENTSTOP", "VCUSTOMERRENTSTOP", "VRENTOTHERS", "VASSIGNED", "LANGUAGECODE", "VARIATIONQTYRENTEDRETURNRENT", "VARIATIONQTYRENTEDMINRENT", "QTYRENTEDRETURNRENT", "QTYFULLYAMORTIZED", "VQTYFULLYAMORTIZED", "CITY", "PRODUCTDESC", "PRODUCTGROUPDESC", "WEARERNUMBER", "QRENTPIECES", "QBEYONDLIFETIME", "QALLFREEQTY", "VRENTPIECES", "VALLFREEQTY") AS 
  select /*version 2.0*/
       sh.year*100 + sh.week yearweek, sh.year, sh.week, cust.customernumber, cust.name customername, dep.departmentnumber, dep.description departmentdesc, prl.code productcode,
       sd.code sizecode, prl.productgroupcode, sqi.changesperweek qrentchanges, sqi.maxinv qmaxinv, sqi.totalcircinv qtotalincirc, sqi.freeissuedcircinv qfreeissued,
       sqi.cogcircinv qfreecustomerowned, sqi.freeseasoncircinv qfreeseason, sqi.qtyrentstop qtywearerrentstop, sqi.qtycustomerrentstop, sqi.qtyrentedother qtyrentothers,
       sqi.qtyassigned, sqi.qtyreplacement, sqi.variationchangesperweek vrentchanges, sqi.variationmaxinv vmaxinv, sqi.variationtotalcircinv vtotalincirc,
       sqi.variationfreeissuedcircinv vfreeissued, sqi.variationcogcircinv vfreecustomerowned, sqi.variationfreeseasoncircinv vfreeseason, sqi.qtyrentedminrent,
       sqi.variationbeyondlifetimecirc vbeyondlifetime, sqi.variationqtyreplacement vreplacement, we.sequencenumber employment_nr, we.wearername wearer_full_name,
       sqi.variationqtyrentstop vwearerrentstop, sqi.variationqtycustomerrentstop vcustomerrentstop, sqi.variationrentedother vrentothers, sqi.variationqtyassigned vassigned,
       lan.code languagecode, sqi.variationqtyrentedreturnrent, sqi.variationqtyrentedminrent, sqi.qtyrentedreturnrent, sqi.qtyfullyamortized,
       sqi.variationqtyfullyamortized vqtyfullyamortized,
       case when ((cust.customer_id <> cust.debtor_id) and (cust.invoiceaddress_id is null)) then (select adr.city
                                                                                            from address adr
                                                                                                 join customer bc on adr.address_id = bc.invoiceaddress_id
                                                                                           where bc.customer_id = cust.debtor_id)
       else (select adr.city
               from address adr
              where cust.invoiceaddress_id = adr.address_id)
        end city,
       (select pd.description
          from product_link_desc pd
         where pd.product_link_id = prl.product_link_id
           and pd.language_id = lan.language_id) productdesc,
       (select pgd.description
          from productgroup_desc pgd
               join productgroup pg on pgd.productgroup_id = pg.productgroup_id
         where pg.code = prl.productgroupcode
           and pgd.language_id = lan.language_id) productgroupdesc,
       (select w.wearernumber
          from wearer w
               join weareremployment wem on w.wearer_id = wem.wearer_id
         where wem.weareremployment_id = we.weareremployment_id) wearernumber,
       case sqi.chargeafterdepreciation when 'Y' then ( sqi.qtyrentedperpiece + sqi.beyondlifetimecirc )
       else sqi.qtyrentedperpiece
        end qrentpieces,
       case sqi.chargeafterdepreciation when 'Y' then 0
       else sqi.beyondlifetimecirc
        end qbeyondlifetime,
       case ss.value when 'N' then (sqi.qtyassigned + sqi.freeissuedcircinv + sqi.beyondlifetimecirc + sqi.qtyrentstop + sqi.qtycustomerrentstop + sqi.cogcircinv + sqi.freeseasoncircinv + sqi.qtyreplacement)
       else (sqi.qtyassigned + sqi.freeissuedcircinv + sqi.beyondlifetimecirc + sqi.qtyrentstop + sqi.qtycustomerrentstop + sqi.cogcircinv + sqi.freeseasoncircinv)
        end qallfreeqty,
       case sqi.chargeafterdepreciation when 'Y' then (sqi.variationrentedperpiece + sqi.variationbeyondlifetimecirc)
       else sqi.variationrentedperpiece
        end vrentpieces,
       case ss.value when 'N' then (sqi.variationqtyassigned + sqi.variationfreeissuedcircinv + sqi.variationbeyondlifetimecirc + sqi.variationqtyrentstop + sqi.variationqtycustomerrentstop + sqi.variationcogcircinv + sqi.variationfreeseasoncircinv + sqi.variationqtyreplacement)
       else (sqi.variationqtyassigned + sqi.variationfreeissuedcircinv + sqi.variationbeyondlifetimecirc + sqi.variationqtyrentstop + sqi.variationqtycustomerrentstop + sqi.variationcogcircinv + sqi.variationfreeseasoncircinv)
        end vallfreeqty
  from statusquoheader sh
       join sqitemincirculation sqi
            left join weareremployment_link we on we.weareremployment_link_id = sqi.weareremployment_link_id
            join customer_link c
                 left join customer cust on c.customer_id = cust.customer_id
            on sqi.customer_link_id = c.customer_link_id
            join department_link dep on sqi.department_link_id = dep.department_link_id
            join product_link prl on sqi.product_link_id = prl.product_link_id
            join sizedefinition_link sd on sqi.sizedefinition_link_id = sd.sizedefinition_link_id
       on sh.statusquoheader_id = sqi.statusquoheader_id
       join businessunit processbu
            join plant
                 join systemsetting ss on plant.plant_id = ss.plant_id
            on processbu.plant_id = plant.plant_id
       on sh.processbusinessunit_id = processbu.businessunit_id
       cross join languages lan
 where sh.statusquotype = 1
   and ss.name = 'INVOICEREPLACEMENTS'
   and sh.subtype in (0, 2)
/

  CREATE OR REPLACE VIEW "VR_STATUSQUOITEMSINCIRC_UD" ("YEARWEEK", "YEAR", "WEEK", "STATUSQUODATE", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "PRODUCTCODE", "QRENTCHANGES", "QMAXINV", "QTOTALINCIRC", "QFREEISSUED", "QFREECUSTOMEROWNED", "QFREESEASON", "QTYWEARERRENTSTOP", "QTYCUSTOMERRENTSTOP", "QTYRENTOTHERS", "QTYASSIGNED", "QTYREPLACEMENT", "VRENTCHANGES", "VMAXINV", "VTOTALINCIRC", "VFREEISSUED", "VFREECUSTOMEROWNED", "VFREESEASON", "VWEARERRENTSTOP", "VCUSTOMERRENTSTOP", "VRENTOTHERS", "VASSIGNED", "VREPLACEMENT", "SIZECODE", "FINMETHODCODE", "CHARGEAFTERDEPRECIATION", "EMPLOYMENT_NR", "WEARERNUMBER", "WEARER_FULL_NAME", "LANGUAGECODE", "ACTIVITYBUSINESSUNIT_ID", "DEFAULTBUSINESSUNIT_ID", "INVOICEBUSINESSUNIT_ID", "QTYRENTEDRETURNRENT", "QTYRENTEDMINRENT", "QTYFULLYAMORTIZED", "VQTYFULLYAMORTIZED", "PLANTCODE", "PLANTNAME", "INVOICEHEADER_ID", "INVOICENUMBER", "INVOICEDATE", "STARTWEEK", "STARTMONTH", "STARTYEAR", "ENDWEEK", "ENDMONTH", "ENDYEAR", "WEEKSINYEAR", "STARTDATE", "ENDDATE", "NEXTPERIODSTARTDATE", "NEXTPERIODENDDATE", "CITY", "PRODUCTDESC", "FINMETHODDESC", "MIN_ACTIVITY_ID", "QRENTPIECES", "QBEYONDLIFETIME", "QALLFREEQTY", "VRENTPIECES", "VBEYONDLIFETIME", "VALLFREEQTY", "NROFWEEKS") AS 
  select --+index(d xpkcustomer) index(k xpkfinishingmethod) index(i xpksizedefinition_link) index(g xpkproduct_link) index(e xpkdepartment_link)
       /*version 2.0*/
       sh.year*100 + sh.week yearweek, sh.year, sh.week, sh.statusquodate, cu.customernumber, cu.name customername, de.departmentnumber,
       de.description departmentdesc, pr.code productcode, sic.changesperweek qrentchanges, sic.maxinv qmaxinv, sic.totalcircinv qtotalincirc,
       sic.freeissuedcircinv qfreeissued, sic.cogcircinv qfreecustomerowned, sic.freeseasoncircinv qfreeseason, sic.qtyrentstop qtywearerrentstop,
       sic.qtycustomerrentstop, sic.qtyrentedother qtyrentothers, sic.qtyassigned, sic.qtyreplacement, sic.variationchangesperweek vrentchanges,
       sic.variationmaxinv vmaxinv, sic.variationtotalcircinv vtotalincirc, sic.variationfreeissuedcircinv vfreeissued,
       sic.variationcogcircinv vfreecustomerowned, sic.variationfreeseasoncircinv vfreeseason, sic.variationqtyrentstop vwearerrentstop,
       sic.variationqtycustomerrentstop vcustomerrentstop, sic.variationrentedother vrentothers, sic.variationqtyassigned vassigned,
       sic.variationqtyreplacement vreplacement, sd.code sizecode, fm.code finmethodcode, sic.chargeafterdepreciation, we.sequencenumber employment_nr,
       we.wearernumber wearernumber, we.wearername wearer_full_name, lan.code languagecode, abu.businessunit_id activitybusinessunit_id,
       cu.defaultbusinessunit_id, sh.invoicebusinessunit_id, sic.qtyrentedreturnrent, sic.qtyrentedminrent, sic.qtyfullyamortized,
       sic.variationqtyfullyamortized vqtyfullyamortized, pl.code plantcode, pl.name plantname, ih.invoiceheader_id, ih.invoicenumber,
       ih.invoicedate, ih.startweek, ih.startmonth, ih.startyear, ih.endweek, ih.endmonth, ih.endyear, getweeksinyear(ih.startyear) weeksinyear,
       ih.startdate, ih.enddate, ih.nextperiodstartdate, ih.nextperiodenddate,
       (select adr.city
          from address adr
         where cu.visitaddress_id = adr.address_id) city,
       (select pd.description
          from product_link_desc pd
         where pd.product_link_id = pr.product_link_id
           and pd.language_id = lan.language_id) productdesc,
       (select fmd.description
          from finishingmethod_desc fmd
         where fmd.finishingmethod_id = fm.finishingmethod_id
           and fmd.language_id = lan.language_id) finmethoddesc,
       (select min(caa.activity_id)
          from customeractivities caa
         where caa.customer_id=cu.customer_id
           and caa.invoicebusinessunit_id = abu.businessunit_id) min_activity_id,
       case sic.chargeafterdepreciation when 'Y' then ( sic.qtyrentedperpiece + sic.beyondlifetimecirc)
       else sic.qtyrentedperpiece
        end qrentpieces,
       case sic.chargeafterdepreciation when 'Y' then 0
       else sic.beyondlifetimecirc
        end qbeyondlifetime,
       case ss.value when 'N' then (sic.qtyassigned + sic.freeissuedcircinv + sic.beyondlifetimecirc + sic.qtyrentstop + sic.qtycustomerrentstop + sic.cogcircinv + sic.freeseasoncircinv + sic.qtyreplacement)
       else (sic.qtyassigned + sic.freeissuedcircinv + sic.beyondlifetimecirc + sic.qtyrentstop + sic.qtycustomerrentstop + sic.cogcircinv + sic.freeseasoncircinv)
        end qallfreeqty,
       case sic.chargeafterdepreciation when 'Y' then (sic.variationrentedperpiece + sic.variationbeyondlifetimecirc)
       else sic.variationrentedperpiece
        end vrentpieces,
       case sic.chargeafterdepreciation when 'Y' then 0
       else sic.variationbeyondlifetimecirc
        end vbeyondlifetime,
       case ss.value when 'N' then (sic.variationqtyassigned + sic.variationfreeissuedcircinv + sic.variationbeyondlifetimecirc + sic.variationqtyrentstop + sic.variationqtycustomerrentstop + sic.variationcogcircinv + sic.variationfreeseasoncircinv + sic.variationqtyreplacement )
       else (sic.variationqtyassigned + sic.variationfreeissuedcircinv + sic.variationbeyondlifetimecirc + sic.variationqtyrentstop + sic.variationqtycustomerrentstop + sic.variationcogcircinv + sic.variationfreeseasoncircinv)
        end vallfreeqty,
       case when ih.startweek > ih.endweek then (1 + ih.endweek + getweeksinyear(ih.startyear) - ih.startweek)
       else (1 + ih.endweek - ih.startweek)
        end nrofweeks
  from invoiceheader ih
       join customer cu on ih.deltocustomer_link_id = cu.customer_id
       join statusquoheader sh
            join sqitemincirculation sic
                 left join weareremployment_link we on we.weareremployment_link_id = sic.weareremployment_link_id
                 join department_link de on sic.department_link_id = de.department_link_id
                 join product_link pr on sic.product_link_id = pr.product_link_id
                 join sizedefinition_link sd on sic.sizedefinition_link_id = sd.sizedefinition_link_id
                 join finishingmethod fm on sic.finishingmethod_id = fm.finishingmethod_id
            on sh.statusquoheader_id = sic.statusquoheader_id
       on sh.statusquodate >= getfirstdayofweek(ih.startdate) and sh.statusquodate <= coalesce(ih.enddate, ih.nextperiodenddate, ih.invoicedate)
       join businessunit processbu
            join plant pl
                 join systemsetting ss on pl.plant_id = ss.plant_id and ss.name = 'INVOICEREPLACEMENTS'
            on processbu.plant_id = pl.plant_id
       on sh.processbusinessunit_id = processbu.businessunit_id
       join businessunit abu on ih.invoicebusinessunit_id = abu.businessunit_id
       cross join languages lan
 where sh.statusquotype = 1
   and sh.subtype in (0, 2)
   and cu.dateinactive > sysdate
   and sic.customer_link_id = cu.customer_id
/

  CREATE OR REPLACE VIEW "VR_STATUSQUOWEARERS" ("YEARWEEK", "YEAR", "WEEK", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "ACTIVEWEARERS", "ACTIVEWEARERSWITHGARM", "INACTIVEWEARERS", "ACTIVEEMPLOYMENTS", "ACTIVEEMPLOYMENTSWITHGARM", "INACTIVEEMPLOYMENTS", "ACTIVEWEARERSWITHFUNCTION", "LOCKERSINUSE", "VARIATIONACTIVEWEARERS", "VARIATIONACTIVEWEARERSWITHFUNC", "VARIATIONACTIVEWEARERSWITHGARM", "VARIATIONINACTIVEWEARERS", "VARIATIONACTIVEEMPLOYMENTS", "VARIATIONACTIVEEMPLOYWITHGARM", "VARIATIONINACTIVEEMPLOYMENTS", "VARIATIONLOCKERSINUSE", "LANGUAGECODE", "INVOICEBUSINESSUNIT_ID", "DEFAULTBUSINESSUNIT_ID", "ACTIVITYBUSINESSUNIT_ID", "CUSTOMERCITY", "MIN_ACTIVITY_ID") AS 
  select /*version 2.0 */
       (sqh.year*100+sqh.week) yearweek, sqh.year, sqh.week, cu.customernumber, cu.name customername, de.departmentnumber,
       de.description departmentdescription, sqw.activewearers, sqw.activewearerswithgarm, sqw.inactivewearers, sqw.activeemployments,
       sqw.activeemploymentswithgarm, sqw.inactiveemployments, sqw.activewearerswithfunction, sqw.lockersinuse, sqw.variationactivewearers,
       sqw.variationactivewearerswithfunc, sqw.variationactivewearerswithgarm, sqw.variationinactivewearers, sqw.variationactiveemployments,
       sqw.variationactiveemploywithgarm, sqw.variationinactiveemployments, sqw.variationlockersinuse, lan.code languagecode,
       sqh.invoicebusinessunit_id, cu.defaultbusinessunit_id, abu.businessunit_id activitybusinessunit_id,
       (select adr.city
          from address adr
         where cu.mailaddress_id = adr.address_id) customercity,
       (select min(caa.activity_id)
          from customeractivities caa
         where caa.customer_id=cu.customer_id
           and caa.invoicebusinessunit_id = abu.businessunit_id) min_activity_id
  from statusquoheader sqh
       join sqwearer sqw
            join customer_link culk
                 left join customer cu on culk.customer_id = cu.customer_id
            on sqw.customer_link_id = culk.customer_link_id
            join department_link delk
                 left join department de on delk.department_id = de.department_id
            on sqw.department_link_id = delk.department_link_id
       on sqh.statusquoheader_id = sqw.statusquoheader_id
       cross join languages lan
       cross join businessunit abu
 where cu.dateinactive > sysdate
/

  CREATE OR REPLACE VIEW "V_ABSSOLUTEDOMAINUI1" ("REPORTPARAM_ID", "MINUSERGROUP", "MAXUSERGROUP", "ONLYACTIVE", "USERGROUPNAME", "USERGROUPDESC", "SYSTEMUSER_ID", "USERNAME", "FULLNAME", "DOMAINUSER", "LASTLOGINTIMESTAMP", "LASTLOGINDATE", "ACTIVE", "LOCKEDOUT", "LASTLOGINATWORKSTATION", "WORKSTATIONCODE") AS 
  select rp.reportparam_id, rp.string_value MinUserGroup, rp.string_value1 MaxUserGroup, rp.string_value6 OnlyActive,
ug.groupname UserGroupName, ug.description UserGroupDesc, su.systemuser_id, su.username, su.fullname, su.domainuser,
su.lastlogintimestamp, trunc(su.lastlogintimestamp) lastlogindate, su.active, su.lockedout, su.lastloginatworkstation
, (select ws.code from workstation ws where ws.workstation_id = su.lastloginatworkstation) workstationCode
from reportparam rp, systemuser su, usergroup ug
where su.systemuser_id = rp.number_value and su.usergroup_id = ug.usergroup_id
      and ug.groupname >= rp.string_value and ug.groupname <= rp.string_value1
      and ((rp.string_value6 = 'true' and su.active = 'Y') or (rp.string_value6 <> 'true'))
/

  CREATE OR REPLACE VIEW "V_ABSSOLUTEDOMAINUI2" ("REPORTPARAM_ID", "MINUSERGROUP", "MAXUSERGROUP", "ONLYACTIVE", "USERGROUPNAME", "USERGROUPDESC", "SYSTEMUSER_ID", "USERNAME", "FULLNAME", "DOMAINUSER", "LASTLOGINTIMESTAMP", "LASTLOGINDATE", "ACTIVE", "LOCKEDOUT", "LASTLOGINATWORKSTATION", "WORKSTATIONCODE") AS 
  select rp.reportparam_id, rp.string_value MinUserGroup, rp.string_value1 MaxUserGroup, rp.string_value6 OnlyActive,
ug.groupname UserGroupName, ug.description UserGroupDesc, su.systemuser_id, su.username, su.fullname, su.domainuser,
su.lastlogintimestamp, trunc(su.lastlogintimestamp) lastlogindate, su.active, su.lockedout, su.lastloginatworkstation
, (select ws.code from workstation ws where ws.workstation_id = su.lastloginatworkstation) workstationCode
from reportparam rp, systemuser su, usergroup ug
where su.usergroup_id = ug.usergroup_id
      and ug.groupname >= rp.string_value and ug.groupname <= rp.string_value1
      and su.lockedout = 'Y'
/

  CREATE OR REPLACE VIEW "V_ABSSOLUTEDOMAINUI3" ("REPORTPARAM_ID", "ONLYACTIVE", "FIRSTNAME", "SECONDNAME", "DISPLAYNAME", "USERNAME", "ACTIVE", "LOCKED", "LOCKEDARGUMENTS") AS 
  select rp.reportparam_id, rp.string_value6 OnlyActive,
rp.string_value firstName, rp.string_value1 secondName, rp.string_value2 displayName,
rp.string_value3 userName, rp.string_value4 Active, rp.string_value5 Locked, rp.string_value7 LockedArguments
from reportparam rp
/

  CREATE OR REPLACE VIEW "V_ABSSOLUTEDOMAINUI4" ("REPORTPARAM_ID", "FIRSTNAME", "SECONDNAME", "DISPLAYNAME", "USERNAME", "ACTIVE", "LOCKED", "LOCKEDARGUMENTS") AS 
  select rp.reportparam_id,
rp.string_value firstName, rp.string_value1 secondName, rp.string_value2 displayName,
rp.string_value3 userName, rp.string_value4 Active, 'Y' Locked,rp.string_value7 LockedArguments
from reportparam rp
/

  CREATE OR REPLACE VIEW "V_ACCESSRIGHTS" ("PLANT_ID", "PLANTCODE", "PLANTNAME", "USERGROUP_ID", "GROUPNAME", "GROUPDESC", "SINGLETASK", "BU_CODE", "BU_DESC", "LANGUAGE_CODE", "LANGUAGE_ID") AS 
  select /*version 2.0*/
       distinct pt.plant_id, pt.code plantcode, pt.name plantname, ug.usergroup_id, ug.groupname, ug.description groupdesc,
       ug.singletask, bu.code bu_code, bu.description bu_desc, lan.code language_code, lan.language_id
  from usergroup ug
       join businessunitsperusergroup bug
            join businessunit bu on bug.businessunit_id = bu.businessunit_id
       on ug.usergroup_id = bug.usergroup_id
       join menusperusergroup mpu
            join menu m
                 join plant pt on m.plant_id = pt.plant_id
                 join menugroup mg
                      join menuitem mi on mg.menugroup_id = mi.menugroup_id
                 on m.menu_id = mg.menu_id
            on mpu.menu_id = m.menu_id
       on ug.usergroup_id = mpu.usergroup_id
       cross join languages lan
/

  CREATE OR REPLACE VIEW "V_ACCESSRIGHTS_DETAILS" ("USERGROUP_ID", "USERNAME", "FULLNAME", "ACTIVE", "SYSADMIN", "PASSWORDEXPIRES", "CHANGEPASSWORDNEXLOGIN", "LOCKEDOUT", "EMPLOYEENUMBER", "EMPLOYEENAME", "CREDITCARDAUTHORISED", "CONTACTMGRFULLRIGHTS", "SHOWCONTACTLOGIN", "WEIGHTOVERRIDE", "MAYCHANGESTOCKROOMFORWO", "MAYCHANGESTOCKROOMFORMO", "MAYCHANGEDELIVERYWO", "MAYCHANGEDELIVERYSN", "MAYCHANGEPRIORITYFORWO", "MAYUNDOSTOCKRECEPTION", "PASSWORDCHANGETIMESTAMP", "LASTLOGINTIMESTAMP", "LASTINCORRECTLOGINTIMESTAMP", "INCORRECTLOGINSSINCEPWCHANGE", "LASTLOGINATWORKSTATION_CODE") AS 
  select /*version 2.0*/
       su.usergroup_id, su.username, su.fullname, su.active, su.sysadmin, su.passwordexpires, su.changepasswordnexlogin, su.lockedout,
       emp.employeenumber, emp.name employeename, su.creditcardauthorised, su.contactmgrfullrights, su.showcontactlogin, su.weightoverride,
       su.maychangestockroomforwo, su.maychangestockroomformo, su.maychangedeliverywo, su.maychangedeliverysn, su.maychangepriorityforwo,
       su.mayundostockreception, su.passwordchangetimestamp, su.lastlogintimestamp, su.lastincorrectlogintimestamp, su.incorrectloginssincepwchange,
       (select wo.code
          from workstation wo
         where wo.workstation_id = su.lastloginatworkstation) lastloginatworkstation_code
  from systemuser su
       left join employee emp on su.employee_id = emp.employee_id
/

  CREATE OR REPLACE VIEW "V_ACCESSRIGHTS_USERS" ("USERGROUP_ID", "USERNAME", "FULLNAME", "LANGUAGE_CODE", "ACTIVE", "SYSADMIN") AS 
  select /*version 2.0 */
       su.usergroup_id, su.username, su.fullname, lan.code language_code, su.active, su.sysadmin
  from systemuser su
       join languages lan on su.language_id = lan.language_id
/

  CREATE OR REPLACE VIEW "V_ACCESSRIGHTS_WORKSPOTS" ("USERGROUP_ID", "MENUDESC", "MENUGROUPDESC", "DIALOGDESC", "MENUITEM_ID", "MENUGROUP_ID", "MENU_SEQ", "MENU_ID", "MENUGROUP_SEQ", "MENUITEM_SEQ", "PLANT_ID", "ACCESSRIGHTS_USERGROUP_ID", "MENUGROUP_USERGROUP_ID", "MGPU_VISIBLE", "ARPG_VISIBLE", "READONLY", "LANGUAGE_ID", "LANGUAGE_CODE", "PROFILE") AS 
  select /*version 2.0*/
       y.usergroup_id, y.menudesc, y.menugroupdesc, y.dialogdesc, y.menuitem_id, y.menugroup_id, y.menu_seq, y.menu_id, y.menugroup_seq, y.menuitem_seq,
       y.plant_id, y.accessrights_usergroup_id, y.menugroup_usergroup_id, y.mgpu_visible, y.arpg_visible, y.readonly, y.language_id, y.language_code,
       (select ugda.profile
          from usergroupdialogaccess ugda
         where ugda.usergroup_id = nvl(y.arpgus, y.mgpus)
           and ugda.dialog_id = y.dialog_id) profile
  from (select x.groupname,  x.groupdesc, x.plantcode, x.plant_id, x.menudesc, x.menugroupdesc, x.dialogdesc,
               coalesce(mgpu.visible, (case when mpu.systemuser_id is null then 'N' else 'Y' end), 'N') mgpu_visible,
               coalesce(arpg.visible, mgpu.visible, (case when mpu.systemuser_id is null then 'N' else 'Y' end), 'N') arpg_visible,
               coalesce(arpg.readonly, (case when mpu.systemuser_id is null then 'N' else 'Y' end), 'N') readonly,
               mgpu.usergroup_id menugroup_usergroup_id, arpg.usergroup_id accessrights_usergroup_id, x.menu_id, x.menuitem_id,
               x.menu_seq, x.menugroup_seq,  x.menuitem_seq, x.menugroup_id, x.dialogonly, x.dialogtype, arpg.usergroup_id arpgus,
               mgpu.usergroup_id mgpus, x.usergroup_id, x.dialog_id, x.language_id, x.language_code
          from (select pt.code plantcode, pt.plant_id, md.description  menudesc, mgd.description menugroupdesc,
                       coalesce((select mid.description
                                   from menuitem_desc mid
                                  where mid.menuitem_id = mi.menuitem_id
                                    and mid.language_id = l.language_id),
                                (case substr(l.code, 1, 2)
                                 when 'DE' then (select dd.description from dialogs_desc dd, license_languages lan where dd.license_language_id = lan.license_language_id and lan.code = 'DE_DE')
                                 when 'NL' then (select dd.description from dialogs_desc dd, license_languages lan where dd.license_language_id = lan.license_language_id and lan.code = 'NL_NL')
                                 else (select dd.description from dialogs_desc dd, license_languages lan where dd.license_language_id = lan.license_language_id and lan.code = 'EN_US')
                                  end)) dialogdesc,
                       dg.dialogonly, dg.dialogtype, dg.dialog_id, mi.menuitem_id, m.menu_id, mg.menugroup_id, m.sequence  menu_seq, mg.sequence menugroup_seq,
                       mi.sequence menuitem_seq, ug.usergroup_id, ug.groupname, ug.description groupdesc, l.language_id, l.code language_code
                  from menu m
                       join menu_desc md on m.menu_id = md.menu_id
                       join plant pt on m.plant_id = pt.plant_id
                       join menugroup mg
                            join menugroup_desc mgd on mg.menugroup_id = mgd.menugroup_id
                            join menuitem mi
                                 join dialogs dg on mi.dialog_id = dg.dialog_id
                            on mg.menugroup_id = mi.menugroup_id
                       on m.menu_id = mg.menu_id
                       cross join usergroup ug
                       cross join languages l
                 where md.language_id = l.language_id
                   and mgd.language_id = l.language_id) x
               left join accessrightsperusergroup arpg on arpg.menuitem_id = x.menuitem_id and arpg.usergroup_id = x.usergroup_id
               left join menugroupsperusergroup mgpu on mgpu.menugroup_id = x.menugroup_id and mgpu.usergroup_id = x.usergroup_id
               left join Menusperusergroup mpu on mpu.menu_id = x.menu_id and mpu.usergroup_id = x.usergroup_id) y
/

  CREATE OR REPLACE VIEW "V_ACTIVESTOCKALTPACKINGSLIP" ("ROUTECONTROL_ID", "STOPNUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "STREET", "ZIPCODE", "CITY", "ROUTENUMBER", "ROUTEDESC", "PUTUPREPORTROUTESTOP", "DRIVINGDATE", "NOTENUMBER", "PRODUCTCODE", "SIZECODE", "PRODUCTDESC", "SIZEDESC", "UNIQUEID_ASKD", "LASTSCANDATE", "SECTION", "LOCATION", "UNIQUEID_ASKL", "TIMESTAMP", "USERNAME", "LANGUAGECODE") AS 
  select /*version 2.0*/
       rc.routecontrol_id,
       (select rs.stopnumber
           from routestop rs
          where rs.route_id = r.route_id
            and rs.customer_id = cu.customer_id) stopnumber, cu.customernumber, cu.name customername, addr.street, addr.zipcode, addr.city,
       r.routenumber, r.description routedesc, r.putupreportroutestop, rc.drivingdate, pn.notenumber, prdlk.code productcode,
       szlk.code sizecode,
       (select prdlk_d.description
           from product_link_desc prdlk_d
          where prdlk_d.product_link_id = prdlk.product_link_id
            and prdlk_d.language_id = lan.language_id) productdesc,
       (select szlk_d.description
           from sizedefinition_link_desc szlk_d
          where szlk_d.sizedefinition_link_id = szlk.sizedefinition_link_id
            and szlk_d.language_id = lan.language_id) sizedesc, askd.uniqueid uniqueid_askd, uq.lastscandate, askl.section, askl.location,
       askl.uniqueid uniqueid_askl, askd.timestamp, su.username, lan.code languagecode
  from activestockdelivery ask
       left join customer cu
                 join address addr on cu.visitaddress_id = addr.address_id
       on ask.customer_link_id = cu.customer_id
       left join packingnoteline pnl
                 join packingnote pn on pnl.packingnote_id = pn.packingnote_id
       on ask.packingnoteline_id = pnl.packingnoteline_id
       join activestockdeliverydetail askd
            left join activestocklocation askl on askd.activestocklocation_id = askl.activestocklocation_id
            join uniqueitem uq on askd.uniqueid = uq.primaryid
            join systemuser su on askd.systemuser_id = su.systemuser_id
       on ask.activestockdelivery_id = askd.activestockdelivery_id
       join routecontrol rc
            join route r on rc.route_id = r.route_id
       on ask.routecontrol_id = rc.routecontrol_id
       join product_link prdlk on ask.product_link_id = prdlk.product_link_id
       join sizedefinition_link szlk on ask.sizedefinition_link_id = szlk.sizedefinition_link_id
       cross join languages lan
 where askd.detailinfo = 4 -- emergency procedure
/

  CREATE OR REPLACE VIEW "V_ACTIVITY" ("CODE", "ACTIVITY_DESC", "ACTIVE", "LEGACYACTIVITYCODE", "SYSTEMUSER_ID", "TIMESTAMP", "ACTIVITY_ID", "LANGUAGECODE") AS 
  SELECT ACTIVITY.CODE,
 (SELECT description FROM ACTIVITY_DESC A WHERE A.ACTIVITY_ID = ACTIVITY.ACTIVITY_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) ACTIVITY_DESC,
 ACTIVITY.ACTIVE, ACTIVITY.LEGACYACTIVITYCODE,
 activity.systemuser_id, ACTIVITY.TIMESTAMP, ACTIVITY.ACTIVITY_ID, LANGUAGES.CODE languagecode
FROM ACTIVITY,  LANGUAGES
/

  CREATE OR REPLACE VIEW "V_ADDRESS" ("CUSTOMERNUMBER", "ADDRESS_ID", "ADDRESS_FIELD", "STREETSTRING", "HOUSENUMBER", "HOUSEEXTENSION") AS 
  select
c.customernumber,
a.address_id,
a.street address_field,
substr(ltrim(a.street),1,instr(rtrim(a.street),' ',-1,2)) streetstring,
replace(substr(ltrim(a.street),1+instr(rtrim(a.street),' ',-1,2),instr(ltrim(rtrim(a.street)),' ',-1,1)-instr(rtrim(a.street),' ',-1,2)),',') housenumber,
substr(ltrim(a.street),1+instr(rtrim(a.street),' ',-1)) houseextension
from address a, customer c
where instr(rtrim(a.street),' ',-1)>0
and a.address_id = c.invoiceaddress_id
and isnumeric(substr(ltrim(a.street),1+instr(rtrim(a.street),' ',-1,2),instr(ltrim(rtrim(a.street)),' ',-1,1)-instr(rtrim(a.street),' ',-1,2))) =1
and length(substr(ltrim(a.street),1+instr(rtrim(a.street),' ',-1)))<=6--house extension enlarged to 6
and length(substr(ltrim(a.street),1+instr(rtrim(a.street),' ',-1,2),instr(ltrim(rtrim(a.street)),' ',-1,1)-instr(rtrim(a.street),' ',-1,2)))<=5--house number
union
select
c.customernumber,
a.address_id,
a.street address_field,
substr(ltrim(a.street),1,length(rtrim(ltrim(a.street)))-(length(rtrim(a.street))-instr(rtrim(a.street),'.',-1))) streetstring,
replace(substr(ltrim(rtrim(a.street)), 1+instr(rtrim(a.street),'.',-1)),',')  housenumber,
' ' houseextension
from address a, customer c
where a.address_id = c.invoiceaddress_id
and instr(ltrim(rtrim(a.street)),' ',1)=0
and isnumeric(substr(ltrim(rtrim(a.street)), 1+instr(rtrim(a.street),'.',-1)))=1
and length(substr(ltrim(rtrim(a.street)), 1+instr(rtrim(a.street),'.',-1)))<=5--house number
union
select
c.customernumber,
a.address_id,
a.street address_field,
substr(ltrim(a.street),1,length(rtrim(ltrim(a.street)))-(length(rtrim(a.street))-instr(rtrim(a.street),' ',-1))) streetstring,
case isnumeric(substr(ltrim(a.street),-(length(rtrim(a.street))-instr(rtrim(a.street),' ',-1)),length(rtrim(a.street))-instr(rtrim(a.street),' ',-1)))
when 1 then replace(substr(ltrim(a.street),-(length(rtrim(a.street))-instr(rtrim(a.street),' ',-1)),length(rtrim(a.street))-instr(rtrim(a.street),' ',-1)),',')
when 0 then replace(gethousenumber(substr(ltrim(a.street),-(length(rtrim(a.street))-instr(rtrim(a.street),' ',-1)),length(rtrim(a.street))-instr(rtrim(a.street),' ',-1)),'l'),',')
end  housenumber,
case isnumeric(substr(ltrim(a.street),-(length(rtrim(a.street))-instr(rtrim(a.street),' ',-1)),length(rtrim(a.street))-instr(rtrim(a.street),' ',-1)))
when 1 then ' '
when 0 then substr(substr(ltrim(a.street),-(length(rtrim(a.street))-instr(rtrim(a.street),' ',-1)),length(rtrim(a.street))-instr(rtrim(a.street),' ',-1)), 1+length(gethousenumber(substr(ltrim(a.street),-(length(rtrim(a.street))-instr(rtrim(a.street),' ',-1)),length(rtrim(a.street))-instr(rtrim(a.street),' ',-1)),'l')))
end
 houseextension
from address a, customer c
where instr(rtrim(a.street),' ',-1)>0
and
a.address_id = c.invoiceaddress_id
and length(case isnumeric(substr(ltrim(a.street),-(length(rtrim(a.street))-instr(rtrim(a.street),' ',-1)),length(rtrim(a.street))-instr(rtrim(a.street),' ',-1)))
when 1 then substr(ltrim(a.street),-(length(rtrim(a.street))-instr(rtrim(a.street),' ',-1)),length(rtrim(a.street))-instr(rtrim(a.street),' ',-1))
when 0 then gethousenumber(substr(ltrim(a.street),-(length(rtrim(a.street))-instr(rtrim(a.street),' ',-1)),length(rtrim(a.street))-instr(rtrim(a.street),' ',-1)),'l')
end)<=5--house number
and length(case isnumeric(substr(ltrim(a.street),-(length(rtrim(a.street))-instr(rtrim(a.street),' ',-1)),length(rtrim(a.street))-instr(rtrim(a.street),' ',-1)))
when 1 then ' '
when 0 then substr(substr(ltrim(a.street),-(length(rtrim(a.street))-instr(rtrim(a.street),' ',-1)),length(rtrim(a.street))-instr(rtrim(a.street),' ',-1)), 1+length(gethousenumber(substr(ltrim(a.street),-(length(rtrim(a.street))-instr(rtrim(a.street),' ',-1)),length(rtrim(a.street))-instr(rtrim(a.street),' ',-1)),'l')))
end )<=6-- --house extension enlarged to 6
and not exists (select
a2.address_id
from address a2, customer c
where instr(rtrim(a2.street),' ',-1)>0
and a2.address_id = c.invoiceaddress_id
and isnumeric(substr(ltrim(a2.street),1+instr(rtrim(a2.street),' ',-1,2),instr(ltrim(rtrim(a2.street)),' ',-1,1)-instr(rtrim(a2.street),' ',-1,2))) =1
and length(substr(ltrim(a2.street),1+instr(rtrim(a2.street),' ',-1)))<= 6 and a2.address_id = a.address_id)
/

  CREATE OR REPLACE VIEW "V_ADJUSTMENTVERIF" ("BUSINESSUNITCODE", "BUSINESSUNITDESCRIPTION", "INVOICEDATE", "ROUTENUMBER", "ROUTEDESCRIPTION", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "INVOICENUMBER", "LINENUMBER", "WEARERNUMBER", "INVOICELINETYPEDESC", "INVOICELINEDESC", "INVOICELINECODE", "ADJUSTMENTCODE", "ADJUSTMENTDESC", "ADJUSTEDAMOUNT", "AMOUNT", "ADJUSTMENTBILLEDQTY", "CURRENCYCODE", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE", "DISTRICTCODE", "ROUTEMANAGERNR", "ROUTE_ID", "CHTIMESTAMP", "CHUSER") AS 
  select /*version 2.0*/
       invbu.code businessunitcode, invbu.description businessunitdescription, ih.invoicedate, r.routenumber,
       r.description routedescription, ih.deltocustomernumber, ih.deltocustomername, ih.invoicenumber, il.linenumber, ilp.wearernumber,
       (select description
           from invoicelinetype_desc iltd
          where iltd.invoicelinetype_id = ilt.invoicelinetype_id
            and iltd.language_id = lan.language_id) invoicelinetypedesc, il.description invoicelinedesc, il.code invoicelinecode,
       rc.code adjustmentcode,
       (select description
           from reasoncode_desc rcd
          where rcd.reasoncode_id = rc.reasoncode_id
            and rcd.language_id = lan.language_id) adjustmentdesc, il.adjustedamount, il.amount, il.adjustmentbilledqty, cu.code currencycode,
       cu.invoiceamountdecimals, lan.code languagecode, (select d.code from district d where r.district_id = d.district_id) districtcode,
       (select e.employeenumber from employee e where e.employee_id = r.routemanager_id) routemanagernr, ih.route_id, il.timestamp chtimestamp,
       (select su.username from systemuser su where su.systemuser_id = il.systemuser_id) chuser
  from invoiceline il
       left join invoicelineproduct ilp on il.invoiceline_id = ilp.invoiceline_id
       join invoicelinetype ilt on il.invoicelinetype_id = ilt.invoicelinetype_id
       join invoiceheader ih
            left join route r on ih.route_id = r.route_id and r.active = 'Y'
            join status st on ih.status_id = st.status_id
            join businessunit invbu on ih.invoicebusinessunit_id = invbu.businessunit_id
            join currency cu on ih.currency_id = cu.currency_id
       on il.invoiceheader_id = ih.invoiceheader_id
       join reasoncode rc on il.adjustmentreason_id = rc.reasoncode_id
       cross join languages lan
 where st.statustype = 'IN'
/

  CREATE OR REPLACE VIEW "V_ADJUSTMENTVERIF_CASHDELAY" ("DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "INVOICENUMBER", "INVOICEDATE", "ROUTE_ID", "ROUTENUMBER", "OPENAMOUNT") AS 
  select /*version 2.0*/
       ih.deltocustomernumber, ih.deltocustomername, ih.invoicenumber,
       ih.invoicedate, ih.route_id, ih.routenumber,
       (ih.paythisamount - ih.cashcollected) openamount
from invoiceheader ih
where ih.originalcollectiontype = 1
      and ih.paythisamount - ih.cashcollected > 0
/

  CREATE OR REPLACE VIEW "V_ADJUSTMENTVERIF_UNDELIV" ("DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "INVOICENUMBER", "INVOICEDATE", "ROUTENUMBER", "ROUTE_ID", "OPENAMOUNT", "LANGUAGECODE", "ADJUSTMENTDESC") AS 
  select /*version 2.0*/
       ih.deltocustomernumber, ih.deltocustomername, ih.invoicenumber,
       ih.invoicedate, ih.routenumber, ih.route_id,
       ih.paythisamount openamount, lan.code languageCode,
			 (select description from reasoncode_desc y where y.reasoncode_id = rc.reasoncode_id
       and y.language_id = lan.language_id) adjustmentDesc
from invoiceheader ih
     join reasoncode rc on ih.adjustmentreason_id = rc.reasoncode_id
     cross join languages lan
/

  CREATE OR REPLACE VIEW "V_AGEANALYSISGARMENTSPERWEARER" ("CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "WEARERNUMBER", "WEARERNAME", "WEAREREDATEACTIVE", "CIRCINVENTORY", "WEARERFUNCTIONCODE", "PRODUCTGROUPCODE", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "SIZEDESC", "DAYSINCIRCPREVISSUE", "LASTISSUEDATE", "UNIQUEITEM_ID", "LANGUAGECODE") AS 
  select /*version 2.0*/
       cu.customer_id, cu.customernumber, cu.name customername, adr.city, dp.departmentnumber, dp.description departmentdesc, w.wearernumber,
       w.fullname wearername, w.dateactive weareredateactive, wi.circinventory, wf.code wearerfunctioncode,
       pg.code productgroupcode, pr.code productcode,
       (select pdd.description
           from product_desc pdd
          where pdd.product_id = pr.product_id
            and pdd.language_id = lan.language_id) productdesc, sz.code sizecode,
       (select sdd.description
           from sizedefinition_desc sdd
          where sdd.sizedefinition_id = sz.sizedefinition_id
            and sdd.language_id = lan.language_id) sizedesc, uifi.daysincircprevissue,
       uifi.lastissuedate, ui.uniqueitem_id, lan.code languagecode
  from weareremployment we
       left join wearerfunction wf on we.wearerfunction_id = wf.wearerfunction_id
       join wearerinventory wi
            join uniqueitemnonpool uinp
                 join uniqueitem ui
                      join uniqueitemfixedinfo uifi on ui.uniqueitem_id = uifi.uniqueitem_id
                      join status st on ui.status_id = st.status_id
                 on uinp.uniqueitem_id = ui.uniqueitem_id
            on uinp.wearerinventory_id = wi.wearerinventory_id
            join product pr
                 join productgroup pg on pr.productgroup_id = pg.productgroup_id
            on wi.product_id = pr.product_id
            join sizedefinition sz on wi.sizedefinition_id = sz.sizedefinition_id
       on we.weareremployment_id = wi.weareremployment_id
       join wearer w
            join customer cu
                 join address adr on cu.mailaddress_id = adr.address_id
            on w.customer_id = cu.customer_id
       on we.wearer_id = w.wearer_id
       join distributionpoint dsp
            join department dp on dsp.department_id = dp.department_id
       on we.distributionpoint_id = dsp.distributionpoint_id
       cross join languages lan
 where st.code = 20 -- in circulation
   and st.statustype = 'UI' -- unique items
   and pr.typeofmerchandise = 2 -- garments
/

  CREATE OR REPLACE VIEW "V_AGEANALYSISGARMENTSPRODUCT" ("CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "PRODUCTGROUPCODE", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "SIZEDESC", "DAYSINCIRCPREVISSUE", "LASTISSUEDATE", "LANGUAGECODE") AS 
  select /*version 2.0*/
       /*+ rule */
 (select c.customer_id
     from customer c
     join wearer w
          join weareremployment we on w.wearer_id = we.wearer_id
     on c.customer_id = w.customer_id
    where we.weareremployment_id = uinp.weareremployment_id) customer_id,
 (select c.customernumber
     from customer c
     join wearer w
          join weareremployment we on w.wearer_id = we.wearer_id
     on c.customer_id = w.customer_id
    where we.weareremployment_id = uinp.weareremployment_id) customernumber,
 (select c.name
     from customer c
     join wearer w
          join weareremployment we on w.wearer_id = we.wearer_id
     on c.customer_id = w.customer_id
    where we.weareremployment_id = uinp.weareremployment_id) customername,
 (select ad.city
     from address ad
     join customer c
          join wearer w
               join weareremployment we on w.wearer_id = we.wearer_id
          on c.customer_id = w.customer_id
     on ad.address_id = c.visitaddress_id
    where we.weareremployment_id = uinp.weareremployment_id) city, pg.code productgroupcode, pr.code productcode,
 (select pd.description
     from product_desc pd
    where pd.product_id = pr.product_id
      and pd.language_id = lan.language_id) productdesc, sz.code sizecode,
 (select szd.description
     from sizedefinition_desc szd
    where szd.sizedefinition_id = sz.sizedefinition_id
      and szd.language_id = lan.language_id) sizedesc, uifi.daysincircprevissue, uifi.lastissuedate, lan.code languagecode
  from uniqueitemnonpool uinp
       join uniqueitem ui
            join product pr
                 join productgroup pg on pr.productgroup_id = pg.productgroup_id
            on ui.product_id = pr.product_id
            join sizedefinition sz on ui.sizedefinition_id = sz.sizedefinition_id
            join status st on ui.status_id = st.status_id
            join uniqueitemfixedinfo uifi on ui.uniqueitem_id = uifi.uniqueitem_id
       on uinp.uniqueitem_id = ui.uniqueitem_id
       cross join languages lan
 where st.code = 20 -- in circulation
   and st.statustype = 'UI' -- unique items
   and pr.typeofmerchandise = 2 -- garments
/

  CREATE OR REPLACE VIEW "V_AGEANALYSISPOOLITEMS" ("REPORTPARAM_ID", "PRODUCTGROUPCODE", "PRODUCTGROUPDESC", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "SIZEDESC", "COLUMN1", "COLUMN2", "COLUMN3", "COLUMN4", "COLUMN5", "COLUMN6", "COLUMN7", "COLUMN8", "COLUMN9", "TOTAL_WEEKS_IN_CIRC", "TOTAL_WASHES", "TOTAL_STOCK", "LANGUAGECODE", "CUSTOMERNUMBER", "CUSTOMERNAME") AS 
  select /*version 2.0*/
       q.reportparam_id,
       pg.code productgroupcode,
       (select pgd.description
          from productgroup_desc pgd
         where pgd.productgroup_id = pg.productgroup_id
           and pgd.language_id = lan.language_id) productgroupdesc,
       q.product_id,
       p.code productcode,
       (select product_desc.description
          from product_desc
         where product_desc.product_id = q.product_id
           and product_desc.language_id = lan.language_id) productdesc,
       s.code sizecode,
       (select size_desc.description
          from sizedefinition_desc size_desc
         where size_desc.sizedefinition_id = q.sizedefinition_id
           and size_desc.language_id = lan.language_id) sizedesc,
       q.column1,
       q.column2,
       q.column3,
       q.column4,
       q.column5,
       q.column6,
       q.column7,
       q.column8,
       q.column9,
       q.total_weeks_in_circ,
       q.total_washes,
       q.total_stock,
       lan.code languagecode, q.customernumber, q.customername
  from (select x.reportparam_id,
               x.product_id,
               x.sizedefinition_id,
               sum(case when x.showagebyweeks = 'Y'
                        then case when x.weekscolumnnr = 1 then 1 else 0 end
                        else case when x.washescolumnnr =1 then 1 else 0 end end) column1,
               sum(case when x.showagebyweeks = 'Y'
                        then case when x.weekscolumnnr = 2 then 1 else 0 end
                        else case when x.washescolumnnr =2 then 1 else 0 end end) column2,
               sum(case when x.showagebyweeks = 'Y'
                        then case when x.weekscolumnnr = 3 then 1 else 0 end
                        else case when x.washescolumnnr =3 then 1 else 0 end end) column3,
               sum(case when x.showagebyweeks = 'Y'
                        then case when x.weekscolumnnr = 4 then 1 else 0 end
                        else case when x.washescolumnnr =4 then 1 else 0 end end) column4,
               sum(case when x.showagebyweeks = 'Y'
                        then case when x.weekscolumnnr = 5 then 1 else 0 end
                        else case when x.washescolumnnr =5 then 1 else 0 end end) column5,
               sum(case when x.showagebyweeks = 'Y'
                        then case when x.weekscolumnnr = 6 then 1 else 0 end
                        else case when x.washescolumnnr =6 then 1 else 0 end end) column6,
               sum(case when x.showagebyweeks = 'Y'
                        then case when x.weekscolumnnr = 7 then 1 else 0 end
                        else case when x.washescolumnnr =7 then 1 else 0 end end) column7,
               sum(case when x.showagebyweeks = 'Y'
                        then case when x.weekscolumnnr = 8 then 1 else 0 end
                        else case when x.washescolumnnr =8 then 1 else 0 end end) column8,
               sum(case when x.showagebyweeks = 'Y'
                        then case when x.weekscolumnnr = 9 then 1 else 0 end
                        else case when x.washescolumnnr =9 then 1 else 0 end end) column9,
               count(*) total_stock,
               sum(x.weeks_in_circ) total_weeks_in_circ,
               sum(x.washestotal) total_washes, x.customernumber, x.customername
          from (select rp.reportparam_id, rp.string_value8 showagebyweeks,
                       uq.product_id, uq.sizedefinition_id, uq.uniqueitem_id,
                       ceil((uf.daysincircprevissue + (trunc(sysdate) - uf.lastissuedate))/7) weeks_in_circ,
                       case
                         when floor(ceil((uf.daysincircprevissue + (trunc(sysdate) - uf.lastissuedate))/7) / rp.number_value3) + 1 > 9
                           then 9
                           else floor(ceil((uf.daysincircprevissue + (trunc(sysdate) - uf.lastissuedate))/7) / rp.number_value3) + 1
                       end weekscolumnnr,
                       uq.washestotal,
                       case
                         when floor(uq.washestotal / rp.number_value3) + 1 > 9
                           then 9
                           else floor(uq.washestotal / rp.number_value3) + 1
                       end washescolumnnr, -1 customernumber, '' customername
                  from uniqueitem        uq,
                       uniqueitemfixedinfo uf,
                       businessunit      bu,
                       product           prd,
                       productgroup      pg,
                       systemuser        su,
                       reportparam       rp
                 where rp.number_value5 = -1 and uq.customerowned = 'N'
                   and uq.poolitem = 1
                   and uf.uniqueitem_id = uq.uniqueitem_id
                   and prd.product_id = uq.product_id
                   and prd.uniquepoolitem = 'Y'
                   and pg.productgroup_id = prd.productgroup_id
                   and uq.status_id in
                       (select s1.status_id
                          from status s1
                         where s1.statustype = 'UI'
                           and s1.code in ('20', '30'))
                   and bu.businessunit_id = uq.businessunit_id
                   and bu.code >= rp.string_value1
                   and bu.code <= rp.string_value2
                   and pg.code >= rp.string_value3
                   and pg.code <= rp.string_value4
                   and prd.code >= rp.string_value5
                   and prd.code <= rp.string_value6
                   and (trunc(sysdate) - trunc(uq.lastscandate)) <= rp.number_value4
                   and su.systemuser_id = rp.number_value
                   and bu.businessunit_id in (select bug.businessunit_id from businessunitsperusergroup bug where bug.usergroup_id = su.usergroup_id)
                   union all --related to customer
                   select rp.reportparam_id, rp.string_value8 showagebyweeks,
                       uq.product_id, uq.sizedefinition_id, uq.uniqueitem_id,
                       ceil((uf.daysincircprevissue + (trunc(sysdate) - uf.lastissuedate))/7) weeks_in_circ,
                       case
                         when floor(ceil((uf.daysincircprevissue + (trunc(sysdate) - uf.lastissuedate))/7) / rp.number_value3) + 1 > 9
                           then 9
                           else floor(ceil((uf.daysincircprevissue + (trunc(sysdate) - uf.lastissuedate))/7) / rp.number_value3) + 1
                       end weekscolumnnr,
                       uq.washestotal,
                       case
                         when floor(uq.washestotal / rp.number_value3) + 1 > 9
                           then 9
                           else floor(uq.washestotal / rp.number_value3) + 1
                       end washescolumnnr, cu.customernumber, cu.name customername
                  from uniqueitem        uq,
                       uniqueitemfixedinfo uf,
                       businessunit      bu,
                       product           prd,
                       productgroup      pg,
                       systemuser        su,
                       reportparam       rp,
                       distributionpoint dp, department de, customer cu
                 where rp.number_value5 = cu.customernumber
                   and uq.relatedcustomer_id is not null
                   and uq.distributionpoint_id = dp.distributionpoint_id
                   and dp.department_id = de.department_id
                   and de.customer_id = cu.customer_id
                   and uq.poolitem = 1
                   and uf.uniqueitem_id = uq.uniqueitem_id
                   and prd.product_id = uq.product_id
                   and prd.uniquepoolitem = 'Y'
                   and pg.productgroup_id = prd.productgroup_id
                   and uq.status_id in
                       (select s1.status_id
                          from status s1
                         where s1.statustype = 'UI'
                           and s1.code in ('20', '30'))
                   and bu.businessunit_id = uq.businessunit_id
                   and bu.code >= rp.string_value1
                   and bu.code <= rp.string_value2
                   and pg.code >= rp.string_value3
                   and pg.code <= rp.string_value4
                   and prd.code >= rp.string_value5
                   and prd.code <= rp.string_value6
                   and (trunc(sysdate) - trunc(uq.lastscandate)) <= rp.number_value4
                   and su.systemuser_id = rp.number_value
                   and bu.businessunit_id in (select bug.businessunit_id from businessunitsperusergroup bug where bug.usergroup_id = su.usergroup_id)
                   ) x
         group by x.reportparam_id, x.showagebyweeks, x.product_id, x.sizedefinition_id, x.customernumber, x.customername) q
         join sizedefinition s on q.sizedefinition_id = s.sizedefinition_id
         join product p
              join productgroup pg on p.productgroup_id = pg.productgroup_id
         on q.product_id = p.product_id
cross join languages lan
/

  CREATE OR REPLACE VIEW "V_AGEDAMOUNTVSTOTALSALES1" ("CURRENT_AMOUNT", "AMOUNT_30", "AMOUNT_60", "AMOUNT_90", "AMOUNT_120", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_ID", "ROUTE_ID", "ROUTE_NR", "ROUTE_DESC", "DAY", "DEPOT_CODE", "DEPOT_DESC", "BU_CODE", "BU_DESC", "BUSINESSUNIT_ID", "REPORTPARAM_ID", "MONTH_AR", "YEAR_AR", "STOPNUMBER") AS 
  select /*version 2.0*/ distinct
       f_getaragingamount(c.customer_id, rp.number_value, 0, rp.date_value1, rp.date_value2, rp.date_value3, rp.date_value4, a.route_id) current_amount,
       f_getaragingamount(c.customer_id, rp.number_value, 1, rp.date_value1, rp.date_value2, rp.date_value3, rp.date_value4, a.route_id) amount_30,
       f_getaragingamount(c.customer_id, rp.number_value, 2, rp.date_value1, rp.date_value2, rp.date_value3, rp.date_value4, a.route_id) amount_60,
       f_getaragingamount(c.customer_id, rp.number_value, 3, rp.date_value1, rp.date_value2, rp.date_value3, rp.date_value4, a.route_id) amount_90,
       f_getaragingamount(c.customer_id, rp.number_value, 4, rp.date_value1, rp.date_value2, rp.date_value3, rp.date_value4, a.route_id) amount_120,
       c.customernumber, c.name customername, c.customer_id, r.route_id, r.routenumber route_nr, r.description route_desc, r.drivingday_id day, d.code depot_code, d.description depot_desc,
       bu.code bu_code, bu.description bu_desc, bu.businessunit_id, rp.reportparam_id, month(a.artransactiondate) month_ar ,year(a.artransactiondate) year_ar,
       (select min(rs.stopnumber)
          from routestop rs
         where rs.route_id = r.route_id
           and rs.customer_id = c.customer_id) stopnumber
  from artransaction a
       join artransactiontype at on a.artransactiontype_id = at.artransactiontype_id
       join customer_link c on a.deltocustomer_link_id = c.customer_id
       join route r
            left join depot d on r.depot_id = d.depot_id and r.plant_id = d.plant_id
       on a.route_id = r.route_id
       join businessunit bu on a.businessunit_id = bu.businessunit_id
       cross join reportparam rp
 where a.debitcredit = 'D'
   and at.typenumber in (1,3)
/

  CREATE OR REPLACE VIEW "V_AGEDAMOUNTVSTOTALSALES2" ("CURRENT_AMOUNT", "AMOUNT_30", "AMOUNT_60", "AMOUNT_90", "AMOUNT_120", "OUTSTANDINGBALANCE", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_ID", "CHAIN_CODE", "CHAIN_NAME", "BU_CODE", "BU_DESC", "BUSINESSUNIT_ID", "REPORTPARAM_ID", "MONTH_AR", "YEAR_AR") AS 
  select /*version 2.0*/ distinct
       f_getaragingamount(c.customer_id, rp.number_value, 0, rp.date_value1, rp.date_value2, rp.date_value3, rp.date_value4) current_amount,
       f_getaragingamount(c.customer_id, rp.number_value, 1, rp.date_value1, rp.date_value2, rp.date_value3, rp.date_value4) amount_30,
       f_getaragingamount(c.customer_id, rp.number_value, 2, rp.date_value1, rp.date_value2, rp.date_value3, rp.date_value4) amount_60,
       f_getaragingamount(c.customer_id, rp.number_value, 3, rp.date_value1, rp.date_value2, rp.date_value3, rp.date_value4) amount_90,
       f_getaragingamount(c.customer_id, rp.number_value, 4, rp.date_value1, rp.date_value2, rp.date_value3, rp.date_value4) amount_120,
       f_getaragingamount(c.customer_id, rp.number_value, 0, rp.date_value1, rp.date_value2, rp.date_value3, rp.date_value4) +
       f_getaragingamount(c.customer_id, rp.number_value, 1, rp.date_value1, rp.date_value2, rp.date_value3, rp.date_value4) +
       f_getaragingamount(c.customer_id, rp.number_value, 2, rp.date_value1, rp.date_value2, rp.date_value3, rp.date_value4) +
       f_getaragingamount(c.customer_id, rp.number_value, 3, rp.date_value1, rp.date_value2, rp.date_value3, rp.date_value4) +
       f_getaragingamount(c.customer_id, rp.number_value, 4, rp.date_value1, rp.date_value2, rp.date_value3, rp.date_value4) outstandingbalance,
       c.customernumber, c.name customername, c.customer_id, ch.code chain_code, ch.name chain_name, bu.code bu_code, bu.description bu_desc,
       bu.businessunit_id, rp.reportparam_id, month(a.artransactiondate) month_ar ,year(a.artransactiondate) year_ar
  from artransaction a
       join artransactiontype at on a.artransactiontype_id = at.artransactiontype_id
       join customer c
            left join chain ch on c.chain_id = ch.chain_id
       on a.deltocustomer_link_id = c.customer_id
       join businessunit bu on a.businessunit_id = bu.businessunit_id
       cross join reportparam rp
 where a.closingtransaction_id is null
   and a.debitcredit = 'D'
   and at.typenumber in (1,3)
   and a.route_id is not null
/

  CREATE OR REPLACE VIEW "V_ALT_SUPLIER_PRODUCTS" ("PRIO", "SUPPLIERNUMBER", "NAME", "PURCHASEPRICE", "SUPPLYINGSTOCKROOM_ID", "CURRENCY_ID", "DELIVERYDAYS", "SUPPLIERDELDAY_ID", "MINORDERQTY", "BOXQUANTITY", "CALCULATEDQTY", "PRODUCT_CODE", "PROD_DESC", "SIZEDEFINITION_CODE", "PRODUCT_ID", "SIZEDEFINITION_ID", "SUPPLIERTYPE", "SUPPLIER_ID", "SUPPLIERPRODUCT_ID", "STOCKROOM_ID", "UNIQUEITEM") AS 
  SELECT /*version 2.0*/ distinct
1 prio,
  Supplier.SupplierNumber,
  Supplier.Name,
  (select spp.purchaseprice
    from supplierproductprice spp
    where spp.supplierproduct_id = supplierproduct.supplierproduct_id
    and  spp.startdate = (select max(x.startdate)
                     from supplierproductprice x
                     where x.supplierproduct_id = supplierproduct.supplierproduct_id
                     and  x.startdate <= sysdate)) as purchaseprice,
Supplier.Supplyingstockroom_Id,
Supplier.Currency_Id,
Supplierproduct.Deliverydays,
Supplierproduct.supplierdelday_id,
Supplierproduct.Minorderqty,
Supplierproduct.Boxquantity,
0 calculatedqty,
Supplierproductcode product_code,
Supplierproductdescription prod_desc,
Suppliersizecode SizeDefinition_code,
Productsizepersupproduct.Product_Id,
Productsizepersupproduct.Sizedefinition_Id,
Suppliertype,
Supplier.Supplier_Id,
Supplierproduct.Supplierproduct_Id, sr.stockroom_id,
Supplierproduct.uniqueitem
FROM SUPPLIERPRODUCT , SUPPLIER , PRODUCTSIZEPERSUPPRODUCT, stockroomsupplier sr
WHERE
 SUPPLIER.SUPPLIER_ID = SUPPLIERPRODUCT.SUPPLIER_ID
 and PRODUCTSIZEPERSUPPRODUCT.SUPPLIERPRODUCT_ID = SUPPLIERPRODUCT.SUPPLIERPRODUCT_ID
 and supplierproduct.supplier_id = sr.supplier_id
 and SUPPLIERPRODUCT.ACTIVE = 'Y'
 and SUPPLIER.SUPPLIERTYPE =1--ORDER BY SUPPLIER.SUPPLIERNUMBER, SUPPLIERPRODUCTCODE, SUPPLIERSIZECODE
UNION
/*select
(suppliernumber, suppliername, purchaseprice, currency_id, deliverydays, minorderqty, boxquantity, product_code, product_desc, sizedefinition_code, product_id, sizedefinition_id, suppliertype, supplier_id, stockroom_id)
AS*/
SELECT distinct
2 prio,
Supplier.SupplierNumber,
Supplier.Name,
Supplier.Supplyingstockroom_Id,
--Purchaserequest.purchaseprice ,
CASE (SELECT distinct STOCKVALUATIONMETHOD
      FROM QUALITYGRADE q
      WHERE q.QUALITYGRADE_ID = Purchaserequest.REQUESTEDGRADE_ID
      )
WHEN 0 THEN  --link with suplpierProduct, Standard (Historical purchase price)
F_PURCHASEPRICE ( Supplier.Supplier_Id,  Product.Product_Id, Productsize.SizeDefinition_ID, sysdate)
WHEN 1 THEN  --link with suplpierProduct, FIFO (First in First out)
F_PURCHASEPRICE ( Supplier.Supplier_Id,  Product.Product_Id, Productsize.SizeDefinition_ID, sysdate)
WHEN 2 THEN  --AVGPP (average purchase price)
(
SELECT t.avgpurchaseprice
FROM StockValueAVGPP t
WHERE t.transactiondate = (SELECT  MAX(s.transactiondate)
                           FROM StockValueAVGPP s, PRODUCT_LINK pl, SIZEDEFINITION_LINK sl, CUSTOMER_LINK cl
                           WHERE
                            s.product_link_id = pl.product_link_id
                            and s.sizedefinition_link_id = sl.sizedefinition_link_id
                            and s.customer_link_id = cl.customer_link_id
                            and pl.product_id = product.product_id
                            AND sl.sizedefinition_id = ProductSize.sizedefinition_id
                            AND cl.customer_id = purchaserequest.customer_id
                            AND s.customerowned in ('Y', 'N')
                            AND s.qualitygrade_id = purchaserequest.requestedgrade_id))
WHEN 3 THEN 0 --FSP (fixed settle price)
ELSE 0 END,
Supplier.Currency_ID,
supplier.defaultDeliveryDays,
supplier.defaultsupplierdelday_id,
1, --fixed minimum order qty
1, --fixed box qty
Purchaserequest.requestedstock + Purchaserequest.requesteddirectissue calculatedqty, --calculated qty
Product.CODE prod_code, '-' prod_desc,
(select sd.code from sizedefinition sd where sd.SizeDefinition_ID=productsize.SizeDefinition_ID) as SizeDefinition_code,
Product.Product_ID,
ProductSize.SizeDefinition_ID,
Suppliertype,
Supplier.Supplier_Id,0,
Purchaserequest.Stockroom_Id,
(select distinct sprod.uniqueitem from  Supplierproduct sprod, productsizepersupproduct psp
  where sprod.Supplier_Id = Supplier.Supplier_Id
    and sprod.Supplierproduct_Id = Purchaserequest.Supplierproduct_Id
    and psp.SupplierProduct_Id = sprod.SupplierProduct_Id
    and psp.SizeDefinition_id = Productsize.SizeDefinition_ID) as uniqueitem
FROM Purchaserequest , Supplier , Productsize, Product, stockroom str, stockroomsupplier sp
WHERE Product.Product_ID = PurchaseRequest.Product_ID
and  Purchaserequest.Stockroom_Id=str.stockroom_id
and sp.stockroom_id=str.stockroom_id
and sp.supplier_id=Supplier.Supplier_Id
--and Supplier.Supplier_Id=Product.Supplier_Id
and Productsize.Product_Id=Product.Product_Id
and ProductSize.SizeDefinition_ID = PurchaseRequest.SizeDefinition_ID
and Product.Active = 'Y'
and Product.RecordPassiveStock = 'Y'
and Supplier.SupplierType = 1
and supplier.supplyingstockroom_id <> str.stockroom_id
ORDER BY prio, SUPPLIERNUMBER
/

  CREATE OR REPLACE VIEW "V_AMOUNTOFPACKINGNOTES" ("DELIVERYDATE", "SALESAREA", "CUSTOMERNUMBER", "CUSTOMERNAME", "DELIVERYPOINTZIPCODE", "ROUTENUMBER", "TRANSPORTARTICLEDESCRIPTION", "NOTEQT", "CUSTOMER_REMARK", "THEORETICALWEIGHT") AS 
  select /*view v_amountofpackingnotes  version 0.4*/
 pk.deliverydate, max(sa.code) salesarea, c.customernumber, max(c.name) customername,
 dela.zipcode deliverypointzipcode, max(r.routenumber) routenumber,
 tad.description transportarticledescription, count(1) noteqt, max(c.remark) customer_remark,
 round(sum((select sum(nvl(p.theoreticalweight * pkl.deliveredamount, 0))
            from   packingnoteline pkl
            join   product p
            on     p.product_id = pkl.product_id
            where  pkl.packingnote_id = pk.packingnote_id)), 2) theoreticalweight
from   packingnote pk
join   deliverypoint delp
on     delp.deliverypoint_id = pk.deliverypoint_id
join   address dela
on     dela.address_id = delp.deliveryaddress_id
join   customer c
on     c.customer_id = delp.customer_id
join   salesarea sa
on     sa.salesarea_id = c.salesarea_id
join   transportarticle_desc tad
on     (tad.transportarticle_id = pk.transportarticle_id and tad.language_id = c.language_id)
left   outer join route r
on     r.route_id = pk.route_id
where  pk.status_id <> (select st.status_id
                        from   status st
                        where  st.statustype = 'PN'
                        and    st.code = '40')
group  by pk.deliverydate, c.customernumber, dela.zipcode, tad.description
/

  CREATE OR REPLACE VIEW "V_ANALYSISSTOCKTRANSACTION" ("BUSINESSUNIT_ID", "STOCKROOM_ID", "STCODE", "NAME", "REASCODE", "RCDESCRIPTION", "BUCODE", "MOYEAR", "TRANSACTIONTYPE_ID", "TRANSDESC", "TRANSACTIONDATE", "QUALITYGR", "QGPRIORITY", "QQCATEG", "PGCODE", "PRODCODE", "SIZECODE", "PRODDESC", "SIZEDESC", "QUANTITY", "CALCULATIONPRICE", "STOCKTRGRP", "LANGUAGECODE") AS 
  select sr.managedbybu_id businessunit_id, sr.stockroom_id, sr.code stcode, sr.name, r.code reascode,
       (select rd.description
          from reasoncode_desc rd
         where rd.reasoncode_id = r.reasoncode_id
           and rd.language_id = lan.language_id) rcdescription,
       (bu.code || ' / ' ||
        coalesce(cl.customernumber, cl1.customernumber) || ' ' ||
        coalesce(cl.name, cl1.name)) bucode,
       to_char(st.transactiondate, 'MM.YYYY') moyear, tt.transactiontype_id,
       (select ttd.description
          from transactiontype_desc ttd
         where ttd.transactiontype_id = tt.transactiontype_id
           and ttd.language_id = lan.language_id) transdesc, st.transactiondate, q.code qualitygr, q.priority qgpriority,
       (case when q.newgarment = 'Y' then 1
             when q.newgarment = 'N' and q.defectitem = 'N' then 2
             when q.newgarment = 'N' and q.defectitem = 'Y' then 3
         else 1 end) qqcateg, pg.code pgcode, p.code prodcode, s.code sizecode,
       (select pd.description
          from product_desc pd
         where pd.product_id = p.product_id
           and pd.language_id = lan.language_id) proddesc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = s.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc, st.quantity, st.calculationprice,
       (case
         when tt.transactiontype_id in (10, 12, 13, 15, 16, 18, 53, 400, 401, 402, 411) then
          'IN'
         when (tt.transactiontype_id = 84 and st.quantity > 0) then
          'IN'
         when tt.transactiontype_id in (22, 32, 40, 41, 44, 50, 54, 409, 102) then
          'OUT'
         when (tt.transactiontype_id = 84 and st.quantity < 0) then
          'OUT'
         when tt.transactiontype_id in (80, 81, 82, 93, 403, 404, 490) then
          'REST'
         else
          'REST'
       end) stocktrgrp, lan.code languagecode
  from stocktransaction st
  join stockreservationpergrade sg
       join stockdefinitionperitem sd
            join product p
                 join productgroup pg on p.productgroup_id = pg.productgroup_id
            on sd.product_id = p.product_id
            join sizedefinition s on sd.sizedefinition_id = s.sizedefinition_id
            join stockroom sr on sd.stockroom_id = sr.stockroom_id
       on sg.stockdefinitionperitem_id = sd.stockdefinitionperitem_id
       join qualitygrade q on sg.qualitygrade_id = q.qualitygrade_id
  on st.stockreservationpergrade_id = sg.stockreservationpergrade_id
  join reasoncode r on st.reasoncode_id = r.reasoncode_id
  join transactiontype tt on st.transactiontype_id = tt.transactiontype_id
  left outer join customer_link cl on st.returnedcustomer_link_id = cl.customer_link_id
  join workorder wo
       join customer_link cl1 on wo.customer_link_id = cl1.customer_link_id
       join businessunit bu on wo.businessunit_id = bu.businessunit_id
  on st.documentnumber = wo.workordernumber,
       languages lan
 where q.defectitem = 'N'
   and st.documenttype in (3, 6, 7, 8, 9, 10, 11)
union all
select sr.managedbybu_id businessunit_id, sr.stockroom_id, sr.code stcode, sr.name, r.code reascode,
       (select rd.description
          from reasoncode_desc rd
         where rd.reasoncode_id = r.reasoncode_id
           and rd.language_id = lan.language_id) rcdescription,
       (bu.code || ' / ' ||
        coalesce(cl.customernumber, cl1.customernumber) || ' ' ||
        coalesce(cl.name, cl1.name)) bucode,
       to_char(st.transactiondate, 'MM.YYYY') moyear, tt.transactiontype_id,
       (select ttd.description
          from transactiontype_desc ttd
         where ttd.transactiontype_id = tt.transactiontype_id
           and ttd.language_id = lan.language_id) transdesc, st.transactiondate, q.code qualitygr, q.priority qgpriority,
       (case when q.newgarment = 'Y' then 1
             when q.newgarment = 'N' and q.defectitem = 'N' then 2
             when q.newgarment = 'N' and q.defectitem = 'Y' then 3
         else 1 end) qqcateg, pg.code pgcode, p.code prodcode, s.code sizecode,
       (select pd.description
          from product_desc pd
         where pd.product_id = p.product_id
           and pd.language_id = lan.language_id) proddesc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = s.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc, st.quantity, st.calculationprice,
       (case
         when tt.transactiontype_id in (10, 12, 13, 15, 16, 18, 53, 400, 401, 402, 411) then
          'IN'
         when (tt.transactiontype_id = 84 and st.quantity > 0) then
          'IN'
         when tt.transactiontype_id in (22, 32, 40, 41, 44, 50, 54, 409, 102) then
          'OUT'
         when (tt.transactiontype_id = 84 and st.quantity < 0) then
          'OUT'
         when tt.transactiontype_id in (80, 81, 82, 93, 403, 404, 490) then
          'REST'
         else
          'REST'
       end) stocktrgrp, lan.code languagecode
  from stocktransaction st
  join stockreservationpergrade sg
       join stockdefinitionperitem sd
            join product p
                 join productgroup pg on p.productgroup_id = pg.productgroup_id
            on sd.product_id = p.product_id
            join sizedefinition s on sd.sizedefinition_id = s.sizedefinition_id
            join stockroom sr on sd.stockroom_id = sr.stockroom_id
       on sg.stockdefinitionperitem_id = sd.stockdefinitionperitem_id
       join qualitygrade q on sg.qualitygrade_id = q.qualitygrade_id
  on st.stockreservationpergrade_id = sg.stockreservationpergrade_id
  join reasoncode r on st.reasoncode_id = r.reasoncode_id
  join transactiontype tt on st.transactiontype_id = tt.transactiontype_id
  left outer join customer_link cl on st.returnedcustomer_link_id = cl.customer_link_id
  join packingnote pn
       join distributionpoint dp
            join department dep
                 join customer cl1 on dep.customer_id = cl1.customer_id
            on dp.department_id = dep.department_id
       on pn.distributionpoint_id = dp.distributionpoint_id
       join businessunit bu on pn.processbusinessunit_id = bu.businessunit_id
  on st.documentnumber = pn.notenumber,
       languages lan
 where q.defectitem = 'N'
   and st.documenttype = 12
union all
select bu.businessunit_id, sr.stockroom_id, sr.code stcode, sr.name, r.code reascode,
       (select rd.description
           from reasoncode_desc rd
          where rd.reasoncode_id = r.reasoncode_id
            and rd.language_id = lan.language_id) rcdescription,
       (bu.code || ' / ' || coalesce((select c.customernumber || ' ' || c.name from customer c where c.customer_id = st.returnedcustomer_link_id), ' ')) bucode,
       to_char(st.transactiondate, 'MM.YYYY') moyear, tt.transactiontype_id,
       (select ttd.description
          from transactiontype_desc ttd
         where ttd.transactiontype_id = tt.transactiontype_id
           and ttd.language_id = lan.language_id) transdesc, st.transactiondate, q.code qualitygr, q.priority qgpriority,
       (case when q.newgarment = 'Y' then 1
             when q.newgarment = 'N' and q.defectitem = 'N' then 2
             when q.newgarment = 'N' and q.defectitem = 'Y' then 3
         else 1 end) qqcateg, pg.code pgcode, p.code prodcode, s.code sizecode,
       (select pd.description
          from product_desc pd
         where pd.product_id = p.product_id
           and pd.language_id = lan.language_id) proddesc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = s.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc, st.quantity, st.calculationprice,
       (case
          when tt.transactiontype_id in (10, 12, 13, 15, 16, 18, 53, 400, 401, 402, 411) then
           'IN'
          when (tt.transactiontype_id = 84 and st.quantity > 0) then
           'IN'
          when tt.transactiontype_id in (22, 32, 40, 41, 44, 50, 54, 409, 102) then
           'OUT'
          when (tt.transactiontype_id = 84 and st.quantity < 0) then
           'OUT'
          when tt.transactiontype_id in (80, 81, 82, 93, 403, 404, 490) then
           'REST'
          else
           'REST'
        end) stocktrgrp, lan.code languagecode
  from stocktransaction st
  join stockreservationpergrade sg
       join stockdefinitionperitem sd
            join stockroom sr
                 join businessunit bu on sr.managedbybu_id = bu.businessunit_id
            on sd.stockroom_id = sr.stockroom_id
            join product p
                 join productgroup pg on p.productgroup_id = pg.productgroup_id
            on sd.product_id = p.product_id
            join sizedefinition s on sd.sizedefinition_id = s.sizedefinition_id
       on sg.stockdefinitionperitem_id = sd.stockdefinitionperitem_id
       join qualitygrade q on sg.qualitygrade_id = q.qualitygrade_id
  on st.stockreservationpergrade_id = sg.stockreservationpergrade_id
  join reasoncode r on st.reasoncode_id = r.reasoncode_id
  join transactiontype tt on st.transactiontype_id = tt.transactiontype_id,
       languages lan
 where q.defectitem = 'N'
   and st.documenttype not in (3, 6, 7, 8, 9, 10, 11, 12)
   and tt.transactiontype_id in (10, 12, 13, 15, 16, 18, 53, 400, 401, 402, 411, 84, 22, 32, 40, 41, 44, 50, 54, 409, 102, 80, 81, 82, 93, 403, 404, 490)
/

  CREATE OR REPLACE VIEW "V_APPENDIXCOSTSPERCLIENT" ("LINETYPE", "INVOICEHEADER_ID", "INVOICENUMBER", "INVOICEDATE", "ENDDATE", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "DELTOSTREET", "DELTOZIPCODE", "DELTOCITY", "CLIENTNUMBER", "CLIENTNAME", "CLIENTDELIVERYNOTENUMBER", "DELIVERYDATE", "CODE", "DESCRIPTION", "PRICE", "PRICE2", "DISCOUNTPERCENTAGE", "VATPERC", "QTYSCANNEDOUT", "QTYCOUNTEDOUT", "BU_CODE", "BU_DESC", "BU_VATNUMBER", "PLANT_NAME", "PLANT_STREET", "PLANT_ZIPCODE", "PLANT_CITY", "CURRENCY_CODE", "INVOICEAMOUNTDECIMALS", "DECIMALS", "LANGUAGECODE", "DEPARTMENTNUMBER", "DEPARTMENTDESCR") AS 
  select --Version 1.02
 y.linetype, x.invoiceheader_id, x.invoicenumber, x.invoicedate, x.enddate, x.deltocustomernumber,
 x.deltocustomername, x.deltostreet, x.deltozipcode, x.deltocity, x.clientnumber, x.clientname,
 x.clientdeliverynotenumber, x.deliverydate, x.code, x.description, x.price, x.price2,
 x.discountpercentage, x.vatperc, x.qtyscannedout, x.qtycountedout, x.bu_code, x.bu_desc,
 x.bu_vatnumber, x.plant_name, x.plant_street, x.plant_zipcode, x.plant_city, x.currency_code,
 x.invoiceamountdecimals, x.decimals, x.languagecode, x.departmentnumber, x.departmentdescr
from   (select ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.enddate,
                ih.deltocustomernumber, ih.deltocustomername, ih.deltostreet, ih.deltozipcode,
                ih.deltocity, cl.clientnumber, cl.name clientname, cdn.clientdeliverynotenumber,
                cdn.deliverydate, il.code, il.description, il.price,
                (select max(gw.price) /*max price only 1 pricetype is used!*/
                  from   customerresidentialsettings crs
                  join   generalwashprice gw
                  on     gw.generalpricelist_id = crs.enduserpricelist_id
                  where  crs.customer_id = ih.deltocustomer_link_id
                  and    gw.product_id = ilp.product_link_id
                  and    gw.sizedefinition_id = ilp.sizedefinition_link_id
                  and    gw.finishingmethod_id = ilp.finishingmethod_id
                  and    gw.startdate = (select max(x.startdate)
                                         from   generalwashprice x
                                         where  x.generalpricelist_id = gw.generalpricelist_id
                                         and    x.product_id = gw.product_id
                                         and    x.sizedefinition_id = gw.sizedefinition_id
                                         and    x.finishingmethod_id = gw.finishingmethod_id
                                         and    x.startdate <= ih.enddate
                                         and    x.pricetype = gw.pricetype)) price2,
                il.discountpercentage,
                case
                  when ih.parentinvoiceheader_id is not null and
                       ih.parentinvoiceheader_id <> ih.invoiceheader_id /*is Child Invoice*/
                   then
                   (select ilv.percentage
                    from   invoicelinevarious ilv
                    join   invoiceline il2
                    on     ilv.invoiceline_id = il2.invoiceline_id
                    where  il2.invoicelinetype_id = 18
                    and    il2.invoiceheader_id = ih.parentinvoiceheader_id
                    and    il2.code = il.taxgroupcode)
                  else
                   (select ilv.percentage
                    from   invoicelinevarious ilv
                    join   invoiceline il2
                    on     ilv.invoiceline_id = il2.invoiceline_id
                    where  il2.invoicelinetype_id = 18
                    and    il2.invoiceheader_id = il.invoiceheader_id
                    and    il2.code = il.taxgroupcode)
                end vatperc, cdl.qtyscannedout, cdl.qtycountedout, ibu.code bu_code,
                ibu.description bu_desc, ibu.vatnumber bu_vatnumber, pl.name plant_name,
                pla.street plant_street, pla.zipcode plant_zipcode, pla.city plant_city,
                curr.code currency_code, curr.invoiceamountdecimals, curr.decimals,
                lan.code languagecode,
                (select dep.departmentnumber
                  from   department dep
                  where  dep.department_id =
                         (select dr.department_id
                          from   departmentroom dr
                          where  dr.departmentroom_id =
                                 (select cr.departmentroom_id
                                  from   clientresident cr
                                  where  cr.client_id = cl.client_id))) departmentnumber,
                (select dep.description
                  from   department dep
                  where  dep.department_id =
                         (select dr.department_id
                          from   departmentroom dr
                          where  dr.departmentroom_id =
                                 (select cr.departmentroom_id
                                  from   clientresident cr
                                  where  cr.client_id = cl.client_id))) departmentdescr
         from   invoiceheader ih
         join   invoiceline il
         on     il.invoiceheader_id = ih.invoiceheader_id
         left   outer join invoicelineproduct ilp
         on     ilp.invoiceline_id = il.invoiceline_id
         join   currency curr
         on     ih.currency_id = curr.currency_id
         join   clientdeliverynoteline cdl
         on     cdl.invoiceline_id = il.invoiceline_id
         join   clientdeliverynote cdn
         on     cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
         join   client cl
         on     cl.client_id = cdn.client_link_id
         join   businessunit ibu
         on     ih.invoicebusinessunit_id = ibu.businessunit_id
         join   plant pl
         on     ibu.plant_id = pl.plant_id
         join   address pla
         on     pl.address_id = pla.address_id, languages lan
         where  (cl.budgetclient = 1 /*Self payer*/
                or exists (select 1
                           from   productlistpercustomer plpc
                           where  plpc.customer_id = ih.deltocustomer_link_id
                           and    plpc.product_id = cdl.product_link_id
                           and    plpc.sizedefinition_id = cdl.sizedefinition_link_id
                           and    plpc.finishingmethod_id = cdl.finishingmethod_id
                           and    plpc.dateactive <= cdn.deliverydate
                           and    plpc.dateinactive >= cdn.deliverydate
                           and    plpc.budgetusage = 1 /*Self paid*/
                           ))) x,
       (select d.daynumber linetype from day d where d.daynumber in (1, 2)) y
/

  CREATE OR REPLACE VIEW "V_APPENDIX_ACCEPTGIRO" ("INVOICEHEADER_ID", "INVOICEDATE", "INVOICENUMBER", "PAYTHISAMOUNT", "BILLTOCUSTOMERNAME", "DELTOCUSTOMERNUMBER", "INV_STREET", "INV_ZIPCODE", "INV_CITY", "PLANT_ID", "PLANT_CODE", "PLANT_NAME", "PLANT_STREET", "PLANT_CITY", "PLANT_ZIPCODE", "ACCEPTGIROREFERENCE", "ACCEPTGIROCODELINE", "LNDRY_BNK_DESC", "LNDRY_BNK_ZIPCODE", "LNDRY_BNK_STREET", "LNDRY_BNK_CITY", "BNK_IDCODE", "BNK_DESC", "BNK_INTERNID", "BNK_IBANNO", "LAUNDRYBNK_INTERNID", "LAUNDRYBNK_IBANNO", "ACCEPTGIROFORMAT", "CREDITSQUEEZEPERC", "INVOICELAYOUTCODE", "PAYMENTDISCOUNT", "PAYMENTDISCOUNT2", "PAYMENTTERMSDESCRIPTION", "DISCOUNTDAYS", "DISCOUNTDAYS2", "GENERALINV_REMARK_PLANT", "GENERALINV_REMARK_CUSTOMER", "NETPAYMENTDAYS", "CREDITSQUEEZEAMOUNT", "BILLTOCUSTOMERNUMBER", "BILLTOSENDINVOICETO", "PAYAMOUNT12CHAR") AS 
  select h.invoiceheader_id, h.invoicedate, h.invoicenumber, h.paythisamount, h.billtocustomername, h.deltocustomernumber,
       h.street inv_street, h.zipcode inv_zipcode, h.city inv_city,
       pl.plant_id, pl.code plant_code, pl.name plant_name, pa.street plant_street, pa.city plant_city, pa.zipcode plant_zipcode,
       ihe.acceptgiroreference, ihe.acceptgirocodeline,
       lbi.description lndry_bnk_desc, ba.zipcode lndry_bnk_zipcode, ba.street lndry_bnk_street, ba.city lndry_bnk_city,
       bi.idcode bnk_idcode, bi.description bnk_desc, bi.internalidcode bnk_internID, bi.ibanno bnk_ibanno,
       lbi.internalidcode laundrybnk_internID, lbi.ibanno  laundrybnk_ibanno,
       ss.value ACCEPTGIROFORMAT
       , h.creditsqueezeperc
       , ihe.formlayoutcode INVOICELAYOUTCODE --todo 4799
       , ihe.paymentdiscount, ihe.paymentdiscount2, ihe.paymenttermsdescription
       , ihe.discountdays, ihe.discountdays2
       , (SELECT pldesc.invoiceremark FROM plantinvoiceremark_desc pldesc
          where pldesc.plant_id = pl.plant_id and pldesc.language_id = pl.language_id) GENERALINV_REMARK_PLANT
       , (SELECT pldesc.invoiceremark FROM plantinvoiceremark_desc pldesc
          where pldesc.plant_id = pl.plant_id and pldesc.language_id = (SELECT C.LANGUAGE_ID
                     FROM CUSTOMER C WHERE C.CUSTOMER_ID = h.DELTOCUSTOMER_LINK_ID)) GENERALINV_REMARK_CUSTOMER
       , h.netpaymentdays, h.creditsqueezeamount --end todo 4799
       , h.billtocustomernumber
       ,(select c.sendinvoiceto from customer c where h.deltocustomer_link_id = c.customer_id) billtosendinvoiceto
       ,(castnumberasvarcharwithformat((h.paythisamount*100),'000000000000') ||'<') payamount12char
from invoiceheader h, businessunit bu, plant pl, address pa, systemsetting ss,
     invoiceheaderextrainfo ihe
         left outer join
              (bankinstitution lbi left outer join address ba on ba.address_id = lbi.address_id)
            on lbi.bankinstitution_id = ihe.laundrybankinstitution_id
         left outer join bankinstitution bi on bi.bankinstitution_id = ihe.bankinstitution_id
where h.invoiceheader_id = ihe.invoiceheader_id
      and h.invoicebusinessunit_id = bu.businessunit_id
      and bu.plant_id = pl.plant_id
      and pa.address_id = pl.address_id
      and ss.plant_id = bu.plant_id and ss.name = 'ACCEPTGIROFORMAT'
/

  CREATE OR REPLACE VIEW "V_ARAGEDTRIALBALANCEPERROUTE" ("BUSINESSUNITCODE", "BUSINESSUNITDESC", "CHAINCODE", "DEPOTCODE", "DEPOTDESC", "ROUTENUMBER", "ROUTEDESC", "ARTRANSACTIONDATE", "DRIVINGDAY_ID", "PAYMENTMETHOD", "AMOUNT", "DEBITCREDIT", "DAYSNO", "DELINQUENT", "SYSTEMUSER_ID") AS 
  select bu.code businessunitcode, bu.description businessunitdesc,
  ch.code chaincode,
  dp.code depotcode, dp.description depotdesc,
  ru.routenumber, ru.description routedesc,
  ar.artransactiondate, ru.drivingday_id, bcu.paymentmethod,
  ar.amount, ar.debitcredit,
  (trunc(sysdate) - ar.artransactiondate) daysno,
  (select COUNT(*) from artransaction ar2 where ar2.billtocustomer_link_id = bcu.customer_id and ar2.closingtransaction_id is null
     and trunc(sysdate) - ar2.artransactiondate >= cbi.delinquentmarkafter) delinquent,
  su.systemuser_id
from artransaction ar, businessunit bu, systemuser su, customer bcu, chain ch, route ru, depot dp,
  customerbillinginfo cbi
where ar.businessunit_id = bu.businessunit_id
  and ar.closingtransaction_id is null
  and (ar.parentartransaction_id is null or ar.parentartransaction_id = ar.artransaction_id)
  and ar.billtocustomer_link_id = bcu.customer_id
  and bcu.chain_id = ch.chain_id
  and ar.route_id = ru.route_id
  and ru.depot_id = dp.depot_id
  and bcu.customer_id = cbi.customer_id
  and exists (select * from businessunitsperusergroup bug where su.usergroup_id = bug.usergroup_id and bu.businessunit_id = bug.businessunit_id)
/

  CREATE OR REPLACE VIEW "V_ARBALANCES" ("ARBALANCEID", "BUSINESSUNITID", "BUSINESSUNITCODE", "BUSINESSUNITDESCRIPTION", "ENDDATE", "STARTDATE", "STARTBALANCE", "ENDBALANCE", "INVOICEAMOUNT", "PAYMENTAMOUNT", "DISCOUNTAMOUNT", "MISCPLUSAMOUNT", "MISCMINUSAMOUNT") AS 
  select
  ARBalance.ARBALANCE_ID arbalanceID,ARBalance.BUSINESSUNIT_ID businessunitID
, businessunit.code businessunitCode, businessunit.description businessunitdescription
, ARBalance.ENDDATE enddate,ARBalance.STARTDATE startdate
, ARBalance.STARTBALANCE startbalance,ARBalance.ENDBALANCE endbalance
, ARBalance.INVOICEAMOUNT invoiceamount,ARBalance.PAYMENTAMOUNT paymentamount
, ARBalance.DISCOUNTAMOUNT discountamount, ARBalance.MISCPLUSAMOUNT miscplusamount
, ARBalance.MISCMINUSAMOUNT miscminusamount
from
ARBalance, businessunit
where
ARBalance.Businessunit_Id = businessunit.businessunit_id
/

  CREATE OR REPLACE VIEW "V_ARINVOICEDETAILS" ("BUSINESSUNITCODE", "PRCBUSINESSUNITCODE", "INVOICEFREQUENCYNUMBER", "INVOICEHEADER_ID", "PARENTINVOICEHEADER_ID", "ARTRANSACTIONDATE", "CONSOLIDATEDYN", "CLUSTERCODE", "BILLTONUMBER", "BILLTOCITY", "BILLTOCHAINCODE", "BILLTOCHAINNAME", "DELTONUMBER", "DELTONAME", "DELTOCITY", "TURNOVERDESC", "TURNOVERCODE", "LEDGERACCOUNTSNUMBER", "LEDGERACCOUNTSDESC", "INVOICENUMBER", "INVOICEDATE", "PARENTINVOICEDATE", "PARENTINVOICENUMBER", "PARENTTOTALAMOUNT", "PARENTTOTALAMOUNTEXCLVAT", "TOTALAMOUNT", "TOTALAMOUNTEXCLVAT", "TOTALTAXAMOUNT", "TURNOVERAMOUNT", "LEDGERACCOUNTSAMOUNT", "EXPORTSTATUS", "CURRENCYCODE", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE", "TURNOVERGROUP_ID", "LEDGERACCOUNTS_ID", "ARTRANSACTION_ID", "BUSINESSUNIT_ID", "SYSTEMUSER_ID") AS 
  select /*version 2.1*/
       bu.code businessunitcode, pbu.code prcbusinessunitcode, infq.invoicefrequencynumber,
       ih.invoiceheader_id, ih.parentinvoiceheader_id, ar.artransactiondate artransactiondate,
       (case ih.parentinvoiceheader_id
          when ih.invoiceheader_id then 'Y'
          else 'N' end) consolidatedyn,
       coalesce(clu.code, ' ') clustercode, billto.customernumber billtonumber,
       bilad.city billtocity, bilch.code billtochaincode, bilch.name billtochainname,
       coalesce(ih.deltocustomernumber, ih.billtocustomernumber) deltonumber,
       coalesce(ih.deltocustomername, ih.billtocustomername) deltoname,
       coalesce(ih.deltocity, ih.city) deltocity,
       (select tgd.description
          from turnovergroup_desc tgd
         where tgd.turnovergroup_id = tgr.turnovergroup_id
           and tgd.language_id = lan.language_id) turnoverdesc,
       tgr.code turnovercode, coalesce(lgr.accountnumber, -1) ledgeraccountsnumber,
       lgr.description ledgeraccountsdesc, ih.invoicenumber, ih.invoicedate invoicedate,
       nvl(pih.invoicedate, ih.invoicedate) parentinvoicedate, nvl(pih.invoicenumber, ih.invoicenumber) parentinvoicenumber,
       nvl((select sum(arp.amount)
              from artransaction arp
             where arp.invoiceheader_id = ih.parentinvoiceheader_id)
          , ar.amount) parenttotalamount,
       nvl(pih.totalamountexclvat, ih.totalamountexclvat) parenttotalamountexclvat,
       ar.amount totalamount, ih.totalamountexclvat,
       (ar.amount - ih.totalamountexclvat) totaltaxamount, ard.amount turnoveramount,
       arl.amount ledgeraccountsamount, ar.exportstatus, cur.code currencycode,
       cur.invoiceamountdecimals, lan.code languagecode, tgr.turnovergroup_id,
       lgr.ledgeraccounts_id, arl.artransaction_id, arl.businessunit_id, su.systemuser_id
  from artransaction ar
       left join artransledgeraccounts arl
            join ledgeraccounts lgr on arl.ledgeraccounts_id = lgr.ledgeraccounts_id
       on ar.artransaction_id = arl.artransaction_id
       join invoiceheader ih
            left join customercluster clu on ih.cluster_id = clu.cluster_id
            left join invoiceheader pih on ih.parentinvoiceheader_id = pih.invoiceheader_id
            join invoicefrequency infq on ih.invoicefrequency_id = infq.invoicefrequency_id
       on ar.invoiceheader_id = ih.invoiceheader_id
       join currency cur on ar.currency_id = cur.currency_id
       join businessunit bu on ar.businessunit_id = bu.businessunit_id
       join businessunit pbu on ar.processbusinessunit_id = pbu.businessunit_id
       join artransactiontype artt on ar.artransactiontype_id = artt.artransactiontype_id
       join customer billto
            left join chain bilch on billto.chain_id = bilch.chain_id
            join address bilad on billto.visitaddress_id = bilad.address_id
       on ar.billtocustomer_link_id = billto.customer_id
       join artransactiondetail ard
            join turnovergroup tgr on ard.turnovergroup_id = tgr.turnovergroup_id
       on ar.artransaction_id = ard.artransaction_id
       cross join languages lan
       cross join systemuser su
 where artt.typenumber = 1
   and artt.debitcredit = 'D'
   and exists (select 1
                 from businessunitsperusergroup bug
                where bug.businessunit_id = ar.businessunit_id
                  and bug.usergroup_id = su.usergroup_id)
   and exists (select 1
                 from businessunitsperusergroup pbug
                where pbug.businessunit_id = ar.processbusinessunit_id
                  and pbug.usergroup_id = su.usergroup_id)
/

  CREATE OR REPLACE VIEW "V_ARTRANSACTION" ("ARTRANSACTIONID", "ARBALANCEID", "BUSINESSUNITCODE", "BUSINESSUNITDESC", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "ARTRANSACTIONDATE", "DEBITCREDIT", "ARTRANSACTIONTYPENUMBER", "ARTRANSACTIONTYPECODE", "ARTRANSACTIONTYPEDESC", "CURRENCYCODE", "CURRENCYDECIMALS", "INVOICEAMOUNTDECIMALS", "CURRENCYDESC", "AMOUNT", "ROUTENUMBER", "ROUTEDESC", "PAYMENTTYPE", "REMARK", "REMITIDENTIFICATION", "INVOICENUMBER", "REMITBATCHNUMBER", "REMITBATCHDATE", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  select
  a.artransaction_id artransactionID,a.arbalance_id arbalanceID, c.code businessunitcode
, c.description businessunitdesc, billto.customernumber billtocustomernumber
, billto.name billtocustomername, delto.customernumber deltocustomernumber
, delto.name deltocustomername, a.artransactiondate, a.debitcredit, b.typenumber artransactiontypenumber
, b.code artransactiontypecode
,(SELECT description FROM artransactiontype_desc f WHERE f.artransactiontype_id = a.artransactiontype_id
  AND f.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) artransactiontypedesc
, d.code currencycode, d.decimals currencyDecimals, d.invoiceamountdecimals, d.description currencydesc
, a.amount, r.routenumber, r.description routedesc
, a.paymenttype, a.remark, a.remitidentification, a.invoicenumber
, e.batchnumber remitbatchnumber, e.batchdate remitbatchdate
--, a.closingtransaction_id closingtransactionnumber, a.closingamount, a.closingdate
, a.systemuser_id, a.timestamp, languages.code languagecode
from
artransaction a
  left outer join route r on(r.route_id = a.route_id)
  left outer join customer_link delto on(a.deltocustomer_link_id = delto.customer_link_id)
  left outer join remitbatch e on(a.remitbatch_id = e.remitbatch_id)
, artransactiontype b, businessunit c, customer_link billto
, currency d, languages
where
    a.artransactiontype_id = b.artransactiontype_id
and a.businessunit_id = c.businessunit_id
and a.billtocustomer_link_id = billto.customer_link_id
and a.currency_id = d.currency_id
/

  CREATE OR REPLACE VIEW "V_ARTRANSACTIONDETAIL" ("INVOICENUMBER", "ARTRANSACTIONDATE", "BUSINESSUNITCODE", "BUSINESSUNITDESC", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "CURRENCYCODE", "CURRENCYDESC", "PAYMENTTYPE", "AMOUNT", "TURNOVERGROUPCODE", "TURNOVERGROUPDESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  select a.invoicenumber,a.artransactiondate, c.code businessunitcode, c.description businessunitdesc,
 billto.customernumber billtocustomernumber, billto.name billtocustomername,
 delto.customernumber deltocustomernumber, delto.name deltocustomername,
 d.code currencycode, d.description currencydesc, a.paymenttype, b.amount,
 x.code turnovergroupcode,
 (SELECT description FROM turnovergroup_desc e WHERE e.turnovergroup_id = b.turnovergroup_id
  AND e.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) turnovergroupdescription,
 b.systemuser_id, b.timestamp, languages.code languagecode
from artransaction a
 left outer join customer_link delto on (a.deltocustomer_link_id = delto.customer_link_id),
 artransactiondetail b, businessunit c, customer_link billto,
 currency d, turnovergroup x, languages
where a.artransaction_id = b.artransaction_id
 and a.businessunit_id = c.businessunit_id
 and a.billtocustomer_link_id = billto.customer_link_id
 and a.currency_id = d.currency_id
 and b.turnovergroup_id = x.turnovergroup_id
/

  CREATE OR REPLACE VIEW "V_ARTRANSACTIONTYPE" ("TYPENUMBER", "CODE", "DESCRIPTION", "FACTORYDESCRIPTION", "DEBITCREDIT", "LEGACYCODE", "PREDEFINED", "SYSTEMUSER_ID", "TIMESTAMP", "ARTRANSACTIONTYPE_ID", "LANGUAGECODE") AS 
  select typenumber, artransactiontype.code,
 (SELECT description FROM artransactiontype_desc a WHERE a.artransactiontype_id = artransactiontype.artransactiontype_id
  AND a.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) DESCRIPTION,
 factorydescription, debitcredit, legacycode, predefined, artransactiontype.systemuser_id,
 artransactiontype.timestamp, artransactiontype_id, languages.code languagecode
from artransactiontype, languages
/

  CREATE OR REPLACE VIEW "V_ASSEMBLEPACKS" ("PLANTDEPARTMENT_ID", "DELIVERYDATE", "PRODUCTIONDATE", "SEQUENCENUMBER", "NOTENUMBER", "PACKINGNOTE_ID", "DELIVERYPOINT_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CHAINCODE", "CHAINNAME", "RANKING", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINT_ID", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "PACKINGNOTELINE_ID", "ASSEMBLEDQUANTITY", "TOBEDELIVEREDAMOUNT", "TODOQUANTITY", "PRODUCT_ID", "PRODUCTCODE", "SIZEDEFINITION_ID", "SIZECODE", "FINISHINGMETHOD_ID", "FINMETHODCODE", "FINMETHCOLOR", "PROCESSBUSINESSUNIT_ID", "INTERNALPROCESSINGBU_ID") AS 
  SELECT pn.plantdepartment_id, pn.deliverydate, pn.productiondate, pn.sequencenumber
       , pn.notenumber, pn.packingnote_id, pn.deliverypoint_id
       , c.customer_id, c.customernumber, c.name customerName, ch.code chainCode, ch.name chainName, cr.ranking
       , dep.department_id, dep.departmentnumber, dep.description departmentDescription
       , dp.distributionpoint_id, dp.distributionpointnumber, dp.description distributionPointDescription
       , pnl.packingnoteline_id, pnl.assembledquantity, pnl.tobedeliveredamount, (pnl.tobedeliveredamount - pnl.assembledquantity) toDoQuantity
       , pnl.product_id, p.code productCode, pnl.sizedefinition_id, s.code sizeCode, pnl.finishingmethod_id, f.code finMethodCode
       , f.color finMethColor, pn.processbusinessunit_id, pn.internalprocessingbu_id
FROM packingnote pn, packingnoteline pnl
     , distributionpoint dp, department dep
     , product p, sizedefinition s, finishingmethod f
     , customer c LEFT OUTER JOIN chain ch ON ch.chain_id = c.chain_id
                  LEFT OUTER JOIN customerranking cr ON cr.customerranking_id = c.customerranking_id
WHERE pn.packingnote_id = pnl.packingnote_id
      AND pn.status_id IN (SELECT status_id FROM status WHERE status.statustype = 'PN' AND (status.code IN ('10', '20'))) -- status New or In Progress
      AND pnl.assembledquantity < pnl.tobedeliveredamount
      AND pn.distributionpoint_id = dp.distributionpoint_id
      AND dp.department_id = dep.department_id
      AND dep.customer_id = c.customer_id
      AND pnl.product_id = p.product_id
      AND pnl.sizedefinition_id = s.sizedefinition_id
      AND pnl.finishingmethod_id = f.finishingmethod_id
      AND p.packtype = 2 --OR Ppack
/

  CREATE OR REPLACE VIEW "V_ASSIGNEDGARMENTS" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "WEARERNUMBER", "WEARERNAME", "DATEACTIVE", "PRIMARYID", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "ASSIGNDATE", "STARTRENTFROM", "ISSUEDATE", "SIZEDESC", "REASONCODE", "REASONDESC", "DEFAULTBUSINESSUNIT_ID", "LANGUAGECODE") AS 
  select
  cu.customernumber, cu.name customerName, address.city, dep.departmentnumber, dep.description departmentDesc
, we.wearernumber, we.fullname wearerName, we.dateactive, uq.primaryid, prd.code productCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, sz.code sizeCode, uq.StayChangeDate AssignDate, uq.startrentfrom, uqfx.lastissuedate issuedate
, ( select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sz.sizedefinition_id
  and sdd.language_id = languages.language_id ) sizeDesc
, reasoncode.code reasoncode
, ( select reasoncode_desc.description from reasoncode_desc where reasoncode_desc.reasoncode_id = reasoncode.reasoncode_id
  and reasoncode_desc.language_id = languages.language_id ) reasonDesc
, uq.businessunit_id defaultbusinessunit_id , languages.code languageCode
from
  uniqueitem uq, status, uniqueitemfixedinfo uqfx, uniqueitemnonpool uqnp
, weareremployment wemp, wearer we, distributionpoint dip, department dep, customer cu, address
, product prd, sizedefinition sz, reasoncode
, languages
where
    uq.status_id = status.status_id
and status.statustype = 'UI'
    and status.code = '30'
and uq.uniqueitem_id = uqfx.uniqueitem_id
and uq.uniqueitem_id = uqnp.uniqueitem_id
    and uqnp.weareremployment_id = wemp.weareremployment_id
        and wemp.wearer_id = we.wearer_id
        and wemp.distributionpoint_id = dip.distributionpoint_id
            and dip.department_id = dep.department_id
                and dep.customer_id = cu.customer_id
                    and cu.visitaddress_id = address.address_id
and uq.product_id = prd.product_id
and uq.sizedefinition_id = sz.sizedefinition_id
and uqfx.reasoncode_id = reasoncode.reasoncode_id
/

  CREATE OR REPLACE VIEW "V_AUTOREPLACEUNIQUEITEM" ("UNIQUEITEM_ID", "CUSTOMER_ID", "WEARERNUMBER", "PRODUCT_ID", "SIZEDEFINITION_ID", "PRIMARYID", "ENDDATEFULLRENT", "DAYSINCIRC", "NROFWASHES", "NROFREPAIRS") AS 
  select ui.uniqueitem_id Uniqueitem_ID,
(select w.customer_id from weareremployment we, wearerinventory wi, wearer w where
np.wearerinventory_id=wi.wearerinventory_id and
wi.weareremployment_id=we.weareremployment_id and
we.wearer_id=w.wearer_id) Customer_ID,
(select w.wearernumber from weareremployment we, wearerinventory wi, wearer w where
np.wearerinventory_id=wi.wearerinventory_id and
wi.weareremployment_id=we.weareremployment_id and
we.wearer_id=w.wearer_id) WearerNumber,
ui.product_id Product_ID,
ui.sizedefinition_id Sizedefinition_ID,
ui.primaryid PrimaryID,
fi.enddatefullrent EndDateFullRent,
(fi.Daysincircprevissue + ((select trunc (sysdate) from dual) - fi.lastissuedate + 1)) DaysInCirc,
(ui.washestotal+np.washesthisissue) NrOfWashes,
(ui.repairstotal+np.repairsthisissue) NrOfRepairs
 from uniqueitem ui, uniqueitemfixedinfo fi, uniqueitemnonpool np
 where ui.uniqueitem_id=fi.uniqueitem_id
 and ui.uniqueitem_id=np.uniqueitem_id
 and not exists (select * from uniqueitemflag uif where uif.uniqueitem_id=np.uniqueitem_id
                                                  and uif.flag_id=(select a.flag_id from automaticflag a where a.automaticflag_id=2))
/

  CREATE OR REPLACE VIEW "V_AVAILABLEBUNDLES" ("UNIQUEBUNDLE_ID", "PACKINGSEQUENCE", "BUSINESSUNIT_ID", "PACKINGNOTELINE_ID", "DELIVERYDATE", "DAYNUMBER", "PLANTDEPARTMENTCODE", "PLANTDEPARTMENTDESC", "DEPOTCODE", "DEPOTDESC", "ROUTENUMBER", "ACTIVITYCODE", "ACTIVITYDESC", "PRODUCTCODE", "PRODUCTDESC", "PRODUCTGROUPCODE", "PRODUCTGROUPDESC", "SIZECODE", "TOBEDELIVEREDAMOUNT", "QUANTITY", "NOOFPACKINGNOTELINES", "LANGUAGECODE", "REPORTPARAM_ID") AS 
  select ub.uniquebundle_id,
  pnl.packingsequence,
  ub.businessunit_id, pnl.packingnoteline_id,
  pn.deliverydate, pn.daynumber,
  pd.code plantdepartmentcode, pd.description plantdepartmentdesc,
  de.code depotcode, de.description depotdesc,
  ru.routenumber,
  ac.code activitycode,
  (select acd.description from activity_desc acd where acd.activity_id = ac.activity_id
    and acd.language_id = languages.language_id) activitydesc,
  pr.code productcode,
  (select prd.description from product_desc prd where prd.product_id = pr.product_id
    and prd.language_id = languages.language_id) productdesc,
  pg.code productgroupcode,
  (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pg.productgroup_id
    and pgd.language_id = languages.language_id) productgroupdesc,
  sz.code sizecode,
  pnl.tobedeliveredamount,
  ub.quantity,
  F_GETNOOFPACKINGNOTELINES(ub.uniquebundle_id, ub.businessunit_id, pd.plantdepartment_id, rp.reportparam_id) NOOFPACKINGNOTELINES,
  languages.code languagecode, rp.reportparam_id
from packingnote pn
    left outer join (route ru
      left outer join depot de on ru.depot_id = de.depot_id)
        on pn.route_id = ru.route_id and ru.active = 'Y',
  packingnoteline pnl, product pr, sizedefinition sz, uniquebundle ub, plantdepartment pd,
  productgroup pg, activity ac, status st, businessunit bu, status stb,
  languages, reportparam rp
where pn.packingnote_id = pnl.packingnote_id
  and pnl.product_id = pr.product_id
  and pnl.sizedefinition_id = sz.sizedefinition_id
  and pnl.finishingmethod_id = ub.finishingmethod_id
  and pnl.sizedefinition_id = ub.sizedefinition_link_id
  and pnl.product_id = ub.product_link_id
  and ub.businessunit_id = bu.businessunit_id
  and ub.deliverynotenumber = 0
  and pn.processbusinessunit_id = bu.businessunit_id
  and bu.plant_id = pd.plant_id
  and pn.plantdepartment_id = pd.plantdepartment_id
  and pr.productgroup_id = pg.productgroup_id
  and pg.activity_id = ac.activity_id
  and pn.status_id = st.status_id
  and st.code in ('10', '20')
  and ub.status_id = stb.status_id
  and stb.code = '10'
/

  CREATE OR REPLACE VIEW "V_AVAILABLEBUNDLES_UB" ("BUSINESSUNIT_ID", "PRODUCT_ID", "SIZEDEFINITION_ID", "FINISHINGMETHOD_ID", "QUANTITY", "CNT") AS 
  select ub.businessunit_id,
  ub.product_link_id product_id, ub.sizedefinition_link_id sizedefinition_id, UB.FINISHINGMETHOD_ID,
  avg(ub.quantity) quantity, COUNT(ub.businessunit_id) cnt
from uniquebundle ub, status st
where ub.status_id = st.status_id
  and st.code = '10'
  and ub.deliverynotenumber = 0
group by ub.businessunit_id,
  ub.product_link_id, ub.sizedefinition_link_id, ub.quantity, UB.FINISHINGMETHOD_ID
/

  CREATE OR REPLACE VIEW "V_AVERAGESALES" ("INVOICEHEADER_ID", "BUSINESSUNITCODE", "INVOICEBUSINESSUNIT_ID", "INVOICEDATE", "ROUTENUMBER", "STOPNUMBER", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "DELTOSTREET", "DELTOZIPCODE", "DELTOCITY", "DELTOSTATE", "PAYTHISAMOUNT", "DRIVINGDAY_ID", "DAYCODE", "SYSTEMUSER_ID", "LANGUAGECODE") AS 
  select distinct ih.invoiceheader_id,
  bu.code businessunitcode, ih.invoicebusinessunit_id,
  ih.invoicedate,
  ih.routenumber, rs.stopnumber, --ih.stopnumber,
  ih.deltocustomernumber, ih.deltocustomername,
  ih.deltostreet, ih.deltozipcode, ih.deltocity, ih.deltostate,
  ih.paythisamount, ru.drivingday_id,
  (select dd.code from day_desc dd where ru.drivingday_id = dd.day_id
    and dd.language_id = languages.language_id) daycode,s.systemuser_id,
  languages.code languagecode
from invoiceheader ih
     left outer join route ru on ih.route_id = ru.route_id
     left outer join (stop
       left outer join routestop rs on stop.routestop_id = rs.routestop_id)
       on ih.stop_id = stop.stop_id,
  status st, businessunit bu,businessunitsperusergroup bus, usergroup u, systemuser s,
  languages
where ih.status_id = st.status_id
  and st.code = '2'
  and st.statustype = 'IN'
  and ih.invoicebusinessunit_id = bu.businessunit_id
  and ih.documenttype = 1
  and bu.businessunit_id=bus.businessunit_id
  and bus.usergroup_id=u.usergroup_id
  and u.usergroup_id=s.usergroup_id
/

  CREATE OR REPLACE VIEW "V_AVERAGESALES_INVH" ("INVOICEBUSINESSUNIT_ID", "ROUTENUMBER", "STOPNUMBER", "DELTOCUSTOMERNUMBER", "INVOICEDATE", "DELIVERYDATES") AS 
  SELECT IH.INVOICEBUSINESSUNIT_ID, IH.ROUTENUMBER, rs.stopnumber, --IH.STOPNUMBER,
  IH.DELTOCUSTOMERNUMBER, IH.INVOICEDATE,
  CAST(CONCATENATE3(GETMONTHASVARCHAR(IH.INVOICEDATE), '-', GETDAYASVARCHAR(IH.INVOICEDATE)) AS VARCHAR2(5)) DELIVERYDATES
FROM INVOICEHEADER IH
       left outer join (stop
         left outer join routestop rs on stop.routestop_id = rs.routestop_id)
       on ih.stop_id = stop.stop_id,
     status st
where (ih.deltocustomernumber is not null)
  and ih.status_id = st.status_id
  and st.code = '2'
/

  CREATE OR REPLACE VIEW "V_AVGCONTAINERSTAYATCUSTOMER" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DEFAULTBUSINESSUNIT_ID", "CONTAINERTYPECODE", "CONTAINERTYPEDESC", "PRIMARYID", "STAYCHANGEDATE", "C_DAYS", "LANGUAGECODE") AS 
  select
  cu.customernumber, cu.name customerName, address.city, de.departmentnumber, de.description departmentDesc
,  bu.businessunit_id defaultbusinessunit_id, cty.code containertypeCode
, (select containertype_desc.description from containertype_desc where containertype_desc.containertype_id = cty.containertype_id
  and containertype_desc.language_id = languages.language_id ) containertypeDesc
, ct.primaryid, ct.staychangedate
, coalesce((trunc(sysdate)-trunc(ct.staychangedate)), 0) C_Days
, languages.code languageCode
from
  container ct, containertype cty, distributionpoint dip, department de, customer cu
, stay, address,businessunit bu, languages
where
    ct.stay_id = stay.stay_id
and stay.staynr >= 20 and stay.staynr < 30
and ct.containertype_id = cty.containertype_id
and ct.distributionpoint_id = dip.distributionpoint_id
    and dip.department_id = de.department_id
        and de.customer_id = cu.customer_id
            and cu.visitaddress_id = address.address_id
             and (cu.defaultbusinessunit_id = bu.businessunit_id or
    exists (select 1 from customeractivities ca where
        (ca.processbusinessunit_id = bu.businessunit_id or ca.invoicebusinessunit_id=bu.businessunit_id
        or ca.internalprocessingbu_id=bu.businessunit_id)
        and ca.customer_id = cu.customer_id))
/

  CREATE OR REPLACE VIEW "V_BAGTAGS" ("INVOICENUMBER", "ROUTENUMBER", "DAYNR", "DRIVINGDATE", "PLANT_ID", "DELIVERYSCHEME", "STOPNUMBER", "DELTOCUSTOMERNUMBER", "DELTOSTREET", "DELTOSTREET2", "DELTOCITY", "DELTOSTATE", "DELTOZIPCODE", "PICKUP", "BAGTAGS", "BAGTAGSCOUNTER", "ROUTECONTROL_ID", "DELTOCUSTOMERNAME", "LANGUAGE_CODE") AS 
  select ih.invoicenumber,
       r.routenumber,
       getabsdaynumber(rc.drivingdate) daynr,
       rc.drivingdate,
       rc.plant_id,
       nvl(nvl(nvl((select min(ds.frequency) -- first try routestop linked to stop
                     from deliveryscheme ds, deliveryschemesperstop dsps
                    where dsps.routestop_id = rs1.routestop_id
                      and dsps.customer_id = ih.deltocustomer_link_id
                      and dsps.deliveryscheme_id = ds.deliveryscheme_id),
                   (select min(ds.frequency) -- then try 1st routestop for customer in route
                      from deliveryscheme ds, deliveryschemesperstop dsps
                     where dsps.routestop_id =
                           (select min(rs2.routestop_id)
                              from routestop rs2
                             where rs2.route_id = r.route_id
                               and rs2.customer_id = ih.deltocustomer_link_id)
                       and dsps.customer_id = ih.deltocustomer_link_id
                       and dsps.deliveryscheme_id = ds.deliveryscheme_id)),
               (select min(ds.frequency) -- then try 1st routestop for customer
                  from deliveryscheme ds, deliveryschemesperstop dsps
                 where dsps.routestop_id =
                       (select min(rs4.routestop_id)
                          from routestop rs4
                         where rs4.customer_id = ih.deltocustomer_link_id)
                   and dsps.customer_id = ih.deltocustomer_link_id
                   and dsps.deliveryscheme_id = ds.deliveryscheme_id)),
           1) deliveryscheme,
       ih.stopnumber,
       ih.deltocustomernumber,
       ih.deltostreet,
       ih.deltostreet2,
       ih.deltocity,
       ih.deltostate,
       ih.deltozipcode,
       (rc.drivingdate - 7) pickup,
       nvl(nvl(nvl(rs1.soiltickets, -- first try routestop linked to stop
                   (select max(rs5.soiltickets) -- then try 1st routestop for customer in route
                      from routestop rs5
                     where rs5.route_id = r.route_id
                       and rs5.customer_id = ih.deltocustomer_link_id)),
               (select max(rs6.soiltickets) -- then try 1st routestop for customer
                  from routestop rs6
                 where rs6.customer_id = ih.deltocustomer_link_id)),
           1) bagtags,
       --       rs1.soiltickets bagtags,
       c.nr bagtagscounter,
       rc.routecontrol_id,
       ih.deltocustomername,
(select lan.code from languages lan, customer cu where cu.customer_id = sp.customer_link_id and lan.language_id = cu.language_id) language_code
  from invoiceheader ih,
       routecontrol rc,
       route r,
       routestop rs1,
       stop sp,
       (select rownum nr
          from (select 1 just_a_column from dual connect by level <= 99)) c
 where ih.routecontrol_id = rc.routecontrol_id
   and r.route_id = rc.route_id
   and sp.stop_id = ih.stop_id
   and rs1.routestop_id(+) = sp.routestop_id -- outer join
   and c.nr <= --rs.soiltickets
          nvl(nvl(nvl(rs1.soiltickets, -- first try routestop linked to stop
                   (select max(rs5.soiltickets) -- then try 1st routestop for customer in route
                      from routestop rs5
                     where rs5.route_id = r.route_id
                       and rs5.customer_id = ih.deltocustomer_link_id)),
               (select max(rs6.soiltickets) -- then try 1st routestop for customer
                  from routestop rs6
                 where rs6.customer_id = ih.deltocustomer_link_id)),
           1)
/

  CREATE OR REPLACE VIEW "V_BANKLOCKERSTICKER" ("BUSINESSUNIT_ID", "SCANTIMESTAMP", "SCANDATE", "FROMSTOCK", "CHARGEWASHING", "BATCHNUMBER", "UNIQUEITEM_LINK_ID", "PRIMARYID", "CUSTOMER_LINK_ID", "CUST_NUMBER", "CUST_NAME", "WEAREREMPLOYMENT_LINK_ID", "WEARERNUMBER", "WEARERNAME", "WEARERSEARCHNAME", "PLANT_CODE", "PLANT_NAME", "BU_CODE", "BU_DESC", "PRODUCT_LINK_ID", "PROD_CODE", "PRODUCTGROUPCODE", "PROD_DESC", "LOCKER_ID", "BANK", "LOCKER", "LOCKERSTATUS", "REMARK", "SORTADDRESS", "KEYCOMBINATION", "LANGUAGE_CODE") AS 
  select ds.businessunit_id, ds.scantimestamp, trunc(ds.scantimestamp) scandate,--to_date(ds.scantimestamp, 'DD/MM/YYYY') scandate,
ds.fromstock, ds.chargewashing, ds.batchnumber,
       ds.uniqueitem_link_id, ui.primaryid,
       ds.customer_link_id, cl.customernumber cust_number, cl.name cust_name,
       ds.weareremployment_link_id, wel.wearernumber, wel.wearername, wel.wearersearchname,
       pl.code plant_code, pl.name plant_name,
       bu.code bu_code, bu.description bu_desc,
       ds.product_link_id, p.code prod_code, p.productgroupcode,
       (select pd.description from product_link_desc pd where pd.product_link_id = p.product_link_id and pd.language_id = lang.language_id) prod_desc,
       ds.locker_id, l.bank, l.locker, l.lockerstatus, l.remark, l.sortaddress, l.keycombination,
       lang.code language_code
from deliveryscan ds, uniqueitem ui, product_link p, locker l
     , businessunit bu, plant pl, customer_link cl, weareremployment_link wel
     , languages lang
where ds.uniqueitem_link_id = ui.uniqueitem_id
      and ds.product_link_id = p.product_link_id
      and ds.businessunit_id = bu.businessunit_id
      and bu.plant_id = pl.plant_id
      and ds.locker_id = l.locker_id
      and ds.customer_link_id = cl.customer_link_id
      and ds.weareremployment_link_id = wel.weareremployment_link_id
/

  CREATE OR REPLACE VIEW "V_BATCHCARD_REMARK" ("PRODUCTCODE", "REMARK", "SIZEDEFINITION_ID", "FINISHINGMETHOD_ID", "BATCH_ID") AS 
  select y.code productcode, y.remark,y.sizedefinition_id, y.finishingmethod_id, y.batch_id
         from   (select distinct l.remark, p.code, l.sizedefinition_id, l.finishingmethod_id, rsi.batch_id
                  from   residentialitemscan rsi
                  join   uniqueresidentialitemproduct urp
                  on     urp.uniqueresidentialitem_id = rsi.uniqueresidentialitem_link_id
                  left   outer join productlistpercustomer l
                  on     (l.customer_id = rsi.customer_link_id and l.product_id = rsi.product_link_id and
                         l.sizedefinition_id = rsi.sizedefinition_link_id and
                         l.finishingmethod_id = rsi.finishingmethod_id and
                         rsi.scantimestamp between l.dateactive and l.dateinactive)
                  join   product p
                  on     p.product_id = rsi.product_link_id
                  where rsi.transactiontype_id = 1 --only inscans!
                  union
                  select distinct l.remark, p.code,l.sizedefinition_id, l.finishingmethod_id,  cld.batch_id
                  from   clientdeliverynote cld
                  join   clientdeliverynoteline cldl
                  on     cldl.clientdeliverinote_id = cld.clientdeliverynote_id
                  left   outer join productlistpercustomer l
                  on     (l.customer_id = cld.customer_link_id and l.product_id = cldl.product_link_id and
                         l.sizedefinition_id = cldl.sizedefinition_link_id and
                         l.finishingmethod_id = cldl.finishingmethod_id and
                         cld.deliverydate between l.dateactive and l.dateinactive)
                  join   product p
                  on     p.product_id = cldl.product_link_id
                  union
                  Select distinct plpc.remark, p.code, plpc.sizedefinition_id, plpc.finishingmethod_id, GBS.GarmentBatch_ID batch_id
                  From GarmentBatchScan GBS, UniqueItem UI, UniqueItemNonPool NP, Product P, WearerEmployment WE, Wearer WR, ProductListPerCustomer PLPC
                  Where GBS.ScanType = 0
                        And UI.UniqueItem_ID = GBS.UniqueItem_ID
                        And NP.UniqueItem_ID = GBS.UniqueItem_ID
                        And WE.WearerEmployment_ID = NP.WearerEmployment_ID
                        And WR.Wearer_ID = WE.Wearer_ID
                        And P.Product_ID = UI.Product_Id
                        And PLPC.Customer_ID = WR.Customer_Id
                        And PLPC.Product_ID = UI.Product_ID
                        And ((PLPC.SizeDefinition_ID = UI.SizeDefinition_ID)
                          Or (PLPC.SizeDefinition_ID in (select sizestar.sizedefinition_id from sizedefinition sizestar where sizestar.code ='*')))
                        And PLPC.FinishingMethod_ID = UI.FinishingMethod_ID
                        And PLPC.DateActive <= sysdate
                        And PLPC.DateInactive > sysdate
                  ) y
/

  CREATE OR REPLACE VIEW "V_BATCHNUMBERDN" ("BATCHNUMBER", "PACKINGNOTE_ID") AS 
  select distinct ui.batchnumber, ds.packingnote_id
          from uniqueitem ui
          join deliveryscan ds
            on ui.uniqueitem_id = ds.uniqueitem_link_id
/

  CREATE OR REPLACE VIEW "V_BATCHSORTLIST" ("BATCH_ID", "YEAR", "WEEK", "BATCHNUMBER", "BATCHCODE", "BATCHCOLORDESC", "ROUTENUMBER", "DRIVINGDAY_ID", "STOPNUMBER", "DAYDESC", "CLIENTDELIVERYNOTENUMBER", "DELIVERYDATE", "ROOMNUMBER", "BOXNUMBER", "CLIENTNUMBER", "SEARCHNAME", "CLIENTNAME", "LEGACYCODE", "LABELNAME", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENT", "DELIVERYPOINT", "LANGUAGECODE", "REPORTPARAM_ID", "SORTORDER", "ROOMSEQUENCE") AS 
  SELECT b.batch_id,
    b.year,
    b.week,
    b.batchnumber,
    b.batchcode,
    bc.description batchcolordesc,
    --  coalesce(r.routenumber, 0) routenumber
    r.routenumber,
    r.drivingday_id,
    (
    CASE
      WHEN r.routenumber IS NOT NULL
      THEN cd.stopnumber
      ELSE NULL
    END) stopnumber,
    (
      SELECT dd.description
      FROM day_desc dd
      WHERE r.drivingday_id = dd.day_id
      AND dd.language_id    = languages.language_id
    )
    daydesc,
    cd.clientdeliverynotenumber,
    cd.deliverydate,
    CASE
      WHEN cd.closingdate IS NULL
      THEN dr.roomnumber
      ELSE cd.roomnumber
    END roomNUMBER,
    cd.boxnumber,
    cl.clientnumber, cl.searchname,
    cl.name clientname, cl.legacycode, cr.labelname,
    cu.customernumber,
    cu.name customername,
    CAST((
    CASE
      WHEN COALESCE(crs.customerclients, 1) = 0 -- resident
      THEN
        (
          SELECT concatenate3(ltrim(castnumberasvarcharwithformat(
            d.departmentnumber, '999999999999')), '/', d.description)
          FROM clientresident cr,
            departmentroom dr,
            department d
          WHERE cl.client_id       = cr.client_id
          AND cr.departmentroom_id = dr.departmentroom_id
          AND dr.department_id     = d.department_id
        )
      ELSE
        (
          SELECT concatenate3(ltrim(castnumberasvarcharwithformat(
            d2.departmentnumber, '999999999999')), '/', d2.description) --
            -- private
          FROM clientprivateperson cp,
            distributionpoint dip,
            department d2
          WHERE cl.client_id          = cp.client_id
          AND cp.distributionpoint_id = dip.distributionpoint_id
          AND dip.department_id       = d2.department_id
        )
    END) AS VARCHAR2(20)) department,
    CAST((
    CASE
      WHEN COALESCE(crs.customerclients, 1) = 0 -- resident
      THEN
        (
          SELECT concatenate3(dep1.code, '/', dep1.description)
          FROM clientresident cr1,
            departmentroom dr1,
            distributionpoint dip1,
            deliverypoint dep1
          WHERE cl.client_id           = cr1.client_id
          AND cr1.departmentroom_id    = dr1.departmentroom_id
          AND dr1.distributionpoint_id = dip1.distributionpoint_id
          AND dip1.deliverypoint_id    = dep1.deliverypoint_id
        )
      ELSE (
        CASE
          WHEN cpp.deliverypoint_id IS NOT NULL
          THEN
            (
              SELECT concatenate3(dep2.code, '/', dep2.description)
              FROM deliverypoint dep2
              WHERE cpp.deliverypoint_id = dep2.deliverypoint_id
            )
          ELSE
            (
              SELECT concatenate3(dep3.code, '/', dep3.description)
              FROM distributionpoint dip3,
                deliverypoint dep3
              WHERE cpp.distributionpoint_id = dip3.distributionpoint_id
              AND dip3.deliverypoint_id      = dep3.deliverypoint_id
            )
        END)
    END) AS VARCHAR2(20)) deliverypoint,
    languages.code languagecode,
    rp.reportparam_id, crs.sortorder,
    Coalesce(dr.sequencenumber, cd.sequencenumber) roomsequence
  FROM clientdeliverynote cd
  LEFT OUTER JOIN route r
  ON cd.route_id = r.route_id,
    client cl
  LEFT OUTER JOIN clientprivateperson cpp
  ON cl.client_id = cpp.client_id
  LEFT OUTER JOIN(clientresident cr
  JOIN (departmentroom dr
  JOIN department de
  ON dr.department_id     = de.department_id)
  ON cr.departmentroom_id = dr.departmentroom_id)
  ON cl.client_id         = cr.client_id,
    batch b,
    batchcolor bc,
    customer cu
  LEFT OUTER JOIN customerresidentialsettings crs
  ON cu.customer_id = crs.customer_id,
    languages,
    reportparam rp
  WHERE cd.batch_id       = b.batch_id
  AND cd.client_link_id   = cl.client_id
  AND cd.customer_link_id = cu.customer_id
  AND b.batchcolor_id     = bc.batchcolor_id
  AND b.batch_id          = rp.number_value
  AND languages.code      = rp.string_value
/

  CREATE OR REPLACE VIEW "V_BATCHTREATMENTCONTPERCUST" ("CLEANROOMBATCH_ID", "CLEANROOMBATCHNUMBER", "PRODUCTCODE", "BATCHSTATUS", "CREATIONDATE", "PLANTNAME", "TREATMENTCODE", "TREATMENT_DESC", "PRIMARYID", "CONSUMPTIONPOINTNUMBER", "CPDESCRIPTION", "DEPARTMENTNUMBER", "DEPARTMENT_DESC", "DELIVERYPOINTCODE", "DELIVERYPOINT_DESC", "DELP_STREET", "DELP_ZIPCODE", "DELP_CITY", "LOCKER", "BANK", "LANGUAGECODE", "PROD_DESC", "PLANTSTREET", "PLANTZIPCODE", "PLANTCITY", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMERSTREET", "CUSTOMERZIPCODE", "CUSTOMERCITY", "SIZE_DESC", "WEARERNAME", "WEARERNUMBER", "FMCODE", "LASTSCANDATE", "SIZECODE", "FMDESC", "CURRSTAY") AS 
  select cb.cleanroombatch_id, --garments
       cb.cleanroombatchnumber,
       p.code productcode,
       cb.batchstatus,
       cb.creationdate,
       pl.name plantname,
       tt.code treatmentcode,
       (select td.description
          from treatmenttype_desc td
         where td.treatmenttype_id = tt.treatmenttype_id
           and td.language_id = l.language_id) treatment_desc,
       ui.primaryid,
       dp.distributionpointnumber consumptionpointnumber,
       dp.description cpdescription,
       dep.departmentnumber,
       dep.description department_desc,
       delp.code deliverypointcode,
       delp.description deliverypoint_desc,
       (select a.street
          from address a
         where a.address_id = delp.deliveryaddress_id) delp_street,
       (select a.zipcode
          from address a
         where a.address_id = delp.deliveryaddress_id) delp_zipcode,
       (select a.city
          from address a
         where a.address_id = delp.deliveryaddress_id) delp_city,
        null locker,
       null bank,
       l.code languagecode,
       (select pdsc.description
          from product_desc pdsc
         where pdsc.product_id = p.product_id
           and pdsc.language_id = l.language_id) prod_desc,
       (select a.street from address a where a.address_id = pl.address_id) plantstreet,
       (select a.zipcode from address a where a.address_id = pl.address_id) plantzipcode,
       (select a.city from address a where a.address_id = pl.address_id) plantcity,
       c.customernumber customernumber,
       c.name customername,
       (select a.street from address a where a.address_id = c.mailaddress_id) customerstreet,
       (select a.zipcode
          from address a
         where a.address_id = c.mailaddress_id) customerzipcode,
       (select a.city from address a where a.address_id = c.mailaddress_id) customercity,
       (select sdesc.description
          from sizedefinition_desc sdesc
         where sdesc.sizedefinition_id = sd.sizedefinition_id
           and sdesc.language_id = l.language_id) size_desc,
       wylk.wearername,
       wylk.wearernumber,
       fm.code fmcode,
       ui.lastscandate,
       sd.code sizecode,
       (select fd.description
          from finishingmethod_desc fd
         where fd.finishingmethod_id = fm.finishingmethod_id
           and fd.language_id = l.language_id) fmdesc,
       s.factorydescription currstay
  from cleanroombatch cb
 inner join cleanroombatchcontent cbc
    on cb.cleanroombatch_id = cbc.cleanroombatch_id
 inner join businessunit bu
    on bu.businessunit_id = cb.businessunit_id
 inner join plant pl
    on pl.plant_id = bu.plant_id
  left outer join treatmenttype tt
    on cb.treatmenttype_id = tt.treatmenttype_id
 inner join uniqueitem ui
    on cbc.uniqueitem_id = ui.uniqueitem_id
 inner join product p
    on ui.product_id = p.product_id
 inner join sizedefinition sd
    on ui.sizedefinition_id = sd.sizedefinition_id
 inner join finishingmethod fm
    on ui.finishingmethod_id = fm.finishingmethod_id
 inner join stay s
    on s.stay_id = ui.stay_id
 inner join uniqueitemnonpool unp
    on unp.uniqueitem_id = ui.uniqueitem_id
 inner join weareremployment_link wylk
    on wylk.weareremployment_id = unp.weareremployment_id
  left outer join weareremployment wy
    on wy.weareremployment_id = wylk.weareremployment_id
  left outer join deliverypoint delp
    on wy.deliverypoint_id = delp.deliverypoint_id
 inner join distributionpoint dp
    on dp.distributionpoint_id =
       coalesce(wylk.distributionpoint_link_id, ui.distributionpoint_id)
 inner join department dep
    on dep.department_id = dp.department_id
 inner join customer c
    on c.customer_id = dep.customer_id, languages l
    where wy.locker_id is null
union all
select cb.cleanroombatch_id, --garments with bank/lockers
       cb.cleanroombatchnumber,
       p.code productcode,
       cb.batchstatus,
       cb.creationdate,
       pl.name plantname,
       tt.code treatmentcode,
       (select td.description
          from treatmenttype_desc td
         where td.treatmenttype_id = tt.treatmenttype_id
           and td.language_id = l.language_id) treatment_desc,
       ui.primaryid,
       dp.distributionpointnumber consumptionpointnumber,
       dp.description cpdescription,
       dep.departmentnumber,
       dep.description department_desc,
       delp.code deliverypointcode,
       delp.description deliverypoint_desc,
       (select a.street
          from address a
         where a.address_id = delp.deliveryaddress_id) delp_street,
       (select a.zipcode
          from address a
         where a.address_id = delp.deliveryaddress_id) delp_zipcode,
       (select a.city
          from address a
         where a.address_id = delp.deliveryaddress_id) delp_city,
          lk.locker locker,
       lk.bank bank,
       l.code languagecode,
       (select pdsc.description
          from product_desc pdsc
         where pdsc.product_id = p.product_id
           and pdsc.language_id = l.language_id) prod_desc,
       (select a.street from address a where a.address_id = pl.address_id) plantstreet,
       (select a.zipcode from address a where a.address_id = pl.address_id) plantzipcode,
       (select a.city from address a where a.address_id = pl.address_id) plantcity,
       c.customernumber customernumber,
       c.name customername,
       (select a.street from address a where a.address_id = c.mailaddress_id) customerstreet,
       (select a.zipcode
          from address a
         where a.address_id = c.mailaddress_id) customerzipcode,
       (select a.city from address a where a.address_id = c.mailaddress_id) customercity,
       (select sdesc.description
          from sizedefinition_desc sdesc
         where sdesc.sizedefinition_id = sd.sizedefinition_id
           and sdesc.language_id = l.language_id) size_desc,
       wylk.wearername,
       wylk.wearernumber,
       fm.code fmcode,
       ui.lastscandate,
       sd.code sizecode,
       (select fd.description
          from finishingmethod_desc fd
         where fd.finishingmethod_id = fm.finishingmethod_id
           and fd.language_id = l.language_id) fmdesc,
       s.factorydescription currstay
  from cleanroombatch cb
 inner join cleanroombatchcontent cbc
    on cb.cleanroombatch_id = cbc.cleanroombatch_id
 inner join businessunit bu
    on bu.businessunit_id = cb.businessunit_id
 inner join plant pl
    on pl.plant_id = bu.plant_id
  left outer join treatmenttype tt
    on cb.treatmenttype_id = tt.treatmenttype_id
 inner join uniqueitem ui
    on cbc.uniqueitem_id = ui.uniqueitem_id
 inner join product p
    on ui.product_id = p.product_id
 inner join sizedefinition sd
    on ui.sizedefinition_id = sd.sizedefinition_id
 inner join finishingmethod fm
    on ui.finishingmethod_id = fm.finishingmethod_id
 inner join stay s
    on s.stay_id = ui.stay_id
 inner join uniqueitemnonpool unp
    on unp.uniqueitem_id = ui.uniqueitem_id
 inner join weareremployment_link wylk
    on wylk.weareremployment_id = unp.weareremployment_id
  left outer join weareremployment wy
    on wy.weareremployment_id = wylk.weareremployment_id
  inner join locker lk on wy.locker_id=lk.locker_id
  inner join deliverypoint delp
    on lk.deliverypoint_id = delp.deliverypoint_id
 inner join distributionpoint dp
    on dp.distributionpoint_id =
       coalesce(wylk.distributionpoint_link_id, ui.distributionpoint_id)
 inner join department dep
    on dep.department_id = dp.department_id
 inner join customer c
    on c.customer_id = dep.customer_id, languages l
union all
select cb.cleanroombatch_id,  --general pool items
       cb.cleanroombatchnumber,
       p.code productcode,
       cb.batchstatus,
       cb.creationdate,
       pl.name plantname,
       tt.code treatmentcode,
       (select td.description
          from treatmenttype_desc td
         where td.treatmenttype_id = tt.treatmenttype_id
           and td.language_id = l.language_id) treatment_desc,
       ui.primaryid,
       null consumptionpointnumber,
       null cpdescription,
       null departmentnumber,
       null department_desc,
       null deliverypointcode,
       null deliverypoint_desc,
       null delp_street,
       null delp_zipcode,
       null delp_city,
       null locker,
       null bank,
       l.code languagecode,
       (select pdsc.description
          from product_desc pdsc
         where pdsc.product_id = p.product_id
           and pdsc.language_id = l.language_id) prod_desc,
       (select a.street from address a where a.address_id = pl.address_id) plantstreet,
       (select a.zipcode from address a where a.address_id = pl.address_id) plantzipcode,
       (select a.city from address a where a.address_id = pl.address_id) plantcity,
       null customernumber,
       null customername,
       null customerstreet,
       null customerzipcode,
       null customercity,
       (select sdesc.description
          from sizedefinition_desc sdesc
         where sdesc.sizedefinition_id = sd.sizedefinition_id
           and sdesc.language_id = l.language_id) size_desc,
        null wearername,
        null wearernumber,
       fm.code fmcode,
       ui.lastscandate,
       sd.code sizecode,
       (select fd.description
          from finishingmethod_desc fd
         where fd.finishingmethod_id = fm.finishingmethod_id
           and fd.language_id = l.language_id) fmdesc,
       s.factorydescription currstay
  from cleanroombatch cb
 inner join cleanroombatchcontent cbc
    on cb.cleanroombatch_id = cbc.cleanroombatch_id
 inner join businessunit bu
    on bu.businessunit_id = cb.businessunit_id
 inner join plant pl
    on pl.plant_id = bu.plant_id
  left outer join treatmenttype tt
    on cb.treatmenttype_id = tt.treatmenttype_id
 inner join uniqueitem ui
    on cbc.uniqueitem_id = ui.uniqueitem_id
 inner join product p
    on ui.product_id = p.product_id
 inner join sizedefinition sd
    on ui.sizedefinition_id = sd.sizedefinition_id
 inner join finishingmethod fm
    on ui.finishingmethod_id = fm.finishingmethod_id
 inner join stay s
    on s.stay_id = ui.stay_id, languages l
 where (select count(ui.uniqueitem_id)
          from uniqueitemnonpool unp
         where unp.uniqueitem_id = ui.uniqueitem_id) = 0
   and ui.relatedcustomer_id is null
union all
 select cb.cleanroombatch_id,  --customer related pool items
        cb.cleanroombatchnumber,
        p.code productcode,
        cb.batchstatus,
        cb.creationdate,
        pl.name plantname,
        tt.code treatmentcode,
        (select td.description
           from treatmenttype_desc td
          where td.treatmenttype_id = tt.treatmenttype_id
            and td.language_id = l.language_id) treatment_desc,
        ui.primaryid,
        (select dp.distributionpointnumber
           from distributionpoint dp
          where dp.distributionpoint_id = ui.distributionpoint_id) consumptionpointnumber,
        (select dp.description
           from distributionpoint dp
          where dp.distributionpoint_id = ui.distributionpoint_id) cpdescription,
        (select dep.departmentnumber
           from department dep, distributionpoint dp
          where dep.department_id = dp.department_id
            and dp.distributionpoint_id = ui.distributionpoint_id) departmentnumber,
        (select dep.description
           from department dep, distributionpoint dp
          where dep.department_id = dp.department_id
            and dp.distributionpoint_id = ui.distributionpoint_id) department_desc,
        null deliverypointcode,
        null deliverypoint_desc,
        null delp_street,
        null delp_zipcode,
        null delp_city,
        null locker,
        null bank,
        l.code languagecode,
        (select pdsc.description
           from product_desc pdsc
          where pdsc.product_id = p.product_id
            and pdsc.language_id = l.language_id) prod_desc,
        (select a.street from address a where a.address_id = pl.address_id) plantstreet,
        (select a.zipcode from address a where a.address_id = pl.address_id) plantzipcode,
        (select a.city from address a where a.address_id = pl.address_id) plantcity,
        c.customernumber,
        c.name customername,
        (select a.street
           from address a
          where a.address_id = c.mailaddress_id) customerstreet,
        (select a.zipcode
           from address a
          where a.address_id = c.mailaddress_id) customerzipcode,
        (select a.city from address a where a.address_id = c.mailaddress_id) customercity,
        (select sdesc.description
           from sizedefinition_desc sdesc
          where sdesc.sizedefinition_id = sd.sizedefinition_id
            and sdesc.language_id = l.language_id) size_desc,
        null wearername,
        null wearernumber,
        fm.code fmcode,
        ui.lastscandate,
        sd.code sizecode,
        (select fd.description
           from finishingmethod_desc fd
          where fd.finishingmethod_id = fm.finishingmethod_id
            and fd.language_id = l.language_id) fmdesc,
        s.factorydescription currstay
   from cleanroombatch cb
  inner join cleanroombatchcontent cbc
     on cb.cleanroombatch_id = cbc.cleanroombatch_id
  inner join businessunit bu
     on bu.businessunit_id = cb.businessunit_id
  inner join plant pl
     on pl.plant_id = bu.plant_id
   left outer join treatmenttype tt
     on cb.treatmenttype_id = tt.treatmenttype_id
  inner join uniqueitem ui
     on cbc.uniqueitem_id = ui.uniqueitem_id
  inner join product p
     on ui.product_id = p.product_id
  inner join sizedefinition sd
     on ui.sizedefinition_id = sd.sizedefinition_id
  inner join finishingmethod fm
     on ui.finishingmethod_id = fm.finishingmethod_id
  inner join stay s
     on s.stay_id = ui.stay_id
  inner join customer c
     on c.customer_id = ui.relatedcustomer_id, languages l
/

  CREATE OR REPLACE VIEW "V_BILLOFLADING" ("ROUTECONTROL_ID", "PLANT_CODE", "PLANT_NAME", "PLANT_LOGO", "PLANT_STREET", "PLANT_STREET2", "PLANT_STREET3", "PLANT_ZIPCODE", "PLANT_CITY", "PLANT_STATE", "PLANT_COUNTY", "FINALIZATIONCOMPLETETS", "ROUTENUMBER", "ROUTE_DESC", "DRIVINGDATE", "TRUCKCODE", "TRUCKDESC", "DRIVERNR", "DRIVERNAME", "STOPNUMBER", "PRIMARYID", "NOTENUMBER", "WEIGHINGCATEGORY_CODE", "WEIGHINGCATEGORY_DESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEL_STREET", "DEL_STREET2", "DEL_STREET3", "DEL_ZIPCODE", "DEL_CITY", "DEL_STATE", "DEL_COUNTY", "GROSSWEIGHT", "TAREWEIGHT", "MAXWEIGHT", "WEIGHTUNIT") AS 
  select /*version 1.4*/
       rc.routecontrol_id, pl.code plant_code, pl.name plant_name, pl.logo plant_logo,
       pad.street plant_street, pad.street2 plant_street2, pad.street3 plant_street3,
       pad.zipcode plant_zipcode, pad.city plant_city, pad.state plant_state, pad.county plant_county,
       (select rcei.finalizationcompletetimestamp
          from routecontrolextrainfo rcei
         where rcei.routecontrol_id = rc.routecontrol_id) finalizationcompletets,
       ro.routenumber, ro.description route_desc, rc.drivingdate,
       nvl(rc.truckcode, (select tr.code
                            from truck tr
                           where tr.truck_id = ro.truck_id)) truckcode,
       nvl((select tr1.description
              from truck tr1
             where tr1.code = rc.truckcode
               and tr1.plant_id = rc.plant_id),
           (select tr2.description
              from truck tr2
             where tr2.truck_id = ro.truck_id)) truckdesc,
       nvl(rc.drivernumber, (select drv.employeenumber
                               from employee drv
                              where drv.employee_id = ro.driver_id)) drivernr,
       nvl((select drv1.name
              from employee drv1
             where drv1.employeenumber = rc.drivernumber
               and drv1.plant_id = rc.plant_id),
           (select drv2.name
              from employee drv2
             where drv2.employee_id = ro.driver_id)) drivername,
       pn.stopnumber, con.primaryid, pn.notenumber, wc.code weighingcategory_code,
       (select wcd.description
          from weighingcategory_desc wcd
         where wcd.weighingcategory_id = wc.weighingcategory_id
           and wcd.language_id = pl.language_id) weighingcategory_desc,
       cu.customernumber, cu.name customername,
       delad.street del_street, delad.street2 del_street2, delad.street3 del_street3,
       delad.zipcode del_zipcode, delad.city del_city, delad.state del_state, delad.county del_county,
       pnc.grossweight, pnc.tareweight,
       nvl((select tr1.maxweight
              from truck tr1
             where tr1.code = rc.truckcode
               and tr1.plant_id = rc.plant_id),
           (select tr2.maxweight
              from truck tr2
             where tr2.truck_id = ro.truck_id)) maxweight,
       (select ss.value
          from systemsetting ss
         where ss.plant_id = pl.plant_id
           and ss.name = 'WEIGHTUNIT') weightunit
  from packingnote pn
       left join stop stp on pn.stop_id = stp.stop_id
       left join routecontrol rc
            join route ro on rc.route_id = ro.route_id
       on pn.routecontrol_id = rc.routecontrol_id
       left join packingnotecontainer pnc
            left join weighingcategory wc on pnc.weighingcategory_id = wc.weighingcategory_id
            left join container con on pnc.container_id = con.container_id
       on pn.packingnote_id = pnc.packingnote_id
       join status sta on pn.status_id = sta.status_id
       join businessunit pbu
            join plant pl
                 join address pad on pl.address_id = pad.address_id
            on pbu.plant_id = pl.plant_id
       on pn.processbusinessunit_id = pbu.businessunit_id
       join distributionpoint dp
            join department dep
                 join customer cu on dep.customer_id = cu.customer_id
            on dp.department_id = dep.department_id
       on pn.distributionpoint_id = dp.distributionpoint_id
       join deliverypoint delp
            join address delad on delp.deliveryaddress_id = delad.address_id
       on pn.deliverypoint_id = delp.deliverypoint_id
 where sta.code = '30'
/

  CREATE OR REPLACE VIEW "V_BOXLABEL" ("CUSTOMERNUMBER", "NAME", "STREET", "STREET2", "CITY", "ZIPCODE", "COUNTY", "DEPARTMENTNUMBER", "DEPARTMENTDESCR", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "PACKINGNOTE_ID", "DELIVERYDATE", "NOTENUMBER", "BOXNUMBER", "DELIVEREDQTY", "CODE", "PRODUCTDESC", "SIZECODE", "FMCODE", "LANGCODE") AS 
  select /*version 2.0*/
c.customernumber,c.name
,ad.street,ad.street2,ad.city,ad.zipcode,ad.county
,d.departmentnumber,d.description departmentdescr,
db.distributionpointnumber,db.description distributionpointdesc
,pn.packingnote_id,pn.deliverydate,pn.notenumber
,pnb.boxnumber,pnbq.deliveredqty
,p.code
,(select psc.description from product_desc psc where psc.product_id = p.product_id and psc.language_id = l.language_id) productDesc
,sz.code sizecode
,fm.code fmcode
,l.code langcode
from packingnote pn
join packingnotebox pnb on pn.packingnote_id = pnb.packingnote_id
     join packingnoteboxquantity pnbq on pnb.packingnotebox_id = pnbq.packingnotebox_id
          join packingnoteline pnl on pnbq.packingnoteline_id = pnl.packingnoteline_id
join deliverypoint del on pn.deliverypoint_id = del.deliverypoint_id
     join address ad on del.deliveryaddress_id = ad.address_id
join plantdepartment pld on pn.plantdepartment_id = pld.plantdepartment_id
join distributionpoint db on pn.distributionpoint_id = db.distributionpoint_id
     join department d on db.department_id = d.department_id
          join customer c on d.customer_id = c.customer_id
join product p on pnl.product_id = p.product_id
join sizedefinition sz on pnl.sizedefinition_id = sz.sizedefinition_id
join finishingmethod fm on pnl.finishingmethod_id = fm.finishingmethod_id
join languages l on l.language_id = c.language_id
/

  CREATE OR REPLACE VIEW "V_BOXLOAD" ("CLIENTDELIVERYNOTEID", "CLIENTDELIVERYNOTENUMBER", "EMPTIED", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "STREET", "ZIPCODE", "CITY", "CLIENTNUMBER", "CLIENTNAME", "ROOMNUMBER", "BATCHNUMBER", "BOXNUMBER", "PRODUCTLINKCODE", "PRODUCTLINKDESCRIPTION", "SIZEDEFINITIONLINKNCODE", "SIZEDEFINITIONLINKDESCRIPTION", "LANGUAGE_ID", "BOXLOAD", "QUANTITY", "DEPARTMENTROOMNUMBER") AS 
  select cdn.clientdeliverynote_id clientdeliverynoteid,
       cdn.clientdeliverynotenumber clientdeliverynotenumber,
       cdn.emptied emptied,
       custlink.customernumber customernumber,
       custlink.name customername,
       d.departmentnumber departmentnumber,
       d.description departmentdesc,
       a.street street,
       a.zipcode zipcode,
       a.city city,
       clientlink.clientnumber clientnumber,
       clientlink.name clientname,
       case
         when cdn.closingdate is null then
          dr.roomnumber
         else
          cdn.roomnumber
       end roomnumber,
       case (select ss.value v
           from businessunit bu, plant p, systemsetting ss
          where bu.plant_id = p.plant_id
            and ss.plant_id = p.plant_id
            and cdn.processbusinessunit_id = bu.businessunit_id
            and ss.name = 'BATCHCODEUSAGE')
         when '-2' then
          substr(b.batchcode, 1, 2) || to_char(b.batchnumber)
         when '-1' then
          substr(b.batchcode, 1, 1) || to_char(b.batchnumber)
         when '0' then
          to_char(b.batchnumber)
         when '1' then
          to_char(b.batchnumber) || substr(b.batchcode, 1, 1)
         when '2' then
          to_char(b.batchnumber) || substr(b.batchcode, 1, 2)
       end batchnumber,
       cdn.boxnumber boxnumber,
       prlink.code productlinkcode,
       prlinkdesc.description productlinkdescription,
       sdlink.code sizedefinitionlinkncode,
       sdlinkdesc.description sizedefinitionlinkdescription,
       prlinkdesc.language_id language_id,
       cds.boxload boxload,
       count(cds.clientdelnotelinescan_id) quantity,
       dr.roomnumber departmentroomnumber
  from clientdeliverynote       cdn,
       clientdeliverynoteline   cdl,
       clientdelnotelinescan    cds,
       client_link              clientlink,
       departmentroom           dr,
       department               d,
       customer_link            custlink,
       batch                    b,
       distributionpoint        dp,
       deliverypoint            delp,
       address                  a,
       product_link             prlink,
       product_link_desc        prlinkdesc,
       sizedefinition_link      sdlink,
       sizedefinition_link_desc sdlinkdesc
 where cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
   and cdl.clientdeliverynoteline_id = cds.outscanclientdelnoteline_id
   and clientlink.client_link_id = cdn.client_link_id
   and dr.departmentroom_id = clientlink.departmentroom_id
   and d.department_id = dr.department_id
   and custlink.customer_link_id = cdn.customer_link_id
   and dp.distributionpoint_id = dr.distributionpoint_id
   and delp.deliverypoint_id = dp.deliverypoint_id
   and a.address_id = delp.deliveryaddress_id
   and b.batch_id = cdn.batch_id
   and prlink.product_link_id = cdl.product_link_id
   and prlinkdesc.product_link_id = cdl.product_link_id
   and sdlink.sizedefinition_link_id = cdl.sizedefinition_link_id
   and sdlinkdesc.sizedefinition_link_id = cdl.sizedefinition_link_id
   and sdlinkdesc.language_id = prlinkdesc.language_id
 group by prlinkdesc.language_id,
          cdl.clientdeliverynoteline_id,
          cds.boxload,
          cdn.processbusinessunit_id,
          b.batchcode,
          b.batchnumber,
          cdn.clientdeliverynote_id,
          cdn.clientdeliverynotenumber,
          cdn.emptied,
          custlink.customernumber,
          custlink.name,
          d.departmentnumber,
          d.description,
          a.street,
          a.zipcode,
          a.city,
          clientlink.clientnumber,
          clientlink.name,
          cdn.roomnumber,
          cdn.boxnumber,
          prlink.code,
          prlinkdesc.description,
          sdlink.code,
          sdlinkdesc.description,
          prlinkdesc.language_id,
          cds.boxload,
          dr.roomnumber,
          cdn.closingdate
/

  CREATE OR REPLACE VIEW "V_BUDGETPOSTCALCULATION" ("DELTOCUSTOMER_LINK_ID", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "INVOICENUMBER", "INVOICEDATE", "DELTOSTREET", "DELTOSTREET2", "DELTOZIPCODE", "DELTOCITY", "STARTYEAR", "STARTMONTH", "STARTWEEK", "STARTDATE", "ENDYEAR", "ENDMONTH", "ENDWEEK", "ENDDATE", "BUDGET_YEAR", "BUDGET_MONTH", "BUDGET_QUANTITY", "BILLEDQTY", "AMOUNT", "PRICE", "DISCOUNTPERCENTAGE", "INVLINETYPE_DESC", "CODE", "DESCRIPTION", "BUDGETCODE", "INVOICELINETYPE_ID", "DEPARTMENTNUMBER", "DEPARTMENT_DESC", "BUDGETUNIT_CODE", "BUDGETUNIT_DESC", "ACTIVITY_CODE", "COSTCENTER_CODE", "COSTCENTER_DESC", "CCIL_QTY", "CCIL_AMOUNT", "ORIGINALAMOUNT", "ACTIVITY_DESC", "LANGUAGE_CODE", "LANGUAGE_ID", "CURRENCY_CODE", "DECIMALS", "INVOICEAMOUNTDECIMALS") AS 
  select ih.deltocustomer_link_id, ih.deltocustomernumber, cast(ih.deltocustomername AS varchar(60)) deltocustomername,
       ih.invoicenumber, ih.invoicedate, ih.deltostreet, ih.deltostreet2, ih.deltozipcode, ih.deltocity,
       ih.startyear, ih.startmonth, ih.startweek, ih.startdate, ih.endyear, ih.endmonth, ih.endweek, ih.enddate,
       bg.year budget_year, bg.month budget_month, sum(bg.quantity) budget_quantity, il.billedqty, il.amount, il.price, il.discountpercentage,
       (select iltd.description from InvoiceLineType_desc iltd where iltd.invoicelinetype_id = il.invoicelinetype_id and iltd.language_id = lan.language_id) InvLineType_desc,
       il.code, il.description, coalesce(il.budgetcode, il.code) budgetcode, il.invoicelinetype_id, --dep.departmentnumber, dep.description department_desc,
       0 departmentnumber, ' ' department_desc,
       (select bu.code from budgetunit bu where bu.budgetunit_id = bg.budgetunit_id) budgetunit_code,
       (select bud.description from budgetunit_desc bud where bud.budgetunit_id = bg.budgetunit_id and bud.language_id = lan.language_id) budgetunit_desc,
       act.code Activity_Code, ccl.code CostCenter_code, ccl.description CostCenter_desc, ccil.quantity ccil_qty, ccil.amount ccil_amount, ccil.originalamount,
       (select actd.description from activity_desc actd where actd.activity_id = act.activity_id and actd.language_id = lan.language_id) Activity_Desc,
       lan.code Language_code, lan.language_id, curr.code Currency_code, curr.decimals, curr.invoiceamountdecimals
from invoiceheader ih
     inner join budget2 bg
           left outer join department dep on bg.department_id = dep.department_id
     on bg.customer_id = ih.deltocustomer_link_id,
     invoiceline il
     left outer join invoicelineproduct ilp
          left outer join product p
               inner join productgroup pg
                     inner join activity act on act.activity_id = pg.activity_id
               on pg.productgroup_id = p.productgroup_id
          on p.product_id = ilp.product_link_id
     on ilp.invoiceline_id = il.invoiceline_id
     left outer join costcenterinvoiceline ccil
          inner join costcenter_link ccl on ccil.costcenter_link_id = ccl.costcenter_link_id
     on ccil.invoiceline_id = il.invoiceline_id,
     status st, languages lan, currency curr
where ih.invoiceheader_id = il.invoiceheader_id and
      ih.documenttype = 1 and ih.status_id = st.status_id and st.code = '2' and st.statustype = 'IN' and
      ((IL.InvoiceLineType_ID = 31 And coalesce(ccil.originalamount, 1) > 0 and IL.Amount > 0)
      OR IL.BudgetCode is not null) --and coalesce(dep.costcenter_id, ccl.costcenter_link_id, 0) = coalesce(ccl.costcenter_link_id, 0)
      and ih.currency_id = curr.currency_id
      --and month (ih.invoicedate) = bg.month
	  and bg.month>=ih.startmonth
      and bg.month<=ih.endmonth
      and bg.year>=ih.startyear
      and bg.year<=ih.endyear
group by ih.deltocustomer_link_id, ih.deltocustomernumber, ih.deltocustomername,
       ih.invoicenumber, ih.invoicedate, ih.deltostreet, ih.deltostreet2, ih.deltozipcode, ih.deltocity,
       ih.startyear, ih.startmonth, ih.startweek, ih.startdate, ih.endyear, ih.endmonth, ih.endweek, ih.enddate,
       bg.year, bg.month, il.billedqty, il.amount, il.price, il.discountpercentage,
       il.invoicelinetype_id, il.code, il.description, il.budgetcode, --dep.departmentnumber, dep.description,
       bg.budgetunit_id, act.code, ccl.code, ccl.description, ccil.quantity, ccil.amount, ccil.originalamount, act.activity_id,
       lan.code, lan.language_id, curr.code, curr.decimals, curr.invoiceamountdecimals
/

  CREATE OR REPLACE VIEW "V_BUDGETSTATISTICS" ("LINETYPE", "DELTOCUSTOMER_LINK_ID", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "DELTOSTREET", "DELTOSTREET2", "DELTOZIPCODE", "DELTOCITY", "DEPARTMENTID", "DEPARTMENTNUMBER", "DEPARTMENT_DESC", "STARTYEAR", "STARTMONTH", "STARTWEEK", "STARTDATE", "ENDYEAR", "ENDMONTH", "ENDWEEK", "ENDDATE", "BUDGET_YEAR", "BUDGET_MONTH", "CUSTBUD", "BUDGET_QUANTITY", "BILLEDQTY", "AMOUNT", "ORIGINALAMOUNT", "INVLINETYPE_DESC", "CODE", "DESCRIPTION", "BUDGETCODE", "INVOICELINETYPE_ID", "COSTCENTER_CODE", "COSTCENTER_DESC", "BUDGETUNIT_CODE", "BUDGETUNIT_DESC", "ACTIVITY_CODE", "ACTIVITY_DESC", "LANGUAGE_CODE", "LANGUAGE_ID", "BUDGET_QUANTITY_DEP", "INVOICELINE_ID", "INVOICEBUSINESSUNIT_ID") AS 
  SELECT 1 linetype,
    ih.deltocustomer_link_id,
    ih.deltocustomernumber,
    CAST(ih.deltocustomername AS VARCHAR(60)) deltocustomername,
    ih.deltostreet,
    ih.deltostreet2,
    ih.deltozipcode,
    ih.deltocity,
    bg.department_id departmentid,
    0 departmentnumber,
    ' ' department_desc,
    ih.startyear,
    ih.startmonth,
    ih.startweek,
    ih.startdate,
    ih.endyear,
    ih.endmonth,
    ih.endweek,
    ih.enddate,
    bg.year budget_year,
    bg.month budget_month,
    nvl((SELECT sum(bg.quantity)
    FROM budget2 bg
    WHERE bg.customer_id =ih.deltocustomer_link_id
    AND bg.month        >=ih.startmonth
    AND bg.month        <=ih.endmonth
    AND bg.year         >=ih.startyear
    AND bg.year         <=ih.endyear
     AND bg.department_id is null
    ),0 )custbud,
    round((SELECT SUM(bg.quantity)
    FROM budget2 bg
    WHERE bg.customer_id =ih.deltocustomer_link_id
    AND bg.month        >=ih.startmonth
    AND bg.month        <=ih.endmonth
    AND bg.year         >=ih.startyear
    AND bg.year         <=ih.endyear
    AND bg.department_id>=0
    ), 2) budget_quantity,
    il.billedqty,
    round(il.amount, 2) amount,
    il.originalamount,
    (SELECT iltd.description
    FROM InvoiceLineType_desc iltd
    WHERE iltd.invoicelinetype_id = il.invoicelinetype_id
    AND iltd.language_id          = lan.language_id
    ) InvLineType_desc,
    il.code,
    il.description,
    il.budgetcode,
    il.invoicelinetype_id,
    ' ' CostCenter_code,
    ' ' CostCenter_desc,
    (SELECT bu.code FROM budgetunit bu WHERE bu.budgetunit_id = bg.budgetunit_id
    ) budgetunit_code,
    (SELECT bud.description
    FROM budgetunit_desc bud
    WHERE bud.budgetunit_id = bg.budgetunit_id
    AND bud.language_id     = lan.language_id
    ) budgetunit_desc,
    act.code Activity_Code,
    (SELECT actd.description
    FROM activity_desc actd
    WHERE actd.activity_id = act.activity_id
    AND actd.language_id   = lan.language_id
    ) Activity_Desc,
    lan.code Language_code,
    lan.language_id,
    bg.quantity budget_quantity_dep,
    il.invoiceline_id,
    ih.invoicebusinessunit_id
  FROM invoiceheader ih
  INNER JOIN budget2 bg
  ON bg.customer_id = ih.deltocustomer_link_id,
    invoiceline il
  LEFT OUTER JOIN invoicelineproduct ilp
  LEFT OUTER JOIN product p
  INNER JOIN productgroup pg
  INNER JOIN activity act
  ON act.activity_id    = pg.activity_id
  ON pg.productgroup_id = p.productgroup_id
  ON p.product_id       = ilp.product_link_id
  ON ilp.invoiceline_id = il.invoiceline_id,
    status st,
    languages lan
  WHERE ih.invoiceheader_id        = il.invoiceheader_id
  AND ih.documenttype              = 1
  AND ih.status_id                 = st.status_id
  AND st.code                      = '2'
  AND st.statustype                = 'IN'
  AND il.invoicelinetype_id       IN (1, 2, 5, 26, 30)
  AND ih.credited                 <> 2
  AND ih.creditedinvoiceheader_id IS NULL
  AND bg.month                    >=ih.startmonth
  AND bg.month                    <=ih.endmonth
  AND bg.year                     >=ih.startyear
  AND bg.year                     <=ih.endyear
  UNION ALL
  SELECT 2 linetype,
    ih.deltocustomer_link_id,
    ih.deltocustomernumber,
    CAST(ih.deltocustomername AS VARCHAR(60)) deltocustomername,
    ih.deltostreet,
    ih.deltostreet2,
    ih.deltozipcode,
    ih.deltocity,
    dep.department_id departmentid,
    0 departmentnumber,
    ' ' department_desc,
    ih.startyear,
    ih.startmonth,
    ih.startweek,
    ih.startdate,
    ih.endyear,
    ih.endmonth,
    ih.endweek,
    ih.enddate,
    bg.year budget_year,
    bg.month budget_month,
    nvl((SELECT sum(bg.quantity)
    FROM budget2 bg
    WHERE bg.customer_id =ih.deltocustomer_link_id
    AND bg.month        >=ih.startmonth
    AND bg.month        <=ih.endmonth
    AND bg.year         >=ih.startyear
    AND bg.year         <=ih.endyear
    AND bg.department_id is null
    ),0 )custbud,
    (SELECT SUM(bg.quantity)
    FROM budget2 bg
    WHERE bg.customer_id =ih.deltocustomer_link_id
    AND bg.month        >=ih.startmonth
    AND bg.month        <=ih.endmonth
    AND bg.year         >=ih.startyear
    AND bg.year         <=ih.endyear
    AND bg.department_id>=0
    ) budget_quantity,
    ccil.quantity billedqty ,
    ccil.amount,
    ccil.originalamount,
    (SELECT iltd.description
    FROM InvoiceLineType_desc iltd
    WHERE iltd.invoicelinetype_id = il.invoicelinetype_id
    AND iltd.language_id          = lan.language_id
    ) InvLineType_desc,
    il.code,
    il.description,
    il.budgetcode,
    il.invoicelinetype_id,
    ccl.code CostCenter_code,
    ccl.description CostCenter_desc,
    (SELECT bu.code FROM budgetunit bu WHERE bu.budgetunit_id = bg.budgetunit_id
    ) budgetunit_code,
    (SELECT bud.description
    FROM budgetunit_desc bud
    WHERE bud.budgetunit_id = bg.budgetunit_id
    AND bud.language_id     = lan.language_id
    ) budgetunit_desc,
    act.code Activity_Code,
    (SELECT actd.description
    FROM activity_desc actd
    WHERE actd.activity_id = act.activity_id
    AND actd.language_id   = lan.language_id
    ) Activity_Desc,
    lan.code Language_code,
    lan.language_id,
    bg.quantity budget_quantity_dep,
    il.invoiceline_id,
    ih.invoicebusinessunit_id
  FROM invoiceheader ih
  INNER JOIN budget2 bg
  INNER JOIN department dep
  ON bg.department_id = dep.department_id
  ON bg.customer_id   = ih.deltocustomer_link_id,
    invoiceline il
  LEFT OUTER JOIN invoicelineproduct ilp
  LEFT OUTER JOIN product p
  INNER JOIN productgroup pg
  INNER JOIN activity act
  ON act.activity_id    = pg.activity_id
  ON pg.productgroup_id = p.productgroup_id
  ON p.product_id       = ilp.product_link_id
  ON ilp.invoiceline_id = il.invoiceline_id
  LEFT OUTER JOIN costcenterinvoiceline ccil
  INNER JOIN costcenter_link ccl
  ON ccil.costcenter_link_id = ccl.costcenter_link_id
  ON ccil.invoiceline_id     = il.invoiceline_id,
    status st,
    languages lan
  WHERE ih.invoiceheader_id        = il.invoiceheader_id
  AND ih.documenttype              = 1
  AND ih.status_id                 = st.status_id
  AND st.code                      = '2'
  AND st.statustype                = 'IN'
  AND il.invoicelinetype_id       IN (1, 2, 5, 26, 30)
  AND dep.costcenter_id            = COALESCE(ccil.costcenter_link_id, dep.costcenter_id)
  AND ih.credited                 <> 2
  AND ih.creditedinvoiceheader_id IS NULL
  AND bg.month                    >=ih.startmonth
  AND bg.month                    <=ih.endmonth
  AND bg.year                     >=ih.startyear
  AND bg.year                     <=ih.endyear
/

  CREATE OR REPLACE VIEW "V_BUFFERCONTAINERCONTENT" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENT_DESC", "DISTRIBUTIONPOINT_DESC", "CONTAINER_ID", "INTERNALCUSTOMERNUMBER", "CONTAINER_TYPE", "BUSINESSUNIT_ID", "PRODUCT_CODE", "SIZE_CODE", "UNIQUEBUNDLE_ID", "PRODUCT_WEIGHT", "CONTAINER_WEIGHT", "QUANTITY", "LANGUAGECODE", "CONTAINER_PRIMARYID", "CONTAINERBUNDLESCAN", "PRODUCT_DESC", "WEIGHT_UNIT", "PLANTLOGO") AS 
  select /*version 2.3*/
       c.customernumber, c.name customername, d.description department_desc, dp.description distributionpoint_desc, cc.container_id,
       (select pcu.internalcustomernumber
          from productioncustomer pcu
         where pcu.businessunit_id = ub.businessunit_id
           and pcu.distributionpoint_id = ub.distributionpoint_link_id) internalcustomernumber,
       ct.code container_type, bu.businessunit_id, pr.code product_code, sd.code size_code, ub.uniquebundle_id, pr.theoreticalweight product_weight,
       cc.tareweight container_weight, ub.quantity, lan.code languagecode, cc.primaryid container_primaryid, ccb.creationtimestamp containerbundlescan,
       (select pd.description from product_desc pd where pd.product_id = pr.product_id and pd.language_id = lan.language_id) product_desc,
       (select sst.value from systemsetting sst where sst.plant_id = bu.plant_id and sst.name = 'WEIGHTUNIT') weight_unit,
       (select pl.logo from plant pl where pl.plant_id = bu.plant_id) plantlogo
  from containercontentbundle ccb
       join container cc
            join containertype ct on cc.containertype_id = ct.containertype_id
       on ccb.container_id = cc.container_id
       join uniquebundle ub
            join businessunit bu on ub.businessunit_id = bu.businessunit_id
            join distributionpoint dp
                 join department d on dp.department_id = d.department_id
                 join customer c on d.customer_id = c.customer_id
            on ub.distributionpoint_link_id = dp.distributionpoint_id
            join product pr on ub.product_link_id = pr.product_id
            join sizedefinition sd on ub.sizedefinition_link_id = sd.sizedefinition_id
       on ccb.uniquebundle_id = ub.uniquebundle_id
       cross join languages lan
/

  CREATE OR REPLACE VIEW "V_BULKPUTUP" ("PACKINGNOTEID", "STATUSTYPE", "DRIVINGDATE", "DEPOTCODE", "DEPOTDESCRIPTION", "NOTENUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMERLEGALNAME", "STREET", "STREET2", "CITY", "STATE", "ZIPCODE", "COUNTY", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "DELIVERYPOINTCODE", "DELIVERYDATE", "DELIVERYPOINTDESCRIPTION", "SEQUENCENUMBER", "PACKINGDEPARTMENTCODE", "EMPLOYEENAME", "PRODUCTIONDATE", "STATUSCODE", "PACKINGDEPARTMENTDESCRIPTION", "TRANSPORTARTICLECODE", "PROCESSBUDESCRIPTION", "INVOICEBUCODE", "INVOICEBUDESCRIPTION", "ROUTENUMBER", "ROUTEDESCRIPTION", "LOADINGDOCK", "CLEANRETURN", "DEADLINE", "STOPNUMBER", "PUTUPREPORTPERCUSTOMER", "DEADLINEASNUMERIC", "CONSIGNMENTNOTENUMBER", "SYSTEMUSER_ID", "TIMESTAMP", "YEAR", "CREATIONTIMESTAMP", "ENDDATEFORUSE", "DRIVERNAME", "DRIVERNUMBER", "EXTRANAME1", "LEGACYCUSTOMERNUMBER", "DISTRICTDESC", "DISTRICTCODE", "ROUTECONTROL_ID", "ROUTE_ID", "STOP_ID", "TRANSPORTARTICLEDESCRIPTION", "OCCUPANCY", "EMPLOYEENUMBER", "STATUSDESCRIPTION", "REMARK", "PROCESSBUCODE", "DAYDESCRIPTION", "WEEK", "LANGUAGECODE", "PACKINGNOTECOLUMNS", "DELIVERGARMENTS", "BULKPUTUPONPACKINGNOTE") AS 
  select /*version 2.0*/
       pn.packingnote_id packingnoteid, sta.statustype, rc.drivingdate, dep.code depotcode, dep.description depotdescription,
       pn.notenumber, cu.customernumber, cu.name customername, cu.legalname customerlegalname, dela.street, dela.street2,
       dela.city, dela.state, dela.zipcode, dela.county, de.departmentnumber, de.description departmentdescription,
       dp.distributionpointnumber, dp.description distributionpointdescription, delp.code deliverypointcode, pn.deliverydate,
       delp.description deliverypointdescription, pn.sequencenumber, pld.code packingdepartmentcode, emp.name employeename,
       pn.productiondate, sta.code statuscode, pld.description packingdepartmentdescription, ta.code transportarticlecode,
       procbu.description processbudescription, invbu.code invoicebucode, invbu.description invoicebudescription, ro.routenumber,
       ro.description routedescription, ro.loadingdock, pn.cleanreturn, pn.deadline, pn.stopnumber, ro.putupreportpercustomer,
       gettimeasnumeric(pn.deadline) deadlineasnumeric, cn.consignmentnotenumber, pn.systemuser_id, pn.timestamp, pn.year,
       pn.creationtimestamp, pn.enddateforuse, drv.name drivername, drv.employeenumber drivernumber, cu.extraname1,
       cu.legacycustomernumber, di.code districtdesc, di.description districtcode, rc.routecontrol_id, ro.route_id, pn.stop_id,
       (select tad.description
          from transportarticle_desc tad
         where tad.transportarticle_id = pn.transportarticle_id
           and tad.language_id = lan.language_id) transportarticledescription, pn.occupancy, emp.employeenumber,
       (select std.description
          from status_desc std
         where std.status_id = pn.status_id
           and std.language_id = lan.language_id) statusdescription, pn.pnremark remark, procbu.code processbucode,
       (select dd.description
          from day_desc dd
         where dd.language_id = lan.language_id
           and dd.day_id = pn.daynumber) daydescription, cast(pn.week as varchar2(2)) week, lan.code languagecode,
       (select ss.value
          from systemsetting ss
         where ss.plant_id = procbu.plant_id
           and ss.name = 'PACKINGNOTECOLUMNS') packingnotecolumns,
       (select count(1)
          from customerdeliveryday cdd
         where cdd.customer_id = cu.customer_id
           and cdd.day_id = pn.daynumber
           and cdd.typeofmerchadise = 2) delivergarments,
       case when cu.delnoteforbulkputupitems = 0 then 'N'
            else 'Y'
        end bulkputuponpackingnote
  from packingnote pn
       left join employee emp on pn.employee_id = emp.employee_id
       left join routecontrol rc on pn.routecontrol_id = rc.routecontrol_id
       left join consignmentnote cn on pn.consignmentnote_id = cn.consignmentnote_id
       left join route ro
                 left join depot dep on ro.depot_id = dep.depot_id
                 left join employee drv on ro.driver_id = drv.employee_id
                 join district di on ro.district_id = di.district_id
       on pn.route_id = ro.route_id
       join transportarticle ta on pn.transportarticle_id = ta.transportarticle_id
       join status sta on pn.status_id = sta.status_id
       join deliverypoint delp
            join address dela on delp.deliveryaddress_id = dela.address_id
       on pn.deliverypoint_id = delp.deliverypoint_id
       join plantdepartment pld on pn.plantdepartment_id = pld.plantdepartment_id
       join businessunit procbu on pn.processbusinessunit_id = procbu.businessunit_id
       join businessunit invbu on pn.invoicebusinessunit_id = invbu.businessunit_id
       join distributionpoint dp
            join department de
                 join customer cu on de.customer_id = cu.customer_id
            on dp.department_id = de.department_id
       on pn.distributionpoint_id = dp.distributionpoint_id
       cross join languages lan
 where sta.statustype = 'PN'
   and sta.code in ('10', '20', '30')
/

  CREATE OR REPLACE VIEW "V_BULKPUTUPLIST" ("ROUTECONTROL_ID", "PLANTCODE", "ROUTENUMBER", "ROUTEDESCRIPTION", "DEPOTECODE", "DEPOTDESCRIPTION", "DRIVERNAME", "DRIVINGDATE", "LOADINGDOCK", "STARTTIME", "TRUCKCODE", "TRUCKDESCRIPTION", "CUSTOMERNUMBER", "SEARCHNAME", "LEGALNAME", "PRODUCTCODE", "PUTUPREPORTROUTESTOP", "SIZECODE", "FINISHINGMETHODCODE", "TOBEDELIVEREDAMOUNT", "DISTRIBUTIONPOINTNUMBER", "REMARKONPACKINGNOTE", "LANGUAGECODE", "REPLACEMENTQTY", "REPLACEMENTLOSSQTY", "PRODUCTDESCRIPTION") AS 
  select /*version 2.0*/
       rc.routecontrol_id, pla.code plantcode, ro.routenumber, ro.description routedescription, dep.code depotecode, dep.description depotdescription,
       emp.name drivername, rc.drivingdate, rc.loadingdock, rc.packingdeadline starttime, trc.code truckcode, trc.description truckdescription,
       cu.customernumber, cu.searchname, cu.legalname, pr.code productcode, ro.putupreportroutestop, sd.code sizecode, fm.code finishingmethodcode,
       pnl.tobedeliveredamount, dp.distributionpointnumber, dp.remarkonpackingnote, lan.code languagecode, pnl.replacementqty, pnl.replacementlossqty,
       (select pds.description
          from product_desc pds
         where pr.product_id = pds.product_id
           and pds.language_id = lan.language_id) productdescription
  from routecontrol rc
       join route ro
            left join depot dep on dep.depot_id = ro.depot_id
            left join employee emp on emp.employee_id = ro.driver_id
            left join truck trc on trc.truck_id = ro.truck_id
       on rc.route_id = ro.route_id
       join plant pla on rc.plant_id = pla.plant_id
       join stop st
            join packingnote pn
                 join packingnoteline pnl
                      join product pr on pnl.product_id = pr.product_id
                      join sizedefinition sd on pnl.sizedefinition_id = sd.sizedefinition_id
                      join finishingmethod fm on pnl.finishingmethod_id = fm.finishingmethod_id
                 on pn.packingnote_id = pnl.packingnote_id
                 join distributionpoint dp on pn.distributionpoint_id = dp.distributionpoint_id
            on st.stop_id = pn.stop_id
            join customer cu on st.customer_link_id = cu.customer_id
       on rc.routecontrol_id = st.routecontrol_id
       cross join languages lan
 where (st.status = 0 or st.status = 3)
   and (pnl.putuptype = 2 or pnl.putuptype = 4)
   and ro.active = 'Y'
/

  CREATE OR REPLACE VIEW "V_BULKSHORTAGE" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DELIVERYDATE", "DELIVERYDATE_WEEK", "CONSIGNMENTNOTENUMBER", "CONSIGNMENTNOTE_ID", "PRODUCTCODE", "SIZECODE", "FINISHINGCODE", "ORDEREDAMOUNT", "DELIVEREDAMOUNT", "SHORTAGEAMOUNT", "LANGUAGECODE", "DELIVERYDATE_DAYDESC", "PRODUCTDESC") AS 
  select distinct /*version 2.0*/
       cu.customernumber, cu.name customername, pn.deliverydate, pn.week deliverydate_week, cn.consignmentnotenumber, cn.consignmentnote_id,
       prd.code productcode, sz.code sizecode, fm.code finishingcode, pnl.tobedeliveredamount orderedamount, pnl.deliveredamount,
       (pnl.tobedeliveredamount - pnl.deliveredamount) shortageamount, languages.code languagecode,
       (select dd.description
          from day_desc dd
         where dd.day_id = pn.daynumber
           and dd.language_id = languages.language_id ) deliverydate_daydesc,
       (select pds.description
          from product_desc pds
         where pds.product_id = prd.product_id
           and pds.language_id = languages.language_id ) productdesc
  from packingnote pn
       join packingnote bn
            join consignmentnote cn on bn.consignmentnote_id = cn.consignmentnote_id
       on pn.packingnote_id = bn.bulkpackingnote_id
       join packingnoteline pnl
            join product prd on pnl.product_id = prd.product_id
            join sizedefinition sz on pnl.sizedefinition_id = sz.sizedefinition_id
            join finishingmethod fm on pnl.finishingmethod_id = fm.finishingmethod_id
       on pn.packingnote_id = pnl.packingnote_id
       join distributionpoint dip
            join department dep
                 join customer cu on dep.customer_id = cu.customer_id
            on dip.department_id = dep.department_id
       on pn.distributionpoint_id = dip.distributionpoint_id
       cross join languages
 where cu.consignmentnotelevel > 0
   and pnl.deliveredamount < pnl.tobedeliveredamount
/

  CREATE OR REPLACE VIEW "V_BUSINESSUNIT" ("CODE", "DESCRIPTION", "PACKNOTENUMBERPREFIX", "PLANTCODE", "PLANTNAME", "DIVISIONCODE", "DIVISIONDESCRIPTION", "REGIONCODE", "REGIONDESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT BUSINESSUNIT.CODE, BUSINESSUNIT.DESCRIPTION, BUSINESSUNIT.PACKNOTENUMBERPREFIX,
 PLANT.CODE, PLANT.NAME, DIVISION.CODE,
 (SELECT description FROM DIVISION_DESC A WHERE A.DIVISION_ID = BUSINESSUNIT.DIVISION_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) DIVISION_DESC,
 REGION.CODE,
 (SELECT description FROM REGION_DESC B WHERE B.REGION_ID = BUSINESSUNIT.REGION_ID
  AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) REGION_DESC,
 BUSINESSUNIT.SYSTEMUSER_ID, BUSINESSUNIT.TIMESTAMP, LANGUAGES.CODE
FROM BUSINESSUNIT, PLANT, DIVISION, REGION, LANGUAGES
 WHERE BUSINESSUNIT.PLANT_ID = PLANT.PLANT_ID
  and BUSINESSUNIT.DIVISION_ID = DIVISION.DIVISION_ID
  and BUSINESSUNIT.REGION_ID = REGION.REGION_ID
/

  CREATE OR REPLACE VIEW "V_BUSINESSUNITACTIVITIES" ("BUSINESSUNITCODE", "BUSINESSUNITDESCRIPTION", "ACTIVITYCODE", "ACTIVITYDESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT BUSINESSUNIT.CODE, BUSINESSUNIT.DESCRIPTION, ACTIVITY.CODE,
(SELECT description FROM ACTIVITY_DESC A WHERE A.ACTIVITY_ID = BUSINESSUNITACTIVITIES.ACTIVITY_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) ACTIVITY_DESC,
 BUSINESSUNITACTIVITIES.SYSTEMUSER_ID, BUSINESSUNITACTIVITIES.TIMESTAMP, LANGUAGES.CODE
FROM BUSINESSUNIT, BUSINESSUNITACTIVITIES, ACTIVITY, LANGUAGES
WHERE BUSINESSUNITACTIVITIES.BUSINESSUNIT_ID = BUSINESSUNIT.BUSINESSUNIT_ID
 and  BUSINESSUNITACTIVITIES.ACTIVITY_ID = ACTIVITY.ACTIVITY_ID
/

  CREATE OR REPLACE VIEW "V_CANCELLATIONFEE" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPDESCR", "DISTRIBUTIONPOINTNUMBER", "CONSDESCR", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "FMCODE", "DELSCHEMECODE", "BUSINESSUNIT_ID", "STANDARDDELIVERYLINE_ID", "REPORTPARAM_ID", "SERVICE", "CANCELPERIOD", "AVGRENTAL", "AVGDELIV", "AVGFREE", "CANCELDELIV", "RENTPRICE", "WASHPRICE", "CANCELFEERENT", "CANCELFEEWASH", "CANCELLATIONPERCENTAGE", "CURRENCYCODE", "INVOICEAMOUNTDECIMALS", "DECIMALS", "LANGUAGECODE") AS 
  select
  cu.customernumber, cu.name customername,
  dp.departmentnumber, dp.description depdescr,
  dip.distributionpointnumber, dip.description consdescr,
   p.code productcode,
  (select prd.description from product_desc prd where prd.product_id = p.product_id
     and prd.language_id = languages.language_id) productdesc,
  sd.code sizecode,fm.code fmcode,
  ds.code  delschemecode,
  bu.businessunit_id, sdl.standarddeliveryline_id standarddeliveryline_id,
  rp.reportparam_id,
  rp.string_value1 service,
  rp.string_value2 cancelperiod,
  rp.number_value1 Avgrental,
  rp.number_value9 AvgDeliv,
  rp.number_value3 AvgFree,
  rp.number_value4 CancelDeliv,
  rp.number_value5 RentPrice,
  rp.number_value6 WashPrice,
  rp.number_value7 CancelFeeRent,
  rp.number_value8 CancelFeeWash,
  ( select systemsetting.value from systemsetting where systemsetting.plant_id = bu.plant_id and systemsetting.name = 'CANCELLATIONPERCENTAGE' ) CANCELLATIONPERCENTAGE,
  c.code currencycode, c.invoiceamountdecimals,c.decimals,
   languages.code languagecode
from customer cu,department dp,distributionpoint dip, standarddeliveryline sdl,
productlistperdistribpoint plpd, deliveryscheme ds, product p, sizedefinition sd, finishingmethod fm,
businessunit bu,currency c,reportparam rp,languages
where rp.number_value=sdl.standarddeliveryline_id
and sdl.productlistperdistribpoint_id=plpd.productlistperdistribpoint_id
and plpd.distributionpoint_id=dip.distributionpoint_id
and dip.department_id=dp.department_id
and dp.customer_id=cu.customer_id
and sdl.deliveryscheme_id=ds.deliveryscheme_id
and plpd.product_id=p.product_id
and plpd.sizedefinition_id=sd.sizedefinition_id
and plpd.finishingmethod_id=fm.finishingmethod_id
and cu.defaultbusinessunit_id = bu.businessunit_id  -- or custactivities procesate by current bu
and cu.currency_id=c.currency_id
/

  CREATE OR REPLACE VIEW "V_CDN_PERCLIENT" ("LINETYPE", "CLIENT_LINK_ID", "CLIENTDELIVERYNOTENUMBER", "DELIVERYDATE", "INVOICELINE_ID") AS 
  select 1 linetype, cdn.client_link_id, cdn.clientdeliverynotenumber, cdn.deliverydate, cdln.invoiceline_id
from clientdeliverynote cdn, clientdeliverynoteline cdln
where cdln.clientdeliverinote_id = cdn.clientdeliverynote_id
      and cdn.closingdate is not null
union all
select 2 linetype, cdn.client_link_id, cdn.clientdeliverynotenumber, cdn.deliverydate, csc.invoiceline_id
from clientdeliverynotespeccharge csc, clientdeliverynote cdn
where csc.clientdeliverinote_id = cdn.clientdeliverynote_id
      and cdn.closingdate is not null
union all
select 3 linetype, cdn.client_link_id, cdn.clientdeliverynotenumber, cdn.deliverydate, cdn.invoiceline_id
from clientdeliverynote cdn
where cdn.closingdate is not null
union all
select 4 linetype, cdn.client_link_id, cdn.clientdeliverynotenumber, cdn.deliverydate, pqr.invoiceline_id
from printqueueresidentialitem pqr, clientdeliverynote cdn
where pqr.clientdeliverynote_id = cdn.clientdeliverynote_id
/

  CREATE OR REPLACE VIEW "V_CDN_SPECIALSCANS" ("CLIENTDELIVERYNOTE_ID", "PACKINGSEQUENCE", "PRODUCTCODE", "PRODUCTDESC", "PRIMARYID", "NOTENUMBER", "LANGUAGECODE", "PRODCUSTOM_CODE", "PRODCUSTOM_DESC", "STAYNR") AS 
  select cdn.clientdeliverynote_id, prd.packingsequence, prd.code productCode
, (select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, uri.primaryid, cdn.clientdeliverynotenumber noteNumber
, languages.code languageCode
, (SELECT plpc.customcode FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, cdl.sizedefinition_link_id, cdl.finishingmethod_id, cdl.sizedefinition_link_id, cdn.deliverydate, 0)) ProdCustom_Code
, (SELECT plpc.customdescription FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, cdl.sizedefinition_link_id, cdl.finishingmethod_id, cdl.sizedefinition_link_id, cdn.deliverydate, 0)) ProdCustom_Desc
, st.staynr
from
  clientdeliverynote cdn, clientdeliverynoteline cdl
, clientdelnotelinescan cds
, uniqueresidentialitem uri
, product prd, languages, stay st
WHERE cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
and cdl.clientdeliverynoteline_id = cds.outscanclientdelnoteline_id
    and cds.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id
and cdl.product_link_id = prd.product_id
and uri.laststay_id = st.stay_id
and st.staynr in (55, 65)--special scans
/

  CREATE OR REPLACE VIEW "V_CHECKOVERALLUNIQUERANGE8" ("PRIMARYID", "NEXTPRIMARYID", "DIFFERENCE") AS 
  select --view v_checkOverallUniqueRange8 version 0.1
 x.primaryid, x.nextprimaryid, (x.nextprimaryid - x.primaryid) AS difference
from (select a.primaryid,
                (select min(b.primaryid)
                  from   uniqueitem b
                  where  length(b.primaryid) = length(a.primaryid)
                  and    b.primaryid > a.primaryid) AS nextprimaryid
         from   uniqueitem a
         where  length(a.primaryid) = 8) x
where  (x.nextprimaryid - x.primaryid) > 10000
/

  CREATE OR REPLACE VIEW "V_CHECKUNIQUERANGE8" ("CODE", "DESCRIPTION", "PRIMARYID", "NEXTPRIMARYID", "DIFFERENCE") AS 
  select --view v_checkUniqueRange8 version 0.1
 bu.code, bu.description, x.primaryid, x.nextprimaryid, (x.nextprimaryid - x.primaryid) AS difference
from   (select a.businessunit_id, a.primaryid,
                (select min(b.primaryid)
                  from   uniqueitem b
                  where  length(b.primaryid) = length(a.primaryid)
                  and    b.businessunit_id = a.businessunit_id
                  and    b.primaryid > a.primaryid) AS nextprimaryid
         from   uniqueitem a
         where  length(a.primaryid) = 8) x
join   businessunit bu
on     bu.businessunit_id = x.businessunit_id
where  (x.nextprimaryid - x.primaryid) > 10000
/

  CREATE OR REPLACE VIEW "V_CHECK_SEQUENCES" ("SEQUENCE_NAME", "BUSINESSUNIT", "DIFFERENCE", "LAST_NUMBER", "PREFIX", "NUMBERLENGTH", "MAX_VALUE", "SUGGESTED_MAXVALUE", "CORRECTION_SCRIPT") AS 
  select /*view v_check_sequences version 0.6*/
 sequence_name, businessunit, difference, last_number, prefix, numberlength, max_value,
 suggested_maxvalue,
 case
   when t.suggested_maxvalue is null then
    null
   else
    'alter sequence ' || t.sequence_name || ' maxvalue ' || t.suggested_maxvalue || ';'
 end correction_script
from   (select x.sequence_name, x.code businessunit, x.difference, x.last_number, x.prefix,
                x.numberlength, x.max_value,
                case
                  when to_char(x.max_value) <>
                       to_char(x.prefix || rpad('9', x.numberlength - length(x.prefix), '9')) then
                   to_char(x.prefix || rpad('9', x.numberlength - length(x.prefix), '9'))
                  else
                   null
                end suggested_maxvalue
         from   (select bn.sequence_name, bu.code, bn.max_value, bn.last_number,
                         (bn.max_value - bn.last_number) difference, packnotenumberprefix prefix,
                         packnotenumberlength numberlength
                  from   businessunit bu
                  join   (select replace(s.sequence_name, 'SEQ_DELIVERYNOTE_') bucode, s.max_value,
                                s.last_number, s.sequence_name
                         from   user_sequences s
                         where  s.sequence_name like 'SEQ_DELIVERYNOTE%') bn
                  on     bn.bucode = bu.code
                  union all
                  select bn.sequence_name, bu.code, bn.max_value, bn.last_number,
                         (bn.max_value - bn.last_number) difference,
                         bu.consignmentnotenumberprefix prefix,
                         bu.consignmentnotenumberlength numberlength
                  from   businessunit bu
                  join   (select replace(s.sequence_name, 'SEQ_CONSIGNMENT_') bucode, s.max_value,
                                s.last_number, s.sequence_name
                         from   user_sequences s
                         where  s.sequence_name like 'SEQ_CONSIGNMENT_%') bn
                  on     bn.bucode = bu.code
                  union all
                  select bn.sequence_name, bu.code, bn.max_value, bn.last_number,
                         (bn.max_value - bn.last_number) difference, bu.soilticketnumberprefix prefix,
                         bu.soilticketnumberlength numberlength
                  from   businessunit bu
                  join   (select replace(s.sequence_name, 'SEQ_SOILTICKET_') bucode, s.max_value,
                                s.last_number, s.sequence_name
                         from   user_sequences s
                         where  s.sequence_name like 'SEQ_SOILTICKET_%') bn
                  on     bn.bucode = bu.code
                  union all
                  select bn.sequence_name, bu.code, bn.max_value, bn.last_number,
                         (bn.max_value - bn.last_number) difference, bu.workordernumberprefix prefix,
                         bu.workordernumberlength numberlength
                  from   businessunit bu
                  join   (select replace(s.sequence_name, 'SEQ_WORKORDER_') bucode, s.max_value,
                                s.last_number, s.sequence_name
                         from   user_sequences s
                         where  s.sequence_name like 'SEQ_WORKORDER_%') bn
                  on     bn.bucode = bu.code
                  union all
                  select bn.sequence_name, bu.code, bn.max_value, bn.last_number,
                         (bn.max_value - bn.last_number) difference, bu.woreferencenumberprefix prefix,
                         bu.woreferencenumberlength numberlength
                  from   businessunit bu
                  join   (select replace(s.sequence_name, 'SEQ_WOREFERENCENUMBER_') bucode, s.max_value,
                                s.last_number, s.sequence_name
                         from   user_sequences s
                         where  s.sequence_name like 'SEQ_WOREFERENCENUMBER_%') bn
                  on     bn.bucode = bu.code
                  union all
                  select bn.sequence_name, bu.code, bn.max_value, bn.last_number,
                         (bn.max_value - bn.last_number) difference, bu.invoicenumberprefix prefix,
                         bu.invoicenumberlength numberlength
                  from   businessunit bu
                  join   (select replace(s.sequence_name, 'SEQ_INVOICE_') bucode, s.max_value,
                                s.last_number, s.sequence_name
                         from   user_sequences s
                         where  s.sequence_name like 'SEQ_INVOICE_%') bn
                  on     bn.bucode = bu.code
                  union all
                  select bn.sequence_name, bu.code, bn.max_value, bn.last_number,
                         (bn.max_value - bn.last_number) difference, bu.statementnumberprefix prefix,
                         bu.statementnumberlength numberlength
                  from   businessunit bu
                  join   (select replace(s.sequence_name, 'SEQ_STATEMENT_') bucode, s.max_value,
                                s.last_number, s.sequence_name
                         from   user_sequences s
                         where  s.sequence_name like 'SEQ_STATEMENT_%') bn
                  on     bn.bucode = bu.code
                  union all
                  select bn.sequence_name, bu.code, bn.max_value, bn.last_number,
                         (bn.max_value - bn.last_number) difference, bu.remitbatchnumberprefix prefix,
                         bu.remitbatchnumberlength numberlength
                  from   businessunit bu
                  join   (select replace(s.sequence_name, 'SEQ_REMITBATCH_') bucode, s.max_value,
                                s.last_number, s.sequence_name
                         from   user_sequences s
                         where  s.sequence_name like 'SEQ_REMITBATCH_%') bn
                  on     bn.bucode = bu.code
                  union all
                  select bn.sequence_name, bu.code, bn.max_value, bn.last_number,
                         (bn.max_value - bn.last_number) difference, bu.contactmgrnumberprefix prefix,
                         bu.contactmgrnumberlength numberlength
                  from   businessunit bu
                  join   (select replace(s.sequence_name, 'SEQ_CONTACTMGR_') bucode, s.max_value,
                                s.last_number, s.sequence_name
                         from   user_sequences s
                         where  s.sequence_name like 'SEQ_CONTACTMGR_%') bn
                  on     bn.bucode = bu.code
                  union all
                  select bn.sequence_name, bu.code, bn.max_value, bn.last_number,
                         (bn.max_value - bn.last_number) difference, bu.purchaseordernumberprefix prefix,
                         bu.purchaseordernumberlength numberlength
                  from   businessunit bu
                  join   (select replace(s.sequence_name, 'SEQ_PURCHASEORDER_') bucode, s.max_value,
                                s.last_number, s.sequence_name
                         from   user_sequences s
                         where  s.sequence_name like 'SEQ_PURCHASEORDER_%') bn
                  on     bn.bucode = bu.code
                  union all
                  select bn.sequence_name, bu.code, bn.max_value, bn.last_number,
                         (bn.max_value - bn.last_number) difference,
                         bu.cleanroombatchnumberprefix prefix,
                         bu.cleanroombatchnumberlength numberlength
                  from   businessunit bu
                  join   (select replace(s.sequence_name, 'SEQ_CLEANROOMBATCHNR_') bucode, s.max_value,
                                s.last_number, s.sequence_name
                         from   user_sequences s
                         where  s.sequence_name like 'SEQ_CLEANROOMBATCHNR_%') bn
                  on     bn.bucode = bu.code
                  union all
                  select bn.sequence_name, bu.code, bn.max_value, bn.last_number,
                         (bn.max_value - bn.last_number) difference, bu.picklistnumberprefix prefix,
                         bu.picklistnumberlength numberlength
                  from   businessunit bu
                  join   (select replace(s.sequence_name, 'SEQ_PICKLIST_') bucode, s.max_value,
                                s.last_number, s.sequence_name
                         from   user_sequences s
                         where  s.sequence_name like 'SEQ_PICKLIST_%') bn
                  on     bn.bucode = bu.code
                  union all
                  select bn.sequence_name, bu.code, bn.max_value, bn.last_number,
                         (bn.max_value - bn.last_number) difference, bu.shipmentlistnumberprefix prefix,
                         bu.shipmentlistnumberlength numberlength
                  from   businessunit bu
                  join   (select replace(s.sequence_name, 'SEQ_SHIPMENTLISTNUMBER_') bucode, s.max_value,
                                s.last_number, s.sequence_name
                         from   user_sequences s
                         where  s.sequence_name like 'SEQ_SHIPMENTLISTNUMBER_%') bn
                  on     bn.bucode = bu.code
                  union all
                  select bn.sequence_name, bu.code, bn.max_value, bn.last_number,
                         (bn.max_value - bn.last_number) difference,
                         bu.weighingticketnumberprefix prefix,
                         bu.weighingticketnumberlength numberlength
                  from   businessunit bu
                  join   (select replace(s.sequence_name, 'SEQ_WEIGHINGTICKET_') bucode, s.max_value,
                                s.last_number, s.sequence_name
                         from   user_sequences s
                         where  s.sequence_name like 'SEQ_WEIGHINGTICKET_%') bn
                  on     bn.bucode = bu.code) x) t
order  by 3 asc
/

  CREATE OR REPLACE VIEW "V_CIRCINVAGAINSTWASH_PIECHART" ("POINTCONSO_ID", "POINTCONSO", "NUMCLIENT", "PRODUCT_ID", "ARTI_CODE", "TAILLE", "ROTATION", "STOCK", "LANGUAGE_ID", "LANGUAGE_CODE", "REPORTPARAM_ID", "BUSINESSUNIT_ID") AS 
  select v.PointConso_ID, v.PointConso, v.NumClient, v.product_id, v.Arti_Code,
    v.Taille, sum(v.Rotation) Rotation, sum(v.stock) stock, v.language_id, v.Language_Code, v.reportparam_id, v.businessunit_id
from (SELECT dp.distributionpoint_id PointConso_ID, dp.description PointConso,
    c.customernumber NumClient, p.product_id, p.code Arti_Code,
    sd.code Taille
      , count(1) Rotation
      , wi.circinventory stock, EXTRACT(year FROM ds.scantimestamp) ScanYear, EXTRACT(month FROM ds.scantimestamp) ScanMonth
      , lan.language_id, lan.code Language_Code, rp.reportparam_id, ds.businessunit_id
      FROM
          customer                    c,
          department                  dep,
          distributionpoint           dp,
          weareremployment            we,
          wearerinventory             wi,
          sizedefinition              sd,
          languages                   lan,
          product                     p,
          reportparam                 rp,
          deliveryscan                ds
      WHERE dep.customer_id = c.customer_id
            AND dep.department_id = dp.department_id
            AND dp.DISTRIBUTIONPOINT_ID = we.DISTRIBUTIONPOINT_ID
            AND we.WEAREREMPLOYMENT_ID = wi.WEAREREMPLOYMENT_ID
            AND wi.product_id = p.product_id
            AND wi.sizedefinition_id = sd.sizedefinition_id
            and ds.weareremployment_link_id = we.weareremployment_id and
            ds.distributionpoint_link_id = dp.distributionpoint_id  and
            ds.product_link_id = p.product_id and
            ds.sizedefinition_link_id = sd.sizedefinition_id and
            ds.finishingmethod_id = wi.finishingmethod_id and
            trunc(ds.scantimestamp) >= rp.date_value1 and
            trunc(ds.scantimestamp) <= rp.date_value2 and
            not exists (select 1 from raggeditem ri where ri.raggeditem_id = ds.uniqueitem_link_id)
      group by rp.date_value1, rp.date_value2, dp.distributionpoint_id, dp.description, EXTRACT(year FROM ds.scantimestamp), EXTRACT(month FROM ds.scantimestamp),
          c.customernumber, p.product_id, p.code, p.parentproduct_id, ds.businessunit_id, wi.wearerinventory_id, wi.circinventory,
          sd.sizedefinition_id, sd.code, lan.language_id, lan.code, rp.reportparam_id) V
group by v.PointConso_ID, v.PointConso, v.NumClient, v.product_id, v.Arti_Code,
    v.Taille, v.language_id, v.Language_Code, v.reportparam_id, v.businessunit_id
/

  CREATE OR REPLACE VIEW "V_CIRCINVENTORYAGAINSTWASHES" ("DEFAULTBUSINESSUNIT_ID", "CUSTOMERNUMBER", "NAME", "BUSINESSUNIT_ID", "DEPARTMENTNUMBER", "DEP_DESC", "DISTRIBUTIONPOINTNUMBER", "DISTRIB_DESC", "PRODUCT_CODE", "SIZEDEF_CODE", "FINISHING_CODE", "FINISHING_DESC", "SIZEDEF_DESC", "PARENTPRODUCT_DESC", "PRODUCT_DESC", "WEARERINVENTORY_ID", "CIRCINVENTORY", "MAXINVENTORY", "DATEACTIVE", "DATEINACTIVE", "SCANDATE", "SCANYEAR", "SCANMONTH", "RAGGED", "PRIMARYID", "DISTRIBUTIONPOINT_ID", "PRODUCT_ID", "SIZEDEFINITION_ID", "WEAREREMPLOYMENT_ID", "LANGUAGE_CODE", "REPORTPARAM_ID") AS 
  SELECT cu.defaultbusinessunit_id,  cu.customernumber, cu.name, bu.businessunit_id,
       de.departmentnumber, de.description Dep_desc, dp.distributionpointnumber, dp.description Distrib_desc,
       p.code Product_code, s.code Sizedef_code, f.code Finishing_code,
       (SELECT c.DESCRIPTION FROM finishingmethod_desc c WHERE c.finishingmethod_id = f.finishingmethod_id aND c.LANGUAGE_ID = l.LANGUAGE_ID) Finishing_desc,
       (SELECT d.DESCRIPTION FROM sizedefinition_desc d WHERE d.sizedefinition_id = s.sizedefinition_id aND d.LANGUAGE_ID = l.LANGUAGE_ID) Sizedef_desc,
       (SELECT pp.DESCRIPTION FROM product_desc pp WHERE pp.product_id = p.parentproduct_id aND pp.LANGUAGE_ID = l.LANGUAGE_ID) ParentProduct_desc,
       (SELECT e.DESCRIPTION FROM product_desc e WHERE e.product_id = p.product_id aND e.LANGUAGE_ID = l.LANGUAGE_ID) Product_desc,
       wi.wearerinventory_id, wi.circinventory, wi.maxinventory, wi.dateactive, wi.dateinactive, trunc(ds.scantimestamp) ScanDate,
       EXTRACT(year FROM ds.scantimestamp) ScanYear, EXTRACT(month FROM ds.scantimestamp) ScanMonth,
       case when exists(select 1 from raggeditem ri where ri.raggeditem_id = ds.uniqueitem_link_id)
       then 1
       else 0 end Ragged,
       (select ui.primaryid from uniqueitem ui where ui.uniqueitem_id = ds.uniqueitem_link_id) PrimaryID,
       dp.DISTRIBUTIONPOINT_ID, p.product_id, s.sizedefinition_id, wi.weareremployment_id,
       l.code Language_code, rp.reportparam_id
FROM wearerinventory wi, deliveryscan ds--, weareremployment we
     , distributionpoint dp, department de, customer cu
     , product p, sizedefinition s, finishingmethod f
     , businessunit bu, languages l, reportparam rp
WHERE wi.weareremployment_id = ds.weareremployment_link_id and
      ds.distributionpoint_link_id = dp.distributionpoint_id and
      dp.department_id = de.department_id and
      de.customer_id = cu.customer_id and
      wi.product_id = p.product_id and
      wi.sizedefinition_id = s.sizedefinition_id and
      wi.finishingmethod_id = f.finishingmethod_id and
      wi.product_id = ds.product_link_id and
      wi.sizedefinition_id = ds.sizedefinition_link_id and
      wi.finishingmethod_id = ds.finishingmethod_id and
      ds.businessunit_id = bu.businessunit_id
/

  CREATE OR REPLACE VIEW "V_CIRCINVENTORYHISTORYUDR" ("DEFAULTBUSINESSUNIT_ID", "ADJUSTMENTDATE", "CUSTOMERNUMBER", "PRODUCT_CODE", "DEPARTMENTNUMBER", "DISTRIBUTIONPOINTNUMBER", "SIZEDEF_CODE", "FINISHING_CODE", "NAME", "CITY", "DEP_DESC", "DISTRIB_DESC", "REASON_CODE", "QUANTITY", "REASON_DESC", "FINISHING_DESC", "SIZEDEF_DESC", "PRODUCT_DESC", "REMARK") AS 
  SELECT cus.defaultbusinessunit_id, rqa.adjustmentdate,
       cus.customernumber, p.code Product_code, dep.departmentnumber, dp.distributionpointnumber,
       s.code Sizedef_code, f.code Finishing_code, cus.name, a.city, dep.description Dep_desc, dp.description Distrib_desc,
       r.code Reason_code, rqa.quantity,
       (SELECT B.DESCRIPTION FROM reasoncode_desc B WHERE b.reasoncode_id = r.reasoncode_id AND B.LANGUAGE_ID = cus.language_id) Reason_desc,
       (SELECT c.DESCRIPTION FROM finishingmethod_desc c WHERE c.finishingmethod_id = f.finishingmethod_id AND c.LANGUAGE_ID = cus.LANGUAGE_ID) Finishing_desc,
       (SELECT d.DESCRIPTION FROM sizedefinition_desc d WHERE d.sizedefinition_id = s.sizedefinition_id AND d.LANGUAGE_ID = cus.LANGUAGE_ID) Sizedef_desc,
       (SELECT e.DESCRIPTION FROM product_desc e WHERE e.product_id = p.product_id AND e.LANGUAGE_ID = cus.LANGUAGE_ID) Product_desc,
       --(select min(caa.activity_id) from customeractivities caa where caa.customer_id = cus.customer_id and caa.processbusinessunit_id = bu.businessunit_id) min_ACTIVITY_ID,
       rqa.remark
FROM rentalqtyadjustment rqa, reasoncode r
     , productlistperdistribpoint pld
     , distributionpoint dp, department dep, customer cus
     , address a
     , product p, sizedefinition s, finishingmethod f
WHERE
      rqa.productlistperdistribpoint_id = pld.productlistperdistribpoint_id and
      rqa.reasoncode_id = r.reasoncode_id and
      pld.distributionpoint_id = dp.distributionpoint_id and
      dp.department_id = dep.department_id and
      dep.customer_id = cus.customer_id and
      a.address_id = cus.visitaddress_id and
      pld.product_id = p.product_id and
      pld.sizedefinition_id = s.sizedefinition_id and
      pld.finishingmethod_id = f.finishingmethod_id
/

  CREATE OR REPLACE VIEW "V_CIRCULATINGINVENTORYHISTORY" ("DEFAULTBUSINESSUNIT_ID", "ADJUSTMENTDATE", "BUSINESSUNIT_ID", "CUSTOMERNUMBER", "PRODUCT_CODE", "DEPARTMENTNUMBER", "DISTRIBUTIONPOINTNUMBER", "SIZEDEF_CODE", "FINISHING_CODE", "NAME", "CITY", "DEP_DESC", "DISTRIB_DESC", "REASON_CODE", "QUANTITY", "REASON_DESC", "FINISHING_DESC", "SIZEDEF_DESC", "PRODUCT_DESC", "MIN_ACTIVITY_ID", "LANGUAGE_CODE", "REMARK") AS 
  SELECT cus.defaultbusinessunit_id, rqa.adjustmentdate, bu.businessunit_id,
       cus.customernumber, p.code Product_code, dep.departmentnumber, dp.distributionpointnumber,
       s.code Sizedef_code, f.code Finishing_code, cus.name, a.city, dep.description Dep_desc, dp.description Distrib_desc,
       r.code Reason_code, rqa.quantity,
       (SELECT B.DESCRIPTION FROM reasoncode_desc B WHERE b.reasoncode_id = r.reasoncode_id AND B.LANGUAGE_ID = l.LANGUAGE_ID) Reason_desc,
       (SELECT c.DESCRIPTION FROM finishingmethod_desc c WHERE c.finishingmethod_id = f.finishingmethod_id aND c.LANGUAGE_ID = l.LANGUAGE_ID) Finishing_desc,
       (SELECT d.DESCRIPTION FROM sizedefinition_desc d WHERE d.sizedefinition_id = s.sizedefinition_id aND d.LANGUAGE_ID = l.LANGUAGE_ID) Sizedef_desc,
       (SELECT e.DESCRIPTION FROM product_desc e WHERE e.product_id = p.product_id aND e.LANGUAGE_ID = l.LANGUAGE_ID) Product_desc,
       (select min(caa.activity_id) from customeractivities caa where caa.customer_id = cus.customer_id and caa.processbusinessunit_id = bu.businessunit_id) min_ACTIVITY_ID,
       l.code Language_code, rqa.remark
FROM rentalqtyadjustment rqa, reasoncode r
     , productlistperdistribpoint pld
     , distributionpoint dp, department dep, customer cus
     , address a
     , product p, sizedefinition s, finishingmethod f
     , businessunit bu, languages l
WHERE
      rqa.productlistperdistribpoint_id = pld.productlistperdistribpoint_id and
      rqa.reasoncode_id = r.reasoncode_id and
      pld.distributionpoint_id = dp.distributionpoint_id and
      dp.department_id = dep.department_id and
      dep.customer_id = cus.customer_id and
      a.address_id = cus.visitaddress_id and
      pld.product_id = p.product_id and
      pld.sizedefinition_id = s.sizedefinition_id and
      pld.finishingmethod_id = f.finishingmethod_id
/

  CREATE OR REPLACE VIEW "V_CIRCULATINGINVENTORYQTY" ("DEFAULTBUSINESSUNIT_ID", "BUSINESSUNIT_ID", "CUSTOMERNUMBER", "PRODUCT_CODE", "DEPARTMENTNUMBER", "DISTRIBUTIONPOINTNUMBER", "SIZEDEF_CODE", "FINISHING_CODE", "NAME", "CITY", "DEP_DESC", "DISTRIB_DESC", "QUANTITY", "FINISHING_DESC", "SIZEDEF_DESC", "PRODUCT_DESC", "MIN_ACTIVITY_ID", "LANGUAGE_CODE", "ADJUSTMENTDATE", "WIDTH_S", "LENGTH_S") AS 
  SELECT cus.defaultbusinessunit_id, bu.businessunit_id,
       cus.customernumber, p.code Product_code, dep.departmentnumber, dp.distributionpointnumber,
       s.code Sizedef_code, f.code Finishing_code, cus.name, a.city, dep.description Dep_desc, dp.description Distrib_desc,
       SUM(rqa.quantity) quantity,
       (SELECT c.DESCRIPTION FROM finishingmethod_desc c WHERE c.finishingmethod_id = f.finishingmethod_id aND c.LANGUAGE_ID = l.LANGUAGE_ID) Finishing_desc,
       (SELECT d.DESCRIPTION FROM sizedefinition_desc d WHERE d.sizedefinition_id = s.sizedefinition_id aND d.LANGUAGE_ID = l.LANGUAGE_ID) Sizedef_desc,
       (SELECT e.DESCRIPTION FROM product_desc e WHERE e.product_id = p.product_id aND e.LANGUAGE_ID = l.LANGUAGE_ID) Product_desc,
       (select min(caa.activity_id) from customeractivities caa where caa.customer_id = cus.customer_id and caa.processbusinessunit_id = bu.businessunit_id) min_ACTIVITY_ID,
       l.code Language_code, rqa.adjustmentdate,
       s.WIDTH WIDTH_S,s.LENGTH LENGTH_S--CSW
FROM rentalqtyadjustment rqa,
     productlistperdistribpoint pld
     , distributionpoint dp, department dep, customer cus
     , address a
     , product p
     , sizedefinition s, finishingmethod f
     , businessunit bu, languages l
WHERE
      rqa.productlistperdistribpoint_id = pld.productlistperdistribpoint_id and
      pld.distributionpoint_id = dp.distributionpoint_id and
      dp.department_id = dep.department_id and
      dep.customer_id = cus.customer_id and
      a.address_id = cus.visitaddress_id and
      pld.product_id = p.product_id and
      pld.sizedefinition_id = s.sizedefinition_id and
      pld.finishingmethod_id = f.finishingmethod_id
group by cus.defaultbusinessunit_id, bu.businessunit_id,
      cus.customer_id, cus.customernumber, cus.name, a.city,
      dep.departmentnumber, dep.description,
      dp.distributionpointnumber, dp.description,
      p.product_id, p.code,
      s.sizedefinition_id, s.code,
      f.finishingmethod_id, f.code
      , l.LANGUAGE_ID, l.code, rqa.adjustmentdate
      ,s.WIDTH,s.LENGTH
/

  CREATE OR REPLACE VIEW "V_CIRCULATIONSPEED" ("REPORTPARAM_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "PRODUCTCODE", "PRODUCTDESC", "FINISHINGMETHODCODE", "SIZECODE", "DELIVEREDAMOUNT", "INVENTORYQTY", "LANGUAGECODE") AS 
  SELECT rp.reportparam_id, c.customer_id,
  C.CUSTOMERNUMBER, C.NAME CUSTOMERNAME, AD.CITY,
  PR.CODE PRODUCTCODE,
  (SELECT PD.DESCRIPTION FROM PRODUCT_DESC PD WHERE PD.PRODUCT_ID = PR.PRODUCT_ID
    AND PD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESC,
  F.CODE FINISHINGMETHODCODE,
  SZ.CODE SIZECODE,
  SUM(PNL.DELIVEREDAMOUNT) DELIVEREDAMOUNT,
  F_GETINVENTORYQTY(C.CUSTOMER_ID, PR.PRODUCT_ID, SZ.SIZEDEFINITION_ID, F.FINISHINGMETHOD_ID,
  RP.REPORTPARAM_ID) INVENTORYQTY,
  LANGUAGES.CODE LANGUAGECODE
FROM PACKINGNOTE PN, PACKINGNOTELINE PNL, DISTRIBUTIONPOINT DIP, DEPARTMENT DP,
  CUSTOMER C, PRODUCT PR, FINISHINGMETHOD F, SIZEDEFINITION SZ,  ADDRESS AD, STATUS ST,
  reportparam rp, languages
WHERE PN.PACKINGNOTE_ID = PNL.PACKINGNOTE_ID
  AND PN.STATUS_ID = ST.STATUS_ID
  AND ST.STATUSTYPE = 'PN'
  AND ST.CODE = 30
  AND PN.DISTRIBUTIONPOINT_ID = DIP.DISTRIBUTIONPOINT_ID
  AND DIP.DEPARTMENT_ID = DP.DEPARTMENT_ID
  AND DP.CUSTOMER_ID = C.CUSTOMER_ID
  AND C.VISITADDRESS_ID = AD.ADDRESS_ID
  AND PNL.PRODUCT_ID = PR.PRODUCT_ID
  AND PNL.FINISHINGMETHOD_ID = F.FINISHINGMETHOD_ID
  AND PNL.SIZEDEFINITION_ID = SZ.SIZEDEFINITION_ID
  AND PN.DELIVERYDATE >= RP.DATE_VALUE1
  AND PN.DELIVERYDATE <= RP.DATE_VALUE2
GROUP BY c.customer_id, C.CUSTOMERNUMBER, C.NAME, PR.CODE, PR.PRODUCT_ID, F.CODE, SZ.CODE, LANGUAGES.CODE,
  LANGUAGES.LANGUAGE_ID, C.CUSTOMER_ID, PR.PRODUCT_ID, SZ.SIZEDEFINITION_ID, F.FINISHINGMETHOD_ID,
  RP.REPORTPARAM_ID, AD.CITY
union all
select rp2.reportparam_id, c2.customer_id, C2.CUSTOMERNUMBER, C2.NAME CUSTOMERNAME, AD2.CITY,
  PR2.CODE PRODUCTCODE,
  (SELECT PD2.DESCRIPTION FROM PRODUCT_DESC PD2 WHERE PD2.PRODUCT_ID = PR2.PRODUCT_ID
    AND PD2.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESC,
  F2.CODE FINISHINGMETHODCODE,
  SZ2.CODE SIZECODE,
  0 DELIVEREDAMOUNT,
  sum (sq.averageinventoryqty) INVENTORYQTY,
  LANGUAGES.CODE LANGUAGECODE
from sqonsiteinventory sq, statusquoheader sh,
  CUSTOMER C2, PRODUCT PR2, FINISHINGMETHOD F2, SIZEDEFINITION SZ2, ADDRESS AD2,
  reportparam rp2, languages
where
  sq.statusquoheader_id = sh.statusquoheader_id
  and sq.customer_link_id = c2.customer_id
  AND C2.VISITADDRESS_ID = AD2.ADDRESS_ID
  and sq.product_link_id = pr2.product_id
  and sq.finishingmethod_id = f2.finishingmethod_id
  and sq.sizedefinition_link_id = sz2.sizedefinition_id
  and sh.statusquodate >= RP2.DATE_VALUE1
  AND sh.statusquodate <= RP2.DATE_VALUE2
  and not exists
   (SELECT *
    FROM PACKINGNOTE PN, PACKINGNOTELINE PNL, DISTRIBUTIONPOINT DIP, DEPARTMENT DP, STATUS ST
    WHERE PN.PACKINGNOTE_ID = PNL.PACKINGNOTE_ID
      AND PN.STATUS_ID = ST.STATUS_ID
      AND ST.STATUSTYPE = 'PN'
      AND ST.CODE = 30
      AND PN.DISTRIBUTIONPOINT_ID = DIP.DISTRIBUTIONPOINT_ID
      AND DIP.DEPARTMENT_ID = DP.DEPARTMENT_ID
      AND DP.CUSTOMER_ID = sq.customer_link_id
      AND PNL.PRODUCT_ID = sq.product_link_id
      AND PNL.FINISHINGMETHOD_ID = sq.finishingmethod_id
      AND PNL.SIZEDEFINITION_ID = sq.sizedefinition_link_id
      and PN.DELIVERYDATE >= RP2.DATE_VALUE1
      AND PN.DELIVERYDATE <= RP2.DATE_VALUE2)
GROUP BY c2.customer_id, C2.CUSTOMERNUMBER, C2.NAME, PR2.CODE, PR2.PRODUCT_ID, F2.CODE, SZ2.CODE, LANGUAGES.CODE,
  LANGUAGES.LANGUAGE_ID, C2.CUSTOMER_ID, PR2.PRODUCT_ID, SZ2.SIZEDEFINITION_ID, F2.FINISHINGMETHOD_ID,
  RP2.REPORTPARAM_ID, AD2.CITY
/

  CREATE OR REPLACE VIEW "V_CIRCULATIONSPEEDGARMENT" ("REPORTPARAM_ID", "AMOUNTDELIVERED", "TOTALCIRCINV", "CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "FINISHINGMETHODCODE", "LANGUAGECODE") AS 
  select /*+ index(sqh XIE1STATUSQUOHEADER) index(sqi XIF1SQITEMINCIRCULATION)*/
       rp2.reportparam_id,
       f_amountdelivered(sqi.customer_link_id, sqi.product_link_id, sqi.sizedefinition_link_id, sqi.finishingmethod_id, rp2.reportparam_id) amountdelivered,
       (coalesce(sum(sqi.totalcircinv) * 100, 0) +
        coalesce(count(distinct sqi.yearweek), 0)) totalcircinv,
       c2.customernumber, c2.name customername,
       (select ad2.city
         from   address ad2, customer c2
         where  sqi.customer_link_id = c2.customer_id and
                c2.visitaddress_id = ad2.address_id) city,
       (select pr2.code from product pr2 where sqi.product_link_id = pr2.product_id) productcode,
       (select prd.description
         from   product_desc prd
         where  sqi.product_link_id = prd.product_id and
                languages.language_id = prd.language_id) productdesc,
       (select sz2.code
         from   sizedefinition sz2
         where  sqi.sizedefinition_link_id = sz2.sizedefinition_id) sizecode,
       (select f2.code
         from   finishingmethod f2
         where  sqi.finishingmethod_id = f2.finishingmethod_id) finishingmethodcode,
       languages.code languagecode
from   sqitemincirculation sqi, statusquoheader sqh, customer c2, reportparam rp2, languages
where  sqi.statusquoheader_id = sqh.statusquoheader_id and sqi.totalcircinv > 0 and
       sqi.customer_link_id = c2.customer_id and
       sqh.statusquodate between rp2.date_value1 and rp2.date_value2
       and sqh.subtype in (0, 2)
group  by rp2.reportparam_id, sqi.customer_link_id, c2.customernumber, c2.name, sqi.product_link_id,
          sqi.sizedefinition_link_id, sqi.finishingmethod_id, languages.language_id,
          languages.code
/

  CREATE OR REPLACE VIEW "V_CITYCOUNTY" ("TYPE", "NAME", "TAXAUTHORITYCODE", "STARTDATETAXRATE", "OLDTAXRATE", "NEWTAXRATE", "STATESCODE", "STATESNAME", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  select a.type, a.name, a.taxauthoritycode, c.startdatetaxrate, c.oldtaxrate,
c.newtaxrate, b.code statescode, b.name statesname, a.systemuser_id, a.timestamp
from citycounty a, states b, citycountytaxrate c
where a.states_id = b.states_id
and a.citycounty_id = c.citycounty_id
/

  CREATE OR REPLACE VIEW "V_CLEANROOMBATCHCARD" ("CLEANROOMBATCH_ID", "CLEANROOMBATCHNUMBER", "CREATIONDATE", "CREATIONWEEKNO", "DAY_DESCRIPTION", "BATCHQTY", "REMARK", "TREATMENTTYPEDESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "LEGACYCUSTOMERNUMBER", "LANGUAGECODE") AS 
  select cb.cleanroombatch_id, cb.cleanroombatchnumber, cb.creationdate,
getisoweek(cb.creationdate) creationweekno,
(select dd.description
         from   day_desc dd
         where  dd.day_id = getabsdaynumber(cb.creationdate)
         and    dd.language_id = l.language_id) Day_Description,
(select count(cbc1.uniqueitem_id) from cleanroombatchcontent cbc1 where cbc1.cleanroombatch_id = cb.cleanroombatch_id) batchqty,
cb.remark,
(select ttd.description from treatmenttype_desc ttd where ttd.treatmenttype_id = tt.treatmenttype_id and ttd.language_id = l.language_id) treatmenttypedesc,
c.customernumber,
c.name customername,
c.legacycustomernumber,
l.code languagecode
from cleanroombatch cb
left outer join treatmenttype tt on cb.treatmenttype_id = tt.treatmenttype_id
inner join cleanroombatchcontent cbc on cb.cleanroombatch_id = cbc.cleanroombatch_id
inner join uniqueitem ui on cbc.uniqueitem_id = ui.uniqueitem_id
inner join uniqueitemnonpool uinp on cbc.uniqueitem_id = uinp.uniqueitem_id
inner join weareremployment we on uinp.weareremployment_id = we.weareremployment_id
inner join distributionpoint dp on dp.distributionpoint_id = nvl(ui.distributionpoint_id,we.distributionpoint_id)
inner join department d on dp.department_id = d.department_id
inner join customer c on d.customer_id = c.customer_id,
languages l
/

  CREATE OR REPLACE VIEW "V_CLEANROOMBATCHCARD_CONT" ("LINE", "CLEANROOMBATCH_ID", "LANGUAGECODE", "PARENT_CODE", "DISTRIBUTIONPOINTNUMBER", "PRODUCT_ID", "SIZEDEFINITION_ID", "FINISHINGMETHOD_ID", "PARENT_DESC", "FINISHINGCODE", "CP_DESC", "CUSTOMERNAME", "DISTRIBUTIONPOINT_ID", "SORTADDRESS", "REMARKFORPACKINGINSTRUCTIONS", "DELIVERYDATE", "REQUIREDSTERILIZATIONDATE", "INSCAN", "CUSTOMER_ID") AS 
  select 1 line, cbc.cleanroombatch_id, languages.code languagecode, parent_product.code parent_code, dp.distributionpointnumber, p.product_id, ui.sizedefinition_id, ui.finishingmethod_id,
(select pd.description from product_desc pd where pd.product_id = parent_product.product_id and pd.language_id = languages.language_id) parent_desc,
(select max(fc.finishingcode) from productlistpercustomer plpc inner join finishingcode fc on plpc.finishingcode_id = fc.finishingcode_id
 where plpc.customer_id = c.customer_id and plpc.product_id = p.product_id and plpc.finishingmethod_id = ui.finishingmethod_id
       and (plpc.sizedefinition_id = ui.sizedefinition_id or plpc.sizedefinition_id = (select sd.sizedefinition_id from sizedefinition sd where sd.code = '*'))
) finishingcode, dp.description cp_desc, c.name customername, dp.distributionpoint_id,
 (select delp.sortaddress from deliverypoint delp where dp.deliverypoint_id = delp.deliverypoint_id) sortaddress,
nvl(
          (select dff.stringvalue
          from dialogflexfields dff, productlistpercustomer plpc2
          where dff.dialog_id =
          (select d.dialog_id
           from dialogs d
           where d.code = 'ProductListPerCustomer')
           and dff.entity_id = plpc2.productlistpercustomer_id
           and plpc2.customer_id = c.customer_id
           and plpc2.product_id = p.product_id
           and plpc2.sizedefinition_id = (select sd.sizedefinition_id from sizedefinition sd where sd.code = '*')
           and plpc2.finishingmethod_id = ui.finishingmethod_id
           and plpc2.dateactive <= cbcust.deliverydate and plpc2.dateinactive >= cbcust.deliverydate
         ),
         (select dff.stringvalue
          from dialogflexfields dff, productlistpercustomer plpc2
          where dff.dialog_id =
          (select d.dialog_id
           from dialogs d
           where d.code = 'ProductListPerCustomer')
           and dff.entity_id = plpc2.productlistpercustomer_id
           and plpc2.customer_id = c.customer_id
           and plpc2.product_id = p.product_id
           and plpc2.sizedefinition_id = ui.sizedefinition_id
           and plpc2.finishingmethod_id = ui.finishingmethod_id
           and plpc2.dateactive <= cbcust.deliverydate and plpc2.dateinactive >= cbcust.deliverydate
           and plpc2.productlistpercustomer_id = (select min(plpc3.productlistpercustomer_id) from productlistpercustomer plpc3 where plpc3.productlistpercustomer_id = plpc2.productlistpercustomer_id)
         )) remarkforpackinginstructions,
cbcust.deliverydate, cbcust.requiredsterilizationdate, COUNT(1) inscan, c.customer_id
from  cleanroombatchcontent cbc
      left outer join cleanroombatchcustomer cbcust
           inner join distributionpoint dp
                 inner join department dep
                       inner join customer c on dep.customer_id = c.customer_id
                 on dp.department_id = dep.department_id
           on cbcust.distributionpoint_link_id = dp.distributionpoint_id
      on cbc.cleanroombatchcustomer_id = cbcust.cleanroombatchcustomer_id
      inner join uniqueitem ui
            inner join product p
                  inner join product parent_product on p.parentproduct_id = parent_product.product_id
            on ui.product_id = p.product_id
      on cbc.uniqueitem_id = ui.uniqueitem_id
      cross join languages
where cbc.inscanrecord_id is not null
group by cbc.cleanroombatch_id, dp.deliverypoint_id, parent_product.code, dp.description, c.name, p.product_id, ui.sizedefinition_id, ui.finishingmethod_id, c.customer_id, dp.distributionpoint_id,
         ui.product_id, ui.sizedefinition_id, ui.finishingmethod_id, cbcust.deliverydate, cbcust.requiredsterilizationdate, languages.code, languages.language_id, parent_product.product_id,  dp.distributionpointnumber
union all
select 2 line, cbc.cleanroombatch_id, languages.code languagecode, parent_product.code parent_code, dp.distributionpointnumber, p.product_id, ri.sizedefinition_link_id, ri.finishingmethod_id,
(select pd.description from product_desc pd where pd.product_id = parent_product.product_id and pd.language_id = languages.language_id) parent_desc,
(select max(fc.finishingcode) from productlistpercustomer plpc inner join finishingcode fc on plpc.finishingcode_id = fc.finishingcode_id
  where plpc.customer_id = c.customer_id and plpc.product_id = p.product_id and plpc.finishingmethod_id = ri.finishingmethod_id
        and (plpc.sizedefinition_id = ri.sizedefinition_link_id or plpc.sizedefinition_id = (select sd.sizedefinition_id from sizedefinition sd where sd.code = '*'))
  ) finishingcode , dp.description cp_desc, c.name customername, dp.distributionpoint_id,
  (select delp.sortaddress from deliverypoint delp where dp.deliverypoint_id = delp.deliverypoint_id) sortaddress,
nvl(
          (select dff.stringvalue
          from dialogflexfields dff, productlistpercustomer plpc2
          where dff.dialog_id =
          (select d.dialog_id
           from dialogs d
           where d.code = 'ProductListPerCustomer')
           and dff.entity_id = plpc2.productlistpercustomer_id
           and plpc2.customer_id = c.customer_id
           and plpc2.product_id = p.product_id
           and plpc2.sizedefinition_id = (select sd.sizedefinition_id from sizedefinition sd where sd.code = '*')
           and plpc2.finishingmethod_id = ri.finishingmethod_id
           and plpc2.dateactive <= cbcust.deliverydate and plpc2.dateinactive >= cbcust.deliverydate
         ),
         (select dff.stringvalue
          from dialogflexfields dff, productlistpercustomer plpc2
          where dff.dialog_id =
          (select d.dialog_id
           from dialogs d
           where d.code = 'ProductListPerCustomer')
           and dff.entity_id = plpc2.productlistpercustomer_id
           and plpc2.customer_id = c.customer_id
           and plpc2.product_id = p.product_id
           and plpc2.sizedefinition_id = ri.sizedefinition_link_id
           and plpc2.finishingmethod_id = ri.finishingmethod_id
           and plpc2.dateactive <= cbcust.deliverydate and plpc2.dateinactive >= cbcust.deliverydate
           and plpc2.productlistpercustomer_id = (select min(plpc3.productlistpercustomer_id) from productlistpercustomer plpc3 where plpc3.productlistpercustomer_id = plpc2.productlistpercustomer_id)
         )) remarkforpackinginstructions,
cbcust.deliverydate,cbcust.requiredsterilizationdate, COUNT(1) inscan, c.customer_id
from  cleanroombatchcontent cbc
      left outer join cleanroombatchcustomer cbcust
           inner join distributionpoint dp
                 inner join department dep
                       inner join customer c on dep.customer_id = c.customer_id
                 on dp.department_id = dep.department_id
           on cbcust.distributionpoint_link_id = dp.distributionpoint_id
      on cbc.cleanroombatchcustomer_id = cbcust.cleanroombatchcustomer_id
      inner join raggeditem ri
            inner join product p
                  inner join product parent_product on p.parentproduct_id = parent_product.product_id
            on ri.product_link_id = p.product_id
      on cbc.raggeditem_id = ri.raggeditem_id
      cross join languages
where (select cb.batchstatus from cleanroombatch cb where cb.cleanroombatch_id = cbc.cleanroombatch_id) = 2
group by cbc.cleanroombatch_id, parent_product.code, dp.description, c.name, p.product_id, dp.distributionpoint_id, dp.deliverypoint_id, ri.sizedefinition_link_id,
         ri.finishingmethod_id, cbcust.deliverydate, cbcust.requiredsterilizationdate, languages.code, languages.language_id, parent_product.product_id, dp.distributionpointnumber, c.customer_id
union all
select 3 line, cbcust.cleanroombatch_id, languages.code languagecode, parent_product.code parent_code, dp.distributionpointnumber, p.product_id, cbcont.sizedefinition_link_id, cbcont.finishingmethod_id,
(select pd.description from product_desc pd where pd.product_id = parent_product.product_id and pd.language_id = languages.language_id) parent_desc,
  (select max(fc.finishingcode) from productlistpercustomer plpc inner join finishingcode fc on plpc.finishingcode_id = fc.finishingcode_id
   where plpc.customer_id = c.customer_id and plpc.product_id = p.product_id and plpc.finishingmethod_id = cbcont.finishingmethod_id
   and (plpc.sizedefinition_id=cbcont.sizedefinition_link_id or plpc.sizedefinition_id=(select sd.sizedefinition_id from sizedefinition sd where sd.code = '*'))
   ) finishingcode, dp.description cp_desc, c.name customername, dp.distributionpoint_id,
   (select delp.sortaddress from deliverypoint delp where dp.deliverypoint_id = delp.deliverypoint_id) sortaddress,
nvl(
          (select dff.stringvalue
          from dialogflexfields dff, productlistpercustomer plpc2
          where dff.dialog_id =
          (select d.dialog_id
           from dialogs d
           where d.code = 'ProductListPerCustomer')
           and dff.entity_id = plpc2.productlistpercustomer_id
           and plpc2.customer_id = c.customer_id
           and plpc2.product_id = p.product_id
           and plpc2.sizedefinition_id = (select sd.sizedefinition_id from sizedefinition sd where sd.code = '*')
           and plpc2.finishingmethod_id = cbcont.finishingmethod_id
           and plpc2.dateactive <= cbcust.deliverydate and plpc2.dateinactive >= cbcust.deliverydate
         ),
         (select dff.stringvalue
          from dialogflexfields dff, productlistpercustomer plpc2
          where dff.dialog_id =
          (select d.dialog_id
           from dialogs d
           where d.code = 'ProductListPerCustomer')
           and dff.entity_id = plpc2.productlistpercustomer_id
           and plpc2.customer_id = c.customer_id
           and plpc2.product_id = p.product_id
           and plpc2.sizedefinition_id = cbcont.sizedefinition_link_id
           and plpc2.finishingmethod_id = cbcont.finishingmethod_id
           and plpc2.dateactive <= cbcust.deliverydate and plpc2.dateinactive >= cbcust.deliverydate
           and plpc2.productlistpercustomer_id = (select min(plpc3.productlistpercustomer_id) from productlistpercustomer plpc3 where plpc3.productlistpercustomer_id = plpc2.productlistpercustomer_id)
         )) remarkforpackinginstructions,
cbcust.deliverydate, cbcust.requiredsterilizationdate, SUM(cbcont.QUANTITY) inscan, c.customer_id
from CLEANROOMBATCHCOUNTCONTENT  cbcont
      inner join cleanroombatchcustomer cbcust
           inner join distributionpoint dp
                 inner join department dep
                       inner join customer c on dep.customer_id = c.customer_id
                 on dp.department_id = dep.department_id
           on cbcust.distributionpoint_link_id = dp.distributionpoint_id
      on cbcust.cleanroombatchcustomer_id = cbcont.cleanroombatchcustomer_id
      inner join product p
            inner join product parent_product on parent_product.product_id = p.parentproduct_id
      on cbcont.product_link_id = p.product_id
      cross join languages
group by cbcust.cleanroombatch_id, dp.deliverypoint_id, parent_product.code , dp.description, c.name, dp.distributionpoint_id, cbcont.sizedefinition_link_id, cbcont.finishingmethod_id, cbcust.deliverydate,
         cbcust.requiredsterilizationdate, languages.code, languages.language_id, parent_product.product_id, dp.distributionpointnumber, p.product_id, c.customer_id
/

  CREATE OR REPLACE VIEW "V_CLEANROOMSOILSTICKERS" ("CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME") AS 
  select /*version 1.0*/
       cu.customer_id, cu.customernumber, cu.name customername
  from customer cu
/

  CREATE OR REPLACE VIEW "V_CLIENTADDITIONALNOTENUMBER" ("CLIENTDELIVERYNOTE_ID", "ADDITIONALTONOTE_ID", "CLIENTDELIVERYNOTENUMBER") AS 
  select cdn.clientdeliverynote_id, cdn.additionaltonote_id, cdn.clientdeliverynotenumber from
clientdeliverynote cdn
/

  CREATE OR REPLACE VIEW "V_CLIENTBUDGETCONDENSED" ("DELTOCUSTOMER_LINK_ID", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "INVOICEHEADER_ID", "INVOICENUMBER", "INVOICEDATE", "DELTOSTREET", "DELTOSTREET2", "DELTOZIPCODE", "DELTOCITY", "STARTYEAR", "STARTMONTH", "STARTWEEK", "STARTDATE", "ENDYEAR", "ENDMONTH", "ENDWEEK", "ENDDATE", "BILLEDQTY", "AMOUNT", "PRICE", "DISCOUNTPERCENTAGE", "CLIENTNUMBER", "CLIENTNAME", "INVLINETYPE_DESC", "CODE", "DESCRIPTION", "BUDGETCODE", "INVOICELINETYPE_ID", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEPARTMENT_DESC", "QTYSCANNEDOUT", "QTYCOUNTEDOUT", "QTYSCANNEDIN", "QTYCOUNTEDIN", "LANGUAGE_CODE", "LANGUAGE_ID", "CURRENCY_CODE", "PLANTCODE", "PLANTNAME", "PLANTSTREET", "PLANTSTREET2", "PLANTZIPCODE", "PLANTCITY", "PLANTSTATE", "PLANTCOUNTY", "PLANTPHONE", "PLANTFAX", "PLANTWEBSITE", "PLANTEMAIL", "LEGACYCODE") AS 
  select ih.deltocustomer_link_id, ih.deltocustomernumber, cast(ih.deltocustomername AS varchar(60)) deltocustomername,
       ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.deltostreet, ih.deltostreet2, ih.deltozipcode, ih.deltocity,
       ih.startyear, ih.startmonth, ih.startweek, ih.startdate, ih.endyear, ih.endmonth, ih.endweek, ih.enddate,
       il.billedqty, il.amount, il.price, il.discountpercentage, cl.clientnumber, cl.name clientname,
       (select iltd.description from InvoiceLineType_desc iltd where iltd.invoicelinetype_id = il.invoicelinetype_id and iltd.language_id = lan.language_id) InvLineType_desc,
       il.code, il.description, il.budgetcode, il.invoicelinetype_id,
       coalesce(d.department_id,d1.department_id) department_id,
       coalesce(d.departmentnumber,d1.departmentnumber) departmentnumber,
       coalesce(d.description, d1.description) department_desc,
       cdl.qtyscannedout, cdl.qtycountedout, cdl.qtyscannedin, cdl.qtycountedin,
       lan.code Language_code, lan.language_id,
(select curr.code from currency curr where curr.currency_id = ih.currency_id) currency_code,
       p.code plantcode, p.name plantname, x.street plantstreet, x.street2 plantstreet2, x.zipcode plantzipcode,
       x.city plantcity, x.state plantstate, x.county plantcounty, p.phoneno plantphone,
       p.faxno plantfax, p.website plantwebsite, p.email plantemail, cl.legacycode
from invoiceheader ih, invoiceline il, clientdeliverynote cdn, clientdeliverynoteline cdl, client cl
     left outer join clientresident cr
          inner join departmentroom dr
                inner join department d on dr.department_id = d.department_id
          on dr.departmentroom_id = cr.departmentroom_id
     on cr.client_id = cl.client_id
     left outer join clientprivateperson cpp
          inner join distributionpoint dp
                inner join department d1 on d1.department_id = dp.department_id
          on cpp.distributionpoint_id = dp.distributionpoint_id
     on cpp.client_id = cl.client_id,
     languages lan,
      businessunit e,
      plant p, address x
where ih.invoiceheader_id = il.invoiceheader_id and cdl.invoiceline_id = il.invoiceline_id and
      cdl.clientdeliverinote_id = cdn.clientdeliverynote_id and cdn.client_link_id = cl.client_id and
      ih.invoicebusinessunit_id = e.businessunit_id and e.plant_id = p.plant_id and p.address_id = x.address_id
/

  CREATE OR REPLACE VIEW "V_CLIENTBUDGETDETAILED" ("DELTOCUSTOMER_LINK_ID", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "INVOICEHEADER_ID", "INVOICENUMBER", "INVOICEDATE", "DELTOSTREET", "DELTOSTREET2", "DELTOZIPCODE", "DELTOCITY", "STARTYEAR", "STARTMONTH", "STARTWEEK", "STARTDATE", "ENDYEAR", "ENDMONTH", "ENDWEEK", "ENDDATE", "BILLEDQTY", "AMOUNT", "PRICE", "DISCOUNTPERCENTAGE", "CLIENTNUMBER", "CLIENTNAME", "INVLINETYPE_DESC", "CODE", "DESCRIPTION", "BUDGETCODE", "INVOICELINETYPE_ID", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEPARTMENT_DESC", "PRODUCT_CODE", "PRODUCT_DESC", "QTYSCANNEDOUT", "QTYCOUNTEDOUT", "QTYSCANNEDIN", "QTYCOUNTEDIN", "LANGUAGE_CODE", "LANGUAGE_ID", "CURRENCY_CODE", "PLANTCODE", "PLANTNAME", "PLANTSTREET", "PLANTSTREET2", "PLANTZIPCODE", "PLANTCITY", "PLANTSTATE", "PLANTCOUNTY", "PLANTPHONE", "PLANTFAX", "PLANTWEBSITE", "PLANTEMAIL", "LEGACYCODE") AS 
  select ih.deltocustomer_link_id, ih.deltocustomernumber, cast(ih.deltocustomername AS varchar(60)) deltocustomername,
       ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.deltostreet, ih.deltostreet2, ih.deltozipcode, ih.deltocity,
       ih.startyear, ih.startmonth, ih.startweek, ih.startdate, ih.endyear, ih.endmonth, ih.endweek, ih.enddate,
       il.billedqty, il.amount, il.price, il.discountpercentage, cl.clientnumber, cl.name clientname,
       (select iltd.description from InvoiceLineType_desc iltd where iltd.invoicelinetype_id = il.invoicelinetype_id and iltd.language_id = lan.language_id) InvLineType_desc,
       il.code, il.description, il.budgetcode, il.invoicelinetype_id,
       coalesce(d.department_id,d1.department_id) department_id,
       coalesce(d.departmentnumber,d1.departmentnumber) departmentnumber,
       coalesce(d.description, d1.description) department_desc, pr.code product_code,
       (select prd.description from product_desc prd where prd.product_id = pr.product_id and prd.language_id = lan.language_id) product_desc,
       cdl.qtyscannedout, cdl.qtycountedout, cdl.qtyscannedin, cdl.qtycountedin,
       lan.code Language_code, lan.language_id,
(select curr.code from currency curr where curr.currency_id = ih.currency_id) currency_code,
       p.code plantcode, p.name plantname, x.street plantstreet, x.street2 plantstreet2, x.zipcode plantzipcode,
       x.city plantcity, x.state plantstate, x.county plantcounty, p.phoneno plantphone,
       p.faxno plantfax, p.website plantwebsite, p.email plantemail, cl.legacycode
from invoiceheader ih, invoiceline il, clientdeliverynote cdn, clientdeliverynoteline cdl, product pr, client cl
     left outer join clientresident cr
          inner join departmentroom dr
                inner join department d on dr.department_id = d.department_id
          on dr.departmentroom_id = cr.departmentroom_id
     on cr.client_id = cl.client_id
     left outer join clientprivateperson cpp
          inner join distributionpoint dp
                inner join department d1 on d1.department_id = dp.department_id
          on cpp.distributionpoint_id = dp.distributionpoint_id
     on cpp.client_id = cl.client_id,
     languages lan,
      businessunit e,
      plant p, address x
where ih.invoiceheader_id = il.invoiceheader_id and cdl.invoiceline_id = il.invoiceline_id and
      cdl.clientdeliverinote_id = cdn.clientdeliverynote_id and cdn.client_link_id = cl.client_id and
      cdl.product_link_id=pr.product_id and ih.invoicebusinessunit_id = e.businessunit_id
      and e.plant_id = p.plant_id and p.address_id = x.address_id
/

  CREATE OR REPLACE VIEW "V_CLIENTCATEGORYCHECKLIST" ("CUSTOMER_ID", "CLIENTNUMBER", "CLIENTNAME", "ROOMNUMBER", "CLIENTCATEGORYCODE", "CLIENTCATEGORYDESC", "INVENTORYCATEGORYCODE", "INVENTORYCATEGORYDESC", "ACTUALQUANTITY", "MINQUANTITY", "PRODUCTCODE", "PRODUCTDESC", "LANGUAGECODE") AS 
  select c.customer_id, c.clientnumber, c.name clientname, dr.roomnumber,
  cc.categorycode clientcategorycode, cc.description clientcategorydesc,
  ic.categorycode inventorycategorycode, ic.description inventorycategorydesc,
  (select distinct count(uri.uniqueresidentialitem_id)
   from uniqueresidentialitem uri, uniqueresidentialitemproduct urip
   where uri.client_id = c.client_id
     and uri.uniqueresidentialitem_id = urip.uniqueresidentialitem_id
     and urip.product_id = icp.product_id) actualquantity,
  cci.minquantity,
  p.code productcode,
  (select pd.description from product_desc pd where pd.product_id = p.product_id
    and pd.language_id = languages.language_id) productdesc,
  languages.code languagecode
from client c, clientresident cr, departmentroom dr, clientcategory cc, clientcategoryinventory cci,
  inventorycategory ic, inventorycategoryproduct icp, product p,
  languages
where c.client_id = cr.client_id
  and cr.departmentroom_id = dr.departmentroom_id
  and cr.clientcategory_id = cc.clientcategory_id
  and cc.clientcategory_id = cci.clientcategory_id
  and cci.inventorycategory_id = ic.inventorycategory_id
  and ic.inventorycategory_id = icp.inventorycategory_id
  and icp.product_id = p.product_id
/

  CREATE OR REPLACE VIEW "V_CLIENTDELIVERY" ("WEIGHINGCATEGORY_LINK_ID", "PROCESSBUSINESSUNIT_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "CLIENT_ID", "CLIENTNUMBER", "CLIENTNAME", "CLIENTDELIVERYNOTE_ID", "CLIENTDELIVERYNOTENUMBER", "BATCHYEAR", "BATCHWEEK", "BATCH_CODENUMBER", "BATCHNUMBER", "SEQUENCENUMBER", "DELIVERYDATE", "ROUTENUMBER", "ROUTEDESC", "STOPNUMBER", "ROOMNUMBER", "GROSSWEIGHT", "WEIGHTDECIMALS", "INVOICENUMBER", "INVOICESTATUS", "WEIGHTUNIT", "PRODUCTCODE", "SIZECODE", "FINISHINGMETHODCODE", "PRODUCTDESC", "FINISHINGMETHODDESC", "QTYIN", "QTYOUT", "QTY", "BATCHORIGIN", "BATCHSTATUS", "LANGUAGECODE", "INVOICEDTO") AS 
  select cdn.weighingcategory_link_id,
  cdn.processbusinessunit_id, cu.customer_id, cu.customernumber, cu.name customerName
, coalesce(de.departmentnumber, -1) departmentnumber, cli.client_id, cli.clientnumber
, coalesce(cdn.name, cli.name) clientName, cdn.clientdeliverynote_id, cdn.clientdeliverynotenumber
, ba.year batchYear, ba.week batchWeek
, cast(( case
  when ss.value = '-2' then CONCATENATE(GETSUBSTRINGONLENGTH(ba.batchcode, 1, 2), cast(ba.batchnumber as varchar2(255)))
  when ss.value = '-1' then CONCATENATE(GETSUBSTRINGONLENGTH(ba.batchcode, 1, 1), cast(ba.batchnumber as varchar2(255)))
  when ss.value =  '0' then cast(ba.batchnumber as varchar2(255))
  when ss.value =  '1' then CONCATENATE(cast(ba.batchnumber as varchar2(255)), GETSUBSTRINGONLENGTH(ba.batchcode, 1, 1))
  when ss.value =  '2' then CONCATENATE(cast(ba.batchnumber as varchar2(255)), GETSUBSTRINGONLENGTH(ba.batchcode, 1, 2))
  end) as varchar2(255)) batch_CodeNumber, ba.batchnumber
, cdn.sequencenumber, cdn.deliverydate, ro.routenumber, ro.description routeDesc, cdn.stopnumber, cdn.roomnumber
, case when (( cdn.weighingcategory_link_id is not null ) and cdn.grossweight > 0 ) then cdn.grossweight else 0 end grossweight
, cdn.weightdecimals, ih.invoicenumber
, (select st.code from status st where ih.status_id = st.status_id and st.statustype = 'IN') invoiceStatus
, ( select ss2.value from systemsetting ss2 where ss2.plant_id = bu.plant_id and ss2.name = 'WEIGHTUNIT' ) WEIGHTUNIT
, coalesce(prd.code, '') productCode, coalesce(sz.code, '') sizeCode, coalesce(fm.code, '') finishingmethodCode
, coalesce(( select prde.description from product_desc prde where prde.product_id = prd.product_id
  and prde.language_id = lan.language_id ), '') productDesc
, coalesce(( select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
  and fmd.language_id = lan.language_id ), '') finishingmethodDesc
, coalesce(( cdl.qtyscannedin + cdl.qtycountedin ), 0)  qtyIn
, coalesce(( cdl.qtyscannedout + cdl.qtycountedout ), 0) qtyOut
, coalesce((CASE WHEN ih.invoiceheader_id is not null then cdl.qtyscannedout + cdl.qtycountedout
     else 0 end), 0) qty
, ba.origin batchOrigin, ba.status batchStatus, lan.code languageCode
, case when coalesce((select min(cic.invoiceto)
              from clientbillinginfo cbi, clientinvoicecategory cic
              where cli.client_id = cbi.client_id and cbi.clientinvoicecategory_id = cic.clientinvoicecategory_id
              ), 0) = 2
   then coalesce((select min(1)
                 from clientbillinginfo cbi, clientinvoicecategory cic, clientinvoicecategoryproduct cicp
                 where cli.client_id = cbi.client_id and cbi.clientinvoicecategory_id = cic.clientinvoicecategory_id
                 and cicp.clientinvoicecategory_id = cic.clientinvoicecategory_id and cicp.product_id = prd.product_id
                 and cicp.sizedefinition_id = sz.sizedefinition_id and cicp.finishingmethod_id = fm.finishingmethod_id
       ), 0)
   else coalesce((select min(cic.invoiceto)
                 from clientbillinginfo cbi, clientinvoicecategory cic
                 where cli.client_id = cbi.client_id and cbi.clientinvoicecategory_id = cic.clientinvoicecategory_id
       ), 0)
   end InvoicedTo
from clientdeliverynote cdn
      left outer join route ro on cdn.route_id = ro.route_id
      left outer join clientdeliverynoteline cdl
            inner join product prd on cdl.product_link_id = prd.product_id
            inner join sizedefinition sz on cdl.sizedefinition_link_id = sz.sizedefinition_id
            inner join finishingmethod fm on cdl.finishingmethod_id = fm.finishingmethod_id
      on cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
      inner join customer cu on cdn.customer_link_id = cu.customer_id
      inner join client_link cll
           left outer join departmentroom dr
                inner join department de
                      inner join customerresidentialsettings crs1 on de.customer_id = crs1.customer_id and crs1.customerclients = 0
                on dr.department_id = de.department_id
           on cll.departmentroom_id = dr.departmentroom_id
           left outer join deliverypoint dpl
                inner join customerresidentialsettings crs2 on dpl.customer_id = crs2.customer_id and crs2.customerclients = 1
           on cll.deliverypoint_link_id = dpl.deliverypoint_id
           left outer join client cli on cll.client_id = cli.client_id
      on cdn.client_link_id = cll.client_link_id
      inner join batch ba on cdn.batch_id = ba.batch_id
      inner join businessunit bu
            inner join systemsetting ss on bu.plant_id = ss.plant_id AND ss.name = 'BATCHCODEUSAGE'
      on cdn.processbusinessunit_id = bu.businessunit_id
      left outer join invoiceline il
           inner join invoiceheader ih on il.invoiceheader_id = ih.invoiceheader_id
      on coalesce(cdl.invoiceline_id, cdn.invoiceline_id) = il.invoiceline_id
, languages lan
/

  CREATE OR REPLACE VIEW "V_CLIENTDELIVERY1" ("WEIGHINGCATEGORY_LINK_ID", "PROCESSBUSINESSUNIT_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "CLIENT_ID", "CLIENTNUMBER", "CLIENTNAME", "CLIENTDELIVERYNOTE_ID", "CLIENTDELIVERYNOTENUMBER", "BATCHYEAR", "BATCHWEEK", "BATCH_CODENUMBER", "BATCHNUMBER", "SEQUENCENUMBER", "DELIVERYDATE", "ROUTENUMBER", "ROUTEDESC", "STOPNUMBER", "ROOMNUMBER", "GROSSWEIGHT", "WEIGHTDECIMALS", "INVOICENUMBER", "INVOICESTATUS", "WEIGHTUNIT", "PRODUCTCODE", "SIZECODE", "FINISHINGMETHODCODE", "PRODUCTDESC", "FINISHINGMETHODDESC", "QTYIN", "QTYOUT", "QTY", "BATCHORIGIN", "BATCHSTATUS", "LANGUAGECODE", "INVOICEDTO") AS 
  select -- count(*) -- : 2345
--CDL.INVOICELINE_ID,
  cdn.weighingcategory_link_id,
  cdn.processbusinessunit_id, cu.customer_id, cu.customernumber, cu.name customerName
, de.departmentnumber, client.client_id, client.clientnumber
, coalesce(cdn.name, client.name) clientName, cdn.clientdeliverynote_id, cdn.clientdeliverynotenumber
, batch.year batchYear, batch.week batchWeek
, cast(( case
  when ss.value = '-2' then CONCATENATE(GETSUBSTRINGONLENGTH(batch.batchcode, 1, 2), cast(batch.batchnumber as varchar2(255)))
  when ss.value = '-1' then CONCATENATE(GETSUBSTRINGONLENGTH(batch.batchcode, 1, 1), cast(batch.batchnumber as varchar2(255)))
  when ss.value =  '0' then cast(batch.batchnumber as varchar2(255))
  when ss.value =  '1' then CONCATENATE(cast(batch.batchnumber as varchar2(255)), GETSUBSTRINGONLENGTH(batch.batchcode, 1, 1))
  when ss.value =  '2' then CONCATENATE(cast(batch.batchnumber as varchar2(255)), GETSUBSTRINGONLENGTH(batch.batchcode, 1, 2))
  end) as varchar2(255)) batch_CodeNumber, batch.batchnumber
, cdn.sequencenumber, cdn.deliverydate, route.routenumber, route.description routeDesc, cdn.stopnumber, cdn.roomnumber
, case when (( cdn.weighingcategory_link_id is not null ) and cdn.grossweight > 0 ) then cdn.grossweight else 0 end grossweight
, cdn.weightdecimals, ih.invoicenumber, st.code invoiceStatus
, ( select systemsetting.value from systemsetting where systemsetting.plant_id = bu.plant_id and systemsetting.name = 'WEIGHTUNIT' ) WEIGHTUNIT
, prd.code productCode, sz.code sizeCode, fm.code finishingmethodCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( select finishingmethod_desc.description from finishingmethod_desc where finishingmethod_desc.finishingmethod_id = fm.finishingmethod_id
  and finishingmethod_desc.language_id = languages.language_id ) finishingmethodDesc
, ( cdl.qtyscannedin + cdl.qtycountedin ) qtyIn
, ( cdl.qtyscannedout + cdl.qtycountedout ) qtyOut
--, ( cdl.qtyscannedin + cdl.qtycountedin + cdl.qtyscannedout + cdl.qtycoutedout ) qty
, (CASE WHEN ih.invoiceheader_id is not null then cdl.qtyscannedout + cdl.qtycountedout
     else 0 end) qty
, batch.origin batchOrigin, batch.status batchStatus
, languages.code languageCode
, case when coalesce((select min(cic.invoiceto)
              from clientbillinginfo cbi, clientinvoicecategory cic
              where client.client_id = cbi.client_id and cbi.clientinvoicecategory_id = cic.clientinvoicecategory_id
              ), 0) = 2
   then coalesce((select min(1)
                 from clientbillinginfo cbi, clientinvoicecategory cic, clientinvoicecategoryproduct cicp
                 where client.client_id = cbi.client_id and cbi.clientinvoicecategory_id = cic.clientinvoicecategory_id
                 and cicp.clientinvoicecategory_id = cic.clientinvoicecategory_id and cicp.product_id = prd.product_id
                 and cicp.sizedefinition_id = sz.sizedefinition_id and cicp.finishingmethod_id = fm.finishingmethod_id
       ), 0)
   else coalesce((select min(cic.invoiceto)
                 from clientbillinginfo cbi, clientinvoicecategory cic
                 where client.client_id = cbi.client_id and cbi.clientinvoicecategory_id = cic.clientinvoicecategory_id
       ), 0)
   end InvoicedTo
from
  clientdeliverynote cdn
    left outer join route on cdn.route_id = route.routenumber
, customer cu, batch
, client, client_link, departmentroom dr, department de
/*, clientdeliverynoteline cdl
    left outer join
         ( invoiceheader ih join status st on ih.status_id = st.status_id and st.statustype = 'IN' )
         on cdl.invoiceheader_id = ih.invoiceheader_id */
, clientdeliverynoteline cdl
    left outer join (invoiceline il
      left join (invoiceheader ih
        left join status st on ih.status_id = st.status_id and st.statustype = 'IN')
      on il.invoiceheader_id = ih.invoiceheader_id)
    on cdl.invoiceline_id = il.invoiceline_id
, product prd, sizedefinition sz, finishingmethod fm
, businessunit bu, systemsetting ss
, languages
where
    cdn.customer_link_id = cu.customer_id
and cdn.client_link_id = client.client_id
    and client.client_id = client_link.client_id
        and client_link.departmentroom_id = dr.departmentroom_id
            and dr.department_id = de.department_id
and cdn.batch_id = batch.batch_id
and cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
    and cdl.product_link_id = prd.product_id
    and cdl.sizedefinition_link_id = sz.sizedefinition_id
    and cdl.finishingmethod_id = fm.finishingmethod_id
and cdn.processbusinessunit_id = bu.businessunit_id
    and bu.plant_id = ss.plant_id
        AND ss.name = 'BATCHCODEUSAGE'
union all
select -- count(*) -- : 2345
--CDL.INVOICELINE_ID,
  cdn.weighingcategory_link_id,
  cdn.processbusinessunit_id, cu.customer_id, cu.customernumber, cu.name customerName
, -1 departmentnumber, client.client_id, client.clientnumber
, coalesce(cdn.name, client.name) clientName, cdn.clientdeliverynote_id, cdn.clientdeliverynotenumber
, batch.year batchYear, batch.week batchWeek
, cast(( case
  when ss.value = '-2' then CONCATENATE(GETSUBSTRINGONLENGTH(batch.batchcode, 1, 2), cast(batch.batchnumber as varchar2(255)))
  when ss.value = '-1' then CONCATENATE(GETSUBSTRINGONLENGTH(batch.batchcode, 1, 1), cast(batch.batchnumber as varchar2(255)))
  when ss.value =  '0' then cast(batch.batchnumber as varchar2(255))
  when ss.value =  '1' then CONCATENATE(cast(batch.batchnumber as varchar2(255)), GETSUBSTRINGONLENGTH(batch.batchcode, 1, 1))
  when ss.value =  '2' then CONCATENATE(cast(batch.batchnumber as varchar2(255)), GETSUBSTRINGONLENGTH(batch.batchcode, 1, 2))
  end) as varchar2(255)) batch_CodeNumber, batch.batchnumber
, cdn.sequencenumber, cdn.deliverydate, route.routenumber, route.description routeDesc, cdn.stopnumber, cdn.roomnumber
, case when (( cdn.weighingcategory_link_id is not null ) and cdn.grossweight > 0 ) then cdn.grossweight else 0 end grossweight
, cdn.weightdecimals, ih.invoicenumber, st.code invoiceStatus
, ( select systemsetting.value from systemsetting where systemsetting.plant_id = bu.plant_id and systemsetting.name = 'WEIGHTUNIT' ) WEIGHTUNIT
, prd.code productCode, sz.code sizeCode, fm.code finishingmethodCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( select finishingmethod_desc.description from finishingmethod_desc where finishingmethod_desc.finishingmethod_id = fm.finishingmethod_id
  and finishingmethod_desc.language_id = languages.language_id ) finishingmethodDesc
, ( cdl.qtyscannedin + cdl.qtycountedin ) qtyIn
, ( cdl.qtyscannedout + cdl.qtycountedout ) qtyOut
--, ( cdl.qtyscannedin + cdl.qtycountedin + cdl.qtyscannedout + cdl.qtycoutedout ) qty
, (CASE WHEN ih.invoiceheader_id is not null then cdl.qtyscannedout + cdl.qtycountedout
     else 0 end) qty
, batch.origin batchOrigin, batch.status batchStatus
, languages.code languageCode
, case when coalesce((select min(cic.invoiceto)
              from clientbillinginfo cbi, clientinvoicecategory cic
              where client.client_id = cbi.client_id and cbi.clientinvoicecategory_id = cic.clientinvoicecategory_id
              ), 0) = 2
   then coalesce((select min(1)
                 from clientbillinginfo cbi, clientinvoicecategory cic, clientinvoicecategoryproduct cicp
                 where client.client_id = cbi.client_id and cbi.clientinvoicecategory_id = cic.clientinvoicecategory_id
                 and cicp.clientinvoicecategory_id = cic.clientinvoicecategory_id and cicp.product_id = prd.product_id
                 and cicp.sizedefinition_id = sz.sizedefinition_id and cicp.finishingmethod_id = fm.finishingmethod_id
       ), 0)
   else coalesce((select min(cic.invoiceto)
                 from clientbillinginfo cbi, clientinvoicecategory cic
                 where client.client_id = cbi.client_id and cbi.clientinvoicecategory_id = cic.clientinvoicecategory_id
       ), 0)
   end InvoicedTo
from
  clientdeliverynote cdn
    left outer join route on cdn.route_id = route.routenumber
, customer cu, batch
, client, client_link, deliverypoint dpl--, department de
/*, clientdeliverynoteline cdl
    left outer join
         ( invoiceheader ih join status st on ih.status_id = st.status_id and st.statustype = 'IN' )
         on cdl.invoiceheader_id = ih.invoiceheader_id */
, clientdeliverynoteline cdl
    left outer join (invoiceline il
      left join (invoiceheader ih
        left join status st on ih.status_id = st.status_id and st.statustype = 'IN')
      on il.invoiceheader_id = ih.invoiceheader_id)
    on cdl.invoiceline_id = il.invoiceline_id
, product prd, sizedefinition sz, finishingmethod fm
, businessunit bu, systemsetting ss
, languages
where
    cdn.customer_link_id = cu.customer_id
and cdn.client_link_id = client.client_id
    and client.client_id = client_link.client_id
        and client_link.deliverypoint_link_id= dpl.deliverypoint_id
            and dpl.customer_id = cu.customer_id
and cdn.batch_id = batch.batch_id
and cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
    and cdl.product_link_id = prd.product_id
    and cdl.sizedefinition_link_id = sz.sizedefinition_id
    and cdl.finishingmethod_id = fm.finishingmethod_id
and cdn.processbusinessunit_id = bu.businessunit_id
    and bu.plant_id = ss.plant_id
        AND ss.name = 'BATCHCODEUSAGE'
/

  CREATE OR REPLACE VIEW "V_CLIENTDELIVERYNOTELABELS" ("CLIENTDELIVERYNOTE_ID", "PRICE", "QUANTITY", "PRICEDECIMALS", "AMOUNTDECIMALS") AS 
  select /*version 2.0*/
       p.clientdeliverynote_id, p.price, p.quantity,
       (select crr.decimals
          from currency crr
               join customer cu
                    join clientdeliverynote cdn on cu.customer_id = cdn.customer_link_id
               on crr.currency_id = cu.currency_id
         where cdn.clientdeliverynote_id = p.clientdeliverynote_id) pricedecimals,
       (select crr.invoiceamountdecimals
          from currency crr
               join customer cu
                    join clientdeliverynote cdn on cu.customer_id = cdn.customer_link_id
               on crr.currency_id = cu.currency_id
         where cdn.clientdeliverynote_id = p.clientdeliverynote_id) amountdecimals
from printqueueresidentialitem p
where p.chargeable = 'Y'
/

  CREATE OR REPLACE VIEW "V_CLIENTDELIVERYNOTESCHARGE" ("CLIENTDELIVERINOTE_ID", "LANGUAGECODE", "CODE", "DESCRIPTION", "QUANTITY", "PRICE", "PRICEONDELNOTE", "PRICEDECIMALS", "AMOUNTDECIMALS") AS 
  select /*version 2.0*/
       cdsc.clientdeliverinote_id, l.code languagecode,
       sc.code,
       (select sd.description from specialcharge_desc sd where sd.specialcharge_id = cdsc.specialcharge_id
       and l.language_id = sd.language_id) description,
       cdsc.quantity, cdsc.price, cdsc.priceondelnote,
       (select crr.decimals
          from currency crr
               join customer cu
                    join clientdeliverynote cdn on cu.customer_id = cdn.customer_link_id
               on crr.currency_id = cu.currency_id
         where cdn.clientdeliverynote_id = cdsc.clientdeliverinote_id) pricedecimals,
       (select crr.invoiceamountdecimals
          from currency crr
               join customer cu
                    join clientdeliverynote cdn on cu.customer_id = cdn.customer_link_id
               on crr.currency_id = cu.currency_id
         where cdn.clientdeliverynote_id = cdsc.clientdeliverinote_id) amountdecimals
from clientdeliverynotespeccharge cdsc
     join specialcharge sc on cdsc.specialcharge_id = sc.specialcharge_id
     cross join languages l
-- ClientDeliveryNote.rpt
/

  CREATE OR REPLACE VIEW "V_CLIENTDELIVERYNOTEVAT" ("CLIENTDELIVERINOTE_ID", "STARTDATETAXRATE", "CODE", "TAXDESC", "TAXPERCENTAGE", "TAXAMOUNT", "AMOUNTDECIMALS") AS 
  select /*version 2.0*/
       cdt.clientdeliverinote_id, tg.startdatetaxrate, tg.code, tg.description taxdesc, cdt.taxpercentage, cdt.taxamount,
       (select crr.invoiceamountdecimals
         from currency crr
         join customer cu
         join clientdeliverynote cdn on cu.customer_id = cdn.customer_link_id on crr.currency_id = cu.currency_id
        where cdn.clientdeliverynote_id = cdt.clientdeliverinote_id) amountdecimals
  from clientdeliverynotetax cdt, taxgroup tg
 where cdt.taxgroup_id = tg.taxgroup_id
/

  CREATE OR REPLACE VIEW "V_CLIENTDELIVERYNOTE_FLAG" ("PRINTIDCODE", "UNIQUERESIDENTIALITEM_LINK_ID", "SCANTIMESTAMP", "LANGUAGE_CODE", "FLAGCODE", "FLAGDESC") AS 
  select 'Y' printidcode, ris.uniqueresidentialitem_link_id, trunc(ris.scantimestamp) scantimestamp, languages.code Language_code, flag.code flagCode, (select flag_desc.description from flag_desc where flag.flag_id = flag_desc.flag_id and flag_desc.language_id = languages.language_id) flagDesc
from flag, residentialitemscan ris, residentialitemscanflag risf, languages
where risf.flag_id = flag.flag_id and ris.residentialitemscan_id = risf.residentialitemscan_id
and ris.transactiontype_id = 2
--and cds.uniqueresidentialitem_link_id = ris.uniqueresidentialitem_link_id
--and trunc(cds.outscantimestamp) = trunc(ris.scantimestamp)
--union all select 'N' printidcode, null, null, null, null, null from dual
/

  CREATE OR REPLACE VIEW "V_CLIENTDEPARTMENT_EXT" ("CUSTOMER_ID", "CLIENT_ID", "CLIENTNUMBER", "CLIENT_SEARCHNAME", "CLIENT_NAME", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEP_DESC", "ROOMNUMBER", "CUSTOMER_NUMBER", "CUSTOMER_NAME", "DATEACTIVE", "DATEINACTIVE", "DECEASEDDATE", "LANGUAGECODE", "WEBUSERDEPARTMENT_ID", "WEBSESSION_ID", "WEBUSER_ID", "CURRENTDATE") AS 
  select cli.customer_id, cli.client_id, cli.clientnumber
, cli.searchname Client_searchname, cli.name Client_name
, coalesce(d.department_id,d1.department_id) department_id
, coalesce(d.departmentnumber,d1.departmentnumber) departmentnumber
, coalesce(d.description, d1.description) Dep_desc
, coalesce(dr.roomnumber, '-') roomnumber
,cu.customernumber Customer_number, cu.name Customer_name
,cli.dateactive , cli.dateinactive
,cr.deceaseddate,
languages.code languagecode,
  wd.department_id webuserdepartment_id,
  wus.websession_id websession_id,
  wc.webuser_id webuser_id, trunc(sysdate) CurrentDate
from client cli left outer join clientresident cr
                     join departmentroom dr
                       join department d on dr.department_id = d.department_id
                     on dr.departmentroom_id = cr.departmentroom_id
                on cli.client_id = cr.client_id
                left outer join clientprivateperson cpp
                        join distributionpoint dp
                            join department d1 on d1.department_id = dp.department_id
                        on cpp.distributionpoint_id = dp.distributionpoint_id
                on cpp.client_id = cli.client_id
                join customer cu
                     on cli.customer_id=cu.customer_id
                    join webusercustomer wc
                     on wc.customer_id = cu.customer_id
                     left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id)
                          join webusersession wus
                               on wus.customer_id = wc.customer_id,
                              languages
/

  CREATE OR REPLACE VIEW "V_CLIENTNOTE_NEW_DEPBOX" ("CLIENTDELIVERYNOTE_ID", "BATCH_ID", "BOXNUMBER", "CUSTOMERNUMBER", "DEPARTMENTNUMBER", "CHANGE_YN", "STATE") AS 
  select /*view v_clientnote_new_depbox version 0.2*/
 cdn.clientdeliverynote_id, cdn.batch_id, cdn.boxnumber, c.customernumber, t.departmentnumber,
 case cdn.boxnumber
    when 1 then
     'N'
    else
     case
      (lag(c.customernumber * 1000 + t.departmentnumber) over(order by cdn.batch_id, cdn.boxnumber))
       when null then
        'N'
       when c.customernumber * 1000 + t.departmentnumber then
        'N'
       else
        'Y'
     end
  end change_yn, cdn.state
from   clientdeliverynote cdn
join   client cl
on     cl.client_id = cdn.client_link_id
join   clientresident cr
on     cr.client_id = cl.client_id
join   departmentroom dr
on     dr.departmentroom_id = cr.departmentroom_id
join   department t
on     t.department_id = dr.department_id
join   customer c
on     c.customer_id = t.customer_id
where  cdn.deliverydate > trunc(sysdate) - 7
order  by cdn.batch_id, cdn.boxnumber, c.customernumber, t.departmentnumber
/

  CREATE OR REPLACE VIEW "V_CLIENTRENT" ("CLIENTRENTADJUSTMENT_ID", "CUSTOMER_ID", "CLIENT_ID", "CLIENTNUMBER", "NAME", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTDESC", "SIZEDEFINITION_ID", "CODE", "FINISHINGMETHOD_ID", "FM_CODE", "LANGUAGE_ID", "CURRENTQUANTITY", "LASTADJUSTMENTDATE") AS 
  select cra.clientrentadjustment_id,
c.customer_id,
cra.client_id,
c.clientnumber,
c.name,
cra.product_id,
p.code productcode,
(select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = l.language_id) productdesc,
cra.sizedefinition_id,
sd.code,
cra.finishingmethod_id,
fm.code fm_code,
l.language_id,
sum(cra.quantity) currentquantity,
max(cra.adjustmentdate) lastadjustmentdate
from clientrentadjustment cra, client c, product p, sizedefinition sd, finishingmethod fm, languages l
where cra.client_id = c.client_id
and cra.product_id = p.product_id
and cra.sizedefinition_id = sd.sizedefinition_id
and cra.finishingmethod_id = fm.finishingmethod_id
group by cra.client_id, c.clientnumber, cra.product_id,
cra.sizedefinition_id, cra.finishingmethod_id,
c.customer_id, c.name, p.product_id, p.code, l.language_id,
sd.code, fm.code, cra.clientrentadjustment_id
/

  CREATE OR REPLACE VIEW "V_CLIENTRENTREPORT" ("CLIENTNUMBER", "CLIENTNAME", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTDESC", "SIZEDEFINITION_ID", "SIZECODE", "FINISHINGMETHOD_ID", "FM_CODE", "LANGUAGE_CODE", "CURRENTQUANTITY", "ADJUSTMENTDATE", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DECIMALS", "INVOICEAMOUNTDECIMALS", "BUSINESSUNIT_ID", "PRICE") AS 
  select c.clientnumber, c.name clientname, cra.product_id, p.code productcode,
(select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = l.language_id) productdesc,
cra.sizedefinition_id, sd.code sizecode, cra.finishingmethod_id, fm.code fm_code, l.code language_code,
sum(cra.quantity) currentquantity, cra.adjustmentdate,
cu.customernumber, cu.name customername, dep.departmentnumber, dep.description departmentdesc,
curr.decimals, curr.invoiceamountdecimals, bu.businessunit_id,
pack_price.ResidentialRent_Price(cu.customer_id, p.product_id, sd.sizedefinition_id, fm.finishingmethod_id, cra.adjustmentdate) price
from clientrentadjustment cra, client c, product p, sizedefinition sd, finishingmethod fm, languages l
, customer cu, department dep, currency curr, businessunit bu, clientresident cr, departmentroom dr
where cra.client_id = c.client_id
and cra.product_id = p.product_id
and cra.sizedefinition_id = sd.sizedefinition_id
and cra.finishingmethod_id = fm.finishingmethod_id
and c.customer_id = cu.customer_id
and cu.customer_id = dep.customer_id
and cu.currency_id = curr.currency_id
and c.client_id = cr.client_id
and cr.departmentroom_id = dr.departmentroom_id
and dr.department_id = dep.department_id
and (cu.defaultbusinessunit_id = bu.businessunit_id or
    exists (select 1 from customeractivities ca where ca.customer_id = cu.customer_id and ca.processbusinessunit_id = bu.businessunit_id))
group by c.clientnumber, cra.product_id,
cra.sizedefinition_id, cra.finishingmethod_id,
c.name, p.product_id, p.code, l.code, l.language_id, bu.businessunit_id,
sd.code, fm.code, cu.customer_id, p.product_id, sd.sizedefinition_id, fm.finishingmethod_id, cra.adjustmentdate,
cu.customernumber, cu.name, dep.departmentnumber, dep.description, curr.decimals, curr.invoiceamountdecimals
/

  CREATE OR REPLACE VIEW "V_COLOR" ("CODE", "DESCRIPTION", "RALCODE", "SYSTEMUSER_ID", "TIMESTAMP", "COLOR_ID") AS 
  SELECT COLOR.CODE,
(SELECT DESCRIPTION FROM COLOR_DESC WHERE COLOR_DESC.COLOR_ID = COLOR.COLOR_ID AND COLOR_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) DESCRIPTION, COLOR.RALCODE, COLOR.SYSTEMUSER_ID, COLOR.TIMESTAMP, COLOR.COLOR_ID
       FROM COLOR,  LANGUAGES
/

  CREATE OR REPLACE VIEW "V_COMBINEDPACKINGNOTE" ("CUSTOMER_ID", "DEPARTMENT_ID", "DISTRIBUTIONPOINT_ID", "DELIVERYDATE", "COMBINEDTRANSPORTATIONNR", "NOTENUMBER", "PACKINGNOTE_ID", "COMBINEDPACKINGNOTE_ID", "COMBINEDNOTENUMBER") AS 
  select dep.customer_id,
       dp.department_id,
       pn.distributionpoint_id,
       pn.deliverydate,
       pn.combinedtransportationnr,
       pn.notenumber,
       pn.packingnote_id,
       pn2.packingnote_id combinedpackingnote_id,
       pn2.notenumber combinednotenumber
  from packingnote       pn,
       distributionpoint dp,
       department        dep,
       packingnote       pn2,
       distributionpoint dp2,
       department        dep2
 where dp.distributionpoint_id = pn.distributionpoint_id
   and dep.department_id = dp.department_id
   and dep.customer_id = dep2.customer_id
   and dp2.department_id = dep2.department_id
   and pn2.distributionpoint_id = dp2.distributionpoint_id
   and pn.packingnote_id <> pn2.packingnote_id
   and pn.deliverydate = pn2.deliverydate
   and pn.combinedtransportationnr is not null
   and pn.combinedtransportationnr = pn2.combinedtransportationnr
   and pn.status_id not in (select s.status_id from status s where s.statustype = 'PN' and (s.code=40 or s.code=60))
   and pn2.status_id not in (select s.status_id from status s where s.statustype = 'PN' and (s.code=40 or s.code=60))
/

  CREATE OR REPLACE VIEW "V_COMMISSIONBYSALESPERSON" ("PLANT_ID", "PLANTCODE", "BUSINESSUNIT_ID", "ARTRANSACTIONDATE", "TURNOVERGROUP_CODE", "TURNOVERGROUP_ID", "DEBITCRED", "TYPENR", "DEBITCREDIT", "BILLCUST", "TURNOVERGROUP_DESC", "DRIVER", "SALESPERSON", "ACCOUNTMANAGER", "AMOUNT", "AMOUNTINPLANTCURRENCY", "COMMISSIONPERCENTAGE", "ROUTENUMBER", "EMPLOYEENUMBER", "EMPLOYEENAME", "INVOICEAMOUNTDECIMALS", "PRICEDECIMALS", "LANGUAGE_CODE", "INVOICENUMBER", "INVOICEDATE", "INVOICEHEADER_ID", "SEARCHNAME", "ARTRANSACTIONCOMMISSIONAMOUNT") AS 
  SELECT pl.plant_id, pl.code PlantCode, t.businessunit_id, t.artransactiondate
, tg.code TurnoverGroup_Code, td.turnovergroup_id
, (select x.debitcredit from artransactiontype x where x.artransactiontype_id=t.artransactiontype_id) debitcred
, (select x.typenumber from artransactiontype x where x.artransactiontype_id=t.artransactiontype_id) typenr
, t.debitcredit
, (select y.name from customer y where y.customer_id=t.billtocustomer_link_id) billcust
, (select tgd.description from turnovergroup_desc tgd where tg.turnovergroup_id=tgd.turnovergroup_id and tgd.language_id=lan.language_id) TurnoverGroup_desc
, tc.driver, tc.salesperson, tc.accountmanager
, coalesce( (select cd.overamount from Commissiondetail cd where cd.artransaction_id=t.artransaction_id and tc.turnovergroup_id=cd.turnovergroup_id and cd.employee_id = tc.employee_id ),  td.amount) amount,
td.amountinplantcurrency, tc.commissionpercentage
, r.routenumber
, e.employeenumber, e.name employeename
, crr.invoiceamountdecimals, crr.decimals PriceDecimals
, lan.code Language_code
, ih.invoicenumber, ih.invoicedate, ih.invoiceheader_id
, (select s.searchname from Customer S where s.customer_id = ih.deltocustomer_link_id ) Searchname
, tc.amount ARTransactionCommissionAmount
FROM ARTransactionDetail td, ARTransactionCommission tc, ARTransaction t
left outer join  Invoiceheader Ih
     left outer join Route r on ih.route_id=r.route_id
on t.invoiceheader_id=ih.invoiceheader_id
, Employee e, Turnovergroup tg
, businessunit bu, plant pl, country co, currency crr
, languages lan
WHERE t.artransaction_id = tc.artransaction_id and td.artransaction_id = t.artransaction_id
and tg.turnovergroup_id = tc.turnovergroup_id and tc.employee_id = e.employee_id
and t.businessunit_id = bu.businessunit_id and pl.plant_id = bu.plant_id
and pl.country_id = co.country_id and co.defaultcurrency_id = crr.currency_id
and t.commissioncalculated = 'Y'
and td.turnovergroup_id = tg.turnovergroup_id
/

  CREATE OR REPLACE VIEW "V_COMPANYSTAMP" ("IMAGE", "IMAGE_ID", "LANGUAGECODE") AS 
  select im.image, im.image_id, lan.code languagecode from image im, languages lan
where im.imagetype = 5
/

  CREATE OR REPLACE VIEW "V_COMPETITOR" ("COMPETITORCODE", "COMPETITORNAME", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  SELECT COMPETITOR.CODE, COMPETITOR.NAME, COMPETITOR.SYSTEMUSER_ID, COMPETITOR.TIMESTAMP
       FROM COMPETITOR
/

  CREATE OR REPLACE VIEW "V_COMPRESSEDDELIVERYNOTE" ("PACKINGNOTE_ID", "NOTENUMBER", "DELIVERYDATE", "PRODUCTIONDATE", "REMARK", "ORIGIN", "STOPNUMBER", "ROUTE_ID", "CORRECTEDNOTENUMBER", "CONSIGNMENTNOTE_ID", "YEAR", "WEEK", "DAYNUMBER", "TOTALAMOUNT", "TOTALAMOUNTEXCLUDINGVAT", "INVOICEHEADER_ID", "AMOUNT", "VAT") AS 
  select h.packingnote_id, h.notenumber, h.deliverydate, h.productiondate, h.remark, h.origin,
       --h.invoiceheader_id,
       h.stopnumber, h.route_id, h.correctednotenumber,
       h.consignmentnote_id, h.year, h.week, h.daynumber,
       h.totalamount, h.totalamountexcludingvat,
       l.invoiceheader_id, l.amount
, coalesce((select pnt.taxpercentage from packingnotetax pnt where l.packingnote_id = pnt.packingnote_id and l.taxgroupcode = pnt.taxgroupcode), 0) vat
from PACKINGNOTE H, STATUS, packingnoteline l
where H.STATUS_ID = STATUS.STATUS_ID
      AND (STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20))
      AND H.PRICESCALCULATED = 'Y'
      and l.packingnote_id=h.packingnote_id
union all
select h.packingnote_id, h.notenumber, h.deliverydate, h.productiondate, h.remark, h.origin,
       --h.invoiceheader_id,
       h.stopnumber, h.route_id, h.correctednotenumber,
       h.consignmentnote_id, h.year, h.week, h.daynumber,
       h.totalamount, h.totalamountexcludingvat,
       c.invoiceheader_id, c.amount
, coalesce((select pnt.taxpercentage from packingnotetax pnt where c.packingnote_id = pnt.packingnote_id and c.taxgroupcode = pnt.taxgroupcode), 0) vat
from PACKINGNOTE H, STATUS, packingnotecontainer c
where H.STATUS_ID = STATUS.STATUS_ID
      AND (STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20))
      AND H.PRICESCALCULATED = 'Y'
      and c.packingnote_id=h.packingnote_id
/

  CREATE OR REPLACE VIEW "V_COMPRESSEDDELIVERYNOTE_INV" ("INVOICEHEADER_ID", "INVOICEDATE", "INVOICENUMBER", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "DELTOSTREET", "DELTOSTREET2", "DELTOCOUNTY", "DELTOSTATE", "DELTOCITY", "DELTOZIPCODE", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "STREET", "STREET2", "COUNTY", "STATE", "CITY", "ZIPCODE", "TOTALAMOUNTEXCLVAT", "TOTALMINUSADJUSTMENT", "TOTALPLUSADJUSTMENT", "PREBILLAMOUNT", "PAYTHISAMOUNT", "ENDWEEK", "ENDMONTH", "ENDYEAR", "ENDDATE", "STARTWEEK", "STARTMONTH", "STARTYEAR", "STARTDATE", "CONTACTPERSONPHONE", "CONTACTPERSONNAME", "STOPNUMBER", "INVOICETYPE", "INVOICEYEAR", "INVOICEWEEK", "INVOICEDAYNUMBER", "PURCHASEORDER", "DELIVERINSTRUCTIONS", "INVOICECOMMENTS", "ROUTENUMBER", "CONTRACTCODE", "CONTRACTSTARTDATE", "CONTRACTENDDATE", "DEPOTCODE", "SPLITUPCODE", "SPLITUPDESCRIPTION", "EXTRANAME1", "EXTRANAME2", "CREDITSQUEEZEAMOUNT", "CREDITSQUEEZEPERC", "ROUNDINGAMOUNT", "CURRENCY_CODE", "CURRENCY_DESC", "INVOICEAMOUNTDECIMALS", "DECIMALS") AS 
  SELECT H.INVOICEHEADER_ID, H.INVOICEDATE, H.INVOICENUMBER,
       H.DELTOCUSTOMERNUMBER, H.DELTOCUSTOMERNAME,
       H.DELTOSTREET, H.DELTOSTREET2, H.DELTOCOUNTY, H.DELTOSTATE, H.DELTOCITY, H.DELTOZIPCODE,
       H.BILLTOCUSTOMERNUMBER, H.BILLTOCUSTOMERNAME,
       H.STREET, H.STREET2, H.COUNTY, H.STATE, H.CITY, H.ZIPCODE,
       H.TOTALAMOUNTEXCLVAT, H.TOTALMINUSADJUSTMENT, H.TOTALPLUSADJUSTMENT,
       H.PREBILLAMOUNT, H.PAYTHISAMOUNT,
       H.ENDWEEK, H.ENDMONTH, H.ENDYEAR, H.ENDDATE,
       H.STARTWEEK, H.STARTMONTH, H.STARTYEAR, H.STARTDATE,
       H.CONTACTPERSONPHONE, H.CONTACTPERSONNAME,
       H.STOPNUMBER, H.INVOICETYPE, H.INVOICEYEAR, H.INVOICEWEEK, H.INVOICEDAYNUMBER,
       H.PURCHASEORDER, H.DELIVERINSTRUCTIONS, H.INVOICECOMMENTS, H.ROUTENUMBER,
       H.CONTRACTCODE, H.CONTRACTSTARTDATE, H.CONTRACTENDDATE, H.DEPOTCODE,
       H.SPLITUPCODE, H.SPLITUPDESCRIPTION, H.EXTRANAME1, H.EXTRANAME2,
       H.CREDITSQUEEZEAMOUNT, H.CREDITSQUEEZEPERC, H.ROUNDINGAMOUNT,
       c.code currency_code, c.description currency_desc, c.invoiceamountdecimals, c.decimals
FROM INVOICEHEADER H, currency c
where h.currency_id = c.currency_id
/

  CREATE OR REPLACE VIEW "V_COMPRESS_SQITEMINCIRCULATION" ("STATUSQUOHEADER_ID", "YEAR", "WEEK", "CUSTOMER_LINK_ID", "DEPARTMENT_LINK_ID", "DISTRIBUTIONPOINT_LINK_ID", "PRODUCT_LINK_ID", "SIZEDEFINITION_LINK_ID", "FINISHINGMETHOD_ID", "WEAREREMPLOYMENT_LINK_ID", "EMBLEMTEMPLATE_ID", "BEYONDLIFETIMECIRC", "CHANGESPERWEEK", "COGCIRCINV", "FREEISSUEDCIRCINV", "FREESEASONCIRCINV", "MAXFREEINV", "MAXINV", "QTYASSIGNED", "QTYCUSTOMERRENTSTOP", "QTYRENTEDDEPOSITSTOCK", "QTYRENTEDOTHER", "QTYRENTEDPERPIECE", "QTYRENTEMBLEM", "QTYRENTSTOP", "QTYREPLACEMENT", "QTYSUBSTITUTE", "TOTALCIRCINV", "VARIATIONBEYONDLIFETIMECIRC", "VARIATIONCHANGESPERWEEK", "VARIATIONCOGCIRCINV", "VARIATIONFREEISSUEDCIRCINV", "VARIATIONFREESEASONCIRCINV", "VARIATIONMAXFREEINV", "VARIATIONMAXINV", "VARIATIONQTYASSIGNED", "VARIATIONQTYCUSTOMERRENTSTOP", "VARIATIONQTYRENTEMBLEM", "VARIATIONQTYRENTSTOP", "VARIATIONQTYREPLACEMENT", "VARIATIONQTYSUBSTITUTE", "VARIATIONRENTEDDEPOSITSTOCK", "VARIATIONRENTEDOTHER", "VARIATIONRENTEDPERPIECE", "VARIATIONTOTALCIRCINV") AS 
  select s.statusquoheader_id, s.year, s.week,
				customer_link_id, department_link_id, distributionpoint_link_id, product_link_id,
				sizedefinition_link_id, finishingmethod_id, null, null,
				sum(beyondlifetimecirc), sum(changesperweek), sum(cogcircinv),
				sum(freeissuedcircinv), sum(freeseasoncircinv), sum(maxfreeinv), sum(maxinv), sum(qtyassigned),
				sum(qtycustomerrentstop), sum(qtyrenteddepositstock), sum(qtyrentedother), sum(qtyrentedperpiece),
				sum(qtyrentemblem), sum(qtyrentstop), sum(qtyreplacement), sum(qtysubstitute), sum(totalcircinv),
				sum(variationbeyondlifetimecirc), sum(variationchangesperweek), sum(variationcogcircinv), sum(variationfreeissuedcircinv),
				sum(variationfreeseasoncircinv), sum(variationmaxfreeinv), sum(variationmaxinv), sum(variationqtyassigned),
				sum(variationqtycustomerrentstop), sum(variationqtyrentemblem), sum(variationqtyrentstop),
				sum(variationqtyreplacement), sum(variationqtysubstitute), sum(variationrenteddepositstock),
				sum(variationrentedother), sum(variationrentedperpiece), sum(variationtotalcircinv)
	from statusquoheader s, sqitemincirculation sqi
	where s.statusquoheader_id = sqi.statusquoheader_id
	group by s.statusquoheader_id, s.year, s.week,
						customer_link_id, department_link_id, distributionpoint_link_id,
						product_link_id, sizedefinition_link_id, finishingmethod_id
/

  CREATE OR REPLACE VIEW "V_COMPRESS_SQSETINCIRCULATION" ("STATUSQUOHEADER_ID", "YEAR", "WEEK", "CUSTOMER_LINK_ID", "DEPARTMENT_LINK_ID", "DISTRIBUTIONPOINT_LINK_ID", "PRODUCT_LINK_ID", "SIZEDEFINITION_LINK_ID", "FINISHINGMETHOD_ID", "WEAREREMPLOYMENT_LINK_ID", "CHANGESPERWEEK", "FREECIRCINV", "FREEMAXINV", "MAXINV", "NUMBEREMPLCUSTRENTSTOP", "NUMBEREMPLOYMENTSCHARGE", "NUMBEREMPLOYMENTSFREE", "NUMBEREMPLOYMENTSRENTSTOP", "TOTALCIRCINV", "VARIATIONEMPLCUSTRENTSTOP", "VARIATIONEMPLOYMENTSCHARGE", "VARIATIONEMPLOYMENTSFREE", "VARIATIONEMPLOYMENTSRENTSTOP", "VARIATIONFREECIRCINV", "VARIATIONFREEMAXINV", "VARIATIONMAXINV", "VARIATIONTOTALCIRCINV") AS 
  select s.statusquoheader_id, s.year, s.week,
			customer_link_id, department_link_id, distributionpoint_link_id, product_link_id,
			sizedefinition_link_id, finishingmethod_id, null,
			sum(changesperweek), sum(freecircinv), sum(freemaxinv), sum(maxinv), sum(numberemplcustrentstop),
			sum(numberemploymentscharge), sum(numberemploymentsfree), sum(numberemploymentsrentstop), sum(totalcircinv),
			sum(variationemplcustrentstop), sum(variationemploymentscharge), sum(variationemploymentsfree),
			sum(variationemploymentsrentstop), sum(variationfreecircinv), sum(variationfreemaxinv),
			sum(variationmaxinv), sum(variationtotalcircinv)
	from statusquoheader s, sqsetincirculation sqs
	where s.statusquoheader_id = sqs.statusquoheader_id
	group by s.statusquoheader_id, s.year, s.week,
						customer_link_id, department_link_id, distributionpoint_link_id,
						product_link_id, sizedefinition_link_id, finishingmethod_id
/

  CREATE OR REPLACE VIEW "V_CONDENSEDCOSTREPORT" ("INVOICEHEADER_ID", "INVOICENUMBER", "ACTIVITYREFERENCE", "STARTWEEK", "ENDWEEK", "STARTMONTH", "ENDMONTH", "STARTYEAR", "ENDYEAR", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "CITY", "ZIPCODE", "STREET", "CONTACTPERSONNAME", "COSTCENTER_CODE", "COSTCENTER_DESCRIPTION", "COSTCENTERINVOICELINE_AMOUNT", "TAXGROUPCODE", "PERCENTAGE", "AMOUNT_VAT", "AMOUNT_GROSS", "CURRENCYCODE", "INVOICEAMOUNTDECIMALS", "PRINTTAXONAPPENDIX", "LANGUAGECODE", "INVOICEBUSINESSUNIT_ID") AS 
  select
  ih.invoiceheader_id, ih.invoicenumber,ih.activityreference, ih.startweek, ih.endweek, ih.startmonth, ih.endmonth, ih.startyear, ih.endyear
, ih.billtocustomernumber, ih.billtocustomername, ih.deltocustomernumber, ih.deltocustomername
, ih.city, ih.zipcode, ih.street, ih.contactpersonname
, cclk.code costcenter_code, cclk.description costcenter_description
, round(sum(ccil.amount), coalesce(currency.invoiceamountdecimals, 2)) costcenterinvoiceline_amount
, coalesce(il.taxgroupcode, ' ') taxgroupcode
, coalesce(ilv.percentage  , 0) percentage
, round(( sum(ccil.amount) * coalesce(ilv.percentage  , 0))/100, coalesce(currency.invoiceamountdecimals, 2)) Amount_VAT
, round(( sum(ccil.amount) + ( sum(ccil.amount)*coalesce(ilv.percentage  , 0))/100 ), coalesce(currency.invoiceamountdecimals, 2)) Amount_Gross
, currency.code currencycode, coalesce(currency.invoiceamountdecimals, 2) invoiceamountdecimals
, max((select c.printtaxonappendix from customer c where c.customer_id = ih.billtocustomer_link_id)) printtaxonappendix
, languages.code languageCode, ih.invoicebusinessunit_id
from
  invoiceheader ih
, invoiceline il
    left outer join
               ( invoiceline il2
                   join invoicelinetype ilty2
                                 on il2.invoicelinetype_id = ilty2.invoicelinetype_id
                                 and ilty2.type = 18
                   join
                   invoicelinevarious ilv on ilv.invoiceline_id = il2.invoiceline_id )
         on il2.code = il.taxgroupcode  -- ! lineNumber
            and il2.invoiceheader_id = il.invoiceheader_id
, invoicelinetype ilty
, costcenterinvoiceline ccil, costcenter_link cclk
, currency , languages
where
    ih.documenttype = 1
and ih.invoiceheader_id = il.invoiceheader_id
    and il.invoicelinetype_id = ilty.invoicelinetype_id
        and ilty.type <> 18
    and il.invoiceline_id = ccil.invoiceline_id
        and ccil.costcenter_link_id = cclk.costcenter_link_id
and ih.currency_id = currency.currency_id
group by
  ih.invoiceheader_id, ih.invoicenumber,ih.activityreference, ih.startweek, ih.endweek, ih.startmonth, ih.endmonth, ih.startyear, ih.endyear
, ih.billtocustomernumber, ih.billtocustomername, ih.deltocustomernumber, ih.deltocustomername
, ih.city, ih.zipcode, ih.street, ih.contactpersonname, ih.invoicecomments, ih.nextperiodstartdate, ih.invoicefrequency_id
, cclk.code, cclk.description, il.taxgroupcode, ilv.percentage
, currency.code, currency.invoiceamountdecimals, ih.billtocustomer_link_id
, languages.code, ih.invoicebusinessunit_id
/

  CREATE OR REPLACE VIEW "V_CONDENSEDCOSTREPORTWEEK_AUX" ("INVOICEHEADER_ID", "INVOICENUMBER", "ACTIVITYREFERENCE", "STARTWEEK", "ENDWEEK", "STARTMONTH", "ENDMONTH", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "CITY", "ZIPCODE", "STREET", "CONTACTPERSONNAME", "COSTCENTER_CODE", "COSTCENTER_DESCRIPTION", "COSTCENTERINVOICELINE_AMOUNT", "TAXGROUPCODE", "PERCENTAGE", "AMOUNT_VAT", "AMOUNT_GROSS", "CURRENCYCODE", "INVOICEAMOUNTDECIMALS", "PRINTTAXONAPPENDIX", "LANGUAGECODE", "SHOWVATONCONDCOSTREP", "YEAR", "WEEK", "YEARWEEK", "BILLTOSENDINVOICETO", "PARENTINVOICEHEADER_ID", "PARENTINVNR") AS 
  select
  ih.invoiceheader_id, ih.invoicenumber,ih.activityreference, ih.startweek, ih.endweek, ih.startmonth, ih.endmonth
, ih.billtocustomernumber, ih.billtocustomername, ih.deltocustomernumber, ih.deltocustomername
, ih.city, ih.zipcode, ih.street, ih.contactpersonname
, cclk.code costcenter_code, cclk.description costcenter_description
, sum(cri.amount) costcenterinvoiceline_amount
, coalesce(il.taxgroupcode, ' ') taxgroupcode
, coalesce(ilv.percentage  , 0) percentage
, ( sum(cri.amount) * coalesce(ilv.percentage  , 0))/100 Amount_VAT
, ( sum(cri.amount) + ( sum(cri.amount)*coalesce(ilv.percentage  , 0))/100 ) Amount_Gross
, currency.code currencycode, currency.invoiceamountdecimals
, (select c.printtaxonappendix from customer c where c.customer_id = ih.billtocustomer_link_id) printtaxonappendix
, languages.code languageCode
, (select s.value from systemsetting s
   where s.name = 'SHOWVATONCONDCOSTREP'
      and s.plant_id = (select bu.plant_id from businessunit bu
                         where bu.businessunit_id = ih.invoicebusinessunit_id)) showvatoncondcostrep
, cri.year, cri.week, 100*cri.year+cri.week yearweek
,(select c.sendinvoiceto from customer c where ih.deltocustomer_link_id = c.customer_id) billtosendinvoiceto
, ih.parentinvoiceheader_id
, (select ihp.invoicenumber from invoiceheader ihp where ihp.invoiceheader_id = ih.parentinvoiceheader_id) parentinvnr
from
  invoiceheader ih
, invoiceline il
    left outer join
               ( invoiceline il2
                   join invoicelinetype ilty2
                                 on il2.invoicelinetype_id = ilty2.invoicelinetype_id
                                 and ilty2.type = 18
                   join
                   invoicelinevarious ilv on ilv.invoiceline_id = il2.invoiceline_id )
         on il2.code = il.taxgroupcode  -- ! lineNumber
            and il2.invoiceheader_id = il.invoiceheader_id
, invoicelinetype ilty--, costcenterinvoiceline ccil
, costcenter_link cclk, costreportinfo cri
, currency, languages
where
    ih.documenttype = 1
and ih.invoiceheader_id = il.invoiceheader_id
    and il.invoicelinetype_id = ilty.invoicelinetype_id
        and ilty.type <> 18
    and il.invoiceline_id = cri.invoiceline_id
        and cri.costcenter_link_id = cclk.costcenter_link_id
and ih.currency_id = currency.currency_id
group by
  ih.invoiceheader_id, ih.invoicenumber,ih.activityreference, ih.startweek, ih.endweek, ih.startmonth
, ih.endmonth, ih.billtocustomernumber, ih.billtocustomername, ih.deltocustomernumber, ih.deltocustomername
, ih.city, ih.zipcode, ih.street, ih.contactpersonname, ih.invoicecomments, ih.nextperiodstartdate, ih.invoicefrequency_id
, cclk.code , cclk.description
, il.taxgroupcode, ilv.percentage
, currency.code , currency.invoiceamountdecimals, ih.billtocustomer_link_id, ih.deltocustomer_link_id
, languages.code, ih.invoicebusinessunit_id
, cri.year, cri.week
, ih.parentinvoiceheader_id
/

  CREATE OR REPLACE VIEW "V_CONDENSEDGARMENTINVESTMENTS" ("PROCESSBUSINESSUNIT_ID", "FORBUSINESSUNIT_ID", "ASSIGNDATE", "STOCKROOM_ID", "STOCKROOMCODE", "STOCKROOMNAME", "PROCESSBUCODE", "PROCESSBUDESCR", "FORBUCODE", "FORBUDESCR", "PRODUCT_CODE", "PRODUCT_DESC", "PRODGRCODE", "PRODUCTGR_DESC", "REASONCODE_ID", "REASONCODE", "REASONGROUP", "QUANTITY", "PURCHASEPRICE", "LANGUAGE_CODE") AS 
  select  ih.processbusinessunit_id processbusinessunit_id, ih.forbusinessunit_id forbusinessunit_id,ih.assigndate assigndate, ih.stockroom_id stockroom_id,
 st.code stockroomcode,
 coalesce (st.name, '') stockroomname, bu.code ProcessBuCode, bu.description ProcessBuDescr,bu2.code ForBucode,bu2.description ForBuDescr, p.code Product_code,
        (select pd.description from product_desc pd where p.product_id = pd.product_id and pd.language_id = lan.language_id) Product_desc,
        pg.code prodgrcode, (select pgd.description from productgroup_desc  pgd where pg.productgroup_id=pgd.productgroup_id and pgd.language_id = lan.language_id) Productgr_desc,
        ih.reasoncode_id reasoncode_id, rc.code reasoncode, rc.reasongroup reasongroup,ih.quantity quantity,
        F_PURCHASEPRICE(p.supplier_id,ih.product_link_id,ih.sizedefinition_link_id, ih.assigndate) purchaseprice,
        lan.code Language_code
from issuehistory ih left outer join stockroom st on ih.stockroom_id=st.stockroom_id,--- should be displayed also items not delivered from stock
 product p, productgroup pg,  reasoncode rc,qualitygrade q, businessunit bu ,businessunit bu2,
plant pl, plant pl2,languages lan
where ih.processbusinessunit_id=bu.businessunit_id
and ih.forbusinessunit_id=bu2.businessunit_id
and (st.managedbybu_id=bu.businessunit_id or ih.stockroom_id is null)
and ih.product_link_id=p.product_id
and p.productgroup_id=pg.productgroup_id
and p.typeofmerchandise=2 --only garments
and ih.issuegrade_id=q.qualitygrade_id
and q.newgarment='Y'
and ih.reasoncode_id=rc.reasoncode_id
and rc.reasongroup is not null
and bu.plant_id = pl.plant_id
and bu2.plant_id = pl2.plant_id
/

  CREATE OR REPLACE VIEW "V_CONDENSEDINVOICESREPORT" ("BILLNUMBER", "BILLNAME", "CONTACTPERSONNAME", "STREET", "ZIPCODE", "CITY", "STATE", "DELLNUMBER", "DELLNAME", "INVOICENUMBER", "INVOICEDATE", "INVOICESTARTPERIOD", "INVOICEENDPERIOD", "TOTALAMOUNTEXCLVAT", "PREBILLAMOUNT", "CURRENCYCODE", "INVOICEAMOUNTDECIMALS", "PURCHASEORDERNUMBER", "CUST_CLUSTER_CODE") AS 
  select
  bill.customernumber BillNumber, bill.legalname BillName
, ( select max(invoiceheader.contactpersonname) from invoiceheader
where invoiceheader.billtocustomer_link_id = bill.customer_id
) contactpersonname
, address.street, address.zipcode, address.city, address.state
, coalesce(del.customernumber, bill.customernumber ) DellNumber
, coalesce(del.legalname, bill.legalname) DellName
, ih.invoicenumber, ih.invoicedate
, case when ih.invoicefrequency_id <> 0 then ih.startdate-- 0 means Direct invoice in invoicefrequency table
  else ih.invoicedate end InvoiceStartPeriod
, case when ih.invoicefrequency_id <> 0 then ih.enddate
       /*when ih.invoicefrequency_id = 0 then (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber <= ih.invoicenumber)*/--may cause timeout for large customers
  else ih.invoicedate end InvoiceEndPeriod
, ih.totalamountexclvat, ih.prebillamount, cu.code currencyCode, cu.invoiceamountdecimals
, ih.purchaseorder PurchaseOrderNumber
, (select cc.code from customercluster cc where cc.cluster_id = ih.cluster_id) cust_cluster_code
from
  invoiceheader ih left outer join customer del on del.customer_id = ih.deltocustomer_link_id
  inner join currency cu on cu.currency_id = ih.currency_id
, customer bill, status, customerbillinginfo, address
where
    ih.billtocustomer_link_id = bill.customer_id
and customerbillinginfo.customer_id = bill.customer_id
and ih.status_id = status.status_id
and status.statustype = 'IN'
and status.code = '2'
and customerbillinginfo.Consolidatedreportinv = 'Y'
and address.address_id = bill.mailaddress_id
/

  CREATE OR REPLACE VIEW "V_CONSIGNMENTCORRECTIONNOTES" ("CONSIGNMENTNOTE_ID", "CONSIGNMENTNOTENUMBER", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "CONSPOINT", "CONSPOINTDESC", "NOTENUMBER", "TRANSPORTARTICLE", "PACKINGNOTE_ID", "ORIGIN", "WEIGHTUNIT", "CONTAINERRECORDINGACTIVE", "LANGUAGECODE", "BU_CODE", "BU_DESC") AS 
  select /*version 1.0*/
       /*+index (dep XPKDEPARTMENT)*/
       pn.consignmentnote_id, cn.consignmentnotenumber,
       dep.departmentnumber, dep.description departmentdescription,
       dp.distributionpointnumber conspoint, dp.description conspointdesc, pn.notenumber,
       ta.code transportarticle, pn.packingnote_id, pn.origin, ss.value weightunit,
       ss2.value containerrecordingactive, lan.code languagecode,
			 bu.code BU_code, bu.description BU_desc
  from packingnote pn
       join consignmentnote cn on pn.consignmentnote_id = cn.consignmentnote_id
       join distributionpoint dp
            join department dep on dp.department_id = dep.department_id
       on pn.distributionpoint_id = dp.distributionpoint_id
       join transportarticle ta on pn.transportarticle_id = ta.transportarticle_id
       join businessunit bu
            join systemsetting ss on bu.plant_id = ss.plant_id and ss.name = 'WEIGHTUNIT'
            join systemsetting ss2 on bu.plant_id = ss2.plant_id and ss2.name = 'CONTAINERRECORDINGACTIVE'
       on pn.processbusinessunit_id = bu.businessunit_id
       cross join languages lan
/

  CREATE OR REPLACE VIEW "V_CONSIGNMENTDELIVEREDPRODUCTS" ("CONSIGNMENTNOTENUMBER", "PRODUCTGROUPCODE", "PRODUCTGROUPDESC", "TYPEOFMERCHANDISE", "PRODUCTCODE", "SIZEDEFINITIONCODE", "PRODUCTDESCRIPTION", "PRODUCTLONGDESCRIPTION", "FINMETHDESC", "DELIVEREDAMOUNT", "LANGUAGECODE", "NOCHARGEPREVSHORTAGE", "NOCHARGEPREVREJECTED", "BU_CODE") AS 
  select /*version 2.1*/
       cn.consignmentnotenumber, prg.code productgroupcode,
       (select prgd.description
          from productgroup_desc prgd
         where prgd.productgroup_id = prg.productgroup_id
           and prgd.language_id = lan.language_id) productgroupdesc,
       pr.typeofmerchandise, pr.code productcode, sd.code sizedefinitioncode,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdescription,
       (select prd.longdescription
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productlongdescription,
       (select fmd.description
          from finishingmethod_desc fmd
         where fmd.finishingmethod_id = fm.finishingmethod_id
           and fmd.language_id = lan.language_id) finmethdesc,
       sum(pnl.deliveredamount) deliveredamount, lan.code languagecode,
       case when sum(pnl.nochargeprevshortage) = 0
            then coalesce((select sum(dv.amount)
                             from packingnoteline pnl1
                                  join packingnote pn1
                                       join consignmentnote cn1 on pn1.consignmentnote_id = cn1.consignmentnote_id
                                  on pnl1.packingnote_id = pn1.packingnote_id
                                  join deliveryvariations dv on pnl1.packingnote_id = dv.causenote_id
                                                                and pnl1.product_id = dv.product_id
                                                                and pnl1.sizedefinition_id = dv.sizedefinition_id
                                                                and pnl1.finishingmethod_id = dv.finishingmethod_id
                            where dv.origin = 1
                              and dv.soilcountsubtype = 2
                              and cn1.consignmentnotenumber = cn.consignmentnotenumber), 0)
            else sum(pnl.nochargeprevshortage)
       end nochargeprevshortage,
       case when sum(pnl.nochargeprevrejected) = 0
            then coalesce((select sum(dv.amount)
                             from packingnoteline pnl1
                                  join packingnote pn1
                                       join consignmentnote cn1 on pn1.consignmentnote_id = cn1.consignmentnote_id
                                  on pnl1.packingnote_id = pn1.packingnote_id
                                  join deliveryvariations dv on pnl1.packingnote_id = dv.causenote_id
                                                                and pnl1.product_id = dv.product_id
                                                                and pnl1.sizedefinition_id = dv.sizedefinition_id
                                                                and pnl1.finishingmethod_id = dv.finishingmethod_id
                            where dv.origin = 1
                              and dv.soilcountsubtype = 3
                              and cn1.consignmentnotenumber = cn.consignmentnotenumber), 0)
            else sum(pnl.nochargeprevrejected)
       end nochargeprevrejected,
       (select bu.code
          from businessunit bu
         where pn.processbusinessunit_id = bu.businessunit_id) bu_code
  from packingnoteline pnl
       join packingnote pn on pnl.packingnote_id = pn.packingnote_id
            join consignmentnote cn on pn.consignmentnote_id = cn.consignmentnote_id
       join product pr
            join productgroup prg on pr.productgroup_id = prg.productgroup_id
       on pnl.product_id = pr.product_id
       join sizedefinition sd on pnl.sizedefinition_id = sd.sizedefinition_id
       join finishingmethod fm on pnl.finishingmethod_id = fm.finishingmethod_id
     cross join languages lan
 group by lan.language_id, lan.code, cn.consignmentnotenumber, prg.code, prg.productgroup_id,
          pr.code, pr.product_id, sd.code, fm.finishingmethod_id, pnl.product_id, pnl.sizedefinition_id,
          pnl.finishingmethod_id, pn.processbusinessunit_id, pr.typeofmerchandise
/

  CREATE OR REPLACE VIEW "V_CONSIGNMENTDELIVERYNOTES" ("CONSIGNMENTNOTE_ID", "CONSIGNMENTNOTENUMBER", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "CONSPOINT", "NOTENUMBER", "CONSPOINT_DESC", "TRANSPORTARTICLE", "PACKINGNOTE_ID", "WEIGHTUNIT", "CONTAINERRECORDINGACTIVE", "LANGUAGECODE", "ORIGIN", "BU_CODE", "BU_DESC") AS 
  select /*version 1.0*/
       /*+index (dep XPKDEPARTMENT)*/
       pn.consignmentnote_id, cn.consignmentnotenumber,
       dep.departmentnumber, dep.description departmentdescription,
       dp.distributionpointnumber conspoint, pn.notenumber, dp.description conspoint_desc,
       ta.code transportarticle, pn.packingnote_id, ss.value weightunit,
       ss2.value containerrecordingactive, lan.code languagecode, pn.origin,
			 bu.code bu_code, bu.description bu_desc
  from packingnote pn
       join consignmentnote cn on pn.consignmentnote_id = cn.consignmentnote_id
       join distributionpoint dp
            join department dep on dp.department_id = dep.department_id
       on pn.distributionpoint_id = dp.distributionpoint_id
       join transportarticle ta on pn.transportarticle_id = ta.transportarticle_id
       join businessunit bu
            join systemsetting ss on bu.plant_id = ss.plant_id and ss.name = 'WEIGHTUNIT'
            join systemsetting ss2 on bu.plant_id = ss2.plant_id and ss2.name = 'CONTAINERRECORDINGACTIVE'
       on pn.processbusinessunit_id = bu.businessunit_id
       cross join languages lan
/

  CREATE OR REPLACE VIEW "V_CONSIGNMENTNOTE" ("PLANTNAME", "PLANTSTREET", "PLANTSTREET2", "PLANTZIPCODE", "PLANTCITY", "PLANTPHONENO", "PLANTFAXNO", "PLANTSTATE", "CONSIGNMENTNOTE_ID", "CONSIGNMENTNOTENUMBER", "CONSIGNMENTNOTEYEAR", "CONSIGNMENTNOTEWEEK", "ROUTENUMBER", "ROUTEDESCRIPTION", "PLANTSTREET3", "STOPNUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "LEGALNAME", "CUSTOMERSTREET", "CUSTOMERSTREET2", "CUSTOMERZIPCODE", "CUSTOMERCITY", "CUSTOMERSTATE", "DELIVERYDATE", "CONSIGNMENTNOTELEVEL", "DEPARTMENT_LINK_ID", "DELIVERYPOINT_LINK_ID", "EXTERNALORDERNUMBER", "DEL_POINT_CODE", "DEL_POINT_DESC", "DEL_POINT_STREET", "CUSTOMERSTREET3", "DEL_POINT_ZIP", "DEL_POINT_CITY", "DEL_POINT_STATE", "DEL_POINT_STREET2", "DEL_POINT_STREET3", "DEL_POINT_COUNTY", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "BU_CODE", "BU_DESC", "SCANSONDELIVERYNOTE", "PHONELEN", "LAYOUTCODE", "DAYDESCRIPTION", "DVREFERENCE") AS 
  select /* version 2.2*/
       p.name plantname, p_ads.street plantstreet, p_ads.street2 plantstreet2, p_ads.zipcode plantzipcode, p_ads.city plantcity,
       p.phoneno plantphoneno, p.faxno plantfaxno, p_ads.state plantstate, cn.consignmentnote_id, cn.consignmentnotenumber,
       cn.year consignmentnoteyear, cn.week consignmentnoteweek, ro.routenumber, ro.description routedescription, p_ads.street3 plantstreet3,
       cn.stopnumber stopnumber, cu.customernumber, cu.name customername, cu.legalname, cu_ads.street customerstreet, cu_ads.street2 customerstreet2,
       cu_ads.zipcode customerzipcode, cu_ads.city customercity, cu_ads.state customerstate, cn.deliverydate, cu.consignmentnotelevel, cn.department_link_id,
       cn.deliverypoint_link_id, cn.externalordernumber, dp.code del_point_code, dp.description del_point_desc, dp_addr.street del_point_street, cu_ads.street3 customerstreet3,
       dp_addr.zipcode del_point_zip, dp_addr.city del_point_city, dp_addr.state del_point_state, dp_addr.street2 del_point_street2, dp_addr.street3 del_point_street3,
       dp_addr.county del_point_county, d.departmentnumber, d.description departmentdesc, bu.code bu_code, bu.description bu_desc, cu.scansondeliverynote,
       (select ss.value
          from systemsetting ss
         where ss.name like 'PHONEFAXLENGTH'
           and ss.plant_id = p.plant_id) phonelen,
       (select fl.code
          from formlayout fl
         where fl.formlayout_id = cu.consignmentnotelayout_id) layoutcode,
       (select dd.description
          from day_desc dd
         where dd.language_id = cu.language_id
           and dd.day_id = cn.daynumber) daydescription,
       (select min(dv.reference)
          from deliveryvariations dv
          join packingnote pn on dv.packingnote_id = pn.packingnote_id
         where pn.consignmentnote_id = cn.consignmentnote_id) dvreference
  from consignmentnote cn
       left join route ro on cn.route_id = ro.route_id
       left join department d on cn.department_link_id = d.department_id
       left join deliverypoint dp
            join address dp_addr on dp.deliveryaddress_id = dp_addr.address_id
       on cn.deliverypoint_link_id = dp.deliverypoint_id
       join businessunit bu
            join plant p
                 join address p_ads on p.address_id = p_ads.address_id
            on bu.plant_id = p.plant_id
       on cn.businessunit_id = bu.businessunit_id
       join customer cu
            join address cu_ads on cu.visitaddress_id = cu_ads.address_id
       on cn.customer_link_id = cu.customer_id
 where cu.consignmentnotelevel > 0
/

  CREATE OR REPLACE VIEW "V_CONSIGNMENTNOTES2SEND" ("CONSIGNMENTNOTE_ID", "NOTENUMBER", "CUSTOMER_LINK_ID", "DEPARTMENT_LINK_ID", "DELIVERYPOINT_LINK_ID", "BUSINESSUNIT_ID", "CODE", "DELIVERYDATE") AS 
  select cn.consignmentnote_id,
       cn.consignmentnotenumber notenumber,
       cn.customer_link_id,
       cn.department_link_id,
       cn.deliverypoint_link_id,
       bu.businessunit_id,
       bu.code, cn.deliverydate
  from consignmentnote cn, businessunit bu
 where bu.businessunit_id = cn.businessunit_id
   and cn.emailstatus = 1
/

  CREATE OR REPLACE VIEW "V_CONSNOTEEMPTYCONTAINERID" ("CONSIGNMENTNOTE_ID", "PRIMARYID") AS 
  select distinct pn.consignmentnote_id, cnt.primaryid
from packingnote pn, packingnotecontainer pnc, container cnt
where pn.packingnote_id = pnc.packingnote_id and pnc.container_id = cnt.container_id and pnc.grossweight - pnc.tareweight <= 0
/

  CREATE OR REPLACE VIEW "V_CONSOLIDATEDINVOICE" ("PARENTINVOICEHEADER_ID", "INVOICEDATE", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "BILLTOCUSTOMER_LINK_ID", "INVOICEHEADER_ID", "EXTRANAME1", "EXTRANAME2", "DELTOCUSTOMER_LINK_ID", "DELTOSTREET", "DELTOSTREET2", "DELTOCITY", "DELTOCOUNTY", "DELTOSTATE", "DELTOZIPCODE", "CREDITSQUEEZEPERC", "NETPAYMENTDAYS", "PAYMENTDISCOUNTDAYS", "PLANTADDRESS", "PLANTSTREET2", "PLANTPHONE", "PLANTCITY", "PLANTSTATE", "PLANTZIPCODE", "PLANTWEBSITE", "CONTACTPERSONNAME", "COSTCENTERCODE", "CONTACTPERSONPHONE", "STREET", "STREET2", "STREET3", "ZIPCODE", "CITY", "STATE", "INVOICENUMBER", "ACTIVITYREFERENCE", "SEQ", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "DELTOCUVATNUMBER", "INVOICESTARTPERIOD", "INVOICEENDPERIOD", "PAYTHISAMOUNT", "PREBILLAMOUNT", "CREDITSQUEEZEAMOUNT", "BTW_NR", "PAYMENTTERMSDESC", "CUSTOMERRELATEDMESSAGE", "GENERALINVOICEMESSAGE", "SUPPRESSCUSTOMERRELATEDMESSAGE", "CURRENCYCODE", "INVOICEAMOUNTDECIMALS", "INVOICETYPE", "ROUNDINGAMOUNT", "BILLTOCOUNTRYDESCRIPTION", "DELTOCOUNTRYDESCRIPTION", "PLANTCOUNTRY_DESC", "PAYMENTTYPE", "INVOICEADDRESS_ID", "GENERALINV_REMARK_PLANT", "GENERALINV_REMARK_CUSTOMER", "INVOICEREMARKSTARTDATE", "INVOICEREMARKENDDATE", "BANKACCOUNT", "CONS_INV_LAYOUT_CODE", "NEXTPERIODSTARTDATE", "NEXTPERIODENDDATE", "SPLITUPCODE", "SPLITUPDESCRIPTION", "STARTWEEK", "ENDWEEK", "DELTOCUSTLANG", "PAYMENTTERMSDUEDATE", "DISCOUNTDAYS", "DISCOUNTDAYS2", "PAYMENTDISCOUNT", "PAYMENTDISCOUNT2", "INVOICELAYOUTCODE", "PLANTCODE", "PLANTNAME", "PURCHASEORDER", "TOTALAMOUNTEXCLVAT", "PARENTDELTOCUSTNR", "PARENTDELTOCUSTNAME") AS 
  select /*version 2.1*/
       ih.parentinvoiceheader_id, pih.invoicedate, pih.billtocustomernumber, pih.billtocustomername, pih.billtocustomer_link_id,
       ih.invoiceheader_id, bill.extraname1, bill.extraname2, ih.deltocustomer_link_id, ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltocounty,
       ih.deltostate, ih.deltozipcode, ih.creditsqueezeperc, ih.netpaymentdays, ih.paymentdiscountdays, pad.street plantaddress,
       pad.street2 plantstreet2, p.phoneno plantphone, pad.city plantcity, pad.state plantstate, pad.zipcode plantzipcode, p.website plantwebsite,
       (select max(invoiceheader.contactpersonname)
          from invoiceheader
         where invoiceheader.billtocustomer_link_id = bill.customer_id
           and invoiceheader.invoicedate =
               (select max(ihh.invoicedate) from invoiceheader ihh where invoiceheader.billtocustomer_link_id = ihh.billtocustomer_link_id)) contactpersonname,
       ih.splitupcode costcentercode, pih.contactpersonphone, concatenatewithsign(pih.street, '  ', pih.street2) street, pih.street2, pih.street3, pih.zipcode, pih.city,
       pih.state, pih.invoicenumber, pih.activityreference, cast(getsubstring(ih.invoicenumber, -3) as varchar2(3)) seq,
       coalesce(ih.deltocustomernumber, ih.billtocustomernumber) deltocustomernumber,
       cast(coalesce(ih.deltocustomername, ih.billtocustomername) as varchar2(30)) deltocustomername,
       coalesce((select pdel.vatnumber
                   from customer pdel
                  where pdel.customer_id = pih.deltocustomer_link_id), bill.vatnumber) deltocuvatnumber,
       case pih.invoicefrequency_id
          when 0 then pih.invoicedate
          else pih.startdate end invoicestartperiod,
       coalesce((select invoiceheader.enddate
                   from invoiceheader
                  where pih.invoiceheader_id = invoiceheader.invoiceheader_id
                    and invoiceheader.invoicefrequency_id <> 0),
                (select max(invoiceheader.invoicedate)
                   from invoiceheader
                  where invoiceheader.billtocustomer_link_id = pih.billtocustomer_link_id
                    and invoiceheader.invoicenumber < pih.invoicenumber
                    and invoiceheader.invoicefrequency_id = 0),
                (select max(invoiceheader.invoicedate)
                   from invoiceheader
                  where invoiceheader.billtocustomer_link_id = pih.billtocustomer_link_id
                    and invoiceheader.invoicenumber = pih.invoicenumber
                    and invoiceheader.invoicefrequency_id = 0)) invoiceendperiod,
       ih.paythisamount, pih.prebillamount, pih.creditsqueezeamount, b.vatnumber btw_nr,
       (select pdesc.description
          from paymentterms_desc pdesc
         where pdesc.paymentterms_id = cbi.paymentterms_id
           and pdesc.language_id = coalesce(dell.language_id, bill.language_id)) paymenttermsdesc,
       cbc.description customerrelatedmessage, ih.invoicecomments generalinvoicemessage,
       case coalesce(cbc.description, ih.invoicecomments, ' ')
          when ' ' then 'Y'
          else 'N' end suppresscustomerrelatedmessage,
       curr.code currencycode, curr.invoiceamountdecimals, ih.invoicetype, ih.roundingamount, ihextr.billtocountrydescription,
       ihextr.deltocountrydescription, c.description plantcountry_desc, ihextr.paymenttype, bill.invoiceaddress_id,
       (select pldesc.invoiceremark
          from plantinvoiceremark_desc pldesc
         where pldesc.plant_id = p.plant_id
           and pldesc.language_id = p.language_id) generalinv_remark_plant,
       (select pldesc.invoiceremark
          from plantinvoiceremark_desc pldesc
         where pldesc.plant_id = p.plant_id
           and pldesc.language_id = dell.language_id) generalinv_remark_customer, p.invoiceremarkstartdate, p.invoiceremarkenddate, ihextr.bankaccount,
       (select fl.code from formlayout fl where fl.formlayout_id = cbi.consolidatedinvoicelayout_id) cons_inv_layout_code, pih.nextperiodstartdate,
       pih.nextperiodenddate, ih.splitupcode, ih.splitupdescription, pih.startweek, pih.endweek,
       (select lan.code from languages lan where lan.language_id = dell.language_id) deltocustlang,
       ihextr.paymenttermsduedate, ihextr.discountdays, ihextr.discountdays2, ihextr.paymentdiscount, ihextr.paymentdiscount2,
       ihextr.formlayoutcode invoicelayoutcode, p.code plantcode, p.name plantname, ih.purchaseorder, ih.totalamountexclvat,
       coalesce(pih.deltocustomernumber, pih.billtocustomernumber) parentdeltocustnr,
       cast(coalesce(pih.deltocustomername, pih.billtocustomername) as varchar2(30)) parentdeltocustname
  from invoiceheader ih
       left join customer dell
            left join customerbillingcomment cbc on cbc.customer_id = dell.customer_id and cbc.type = 1
       on ih.deltocustomer_link_id = dell.customer_id
       join invoiceheaderextrainfo ihextr on ih.invoiceheader_id = ihextr.invoiceheader_id
       join status st on ih.status_id = st.status_id and st.statustype = 'IN' and st.code = '2'
       join currency curr on ih.currency_id = curr.currency_id
       join businessunit b
            join plant p
                 join address pad on p.address_id = pad.address_id
                 join country c on p.country_id = c.country_id
            on b.plant_id = p.plant_id
       on ih.invoicebusinessunit_id = b.businessunit_id
       join invoiceheader pih
            join customer bill
                 join customerbillinginfo cbi on bill.customer_id = cbi.customer_id
            on pih.billtocustomer_link_id = bill.customer_id
       on ih.parentinvoiceheader_id = pih.invoiceheader_id
/

  CREATE OR REPLACE VIEW "V_CONSOLIDATEDINVOICE_LINE" ("INVOICEHEADER_ID", "PERCENTAGE", "INVOICELINETYPE", "OVERAMOUNT", "AMOUNT", "LANGUAGECODE", "INVOICELINETYPEDESC", "AMOUNTDECIMALS") AS 
  select /* version 2.1*/
       il.invoiceheader_id, ilv.percentage, ilt.type invoicelinetype, ilv.overamount, il.amount, languages.code languagecode,
       (select iltdesc.description
          from invoicelinetype_desc iltdesc
         where iltdesc.invoicelinetype_id = il.invoicelinetype_id
           and iltdesc.language_id = languages.language_id) invoicelinetypedesc,
       (select crr.invoiceamountdecimals from currency crr where crr.currency_id = ih.currency_id) amountdecimals
  from invoiceheader ih
       join invoiceline il
            join invoicelinevarious ilv on il.invoiceline_id = ilv.invoiceline_id
            join invoicelinetype ilt on il.invoicelinetype_id = ilt.invoicelinetype_id
       on ih.parentinvoiceheader_id = il.invoiceheader_id
       cross join languages
 where ih.parentinvoiceheader_id = ih.invoiceheader_id
   and ih.documenttype = 1
/

  CREATE OR REPLACE VIEW "V_CONTACT" ("CONTACT_ID", "CUSTOMER_LINK_ID", "DEPARTMENT_LINK_ID", "BUSINESSUNIT_ID", "CONTACTCATEGORY_ID", "CREATEDBYUSER_ID", "FOLLOWUPBYUSER_ID", "NEWDATE", "CALLNUMBER", "FOLLOWUPDATE", "INPROGRESSDATE", "CLOSEDATE", "STATUS", "CONTACTPERSONNAME", "CONTACTPERSON_ID", "FOLLOWUPBYUSERNAME", "CREATEDBYUSERNAME", "CONTACTNOTES", "FOLLOWUPNOTES", "ATTACHMENT", "SYSTEMUSER_ID", "TIMESTAMP", "SHOWONROUTELIST") AS 
  select "CONTACT_ID","CUSTOMER_LINK_ID","DEPARTMENT_LINK_ID","BUSINESSUNIT_ID","CONTACTCATEGORY_ID","CREATEDBYUSER_ID","FOLLOWUPBYUSER_ID","NEWDATE","CALLNUMBER","FOLLOWUPDATE","INPROGRESSDATE","CLOSEDATE","STATUS","CONTACTPERSONNAME","CONTACTPERSON_ID","FOLLOWUPBYUSERNAME","CREATEDBYUSERNAME","CONTACTNOTES","FOLLOWUPNOTES","ATTACHMENT","SYSTEMUSER_ID","TIMESTAMP","SHOWONROUTELIST" from  CONTACT C
WHERE --R.CONTACTPERSON_ID= C.CONTACTPERSON_ID(+)
--AND
C.SHOWONROUTELIST ='Y'
AND (C.STATUS= 1 OR C.STATUS= 2)
/

  CREATE OR REPLACE VIEW "V_CONTACTPERSON" ("CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CONTACTPERSONNUMBER", "CONTACTPERSONNAME", "PHONE", "MOBILEPHONE", "EMAIL", "FAX", "INVOICECONTACTPERSON", "CONTACPERSONFUNCTIONCODE", "CONTACTPERSONFUNCTIONDESCRIPTI", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT customer.customer_id, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, CONTACTPERSON.CONTACTPERSONNUMBER,
 CONTACTPERSON.NAME, CONTACTPERSON.PHONE, CONTACTPERSON.MOBILEPHONE, CONTACTPERSON.EMAIL,
 CONTACTPERSON.FAX, CONTACTPERSON.INVOICECONTACTPERSON, CONTACTPERSONFUNCTION.CODE,
 (SELECT description FROM CONTACTPERSONFUNCTION_DESC A WHERE A.CONTACTPERSONFUNCTION_ID = CONTACTPERSON.CONTACTPERSONFUNCTION_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) CONTACTPERSONFUNCTION_DESC,
 contactperson.systemuser_id, CONTACTPERSON.TIMESTAMP, LANGUAGES.CODE
FROM CONTACTPERSON
                   left outer join CUSTOMER
                   on CONTACTPERSON.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
     ,  CONTACTPERSONFUNCTION, LANGUAGES
WHERE CONTACTPERSON.CONTACTPERSONFUNCTION_ID = CONTACTPERSONFUNCTION.CONTACTPERSONFUNCTION_ID
/

  CREATE OR REPLACE VIEW "V_CONTAINERCONTENTS" ("PACKINGNOTE_ID", "PACKINGNOTENUMBER", "DELIVERYDATE", "CREATIONTIMESTAMP", "PROCBU_CODE", "PROCBU_DESC", "INVBU_CODE", "INVBU_DESC", "ROUTENUMBER", "ROUTECODE", "ROUTEDESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPT_NR", "DEPT_DESC", "DISTRIB_NR", "DISTRIB_DESC", "DELP_CODE", "DELP_DESC", "STOCKLOCATION", "PRODUCTCODE", "PRODUCTCUSTOMCODE", "PRODUCTCUSTOMDESCRIPTION", "PRODUCTDESC", "PRODUCTLONGDESC", "PACKINGNOTELINE_ID", "PACKINGSEQUENCE", "STANDARDAMOUNT", "VARIATIONAMOUNT", "DELIVEREDAMOUNT", "TOBEDELIVEREDAMOUNT", "TYPEOFMERCHANDISE", "REMARKFORPACKINGINSTRUCTIONS", "LINE_ORIGIN", "NOCHARGEFIRSTISSUE", "NOCHARGEACTIVESEASON", "NOCHARGENOTCOG", "PRICE", "AMOUNT", "TAXGROUPCODE", "LANGUAGECODE", "SYSTEMUSER_ID", "USERNAME", "FULLNAME") AS 
  select pn.packingnote_id, pn.notenumber packingnotenumber, pn.deliverydate, pn.creationtimestamp,
       pbu.code procbu_code, pbu.description procbu_desc, ibu.code invbu_code, ibu.description invbu_desc,
       ro.routenumber, ro.routecode, ro.description routedesc, cu.customernumber, cu.name customername,
       de.departmentnumber dept_nr, de.description dept_desc,
       dp.distributionpointnumber distrib_nr, dp.description distrib_desc,
       delp.code delp_code, delp.description delp_desc,
       (select dff.stringvalue
          from dialogs dia, characteristicstemplate cht, characteristicstempline chtl,
               characteristic ch, dialogflexfields dff
         where cht.dialog_id = dia.dialog_id
           and chtl.characteristicstemplate_id = cht.characteristicstemplate_id
           and chtl.characteristic_id = ch.characteristic_id
           and dff.dialog_id = dia.dialog_id
           and dff.characteristic_id = ch.characteristic_id
           and dff.entity_id = cu.customer_id
           and dia.code = 'Customer'
           and cht.code = '30'
           and ch.code = '30') StockLocation,
       pr.code productcode, pnl.customcode productcustomcode, pnl.customdescription productcustomdescription,
       (select prde.description
          from product_desc prde
         where prde.product_id = pr.product_id and prde.language_id = lan.language_id) productdesc,
       (select prde.longdescription
          from product_desc prde
         where prde.product_id = pr.product_id and prde.language_id = lan.language_id) productlongdesc,
       pnl.packingnoteline_id, pnl.packingsequence, pnl.standardamount, pnl.variationamount, pnl.deliveredamount,
       pnl.tobedeliveredamount, pr.typeofmerchandise, pnl.remarkforpackinginstructions, pnl.origin line_origin,
       pnl.nochargefirstissue, pnl.nochargeactiveseason, pnl.deliveredcogqty nochargenotcog,
       coalesce(pnl.price, 0) price, pnl.amount, pnl.taxgroupcode, lan.code languagecode,
       su.systemuser_id, su.username, su.fullname
from packingnoteline pnl
     join product pr on pnl.product_id = pr.product_id
     join packingnote pn on pnl.packingnote_id = pn.packingnote_id
     left outer join route ro on pn.route_id = ro.route_id
     join businessunit pbu on pn.processbusinessunit_id = pbu.businessunit_id
     join businessunit ibu on pn.invoicebusinessunit_id = ibu.businessunit_id
     join deliverypoint delp on pn.deliverypoint_id = delp.deliverypoint_id
     join distributionpoint dp on pn.distributionpoint_id = dp.distributionpoint_id
     join department de on dp.department_id = de.department_id
     join customer cu on de.customer_id = cu.customer_id
     , languages lan, systemuser su
/

  CREATE OR REPLACE VIEW "V_CONTAINERLABEL" ("CONTAINER_ID", "PRIMARYID") AS 
  select /*version 1.0*/
       co.container_id, co.primaryid
  from container co
/

  CREATE OR REPLACE VIEW "V_CONTAINERRENTAPPENDIX" ("INVOICEHEADER_ID", "INVOICENUMBER", "INVOICEDATE", "STARTDATE", "ENDDATE", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "CURRENCYCODE", "PRICEDECIMALS", "INVOICEDECIMALS", "CONTAINERTYPE_ID", "TOTALQTYALLOWEDFREEONSITE", "INVOICELINE_ID", "CONTAINER_TYPE_DESC", "CONTAINER_TYPE_CODE", "COSTCENTER_CODE", "COSTCENTER_DESC", "COL1_WKNR", "COL2_WKNR", "COL3_WKNR", "COL4_WKNR", "COL5_WKNR", "DISTRIBUTIONPOINT_LINK_ID", "DEPARTMENTNUMBER", "DEPARTMENT_DESC", "CONSPOINT_NR", "CONSPOINT_DESC", "CONTAINER_ID", "DELIVERYDATE", "RETURNDATE", "COL1_STATUS", "COL2_STATUS", "COL3_STATUS", "COL4_STATUS", "COL5_STATUS", "COL1_QTY", "COL2_QTY", "COL3_QTY", "COL4_QTY", "COL5_QTY", "TOTAL_QTY", "BILLEDQTY", "PRICE", "AMOUNT", "LANGUAGECODE", "INVOICELINESUBTYPE", "INVOICELINESUBTYPE_DESC") AS 
  select ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.startdate, ih.enddate,
       ih.deltocustomernumber, ih.deltocustomername, ih.billtocustomernumber, ih.billtocustomername,
       cu.code currencycode, cu.decimals pricedecimals, cu.invoiceamountdecimals invoicedecimals,
       ilc.containertype_id, ilc.totalqtyallowedfreeonsite, il.invoiceline_id,
       (select cdsc.description from containertype_desc cdsc where cdsc.containertype_id = ilc.containertype_id and cdsc.language_id = lan.language_id) container_type_desc,
       (select ctp.code from containertype ctp where ctp.containertype_id = ilc.containertype_id) container_type_code,
       cc.code costcenter_code, cc.description costcenter_desc, getisoweek(ih.startdate) col1_wknr,
       case when ih.startdate + 7 <= ih.enddate then getisoweek(ih.startdate + 7)
       end col2_wknr,
       case when ih.startdate + 14 <= ih.enddate then getisoweek(ih.startdate + 14)
       end col3_wknr,
       case when ih.startdate + 21 <= ih.enddate then getisoweek(ih.startdate + 21)
       end col4_wknr,
       case when ih.startdate + 28 <= ih.enddate then getisoweek(ih.startdate + 28)
       end col5_wknr,
       dp.distributionpoint_link_id, de.departmentnumber, de.description department_desc,
       dp.distributionpointnumber conspoint_nr, dp.description conspoint_desc,
       co.primaryid container_id, cr.deliverydate, cr.returndate,
       y.col1_status, y.col2_status, y.col3_status, y.col4_status, y.col5_status,
       y.col1_qty, y.col2_qty, y.col3_qty, y.col4_qty, y.col5_qty, y.total_qty,
       il.billedqty, il.price, il.amount, lan.code languagecode, il.invoicelinesubtype,
       (select ilstd.description from invoicelinesubtype_desc ilstd
          join invoicelinesubtype ilst on ilstd.invoicelinesubtype_id = ilst.invoicelinesubtype_id
         where ilst.subtype = il.invoicelinesubtype and ilst.invoicelinetype_id = il.invoicelinetype_id
           and ilstd.language_id = lan.language_id) invoicelinesubtype_desc
  from  (select x.containerrent_id, x.invoiceheader_id,
               min(case when x.columnnr = 1 then x.charge_status end) col1_status,
               min(case when x.columnnr = 2 then x.charge_status end) col2_status,
               min(case when x.columnnr = 3 then x.charge_status end) col3_status,
               min(case when x.columnnr = 4 then x.charge_status end) col4_status,
               min(case when x.columnnr = 5 then x.charge_status end) col5_status,
               sum(case when x.columnnr = 1 and x.charge_status = 'B' then 1 else 0 end) col1_qty,
               sum(case when x.columnnr = 2 and x.charge_status = 'B' then 1 else 0 end) col2_qty,
               sum(case when x.columnnr = 3 and x.charge_status = 'B' then 1 else 0 end) col3_qty,
               sum(case when x.columnnr = 4 and x.charge_status = 'B' then 1 else 0 end) col4_qty,
               sum(case when x.columnnr = 5 and x.charge_status = 'B' then 1 else 0 end) col5_qty,
               sum(case when x.charge_status = 'B' then 1 else 0 end) total_qty
           from
                (select c.containerrent_id, c.invoiceheader_id, c.freeofchargeweek,
                        getweeksdifference(getyearofweek(h.startdate), getisoweek(h.startdate), getyearofweek(c.chargedate), getisoweek(c.chargedate)) columnnr,
                        case c.freeofchargeweek
                          when 'Y' then 'F' -- free
                          when 'N' then 'B' -- bill
                        end charge_status
                  from containerrentdetails c join invoiceheader h on h.invoiceheader_id = c.invoiceheader_id) x
         group by x.containerrent_id, x.invoiceheader_id) y
         join invoiceheader ih on ih.invoiceheader_id = y.invoiceheader_id
         join currency cu on cu.currency_id = ih.currency_id
         join containerrent cr on cr.containerrent_id = y.containerrent_id
         join distributionpoint_link dp on dp.distributionpoint_link_id = cr.distributionpoint_link_id
         join department_link de on de.department_id = dp.department_link_id
         join container co on co.container_id = cr.container_id
         join containerbillpercustomer cb on cb.containerbillpercustomer_id = cr.containerbillpercustomer_id
         join costcenter cc on cc.costcenter_id = cb.costcenter_link_id
         join invoiceline il on il.invoiceheader_id = ih.invoiceheader_id
         join invoicelinecontainer ilc on ilc.invoiceline_id = il.invoiceline_id and ilc.containertype_id = cb.containertype_id
         , languages lan
   where il.invoicelinetype_id = 36 and il.invoicelinesubtype = 0
union all
select ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.startdate, ih.enddate,
       ih.deltocustomernumber, ih.deltocustomername, ih.billtocustomernumber, ih.billtocustomername,
       cu.code currencycode, cu.decimals pricedecimals, cu.invoiceamountdecimals invoicedecimals,
       ct.containertype_id, 0 totalqtyallowedfreeonsite, il.invoiceline_id,
       (select cdsc.description from containertype_desc cdsc where cdsc.containertype_id = ct.containertype_id and cdsc.language_id = lan.language_id) container_type_desc,
       ct.code container_type_code,
       cc.code costcenter_code, cc.description costcenter_desc, getisoweek(ih.startdate) col1_wknr,
       case when ih.startdate + 7 <= ih.enddate then getisoweek(ih.startdate + 7)
       end col2_wknr,
       case when ih.startdate + 14 <= ih.enddate then getisoweek(ih.startdate + 14)
       end col3_wknr,
       case when ih.startdate + 21 <= ih.enddate then getisoweek(ih.startdate + 21)
       end col4_wknr,
       case when ih.startdate + 28 <= ih.enddate then getisoweek(ih.startdate + 28)
       end col5_wknr,
       dp.distributionpoint_link_id, de.departmentnumber, de.description department_desc,
       dp.distributionpointnumber conspoint_nr, dp.description conspoint_desc,
       co.primaryid container_id, case when coch.type = 1 then coch.chargecreateddate else null end deliverydate,
       case when coch.type = 2 then coch.chargecreateddate else null end returndate,
       y.col1_status, y.col2_status, y.col3_status, y.col4_status, y.col5_status,
       y.col1_qty, y.col2_qty, y.col3_qty, y.col4_qty, y.col5_qty, y.total_qty,
       il.billedqty, il.price, il.amount, lan.code languagecode, il.invoicelinesubtype,
       (select ilstd.description from invoicelinesubtype_desc ilstd
          join invoicelinesubtype ilst on ilstd.invoicelinesubtype_id = ilst.invoicelinesubtype_id
         where ilst.subtype = il.invoicelinesubtype and ilst.invoicelinetype_id = il.invoicelinetype_id
           and ilstd.language_id = lan.language_id) invoicelinesubtype_desc
  from  (select x.containercharge_id, x.invoiceheader_id,
               min(case when x.columnnr = 1 then x.charge_status end) col1_status,
               min(case when x.columnnr = 2 then x.charge_status end) col2_status,
               min(case when x.columnnr = 3 then x.charge_status end) col3_status,
               min(case when x.columnnr = 4 then x.charge_status end) col4_status,
               min(case when x.columnnr = 5 then x.charge_status end) col5_status,
               sum(case when x.columnnr = 1 and x.charge_status = 'B' then 1 else 0 end) col1_qty,
               sum(case when x.columnnr = 2 and x.charge_status = 'B' then 1 else 0 end) col2_qty,
               sum(case when x.columnnr = 3 and x.charge_status = 'B' then 1 else 0 end) col3_qty,
               sum(case when x.columnnr = 4 and x.charge_status = 'B' then 1 else 0 end) col4_qty,
               sum(case when x.columnnr = 5 and x.charge_status = 'B' then 1 else 0 end) col5_qty,
               sum(case when x.charge_status = 'B' then 1 else 0 end) total_qty
           from
                (select coc.containercharge_id, coc.invoiceheader_id,
                        getweeksdifference(getyearofweek(h.startdate), getisoweek(h.startdate), getyearofweek(coc.chargecreateddate), getisoweek(coc.chargecreateddate)) columnnr,
                        'B' -- bill
                        charge_status
                  from containercharge coc join invoiceheader h on coc.invoiceheader_id = h.invoiceheader_id) x
         group by x.containercharge_id, x.invoiceheader_id) y
         join invoiceheader ih on ih.invoiceheader_id = y.invoiceheader_id
         join currency cu on cu.currency_id = ih.currency_id
         join containercharge coch on coch.containercharge_id = y.containercharge_id
         join distributionpoint_link dp on dp.distributionpoint_link_id = coch.distributionpoint_link_id
         join department_link de on de.department_id = dp.department_link_id
         join container co on co.container_id = coch.container_id
         join containertype ct on ct.containertype_id = co.containertype_id
         join containerbillpercustomer cb on cb.containerbillpercustomer_id = coch.containerbillpercustomer_id
         join costcenter cc on cc.costcenter_id = cb.costcenter_link_id
         join invoiceline il on il.invoiceheader_id = ih.invoiceheader_id and il.invoicelinesubtype = coch.type and il.code = ct.code
         , languages lan
   where il.invoicelinetype_id = 36 and il.invoicelinesubtype <> 0
/

  CREATE OR REPLACE VIEW "V_CONTAINERSPERLOCATION" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DEFAULTBUSINESSUNIT_ID", "BUSINESSUNITCODE", "CONTAINERTYPECODE", "CONTAINERTYPEDESC", "STAYNR", "PREVSTAYNR", "STAYDESC", "PREVSTAYDESC", "LASTCUSTOMERNUMBER", "LASTCUSTOMERNAME", "PRIMARYID", "STAYCHANGEDATE", "NR_DAYS", "LANGUAGECODE") AS 
  select  -- Containers at Customer
  cu.customernumber, cu.name customerName, address.city, de.departmentnumber, de.description departmentDesc
, cu.defaultbusinessunit_id, bu.code businessunitCode, cty.code containertypeCode
, (select containertype_desc.description from containertype_desc where containertype_desc.containertype_id = cty.containertype_id
  and containertype_desc.language_id = languages.language_id ) containertypeDesc
, stay.staynr, prev_stay.staynr prevStayNR
, (select stay_desc.description from stay_desc where stay_desc.stay_id = ct.stay_id
   and stay_desc.language_id = languages.language_id ) StayDesc
, ( select stay_desc.description from stay_desc where stay_desc.stay_id = ct.prevstay_id
   and stay_desc.language_id = languages.language_id ) prevStayDesc
, culk.customernumber  LastCustomerNumber, culk.name LastCustomerName
, ct.primaryid, ct.staychangedate
, coalesce((trunc(sysdate) - trunc(ct.staychangedate)),0) NR_Days
, languages.code languageCode
from
  container ct
            left outer join stay prev_stay on ct.prevstay_id = prev_stay.stay_id
            left outer join
                 ( distributionpoint_link dilk
                   join
                        ( department_link delk join customer_link culk on delk.customer_link_id = culk.customer_link_id )
                   on dilk.department_link_id = delk.department_link_id)
                 on ct.lastdistributionpoint_link_id = dilk.distributionpoint_link_id
, containertype cty, distributionpoint dip, department de, customer cu, businessunit bu
, stay, address, languages
where
    ( ct.dateactive <= trunc(sysdate) and ct.dateinactive > trunc(sysdate) )
and ct.stay_id = stay.stay_id
    and stay.staytype = 2
        and stay.staynr in (20, 21)-->= 20 and stay.staynr < 30
and ct.containertype_id = cty.containertype_id
and ct.distributionpoint_id = dip.distributionpoint_id
    and dip.department_id = de.department_id
        and de.customer_id = cu.customer_id
            and cu.visitaddress_id = address.address_id
and (cu.defaultbusinessunit_id = bu.businessunit_id or
    exists (select 1 from customeractivities ca where
         (ca.processbusinessunit_id = bu.businessunit_id or ca.invoicebusinessunit_id=bu.businessunit_id
        or ca.internalprocessingbu_id=bu.businessunit_id)
        and ca.customer_id = cu.customer_id))
UNION ALL
select  -- Containers In Laundry
  -1 customernumber, '' customerName, '' city, -1 departmentnumber, '' departmentDesc
, ct.businessunit_id --defaultbusinessunit_id
, bu.code businessunitCode, cty.code containertypeCode
, (select containertype_desc.description from containertype_desc where containertype_desc.containertype_id = cty.containertype_id
  and containertype_desc.language_id = languages.language_id ) containertypeDesc
, stay.staynr, prev_stay.staynr prevStayNR
, (select stay_desc.description from stay_desc where stay_desc.stay_id = ct.stay_id
   and stay_desc.language_id = languages.language_id ) StayDesc
, ( select stay_desc.description from stay_desc where stay_desc.stay_id = ct.prevstay_id
   and stay_desc.language_id = languages.language_id ) prevStayDesc
, culk.customernumber  LastCustomerNumber, culk.name LastCustomerName
, ct.primaryid, ct.staychangedate
, coalesce((trunc(sysdate)-trunc(ct.staychangedate)),0) NR_Days
, languages.code languageCode
from
  container ct
            left outer join stay prev_stay on ct.prevstay_id = prev_stay.stay_id
            left outer join
                 ( distributionpoint_link dilk
                   join
                        ( department_link delk join customer_link culk
                                                 on delk.customer_link_id = culk.customer_link_id )
                   on dilk.department_link_id = delk.department_link_id)
                 on ct.lastdistributionpoint_link_id = dilk.distributionpoint_link_id
, containertype cty, stay, businessunit bu
, languages
where
    ( ct.dateactive <= trunc(sysdate) and ct.dateinactive > trunc(sysdate) )
and ct.stay_id = stay.stay_id
    and stay.staytype = 2
        and (stay.staynr <> 20 and stay.staynr <> 21)--(stay.staynr < 20 or stay.staynr >= 30)
and ct.containertype_id = cty.containertype_id
and ct.businessunit_id = bu.businessunit_id
/

  CREATE OR REPLACE VIEW "V_CONTAINERSTICKER" ("LINETYPE", "NOTENUMBER", "CORRECTEDNOTENUMBER", "SEQUENCENUMBER", "DELIVERYDATE", "ORIGINALDELIVERYDATE", "REMARK", "STOPNUMBER", "PACKINGNOTE_ID", "ENDDATEFORUSE", "ORIGIN", "PRODUCTIONDATE", "NUMBEROFGARMENTSINLOCKER", "NUMBEROFLOCKERS", "CUSTOMERNUMBER", "CUSTOMERNAME", "LEGALNAME", "PHONENO", "CUSTOMERSTREET", "CUSTOMERZIP", "CUSTOMERCITY", "CUSTOMERSTREET2", "CUSTOMERSTATE", "CUSTOMERCOUNTY", "MAIL_STREET", "MAIL_ZIPCODE", "MAIL_CITY", "MAIL_STATE", "MAIL_COUNTY", "MAIL_STREET2", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "DELIVERYPOINTCODE", "DELIVERYPOINTDESCRIPTION", "BUDESCRIPTION", "PLANTNAME", "PLANTSTREET", "PLANTZIPCODE", "PLANTCITY", "PLANTPHONENO", "PLANTFAXNO", "PLANTLOGO", "SORTADDRESS", "BUSINESSUNIT_ID", "BU_CODE", "PLANT_COUNTRYCODE", "DRIVINGDAY_DESC", "PACKINGDAY_DESC", "ROUTENUMBER", "ROUTEDESCRIPTION", "LOADINGDOCK", "LANGUAGECODE", "DELPOINT_STREET", "DELPOINT_STREET2", "DELPOINT_ZIPCODE", "DELPOINT_CITY", "DELPOINT_STATE", "DELPOINT_COUNTY", "DEPOTDESCRIPTION", "REMARKONPACKINGNOTE", "REMARKONDELIVERYNOTE", "LANGUAGECODECUSTOMER", "CP_LABELCOLOR", "INTERNALREMARKFORTRANSPLABEL", "TRANSPLABINTERNALREMARKENDDATE", "EXTERNALREMARKFORTRANSPLABEL", "TRANSPLABEXTERNALREMARKENDDATE", "NOOFTRANSPORTLABELS", "USAGEDAYNUMBER", "USAGEDAYDESC", "CU_LABELCOLOR", "DAY_ID", "EMPLOYEENAME", "EMPLOYEESEARCHNAME", "EMPLOYEENUMBER", "TRANSPORTARTICLE", "PACKINGNOTECONTAINER_ID", "CONTAINERSEQUENCENR", "CONTAINERID", "GROSSWEIGHT", "NETWEIGHT", "WEIGHTDECIMALS", "WEIGHTUNIT", "EXTRANAME1") AS 
  select /*version 6.2*/
       0 linetype, -- packingnote level
       pn.notenumber, pn.correctednotenumber, pn.sequencenumber, pn.deliverydate, pn.originaldeliverydate, pn.remark, pn.stopnumber, pn.packingnote_id,
       pn.enddateforuse, pn.origin, pn.productiondate productiondate, pn.numberofgarmentsinlocker, pn.numberoflockers, cu.customernumber,
       cu.name customername, cu.legalname, cu.phoneno, ad.street customerstreet, ad.zipcode customerzip, ad.city customercity, ad.street2 customerstreet2,
       ad.state customerstate, ad.county customercounty, mail_ad.street mail_street, mail_ad.zipcode mail_zipcode, mail_ad.city mail_city,
       mail_ad.state mail_state, mail_ad.county mail_county, mail_ad.street2 mail_street2, de.departmentnumber, de.description departmentdescription,
       dp.distributionpointnumber, dp.description distributionpointdescription, delp.code deliverypointcode, delp.description deliverypointdescription,
       procbu.description budescription, pl.name plantname, pl_ad.street plantstreet, pl_ad.zipcode plantzipcode, pl_ad.city plantcity,
       pl.phoneno plantphoneno, pl.faxno plantfaxno, pl.logo plantlogo, de.sortaddress, procbu.businessunit_id, procbu.code bu_code,
       (select con.code
          from country con
         where con.country_id = pl.country_id) plant_countrycode,
       (select dd.description
          from day_desc dd
         where dd.day_id = ro.drivingday_id
           and dd.language_id = lan.language_id) drivingday_desc,
       (select dd.description
          from day_desc dd
         where dd.day_id = ro.packingday_id
           and dd.language_id = lan.language_id) packingday_desc, ro.routenumber, ro.description routedescription, ro.loadingdock, lan.code languagecode,
       delp_ad.street delpoint_street, delp_ad.street2 delpoint_street2, delp_ad.zipcode delpoint_zipcode, delp_ad.city delpoint_city,
       delp_ad.state delpoint_state, delp_ad.county delpoint_county, dep.description depotdescription, dp.remarkonpackingnote, dp.remarkondeliverynote,
       (select culan.code from languages culan where cu.language_id = culan.language_id) languagecodecustomer, dp.labelcolor cp_labelcolor,
       dp.internalremarkfortransplabel, dp.transplabinternalremarkenddate, dp.externalremarkfortransplabel, dp.transplabexternalremarkenddate,
       dp.nooftransportlabels,
       (select dud.usageday_id
          from departmentusageday dud
         where dud.department_id = de.department_id
           and dud.day_id = ro.drivingday_id) usagedaynumber,
       (select dd.description
          from departmentusageday dud, day_desc dd
         where dud.department_id = de.department_id
           and dud.usageday_id = dd.day_id
           and dud.day_id = ro.drivingday_id
           and dd.language_id = lan.language_id) usagedaydesc, cu.labelcolor cu_labelcolor, ro.drivingday_id day_id, em.name employeename,
       em.searchname employeesearchname, em.employeenumber,
       (select tad.description
          from transportarticle_desc tad
         where tad.transportarticle_id = pn.transportarticle_id
           and tad.language_id = lan.language_id) transportarticle, null packingnotecontainer_id, null containersequencenr, null containerid,
       null grossweight, null netweight, 1 weightdecimals, null weightunit,
       (case when cu.sendinvoiceto = 0 then cu.extraname1
             when cu.sendinvoiceto = 1 then (select cust.extraname1
                                              from customer cust
                                             where cust.customer_id = cu.debtor_id)
             else cu.extraname1
         end) extraname1
  from packingnote pn
       left join employee em on pn.employee_id = em.employee_id
       left join route ro
            left join depot dep on ro.depot_id = dep.depot_id
       on pn.route_id = ro.route_id
       join distributionpoint dp
            join department de
                 join customer cu
                      join address ad on cu.visitaddress_id = ad.address_id
                      join address mail_ad on cu.mailaddress_id = mail_ad.address_id
                 on de.customer_id = cu.customer_id
            on dp.department_id = de.department_id
       on pn.distributionpoint_id = dp.distributionpoint_id
       join deliverypoint delp
            join address delp_ad on delp.deliveryaddress_id = delp_ad.address_id
       on pn.deliverypoint_id = delp.deliverypoint_id
       join businessunit procbu
            join plant pl
                 join address pl_ad on pl.address_id = pl_ad.address_id
            on procbu.plant_id = pl.plant_id
       on pn.processbusinessunit_id = procbu.businessunit_id
       cross join languages lan
union all
select 1 linetype, -- packingnote container level
       pn.notenumber, pn.correctednotenumber, pn.sequencenumber, pn.deliverydate, pn.originaldeliverydate, pn.remark, pn.stopnumber, pn.packingnote_id,
       pn.enddateforuse, pn.origin, pn.productiondate productiondate, pn.numberofgarmentsinlocker, pn.numberoflockers, cu.customernumber,
       cu.name customername, cu.legalname, cu.phoneno, ad.street customerstreet, ad.zipcode customerzip, ad.city customercity, ad.street2 customerstreet2,
       ad.state customerstate, ad.county customercounty, mail_ad.street mail_street, mail_ad.zipcode mail_zipcode, mail_ad.city mail_city,
       mail_ad.state mail_state, mail_ad.county mail_county, mail_ad.street2 mail_street2, de.departmentnumber, de.description departmentdescription,
       dp.distributionpointnumber, dp.description distributionpointdescription, delp.code deliverypointcode, delp.description deliverypointdescription,
       procbu.description budescription, pl.name plantname, pl_ad.street plantstreet, pl_ad.zipcode plantzipcode, pl_ad.city plantcity,
       pl.phoneno plantphoneno, pl.faxno plantfaxno, pl.logo plantlogo, de.sortaddress, procbu.businessunit_id, procbu.code bu_code,
       (select con.code
          from country con
         where con.country_id = pl.country_id) plant_countrycode,
       (select dd.description
          from day_desc dd
         where dd.day_id = ro.drivingday_id
           and dd.language_id = lan.language_id) drivingday_desc,
       (select dd.description
          from day_desc dd
         where dd.day_id = ro.packingday_id
           and dd.language_id = lan.language_id) packingday_desc, ro.routenumber, ro.description routedescription, ro.loadingdock, lan.code languagecode,
       delp_ad.street delpoint_street, delp_ad.street2 delpoint_street2, delp_ad.zipcode delpoint_zipcode, delp_ad.city delpoint_city,
       delp_ad.state delpoint_state, delp_ad.county delpoint_county, dep.description depotdescription, dp.remarkonpackingnote, dp.remarkondeliverynote,
       (select culan.code
          from languages culan
         where cu.language_id = culan.language_id) languagecodecustomer,
       dp.labelcolor cp_labelcolor, dp.internalremarkfortransplabel, dp.transplabinternalremarkenddate, dp.externalremarkfortransplabel,
       dp.transplabexternalremarkenddate, dp.nooftransportlabels,
       (select dud.usageday_id
          from departmentusageday dud
         where dud.department_id = de.department_id
           and dud.day_id = ro.drivingday_id) usagedaynumber,
       (select dd.description
          from departmentusageday dud, day_desc dd
         where dud.department_id = de.department_id
           and dud.usageday_id = dd.day_id
           and dud.day_id = ro.drivingday_id
           and dd.language_id = lan.language_id) usagedaydesc, cu.labelcolor cu_labelcolor, ro.drivingday_id day_id, em.name employeename,
       em.searchname employeesearchname, em.employeenumber,
       (select tad.description
          from transportarticle_desc tad
         where tad.transportarticle_id = pn.transportarticle_id
           and tad.language_id = lan.language_id) transportarticle, pnc.packingnotecontainer_id, pnc.sequencenumber containersequencenr,
       co.primaryid containerid, pnc.grossweight, pnc.grossweight - pnc.tareweight netweight, pnc.weightdecimals,
       (select s.value
          from systemsetting s
         where s.plant_id = pl.plant_id
           and s.name = 'WEIGHTUNIT') weightunit,
       (case when cu.sendinvoiceto = 0 then cu.extraname1
             when cu.sendinvoiceto = 1 then (select cust.extraname1
                                              from customer cust
                                             where cust.customer_id = cu.debtor_id)
             else cu.extraname1
         end) extraname1
  from packingnotecontainer pnc
       left join container co on pnc.container_id = co.container_id
       join packingnote pn
            left join employee em on pn.employee_id = em.employee_id
            left join route ro
                 left join depot dep on ro.depot_id = dep.depot_id
            on pn.route_id = ro.route_id
       on pnc.packingnote_id = pn.packingnote_id
       join distributionpoint dp
            join department de
                 join customer cu
                      join address ad on cu.visitaddress_id = ad.address_id
                      join address mail_ad on cu.mailaddress_id = mail_ad.address_id
                 on de.customer_id = cu.customer_id
            on dp.department_id = de.department_id
       on pn.distributionpoint_id = dp.distributionpoint_id
       join deliverypoint delp
            join address delp_ad on delp.deliveryaddress_id = delp_ad.address_id
       on pn.deliverypoint_id = delp.deliverypoint_id
       join businessunit procbu
            join plant pl
                 join address pl_ad on pl.address_id = pl_ad.address_id
            on procbu.plant_id = pl.plant_id
       on pn.processbusinessunit_id = procbu.businessunit_id
       cross join languages lan
/

  CREATE OR REPLACE VIEW "V_CONTAINERSTICKER_ADV" ("CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "LEGALNAME", "PHONENO", "CUSTOMERSTREET", "CUSTOMERZIP", "CUSTOMERCITY", "CUSTOMERSTREET2", "CUSTOMERSTATE", "CUSTOMERCOUNTY", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "DELIVERYPOINT_ID", "DELIVERYPOINTCODE", "DELIVERYPOINTDESCRIPTION", "ROUTENUMBER", "ROUTEDESCRIPTION", "LOADINGDOCK", "REPORTPARAM_ID", "TIMESTAMP", "COPY_NUMBER", "LANGUAGECODE", "DELPOINT_STREET", "DELPOINT_STREET2", "DELPOINT_ZIPCODE", "DELPOINT_CITY", "DELPOINT_STATE", "BU_CODE", "BUSINESSUNIT_ID", "DELPOINT_COUNTY", "DUMMYGRP", "DEPOTDESCRIPTION", "CP_LABELCOLOR", "INTERNALREMARKFORTRANSPLABEL", "TRANSPLABINTERNALREMARKENDDATE", "EXTERNALREMARKFORTRANSPLABEL", "TRANSPLABEXTERNALREMARKENDDATE", "NOOFTRANSPORTLABELS", "CU_LABELCOLOR", "PLANT_COUNTRYCODE", "DRIVINGDAY_DESC", "USAGEDAYNUMBER", "USAGEDAYDESC", "EXTRANAME1") AS 
  select /*version 5.2*/
       c.customer_id, c.customernumber, c.name customername, c.legalname, c.phoneno, ads.street customerstreet, ads.zipcode customerzip, ads.city customercity,
       ads.street2 customerstreet2, ads.state customerstate, ads.county customercounty, d.department_id, d.departmentnumber, d.description departmentdescription,
       dp.distributionpointnumber, dp.description distributionpointdescription, dvp.deliverypoint_id, dvp.code deliverypointcode, dvp.description deliverypointdescription,
       r.routenumber, r.description routedescription, r.loadingdock, rp.reportparam_id, rp.timestamp, rp.copy_number, lan.code languagecode, dpads.street delpoint_street,
       dpads.street2 delpoint_street2, dpads.zipcode delpoint_zipcode, dpads.city delpoint_city, dpads.state delpoint_state, bu.code bu_code, bu.businessunit_id,
       dpads.county delpoint_county, rp.string_value dummygrp, de.description depotdescription, dp.labelcolor cp_labelcolor, dp.internalremarkfortransplabel,
       dp.transplabinternalremarkenddate, dp.externalremarkfortransplabel, dp.transplabexternalremarkenddate, dp.nooftransportlabels, c.labelcolor cu_labelcolor,
       (select con.code
          from plant p
               join country con on p.country_id = con.country_id
         where p.plant_id = bu.plant_id) plant_countrycode,
       (select dd.description
          from day_desc dd
         where dd.day_id = r.drivingday_id
           and dd.language_id = lan.language_id) drivingday_desc,
       (select dud.usageday_id
          from departmentusageday dud
         where dud.department_id = d.department_id
           and dud.day_id = r.drivingday_id) usagedaynumber,
       (select dd.description
          from departmentusageday dud, day_desc dd
         where dud.department_id = d.department_id
           and dud.usageday_id = dd.day_id
           and dud.day_id = r.drivingday_id
           and dd.language_id = lan.language_id) usagedaydesc,
       (case when c.sendinvoiceto = 0 then c.extraname1
             when c.sendinvoiceto = 1 then (select cust.extraname1
                                              from customer cust
                                             where cust.customer_id = c.debtor_id)
             else c.extraname1
         end) extraname1
  from customer c
       join department d
            join distributionpoint dp
                 join reportparam rp on dp.distributionpoint_id = rp.number_value
                      join deliverypoint dvp
                           join  address dpads on dvp.deliveryaddress_id = dpads.address_id
                      on dvp.deliverypoint_id = decode(rp.number_value4, 0, dp.deliverypoint_id, rp.number_value4)
                      join languages lan on rp.string_value2 = lan.code
                      join route r
                           left join depot de on r.depot_id = de.depot_id
                      on rp.number_value1 = r.route_id
            on d.department_id = dp.department_id
       on c.customer_id = d.customer_id
       join address ads on c.visitaddress_id = ads.address_id
       join businessunit bu on c.defaultbusinessunit_id = bu.businessunit_id
/

  CREATE OR REPLACE VIEW "V_CONTRACTEXPIRATION" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMERACTIVEYN", "STREET", "STREET2", "CITY", "STATE", "ZIPCODE", "PHONENO", "ROUTEANDSTOP", "PHONELEN", "DELIVERYSCHEMECODE", "CONTRACTCODE", "CONTRACTDATEACTIVE", "STARTSIGNALINGDATE", "CONTRACTDATEINACTIVE", "MAXCONTRACTDATEACTIVE", "MINCONTRACTDATEINACTIVE", "SIGNALINGWEEKS", "CONTINUESERVICE", "ESTIMATEDWEEKLYSALES", "CONTACTPERSONNAME", "CONTACTPERSONPHONE", "HAVECONTINUE", "BUSINESSUNITCODE") AS 
  select
  cu.customernumber, cu.name CustomerName, cu.active CustomerActiveYN, address.street, address.street2
, address.city, address.state, address.zipcode, cu.phoneno
, CAST(F_FIRSTROUTEANDSTOP(cu.customer_id) as varchar(255)) routeandstop,
      cast((select ss.value  from systemsetting ss, businessunit bu where cu.defaultbusinessunit_id=bu.businessunit_id and ss.plant_id=bu.plant_id and  ss.name='PHONEFAXLENGTH') as varchar2(16)) phonelen,
 (select deliveryscheme.code from deliveryscheme where
F_DELIVERYSCHEMEPERCUSTOMER(cu.customer_id) = deliveryscheme.deliveryscheme_id) deliveryschemeCode
, kcu.code ContractCode, kcu.dateactive Contractdateactive
, (kcu.dateinactive- 7*kcu.signalingweeks) StartSignalingDate, kcu.dateinactive Contractdateinactive
, (select max(contractspercustomer.dateactive) from  contractspercustomer
          where contractspercustomer.customer_id = cu.customer_id) MaxContractdateactive
, (select max(contractspercustomer.dateinactive) from  contractspercustomer
          where contractspercustomer.customer_id = cu.customer_id) MinContractdateinactive
, kcu.signalingweeks
, kcu.continueservice, kcu.estimatedweeklysales, contactperson.name contactpersonName
, contactperson.phone contactpersonPhone
, coalesce((select sum(1)
    from contractspercustomer k
    where k.customer_id = kcu.customer_id
--      and k.dateactive <= kcu.dateinactive
      and k.dateactive <= kcu.dateinactive + 1
      and kcu.dateinactive < k.dateinactive
      and k.code<>kcu.code ),0) HaveContinue,
  bu.code businessunitcode
from
  customer cu, address, businessunit bu
, contractspercustomer kcu left outer join contactperson on contactperson.contactperson_id=kcu.contactperson_id
where cu.mailaddress_id = address.address_id
  and cu.customer_id = kcu.customer_id
  and cu.defaultbusinessunit_id = bu.businessunit_id
/

  CREATE OR REPLACE VIEW "V_CONTRACTEXPIRATION_AUX" ("DELIVERYSCH_CUSTOMER", "CUSTOMER_ID") AS 
  select F_DELIVERYSCHEMEPERCUSTOMER(cu.customer_id) DELIVERYSCH_CUSTOMER, cu.customer_id
from
  customer cu
/

  CREATE OR REPLACE VIEW "V_CONTRACTSCUSTOMER" ("CODE", "DESCRIPTION", "CUSTOMERNAME", "OWNER", "PURCHASEORDER", "STARTDATE", "ENDDATE", "EXPIREDATE", "CUSTOMER_ID") AS 
  select co.code, co.description
, (select cl.name from Customer_Link cl where co.customer_link_id=cl.customer_link_id) CustomerName
, co.owner, co.purchaseorder
, cc.startdate, cc.enddate, co.enddate ExpireDate
, cc.customer_link_id customer_id
from contract co, contractcustomer cc
where co.contract_id = cc.contract_id
--?????and co.customer_link_id = cc.customer_link_id
/

  CREATE OR REPLACE VIEW "V_CONTRACTSPERCUSTOMER" ("CODE", "DATEACTIVE", "DATEINACTIVE", "SIGNDATE", "CONTINUESERVICE", "SIGNALINGWEEKS", "CONTRACTDOCUMENT", "PURCHASEORDER", "PURCHASEORDEREXPIRATIONDATE", "PURCHASEORDERVALUE", "NEXTANNIVERSARYDATE", "ANNIVERSARYPRICEADJ", "CPIBASED", "FIXEDWASHPERC", "FIXEDRENTPERC", "FIXEDREPLACEPERC", "FIXEDSALESPERC", "FIXEDWEIGHTPERC", "ESTIMATEDWEEKLYSALES", "CUSTOMERNUMBER", "CUSTOMERNAME", "CONTACTPERSONNUMBER", "CONTACTPERSONNAME", "GAINREASONCODE", "GAINREASONDESCRIPTION", "GAINCOMPETITORCODE", "GAINCOMPETITORNAME", "LOSTREASONCODE", "LOSTREASONDESCRIPTION", "LOSTCOMPETITORCODE", "LOSTCOMPETITORNAME", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT CONTRACTSPERCUSTOMER.CODE, CONTRACTSPERCUSTOMER.DATEACTIVE, CONTRACTSPERCUSTOMER.DATEINACTIVE,
CONTRACTSPERCUSTOMER.SIGNDATE, CONTRACTSPERCUSTOMER.CONTINUESERVICE,
CONTRACTSPERCUSTOMER.SIGNALINGWEEKS,
CONTRACTSPERCUSTOMER.CONTRACTDOCUMENT, CONTRACTSPERCUSTOMER.PURCHASEORDER,
CONTRACTSPERCUSTOMER.PURCHASEORDEREXPIRATIONDATE, CONTRACTSPERCUSTOMER.PURCHASEORDERVALUE,
CONTRACTSPERCUSTOMER.NEXTANNIVERSARYDATE, CONTRACTSPERCUSTOMER.ANNIVERSARYPRICEADJ,
CONTRACTSPERCUSTOMER.CPIBASED, CONTRACTSPERCUSTOMER.FIXEDWASHPERC,
CONTRACTSPERCUSTOMER.FIXEDRENTPERC, CONTRACTSPERCUSTOMER.FIXEDREPLACEPERC,
CONTRACTSPERCUSTOMER.FIXEDSALESPERC, CONTRACTSPERCUSTOMER.FIXEDWEIGHTPERC,
CONTRACTSPERCUSTOMER.ESTIMATEDWEEKLYSALES,
CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME,
CONTACTPERSON.CONTACTPERSONNUMBER, CONTACTPERSON.NAME,
GAINREASON.CODE,
(SELECT DESCRIPTION FROM GAINLOSTREASON_DESC A WHERE A.GAINLOSTREASON_ID = CONTRACTSPERCUSTOMER.GAINREASON_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) GAINREASONDESC,
GAINCOMPETITOR.CODE, GAINCOMPETITOR.NAME,
LOSTREASON.CODE,
(SELECT DESCRIPTION FROM GAINLOSTREASON_DESC A WHERE A.GAINLOSTREASON_ID = CONTRACTSPERCUSTOMER.LOSTREASON_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) LOSTREASONDESC,
LOSTCOMPETITOR.CODE, LOSTCOMPETITOR.NAME, CONTRACTSPERCUSTOMER.SYSTEMUSER_ID, CONTRACTSPERCUSTOMER.TIMESTAMP, LANGUAGES.CODE
FROM CUSTOMER, LANGUAGES, CONTRACTSPERCUSTOMER
     LEFT OUTER JOIN CONTACTPERSON ON(CONTRACTSPERCUSTOMER.CONTACTPERSON_ID = CONTACTPERSON.CONTACTPERSON_ID)
     LEFT OUTER JOIN GAINLOSTREASON GAINREASON ON (CONTRACTSPERCUSTOMER.GAINREASON_ID=GAINREASON.GAINLOSTREASON_ID)
     LEFT OUTER JOIN GAINLOSTREASON LOSTREASON ON(CONTRACTSPERCUSTOMER.LOSTREASON_ID=LOSTREASON.GAINLOSTREASON_ID)
     LEFT OUTER JOIN COMPETITOR GAINCOMPETITOR ON(CONTRACTSPERCUSTOMER.GAINCOMPETITOR_ID = GAINCOMPETITOR.COMPETITOR_ID)
     LEFT OUTER JOIN COMPETITOR LOSTCOMPETITOR ON(CONTRACTSPERCUSTOMER.LOSTCOMPETITOR_ID = LOSTCOMPETITOR.COMPETITOR_ID)
WHERE CONTRACTSPERCUSTOMER.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
/

  CREATE OR REPLACE VIEW "V_CORRECTIONTICKETAPPENDIX" ("INVOICEHEADER_ID", "LANGUAGE_CODE", "DELIVERYDATE", "CUSTOMERNUMBER", "CUSTOMERNAME", "QTYDEL", "QTYFOC", "PRODUCTCODE", "PRODUCTDESC", "CORRECTIONREASONCODE", "CORRECTIONREASONCODEDESC", "INVOICENUMBER", "INVOICEDATE", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "SPLITUPCODE", "SPLITUPDESCRIPTION", "STARTWEEK", "ENDWEEK", "STARTMONTH", "ENDMONTH", "INVOICEFREQUENCYNUMBER") AS 
  select pnl.invoiceheader_id, lan.code language_code,
       pn.deliverydate, cu.customernumber, cu.name customername,
       (case
          when pn.correctednotenumber = 0 then
           0
          else
           (select sum(pal.deliveredamount)
            from   packingnote pa, packingnoteline pal
            where  pa.packingnote_id = pal.packingnote_id and
                   pal.product_id = pnl.product_id and
                   pal.sizedefinition_id = pnl.sizedefinition_id and
                   pal.finishingmethod_id = pnl.finishingmethod_id and
                   pa.notenumber = pn.correctednotenumber)
        end) QtyDel,
       pnl.deliveredamount QtyFoc, pr.code ProductCode,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) ProductDesc,
       (select rsc.code from reasoncode rsc where rsc.reasoncode_id = pn.correctionreasoncode_id) correctionreasoncode,
       (select rdc.description
          from reasoncode_desc rdc
         where rdc.reasoncode_id = pn.correctionreasoncode_id
           and rdc.language_id = lan.language_id) correctionreasoncodedesc,
       ih.invoicenumber, ih.invoicedate, ih.deltocustomernumber, ih.deltocustomername, ih.splitupcode, ih.splitupdescription,
       ih.startweek, ih.endweek, ih.startmonth, ih.endmonth, ih.invoicefrequency_id invoicefrequencynumber
  from packingnoteline pnl
  join packingnote pn on pnl.packingnote_id = pn.packingnote_id
  join distributionpoint dp on pn.distributionpoint_id = dp.distributionpoint_id
  join department de on dp.department_id = de.department_id
  join customer cu on de.customer_id = cu.customer_id
  join languages lan on cu.language_id = lan.language_id
  join product pr on pnl.product_id = pr.product_id
  join invoiceheader ih on pnl.invoiceheader_id = ih.invoiceheader_id
 where pn.origin = 3
/

  CREATE OR REPLACE VIEW "V_CORRECTIONTICKETDETAILS" ("INVOICEHEADER_ID", "LANGUAGE_CODE", "DELIVERYDATE", "CUSTOMERNUMBER", "CUSTOMERNAME", "QTYDEL", "QTYFOC", "PRODUCTCODE", "PRODUCTDESC", "CORRECTIONREASONCODE", "CORRECTIONREASONCODEDESC", "BU_CODE", "BU_DESC", "PLANT_CODE", "PLANT_NAME") AS 
  select pnl.invoiceheader_id, lan.code language_code,
       pn.deliverydate, cu.customernumber, cu.name customername,
       0 QtyDel,
       pnl.deliveredamount QtyFoc, pr.code ProductCode,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) ProductDesc,
       (select rsc.code from reasoncode rsc where rsc.reasoncode_id = pn.correctionreasoncode_id) correctionreasoncode,
       (select rdc.description
          from reasoncode_desc rdc
         where rdc.reasoncode_id = pn.correctionreasoncode_id
           and rdc.language_id = lan.language_id) correctionreasoncodedesc,
       ibu.code BU_code, ibu.description BU_desc,
       pl.code Plant_Code, pl.name Plant_Name
  from packingnoteline pnl
  join packingnote pn on pnl.packingnote_id = pn.packingnote_id
  join distributionpoint dp on pn.distributionpoint_id = dp.distributionpoint_id
  join department de on dp.department_id = de.department_id
  join customer cu on de.customer_id = cu.customer_id
  join languages lan on cu.language_id = lan.language_id
  join product pr on pnl.product_id = pr.product_id
  join businessunit ibu on pn.invoicebusinessunit_id = ibu.businessunit_id
  join plant pl on ibu.plant_id = pl.plant_id
 where pn.origin = 3
union all
select -1 invoiceheader_id, lan.code language_code,
       dh.deliverydate, cu.customernumber, cu.name customername,
       sum(dh.amountdelivered) QtyDel,
       0 QtyFoc, pr.code ProductCode,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) ProductDesc,
       null correctionreasoncode,
       null correctionreasoncodedesc,
       ibu.code BU_code, ibu.description BU_desc,
       pl.code Plant_Code, pl.name Plant_Name
  from deliveryhistory dh
  join distributionpoint dp on dh.distributionpoint_link_id = dp.distributionpoint_id
  join department de on dp.department_id = de.department_id
  join customer cu on de.customer_id = cu.customer_id
  join languages lan on cu.language_id = lan.language_id
  join product pr on dh.product_link_id = pr.product_id
  join businessunit ibu on dh.invoicebusinessunit_id = ibu.businessunit_id
  join plant pl on ibu.plant_id = pl.plant_id
group by lan.code, dh.deliverydate, cu.customernumber, cu.name, pr.code, pr.product_id, lan.language_id,
       ibu.code, ibu.description, pl.code, pl.name
/

  CREATE OR REPLACE VIEW "V_CORRECT_STOCK_ORDERED_QTYS" ("STOCKROOMCODE", "PRODUCTCODE", "SIZECODE", "STOCKRESERVATIONPERGRADE_ID", "QTYUNIQUEORDERED", "OUTSTANDINGUNIQUE", "QTYUNIQUEORDEREDDIRECTISSUE", "OUTSTANDINGUNIQUEDI", "QTYNONUNIQUEORDERED", "OUTSTANDINGNONUNIQUE", "QTYNONUNIQUEORDEREDDIRECTISSUE", "OUTSTANDINGNONUNIQUEDI") AS 
  select /*view correct_stock_ordered_qtys version 1.0*/
 x.stockroomcode,
 x.productcode,
 x.sizecode,
 x.stockreservationpergrade_id,
 x.qtyuniqueordered,
 x.outstandingunique,
 x.qtyuniqueordereddirectissue,
 x.outstandinguniquedi,
 x.qtynonuniqueordered,
 x.outstandingnonunique,
 x.qtynonuniqueordereddirectissue,
 x.outstandingnonuniquedi
from   (select sr.code stockroomcode, p.code productcode, s.code sizecode,
                srg.stockreservationpergrade_id, srg.qtynonuniqueordered,
                srg.qtynonuniqueordereddirectissue, srg.qtyuniqueordered,
                srg.qtyuniqueordereddirectissue,
                f_orderedcorrectiongrade(sdi.stockroom_id, sdi.product_id, sdi.sizedefinition_id,
                                          sdi.customer_id, 'N', 'N', srg.qualitygrade_id) outstandingnonunique,
                f_orderedcorrectiongrade(sdi.stockroom_id, sdi.product_id, sdi.sizedefinition_id,
                                          sdi.customer_id, 'Y', 'N', srg.qualitygrade_id) outstandingunique,
                f_orderedcorrectiongrade(sdi.stockroom_id, sdi.product_id, sdi.sizedefinition_id,
                                          sdi.customer_id, 'N', 'Y', srg.qualitygrade_id) outstandingnonuniquedi,
                f_orderedcorrectiongrade(sdi.stockroom_id, sdi.product_id, sdi.sizedefinition_id,
                                          sdi.customer_id, 'Y', 'Y', srg.qualitygrade_id) outstandinguniquedi
         from   stockreservationpergrade srg
         join   stockdefinitionperitem sdi
         on     sdi.stockdefinitionperitem_id = srg.stockdefinitionperitem_id
         join   product p
         on     p.product_id = sdi.product_id
         join   sizedefinition s
         on     s.sizedefinition_id = sdi.sizedefinition_id
         join   qualitygrade q
         on     q.qualitygrade_id = srg.qualitygrade_id
         join   stockroom sr
         on     sr.stockroom_id = sdi.stockroom_id) x
where  (x.qtyuniqueordered <> x.outstandingunique or
       x.qtyuniqueordereddirectissue <> x.outstandinguniquedi or
       x.qtynonuniqueordered <> x.outstandingnonunique or
       x.qtynonuniqueordereddirectissue <> x.outstandingnonuniquedi)
/

  CREATE OR REPLACE VIEW "V_COSTCENTER" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CODE", "DESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, COSTCENTER.CODE, COSTCENTER.DESCRIPTION,
COSTCENTER.SYSTEMUSER_ID, COSTCENTER.TIMESTAMP
       FROM COSTCENTER, CUSTOMER
       WHERE COSTCENTER.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
/

  CREATE OR REPLACE VIEW "V_COSTCENTERINVLINECOSTSPEC" ("INVOICEDATE", "INVOICENUMBER", "LINENUMBER", "INVOICELINETYPE", "INVOICELINETYPEDESC", "CODE", "TAXCODE", "DESCRIPTION", "ADJUSTEDAMOUNT", "ADJUSTEDPRICE", "ADJUSTMENTBILLEDQTY", "EXTEND", "AMOUNT", "DISCOUNTPERCENTAGE", "PRICE", "BILLEDQTY", "TAXGROUPCODE", "TAXTYPE", "SUBJECTTOMINIMUM", "TURNOVERGROUPCODE", "TURNOVERGROUPDESCRIPTION", "INVOICELINESUBTYPE", "PRODUCTGROUPCODE", "PRODUCTGROUPDESCRIPTION", "PRODUCTSHORTDESCRIPTION", "SHORTDESCRIPTION", "SIZECODE", "SIZEDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "INVOICEQTYCOLUMN", "INVENTORYQTY", "DELIVEREDQTY", "ABUSEDQUANTITY", "SOILQUANTITY", "SOILCOUNTMETHOD", "BILLINGMETHOD", "WEARERNUMBER", "WEARERNAME", "WEARERADMINNR", "WEARERBANK", "WEARERLOCKER", "TRANSACTIONTYPE", "TRANSACTIONDATE", "PERCENTAGE", "SYSTEMUSER_ID", "TIMESTAMP", "INVOICELINE_ID", "REMARK", "LANGUAGECODE", "INVOICEHEADER_ID", "OVERAMOUNT", "COSTCENTER_CODE", "COSTCENTER_DESCRIPTION", "COSTCENTERINVOICELINE_QUANTITY", "COSTCENTERINVOICELINE_AMOUNT", "COSTCENTER_LINK_ID", "REGISTRATIONUNITDESCRIPTION", "SEQUENCENUMBER", "TOTALAMOUNTEXCLVAT", "ACTIVITYCODE", "ACTIVITYDESC", "CCCODE", "CCDESC") AS 
  select f.invoicedate, f.invoicenumber, a.linenumber,
       (select e.type from invoicelinetype e where a.invoicelinetype_id = e.invoicelinetype_id) invoicelinetype,
       (select description
         from   invoicelinetype_desc z
         where  z.invoicelinetype_id = a.invoicelinetype_id
         and    z.language_id = languages.language_id) invoicelinetypedesc, a.code,
       cast(fsget_taxcode(f.invoicenumber, a.linenumber) as varchar2(255)) taxcode, a.description,
       a.adjustedamount, a.adjustedprice, a.adjustmentbilledqty, a.extend, a.amount,
       a.discountpercentage, a.price, a.billedqty, a.taxgroupcode, a.taxtype,
       a.subjecttominimum,
       (select d.code from turnovergroup d where a.turnovergroup_id = d.turnovergroup_id) turnovergroupcode,
       (select description
         from   turnovergroup_desc t
         where  t.turnovergroup_id = a.turnovergroup_id
         and    t.language_id = languages.language_id) turnovergroupdescription,
       a.invoicelinesubtype, b.productgroupcode, b.productgroupdescription,
       b.productshortdescription,
       cast(fsget_code(f.invoicenumber, a.linenumber) as varchar2(255)) shortdescription, b.sizecode,
       b.sizedescription, b.finishingmethodcode, b.finishingmethoddescription, b.invoiceqtycolumn,
       b.inventoryqty, b.deliveredqty, b.abusedquantity, b.soilquantity, b.soilcountmethod,
       b.billingmethod, b.wearernumber, b.wearername, b.weareradminnr, b.wearerbank, b.wearerlocker,
       c.transactiontype, c.transactiondate, c.percentage, a.systemuser_id, a.timestamp,
       a.invoiceline_id, a.remark, languages.code languagecode, a.invoiceheader_id, c.overamount,
       (select cc.code from costcenter_link cc where ccil.costcenter_link_id = cc.costcenter_link_id) costcenter_code,
       (select cc.description
         from   costcenter_link cc
         where  ccil.costcenter_link_id = cc.costcenter_link_id) costcenter_description,
       ccil.quantity costcenterinvoiceline_quantity, ccil.amount costcenterinvoiceline_amount,
       ccil.costcenter_link_id,
       (select pd.registrationunitdescription
         from   product_link_desc pd
         where  pd.product_link_id = b.product_link_id
         and    pd.language_id = languages.language_id) registrationunitdescription,
       (select pilt.sequencenumber
         from   plantinvoicelinetype pilt, businessunit bu, invoiceheader h
         where  a.invoiceheader_id = h.invoiceheader_id
         and    h.invoicebusinessunit_id = bu.businessunit_id
         and    bu.plant_id = pilt.plant_id
         and    pilt.invoicelinetype_id = a.invoicelinetype_id) sequencenumber,
       (select sum(ccilb.amount)
         from   invoiceline ab, costcenterinvoiceline ccilb
         where  ab.invoiceline_id = ccilb.invoiceline_id
         and ccil.costcenter_link_id  = ccilb.costcenter_link_id
         and ab.invoiceheader_id = f.invoiceheader_id
         and ab.invoicelinetype_id = (select e.invoicelinetype_id
                 from invoicelinetype e
                 where e.type <> 18
                       and ab.invoicelinetype_id = e.invoicelinetype_id
                       and ccilb.amount <> 0)
         group  by a.invoiceheader_id, ccil.costcenter_link_id) totalamountexclvat,
(select av.code from activity av where      av.activity_id in (coalesce( (select pg.activity_id  from product p, productgroup pg
                           where  p.productgroup_id=pg.productgroup_id and p.product_id=b.product_link_id )
 ,(select  wg.activity_id  from weighingcategory wg  where wg. weighingcategory_id =b.weighingcategory_link_id)),''))activitycode
,(select av.code from activity av, activity_desc ad where
  av.activity_id in (coalesce( (select pg.activity_id  from product p, productgroup pg
                           where  p.productgroup_id=pg.productgroup_id and p.product_id=b.product_link_id )
     ,(select  wg.activity_id  from weighingcategory wg  where wg. weighingcategory_id =b.weighingcategory_link_id)),'')
and av.activity_id=ad.activity_id and ad.language_id = languages.language_id)activitydesc,
cast( coalesce((f_getcustcostspeccode(b.product_link_id, b.sizedefinition_link_id, b.finishingmethod_id, f.invoicedate, b.weighingcategory_link_id, f.deltocustomer_link_id, a.invoicelinetype_id)),'**') as varchar2(12))cccode,
cast(f_getcustcostspecdesc(b.product_link_id, b.sizedefinition_link_id, b.finishingmethod_id, f.invoicedate, b.weighingcategory_link_id, f.deltocustomer_link_id, a.invoicelinetype_id)as varchar2(40))ccdesc
from invoiceheader f, invoiceline a, costcenterinvoiceline cciL
  left outer join invoicelineproduct b on (ccil.invoiceline_id = b.invoiceline_id)
  left outer join invoicelinevarious c on (ccil.invoiceline_id = c.invoiceline_id)
, languages
where a.invoiceheader_id = f.invoiceheader_id
and f.documenttype = 1
and ccil.invoiceline_id = a.invoiceline_id
/

  CREATE OR REPLACE VIEW "V_COSTREPORTINFO_AUX" ("INVOICELINE_ID", "COSTCENTER_LINK_ID", "YEAR", "WEEK", "QUANTITY", "AMOUNT", "SYSTEMUSER_ID", "YEARWEEK", "TIMESTAMP") AS 
  select
  ci.invoiceline_id, ci.costcenter_link_id, ci.year, ci.week, ci.quantity, ci.amount, ci.systemuser_id,
  ci.year*100+ci.week yearweek,
  ci.timestamp
from
costreportinfo ci
/

  CREATE OR REPLACE VIEW "V_COSTSPERBENCHMARKINVOICE" ("BENCHMARKCODE", "BENCHMARKDESC", "BILLNUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEFAULTBUSINESSUNIT_ID", "MARKETSEGMENTCODE", "PRODUCTCODE", "SIZECODE", "FINISHINGCODE", "PRODUCTDESC", "COSTCENTERCODE", "COSTCENTERDESC", "COSTS", "COSTS_VATINCLUDED", "REPORTPARAM_ID", "LANGUAGECODE") AS 
  select distinct -- selection on WEEK based on costreportinfo CCIF
  bkc.code benchmarkCode, bkc.description benchmarkDesc
, bill.customernumber billNumber, cu.customernumber, cu.name customerName
, cu.defaultbusinessunit_id, marketsegment.code marketsegmentCode
, prd.code productCode, sz.code sizeCode, fm.code finishingCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, cc.code costcenterCode, cc.description costcenterDesc
, sum(ccif.amount) Costs
, sum( ccif.amount * ( 100 + F_TAXRATE(cu.customer_id, prd.product_id, cu.country_id, IH.INVOICEDATE)) / 100 ) Costs_VATINCLUDED
, rp.reportparam_id, languages.code languageCode
from
  customer cu, customer bill, marketsegment, costcenter cc, costreportinfo ccif
, invoiceline il, invoicelineproduct ilp, invoicelinetype ilty, invoiceheader ih
, benchmarkcategory bkc, product prd, sizedefinition sz, finishingmethod fm
, reportparam rp, languages
where
    cu.debtor_id = bill.customer_id
and cu.marketsegment_id = marketsegment.marketsegment_id
and cu.customer_id = cc.customer_id
    and cc.benchmarkcategory_id = bkc.benchmarkcategory_id
    and cc.costcenter_id = ccif.costcenter_link_id
        and ccif.invoiceline_id = ilp.invoiceline_id
            and ilp.product_link_id = prd.product_id
                and prd.benchmarkrelevant = 'Y'
            and ilp.sizedefinition_link_id = sz.sizedefinition_id
            and ilp.finishingmethod_id = fm.finishingmethod_id
        and ccif.invoiceline_id = il.invoiceline_id
            and il.invoicelinetype_id = ilty.invoicelinetype_id
                and ilty.type in (2, 5) -- 2: wash, 5: sales
            and il.invoiceheader_id = ih.invoiceheader_id
            and ih.status_id = (select status_id from status where statustype='IN' and code='2')
and ih.deltocustomer_link_id = cu.customer_id
and ccif.year = rp.number_value1
and
    ( rp.number_value4 = 0 and rp.number_value5 = 0
          and ccif.week between rp.number_value2 and rp.number_value3 )
group by
  bkc.code , bkc.description
, bill.customernumber , cu.customernumber, cu.name
, cu.defaultbusinessunit_id, marketsegment.code
, prd.code , sz.code , fm.code
, prd.product_id, languages.language_id
, cc.code , cc.description
, rp.reportparam_id, languages.code
union
select distinct -- selection on MONTH based on costcenterinvoiceline CCIL
  bkc.code benchmarkCode, bkc.description benchmarkDesc
, bill.customernumber billNumber, cu.customernumber, cu.name customerName
, cu.defaultbusinessunit_id, marketsegment.code marketsegmentCode
, prd.code productCode, sz.code sizeCode, fm.code finishingCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, cc.code costcenterCode, cc.description costcenterDesc
, sum(ccil.amount) Costs
, sum( ccil.amount * ( 100 +  F_TAXRATE(cu.customer_id, prd.product_id, cu.country_id, IH.INVOICEDATE) ) / 100 ) Costs_VATINCLUDED
, rp.reportparam_id, languages.code languageCode
from
  customer cu, customer bill, marketsegment, costcenter cc, costcenterinvoiceline ccil
, invoiceline il, invoicelineproduct ilp, invoicelinetype ilty, invoiceheader ih
, benchmarkcategory bkc, product prd, sizedefinition sz, finishingmethod fm
, reportparam rp, languages
where
    cu.debtor_id = bill.customer_id
and cu.marketsegment_id = marketsegment.marketsegment_id
and cu.customer_id = cc.customer_id
    and cc.benchmarkcategory_id = bkc.benchmarkcategory_id
    and cc.costcenter_id = ccil.costcenter_link_id
        and ccil.invoiceline_id = ilp.invoiceline_id
            and ilp.product_link_id = prd.product_id
                and prd.benchmarkrelevant = 'Y'
            and ilp.sizedefinition_link_id = sz.sizedefinition_id
            and ilp.finishingmethod_id = fm.finishingmethod_id
        and ccil.invoiceline_id = il.invoiceline_id
            and il.invoicelinetype_id = ilty.invoicelinetype_id
                and ilty.type in (2, 5) -- 2: wash, 5: sales
            and il.invoiceheader_id = ih.invoiceheader_id
            and ih.status_id = (select status_id from status where statustype='IN' and code='2')
and ih.deltocustomer_link_id = cu.customer_id
and ih.endyear = rp.number_value1
and
    ( rp.number_value2 = 0 and rp.number_value3 = 0
          and ih.endmonth between rp.number_value4 and rp.number_value5 )
group by
  bkc.code , bkc.description
, bill.customernumber , cu.customernumber, cu.name
, cu.defaultbusinessunit_id, marketsegment.code
, prd.code , sz.code , fm.code
, prd.product_id, languages.language_id
, cc.code , cc.description
, rp.reportparam_id, languages.code
/

  CREATE OR REPLACE VIEW "V_COSTSPERBENCHMARKPRICE" ("BENCHMARKCODE", "BENCHMARKDESC", "BILLNUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEFAULTBUSINESSUNIT_ID", "MARKETSEGMENTCODE", "PRODUCTCODE", "SIZECODE", "FINISHINGCODE", "PRODUCTDESC", "COSTCENTERCODE", "COSTCENTERDESC", "GENERALPRICELIST_ID", "GENERALPRICELISTCODE", "GENERALPRICELISTDESC", "COSTS", "REPORTPARAM_ID", "LANGUAGECODE") AS 
  select distinct -- selection on WEEK based on costreportinfo CCIF
  bkc.code benchmarkCode, bkc.description benchmarkDesc
, bill.customernumber billNumber, cu.customernumber, cu.name customerName
, cu.defaultbusinessunit_id, marketsegment.code marketsegmentCode
, prd.code productCode, sz.code sizeCode, fm.code finishingCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, cc.code costcenterCode, cc.description costcenterDesc
, gpl.generalpricelist_id, gpl.code generalpricelistCode, gpl.description generalpricelistDesc
, sum( ccif.quantity) * F_PRICEWASH_BENCHMARK(gpl.generalpricelist_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, RP.REPORTPARAM_ID, 'W') Costs
, RP.REPORTPARAM_ID, languages.code languageCode
from
  customer cu, customer bill, marketsegment
, costcenter cc
, costreportinfo ccif, invoiceline il, invoicelineproduct ilp, invoicelinetype ilty, invoiceheader ih
, benchmarkcategory bkc
, product prd, sizedefinition sz, finishingmethod fm
, generalpricelist gpl
, reportparam rp, languages
where
    cu.debtor_id = bill.customer_id
and cu.marketsegment_id = marketsegment.marketsegment_id
and cu.customer_id = cc.customer_id
    and cc.benchmarkcategory_id = bkc.benchmarkcategory_id
    and cc.costcenter_id = ccif.costcenter_link_id
        and ccif.invoiceline_id = ilp.invoiceline_id
            and ilp.product_link_id = prd.product_id
                and prd.benchmarkrelevant = 'Y'
            and ilp.sizedefinition_link_id = sz.sizedefinition_id
            and ilp.finishingmethod_id = fm.finishingmethod_id
        and ccif.invoiceline_id = il.invoiceline_id
            and il.invoicelinetype_id = ilty.invoicelinetype_id
                and ilty.type in (2, 5) -- 2: wash, 5: sales
            and il.invoiceheader_id = ih.invoiceheader_id
            and ih.status_id = (select status_id from status where statustype='IN' and code='2')
and ih.deltocustomer_link_id = cu.customer_id
and ccif.year = rp.number_value1
and
    ( rp.number_value4 = 0 and rp.number_value5 = 0
          and ccif.week between rp.number_value2 and rp.number_value3 )
and gpl.pricetype = 1 -- wash
group by
  bkc.code, bkc.description
, bill.customernumber, cu.customernumber, cu.name, gpl.generalpricelist_id, gpl.code, gpl.description
, cu.defaultbusinessunit_id, marketsegment.code
, prd.code, sz.code, fm.code
, prd.product_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, languages.language_id
, cc.code, cc.description
, RP.REPORTPARAM_ID, languages.code
union
select distinct -- selection on MONTH based on costcenterinvoiceline CCIL
  bkc.code benchmarkCode, bkc.description benchmarkDesc
, bill.customernumber billNumber, cu.customernumber, cu.name customerName
, cu.defaultbusinessunit_id, marketsegment.code marketsegmentCode
, prd.code productCode, sz.code sizeCode, fm.code finishingCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, cc.code costcenterCode, cc.description costcenterDesc
, gpl.generalpricelist_id, gpl.code generalpricelistCode, gpl.description generalpricelistDesc
, sum(ccil.quantity) * F_PRICEWASH_BENCHMARK(gpl.generalpricelist_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, RP.REPORTPARAM_ID, 'M') Costs
, RP.REPORTPARAM_ID, languages.code languageCode
from
  customer cu, customer bill, marketsegment
, costcenter cc
, costcenterinvoiceline ccil, invoiceline il, invoicelineproduct ilp, invoicelinetype ilty, invoiceheader ih
, benchmarkcategory bkc, product prd, sizedefinition sz, finishingmethod fm
, generalpricelist gpl
, reportparam rp, languages
where
    cu.debtor_id = bill.customer_id
and cu.marketsegment_id = marketsegment.marketsegment_id
and cu.customer_id = cc.customer_id
    and cc.benchmarkcategory_id = bkc.benchmarkcategory_id
    and cc.costcenter_id = ccil.costcenter_link_id
        and ccil.invoiceline_id = ilp.invoiceline_id
            and ilp.product_link_id = prd.product_id
                and prd.benchmarkrelevant = 'Y'
            and ilp.sizedefinition_link_id = sz.sizedefinition_id
            and ilp.finishingmethod_id = fm.finishingmethod_id
        and ccil.invoiceline_id = il.invoiceline_id
            and il.invoicelinetype_id = ilty.invoicelinetype_id
                and ilty.type in (2, 5) -- 2: wash, 5: sales
            and il.invoiceheader_id = ih.invoiceheader_id
            and ih.status_id = (select status_id from status where statustype='IN' and code='2')
and ih.deltocustomer_link_id = cu.customer_id
and ih.endyear = rp.number_value1
and
    ( rp.number_value2 = 0 and rp.number_value3 = 0
          and ih.endmonth between rp.number_value4 and rp.number_value5 )
and gpl.pricetype = 1 -- wash
group by
  bkc.code, bkc.description
, bill.customernumber, cu.customernumber, cu.name, gpl.generalpricelist_id, gpl.code, gpl.description
, cu.defaultbusinessunit_id, marketsegment.code
, prd.code, sz.code, fm.code
, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, languages.language_id
, cc.code, cc.description
, RP.REPORTPARAM_ID, languages.code
/

  CREATE OR REPLACE VIEW "V_COSTSPERPATIENTDAY" ("DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "STREET", "ZIPCODE", "CITY", "ENDMONTH", "ENDYEAR", "YEARMONTH", "COSTCENTERCODE", "COSTCENTERDESC", "PRODUCTCODE", "SIZECODE", "SIZEDESCRIPTION", "FINISHINGMETHODCODE", "PRODUCTDESC", "QUANTITY", "AMOUNT", "PATIENTDAYS", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE") AS 
  select
  ih.deltocustomernumber , ih.deltocustomername
, cast(CONCATENATEWITHBLANK(ih.street, ih.street2) as varchar2(255)) street, ih.zipcode, ih.city
, ih.endmonth, ih.endyear
, ( ih.endyear * 100 + ih.endmonth ) YEARMONTH
, cc.code CostcenterCode, cc.description CostcenterDesc
, prd.code ProductCode, ilp.sizecode, ilp.sizedescription, ilp.finishingmethodcode
, ( select product_link_desc.description from product_link_desc where product_link_desc.product_link_id = prd.product_id
  and product_link_desc.language_id = languages.language_id ) ProductDesc
, ( case
        when ilty.type in (2, 5)
             then ccil.quantity
                  else 0 end ) quantity
, ccil.amount
, coalesce(( select sum(pa.patientdays) from distributionpoint, patientday pa -------- NOT IN patientdays TABLE
           where cc.costcenter_id = distributionpoint.costcenter_id
                 and distributionpoint.distributionpoint_id = pa.distributionpoint_link_id
                     and ih.endyear = pa.year
                         and ih.endmonth = pa.month ), 0) patientdays
, currency.invoiceamountdecimals
, languages.code languageCode
from
  invoiceheader ih, invoiceline il, invoicelinetype ilty, invoicefrequency ifq
, invoicelineproduct ilp, product prd
, costcenterinvoiceline ccil, costcenter cc
, currency, languages
where
    ih.documenttype = 1   -- invoice
and ih.invoicetype in (1,3)  -- generated, credit
and ih.invoicefrequency_id = ifq.invoicefrequency_id
    and ifq.invoicefrequencynumber = 110   -- monthly
and ih.invoiceheader_id = il.invoiceheader_id
    and il.invoicelinetype_id = ilty.invoicelinetype_id
        and ilty.type in (1,2,5)  -- rent, wash, sales
and il.invoiceline_id = ilp.invoiceline_id
    and ilp.product_link_id = prd.product_id
and il.invoiceline_id = ccil.invoiceline_id
    and ccil.costcenter_link_id = cc.costcenter_id
and ih.currency_id = currency.currency_id
/

  CREATE OR REPLACE VIEW "V_COSTS_SPECS_PER_WEARER" ("INVOICEBUSINESSUNIT_ID", "STATUSQUODATE", "STATUSQUOTYPE", "TOTALQUANTITY", "YEAR", "WEEK", "MONTH", "CHANGESPERWEEK", "NUMBEREMPLOYMENTSCHARGE", "NUMBEREMPLOYMENTSFREE", "MAXINV", "TOTALCIRCINV", "FREECIRCINV", "FREEMAXINV", "NUMBEREMPLCUSTRENTSTOP", "NUMBEREMPLOYMENTSRENTSTOP", "VARIATIONEMPLOYMENTSCHARGE", "VARIATIONEMPLOYMENTSFREE", "VARIATIONMAXINV", "VARIATIONFREEMAXINV", "VARIATIONFREECIRCINV", "VARIATIONTOTALCIRCINV", "VARIATIONEMPLCUSTRENTSTOP", "VARIATIONEMPLOYMENTSRENTSTOP", "CUSTOMER_ID", "CUSTOMERNUMBER", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "COSTCENTER_ID", "DISTRIBUTIONPOINT_ID", "DISTRIBUTIONPOINTNUMBER", "WEAREREMPLSEQ", "LOCKER", "BANK", "WEARERNUMBER", "WEARERNAME", "WEARERSEARCHNAME", "WEARERFIRSTNAME", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTDESC", "SIZEDEFINITION_ID", "SIZECODE", "SIZEDESC", "FINISHINGMETHOD_ID", "FINISHINGMETHODCODE", "LANGUAGECODE", "COSTCENTERCODE", "COSTCENTERDESC") AS 
  select sh.invoicebusinessunit_id, sh.statusquodate, sh.statusquotype, sh.totalquantity,
       sh.year, sh.week, sh.month,
       si.changesperweek, si.numberemploymentscharge, si.numberemploymentsfree,
       si.maxinv, si.totalcircinv, si.freecircinv, si.freemaxinv, si.numberemplcustrentstop, si.numberemploymentsrentstop,
       si.variationemploymentscharge, si.variationemploymentsfree, si.variationmaxinv,
       si.variationfreemaxinv, si.variationfreecircinv, si.variationtotalcircinv,
       si.variationemplcustrentstop, si.variationemploymentsrentstop,
       c.customer_id, c.customernumber,
       d.department_id, d.departmentnumber, d.description departmentDesc, d.costcenter_id,
       dp.distributionpoint_id, dp.distributionpointnumber,
       we.sequencenumber wearerEmplSeq, lo.locker, lo.bank,
       w.wearernumber, w.fullname wearerName, w.searchname wearerSearchName, w.firstname wearerFirstName,
       p.product_id, p.code productCode,
       (select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = l.language_id) productDesc,
       s.sizedefinition_id, s.code sizeCode,
       (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = s.sizedefinition_id and sdd.language_id = l.language_id) SizeDesc,
       f.finishingmethod_id, f.code finishingMethodCode,
       l.code languageCode,
       cc.code CostcenterCode, cc.description CostcenterDesc
from sqsetincirculation si
     inner join statusquoheader sh on si.statusquoheader_id = sh.statusquoheader_id
     inner join weareremployment we
           left outer join locker lo on we.locker_id = lo.locker_id
           inner join wearer w on we.wearer_id = w.wearer_id
     on si.weareremployment_link_id = we.weareremployment_id
     inner join product p on si.product_link_id = p.product_id
     inner join sizedefinition s on si.sizedefinition_link_id = s.sizedefinition_id
     inner join finishingmethod f on si.finishingmethod_id = f.finishingmethod_id
     inner join distributionpoint dp on si.distributionpoint_link_id = dp.distributionpoint_id
     inner join department d
           inner join Costcenter cc on d.costcenter_id = cc.costcenter_id
     on si.department_link_id = d.department_id
     inner join customer c on si.customer_link_id = c.customer_id,
     LANGUAGES L
where sh.statusquotype = 2 --ONLY SETS
      and si.numberemploymentscharge > 0
      and w.customer_id = c.customer_id
      and we.distributionpoint_id = dp.distributionpoint_id
/

  CREATE OR REPLACE VIEW "V_COSTS_SPECS_PER_WEARER_EXTRA" ("LINETYPE", "INVLINETYPE_DESC", "INVOICEHEADER_ID", "CHANGESPERWEEK", "INVLINEPRICE", "CUSTOMER_ID", "CUSTOMERNUMBER", "WEARERNUMBER", "WEARERNAME", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTDESC", "LANGUAGECODE", "INVOICELINETYPE_ID", "INVOICEBUSINESSUNIT_ID", "ENDWEEK", "ENDYEAR", "INVOICEDATE", "INVOICENUMBER", "PURCHASEORDER", "STARTDATE", "ENDDATE", "BILLTOCUSTOMER_LINK_ID", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "DELTOCUSTOMER_LINK_ID", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "STREET", "STREET2", "CITY", "STATE", "ZIPCODE", "DELTOSTREET", "DELTOSTREET2", "DELTOCITY", "DELTOSTATE", "DELTOZIPCODE", "PLANT_ID", "PLANTCODE", "PLANTNAME", "PLANTPHONENO", "PLANTFAX", "PLANTSTREET", "PLANTSTREET2", "PLANTCITY", "PLANTSTATE", "PLANTZIPCODE") AS 
  select /*+parallel*/ x.linetype, x.invlinetype_desc, x.invoiceheader_id, x.changesperweek, x.invLinePRICE, x.customer_id, x.customernumber, x.wearernumber, x.wearerName,
       x.product_id, x.productCode, x.productDesc, x.languageCode, x.invoicelinetype_id , x.invoicebusinessunit_id, x.endweek, x.endyear, x.invoicedate, x.invoicenumber, x.purchaseorder, x.startdate, x.enddate,
       x.billtocustomer_link_id, x.billtocustomernumber, x.billtocustomername, x.deltocustomer_link_id, x.deltocustomernumber, x.deltocustomername,
       x.street, x.street2, x.city, x.state, x.zipcode, x.deltostreet, x.deltostreet2, x.deltocity, x.deltostate, x.deltozipcode,
       x.plant_id, x.plantCode, x.plantName, x.plantPhoneNo, x.plantFax, x.plantStreet, x.plantStreet2, x.plantCity, x.plantState, x.plantZipcode
from
(select -- RENT - SETS - ILP Wearer Emp = SQ Wearer Emp + NULL ILP Wearer Emp
      1 linetype, ih.invoiceheader_id,
      (select iltd.description from invoicelinetype_desc iltd where iltd.invoicelinetype_id = 1 and iltd.language_id = l.language_id) invlinetype_desc,
      sum(si.maxinv) changesperweek,
      max(il.price * (100 - il.discountpercentage)/100) invLinePRICE,
      c.customer_id, c.customernumber,
      we.wearernumber,  we.wearername wearerName,
      p.product_id, p.code productCode,
      (select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = l.language_id) productDesc,
       l.code languageCode,
       il.invoicelinetype_id --rent line
      , ih.invoicebusinessunit_id, ih.endweek, ih.endyear,
       ih.invoicedate, ih.invoicenumber, ih.purchaseorder, ih.startdate, ih.enddate,
       ih.billtocustomer_link_id, ih.billtocustomernumber, ih.billtocustomername,
       ih.deltocustomer_link_id, ih.deltocustomernumber, ih.deltocustomername,
       ih.street, ih.street2, ih.city, ih.state, ih.zipcode,
       ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltostate, ih.deltozipcode,
       pla.plant_id, pla.code plantCode, pla.name plantName, pla.phoneno plantPhoneNo, pla.faxno plantFax,
       pa.street plantStreet, pa.street2 plantStreet2, pa.city plantCity, pa.state plantState, pa.zipcode plantZipcode
 from sqsetincirculation si
      inner join statusquoheader sh on si.statusquoheader_id = sh.statusquoheader_id
      inner join weareremployment_link we on si.weareremployment_link_id = we.weareremployment_link_id
      inner join customer c on si.customer_link_id = c.customer_id
      inner join product p on si.product_link_id = p.product_id
      inner join invoicelineproduct ilp
            inner join invoiceline il
                  inner join invoiceheader ih
                        inner join businessunit ibu
                              inner join plant pla
                                    inner join address pa on pla.address_id = pa.address_id
                              on ibu.plant_id = pla.plant_id
                        on ih.invoicebusinessunit_id = ibu.businessunit_id
                  on il.invoiceheader_id = ih.invoiceheader_id
            on ilp.invoiceline_id = il.invoiceline_id
      on si.product_link_id = ilp.product_link_id and si.finishingmethod_id = ilp.finishingmethod_id
         and (si.sizedefinition_link_id = ilp.sizedefinition_link_id or ilp.sizedefinition_link_id =
                                          (select sd.sizedefinition_id from sizedefinition sd where sd.code = '*'))
      , LANGUAGES L
 where sh.statusquotype = 2 --ONLY SETS      and si.numberemploymentscharge > 0 -- commented for CBD/PAV
       and coalesce(ilp.weareremployment_link_id, si.weareremployment_link_id) = we.WEAREREMPLOYMENT_LINK_ID
       and il.invoicelinetype_id = 1--rent
       and ilp.billingmethod in (1, 3)
       and ih.deltocustomer_link_id = c.customer_id
       and we.distributionpoint_link_id = si.distributionpoint_link_id
       and exists (select 1 from costreportinfo cri where cri.invoiceline_id = il.invoiceline_id
                                   and cri.year || lpad(cri.week,2,'0') = sh.year || lpad(sh.week,2,'0'))
      group by ih.invoiceheader_id,il.invoicelinetype_id, c.customer_id,c.customernumber,we.wearernumber,we.wearername,p.product_id, p.code,l.language_id,l.code,
       ih.invoicebusinessunit_id, ih.endweek, ih.endyear, ih.invoicedate, ih.invoicenumber, ih.purchaseorder, ih.startdate, ih.enddate, ih.billtocustomer_link_id, ih.billtocustomernumber, ih.billtocustomername,
       ih.deltocustomer_link_id, ih.deltocustomernumber, ih.deltocustomername, ih.street, ih.street2, ih.city, ih.state, ih.zipcode, ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltostate, ih.deltozipcode,
       pla.plant_id, pla.code, pla.name, pla.phoneno, pla.faxno, pa.street, pa.street2, pa.city , pa.state, pa.zipcode
 union all   --RENT - ITEMS - ILP Wearer Emp = SQ Wearer Employment +  NULL ILP Wearer Employment
 select 2 linetype, ih.invoiceheader_id,
        (select iltd.description from invoicelinetype_desc iltd where iltd.invoicelinetype_id = 1 and iltd.language_id = l.language_id) invlinetype_desc,
        sum(case when (select max(plpc.inventorybillingtype)
                 from productlistpercustomer plpc where plpc.customer_id = c.customer_id and plpc.product_id = p.product_id
                 and plpc.sizedefinition_id = case when si.sizedefinition_link_id = plpc.sizedefinition_id
                                         then si.sizedefinition_link_id
                                         else (select sd.sizedefinition_id from sizedefinition sd where sd.code = '*')
                                         end
                 and plpc.finishingmethod_id = si.finishingmethod_id
                 and plpc.dateactive <= ih.invoicedate and plpc.dateinactive >= ih.invoicedate ) = 1 --Show REAL INV
            then si.QtyRentedPerPiece
            else si.maxinv end) changesperweek,
        max(il.price * (100 - il.discountpercentage)/100) invLinePRICE,
        c.customer_id, c.customernumber,
        we.wearernumber,  we.wearername wearerName,
        p.product_id, p.code productCode,
       (select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = l.language_id) productDesc,
       l.code languageCode,
       1 invoicelinetype_id
      , ih.invoicebusinessunit_id, ih.endweek, ih.endyear,
       ih.invoicedate, ih.invoicenumber, ih.purchaseorder, ih.startdate, ih.enddate,
       ih.billtocustomer_link_id, ih.billtocustomernumber, ih.billtocustomername,
       ih.deltocustomer_link_id, ih.deltocustomernumber, ih.deltocustomername,
       ih.street, ih.street2, ih.city, ih.state, ih.zipcode,
       ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltostate, ih.deltozipcode,
       pla.plant_id, pla.code plantCode, pla.name plantName, pla.phoneno plantPhoneNo, pla.faxno plantFax,
       pa.street plantStreet, pa.street2 plantStreet2, pa.city plantCity, pa.state plantState, pa.zipcode plantZipcode
 from sqitemincirculation si
      inner join statusquoheader sh on si.statusquoheader_id = sh.statusquoheader_id
      inner join weareremployment_link we on si.weareremployment_link_id = we.weareremployment_link_id
      inner join customer c on si.customer_link_id = c.customer_id
      inner join product p on si.product_link_id = p.product_id
      inner join invoicelineproduct ilp
            inner join invoiceline il
                  inner join invoiceheader ih
                        inner join businessunit ibu
                              inner join plant pla
                                    inner join address pa on pla.address_id = pa.address_id
                              on ibu.plant_id = pla.plant_id
                        on ih.invoicebusinessunit_id = ibu.businessunit_id
                  on il.invoiceheader_id = ih.invoiceheader_id
            on ilp.invoiceline_id = il.invoiceline_id
      on si.product_link_id = ilp.product_link_id and si.finishingmethod_id = ilp.finishingmethod_id
         and (si.sizedefinition_link_id = ilp.sizedefinition_link_id or ilp.sizedefinition_link_id =
                                          (select sd.sizedefinition_id from sizedefinition sd where sd.code = '*'))
      , LANGUAGES L
 where sh.statusquotype = 1 --Items In Circ      and si.numberemploymentscharge > 0 -- commented for CBD/PAV
       and coalesce(ilp.weareremployment_link_id, si.weareremployment_link_id) = we.WEAREREMPLOYMENT_LINK_ID
       and il.invoicelinetype_id = 1 --rent
       and ilp.billingmethod in (1, 3)
       and ih.deltocustomer_link_id = c.customer_id
       and we.distributionpoint_link_id = si.distributionpoint_link_id
       and exists (select 1 from costreportinfo cri where cri.invoiceline_id = il.invoiceline_id
                                   and cri.year || lpad(cri.week,2,'0') = sh.year || lpad(sh.week,2,'0'))
 group by ih.invoiceheader_id,il.invoicelinetype_id, c.customer_id,c.customernumber,we.wearernumber,we.wearername,p.product_id, p.code,l.language_id,l.code,
       ih.invoicebusinessunit_id, ih.endweek, ih.endyear, ih.invoicedate, ih.invoicenumber, ih.purchaseorder, ih.startdate, ih.enddate, ih.billtocustomer_link_id, ih.billtocustomernumber, ih.billtocustomername,
       ih.deltocustomer_link_id, ih.deltocustomernumber, ih.deltocustomername, ih.street, ih.street2, ih.city, ih.state, ih.zipcode, ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltostate, ih.deltozipcode,
       pla.plant_id, pla.code, pla.name, pla.phoneno, pla.faxno, pa.street, pa.street2, pa.city , pa.state, pa.zipcode
 union all -- WASH - ILP Wearer Emp = SQ Wearer Emp + NULL ILP Wearer Emp
 select 3 linetype, ih.invoiceheader_id,
        (select iltd.description from invoicelinetype_desc iltd where iltd.invoicelinetype_id = 2 and iltd.language_id = l.language_id) invlinetype_desc,
        count(ds.uniqueitem_link_id) changesperweek,
        PACK_PRICE.Wash_Price(c.customer_id, p.product_id, ds.sizedefinition_link_id, ds.finishingmethod_id, pn.deliverydate) invLinePRICE,
        c.customer_id, c.customernumber,
        we.wearernumber, we.wearername wearerName,
        p.product_id, p.code productCode,
        (select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = l.language_id) productDesc,
               l.code languageCode,
        2 invoicelinetype_id
      , ih.invoicebusinessunit_id, ih.endweek, ih.endyear,
       ih.invoicedate, ih.invoicenumber, ih.purchaseorder, ih.startdate, ih.enddate,
       ih.billtocustomer_link_id, ih.billtocustomernumber, ih.billtocustomername,
       ih.deltocustomer_link_id, ih.deltocustomernumber, ih.deltocustomername,
       ih.street, ih.street2, ih.city, ih.state, ih.zipcode,
       ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltostate, ih.deltozipcode,
       pla.plant_id, pla.code plantCode, pla.name plantName, pla.phoneno plantPhoneNo, pla.faxno plantFax,
       pa.street plantStreet, pa.street2 plantStreet2, pa.city plantCity, pa.state plantState, pa.zipcode plantZipcode
 from deliveryscan ds
      inner join weareremployment_link we on ds.weareremployment_link_id = we.weareremployment_link_id and ds.distributionpoint_link_id = we.distributionpoint_link_id
      inner join customer c on ds.customer_link_id = c.customer_id
      inner join packingnote pn
            inner join packingnoteline pnl
                  inner join invoiceheader ih
                        inner join businessunit ibu
                              inner join plant pla
                                    inner join address pa on pla.address_id = pa.address_id
                              on ibu.plant_id = pla.plant_id
                        on ih.invoicebusinessunit_id = ibu.businessunit_id
                  on pnl.invoiceheader_id = ih.invoiceheader_id
            on pn.packingnote_id = pnl.packingnote_id
      on ds.packingnote_id = pn.packingnote_id
      inner join product p on ds.product_link_id = p.product_id
      , LANGUAGES L
 where ds.chargewashing = 'Y' and ds.outscannodelivery in (0,2)
       --and il.invoicelinetype_id = 2 --Delivery (wash)
       and ih.deltocustomer_link_id = c.customer_id
       and pnl.product_id = p.product_id and pnl.sizedefinition_id = ds.sizedefinition_link_id and pnl.finishingmethod_id = ds.finishingmethod_id
 group by ih.invoiceheader_id, c.customer_id, c.customernumber,we.wearernumber, we.wearername, p.product_id, p.code, l.language_id, l.code,
       ih.invoicebusinessunit_id, ih.endweek, ih.endyear, ih.invoicedate, ih.invoicenumber, ih.purchaseorder, ih.startdate, ih.enddate, ih.billtocustomer_link_id, ih.billtocustomernumber, ih.billtocustomername,
       ih.deltocustomer_link_id, ih.deltocustomernumber, ih.deltocustomername, ih.street, ih.street2, ih.city, ih.state, ih.zipcode, ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltostate, ih.deltozipcode,
       pla.plant_id, pla.code, pla.name, pla.phoneno, pla.faxno, pa.street, pa.street2, pa.city, pa.state, pa.zipcode,
       PACK_PRICE.Wash_Price(c.customer_id, p.product_id, ds.sizedefinition_link_id, ds.finishingmethod_id, pn.deliverydate)
 union all -- REPAIR
 select 4 linetype, ih.invoiceheader_id,
      (select rtd.description from repairtype_desc rtd where rh.repairtype_id = rtd.repairtype_id and rtd.language_id = l.language_id) invlinetype_desc,
      sum(rh.quantity) changesperweek,
      coalesce(rh.unitprice, 0) invLinePRICE,
      c.customer_id, c.customernumber,
      we.wearernumber,  we.wearername wearerName,
      p.product_id, p.code productCode,
      (select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = l.language_id) productDesc,
      l.code languageCode,
      6 invoicelinetype_id--repair charges
      , ih.invoicebusinessunit_id, ih.endweek, ih.endyear,
       ih.invoicedate, ih.invoicenumber, ih.purchaseorder, ih.startdate, ih.enddate,
       ih.billtocustomer_link_id, ih.billtocustomernumber, ih.billtocustomername,
       ih.deltocustomer_link_id, ih.deltocustomernumber, ih.deltocustomername,
       ih.street, ih.street2, ih.city, ih.state, ih.zipcode,
       ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltostate, ih.deltozipcode,
       pla.plant_id, pla.code plantCode, pla.name plantName, pla.phoneno plantPhoneNo, pla.faxno plantFax,
       pa.street plantStreet, pa.street2 plantStreet2, pa.city plantCity, pa.state plantState, pa.zipcode plantZipcode
 from invoiceheader ih
      inner join repairhistory rh
           left outer join weareremployment_link we on rh.weareremployment_link_id = we.weareremployment_link_id
           left outer join product p on rh.product_link_id = p.product_id
      on rh.invoiceheader_id = ih.invoiceheader_id
      inner join customer c on ih.deltocustomer_link_id = c.customer_id
      inner join businessunit ibu
            inner join plant pla
                  inner join address pa on pla.address_id = pa.address_id
            on ibu.plant_id = pla.plant_id
      on ih.invoicebusinessunit_id = ibu.businessunit_id
 , LANGUAGES L
 where rh.status = 0
       and coalesce(we.distributionpoint_link_id, rh.distributionpoint_link_id) = rh.distributionpoint_link_id
 group by ih.invoiceheader_id, rh.repairtype_id, c.customer_id,c.customernumber,we.wearernumber,we.wearername,p.product_id, p.code,l.language_id,l.code,
       ih.invoicebusinessunit_id, ih.endweek, ih.endyear, ih.invoicedate, ih.invoicenumber, ih.purchaseorder, ih.startdate, ih.enddate, ih.billtocustomer_link_id, ih.billtocustomernumber, ih.billtocustomername,
       ih.deltocustomer_link_id, ih.deltocustomernumber, ih.deltocustomername, ih.street, ih.street2, ih.city, ih.state, ih.zipcode, ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltostate, ih.deltozipcode,
       pla.plant_id, pla.code, pla.name, pla.phoneno, pla.faxno, pa.street, pa.street2, pa.city , pa.state, pa.zipcode,
       rh.unitprice
 union all -- SPECIAL CHARGES
 select 5 linetype, ih.invoiceheader_id,
      il.description invlinetype_desc,
      sum(il.billedqty) changesperweek,
      case when (il.price * (100 - il.discountpercentage)/100) = 0
           then case when il.billedqty = 0 then 0 else il.amount / il.billedqty end
      else (il.price * (100 - il.discountpercentage)/100) end invLinePRICE,
      c.customer_id, c.customernumber,
      we.wearernumber,  we.wearername wearerName,
      p.product_id, p.code productCode,
      (select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = l.language_id) productDesc,
      l.code languageCode,
      il.invoicelinetype_id --special charges
      , ih.invoicebusinessunit_id, ih.endweek, ih.endyear,
       ih.invoicedate, ih.invoicenumber, ih.purchaseorder, ih.startdate, ih.enddate,
       ih.billtocustomer_link_id, ih.billtocustomernumber, ih.billtocustomername,
       ih.deltocustomer_link_id, ih.deltocustomernumber, ih.deltocustomername,
       ih.street, ih.street2, ih.city, ih.state, ih.zipcode,
       ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltostate, ih.deltozipcode,
       pla.plant_id, pla.code plantCode, pla.name plantName, pla.phoneno plantPhoneNo, pla.faxno plantFax,
       pa.street plantStreet, pa.street2 plantStreet2, pa.city plantCity, pa.state plantState, pa.zipcode plantZipcode
 from invoiceheader ih
      inner join invoiceline il
            left outer join invoicelineproduct ilp
                  left outer join product p on ilp.product_link_id = p.product_id
                  left outer join weareremployment_link we on ilp.weareremployment_link_id = we.WEAREREMPLOYMENT_LINK_ID
            on ilp.invoiceline_id = il.invoiceline_id
      on ih.invoiceheader_id = il.invoiceheader_id
      inner join customer c on ih.deltocustomer_link_id = c.customer_id
      inner join businessunit ibu
            inner join plant pla
                  inner join address pa on pla.address_id = pa.address_id
            on ibu.plant_id = pla.plant_id
      on ih.invoicebusinessunit_id = ibu.businessunit_id
      , LANGUAGES L
 where il.invoicelinetype_id in (16)--Special Charges
 group by ih.invoiceheader_id,il.invoicelinetype_id, c.customer_id,c.customernumber,we.wearernumber,we.wearername,p.product_id, p.code,l.language_id,l.code,
       ih.invoicebusinessunit_id, ih.endweek, ih.endyear, ih.invoicedate, ih.invoicenumber, ih.purchaseorder, ih.startdate, ih.enddate, ih.billtocustomer_link_id, ih.billtocustomernumber, ih.billtocustomername,
       ih.deltocustomer_link_id, ih.deltocustomernumber, ih.deltocustomername, ih.street, ih.street2, ih.city, ih.state, ih.zipcode, ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltostate, ih.deltozipcode,
       pla.plant_id, pla.code, pla.name, pla.phoneno, pla.faxno, pa.street, pa.street2, pa.city , pa.state, pa.zipcode,
       case when (il.price * (100 - il.discountpercentage)/100) = 0
       then case when il.billedqty = 0 then 0 else il.amount / il.billedqty end
       else (il.price * (100 - il.discountpercentage)/100) end, il.description
) x
/

  CREATE OR REPLACE VIEW "V_COSTS_SPECS_PER_WEARER_INV" ("INVOICEHEADER_ID", "INVOICEBUSINESSUNIT_ID", "ENDWEEK", "ENDYEAR", "INVOICEDATE", "INVOICENUMBER", "PURCHASEORDER", "EXTRANAME1", "EXTRANAME2", "BILLTOCUSTOMER_LINK_ID", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "DELTOCUSTOMER_LINK_ID", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "STREET", "STREET2", "CITY", "STATE", "ZIPCODE", "DELTOSTREET", "DELTOSTREET2", "DELTOCITY", "DELTOSTATE", "DELTOZIPCODE", "BUCODE", "BUDESCRIPTION", "PLANT_ID", "PLANTCODE", "PLANTNAME", "PLANTPHONENO", "PLANTFAX", "PLANTSTREET", "PLANTSTREET2", "PLANTCITY", "PLANTSTATE", "PLANTZIPCODE", "DECIMALSPRICES", "DECIMALSAMOUNT", "CURRENCYCODE", "CURRENCYDESC", "COSTCENTER_ID") AS 
  select distinct h.invoiceheader_id, h.invoicebusinessunit_id, h.endweek, h.endyear,
       h.invoicedate, h.invoicenumber, h.purchaseorder, h.extraname1, h.extraname2,
       h.billtocustomer_link_id, h.billtocustomernumber, h.billtocustomername,
       h.deltocustomer_link_id, h.deltocustomernumber, h.deltocustomername,
       h.street, h.street2, h.city, h.state, h.zipcode,
       h.deltostreet, h.deltostreet2, h.deltocity, h.deltostate, h.deltozipcode,
       bu.code buCode, bu.description buDescription,
       p.plant_id, p.code plantCode, p.name plantName, p.phoneno plantPhoneNo, p.faxno plantFax,
       pa.street plantStreet, pa.street2 plantStreet2, pa.city plantCity, pa.state plantState, pa.zipcode plantZipcode,
       cy.decimals decimalsPrices, cy.invoiceamountdecimals decimalsAmount, cy.code currencyCode, cy.description currencyDesc,
       cc.costcenter_id
from invoiceheader h, invoicefrequency ifr, businessunit bu, plant p, address pa, currency cy
     , costcenter cc, costcenterinvoiceline ccil, invoiceline il
where h.invoicefrequency_id = ifr.invoicefrequency_id
      and h.documenttype = 1 -- ONLY INVOICES
      and ifr.invoicefrequencynumber = 10 -- ONLY WEEKLY INVOICES
      and h.invoicebusinessunit_id = bu.businessunit_id
      and bu.plant_id = p.plant_id
      and p.address_id = pa.address_id
      and h.currency_id = cy.currency_id
      and cc.costcenter_id = ccil.costcenter_link_id and ccil.invoiceline_id = il.invoiceline_id
      and il.invoiceheader_id = h.invoiceheader_id
/

  CREATE OR REPLACE VIEW "V_COSTS_SPECS_PER_WEARER_INVL" ("INVOICEHEADER_ID", "INVLINEPRICE", "PRODUCT_LINK_ID", "FINISHINGMETHOD_ID", "INVOICEQTYCOLUMN") AS 
  select l.invoiceheader_id,
      max(l.price) invLinePRICE,
       ilp.product_link_id, ilp.finishingmethod_id, ilp.invoiceqtycolumn
from invoiceline l, invoicelinetype ilt, invoicelineproduct ilp
where l.invoicelinetype_id = ilt.invoicelinetype_id
      and ilt.type = 1 --ONLY RENT LINES
      and l.invoiceline_id = ilp.invoiceline_id --MUST EXISTS
      and ilp.billingmethod = 1 --ONLY billing Method 1
group by l.invoiceheader_id, ilp.product_link_id, ilp.finishingmethod_id, ilp.invoiceqtycolumn --only one price should show per invHeader, product and finMeth
/

  CREATE OR REPLACE VIEW "V_COUNTRY" ("CODE", "DESCRIPTION", "DEFAULTCURRENCYCODE", "DEFAULTCURRENCYDESC", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  SELECT COUNTRY.CODE, COUNTRY.DESCRIPTION, CURRENCY.CODE, CURRENCY.DESCRIPTION,
COUNTRY.SYSTEMUSER_ID, COUNTRY.TIMESTAMP
       FROM COUNTRY, CURRENCY
       WHERE COUNTRY.DEFAULTCURRENCY_ID = CURRENCY.CURRENCY_ID
/

  CREATE OR REPLACE VIEW "V_CPLLOCATION" ("PRODUCTLISTPERCUSTOMER_ID", "PROCESSBUSINESSUNIT_ID", "LOCATION", "UNIQUELOCATION", "DATEACTIVE", "DATEINACTIVE") AS 
  select distinct plpc.productlistpercustomer_id, ca.processbusinessunit_id, vplpd.location
       , plpc.UniqueLocation--, vplpd.dateactive, vplpd.dateinactive
       , plpc.dateactive, plpc.dateinactive
-- this view is used in PDProductListPerCustomer.java
from productlistpercustomer plpc, sizedefinition sz, product p, productgroup pg, customeractivities ca,
     (
     select sdl.location, plpd.product_id, plpd.sizedefinition_id, plpd.finishingmethod_id, d.customer_id, sdl.dateactive, sdl.dateinactive
     from productlistperdistribpoint plpd, standarddeliveryline sdl,
          distributionpoint dp, department d
     where sdl.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
           and plpd.distributionpoint_id = dp.distributionpoint_id
           and dp.department_id = d.department_id
           and sdl.location is not null
     ) vplpd
where plpc.customer_id = vplpd.customer_id
      and plpc.product_id = vplpd.product_id
      and plpc.sizedefinition_id = sz.sizedefinition_id
      and (plpc.sizedefinition_id = vplpd.sizedefinition_id or sz.code = '*')
      and plpc.finishingmethod_id = vplpd.finishingmethod_id
      and plpc.product_id = p.product_id
      and p.productgroup_id = pg.productgroup_id
      and plpc.customer_id = ca.customer_id
      and ca.activity_id = pg.activity_id
      and ( (vplpd.dateactive >= plpc.dateactive and vplpd.dateactive < plpc.dateinactive)
            OR
            (vplpd.dateinactive >= plpc.dateactive and vplpd.dateinactive < plpc.dateinactive))
/

  CREATE OR REPLACE VIEW "V_CREATEDCUSTOMERS" ("BUSINESSUNIT_CODE", "BUSINESSUNIT_DESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "DATEACTIVE", "NATIONALID_CODE", "CREATEDTIMESTAMP", "CREATEDBYSYSTEMUSER_ID", "CREATION_USER") AS 
  select /*version 1.0*/
       bu.code businessunit_code, bu.description businessunit_desc, cu.customernumber, cu.name customername,
       trunc(cu.dateactive) dateactive, na.code nationalid_code, cu.createdtimestamp, cu.createdbysystemuser_id,
       (select su.username from systemuser su where su.systemuser_id = cu.createdbysystemuser_id) creation_user
from customer cu
     join businessunit bu on cu.defaultbusinessunit_id =  bu.businessunit_id
          left join nationalaccount na on cu.nationalaccount_id = na.nationalaccount_id
order by cu.createdtimestamp desc
/

  CREATE OR REPLACE VIEW "V_CREATEDISMOUNTINGORDER" ("RENTALQTYADJUSTMENT_ID", "PRODUCTLISTPERDISTRIBPOINT_ID", "QUANTITY", "REASONCODE_ID", "DESIREDMOUNTINGDATE", "MOUNTINGORDER_ID", "QUALITYGRADE_ID", "QUANTITYFIRSTDELIVERY", "TOBEMOUNTED", "STARTSERVICE", "DISTRIBUTIONPOINT_ID", "PRODUCT_ID", "SIZEDEFINITION_ID", "FINISHINGMETHOD_ID", "DISTRIBUTIONPOINTNUMBER", "DESCRIPTION", "QUALITYCODE", "SIZECODE", "DELIVERYPOINT_ID", "SALESITEM", "SALESPRICE", "DEPARTMENTNUMBER", "DEPTDESC", "REMARK") AS 
  SELECT
    RQA.RENTALQTYADJUSTMENT_ID,RQA.PRODUCTLISTPERDISTRIBPOINT_ID,-RQA.QUANTITY QUANTITY,RQA.REASONCODE_ID,
    RQA.DESIREDMOUNTINGDATE,RQA.MOUNTINGORDER_ID,RQA.QUALITYGRADE_ID,RQA.QUANTITYFIRSTDELIVERY,
    RQA.TOBEMOUNTED,RQA.STARTSERVICE,
    PLC.DISTRIBUTIONPOINT_ID,PLC.PRODUCT_ID,PLC.SIZEDEFINITION_ID,PLC.FINISHINGMETHOD_ID,
    DP.DISTRIBUTIONPOINTNUMBER, DP.DESCRIPTION, Q.CODE AS QUALITYCODE, S.CODE AS SIZECODE, DP.DELIVERYPOINT_ID,
    RQA.SALESITEM, RQA.SALESPRICE, D.DEPARTMENTNUMBER, D.DESCRIPTION AS DEPTDESC , RQA.REMARK REMARK
FROM RENTALQTYADJUSTMENT RQA, PRODUCTLISTPERDISTRIBPOINT PLC, PRODUCT PR ,DISTRIBUTIONPOINT DP,
     QUALITYGRADE Q, SIZEDEFINITION S, DEPARTMENT D
WHERE PLC.PRODUCTLISTPERDISTRIBPOINT_ID = RQA.PRODUCTLISTPERDISTRIBPOINT_ID
    AND PLC.DISTRIBUTIONPOINT_ID = DP.DISTRIBUTIONPOINT_ID
    AND PR.PRODUCT_ID = PLC.PRODUCT_ID
    AND DP.DEPARTMENT_ID = D.DEPARTMENT_ID
    AND RQA.QUALITYGRADE_ID = Q.QUALITYGRADE_ID
    AND PLC.SIZEDEFINITION_ID = S.SIZEDEFINITION_ID
    AND PR.SHOWONDISMOUNTINGORDER = 'Y'
    AND RQA.QUANTITY < 0
    AND RQA.MOUNTINGORDER_ID IS NULL
    AND RQA.DESIREDMOUNTINGDATE IS NOT NULL
    AND RQA.DESIREDMOUNTINGDATE <> TO_DATE('31/12/2099','DD/MM/YYYY')
/

  CREATE OR REPLACE VIEW "V_CREATEMOUNTINGORDER" ("RENTALQTYADJUSTMENT_ID", "PRODUCTLISTPERDISTRIBPOINT_ID", "QUANTITY", "REASONCODE_ID", "DESIREDMOUNTINGDATE", "MOUNTINGORDER_ID", "QUALITYGRADE_ID", "QUANTITYFIRSTDELIVERY", "TOBEMOUNTED", "STARTSERVICE", "DISTRIBUTIONPOINT_ID", "PRODUCT_ID", "SIZEDEFINITION_ID", "FINISHINGMETHOD_ID", "DISTRIBUTIONPOINTNUMBER", "DESCRIPTION", "QUALITYCODE", "SIZECODE", "DELIVERYPOINT_ID", "SALESITEM", "SALESPRICE", "DEPARTMENTNUMBER", "DEPTDESC", "REMARK") AS 
  SELECT
      RQA.RENTALQTYADJUSTMENT_ID,RQA.PRODUCTLISTPERDISTRIBPOINT_ID,RQA.QUANTITY,RQA.REASONCODE_ID,
      RQA.DESIREDMOUNTINGDATE,RQA.MOUNTINGORDER_ID,RQA.QUALITYGRADE_ID,RQA.QUANTITYFIRSTDELIVERY,
      RQA.TOBEMOUNTED,RQA.STARTSERVICE,
      PLC.DISTRIBUTIONPOINT_ID,PLC.PRODUCT_ID,PLC.SIZEDEFINITION_ID,PLC.FINISHINGMETHOD_ID,
      DP.DISTRIBUTIONPOINTNUMBER, DP.DESCRIPTION, Q.CODE AS QUALITYCODE, S.CODE AS SIZECODE,
      DP.DELIVERYPOINT_ID, RQA.SALESITEM, RQA.SALESPRICE, D.DEPARTMENTNUMBER, D.DESCRIPTION AS DEPTDESC
      , RQA.REMARK REMARK
FROM RENTALQTYADJUSTMENT RQA, PRODUCTLISTPERDISTRIBPOINT PLC, PRODUCT PR ,DISTRIBUTIONPOINT DP,
     QUALITYGRADE Q, SIZEDEFINITION S, DEPARTMENT D
WHERE PLC.PRODUCTLISTPERDISTRIBPOINT_ID = RQA.PRODUCTLISTPERDISTRIBPOINT_ID
      AND PLC.DISTRIBUTIONPOINT_ID = DP.DISTRIBUTIONPOINT_ID
      AND PR.PRODUCT_ID = PLC.PRODUCT_ID
      AND DP.DEPARTMENT_ID = D.DEPARTMENT_ID
      AND RQA.QUALITYGRADE_ID = Q.QUALITYGRADE_ID
      AND PLC.SIZEDEFINITION_ID = S.SIZEDEFINITION_ID
      AND PR.SHOWONMOUNTINGORDER = 'Y'
      AND RQA.QUANTITY >0
      AND RQA.MOUNTINGORDER_ID IS NULL
      AND RQA.DESIREDMOUNTINGDATE IS NOT NULL
      AND RQA.DESIREDMOUNTINGDATE <> TO_DATE('31/12/2099','DD/MM/YYYY')
/

  CREATE OR REPLACE VIEW "V_CREATEPICKLIST" ("WORKORDER_ID", "ORIGIN", "WORKORDERLINE_ID", "STOCKRESERVATIONPERGRADE_ID", "STOCKTYPE", "QUANTITY", "QUALITYGRADE_ID", "STOCKDEFINITIONPERITEM_ID", "STOCKROOM_ID", "PRODUCT_ID", "SIZEDEFINITION_ID", "CUSTOMER_ID", "CUSTOMEROWNED", "WORKORDERPRINTED", "ALLOWPHASEDELIVERY", "PICKLISTPRINTED") AS 
  SELECT WO.WORKORDER_ID, WO.ORIGIN, WOL.WORKORDERLINE_ID, WOLR.STOCKRESERVATIONPERGRADE_ID,
       WOLR.STOCKTYPE, WOLR.QUANTITY, SRG.QUALITYGRADE_ID, SDI.STOCKDEFINITIONPERITEM_ID,
       SDI.STOCKROOM_ID, SDI.PRODUCT_ID, SDI.SIZEDEFINITION_ID, SDI.CUSTOMER_ID, SDI.CUSTOMEROWNED,
       WO.WORKORDERPRINTED, WO.ALLOWPHASEDELIVERY, WO.PICKLISTPRINTED
FROM WORKORDER WO, WORKORDERLINE WOL, WORKORDERLINERESERVATION WOLR,
     STOCKRESERVATIONPERGRADE SRG, STOCKDEFINITIONPERITEM SDI
WHERE WOL.WORKORDER_ID = WO.WORKORDER_ID
AND WOLR.WORKORDERLINE_ID = WOL.WORKORDERLINE_ID
AND SRG.STOCKRESERVATIONPERGRADE_ID = WOLR.STOCKRESERVATIONPERGRADE_ID
AND SDI.STOCKDEFINITIONPERITEM_ID = SRG.STOCKDEFINITIONPERITEM_ID
AND WO.ADDEDTOITEMPICKINGPOOL = 0
ORDER BY STOCKROOM_ID, STOCKRESERVATIONPERGRADE_ID, STOCKTYPE
/

  CREATE OR REPLACE VIEW "V_CREATEPICKLIST_RSC_PNAS" ("NOTENUMBER", "PACKINGNOTE_ID", "ROUTECONTROL_ID", "PACKINGNOTELINE_ID", "CODEUNIQUELY", "QUANTITY", "PRODUCT_ID", "SIZEDEFINITION_ID", "FINISHINGMETHOD_ID", "PRODUCT_CODE", "SIZE_DEFINITION_CODE", "PICKLISTPRINTED") AS 
  select pn.notenumber,
       pn.packingnote_id,
       pn.routecontrol_id,
       pnl.packingnoteline_id,
       plpc.codeuniquely,
       pnl.tobedeliveredamount quantity,
       pnl.product_id,
       pnl.sizedefinition_id,
       pnl.finishingmethod_id,
       pr.code as product_code,
       sd.code as size_definition_code,
       pn.picklistprinted
  from packingnote            pn,
       packingnoteline        pnl,
       product                pr,
       productlistpercustomer plpc,
       sizedefinition         sd,
       routecontrol           rc
 where pnl.packingnote_id = pn.packingnote_id
   and pr.product_id = pnl.product_id
   and rc.routecontrol_id = pn.routecontrol_id
   and sd.sizedefinition_id = pnl.sizedefinition_id
   and plpc.productlistpercustomer_id =
       coalesce((select max(plpc_1.productlistpercustomer_id)
                  from productlistpercustomer plpc_1
                 where plpc_1.customer_id =
                       (select dp.customer_id
                          from deliverypoint dp
                         where dp.deliverypoint_id = pn.deliverypoint_id)
                   and plpc_1.product_id = pnl.product_id
                   and plpc_1.sizedefinition_id = pnl.sizedefinition_id
                   and plpc_1.finishingmethod_id = pnl.finishingmethod_id
                   and plpc_1.dateactive <= rc.drivingdate
                   and plpc_1.dateinactive >= rc.drivingdate),
                (select max(plpc_2.productlistpercustomer_id)
                   from productlistpercustomer plpc_2
                  where plpc_2.customer_id =
                        (select dp.customer_id
                           from deliverypoint dp
                          where dp.deliverypoint_id = pn.deliverypoint_id)
                    and plpc_2.product_id = pnl.product_id
                    and plpc_2.sizedefinition_id =
                        (select sd.sizedefinition_id
                           from sizedefinition sd
                          where sd.code = '*')
                    and plpc_2.finishingmethod_id = pnl.finishingmethod_id
                    and plpc_2.dateactive <= rc.drivingdate
                    and plpc_2.dateinactive >= rc.drivingdate))
   and pr.showonpicklistrsc = 'Y'
   and pr.deliverfromonpicklistrsc = 0 --Active stock
   and pn.routecontrol_id is not null
   and (pn.origin in (0, 1, 2))
   and pn.status_id in (select status_id
                          from status
                         where statustype = 'PN'
                           and code in (10, 20))
   and pn.picklistprinted = 'N'
/

  CREATE OR REPLACE VIEW "V_CREATEPICKLIST_RSC_PNPS" ("NOTENUMBER", "PACKINGNOTE_ID", "ROUTECONTROL_ID", "PACKINGNOTELINE_ID", "PRODUCTLISTPERCUSTOMER_ID", "CODEUNIQUELY", "CUSTOMERRELATED", "QUANTITY", "PRODUCT_ID", "SIZEDEFINITION_ID", "FINISHINGMETHOD_ID", "PRODUCT_CODE", "SIZE_DEFINITION_CODE", "PICKLISTPRINTED") AS 
  select pn.notenumber,
       pn.packingnote_id,
       pn.routecontrol_id,
       pnl.packingnoteline_id,
       plpc.productlistpercustomer_id,
       plpc.codeuniquely,
       plpc.customerrelated,
       pnl.tobedeliveredamount quantity,
       pnl.product_id,
       pnl.sizedefinition_id,
       pnl.finishingmethod_id,
       pr.code as product_code,
       sd.code as size_definition_code,
       pn.picklistprinted
  from packingnote            pn,
       packingnoteline        pnl,
       product                pr,
       productlistpercustomer plpc,
       sizedefinition         sd,
       routecontrol           rc
 where pnl.packingnote_id = pn.packingnote_id
   and pr.product_id = pnl.product_id
   and rc.routecontrol_id = pn.routecontrol_id
   and plpc.productlistpercustomer_id =
       coalesce((select max(plpc_1.productlistpercustomer_id)
                  from productlistpercustomer plpc_1
                 where plpc_1.customer_id =
                       (select dp.customer_id
                          from deliverypoint dp
                         where dp.deliverypoint_id = pn.deliverypoint_id)
                   and plpc_1.product_id = pnl.product_id
                   and plpc_1.sizedefinition_id = pnl.sizedefinition_id
                   and plpc_1.finishingmethod_id = pnl.finishingmethod_id
                   and plpc_1.dateactive <= rc.drivingdate
                   and plpc_1.dateinactive >= rc.drivingdate),
                (select max(plpc_2.productlistpercustomer_id)
                   from productlistpercustomer plpc_2
                  where plpc_2.customer_id =
                        (select dp.customer_id
                           from deliverypoint dp
                          where dp.deliverypoint_id = pn.deliverypoint_id)
                    and plpc_2.product_id = pnl.product_id
                    and plpc_2.sizedefinition_id =
                        (select sd.sizedefinition_id
                           from sizedefinition sd
                          where sd.code = '*')
                    and plpc_2.finishingmethod_id = pnl.finishingmethod_id
                    and plpc_2.dateactive <= rc.drivingdate
                    and plpc_2.dateinactive >= rc.drivingdate))
   and sd.sizedefinition_id = pnl.sizedefinition_id
   and pr.recordpassivestock = 'Y'
   and pr.showonpicklistrsc = 'Y'
   and pr.deliverfromonpicklistrsc = 1 --Passive stock
   and pn.routecontrol_id is not null
   and (pn.origin in (0, 1, 2))
   and pn.status_id in (select status_id
                          from status
                         where statustype = 'PN'
                           and code in (10, 20))
   and pn.picklistprinted = 'N'
/

  CREATE OR REPLACE VIEW "V_CREATEPICKLIST_RSC_WOAS" ("WORKORDERNUMBER", "WORKORDER_ID", "ORIGIN", "ROUTECONTROL_ID", "WORKORDERLINE_ID", "CODEUNIQUELY", "QUANTITY", "REQUESTEDGRADE_ID", "PROCESSINGSTOCKROOM_ID", "PRODUCT_ID", "SIZEDEFINITION_ID", "FINISHINGMETHOD_ID", "PRODUCT_CODE", "SIZE_DEFINITION_CODE") AS 
  select wo.workordernumber, wo.workorder_id, wo.origin, wo.routecontrol_id, wol.workorderline_id,
       wol.codeuniquely, (wol.quantityordered - wol.quantitycancelled) quantity,
       wol.requestedgrade_id, wo.processingstockroom_id, wol.product_link_id product_id,
       wol.sizedefinition_link_id sizedefinition_id, wol.finishingmethod_id,
       pr.code as product_code, sd.code as size_definition_code
from workorder wo, workorderline wol, product pr
, sizedefinition sd
where wol.workorder_id = wo.workorder_id
and pr.product_id = wol.product_link_id
and sd.sizedefinition_id = wol.sizedefinition_link_id
and ((pr.recordpassivestock = 'N')
or ((pr.recordpassivestock = 'Y') and (pr.deliverfromonpicklistrsc_mo = 0)))
and wo.routecontrol_id is not null
and (wo.origin = 10)
and (wo.status_id in (select status_id from status where code = 10 and statustype = 'MO'))
and wo.picklistprinted = 'N'
union all
select wo.workordernumber, wo.workorder_id, wo.origin, wo.routecontrol_id, wol.workorderline_id,
       wol.codeuniquely, (wol.quantityordered - wol.quantitycancelled) quantity,
       wol.requestedgrade_id, wo.processingstockroom_id, wol.product_link_id product_id,
       wol.sizedefinition_link_id sizedefinition_id, wol.finishingmethod_id,
       pr.code  product_code, sd.code  size_definition_code
from workorder wo, workorderline wol, product pr
, sizedefinition sd
where wol.workorder_id = wo.workorder_id
and pr.product_id = wol.product_link_id
and sd.sizedefinition_id = wol.sizedefinition_link_id
and ((pr.recordpassivestock = 'N')
or ((pr.recordpassivestock = 'Y') and (pr.deliverfromonpicklistrsc_sn = 0)))
and wo.routecontrol_id is not null
and (wo.origin = 6 and wo.driversales = 'N' and wo.mountingordersales = 'N' and wo.addedtoitempickingpool = 0)
and (wo.status_id in (select status_id from status where code = 10 and statustype = 'WO'))
and wo.picklistprinted = 'N'
/

  CREATE OR REPLACE VIEW "V_CREATEPICKLIST_RSC_WOPS" ("WORKORDERNUMBER", "WORKORDER_ID", "ORIGIN", "ROUTECONTROL_ID", "WORKORDERLINE_ID", "STOCKRESERVATIONPERGRADE_ID", "STOCKTYPE", "QUANTITY", "QUALITYGRADE_ID", "STOCKDEFINITIONPERITEM_ID", "STOCKROOM_ID", "PRODUCT_ID", "SIZEDEFINITION_ID", "CUSTOMER_ID", "CUSTOMEROWNED", "PRODUCT_CODE", "SIZE_DEFINITION_CODE", "QUALITY_GRADE_CODE", "DELFROMACTIVE", "TRUCKSTOCKROOM_ID") AS 
  select wo.workordernumber, wo.workorder_id, wo.origin, wo.routecontrol_id, wol.workorderline_id,
       wolr.stockreservationpergrade_id,
       wolr.stocktype, wolr.quantity, srg.qualitygrade_id, sdi.stockdefinitionperitem_id,
       sdi.stockroom_id, sdi.product_id, sdi.sizedefinition_id, sdi.customer_id, sdi.customerowned,
       pr.code as product_code, sd.code as size_definition_code
       ,(select qg.code from qualitygrade qg where qg.qualitygrade_id = srg.qualitygrade_id) as quality_grade_code
       ,(case when wol.quantityfirstdelivery>0 then
wol.quantityordered-wol.quantitycancelled-wol.quantityfirstdelivery else 0 end) DelFromActive
,coalesce((select tr.stockroom_id from truck tr, routecontrol rc
                  where wo.routecontrol_id=rc.routecontrol_id
                  and rc.truckcode=tr.code
                  and  tr.plant_id=rc.plant_id), null) Truckstockroom_id
from workorder wo, workorderline wol, workorderlinereservation wolr,
     stockreservationpergrade srg, stockdefinitionperitem sdi
     , product pr, sizedefinition sd
where wol.workorder_id = wo.workorder_id
and wolr.workorderline_id = wol.workorderline_id
and srg.stockreservationpergrade_id = wolr.stockreservationpergrade_id
and sdi.stockdefinitionperitem_id = srg.stockdefinitionperitem_id
and pr.product_id = wol.product_link_id
and sd.sizedefinition_id = wol.sizedefinition_link_id
and (pr.recordpassivestock = 'Y')
and wo.routecontrol_id is not null
and ((wo.origin = 10 and pr.deliverfromonpicklistrsc_mo = 1)
or (wo.origin = 6 and wo.driversales = 'N' and wo.mountingordersales = 'N' and pr.deliverfromonpicklistrsc_sn = 1
and wo.addedtoitempickingpool = 0))
and (wo.status_id in (select status_id from status where code = 10 and (statustype  ='MO' or statustype  ='WO')))
and wo.picklistprinted='N'
/

  CREATE OR REPLACE VIEW "V_CREDITCARDRECEIPT" ("CUSTOMERNUMBER", "CUSTOMERNAME", "STREET", "ZIPCODE", "CITY", "FAXNO", "CREDITCARDTRANSACTION_ID", "INVOICEAMOUNTDECIMALS", "CURRENCYCODE", "REFERENCENUMBER", "REMITIDENTIFICATION", "ARTRANSACTIONDATE", "REMARK", "AMOUNT", "CLOSINGAMOUNT", "ORIGIN", "RESPDATETIME", "AUTHORIZATIONCODE") AS 
  select
  cu.customernumber, cu.name customerName
, coalesce(address.street, debtorAddress.Street) street
, coalesce(address.zipcode, debtorAddress.zipcode) zipcode
, coalesce(address.city, debtorAddress.city) city
, cu.faxno
, cct.creditcardtransaction_id--, cct.transactionid, cct.transactiondate, cct.approvalnumber
--, cct.expirationmonth, cct.expirationyear, cct.creditcardname-, cct.referencenumber cct_ReferenceNumber
--, cct.amount cctAmount
, currencyCU.Invoiceamountdecimals Invoiceamountdecimals
, currencyCU.Code currencyCode
, cast(( case arT.Debitcredit
  when 'D'
    then CASTNUMBERASVARCHAR(arT.Invoicenumber)
    else arT.Remitidentification end ) as varchar2(255)) ReferenceNumber
, arT.Remitidentification
, arT.Artransactiondate, arT.Remark--, art.amount
, (select a.amount from artransaction a where cct.artransaction_id = a.artransaction_id) amount
/*, coalesce( case when cct.origin in (1, 4) then arT.Closingamount
           else art.amount
                end , 0)
           Closingamount*/
, ca.amount Closingamount--arT.Closingamount
--, cct.transactionrefund
, cct.origin
, cct.respdatetime
, cct.authorizationcode
from
  CreditCardTransaction cct
    left outer join invoiceheader ih on cct.invoiceheader_id = ih.invoiceheader_id
, artransaction art
, customer cu
    left outer join address on cu.invoiceaddress_id = address.address_id
, customer debtor
     left outer join address debtorAddress on debtor.invoiceaddress_id = debtorAddress.address_id
, currency currencyCU
, cashapplication ca
where
    art.currency_id = currencyCU.Currency_Id--and cct.artransaction_id = art.artransaction_id
and art.billtocustomer_link_id = cu.customer_id
and cu.debtor_id = debtor.customer_id
--and art.originaltransaction_id in (select ART2.ARTransaction_ID From ARTransaction ART2 where ART2.OriginalTransaction_ID = cct.ARTransaction_ID and ART2.DebitCredit = 'D')
and art.artransaction_id = ca.debitartransaction_id
and ca.creditartransaction_id = cct.artransaction_id and ca.unapplied_yn = 'N'
/

  CREATE OR REPLACE VIEW "V_CSUTOMER_BANK_INFO" ("CUSTOMER_ID", "BANKACCOUNT", "LAUNDRYBANKINSTITUTION_ID", "BANKINSTITUTION_ID", "IBANNO", "CUST_BANK_IDCODE", "CUST_BANK_DESC", "CUST_BANK_INTERNID", "CUST_LNDRYBANKACCOUNT", "CUST_IBANNO", "LNDRY_BANK_IDCODE", "LNDRY_BANK_DESC", "LNDRY_BANK_INTERNID", "LNDRY_BANK_LNDRYBANKACCOUNT", "LNDRY_BANK_IBANNO") AS 
  select cbi.customer_id, cbi.bankaccount, cbi.laundrybankinstitution_id, cbi.bankinstitution_id, cbi.ibanno,
       -->> CUSTOMER RELATED INFO
       cbank.idcode cust_bank_idcode, cbank.description cust_bank_desc, cbank.internalidcode cust_bank_internid,
       cbank.laundrybankaccount cust_lndrybankaccount, cbank.ibanno cust_ibanno,
       -->> LAUNDRY RELATED INFO
       lbank.idcode lndry_bank_idcode, lbank.description lndry_bank_desc, lbank.internalidcode lndry_bank_internid,
       lbank.laundrybankaccount lndry_bank_lndrybankaccount, lbank.ibanno lndry_bank_ibanno
from customerbillinginfo cbi left outer join bankinstitution cbank
                         on cbank.bankinstitution_id = cbi.bankinstitution_id,
     bankinstitution lbank
where  lbank.bankinstitution_id = cbi.laundrybankinstitution_id
union
select cbi.customer_id, cbi.bankaccount, cbi.laundrybankinstitution_id, cbi.bankinstitution_id, cbi.ibanno,
       -->> CUSTOMER RELATED INFO
       cbank.idcode cust_bank_idcode, cbank.description cust_bank_desc, cbank.internalidcode cust_bank_internid,
       cbank.laundrybankaccount cust_lndrybankaccount, cbank.ibanno cust_ibanno,
       -->> LAUNDRY RELATED INFO
       lbank.idcode lndry_bank_idcode, lbank.description lndry_bank_desc, lbank.internalidcode lndry_bank_internid,
       lbank.laundrybankaccount lndry_bank_lndrybankaccount, lbank.ibanno lndry_bank_ibanno
from customerbillinginfo cbi left outer join bankinstitution cbank
                         on cbank.bankinstitution_id = cbi.bankinstitution_id,
     bankinstitution lbank
where cbi.laundrybankinstitution_id is null
      and lbank.bankinstitution_id =
          (SELECT MIN(BA.BANKINSTITUTION_ID) FROM BANKINSTITUTION BA WHERE BA.DEFAULTLAUNDRYBANK = 'Y')
/

  CREATE OR REPLACE VIEW "V_CURRENTREVENUEPERCUSTOMER" ("LINETYPE", "DELTONR", "DELTONAME", "DEFAULTBUSINESSUNIT_ID", "BU_CODE", "BILLTONR", "BILLTONAME", "PAYBYNR", "PAYBYNAME", "COMMONNR", "COMMONNAME", "MASTERACCOUNTNR", "MASTERACCOUNTNAME", "SALESAREACODE", "ROUTENUMBER", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "PRODUCTCODE", "TYPEOFMERCHANDISE", "PRODUCTDESC", "PRODRANKING", "PRODPRIORITY", "ALLOWRETURNTOSTOCK", "SIZECODE", "FINISHCODE", "FINISHDESC", "DELSCHEMECODE", "WEARER_ID", "WEARERNUMBER", "CHANGESPERWEEK", "MAXINVENTORY", "WEAREREMPLOYMENT_ID", "PRICE", "PLPC_CHANGESPERWEEK", "LANGUAGE_CODE", "SPECIALCHARGE_AMOUNT", "SPECIALCHARGE_CODE", "SPECIALCHARGE_DESC", "CUSTOMER_ID", "MASTACCACTIVE", "PAYBYACTIVE", "DEBTACTIVE", "COMMONACTIVE", "DELTOACTIVE") AS 
  select 0 linetype, cu.customernumber DelToNr, cu.name DelToName, cu.defaultbusinessunit_id
, bu.code bu_code
, deb.customernumber BillToNr, deb.name BillToName
, payby1.customernumber PayByNr, payby1.name PayByName
, comm1.customernumber CommonNr, comm1.name CommonName
, ma1.customernumber masteraccountNr, ma1.name masteraccountName
, sa.code SalesAreaCode
, (select Min(Ro.RouteNumber) from route Ro, routestop RS where Ro.Route_ID = RS.Route_ID and Ro.Active = 'Y'
          and RS.Customer_ID = Cu.Customer_ID and RS.DateActive <= trunc(sysdate) and RS.DateInactive >= trunc(sysdate)) RouteNumber
, dp.distributionpointnumber, dp.description distributionpointdesc
, de.departmentnumber, de.description departmentdesc, pr.code ProductCode, pr.typeofmerchandise
, (select prd.description from product_desc prd where prd.product_id = pr.product_id and prd.language_id = lan.language_id ) ProductDesc
, pra.ranking prodranking
, pra.priority prodpriority
, plpc.allowreturntostock
, (select sd.code from sizedefinition sd where sd.sizedefinition_id = plpd.sizedefinition_id ) SizeCode
, (select fm.code from finishingmethod fm where fm.finishingmethod_id = plpc.finishingmethod_id ) FinishCode
, (select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = plpc.finishingmethod_id and fmd.language_id = lan.language_id ) FinishDesc
, (select ds.code from deliveryscheme ds where sdl.deliveryscheme_id = ds.deliveryscheme_id ) DelSchemeCode
, -1 wearer_id, -1 wearernumber, 0 changesperweek, sdl.fixedrentquantity maxinventory, -1 weareremployment_id
, case when plpc.rentpriceperfrequency = 'Y'
  then pack_price.Rent_Price(cu.customer_id, plpc.product_id, plpc.sizedefinition_id, plpc.finishingmethod_id, sysdate,(select ds.frequency from deliveryscheme ds where sdl.deliveryscheme_id = ds.deliveryscheme_id ) )
  else pack_price.Rent_Price(cu.customer_id, plpc.product_id, plpc.sizedefinition_id, plpc.finishingmethod_id, sysdate)
end Price
, plpc.changesperweek plpc_changesperweek, lan.Code Language_Code
, 0 specialcharge_amount, ' ' specialcharge_code, ' ' specialcharge_desc
, cu.customer_id
, ma1.active MastAccActive, payby1.active paybyActive, deb.active debtActive, comm1.active CommonActive, cu.active DeltoActive
from productlistpercustomer plpc
      inner join product pr
           left outer join productranking pra on pr.productranking_id = pra.productranking_id
      on plpc.product_id = pr.product_id
      inner join customer cu
            left outer join customer ma1 on cu.masteraccount_id = ma1.customer_id
            left outer join customer comm1 on cu.commoncustomer_id = comm1.customer_id
            inner join salesarea sa on cu.salesarea_id = sa.salesarea_id
            inner join businessunit bu on cu.defaultbusinessunit_id = bu.businessunit_id
            inner join customer deb
                  inner join customerbillinginfo cbi1
                        left outer join customer payby1 on cbi1.paybycustomer_link_id = payby1.customer_id
                  on deb.customer_id = cbi1.customer_id
            on cu.debtor_id = deb.customer_id
      on plpc.customer_id = cu.customer_id
      inner join productlistperdistribpoint plpd
            inner join distributionpoint dp
                  inner join department de on dp.department_id = de.department_id
            on plpd.distributionpoint_id = dp.distributionpoint_id
            inner join standarddeliveryline sdl on plpd.productlistperdistribpoint_id = sdl.productlistperdistribpoint_id
      on plpc.product_id = plpd.product_id and plpc.sizedefinition_id = plpd.sizedefinition_id and plpc.finishingmethod_id = plpd.finishingmethod_id
      , languages lan
where plpc.billingmethod in (1, 3)
      and plpc.dateactive <= trunc(sysdate) and plpc.dateinactive >= trunc(sysdate)
      and de.customer_id = cu.customer_id
      and sdl.dateactive <= trunc(sysdate) and sdl.dateinactive >= trunc(sysdate)
      and not exists (select 1 from temporarydeliverystop tds where tds.standarddeliveryline_id = sdl.standarddeliveryline_id
                     and (((TDS.StartDate is not null) and
                          (TDS.StartDate <= trunc(sysdate)) and
                          (TDS.EndDate is not null) and
                          (TDS.EndDate > trunc(sysdate)) and
                          (TDS.TempStopRentForDate = 'Y')) or
                            ((TDS.TemporaryStopStartWeek <> 0) and (TDS.TemporaryStopStartYear <> 0) and
                           TDS.TemporaryStopStartWeek <= to_number(to_char(sysdate,'IW')) and TDS.TemporaryStopStartYear <= to_number(to_char(sysdate,'YYYY')) and
                           TDS.Temporarystopendweek > to_number(to_char(sysdate,'IW')) and TDS.Temporarystopendyear > to_number(to_char(sysdate,'YYYY')) and
                            (TDS.TempStopRentForYearWeek = 'Y')) or
                            ((TDS.TempStopStartWeekForYear <> 0) and
                          TDS.TempStopStartWeekForYear <= to_number(to_char(sysdate,'IW')) and  TDS.TempStopEndWeekForYear > to_number(to_char(sysdate,'IW')) and
                            (TDS.TempStopRentForWeek = 'Y'))))
      and pr.typeofmerchandise = 1
union all
select 1 linetype, cu.customernumber DelToNr, cu.name DelToName, cu.defaultbusinessunit_id
, bu.code bu_code
, deb.customernumber BillToNr, deb.name BillToName
, payby1.customernumber PayByNr, payby1.name PayByName
, comm1.customernumber CommonNr, comm1.name CommonName
, ma1.customernumber masteraccountNr, ma1.name masteraccountName
, sa.code SalesAreaCode
, (select Min(Ro.RouteNumber) from route Ro, routestop RS where Ro.Route_ID = RS.Route_ID and Ro.Active = 'Y'
          and RS.Customer_ID = Cu.Customer_ID and RS.DateActive <= trunc(sysdate) and RS.DateInactive >= trunc(sysdate)) RouteNumber
, dp.distributionpointnumber, dp.description distributionpointdesc
, de.departmentnumber, de.description departmentdesc, pr.code ProductCode, pr.typeofmerchandise
, (select prd.description from product_desc prd where prd.product_id = pr.product_id and prd.language_id = lan.language_id ) ProductDesc
, pra.ranking prodranking
, pra.priority prodpriority
, coalesce((select max(plpc.allowreturntostock) from productlistpercustomer plpc where plpc.customer_id = cu.customer_id
            and plpc.billingmethod in (1, 3) and plpc.dateactive <= trunc(sysdate) and plpc.dateinactive >= trunc(sysdate)
            and wi.product_id = plpc.product_id and wi.finishingmethod_id = plpc.finishingmethod_id
            and wi.sizedefinition_id = plpc.sizedefinition_id),
            (select max(plpc.allowreturntostock) from productlistpercustomer plpc where plpc.customer_id = cu.customer_id
            and plpc.billingmethod in (1, 3) and plpc.dateactive <= trunc(sysdate) and plpc.dateinactive >= trunc(sysdate)
            and wi.product_id = plpc.product_id and wi.finishingmethod_id = plpc.finishingmethod_id
            and plpc.sizedefinition_id in (select sd.sizedefinition_id from sizedefinition sd where sd.code = '*'))
  , 0) allowreturntostock
, (select sd.code from sizedefinition sd where sd.sizedefinition_id = wi.sizedefinition_id ) SizeCode
, (select fm.code from finishingmethod fm where fm.finishingmethod_id = wi.finishingmethod_id ) FinishCode
, (select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = wi.finishingmethod_id and fmd.language_id = lan.language_id ) FinishDesc
, ' ' DelSchemeCode, wr.wearer_id, wr.wearernumber, wi.changesperweek, wi.maxinventory, we.weareremployment_id
, pack_price.Rent_Price(cu.customer_id, wi.product_id, wi.sizedefinition_id, wi.finishingmethod_id, sysdate, wi.changesperweek) Price
, coalesce((select max(plpc.changesperweek) from productlistpercustomer plpc where plpc.customer_id = cu.customer_id
            and plpc.billingmethod in (1, 3) and plpc.dateactive <= trunc(sysdate) and plpc.dateinactive >= trunc(sysdate)
            and wi.product_id = plpc.product_id and wi.finishingmethod_id = plpc.finishingmethod_id
            and wi.sizedefinition_id = plpc.sizedefinition_id),
            (select max(plpc.changesperweek) from productlistpercustomer plpc where plpc.customer_id = cu.customer_id
            and plpc.billingmethod in (1, 3) and plpc.dateactive <= trunc(sysdate) and plpc.dateinactive >= trunc(sysdate)
            and wi.product_id = plpc.product_id and wi.finishingmethod_id = plpc.finishingmethod_id
            and plpc.sizedefinition_id in (select sd.sizedefinition_id from sizedefinition sd where sd.code = '*'))
  , 'N') plpc_changesperweek
, lan.Code Language_Code, 0 specialcharge_amount, ' ' specialcharge_code, ' ' specialcharge_desc
, cu.customer_id
, ma1.active MastAccActive, payby1.active paybyActive, deb.active debtActive, comm1.active CommonActive, cu.active DeltoActive
from wearerinventory wi
     inner join weareremployment we
           inner join wearer wr
                 inner join customer cu
                      left outer join customer ma1 on cu.masteraccount_id = ma1.customer_id
                      left outer join customer comm1 on cu.commoncustomer_id = comm1.customer_id
                      inner join salesarea sa on cu.salesarea_id = sa.salesarea_id
                      inner join businessunit bu on cu.defaultbusinessunit_id = bu.businessunit_id
                      inner join customer deb
                            inner join customerbillinginfo cbi1
                                  left outer join customer payby1 on cbi1.paybycustomer_link_id = payby1.customer_id
                            on deb.customer_id = cbi1.customer_id
                      on cu.debtor_id = deb.customer_id
                 on wr.customer_id = cu.customer_id
           on we.wearer_id = wr.wearer_id
           inner join distributionpoint dp
                 inner join department de on dp.department_id = de.department_id
           on we.distributionpoint_id = dp.distributionpoint_id
     on wi.weareremployment_id = we.weareremployment_id
     inner join product pr
           left outer join productranking pra on pr.productranking_id = pra.productranking_id
     on wi.product_id = pr.product_id
     , languages lan
where wi.dateactive <= trunc(sysdate) and wi.dateinactive >= trunc(sysdate)
      and Not Exists (select -- + INDEX (TGRS, XAK1TEMPORARYGARMENTRENTSTOP)
                     1 from TemporaryGarmentRentStop TGRS where TGRS.Customer_ID = cu.Customer_ID
                     and TGRS.StartYear <> 0 and
                      TGRS.StartWeek <= to_number(to_char(sysdate,'IW')) and TGRS.StartYear <= to_number(to_char(sysdate,'YYYY'))
                     and (TGRS.EndWeek = 0 OR TGRS.EndYear=0 or (TGRS.EndWeek <> 0 and TGRS.EndYear <> 0 and
                     TGRS.EndWeek > to_number(to_char(sysdate,'IW')) and TGRS.EndYear>to_number(to_char(sysdate,'YYYY'))
                     )))
      and pr.typeofmerchandise = 2
union all
select 2 linetype, cu.customernumber DelToNr, cu.name DelToName, cu.defaultbusinessunit_id
, bu.code bu_code
, deb.customernumber BillToNr, deb.name BillToName
, payby1.customernumber PayByNr, payby1.name PayByName
, comm1.customernumber CommonNr, comm1.name CommonName
, ma1.customernumber masteraccountNr, ma1.name masteraccountName
, sa.code SalesAreaCode
, (select Min(Ro.RouteNumber) from route Ro, routestop RS where Ro.Route_ID = RS.Route_ID and Ro.Active = 'Y'
          and RS.Customer_ID = Cu.Customer_ID and RS.DateActive <= trunc(sysdate) and RS.DateInactive >= trunc(sysdate)) RouteNumber
, -1 distributionpointnumber, ' ' distributionpointdesc
, -1 departmentnumber, ' ' departmentdesc, ' ' ProductCode, -1 typeofmerchandise
, ' ' ProductDesc
, ' ' prodranking
, -1 prodpriority
, 0 allowreturntostock
, ' ' SizeCode
, ' ' FinishCode
, ' ' FinishDesc
, ' ' DelSchemeCode, -1 wearer_id, -1 wearernumber, -1 changesperweek, 0 maxinventory, -1 weareremployment_id
, 0 Price
, 'N' plpc_changesperweek, lan.Code Language_Code
, pack_price.SpecialCharge_Price(cu.customer_id, sc.specialcharge_id, sysdate) specialcharge_amount
, sc.code specialcharge_code
, (select scd.description from specialcharge_desc scd where sc.specialcharge_id = scd.specialcharge_id and scd.language_id = lan.language_id)  specialcharge_desc
, cu.customer_id
, ma1.active MastAccActive, payby1.active paybyActive, deb.active debtActive, comm1.active CommonActive, cu.active DeltoActive
from customerspecialcharge csc
     inner join specialcharge sc on csc.specialcharge_id = sc.specialcharge_id
     inner join customer cu
          left outer join customer ma1 on cu.masteraccount_id = ma1.customer_id
          left outer join customer comm1 on cu.commoncustomer_id = comm1.customer_id
          inner join salesarea sa on cu.salesarea_id = sa.salesarea_id
          inner join businessunit bu on cu.defaultbusinessunit_id = bu.businessunit_id
          inner join customer deb
                inner join customerbillinginfo cbi1
                      left outer join customer payby1 on cbi1.paybycustomer_link_id = payby1.customer_id
                on deb.customer_id = cbi1.customer_id
          on cu.debtor_id = deb.customer_id
     on csc.customer_id = cu.customer_id
, languages lan
where sc.fixedamount = 'Y' and sc.frequency <= 4
/

  CREATE OR REPLACE VIEW "V_CUSTMISSINGITEMS" ("CODEUNIQUE", "BATCH_ID", "YEAR", "WEEK", "BATCHNUMBER", "BATCHCODE", "DAYDESCRIPTION", "CUSTOMERNUMBER", "CUSTOMERNAME", "CLIENTNUMBER", "CLIENTNAME", "CLIENTFIRSTNAME", "CLIENT_ID", "PRIMARYID", "PRODUCTDESC", "PRODUCTCODE", "LASTSTAYDESCRIPTION", "LANGUAGECODE", "LASTSTAYDATE", "PRESORTNUMBER", "FMCODE", "SDCODE", "PRESORTBATCH", "QUANTITY", "BELONGTOCURRENTBATCH") AS 
  select  1 codeunique,b.batch_id, b.year, b.week, b.batchnumber, b.batchcode,
       (select dd.description from day_desc dd where b.day_id = dd.day_id and dd.language_id = languages.language_id) DayDescription,
       c.customernumber, c.name customername,
       cl.clientnumber, cl.name clientname, cl.firstname clientfirstname, cl.client_id,
       uri.primaryid,
       (select pdesc.description from product_desc pdesc where p.product_id = pdesc.product_id and pdesc.language_id = languages.language_id) ProductDesc,
       p.code ProductCode,
       (select sdesc.description from stay_desc sdesc where uri.stay_id = sdesc.stay_id and sdesc.language_id = languages.language_id) LastStayDescription,
       languages.code languagecode, uri.laststaydate,
       cdn.presortnumber,
       ( select fm.code from finishingmethod fm where urip.finishingmethod_id=fm.finishingmethod_id)fmcode,
       ( select sd.code from sizedefinition sd where urip.sizedefinition_id=sd.sizedefinition_id)sdcode,
     coalesce((select crs.presortcustomer from  customerresidentialsettings crs where b.customer_link_id=crs.customer_id),'N') presortbatch,
     1 quantity,1 belongtocurrentbatch
from uniqueresidentialitem uri,
     uniqueresidentialitemproduct urip,
     stay s,
     clientdeliverynote cdn, clientdeliverynoteline cdnl, clientdelnotelinescan cdns,
     customer c, client cl, product p,
     batch b,
     languages
where uri.uniqueresidentialitem_id = urip.uniqueresidentialitem_id
      and uri.stay_id = s.stay_id
      and s.staynr in(10, 50,60,70) -- in, rewash, delay, late
      and s.staytype = 5 -- residential
      and uri.client_id = cl.client_id
      and cl.customer_id = c.customer_id
      and cl.client_id = cdn.client_link_id -- link on CDN CLIENT
      and cdn.clientdeliverynote_id = cdnl.clientdeliverinote_id
      and cdnl.product_link_id = p.product_id
      and cdn.batch_id = b.batch_id
      and b.customer_link_id=c.customer_id
      and cdns.inscanclientdelnoteline_id = cdnl.clientdeliverynoteline_id
      and cdns.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id
      and (uri.lastinscandate is null or getdatediff(trunc(sysdate), uri.lastinscandate) <
      coalesce((select to_number(ss.value) from SYSTEMSETTING ss, businessunit bu
               where ss.name = 'PWBMAXCOMPLETENESSDAYS' and ss.plant_id = bu.plant_id and bu.businessunit_id = uri.businessunit_id ),100))
union
select 1 codeunique, b.batch_id, b.year, b.week, b.batchnumber, b.batchcode,
       (select dd.description from day_desc dd where b.day_id = dd.day_id and dd.language_id = languages.language_id) DayDescription,
       c.customernumber, c.name customername,
       cl.clientnumber, cl.name clientname, cl.firstname clientfirstname, cl.client_id,
       uri.primaryid,
       (select pdesc.description from product_desc pdesc where p.product_id = pdesc.product_id and pdesc.language_id = languages.language_id) ProductDesc,
       p.code ProductCode,
       (select sdesc.description from stay_desc sdesc where uri.stay_id = sdesc.stay_id and sdesc.language_id = languages.language_id) LastStayDescription,
       languages.code languagecode, uri.laststaydate,
       cl.presortnumber,
       ( select fm.code from finishingmethod fm where urip.finishingmethod_id=fm.finishingmethod_id)fmcode,
       ( select sd.code from sizedefinition sd where urip.sizedefinition_id=sd.sizedefinition_id)sdcode,
       coalesce((select crs.presortcustomer from  customerresidentialsettings crs where b.customer_link_id=crs.customer_id),'N') presortbatch,
       1 quantity,2 belongtocurrentbatch
from uniqueresidentialitem uri,
     uniqueresidentialitemproduct urip,
     stay s,
     clientdeliverynote cdn,
     customer c, client cl, product p,
     batch b,
     languages
where uri.uniqueresidentialitem_id = urip.uniqueresidentialitem_id
      and uri.stay_id = s.stay_id
      and s.staynr in(50,60,70)-- rewash,delay,late
      and s.staytype = 5 -- residential
      and uri.client_id = cl.client_id
      and cl.customer_id = c.customer_id
      and b.customer_link_id=c.customer_id
      and cl.client_id = cdn.client_link_id -- link on CDN CLIENT
      and urip.product_id = p.product_id
      and (uri.lastinscandate is null or getdatediff(trunc(sysdate), uri.lastinscandate) <
      coalesce((select to_number(ss.value) from SYSTEMSETTING ss, businessunit bu
               where ss.name = 'PWBMAXCOMPLETENESSDAYS' and ss.plant_id = bu.plant_id and bu.businessunit_id = uri.businessunit_id ),100))
      and not exists ( select 1 from clientdeliverynoteline cdnl, clientdelnotelinescan cdns, clientdeliverynote cdni
      where uri.uniqueresidentialitem_id=cdns.uniqueresidentialitem_link_id and cdns.inscanclientdelnoteline_id=cdnl.clientdeliverynoteline_id
      and cdnl.clientdeliverinote_id=cdni.clientdeliverynote_id and cdni.batch_id= b.batch_id)
union
      select 2 codeunique,b.batch_id, b.year, b.week, b.batchnumber, b.batchcode,
       (select dd.description from day_desc dd where b.day_id = dd.day_id and dd.language_id = languages.language_id) DayDescription,
       c.customernumber, c.name customername,
       cl.clientnumber, cl.name clientname, cl.firstname clientfirstname, cl.client_id,
       '-1' primaryid,
       (select pdesc.description from product_desc pdesc where p.product_id = pdesc.product_id and pdesc.language_id = languages.language_id) ProductDesc,
       p.code ProductCode,
       '' LastStayDescription,
       languages.code languagecode, sysdate laststaydate,
       cdn.presortnumber,
       ( select fm.code from finishingmethod fm where cdnl.finishingmethod_id=fm.finishingmethod_id)fmcode,
          ( select sd.code from sizedefinition sd where cdnl.sizedefinition_link_id = sd.sizedefinition_id)sdcode,
     coalesce((select crs.presortcustomer from  customerresidentialsettings crs where b.customer_link_id=crs.customer_id),'N') presortbatch,
      (cdnl.qtycountedin-cdnl.qtycountedout) quantity, 1 belongtocurrentbatch
from clientdeliverynote cdn, clientdeliverynoteline cdnl,
     customer c, client cl, product p, batch b,
     languages
where cl.customer_id = c.customer_id
      and cl.client_id = cdn.client_link_id -- link on CDN CLIENT
      and cdn.clientdeliverynote_id = cdnl.clientdeliverinote_id
      and cdnl.product_link_id = p.product_id
      and cdn.batch_id = b.batch_id
      and b.customer_link_id=c.customer_id
      and cdnl.qtycountedin-cdnl.qtycountedout>0
      and ((select ss.value
          from SYSTEMSETTING ss, businessunit bu
               where ss.name = 'PWBCOMPCHECKNONUNIQUE' and ss.plant_id = bu.plant_id and bu.businessunit_id = b.businessunit_id )=0)
 union
      select 2 codeunique,b.batch_id, b.year, b.week, b.batchnumber, b.batchcode,
       (select dd.description from day_desc dd where b.day_id = dd.day_id and dd.language_id = languages.language_id) DayDescription,
       c.customernumber, c.name customername,
       cl.clientnumber, cl.name clientname, cl.firstname clientfirstname, cl.client_id,
       '-1' primaryid,
       (select pdesc.description from product_desc pdesc where p.product_id = pdesc.product_id and pdesc.language_id = languages.language_id) ProductDesc,
       p.code ProductCode,
       '' LastStayDescription,
       languages.code languagecode, sysdate laststaydate,
       cdn.presortnumber,
       ( select fm.code from finishingmethod fm where cdnl.finishingmethod_id=fm.finishingmethod_id)fmcode,
          ( select sd.code from sizedefinition sd where cdnl.sizedefinition_link_id = sd.sizedefinition_id)sdcode,
     coalesce((select crs.presortcustomer from  customerresidentialsettings crs where b.customer_link_id=crs.customer_id),'N') presortbatch,
      (cdnl.qtycountedin-cdnl.qtycountedout) quantity, 2 belongtocurrentbatch
from clientdeliverynote cdn, clientdeliverynoteline cdnl,
     customer c, client cl, product p, batch b,batch oldbatch,
     languages
where cl.customer_id = c.customer_id
      and cl.client_id = cdn.client_link_id -- link on CDN CLIENT
      and cdn.clientdeliverynote_id = cdnl.clientdeliverinote_id
      and cdn.customer_link_id=c.customer_id
      and cdnl.product_link_id = p.product_id
      and cdn.batch_id=oldbatch.batch_id
      and oldbatch.closingdate is not null
      and oldbatch.origin <> 8
      and oldbatch.batch_id <> b.batch_id
      and b.customer_link_id=oldbatch.customer_link_id
      and b.customer_link_id=c.customer_id
      and cdnl.qtycountedin-cdnl.qtycountedout > 0
      and ((select ss.value
          from SYSTEMSETTING ss, businessunit bu
               where ss.name = 'PWBCOMPCHECKNONUNIQUE' and ss.plant_id = bu.plant_id and bu.businessunit_id = b.businessunit_id )=0)
/

  CREATE OR REPLACE VIEW "V_CUSTMISSINGPRODUCTS" ("CODEUNIQUE", "BATCH_ID", "YEAR", "WEEK", "BATCHNUMBER", "BATCHCODE", "DAYDESCRIPTION", "CUSTOMERNUMBER", "CUSTOMERNAME", "CLIENTNUMBER", "CLIENTNAME", "CLIENTFIRSTNAME", "CLIENT_ID", "PRIMARYID", "PRODUCTDESC", "PRODUCTCODE", "LASTSTAYDESCRIPTION", "LANGUAGECODE", "LASTSTAYDATE", "PRESORTNUMBER", "FMCODE", "SDCODE", "PRESORTBATCH", "QUANTITY", "STAYNR") AS 
  select  1 codeunique,b.batch_id, b.year, b.week, b.batchnumber, b.batchcode,
       (select dd.description from day_desc dd where b.day_id = dd.day_id and dd.language_id = languages.language_id) DayDescription,
       c.customernumber, c.name customername,
       cl.clientnumber, cl.name clientname, cl.firstname clientfirstname, cl.client_id,
       uri.primaryid,
       (select pdesc.description from product_desc pdesc where p.product_id = pdesc.product_id and pdesc.language_id = languages.language_id) ProductDesc,
       p.code ProductCode,
       (select sdesc.description from stay_desc sdesc where uri.stay_id = sdesc.stay_id and sdesc.language_id = languages.language_id) LastStayDescription,
       languages.code languagecode, uri.laststaydate,
       cdn.presortnumber,
       ( select fm.code from finishingmethod fm where urip.finishingmethod_id=fm.finishingmethod_id)fmcode,
       ( select sd.code from sizedefinition sd where urip.sizedefinition_id=sd.sizedefinition_id)sdcode,
     coalesce((select crs.presortcustomer from  customerresidentialsettings crs where b.customer_link_id=crs.customer_id),'N') presortbatch,
     1 quantity, s.staynr staynr
from uniqueresidentialitem uri,
     uniqueresidentialitemproduct urip,
     stay s,
     clientdeliverynote cdn, clientdeliverynoteline cdnl, clientdelnotelinescan cdns,
     customer c, client cl, product p,
     batch b,
     languages
where uri.uniqueresidentialitem_id = urip.uniqueresidentialitem_id
      and uri.stay_id = s.stay_id
      and s.staynr = 10 -- in
      and s.staytype = 5 -- residential
      and uri.client_id = cl.client_id
      and cl.customer_id = c.customer_id
      and cl.client_id = cdn.client_link_id -- link on CDN CLIENT
      and cdn.clientdeliverynote_id = cdnl.clientdeliverinote_id
      and cdnl.product_link_id = p.product_id
      and cdn.batch_id = b.batch_id
      and b.customer_link_id=c.customer_id
      and cdns.inscanclientdelnoteline_id = cdnl.clientdeliverynoteline_id
      and cdns.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id
      and (uri.lastinscandate is null or getdatediff(trunc(sysdate), uri.lastinscandate) <
      coalesce((select to_number(ss.value) from SYSTEMSETTING ss, businessunit bu
               where ss.name = 'PWBMAXCOMPLETENESSDAYS' and ss.plant_id = bu.plant_id and bu.businessunit_id = uri.businessunit_id ),100))
union
select 1 codeunique, b.batch_id, b.year, b.week, b.batchnumber, b.batchcode,
       (select dd.description from day_desc dd where b.day_id = dd.day_id and dd.language_id = languages.language_id) DayDescription,
       c.customernumber, c.name customername,
       cl.clientnumber, cl.name clientname, cl.firstname clientfirstname, cl.client_id,
       uri.primaryid,
       (select pdesc.description from product_desc pdesc where p.product_id = pdesc.product_id and pdesc.language_id = languages.language_id) ProductDesc,
       p.code ProductCode,
       (select sdesc.description from stay_desc sdesc where uri.stay_id = sdesc.stay_id and sdesc.language_id = languages.language_id) LastStayDescription,
       languages.code languagecode, uri.laststaydate,
       cl.presortnumber,
       ( select fm.code from finishingmethod fm where urip.finishingmethod_id=fm.finishingmethod_id)fmcode,
       ( select sd.code from sizedefinition sd where urip.sizedefinition_id=sd.sizedefinition_id)sdcode,
       coalesce((select crs.presortcustomer from  customerresidentialsettings crs where b.customer_link_id=crs.customer_id),'N') presortbatch,
       1 quantity,s.staynr staynr
from uniqueresidentialitem uri,
     uniqueresidentialitemproduct urip,
     stay s,
     clientdeliverynote cdn,
     customer c, client cl, product p,
     batch b,
     languages
where uri.uniqueresidentialitem_id = urip.uniqueresidentialitem_id
      and uri.stay_id = s.stay_id
      and s.staynr in(50,60,70)-- rewash,delay,late
      and s.staytype = 5 -- residential
      and uri.client_id = cl.client_id
      and cl.customer_id = c.customer_id
      and b.customer_link_id=c.customer_id
      and cl.client_id = cdn.client_link_id -- link on CDN CLIENT
      and urip.product_id = p.product_id
      and (uri.lastinscandate is null or getdatediff(trunc(sysdate), uri.lastinscandate) <
      coalesce((select to_number(ss.value) from SYSTEMSETTING ss, businessunit bu
               where ss.name = 'PWBMAXCOMPLETENESSDAYS' and ss.plant_id = bu.plant_id and bu.businessunit_id = uri.businessunit_id ),100))
union
      select 2 codeunique,b.batch_id, b.year, b.week, b.batchnumber, b.batchcode,
       (select dd.description from day_desc dd where b.day_id = dd.day_id and dd.language_id = languages.language_id) DayDescription,
       c.customernumber, c.name customername,
       cl.clientnumber, cl.name clientname, cl.firstname clientfirstname, cl.client_id,
       '-1' primaryid,
       (select pdesc.description from product_desc pdesc where p.product_id = pdesc.product_id and pdesc.language_id = languages.language_id) ProductDesc,
       p.code ProductCode,
       '' LastStayDescription,
       languages.code languagecode, sysdate laststaydate,
       cdn.presortnumber,
       ( select fm.code from finishingmethod fm where cdnl.finishingmethod_id=fm.finishingmethod_id)fmcode,
          ( select sd.code from sizedefinition sd where cdnl.sizedefinition_link_id = sd.sizedefinition_id)sdcode,
     coalesce((select crs.presortcustomer from  customerresidentialsettings crs where b.customer_link_id=crs.customer_id),'N') presortbatch,
      (cdnl.qtycountedin-cdnl.qtycountedout) quantity, 999 staynr
from clientdeliverynote cdn, clientdeliverynoteline cdnl,
     customer c, client cl, product p, batch b,
     languages
where cl.customer_id = c.customer_id
      and cl.client_id = cdn.client_link_id -- link on CDN CLIENT
      and cdn.clientdeliverynote_id = cdnl.clientdeliverinote_id
      and cdnl.product_link_id = p.product_id
      and cdn.batch_id = b.batch_id
      and b.customer_link_id=c.customer_id
      and cdnl.qtycountedin-cdnl.qtycountedout>0
      and ((select ss.value
          from SYSTEMSETTING ss, businessunit bu
               where ss.name = 'PWBCOMPCHECKNONUNIQUE' and ss.plant_id = bu.plant_id and bu.businessunit_id = b.businessunit_id )=0)
 union
      select 2 codeunique,b.batch_id, b.year, b.week, b.batchnumber, b.batchcode,
       (select dd.description from day_desc dd where b.day_id = dd.day_id and dd.language_id = languages.language_id) DayDescription,
       c.customernumber, c.name customername,
       cl.clientnumber, cl.name clientname, cl.firstname clientfirstname, cl.client_id,
       '-1' primaryid,
       (select pdesc.description from product_desc pdesc where p.product_id = pdesc.product_id and pdesc.language_id = languages.language_id) ProductDesc,
       p.code ProductCode,
       '' LastStayDescription,
       languages.code languagecode, sysdate laststaydate,
       cdn.presortnumber,
       ( select fm.code from finishingmethod fm where cdnl.finishingmethod_id=fm.finishingmethod_id)fmcode,
          ( select sd.code from sizedefinition sd where cdnl.sizedefinition_link_id = sd.sizedefinition_id)sdcode,
     coalesce((select crs.presortcustomer from  customerresidentialsettings crs where b.customer_link_id=crs.customer_id),'N') presortbatch,
      (cdnl.qtycountedin-cdnl.qtycountedout) quantity, 60 staynr
from clientdeliverynote cdn, clientdeliverynoteline cdnl,
     customer c, client cl, product p, batch b,batch oldbatch,
     languages
where cl.customer_id = c.customer_id
      and cl.client_id = cdn.client_link_id -- link on CDN CLIENT
      and cdn.clientdeliverynote_id = cdnl.clientdeliverinote_id
      and cdn.customer_link_id=c.customer_id
      and cdnl.product_link_id = p.product_id
      and cdn.batch_id=oldbatch.batch_id
      and oldbatch.closingdate is not null
      and cdn.batch_id <> b.batch_id
      and b.customer_link_id=oldbatch.customer_link_id
      and oldbatch.origin <> 8
      and b.customer_link_id=c.customer_id
      and cdnl.qtycountedin-cdnl.qtycountedout>0
      and ((select ss.value
          from SYSTEMSETTING ss, businessunit bu
               where ss.name = 'PWBCOMPCHECKNONUNIQUE' and ss.plant_id = bu.plant_id and bu.businessunit_id = b.businessunit_id )=0)
/

  CREATE OR REPLACE VIEW "V_CUSTOMER" ("CUSTOMERNUMBER", "NAME", "LEGALNAME", "SEARCHNAME", "PHONENO", "FAXNO", "EMAIL", "DATEACTIVE", "DATEINACTIVE", "ACTIVE", "SICCODE", "REMARK", "LEGACYCUSTOMERNUMBER", "STREET", "STREET2", "ZIPCODE", "CITY", "COUNTY", "STATE", "MAILSTREET", "MAILSTREET2", "MAILZIPCODE", "MAILCITY", "MAILCOUNTY", "MAILSTATE", "COUNTRYCODE", "COUNTRYDESC", "CURRENCYCODE", "CURRENCYDESC", "CUSTOMERLANGUAGECODE", "CUSTOMERLANGUAGEDESC", "BUSINESSUNITCODE", "BUSINESSUNITDESC", "MARKETSEGMENTCODE", "MARKETSEGMENT_DESC", "SALESAREACODE", "SALESAREA_DESC", "DEBTORNUMBER", "DEBTORNAME", "MASTERACCOUNTNUMBER", "MASTERACCOUNTNAME", "COMMUNICATIONMETHODCODE", "COMMUNICATIONMETHOD_DESC", "SOILCOUNT", "DELIVERYLAYOUTCODE", "CONSIGNMENTNOTELEVEL", "INTERNETORDERING", "IMPORTOCCUPANCYHHT", "RETURNLINEN", "RETURNGARMENTS", "CODEGARMENTSUNIQUELY", "LOCKERMANAGEMENT", "USESGARMENTDISPENSER", "SWINGSUITDELIVERY", "GARMENTRENTSPECIFICATION", "CHARGEREPAIRS", "DAYSNOPREPCHARGE", "DAYSSPECIALGRADE", "FIRSTDAYGRADECODE", "FIRSTDAY_DESC", "FIRSTISSUEGRADECODE", "FIRSTISSUE_DESC", "QUALITYGRADECODE", "QUALITYGRADE_DESC", "SERVICETEAMCODE", "SERVICETEAMDESC", "OCCUPANCYFROMSTOCKCOUNT", "STANDARDQTYDEFINITION", "CORRECTSHORTAGES", "CORRECTOVERDELIVERIES", "FORMLAYOUTICODE", "INVOICECOPIES", "MINIMUMINVOICEAMOUNT", "TAXABLE", "PAYMENTMETHOD", "PAYMENTTYPE", "CUSTOMERMARKINGGARMENT", "INVOICEFREQUENCY_ID", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE", "SENDSTATEMENTBYEMAIL", "STATEMENTCOPIES") AS 
  SELECT /*VIEW V_CUSTOMER VERSION 0.3*/
CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, CUSTOMER.LEGALNAME, CUSTOMER.SEARCHNAME,
CUSTOMER.PHONENO, CUSTOMER.FAXNO, CUSTOMER.EMAIL,
CUSTOMER.DATEACTIVE, CUSTOMER.DATEINACTIVE, CUSTOMER.ACTIVE, CUSTOMER.SICCODE,
CUSTOMER.REMARK, CUSTOMER.LEGACYCUSTOMERNUMBER,
VISITADDRESS.STREET, VISITADDRESS.STREET2, VISITADDRESS.ZIPCODE,VISITADDRESS.CITY, VISITADDRESS.COUNTY, VISITADDRESS.STATE,
MAILADDRESS.STREET MAILSTREET, MAILADDRESS.STREET2 MAILSTREET2, MAILADDRESS.ZIPCODE MAILZIPCODE, MAILADDRESS.CITY MAILCITY,
MAILADDRESS.COUNTY MAILCOUNTY,MAILADDRESS.STATE MAILSTATE,
COUNTRY.CODE COUNTRYCODE, COUNTRY.DESCRIPTION COUNTRYDESC,
CURRENCY.CODE CURRENCYCODE, CURRENCY.DESCRIPTION CURRENCYDESC,
CUSTOMERLANGUAGES.CODE CUSTOMERLANGUAGECODE, CUSTOMERLANGUAGES.DESCRIPTION CUSTOMERLANGUAGEDESC,
BUSINESSUNIT.CODE BUSINESSUNITCODE, BUSINESSUNIT.DESCRIPTION BUSINESSUNITDESC,
MARKETSEGMENT.CODE MARKETSEGMENTCODE,
(SELECT DESCRIPTION FROM MARKETSEGMENT_DESC M WHERE M.MARKETSEGMENT_ID = CUSTOMER.MARKETSEGMENT_ID AND M.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) MARKETSEGMENT_DESC,
SALESAREA.CODE SALESAREACODE,
(SELECT DESCRIPTION FROM SALESAREA_DESC S WHERE S.SALESAREA_ID = CUSTOMER.SALESAREA_ID AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SALESAREA_DESC,
DEBTOR.CUSTOMERNUMBER DEBTORNUMBER, DEBTOR.NAME DEBTORNAME,
MASTERACCOUNT.CUSTOMERNUMBER MASTERACCOUNTNUMBER, MASTERACCOUNT.NAME MASTERACCOUNTNAME,
COMMUNICATIONMETHOD.CODE COMMUNICATIONMETHODCODE,
(SELECT DESCRIPTION FROM COMMUNICATIONMETHOD_DESC C WHERE C.COMMUNICATIONMETHOD_ID = CUSTOMER.COMMUNICATIONMETHOD_ID AND C.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) COMMUNICATIONMETHOD_DESC,
CUSTOMER.SOILCOUNT,
DELIVERYLAYOUT.CODE DELIVERYLAYOUTCODE,
CUSTOMER.CONSIGNMENTNOTELEVEL,
CUSTOMER.INTERNETORDERING,
CUSTOMER.IMPORTOCCUPANCYHHT,
CUSTOMER.RETURNLINEN, CUSTOMER.RETURNGARMENTS, CUSTOMER.CODEGARMENTSUNIQUELY,
CUSTOMER.LOCKERMANAGEMENT, CUSTOMER.USESGARMENTDISPENSER,
CUSTOMER.SWINGSUITDELIVERY, CUSTOMER.GARMENTRENTSPECIFICATION, CUSTOMER.CHARGEREPAIRS,
CUSTOMER.DAYSNOPREPCHARGE, CUSTOMER.DAYSSPECIALGRADE,
FIRSTDAYGRADE.CODE FIRSTDAYGRADECODE,
(SELECT DESCRIPTION FROM QUALITYGRADE_DESC A WHERE A.QUALITYGRADE_ID = CUSTOMER.FIRSTDAYSGRADE_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FIRSTDAY_DESC,
FIRSTISSUEGRADE.CODE FIRSTISSUEGRADECODE,
(SELECT DESCRIPTION FROM QUALITYGRADE_DESC A WHERE A.QUALITYGRADE_ID = CUSTOMER.FIRSTISSUEGRADE_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FIRSTISSUE_DESC,
QUALITYGRADE.CODE QUALITYGRADECODE,
(SELECT DESCRIPTION FROM QUALITYGRADE_DESC A WHERE A.QUALITYGRADE_ID = CUSTOMER.QUALITYGRADE_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) QUALITYGRADE_DESC,
SERVICETEAM.CODE SERVICETEAMCODE, SERVICETEAM.DESCRIPTION SERVICETEAMDESC,
CUSTOMER.OCCUPANCYFROMSTOCKCOUNT, CUSTOMER.STANDARDQTYDEFINITION,
CUSTOMER.CORRECTSHORTAGES, CUSTOMER.CORRECTOVERDELIVERIES,
FORMLAYOUT_I.CODE FORMLAYOUTICODE,CUSTOMER.INVOICECOPIES, CUSTOMER.MINIMUMINVOICEAMOUNT, CUSTOMER.TAXABLE,
CUSTOMER.PAYMENTMETHOD, CUSTOMER.PAYMENTTYPE,
CUSTOMER.CUSTOMERMARKINGGARMENT, CUSTOMER.INVOICEFREQUENCY_ID,
CUSTOMER.SYSTEMUSER_ID, CUSTOMER.TIMESTAMP, LANGUAGES.CODE LANGUAGECODE,
CB.SENDSTATEMENTBYEMAIL, CB.STATEMENTCOPIES
FROM CUSTOMER
JOIN CUSTOMER DEBTOR ON DEBTOR.CUSTOMER_ID = CUSTOMER.DEBTOR_ID
JOIN CUSTOMERBILLINGINFO CB ON CB.CUSTOMER_ID = CUSTOMER.DEBTOR_ID
JOIN ADDRESS VISITADDRESS ON CUSTOMER.VISITADDRESS_ID =VISITADDRESS.ADDRESS_ID
JOIN ADDRESS MAILADDRESS ON CUSTOMER.MAILADDRESS_ID = MAILADDRESS.ADDRESS_ID
JOIN COUNTRY ON CUSTOMER.COUNTRY_ID = COUNTRY.COUNTRY_ID
JOIN CURRENCY ON CUSTOMER.CURRENCY_ID = CURRENCY.CURRENCY_ID
JOIN BUSINESSUNIT ON CUSTOMER.DEFAULTBUSINESSUNIT_ID = BUSINESSUNIT.BUSINESSUNIT_ID
JOIN CUSTOMER MASTERACCOUNT ON CUSTOMER.MASTERACCOUNT_ID = MASTERACCOUNT.CUSTOMER_ID
JOIN COMMUNICATIONMETHOD ON CUSTOMER.COMMUNICATIONMETHOD_ID = COMMUNICATIONMETHOD.COMMUNICATIONMETHOD_ID
JOIN MARKETSEGMENT ON CUSTOMER.MARKETSEGMENT_ID = MARKETSEGMENT.MARKETSEGMENT_ID
JOIN SALESAREA ON CUSTOMER.SALESAREA_ID = SALESAREA.SALESAREA_ID
JOIN FORMLAYOUT DELIVERYLAYOUT ON CUSTOMER.DELIVERYNOTELAYOUT_ID = DELIVERYLAYOUT.FORMLAYOUT_ID
JOIN FORMLAYOUT FORMLAYOUT_I ON CUSTOMER.INVOICELAYOUT_ID = FORMLAYOUT_I.FORMLAYOUT_ID
LEFT OUTER JOIN QUALITYGRADE ON CUSTOMER.QUALITYGRADE_ID = QUALITYGRADE.QUALITYGRADE_ID
LEFT OUTER JOIN QUALITYGRADE FIRSTDAYGRADE ON(CUSTOMER.FIRSTDAYSGRADE_ID = FIRSTDAYGRADE.QUALITYGRADE_ID)
LEFT OUTER JOIN QUALITYGRADE FIRSTISSUEGRADE ON(CUSTOMER.FIRSTISSUEGRADE_ID = FIRSTISSUEGRADE.QUALITYGRADE_ID)
LEFT OUTER JOIN SERVICETEAM ON (CUSTOMER.SERVICETEAM_ID = SERVICETEAM.SERVICETEAM_ID)
LEFT OUTER JOIN FORMLAYOUT CONSIGNMENTLAYOUT ON (CUSTOMER.CONSIGNMENTNOTELAYOUT_ID = CONSIGNMENTLAYOUT.FORMLAYOUT_ID)
JOIN LANGUAGES CUSTOMERLANGUAGES ON CUSTOMER.LANGUAGE_ID = CUSTOMERLANGUAGES.LANGUAGE_ID
CROSS JOIN LANGUAGES
/

  CREATE OR REPLACE VIEW "V_CUSTOMERACTIVITIES" ("CUSTOMERNUMBER", "CUSTOMERNAME", "ACTIVITYCODE", "ACTIVITYDESCRIPTION", "PROCESSBUSINESSUNITNR", "PROCESSBUSINESSUNITNAME", "INVOICEBUSINESSUNITNR", "INVOICEBUSINESSUNITNAME", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, ACTIVITY.CODE,
(SELECT A.DESCRIPTION  FROM ACTIVITY_DESC A WHERE A.ACTIVITY_ID = CUSTOMERACTIVITIES.ACTIVITY_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) ACTIVITY_DESC,
 PROCESSBUSINESSUNIT.CODE, PROCESSBUSINESSUNIT.DESCRIPTION,
  INVOICEBUSINESSUNIT.CODE, INVOICEBUSINESSUNIT.DESCRIPTION, CUSTOMERACTIVITIES.SYSTEMUSER_ID,
  CUSTOMERACTIVITIES.TIMESTAMP, LANGUAGES.CODE
       FROM CUSTOMERACTIVITIES, CUSTOMER, ACTIVITY, BUSINESSUNIT PROCESSBUSINESSUNIT, BUSINESSUNIT INVOICEBUSINESSUNIT, LANGUAGES
       WHERE CUSTOMERACTIVITIES.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
and CUSTOMERACTIVITIES.ACTIVITY_ID = ACTIVITY.ACTIVITY_ID
and CUSTOMERACTIVITIES.PROCESSBUSINESSUNIT_ID = PROCESSBUSINESSUNIT.BUSINESSUNIT_ID
and CUSTOMERACTIVITIES.INVOICEBUSINESSUNIT_ID = INVOICEBUSINESSUNIT.BUSINESSUNIT_ID
/

  CREATE OR REPLACE VIEW "V_CUSTOMERADDRESS" ("CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CURRENCYCODE", "STREET", "STREET2", "CITY", "ZIPCODE", "STATE", "DEBTOR_ID", "DEBTOR_NR", "DEBTOR_NAME", "DEBTOR_STREET", "DEBTOR_STREET2", "DEBTOR_CITY", "DEBTOR_ZIPCODE", "DEBTOR_STATE") AS 
  select
  cu.customer_id, cu.customernumber, cu.name customername, cur.code currencyCode,
  cad.street, cad.street2, cad.city, cad.zipcode, cad.state,
  cu.debtor_id, deb.customernumber debtor_nr, deb.name debtor_name,
  bad.street debtor_street, bad.street2 debtor_street2, bad.city debtor_city,
  bad.zipcode debtor_zipcode, bad.state debtor_state
from
  customer cu
  inner join address cad on cu.visitaddress_id = cad.address_id
  inner join customer deb
        inner join currency cur on deb.currency_id = cur.currency_id
        inner join address bad on deb.visitaddress_id = bad.address_id
  on cu.debtor_id = deb.customer_id
/

  CREATE OR REPLACE VIEW "V_CUSTOMERADDRESSSTICKER" ("LINETYPE", "BU_CODE", "BU_DESC", "PLANTNAME", "PLANTPHONE", "PANTFAX", "PLANTSTREET", "PLANTSTREET2", "PLANTZIPCODE", "PLANTCITY", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DELIVERYPOINT_ID", "DELPOINT_CODE", "DELPOINT_DESC", "STREET", "STREET2", "HOUSENUMBER", "HOUSENUMBEREXT", "ZIPCODE", "CITY", "STATE", "COUNTY", "REPORTPARAM_ID", "FROM_CUSTNR", "TO_CUSTNR", "COPY_NUMBER") AS 
  select 1 linetype, bu.code bu_code, bu.description bu_desc, p.name plantname, p.phoneno plantphone, p.faxno pantfax, pa.street plantstreet,
       pa.street2 plantstreet2, pa.zipcode plantzipcode, pa.city plantcity, cu.customer_id, cu.customernumber, cu.name customername, -1 deliverypoint_id,
       '' delpoint_code, '' delpoint_desc, cua.street, cua.street2, cua.housenumber, cua.housenumberext, cua.zipcode, cua.city, cua.state, cua.county,
       rp.reportparam_id, rp.number_value1 from_custnr, rp.number_value2 to_custnr, rp.copy_number
  from customer cu
       join address cua on cu.visitaddress_id = cua.address_id
       join businessunit bu on cu.defaultbusinessunit_id = bu.businessunit_id
       join plant p on bu.plant_id = p.plant_id
       join address pa on p.address_id = pa.address_id
       , reportparam rp
 where rp.number_value is null
   and cu.customernumber between rp.number_value1 and rp.number_value2
union all
select 2 linetype, bu.code bu_code, bu.description bu_desc, p.name plantname, p.phoneno plantphone, p.faxno pantfax, pa.street plantstreet,
       pa.street2 plantstreet2, pa.zipcode plantzipcode, pa.city plantcity, cu.customer_id, cu.customernumber, cu.name customername, dp.deliverypoint_id,
       dp.code delpoint_code, dp.description delpoint_desc, dpa.street, dpa.street2, dpa.housenumber, dpa.housenumberext, dpa.zipcode, dpa.city, dpa.state,
       dpa.county, rp.reportparam_id, rp.number_value1 from_custnr, rp.number_value2 to_custnr, rp.copy_number
  from deliverypoint dp
       join customer cu on dp.customer_id = cu.customer_id
       join address dpa on dp.deliveryaddress_id = dpa.address_id
       join businessunit bu on cu.defaultbusinessunit_id = bu.businessunit_id
       join plant p on bu.plant_id = p.plant_id
       join address pa on p.address_id = pa.address_id
       , reportparam rp
 where dp.deliverypoint_id = rp.number_value
   and cu.customernumber between rp.number_value1 and rp.number_value2
/

  CREATE OR REPLACE VIEW "V_CUSTOMERBILLINGINFO" ("CUSTOMERNUMBER", "NAME", "INVOICEFREQUENCYNUMBER", "FACTORYDESCRIPTION", "SENDSTATEMENTBYEMAIL", "SENDSTATEMENT", "ATTACHINVOICECOPIES", "STATEMENTPERCUSTOMER", "STATEMENTCOPIES", "FINANCECHARGEDAYS", "FINANCECHARGEPUTON", "CREDITLIMIT", "DELINQUENTMARKAFTER", "EMPLOYEENUMBER", "SEARCHNAME", "CODE", "PAYMENTTERMSDESC", "FORMLAYOUTCODE", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT
 CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME,
 INVOICEFREQUENCY.INVOICEFREQUENCYNUMBER,
 INVOICEFREQUENCY.FACTORYDESCRIPTION,
 CUSTOMERBILLINGINFO.SENDSTATEMENTBYEMAIL,
 CUSTOMERBILLINGINFO.SENDSTATEMENT,
 CUSTOMERBILLINGINFO.ATTACHINVOICECOPIES, CUSTOMERBILLINGINFO.STATEMENTPERCUSTOMER,
 CUSTOMERBILLINGINFO.STATEMENTCOPIES, CUSTOMERBILLINGINFO.FINANCECHARGEDAYS,
 CUSTOMERBILLINGINFO.FINANCECHARGEPUTON, CUSTOMERBILLINGINFO.CREDITLIMIT,
 CUSTOMERBILLINGINFO.DELINQUENTMARKAFTER,
 EMPLOYEE.EMPLOYEENUMBER, EMPLOYEE.SEARCHNAME,
 PAYMENTTERMS.CODE,
 (SELECT description FROM PAYMENTTERMS_DESC A WHERE A.PAYMENTTERMS_ID = CUSTOMERBILLINGINFO.PAYMENTTERMS_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) paymenttermsdesc,
 --ADDRESS.STREET, ADDRESS.ZIPCODE, ADDRESS.CITY, ADDRESS.STATE, ADDRESS.COUNTY,
 FORMLAYOUT.CODE formlayoutcode,
 CUSTOMERBILLINGINFO.SYSTEMUSER_ID, CUSTOMERBILLINGINFO.TIMESTAMP, LANGUAGES.CODE languagecode
FROM
 CUSTOMER, CUSTOMERBILLINGINFO
   left outer join EMPLOYEE on CUSTOMERBILLINGINFO.COLLECTIONRESPONSIBLE_ID = EMPLOYEE.EMPLOYEE_ID
   left outer join INVOICEFREQUENCY on CUSTOMERBILLINGINFO.STATEMENTFREQUENCY_ID = INVOICEFREQUENCY.INVOICEFREQUENCY_ID
 , PAYMENTTERMS,
-- ADDRESS,
 FORMLAYOUT,  LANGUAGES
WHERE
 CUSTOMERBILLINGINFO.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
 AND CUSTOMERBILLINGINFO.PAYMENTTERMS_ID = PAYMENTTERMS.PAYMENTTERMS_ID
 --AND CUSTOMERBILLINGINFO.INVOICEADDRESS_ID = ADDRESS.ADDRESS_ID
 AND (CUSTOMERBILLINGINFO.STATEMENTLAYOUT_ID = FORMLAYOUT.FORMLAYOUT_ID
 AND FORMLAYOUT.FORMTYPE = 'ST')
/

  CREATE OR REPLACE VIEW "V_CUSTOMERCONTACTINFOSUMMARY" ("CUSTOMER_ID", "CUSTOMERNUMBER", "NAME", "PHONENO", "FAXNO", "EMAIL", "LEGACYCUSTOMERNUMBER", "DATEACTIVE", "DATEINACTIVE", "ACTIVE", "SICCODE", "SYSTEMUSER_ID", "TIMESTAMP", "CHAIN_ID", "BUSINESSUNITCODE", "BUSINESSUNITDESC", "STREET", "STREET2", "CITY", "COUNTY", "STATE", "ZIPCODE", "CHAINCODE", "ROUTENR", "MSTREET", "MSTREET2", "MCITY", "MCOUNTY", "MSTATE", "MZIPCODE", "DEBTORNUMBER", "DEBTORNAME", "DEBTORPHONE", "DEBTORFAX", "DEBTOREMAIL", "PRIMARYCONTACTNAME", "PRIMARYCONTACTTITLE", "PRIMARYCONTACTEMAIL", "ALTERNATECONTACTNAME", "ALTERNATECONTACTTITLE", "ALTERNATECONTACTEMAIL", "PAYABLECONTACTNAME", "PAYABLECONTACTTITLE", "PAYABLECONTACTEMAIL") AS 
  select cu.customer_id, cu.customernumber, cu.name,
cu.phoneno, cu.faxno, cu.email, cu.legacycustomernumber,
cu.dateactive, cu.dateinactive, cu.active, cu.siccode,
cu.systemuser_id, cu.timestamp, cu.chain_id,
bu.code businessunitcode, bu.description businessunitdesc,
ad.street, ad.street2, ad.city, ad.county, ad.state, ad.zipcode
, (select ch.code from chain ch where cu.chain_id = ch.chain_id) ChainCode
, (select max(ro.routenumber) from routestop rs, route ro where rs.customer_id = cu.customer_id and rs.route_id=ro.route_id) RouteNr
, mad.street Mstreet, mad.street2 Mstreet2, mad.city Mcity, mad.county Mcounty, mad.state Mstate, mad.zipcode Mzipcode
, deb.customernumber DebtorNumber, deb.name DebtorName
, deb.phoneno DebtorPhone, deb.faxno DebtorFax, deb.email DebtorEmail
, (select pp.name from contactperson pp, contactpersonfunction pf where pp.contactpersonfunction_id = pf.contactpersonfunction_id and pf.code='DCPRI'
  and pp.customer_id=cu.customer_id) PrimaryContactName
, (select pfd.description from contactperson pp, contactpersonfunction pf, contactpersonfunction_desc pfd
  where pp.contactpersonfunction_id = pf.contactpersonfunction_id and pf.code='DCPRI'
  and pp.customer_id=cu.customer_id and pf.contactpersonfunction_id = pfd.contactpersonfunction_id and pfd.language_id = cu.language_id ) PrimaryContactTitle
, (select pp.email from contactperson pp, contactpersonfunction pf where pp.contactpersonfunction_id = pf.contactpersonfunction_id and pf.code='DCPRI'
  and pp.customer_id=cu.customer_id) PrimaryContactEmail
, (select pp.name from contactperson pp, contactpersonfunction pf where pp.contactpersonfunction_id = pf.contactpersonfunction_id and pf.code='DCALT'
  and pp.customer_id=cu.customer_id) AlternateContactName
, (select pfd.description from contactperson pp, contactpersonfunction pf, contactpersonfunction_desc pfd
  where pp.contactpersonfunction_id = pf.contactpersonfunction_id and pf.code='DCALT'
  and pp.customer_id=cu.customer_id and pf.contactpersonfunction_id = pfd.contactpersonfunction_id and pfd.language_id = cu.language_id ) AlternateContactTitle
, (select pp.email from contactperson pp, contactpersonfunction pf where pp.contactpersonfunction_id = pf.contactpersonfunction_id and pf.code='DCALT'
  and pp.customer_id=cu.customer_id) AlternateContactEmail
, (select pp.name from contactperson pp, contactpersonfunction pf where pp.contactpersonfunction_id = pf.contactpersonfunction_id and pf.code='APPRI'
  and pp.customer_id=cu.customer_id) PayableContactName
, (select pfd.description from contactperson pp, contactpersonfunction pf, contactpersonfunction_desc pfd
  where pp.contactpersonfunction_id = pf.contactpersonfunction_id and pf.code='APPRI'
  and pp.customer_id=cu.customer_id and pf.contactpersonfunction_id = pfd.contactpersonfunction_id and pfd.language_id = cu.language_id ) PayableContactTitle
, (select pp.email from contactperson pp, contactpersonfunction pf where pp.contactpersonfunction_id = pf.contactpersonfunction_id and pf.code='APPRI'
  and pp.customer_id=cu.customer_id) PayableContactEmail
from address ad, businessunit bu, address mad, customer deb, customer cu
where cu.visitaddress_id = ad.address_id and cu.mailaddress_id = mad.address_id
and cu.defaultbusinessunit_id = bu.businessunit_id --and cu.active='y'
and cu.debtor_id = deb.customer_id
/

  CREATE OR REPLACE VIEW "V_CUSTOMERCONTRACTS" ("LINETYPE", "CUSTOMER_ID", "CONTACTPERSON_ID", "CONTRACTSPERCUSTOMER_ID", "CODE", "DESCRIPTION", "DATEACTIVE", "DATEINACTIVE", "ACCOUNTMANAGER", "PURCHASEORDER", "ANNIVERSARYPRICEADJ", "CPIBASED", "FIXEDRENTPERC", "FIXEDWASHPERC", "FIXEDREPLACEPERC", "FIXEDSALESPERC", "FIXEDWEIGHTPERC", "NEXTANNIVERSARYDATE") AS 
  select 1 linetype
, cpc.customer_id, cpc.contactperson_id, cpc.contractspercustomer_id
, cpc.code, '' description, cpc.dateactive, cpc.dateinactive
, (select e.name from employee e where cpc.accountmanager_id=e.employee_id) AccountManager
, cpc.purchaseorder, cpc.anniversarypriceadj, cpc.cpibased
, cpc.fixedrentperc, cpc.fixedwashperc, cpc.fixedreplaceperc, cpc.fixedsalesperc, cpc.fixedweightperc
, cpc.nextanniversarydate
from contractspercustomer cpc
where not exists (select 1 from contract con1, contractcustomer cc1
      where con1.contract_id = cc1.contract_id and cc1.customer_link_id = cpc.customer_id)
union all
select 2 linetype
, cc.customer_link_id customer_id, con.contactperson_id, cc.contractcustomer_id contractspercustomer_id
, con.code, con.description, con.startdate dateactive, con.enddate dateinactive
, (select e.name from employee e where con.accountmanager_id=e.employee_id) AccountManager
, con.purchaseorder, 2 anniversarypriceadj, 'Y' cpibased
, 0 fixedrentperc, 0 fixedwashperc, 0 fixedreplaceperc, 0 fixedsalesperc, 0 fixedweightperc
, con.nextschedulepriceincrease nextanniversarydate
from contract con, contractcustomer cc
where con.contract_id = cc.contract_id
/

  CREATE OR REPLACE VIEW "V_CUSTOMERDETAILRECAP" ("BUSINESSUNITCODE", "BUSINESSUNITDESCRIPTION", "CUSTOMERID", "CUSTOMERNUMBER", "CUSTOMERNAME", "STREET1", "STREET2", "CITY", "ZIPCODE", "STATE", "SEARCHNAME", "MAILSTREET", "MAILSTREET2", "MAILCITY", "MAILZIP", "MAILSTATE", "PHONENO", "FAXNO", "BILLCUSTOMERNUMBER", "BILLNAME", "BILLSTREET1", "BILLSTREET2", "BILLCITY", "BILLZIPCODE", "BILLSTATE", "PAYMENTMETHOD", "PAYMENTTYPE", "TAXABLE", "VATNUMBER", "BANKACCOUNT", "GARMENTRENTSPECIFICATION", "CUSTOMERCLUSTER_DESC", "MINIMUMINVOICEAMOUNT", "CURRENCYCODE", "REMARK", "SALESAREACODE", "CURRENCYINVOICEAMOUNTDECIMALS", "CUSTOMERDELIVERYDAYNUMBER", "MARKETSEGMENTCODE", "ACTIVE", "DATEACTIVE", "DATEINACTIVE", "LANGUAGECODE", "LANGUAGEDESC", "CONTRACTUSAGE", "DELIVERYDAYS_US", "CUST_DELIVERYDAYS_US", "COUNTRYCODE", "COUNTRYDESC", "MARKET_SEGMENT", "BILLCOUNTRYCODE", "DELIVERYSCHEMECODE", "ROUTENUMBER", "PAYMENTTERMS", "INVOICEFREQUENCY_DESC", "CUSTOMERDELIVERYDAYDESC", "SALESAREA_DESC", "COM_METHOD", "CHAIN_DESC") AS 
  select /*version 2.1*/
       bu.code businessunitcode, bu.description businessunitdescription , cu.customer_id customerid, cu.customernumber, cu.name customername, ads.street street1,
       ads.street2, ads.city, ads.zipcode, ads.state, cu.searchname, adm.street mailstreet, adm.street2 mailstreet2, adm.city mailcity, adm.zipcode mailzip, adm.state mailstate,
       cu.phoneno, cu.faxno, bill.customernumber billcustomernumber, bill.name billname, ba.street billstreet1, ba.street2 billstreet2, ba.city billcity,
       ba.zipcode billzipcode, ba.state billstate, cu.paymentmethod, cu.paymenttype, cu.taxable, cu.vatnumber, cbi.bankaccount, cu.garmentrentspecification,
       f_customerspercluster(cu.customer_id) customercluster_desc, cu.minimuminvoiceamount, curr.code currencycode, cu.remark, sal.code salesareacode,
       curr.invoiceamountdecimals currencyinvoiceamountdecimals, cud.day_id customerdeliverydaynumber, mrk.code marketsegmentcode,
       cu.active, cu.dateactive, cu.dateinactive, lan.code languagecode, lan.description languagedesc, cu.contractusage,
       (select ss.value
          from systemsetting ss
         where bu.plant_id=ss.plant_id
           and ss.name = 'DELIVERYDAYS_US') deliverydays_us,
       (select f_deliverydays_us(ss1.value, cu.customer_id, lan.language_id)
          from systemsetting ss1
         where bu.plant_id=ss1.plant_id
           and ss1.name = 'DELIVERYDAYS_US') cust_deliverydays_us,
       (select co.code
          from country co
               join plant pl on co.country_id = pl.country_id
         where bu.plant_id = pl.plant_id) countrycode,
       (select co.description
          from country co
               join plant pl on co.country_id = pl.country_id
         where bu.plant_id = pl.plant_id) countrydesc,
       (select msd.description
          from marketsegment_desc msd
         where cu.marketsegment_id = msd.marketsegment_id
           and msd.language_id = lan.language_id) market_segment,
       (select co.code
          from country co
               join plant pl
                    join businessunit bt on pl.plant_id = bt.plant_id
               on co.country_id = pl.country_id
         where bill.defaultbusinessunit_id = bt.businessunit_id) billcountrycode,
       (select dels.code
          from deliveryscheme dels
         where dels.deliveryscheme_id = f_deliveryschemepercustomer(cu.customer_id)) deliveryschemecode,
       (select ro.routenumber
          from route ro
               join routestop r on ro.route_id = r.route_id
         where ro.active = 'y'
           and r.routestop_id = f_firstroutestop(cu.customer_id,f_deliveryschemepercustomer(cu.customer_id))) routenumber,
       (select ptd.description
          from paymentterms_desc ptd
         where ptd.paymentterms_id = cbi.paymentterms_id
           and ptd.language_id = lan.language_id) paymentterms,
       (select ifd.description
          from invoicefrequency_desc ifd
         where ifd.invoicefrequency_id = cu.invoicefrequency_id
           and ifd.language_id = lan.language_id) invoicefrequency_desc,
       (select day_desc.description
          from day_desc
         where cud.day_id = day_desc.day_id
           and day_desc.language_id = lan.language_id) customerdeliverydaydesc,
       (select sad.description
          from salesarea_desc sad
         where sad.salesarea_id = sal.salesarea_id
           and sad.language_id = lan.language_id) salesarea_desc,
       (select cmd.description
          from communicationmethod_desc cmd
         where cu.communicationmethod_id = cmd.communicationmethod_id
           and cmd.language_id = lan.language_id) com_method,
       (select cha.name
          from chain cha
         where cha.chain_id = cu.chain_id) chain_desc
  from customer bill
       join address ba on bill.invoiceaddress_id = ba.address_id
       join customer cu
            left join customerbillinginfo cbi
                      join paymentterms pt on cbi.paymentterms_id = pt.paymentterms_id
            on cu.customer_id = cbi.customer_id
            left join marketsegment mrk on cu.marketsegment_id = mrk.marketsegment_id
            left join salesarea sal on cu.salesarea_id = sal.salesarea_id
            join address ads on cu.visitaddress_id = ads.address_id
            join address adm on cu.mailaddress_id = adm.address_id
            join businessunit bu on cu.defaultbusinessunit_id = bu.businessunit_id
            join currency curr on cu.currency_id = curr.currency_id
            join customerdeliveryscheme cud on cu.customer_id = cud.customer_id
       on bill.customer_id = cu.debtor_id
       cross join languages lan
 where cud.deliveryscheme_id = f_deliveryschemepercustomer(cu.customer_id)
/

  CREATE OR REPLACE VIEW "V_CUSTOMERDISCOUNTLIST" ("CUSTOMERNUMBER", "CUSTOMERNAME", "PRICETYPE", "CODE", "DESCRIPTION", "ACTIVE", "PRIORITY", "DATEACTIVE", "DATEINACTIVE", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME,
 DISCOUNTLISTPERCUSTOMER.PRICETYPE, GENERALDISCOUNTLIST.CODE, GENERALDISCOUNTLIST.DESCRIPTION,
 GENERALDISCOUNTLIST.ACTIVE,
 DISCOUNTLISTPERCUSTOMER.PRIORITY, DISCOUNTLISTPERCUSTOMER.DATEACTIVE, DISCOUNTLISTPERCUSTOMER.DATEINACTIVE,
 DISCOUNTLISTPERCUSTOMER.SYSTEMUSER_ID, DISCOUNTLISTPERCUSTOMER.TIMESTAMP
FROM CUSTOMER, DISCOUNTLISTPERCUSTOMER
 left outer join GENERALDISCOUNTLIST on(GENERALDISCOUNTLIST.GENERALDISCOUNTLIST_ID = DISCOUNTLISTPERCUSTOMER.GENERALDISCOUNTLIST_ID)
WHERE      DISCOUNTLISTPERCUSTOMER.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
/

  CREATE OR REPLACE VIEW "V_CUSTOMERGARMENTRENTSTOP" ("CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DATEACTIVE", "DATEINACTIVE", "STARTWEEK", "STARTYEAR", "ENDWEEK", "ENDYEAR", "STARTDATE", "ENDDATE", "CLUSTER_CODE", "CLUSTER_DESC", "CLUSTER_ACTIVE", "CUTOFFDATE", "BU_CODE") AS 
  select cu.customer_id, cu.customernumber, cu.name customername, cu.dateactive, cu.dateinactive
, tgrs.startweek, tgrs.startyear
, tgrs.endweek, tgrs.endyear
, case when tgrs.startyear = 0 then to_date('01-01-1900', 'dd-mm-yyyy')
else getdateforweekyear(1, tgrs.startweek, tgrs.startyear) end startdate
, case when tgrs.endyear = 0 then to_date('31-12-2099', 'dd-mm-yyyy')
else  getdateforweekyear(7, tgrs.endweek, tgrs.endyear) end enddate
, clu.code cluster_code, clu.description cluster_desc, clu.active cluster_active
, (select min(ca.cutoffdate) from customeractivities ca where ca.customer_id = cu.customer_id) cutoffdate
, (select bu.code from businessunit bu where bu.businessunit_id = cu.defaultbusinessunit_id) BU_code
from customer cu, temporarygarmentrentstop tgrs, customerspercluster cpc, customercluster clu
where tgrs.customer_id = cu.customer_id and cpc.customer_id = cu.customer_id and clu.cluster_id = cpc.cluster_id
      and clu.active = 'Y'
/

  CREATE OR REPLACE VIEW "V_CUSTOMERINTERNETOPTIONS" ("CUSTOMERNUMBER", "CUSTOMERNAME", "ORDERSALESITEMS", "ORDERGARMENTS", "ORDERLINEN", "MAINTAINSTOCKLEVELS", "MAINTAINSTDDEL", "TIMESTAMP", "USERNAME") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, CUSTOMERINTERNETOPTIONS.ORDERSALESITEMS,
 CUSTOMERINTERNETOPTIONS.ORDERGARMENTS, CUSTOMERINTERNETOPTIONS.ORDERLINEN,
 CUSTOMERINTERNETOPTIONS.MAINTAINSTOCKLEVELS, CUSTOMERINTERNETOPTIONS.MAINTAINSTDDEL,
 CUSTOMERINTERNETOPTIONS.SYSTEMUSER_ID, CUSTOMERINTERNETOPTIONS.TIMESTAMP
       FROM CUSTOMERINTERNETOPTIONS, CUSTOMER
       WHERE CUSTOMERINTERNETOPTIONS.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
/

  CREATE OR REPLACE VIEW "V_CUSTOMERORDERSTATUS" ("WORKORDER_ID", "WORKORDERNUMBER", "WEARERNAME", "PRODUCTCODE", "PRODUCTDESCRIPTION", "ORDERED", "QUANTITYFILLED", "TOBEDELIVERED", "CUSTOMERNUMBER", "NAME", "STREET", "ZIPCODE", "CITY", "HOUSENUMBER", "HOUSENUMBEREXT", "BUSINESSUNIT_ID", "REFERENCENUMBER", "LANGUAGECODE") AS 
  select
w.workorder_id, w.workordernumber,
we.wearername,
p.code productcode,
(select product_desc.description from product_desc where product_desc.product_id = p.product_id
  and product_desc.language_id = languages.language_id) productDescription,
(wl.quantityordered - wl.quantitycancelled) ordered,
wl.quantityfilled,
(wl.quantityordered - wl.quantitycancelled-wl.quantityfilled) tobedelivered,
c.customernumber, c.name,
a.street, a.zipcode, a.city, a.housenumber, a.housenumberext,
w.businessunit_id,
w.referencenumber,
languages.CODE languagecode
from
workorder w,
workorderline wl,
weareremployment_link we,
product_link p,
status st,
customer c,
address a,
languages
where   w.workorder_id = wl.workorder_id
and wl.product_link_id = p.product_link_id
and w.weareremployment_link_id = we.weareremployment_link_id
and w.status_id = st.status_id
and st.statustype = 'WO'
and (st.code <>'40' and st.code<>'05')
and w.customer_link_id = c.customer_id
and c.visitaddress_id = a.address_id
--and languages.CODE = 'EN_US'
--    and w.workordernumber = 430001331
/

  CREATE OR REPLACE VIEW "V_CUSTOMERPERBUSINESSUNITDI" ("BUSINESSUNIT_ID", "CUSTOMER_ID") AS 
  select defaultbusinessunit_id, customer_id
	from customer
union
select invoicebusinessunit_id, customer_id
	from customeractivities
/

  CREATE OR REPLACE VIEW "V_CUSTOMERPRICELIST" ("CUSTOMERNUMBER", "CUSTOMERNAME", "PRICETYPE", "CODE", "DESCRIPTION", "ACTIVE", "AUTOPRICEUPDATE", "PRICEINDEXCODE", "CURRENCYCODE", "PRIORITY", "DATEACTIVE", "DATEINACTIVE", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  SELECT
CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME,
PRICELISTPERCUSTOMER.PRICETYPE, GENERALPRICELIST.CODE, GENERALPRICELIST.DESCRIPTION,
GENERALPRICELIST.ACTIVE, GENERALPRICELIST.AUTOPRICEUPDATE,
GENERALPRICELIST.PRICEINDEXCODE, CURRENCY.CODE,
PRICELISTPERCUSTOMER.PRIORITY, PRICELISTPERCUSTOMER.DATEACTIVE, PRICELISTPERCUSTOMER.DATEINACTIVE,
PRICELISTPERCUSTOMER.SYSTEMUSER_ID, PRICELISTPERCUSTOMER.TIMESTAMP
FROM CURRENCY, CUSTOMER, PRICELISTPERCUSTOMER
left outer join GENERALPRICELIST on(PRICELISTPERCUSTOMER.GENERALPRICELIST_ID = GENERALPRICELIST.GENERALPRICELIST_ID)
 WHERE PRICELISTPERCUSTOMER.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
 AND CUSTOMER.CURRENCY_ID = CURRENCY.CURRENCY_ID
/

  CREATE OR REPLACE VIEW "V_CUSTOMERPRODUCTUSAGE" ("CUSTOMER_ID", "BUCODE", "DEPARTMENTNUMBER", "DP_CODE", "CUSTOMERNUMBER", "CUSTOMERNAME", "FABRIC_CODE", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "FM_CODE", "COLORCODE", "NOMINAL_INVENTORY", "DELIVEREDAMOUNT", "DELIVERYDATE", "STATUS_CODE", "NOTENUMBER", "PLPC_PRICE", "LANGUAGECODE", "DATEACTIVE", "DATEINACTIVE") AS 
  select c.customer_id,
       (select bu.code from businessunit bu where bu.businessunit_id = c.defaultbusinessunit_id) bucode,
       (select d.departmentnumber from department d where d.customer_id = c.customer_id) departmentnumber,
       (select dp.distributionpointnumber from distributionpoint dp where dp.distributionpoint_id = plpd.distributionpoint_id) dp_code,
       c.customernumber,
       c.name customername,
       (select f.code from fabric f where f.fabric_id = p.fabric_id) fabric_code,
       p.code productcode,
       (select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = l.language_id) productdesc,
       sd.code sizecode,
       fm.code fm_code,
       (select cl.code from color cl where p.color_id = cl.color_id) colorcode,
       (select sum(rqa.quantity)
          from rentalqtyadjustment rqa
         where rqa.productlistperdistribpoint_id =
               plpd.productlistperdistribpoint_id
           and rqa.adjustmentdate <= sysdate
           and rqa.origin <> 2) nominal_inventory,
       coalesce((select sum(pnl.deliveredamount) from packingnoteline pnl
        where pnl.product_id = plpc.product_id
        and pnl.sizedefinition_id = plpc.sizedefinition_id
        and pnl.finishingmethod_id = plpc.finishingmethod_id
        and pnl.packingnote_id = pn.packingnote_id),0) deliveredamount,
       pn.deliverydate,
       (select s.code from status s where s.status_id = pn.status_id) status_code,
       pn.notenumber,
       (case plpc.billingmethod
         when 4
              then pack_price.Wash_Price(plpc.customer_id,plpc.product_id,plpc.sizedefinition_id,plpc.finishingmethod_id,sysdate,0)
         else pack_price.Rent_Price(plpc.customer_id,plpc.product_id,plpc.sizedefinition_id,plpc.finishingmethod_id,sysdate)
       end) plpc_price,
       l.code languagecode,
       plpc.dateactive,
       plpc.dateinactive
  from productlistpercustomer     plpc,
       customer                   c,
       product                    p,
       sizedefinition             sd,
       finishingmethod            fm,
       standarddeliveryline       sdl,
       productlistperdistribpoint plpd
       left outer join packingnote pn
                       on plpd.distributionpoint_id = pn.distributionpoint_id,
       languages l
 where plpc.customer_id = c.customer_id
   and plpc.product_id = p.product_id
   and plpc.sizedefinition_id = sd.sizedefinition_id
   and plpc.finishingmethod_id = fm.finishingmethod_id
   and plpc.productlistpercustomer_id = sdl.productlistpercustomer_id
   and sdl.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
   and to_date(plpc.dateactive,'dd-mm-yyyy') <= to_date(sysdate,'dd-mm-yyyy')
   and to_date(plpc.dateinactive, 'dd-mm-yyyy') > to_date(sysdate,'dd-mm-yyyy')
/

  CREATE OR REPLACE VIEW "V_CUSTOMERRENTDISCOUNT" ("CUSTOMERNUMBER", "CUSTOMERNAME", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "TYPEOFRENT", "STARTDATE", "DISCOUNT", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME,
 PRODUCT.CODE,
 (SELECT description FROM PRODUCT_DESC A WHERE A.PRODUCT_ID = PRODUCTLISTPERCUSTOMER.PRODUCT_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
 SIZEDEFINITION.CODE,
 (SELECT description FROM SIZEDEFINITION_DESC B WHERE B.SIZEDEFINITION_ID = PRODUCTLISTPERCUSTOMER.SIZEDEFINITION_ID
  AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) sizedefinitiondescription,
 FINISHINGMETHOD.CODE,
 (SELECT description FROM FINISHINGMETHOD_DESC C WHERE C.FINISHINGMETHOD_ID = PRODUCTLISTPERCUSTOMER.FINISHINGMETHOD_ID
  AND C.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddescription,
 CUSTOMERRENTDISCOUNT.TYPEOFRENT,
 CUSTOMERRENTDISCOUNT.STARTDATE,CUSTOMERRENTDISCOUNT.DISCOUNT,
 CUSTOMERRENTDISCOUNT.SYSTEMUSER_ID, CUSTOMERRENTDISCOUNT.TIMESTAMP, LANGUAGES.CODE
FROM CUSTOMERRENTDISCOUNT, CUSTOMER, PRODUCTLISTPERCUSTOMER, PRODUCT, SIZEDEFINITION, FINISHINGMETHOD, LANGUAGES
WHERE CUSTOMERRENTDISCOUNT.PRODUCTLISTPERCUSTOMER_ID = PRODUCTLISTPERCUSTOMER.PRODUCTLISTPERCUSTOMER_ID
 AND PRODUCTLISTPERCUSTOMER.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
 AND PRODUCTLISTPERCUSTOMER.PRODUCT_ID = PRODUCT.PRODUCT_ID
 AND PRODUCTLISTPERCUSTOMER.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
 AND PRODUCTLISTPERCUSTOMER.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
/

  CREATE OR REPLACE VIEW "V_CUSTOMERRENTPRICE" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CURRENCYCODE", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "TYPEOFRENT", "CHANGESPERWEEK", "STARTDATE", "PRICE", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, CURRENCY.CODE,
 PRODUCT.CODE,
 (SELECT description FROM PRODUCT_DESC A WHERE A.PRODUCT_ID = PRODUCTLISTPERCUSTOMER.PRODUCT_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
 SIZEDEFINITION.CODE,
 (SELECT description FROM SIZEDEFINITION_DESC B WHERE B.SIZEDEFINITION_ID = PRODUCTLISTPERCUSTOMER.SIZEDEFINITION_ID
  AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) sizedefinitiondescription,
 FINISHINGMETHOD.CODE,
 (SELECT description FROM FINISHINGMETHOD_DESC C WHERE C.FINISHINGMETHOD_ID = PRODUCTLISTPERCUSTOMER.FINISHINGMETHOD_ID
  AND C.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddescription,
 CUSTOMERRENTPRICE.TYPEOFRENT, CUSTOMERRENTPRICE.CHANGESPERWEEK,
 CUSTOMERRENTPRICE.STARTDATE,CUSTOMERRENTPRICE.PRICE,
 CUSTOMERRENTPRICE.SYSTEMUSER_ID, CUSTOMERRENTPRICE.TIMESTAMP, LANGUAGES.CODE
FROM CUSTOMERRENTPRICE, CUSTOMER, CURRENCY, PRODUCTLISTPERCUSTOMER, PRODUCT, SIZEDEFINITION,
 FINISHINGMETHOD, LANGUAGES
WHERE CUSTOMERRENTPRICE.PRODUCTLISTPERCUSTOMER_ID = PRODUCTLISTPERCUSTOMER.PRODUCTLISTPERCUSTOMER_ID
 AND PRODUCTLISTPERCUSTOMER.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
 AND CUSTOMER.CURRENCY_ID = CURRENCY.CURRENCY_ID
 AND PRODUCTLISTPERCUSTOMER.PRODUCT_ID = PRODUCT.PRODUCT_ID
 AND PRODUCTLISTPERCUSTOMER.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
 AND PRODUCTLISTPERCUSTOMER.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
/

  CREATE OR REPLACE VIEW "V_CUSTOMERREPLACEMENTPRICE" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CURRENCYCODE", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESCRIPTION", "STARTDATE", "PRICE", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, CURRENCY.CODE,
 PRODUCT.CODE,
 (SELECT description FROM PRODUCT_DESC A WHERE A.PRODUCT_ID = CUSTOMERREPLACEMENTPRICE.PRODUCT_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
 SIZEDEFINITION.CODE,
 (SELECT description FROM SIZEDEFINITION_DESC B WHERE B.SIZEDEFINITION_ID = CUSTOMERREPLACEMENTPRICE.SIZEDEFINITION_ID
  AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) sizedefinitiondescription,
 CUSTOMERREPLACEMENTPRICE.STARTDATE,CUSTOMERREPLACEMENTPRICE.PRICE,
 CUSTOMERREPLACEMENTPRICE.SYSTEMUSER_ID, CUSTOMERREPLACEMENTPRICE.TIMESTAMP, LANGUAGES.CODE
FROM CUSTOMERREPLACEMENTPRICE, CUSTOMER, CURRENCY, PRODUCT, SIZEDEFINITION, LANGUAGES
WHERE CUSTOMERREPLACEMENTPRICE.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
 AND CUSTOMER.CURRENCY_ID = CURRENCY.CURRENCY_ID
 AND CUSTOMERREPLACEMENTPRICE.PRODUCT_ID = PRODUCT.PRODUCT_ID
 AND CUSTOMERREPLACEMENTPRICE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
/

  CREATE OR REPLACE VIEW "V_CUSTOMERRETENTION" ("CUSTOMER_ID", "DATEACTIVE", "DATEINACTIVE", "BUSINEESUNITOCDE", "SALESAREACODE", "MARKETSEGMENTCODE", "REGIONCODE", "DIVISIONCODE", "ROUTENUMBER", "ROUTE_DESC", "DAYNUMBER", "DAY_DESCRIPTION", "LANGUAGE_CODE") AS 
  select a.customer_id, a.dateactive, a.dateinactive,
 bu.code busineesunitocde,
 b.code salesareacode,
 c.code marketsegmentcode,
 e.code regioncode,
 f.code divisioncode,
 r.routenumber, r.description Route_Desc, coalesce(d.daynumber,0) daynumber,
 (select dd.description from day_desc dd where d.day_id=dd.day_id and dd.language_id=l.language_id) Day_description,
 l.code Language_code
from customer a
     left outer join routestop rs
      join route r
        join day d
        on r.drivingday_id=d.day_id
      on rs.route_id=r.route_id
     on a.customer_id=rs.customer_id
, salesarea b, marketsegment c, businessunit bu, region e, division f, languages l
where a.salesarea_id = b.salesarea_id
  and a.marketsegment_id = c.marketsegment_id
  and a.defaultbusinessunit_id = bu.businessunit_id
  and bu.region_id = e.region_id
  and bu.division_id = f.division_id
/

  CREATE OR REPLACE VIEW "V_CUSTOMERROUTES" ("CUSTOMER_ID", "ROUTENUMBER", "STOPNUMBER", "STOPTYPE", "DAY_DESC", "DELIVERYSCHEME_DESC", "LANGUAGE_CODE", "ROUTE_ID", "ROUTESTOP_ID", "DRIVINGDAY_ID", "ROUTE_DESC") AS 
  select rs.customer_id
, r.routenumber, rs.stopnumber, rs.stoptype
, (select dd.description from day_desc dd where dd.day_id=r.drivingday_id and dd.language_id=l.language_id) Day_desc
, (select dsd.description from deliveryscheme_desc dsd
   where dsd.deliveryscheme_id=F_DELIVERYSCHEMEPERCUSTOMER(rs.customer_id)
   and dsd.language_id=l.language_id) deliveryscheme_desc
, l.code Language_code
, r.route_id, rs.routestop_id, r.drivingday_id
, r.description Route_desc
from route r, routestop rs
, languages l
where rs.route_id = r.route_id
/

  CREATE OR REPLACE VIEW "V_CUSTOMERSALESPRICE" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CURRENCYCODE", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESCRIPTION", "STARTDATE", "PRICE", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, CURRENCY.CODE,
 PRODUCT.CODE,
 (SELECT description FROM PRODUCT_DESC A WHERE A.PRODUCT_ID = CUSTOMERSALESPRICE.PRODUCT_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
 SIZEDEFINITION.CODE,
 (SELECT description FROM SIZEDEFINITION_DESC B WHERE B.SIZEDEFINITION_ID = CUSTOMERSALESPRICE.SIZEDEFINITION_ID
  AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) sizedefinitiondescription,
 CUSTOMERSALESPRICE.STARTDATE,CUSTOMERSALESPRICE.PRICE,
 CUSTOMERSALESPRICE.SYSTEMUSER_ID, CUSTOMERSALESPRICE.TIMESTAMP, LANGUAGES.CODE
FROM CUSTOMERSALESPRICE, CUSTOMER, CURRENCY, PRODUCT, SIZEDEFINITION, LANGUAGES
WHERE CUSTOMERSALESPRICE.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
 AND CUSTOMER.CURRENCY_ID = CURRENCY.CURRENCY_ID
 AND CUSTOMERSALESPRICE.PRODUCT_ID = PRODUCT.PRODUCT_ID
 AND CUSTOMERSALESPRICE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
/

  CREATE OR REPLACE VIEW "V_CUSTOMERSONHOLD" ("LINETYPE", "CUSTOMERNUMBER", "CUSTOMERNAME", "BUCODE", "PRODUCTCODE", "PRODUCTDESCRIPTION", "PRODUCTGROUPCODE", "SIZECODE", "TYPEOFMERCHANDISE", "QUANTITY", "RENTPRICE", "WEARERNUMBER", "WEARERNAME", "LANGUAGECODE", "STARTWEEK", "ENDWEEK") AS 
  select 1 linetype,
       c.customernumber CustomerNumber,
       c.name CustomerName,
       (select bu.code
          from businessunit bu
         where bu.businessunit_id = c.defaultbusinessunit_id) BuCode,
       prd.code ProductCode,
       (select description
          from product_desc
         where l.language_id = product_desc.language_id
           and product_desc.product_id = prd.product_id) ProductDescription,
       (select pg.code
          from Productgroup pg
         where prd.productgroup_id = pg.productgroup_id) ProductgroupCode,
         sz.code sizecode,
       prd.typeofmerchandise TypeofMerchandise,
       (select sum(rqa.quantity) from rentalqtyadjustment rqa where rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
       and rqa.adjustmentdate <= sysdate) Quantity,
       pack_price.Rent_Price(c.customer_id,
                             prd.product_id,
                             sz.sizedefinition_id,
                             fm.FINISHINGMETHOD_ID,
                             sysdate) RentPrice,
       0 WearerNumber,
       ' ' WearerName,
       l.code LanguageCode,
      coalesce(tds.temporarystopstartweek , to_number(getweeknumber (tds.startdate)), tds.TempStopStartWeekForYear) StartWeek ,
      coalesce(tds.temporarystopendweek , to_number(getweeknumber (tds.enddate)), tds.tempstopendweekforyear) EndWeek
  from customer                   c,
       distributionpoint          dp,
       department                 d,
       product                    prd,
       sizedefinition             sz,
       finishingmethod            fm,
       productlistpercustomer     plpc,
       productlistperdistribpoint plpd,
       temporarydeliverystop      tds,
       standarddeliveryline sdl,
       languages            l
 where plpc.customer_id = c.customer_id
   and plpc.product_id = plpd.product_id
   and plpc.sizedefinition_id = plpd.sizedefinition_id
   and plpc.finishingmethod_id = plpd.finishingmethod_id
   and plpd.product_id = prd.product_id
   and plpd.sizedefinition_id = sz.sizedefinition_id
   and plpd.finishingmethod_id = fm.finishingmethod_id
   and plpd.distributionpoint_id = dp.distributionpoint_id
   and dp.department_id = d.department_id
   and d.customer_id = c.customer_id
   and sdl.productlistperdistribpoint_id =
       plpd.productlistperdistribpoint_id
   and prd.typeofmerchandise = 1
   and plpc.dateactive <= trunc(sysdate)
   and plpc.dateinactive >= trunc(sysdate)
   and sdl.dateactive <= trunc(sysdate)
   and sdl.dateinactive >= trunc(sysdate)
   and tds.standarddeliveryline_id = sdl.standarddeliveryline_id
           and (((TDS.StartDate is not null)  and
               (TDS.EndDate is not null) and
               (TDS.TempStopRentForDate = 'Y')) or
               ((TDS.TemporaryStopStartWeek <> 0) and
               (TDS.TemporaryStopStartYear <> 0) and
               TDS.TemporaryStopStartYear =
               to_number(to_char(sysdate, 'YYYY')) and
               TDS.TemporaryStopEndYear =
               to_number(to_char(sysdate, 'YYYY')) and
               (TDS.TempStopRentForYearWeek = 'Y')) or
               ((TDS.TempStopStartWeekForYear <> 0) and
               (tds.tempstopendweekforyear <>0)  and
               (TDS.TempStopRentForWeek = 'Y')))
union all
select 2 linetype,
       c.customernumber CustomerNumber,
       c.name CustomerName,
       (select bu.code
          from businessunit bu
         where bu.businessunit_id = c.defaultbusinessunit_id) BuCode,
       prd.code ProductCode,
       (select description
          from product_desc
         where l.language_id = product_desc.language_id
           and product_desc.product_id = prd.product_id) ProductDescription,
       (select pg.code
          from Productgroup pg
         where prd.productgroup_id = pg.productgroup_id) ProductgroupCode,
       sz.code sizecode,
       prd.typeofmerchandise TypeofMerchandise,
       (case
         when plpc.billingmethod = 1 then
          wi.changesperweek
         else
          wi.maxinventory
       end) Quantity,
       (case
         when plpc.billingmethod = 1 then
          pack_price.Rent_Price(c.customer_id,
                                prd.product_id,
                                sz.sizedefinition_id,
                                fm.FINISHINGMETHOD_ID,
                                sysdate,
                                wi.changesperweek)
         else
          pack_price.Rent_Price(c.customer_id,
                                prd.product_id,
                                sz.sizedefinition_id,
                                fm.FINISHINGMETHOD_ID,
                                sysdate)
       end) RentPrice,
       w.wearernumber WearerNumber,
       w.fullname WearerName,
       l.code LanguageCode,
       tgrs.startweek StartWeek,
       tgrs.endweek EndWeek
  from customer                 c,
       TemporaryGarmentRentStop tgrs,
       product                  prd,
       sizedefinition           sz,
       finishingmethod          fm,
       languages                l,
       wearer                   w,
       weareremployment         we,
       wearerinventory          wi
       join productlistpercustomer plpc
    on (wi.product_id = plpc.product_id and
       (wi.sizedefinition_id = plpc.sizedefinition_id or
       (plpc.sizedefinition_id in
       (select sd.sizedefinition_id
             from sizedefinition sd
            where sd.code = '*'))) and
       wi.finishingmethod_id = plpc.finishingmethod_id and
       plpc.billingmethod in (1, 3) and plpc.dateactive <= trunc(sysdate) and
       plpc.dateinactive >= trunc(sysdate))
 where c.customer_id = plpc.customer_id
   and w.customer_id = c.customer_id
   and we.wearer_id = w.wearer_id
   and wi.weareremployment_id = we.weareremployment_id
   and wi.dateactive <= trunc(sysdate)
   and wi.dateinactive >= trunc(sysdate)
   and wi.product_id = prd.product_id
   and wi.sizedefinition_id = sz.sizedefinition_id
   and wi.finishingmethod_id = fm.finishingmethod_id
   and TGRS.Customer_ID = c.Customer_ID
   and (TGRS.StartYear = to_number(to_char(sysdate, 'YYYY')) and
       TGRS.EndYear = to_number(to_char(sysdate, 'YYYY')))
   and prd.typeofmerchandise = 2
   union all
select 3 linetype,
       c.customernumber CustomerNumber,
       c.name CustomerName,
       (select bu.code
          from businessunit bu
         where bu.businessunit_id = c.defaultbusinessunit_id) BuCode,
       prd.code ProductCode,
       (select description
          from product_desc
         where l.language_id = product_desc.language_id
           and product_desc.product_id = prd.product_id) ProductDescription,
       (select pg.code
          from Productgroup pg
         where prd.productgroup_id = pg.productgroup_id) ProductgroupCode,
       sz.code sizecode,
       prd.typeofmerchandise TypeofMerchandise,
       (case
         when plpc.billingmethod = 1 then
          wi.changesperweek
         else
          wi.maxinventory
       end) Quantity,
       (case
         when plpc.billingmethod = 1 then
          pack_price.Rent_Price(c.customer_id,
                                prd.product_id,
                                sz.sizedefinition_id,
                                fm.FINISHINGMETHOD_ID,
                                sysdate,
                                wi.changesperweek)
         else
          pack_price.Rent_Price(c.customer_id,
                                prd.product_id,
                                sz.sizedefinition_id,
                                fm.FINISHINGMETHOD_ID,
                                sysdate)
       end) RentPrice,
       w.wearernumber WearerNumber,
       w.fullname WearerName,
       l.code LanguageCode,
       to_number(getweeknumber(wi.temporaryrentstopstartdate)) StartWeek,
       to_number(getweeknumber(wi.temporaryrentstopenddate)) EndWeek
  from customer          c,
       product           prd,
       sizedefinition    sz,
       finishingmethod   fm,
       languages         l,
       wearer            w,
       weareremployment  we,
       wearerinventory   wi
   join productlistpercustomer plpc
    on (wi.product_id = plpc.product_id and
       (wi.sizedefinition_id = plpc.sizedefinition_id or
       (plpc.sizedefinition_id in
       (select sd.sizedefinition_id
             from sizedefinition sd
            where sd.code = '*'))) and plpc.billingmethod in (1, 3) and
       wi.finishingmethod_id = plpc.finishingmethod_id and
       plpc.dateactive <= trunc(sysdate) and
       plpc.dateinactive >= trunc(sysdate))
 where c.customer_id = plpc.customer_id
   and w.customer_id = c.customer_id
   and we.wearer_id = w.wearer_id
   and wi.weareremployment_id = we.weareremployment_id
   and wi.dateactive <= trunc(sysdate)
   and wi.dateinactive >= trunc(sysdate)
   and wi.product_id = prd.product_id
   and wi.sizedefinition_id = sz.sizedefinition_id
   and wi.finishingmethod_id = fm.finishingmethod_id
   and year(wi.temporaryrentstopstartdate) =
       to_number(to_char(sysdate, 'YYYY'))
   and year(wi.temporaryrentstopenddate) =
       to_number(to_char(sysdate, 'YYYY'))
   and prd.typeofmerchandise = 2
/

  CREATE OR REPLACE VIEW "V_CUSTOMERSPECIALCHARGE" ("CUSTOMERNUMBER", "CUSTOMERNAME", "SPECIALCHARGECODE", "SPECIALCHARGEDESCRIPTION", "STARTDATE", "NEWSPECIFICPERCENTAGE", "OLDSPECIFICPERCENTAGE", "NEWSPECIFICAMOUNT", "OLDSPECIFICAMOUNT", "OVERRULED", "TIMESTAMP", "SYSTEMUSER_ID", "LANGUAGECODE", "FIXEDAMOUNT", "FREQUENCY", "MINIMUMAMOUNT", "CUSTOMER_ID") AS 
  select c.customernumber, c.name customername, b.code specialchargecode,
( select x.description from specialcharge_desc x where x.specialcharge_id = a.specialcharge_id and x.language_id = languages.language_id) specialchargedescription,
b.startdate,
case when b.fixedamount<>'Y'
         then pack_price.SpecialCharge_Percentage(c.customer_id, b.specialcharge_id, sysdate)
         else 0
       end newspecificpercentage, 0 oldspecificpercentage,
case when b.fixedamount='Y'
         then pack_price.SpecialCharge_Price(c.customer_id, b.specialcharge_id, sysdate)
         else 0
       end newspecificamount, 0 oldspecificamount,
'N' overruled, a.timestamp, a.systemuser_id, languages.code languagecode,
b.fixedamount, b.frequency, 0 minimumamount, c.customer_id
from customerspecialcharge a, specialcharge b, customer c, languages
where a.specialcharge_id = b.specialcharge_id
and a.customer_id = c.customer_id
/

  CREATE OR REPLACE VIEW "V_CUSTOMERSPERBU" ("REPORTPARAM_ID", "CUSTOMER_ID", "BUFILTERED") AS 
  select /*version 2.0*/
       rp.reportparam_id, c.customer_id, 1 bufiltered
  from customer c
       join reportparam rp on c.defaultbusinessunit_id = rp.number_value9
union
select rp.reportparam_id, ca.customer_id, 1 bufiltered
  from customeractivities ca
       join reportparam rp on ca.processbusinessunit_id = rp.number_value9
union all
select rp.reportparam_id, c.customer_id, -1 bufiltered
  from customer c
       cross join reportparam rp
/

  CREATE OR REPLACE VIEW "V_CUSTOMERSPERBUSINESSUNIT" ("BUSINESSUNIT_ID", "CUSTOMER_ID") AS 
  select defaultbusinessunit_id, customer_id
	from customer
union
select defaultinvoicebusinessunit_id, customer_id
	from customer
union
select invoicebusinessunit_id, customer_id
	from customeractivities
union
select processbusinessunit_id, customer_id
	from customeractivities
/

  CREATE OR REPLACE VIEW "V_CUSTOMERSPERBUSINESSUNITD" ("BUSINESSUNIT_ID", "CUSTOMER_ID") AS 
  select defaultbusinessunit_id, customer_id
  from customer
/

  CREATE OR REPLACE VIEW "V_CUSTOMERSPERBUSINESSUNITDI" ("BUSINESSUNIT_ID", "CUSTOMER_ID") AS 
  select defaultbusinessunit_id, customer_id
	from customer
union
select invoicebusinessunit_id, customer_id
	from customeractivities
/

  CREATE OR REPLACE VIEW "V_CUSTOMERSPERBUSINESSUNITDIC" ("BUSINESSUNIT_ID", "CUSTOMER_ID") AS 
  select defaultbusinessunit_id, customer_id
	from customer
union
select internalprocessingbu_id, customer_id
  from customeractivities
/

  CREATE OR REPLACE VIEW "V_CUSTOMERSPERBUSINESSUNITDNOI" ("BUSINESSUNIT_ID", "CUSTOMER_ID") AS 
  select defaultbusinessunit_id, customer_id
  from customer
   where not exists (select ca.activity_id from customeractivities ca where ca.customer_id = customer_id)
union
select invoicebusinessunit_id, customer_id
  from customeractivities
/

  CREATE OR REPLACE VIEW "V_CUSTOMERSPERBUSINESSUNITDPIC" ("BUSINESSUNIT_ID", "CUSTOMER_ID") AS 
  select defaultbusinessunit_id, customer_id
  from customer
union
select processbusinessunit_id, customer_id
  from customeractivities
union
select internalprocessingbu_id, customer_id
  from customeractivities
/

  CREATE OR REPLACE VIEW "V_CUSTOMERSPERBU_DPI" ("REPORTPARAM_ID", "CUSTOMER_ID", "BUFILTERED") AS 
  select rp.reportparam_id, c.customer_id, 1 bufiltered
from customer c, reportparam rp
where c.defaultbusinessunit_id = rp.number_value9
union
select rp.reportparam_id, ca.customer_id, 1 bufiltered
from customeractivities ca, reportparam rp
where ca.processbusinessunit_id = rp.number_value9
or ca.invoicebusinessunit_id = rp.number_value9
union all
select rp.reportparam_id, c.customer_id, -1 bufiltered
from customer c, reportparam rp
/

  CREATE OR REPLACE VIEW "V_CUSTOMERSPERPLANTDP" ("PLANT_ID", "CUSTOMER_ID") AS 
  select b.plant_id, c.customer_id
	from customer c inner join businessunit b on c.defaultbusinessunit_id = b.businessunit_id
union
select b.plant_id, ca.customer_id
  from customeractivities ca inner join businessunit b on ca.processbusinessunit_id = b.businessunit_id
/

  CREATE OR REPLACE VIEW "V_CUSTOMERSTICKER" ("CLIENTDELIVERYNOTE_ID", "CLIENTDELIVERYNOTENUMBER", "DELIVERYDATE", "ROOMNUMBER", "CLIENTNUMBER", "CLIENTNAME", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENT") AS 
  select cd.clientdeliverynote_id, cd.clientdeliverynotenumber, cd.deliverydate,
  cd.roomnumber,
  cl.clientnumber, cl.name clientname,
  cu.customernumber, cu.name customername,
  CAST((CASE
    WHEN coalesce(crs.customerclients, 1) = 0
      THEN (select CONCATENATE3(LTRIM(CASTNUMBERASVARCHARWITHFORMAT(d.departmentnumber, '999999999999')), '/', d.description)
            from clientresident cr, departmentroom dr, department d
            where cl.client_id = cr.client_id
              and cr.departmentroom_id = dr.departmentroom_id
              and dr.department_id = d.department_id)
      else (select CONCATENATE3(LTRIM(CASTNUMBERASVARCHARWITHFORMAT(d2.departmentnumber, '999999999999')), '/', d2.description)
            from clientprivateperson cp, distributionpoint dip, department d2
            where cl.client_id = cp.client_id
              and cp.distributionpoint_id = dip.distributionpoint_id
              and dip.department_id = d2.department_id)
      end) AS VARCHAR2(100)) department
from clientdeliverynote cd, client cl,
  customer cu
    left outer join customerresidentialsettings crs on cu.customer_id = crs.customer_id
where cd.client_link_id = cl.client_id
  and cd.customer_link_id = cu.customer_id
/

  CREATE OR REPLACE VIEW "V_CUSTOMERSURVEYSCHEDULE" ("SURVEYINTERVAL", "LASTSURVEYDATE", "DEFAULTBUSINESSUNIT_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "SURVEY_CODE", "SURVEY_DESCRIPTION", "SURVEY_FREQUENCY", "NEXTSURVEYDATE", "EMPLOYEENUMBER", "EMPLOYEENAME", "REPORTPARAM_ID") AS 
  select /*version 2.0*/
       csvt.surveyinterval, csvt.lastsurveydate,
       cu.defaultbusinessunit_id, cu.customernumber, cu.name customername,
       svt.code survey_code, svt.description survey_description,
       svt.frequency survey_frequency, csvt.nextsurveydate,
       e.employeenumber, e.name employeename, rp.reportparam_id
  from customersurveytype csvt
       left join employee e on csvt.employee_id = e.employee_id
       join surveytype svt on csvt.surveytype_id = svt.surveytype_id
       join customer cu on csvt.customer_id = cu.customer_id
       cross join reportparam rp
 where svt.code >= rp.string_value1
   and svt.code <= rp.string_value2
   and cu.customernumber >= rp.number_value1
   and cu.customernumber <= rp.number_value2
   and nvl(e.employeenumber, rp.number_value3) >= rp.number_value3
   and nvl(e.employeenumber, rp.number_value4) <= rp.number_value4
   and nvl(csvt.lastsurveydate, rp.date_value1) >= rp.date_value1
   and nvl(csvt.lastsurveydate, rp.date_value2) <= rp.date_value2
   and csvt.nextsurveydate >= rp.date_value3
   and csvt.nextsurveydate <= rp.date_value4
   and (cu.defaultbusinessunit_id = rp.number_value9
        or exists
        (select 1
           from customeractivities ca
          where ca.customer_id = cu.customer_id
            and ca.processbusinessunit_id = rp.number_value9))
   and cu.active = 'Y'
   and cu.dateinactive >= trunc(sysdate)
/

  CREATE OR REPLACE VIEW "V_CUSTOMERTAXAREAID" ("CUSTOMER_ID", "CUSTOMERNUMBER", "NAME", "DATEACTIVE", "LEGACYCUSTOMERNUMBER", "DEBTOR_ID", "DEBTOR_NR", "DEBTOR_NAME", "DEBTOR_DATEACTIVE", "DEBTOR_LEGACYNUMBER", "CUST_USERNAME", "CUST_FULLNAME", "CUST_ACTIVE", "BU_CODE", "BU_DESC", "PLANT_CODE", "PLANT_NAME", "DEPO", "VTAXAREAID", "VTIMESTAMP", "VCONFIDENCEINDICATOR", "VUSERNAME", "VFULLNAME", "VACTIVE", "VMSETUSERNAME", "VMSETFULLNAME", "VMSETACTIVE", "VSTREET", "VSTREET2", "VCITY", "VCOUNTY", "VSTATE", "VZIPCODE", "VATIMESTAMP", "VAFULLNAME", "COUNTRY_CODE", "COUNTRY_DESC", "MTAXAREAID", "MTIMESTAMP", "MCONFIDENCEINDICATOR", "MUSERNAME", "MFULLNAME", "MACTIVE", "MMSETUSERNAME", "MMSETFULLNAME", "MMSETACTIVE", "MSTREET", "MSTREET2", "MCITY", "MCOUNTY", "MSTATE", "MZIPCODE", "MATIMESTAMP", "MAFULLNAME", "ITAXAREAID", "ITIMESTAMP", "ICONFIDENCEINDICATOR", "IUSERNAME", "IFULLNAME", "IACTIVE", "IMSETUSERNAME", "IMSETFULLNAME", "IMSETACTIVE", "ISTREET", "ISTREET2", "ICITY", "ICOUNTY", "ISTATE", "IZIPCODE", "IATIMESTAMP", "IAFULLNAME") AS 
  select cu.customer_id, cu.customernumber, cu.name, cu.dateactive, cu.legacycustomernumber,
       deb.customer_id debtor_id, deb.customernumber debtor_nr, deb.name debtor_name,
       deb.dateactive debtor_dateactive, deb.legacycustomernumber debtor_legacynumber,
       null cust_username, null cust_fullname, sysdate cust_active,
       bu.code bu_code, bu.description bu_desc, pl.code plant_code, pl.name plant_name,
       (select min(de.code) from route ro, depot de where ro.plant_id = pl.plant_id and de.depot_id = ro.depot_id
               ) Depo,
       vata.taxareaid vtaxareaid, trunc(vata.timestamp) vtimestamp, vata.confidenceindicator vconfidenceindicator,
       vsu.username vusername, vsu.fullname vfullname, vsu.active vactive,
       vmsu.username vmsetusername, vmsu.fullname vmsetfullname, vmsu.active vmsetactive,
       vad.street vstreet, vad.street2 vstreet2, vad.city vcity,
       vad.county vcounty, vad.state vstate, vad.zipcode vzipcode,
       trunc(vad.timestamp) vatimestamp,
       (select vasu.fullname from systemuser vasu where vasu.systemuser_id = vad.systemuser_id) vafullname,
       co.code country_code, co.description country_desc,
       mata.taxareaid mtaxareaid, trunc(mata.timestamp) mtimestamp, mata.confidenceindicator mconfidenceindicator,
       msu.username musername, msu.fullname mfullname, msu.active mactive,
       mmsu.username mmsetusername, mmsu.fullname mmsetfullname, mmsu.active mmsetactive,
       mad.street mstreet, mad.street2 mstreet2, mad.city mcity,
       mad.county mcounty, mad.state mstate, mad.zipcode mzipcode,
       trunc(mad.timestamp) matimestamp,
       (select masu.fullname from systemuser masu where masu.systemuser_id = mad.systemuser_id) mafullname,
       iata.taxareaid itaxareaid, trunc(iata.timestamp) itimestamp, iata.confidenceindicator iconfidenceindicator,
       isu.username iusername, isu.fullname ifullname, isu.active iactive,
       imsu.username imsetusername, imsu.fullname imsetfullname, imsu.active imsetactive,
       iad.street istreet, iad.street2 istreet2, iad.city icity,
       iad.county icounty, iad.state istate, iad.zipcode izipcode,
       trunc(iad.timestamp) iatimestamp,
       (select iasu.fullname from systemuser iasu where iasu.systemuser_id = iad.systemuser_id) iafullname
from customer cu
     inner join customer deb on cu.debtor_id = deb.customer_id
     inner join businessunit bu
           inner join plant pl on bu.plant_id = pl.plant_id
     on cu.defaultinvoicebusinessunit_id = bu.businessunit_id
     inner join country co on cu.country_id = co.country_id
     inner join address vad
           left outer join AddressTaxAreaID vata
                 inner join systemuser vsu on vata.systemuser_id = vsu.systemuser_id
                 left outer join systemuser vmsu on vata.manuallysetsystemuser_id = vmsu.systemuser_id
           on vad.address_id = vata.address_id
     on cu.visitaddress_id = vad.address_id
     inner join address mad
           left outer join AddressTaxAreaID mata
                 inner join systemuser msu on mata.systemuser_id = msu.systemuser_id
                 left outer join systemuser mmsu on mata.manuallysetsystemuser_id = mmsu.systemuser_id
           on mad.address_id = mata.address_id
     on cu.mailaddress_id = mad.address_id
     left outer join address iad
           left outer join AddressTaxAreaID iata
                 inner join systemuser isu on iata.systemuser_id = isu.systemuser_id
                 left outer join systemuser imsu on iata.manuallysetsystemuser_id = imsu.systemuser_id
           on iad.address_id = iata.address_id
     on cu.invoiceaddress_id = iad.address_id
/

  CREATE OR REPLACE VIEW "V_CUSTOMERWASHDISCOUNT" ("CUSTOMERNUMBER", "CUSTOMERNAME", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "STARTDATE", "DISCOUNT", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME,
 PRODUCT.CODE,
 (SELECT description FROM PRODUCT_DESC A WHERE A.PRODUCT_ID = PRODUCTLISTPERCUSTOMER.PRODUCT_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
 SIZEDEFINITION.CODE,
 (SELECT description FROM SIZEDEFINITION_DESC B WHERE B.SIZEDEFINITION_ID = PRODUCTLISTPERCUSTOMER.SIZEDEFINITION_ID
  AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) sizedefinitiondescription,
 FINISHINGMETHOD.CODE,
 (SELECT description FROM FINISHINGMETHOD_DESC C WHERE C.FINISHINGMETHOD_ID = PRODUCTLISTPERCUSTOMER.FINISHINGMETHOD_ID
  AND C.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddescription,
 CUSTOMERWASHDISCOUNT.STARTDATE,CUSTOMERWASHDISCOUNT.DISCOUNT,
 CUSTOMERWASHDISCOUNT.SYSTEMUSER_ID, CUSTOMERWASHDISCOUNT.TIMESTAMP, LANGUAGES.CODE
FROM CUSTOMERWASHDISCOUNT, CUSTOMER, PRODUCTLISTPERCUSTOMER, PRODUCT, SIZEDEFINITION, FINISHINGMETHOD, LANGUAGES
WHERE CUSTOMERWASHDISCOUNT.PRODUCTLISTPERCUSTOMER_ID = PRODUCTLISTPERCUSTOMER.PRODUCTLISTPERCUSTOMER_ID
 AND PRODUCTLISTPERCUSTOMER.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
 AND PRODUCTLISTPERCUSTOMER.PRODUCT_ID = PRODUCT.PRODUCT_ID
 AND PRODUCTLISTPERCUSTOMER.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
 AND PRODUCTLISTPERCUSTOMER.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
/

  CREATE OR REPLACE VIEW "V_CUSTOMERWASHPRICE" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CURRENCYCODE", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "STARTDATE", "PRICE", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT
 CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, CURRENCY.CODE,
 PRODUCT.CODE,
 (SELECT description FROM PRODUCT_DESC A WHERE A.PRODUCT_ID = PRODUCTLISTPERCUSTOMER.PRODUCT_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
 SIZEDEFINITION.CODE,
 (SELECT description FROM SIZEDEFINITION_DESC B WHERE B.SIZEDEFINITION_ID = PRODUCTLISTPERCUSTOMER.SIZEDEFINITION_ID
  AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) sizedefinitiondescription,
 FINISHINGMETHOD.CODE,
 (SELECT description FROM FINISHINGMETHOD_DESC C WHERE C.FINISHINGMETHOD_ID = PRODUCTLISTPERCUSTOMER.FINISHINGMETHOD_ID
  AND C.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddescription,
 CUSTOMERWASHPRICE.STARTDATE,CUSTOMERWASHPRICE.PRICE,
 CUSTOMERWASHPRICE.SYSTEMUSER_ID, CUSTOMERWASHPRICE.TIMESTAMP, LANGUAGES.CODE
FROM CUSTOMERWASHPRICE, CUSTOMER, CURRENCY, PRODUCTLISTPERCUSTOMER, PRODUCT, SIZEDEFINITION, FINISHINGMETHOD, LANGUAGES
WHERE CUSTOMERWASHPRICE.PRODUCTLISTPERCUSTOMER_ID = PRODUCTLISTPERCUSTOMER.PRODUCTLISTPERCUSTOMER_ID
 AND PRODUCTLISTPERCUSTOMER.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
 AND CUSTOMER.CURRENCY_ID = CURRENCY.CURRENCY_ID
 AND PRODUCTLISTPERCUSTOMER.PRODUCT_ID = PRODUCT.PRODUCT_ID
 AND PRODUCTLISTPERCUSTOMER.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
 AND PRODUCTLISTPERCUSTOMER.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
/

  CREATE OR REPLACE VIEW "V_CUSTPOOLAGEANALYSIS" ("REPORTPARAM_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINT_ID", "CONSPOINTNUMBER", "CONSPOINTDESC", "PRODUCTGROUPCODE", "PRODUCTGROUPDESC", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTDESC", "SIZEDEFINITION_ID", "SIZECODE", "SIZEDESC", "COLUMN1", "COLUMN2", "COLUMN3", "COLUMN4", "COLUMN5", "COLUMN6", "COLUMN7", "COLUMN8", "COLUMN9", "TOTAL_DAYS_AT_CUSTOMER", "TOTAL_STOCK", "QTY_USED", "LANGUAGECODE") AS 
  select /*version 2.1*/
       rp.reportparam_id, cu.customer_id, cu.customernumber, cu.name customername,
       dp.department_id, dp.departmentnumber, dp.description departmentdesc,
       cp.distributionpoint_id, cp.distributionpointnumber conspointnumber,
       cp.description conspointdesc, pg.code productgroupcode,
       (select pgd.description
          from productgroup_desc pgd
         where pgd.productgroup_id = pg.productgroup_id
           and pgd.language_id = lan.language_id) productgroupdesc,
       prd.product_id, prd.code productcode,
       (select prde.description
          from product_desc prde
         where prde.product_id = prd.product_id
           and prde.language_id = lan.language_id) productdesc,
       sd.sizedefinition_id, sd.code sizecode,
       (select sde.description
          from sizedefinition_desc sde
         where sde.sizedefinition_id = sd.sizedefinition_id
           and sde.language_id = lan.language_id) sizedesc,
       sum(case when floor((trunc(sysdate) - trunc(uq.lastoutscandate)) / rp.number_value3) + 1 = 1
                then 1
                else 0 end) column1,
       sum(case when floor((trunc(sysdate) - trunc(uq.lastoutscandate)) / rp.number_value3) + 1 = 2
                then 1
                else 0 end) column2,
       sum(case when floor((trunc(sysdate) - trunc(uq.lastoutscandate)) / rp.number_value3) + 1 = 3
                then 1
                else 0 end) column3,
       sum(case when floor((trunc(sysdate) - trunc(uq.lastoutscandate)) / rp.number_value3) + 1 = 4
                then 1
                else 0 end) column4,
       sum(case when floor((trunc(sysdate) - trunc(uq.lastoutscandate)) / rp.number_value3) + 1 = 5
                then 1
                else 0 end) column5,
       sum(case when floor((trunc(sysdate) - trunc(uq.lastoutscandate)) / rp.number_value3) + 1 = 6
                then 1
                else 0 end) column6,
       sum(case when floor((trunc(sysdate) - trunc(uq.lastoutscandate)) / rp.number_value3) + 1 = 7
                then 1
                else 0 end) column7,
       sum(case when floor((trunc(sysdate) - trunc(uq.lastoutscandate)) / rp.number_value3) + 1 = 8
                then 1
                else 0 end) column8,
       sum(case when floor((trunc(sysdate) - trunc(uq.lastoutscandate)) / rp.number_value3) + 1 >= 9
                then 1
                else 0 end) column9,
       sum(trunc(sysdate) - trunc(uq.lastoutscandate)) total_days_at_customer,
       count(1) total_stock,
       0 qty_used, lan.code languagecode
  from reportparam rp
       join customer cu on rp.number_value = cu.customer_id
       join department dp
            join distributionpoint cp
                 join uniqueitem uq
                      join product prd
                           join productgroup pg on prd.productgroup_id = pg.productgroup_id
                      on uq.product_id = prd.product_id
                      join sizedefinition sd on uq.sizedefinition_id = sd.sizedefinition_id
                 on cp.distributionpoint_id = uq.distributionpoint_id
            on dp.department_id = cp.department_id
       on rp.number_value = dp.customer_id
       cross join languages lan
 where uq.customerowned = 'N' and uq.poolitem = 1 and prd.uniquepoolitem = 'Y'
   and uq.status_id in (select s1.status_id
                          from status s1
                         where s1.statustype = 'UI'
                           and s1.code in ('20', '30'))
   and uq.stay_id in (select s2.stay_id
                        from stay s2
                       where s2.staytype = 1
                         and s2.staynr between 20 and 27)
   and (rp.string_value8 = 'Y' or
       (rp.string_value8 <> 'Y' and not exists (select 1
                                                  from uniqueitemloss uil
                                                 where uil.uniqueitem_link_id = uq.uniqueitem_id
                                                   and uil.lossstatus in (0, 1))))
   and (trunc(sysdate) - trunc(uq.lastoutscandate)) <= rp.number_value4
 group by rp.reportparam_id, cu.customer_id, cu.customernumber, cu.name, dp.department_id, dp.departmentnumber, dp.description,
          cp.distributionpoint_id, cp.distributionpointnumber, cp.description, pg.code, pg.productgroup_id,
          lan.language_id, lan.code, prd.product_id, prd.code, sd.sizedefinition_id, sd.code
 union all -- second part of union: select delivery history for average daily usage
select rp.reportparam_id, cu.customer_id, cu.customernumber, cu.name customername,
       dp.department_id, dp.departmentnumber, dp.description departmentdesc,
       cp.distributionpoint_id, cp.distributionpointnumber conspointnumber,
       cp.description conspointdesc, pg.code productgroupcode,
       (select pgd.description
          from productgroup_desc pgd
         where pgd.productgroup_id = pg.productgroup_id
           and pgd.language_id = lan.language_id) productgroupdesc,
       prd.product_id, prd.code productcode,
       (select prde.description
          from product_desc prde
         where prde.product_id = prd.product_id
           and prde.language_id = lan.language_id) productdesc,
       sd.sizedefinition_id, sd.code sizecode,
       (select sde.description
          from sizedefinition_desc sde
         where sde.sizedefinition_id = sd.sizedefinition_id
           and sde.language_id = lan.language_id) sizedesc,
       0 column1,
       0 column2,
       0 column3,
       0 column4,
       0 column5,
       0 column6,
       0 column7,
       0 column8,
       0 column9,
       0 total_days_at_customer,
       0 total_stock,
       sum(dh.amountdelivered) qty_used,
       lan.code languagecode
  from reportparam rp
       join deliveryhistory dh
            join distributionpoint_link cp on dh.distributionpoint_link_id = cp.distributionpoint_link_id
            join department_link dp on dh.department_link_id = dp.department_link_id
            join customer_link cu on dh.customer_link_id = cu.customer_link_id
            join product prd
                 join productgroup pg on prd.productgroup_id = pg.productgroup_id
            on dh.product_link_id = prd.product_id
            join sizedefinition sd on dh.sizedefinition_link_id = sd.sizedefinition_id
       on rp.number_value = dh.customer_link_id
       cross join languages lan
 where prd.uniquepoolitem = 'Y'
   and dh.deliverydate >= rp.date_value1
   and dh.deliverydate <= rp.date_value2
 group by rp.reportparam_id, cu.customer_id, cu.customernumber, cu.name, dp.department_id, dp.departmentnumber, dp.description,
          cp.distributionpoint_id, cp.distributionpointnumber, cp.description, pg.code, pg.productgroup_id,
          lan.language_id, lan.code, prd.product_id, prd.code, sd.sizedefinition_id, sd.code
/

  CREATE OR REPLACE VIEW "V_DAILYBULKPUTUPSHORTAGES" ("LINETYPE", "BUSINESSUNIT_ID", "PROCESSBUCODE", "PROCESSBUDESCRIPTION", "DEPOTCODE", "DEPOTDESCRIPTION", "ROUTECODE", "ROUTENUMBER", "ROUTEDESCRIPTION", "DRIVINGDATE", "ORIGINALDRIVINGDATE", "PRODUCTGROUPCODE", "PRODUCTCODE", "SIZECODE", "SEQUENCENUMBER", "PROD_PACKINGSEQUENCE", "PRODUCTGROUPDESC", "PRODUCTDESCRIPTION", "SIZEDESCRIPTION", "COLOR", "LOCATIONCODE", "BULKPUTUPROUTECOMPLETED", "TYPE", "QUANTITYTOBEPACKED", "QUANTITYPACKED", "QUANTITYSHORTAGE", "LANGUAGECODE", "LANGUAGE_ID") AS 
  select 1 linetype, bu.businessunit_id, bu.code processbucode, bu.description processbudescription,
       de.code depotcode, de.description depotdescription,
       r.routecode, r.routenumber, r.description routedescription, rc.drivingdate, rc.originaldrivingdate,
       pg.code productgroupcode, coalesce(rpa.customproductcode, p.code) productcode, sd.code sizecode,
       rpa.sequencenumber, p.packingsequence prod_packingsequence,
       (select pgde.description
          from productgroup_desc pgde
         where pgde.productgroup_id = p.productgroup_id
           and pgde.language_id = lan.language_id) productgroupdesc,
       coalesce(rpa.customproductdescription,
               (select prde.description
               from product_desc prde
               where prde.product_id = p.product_id
               and prde.language_id = lan.language_id)) productdescription,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedescription,
       (select col.code from color col where col.color_id = p.color_id) color,
       f_getrowlocationprodsizestock(p.product_id, sd.sizedefinition_id,
                             (select min(sr.stockroom_id)
                                from stockroom sr
                               where sr.managedbybu_id = bu.businessunit_id)) locationcode,
       rc.bulkputuproutecompleted, rpa.type, rpa.quantitytobepacked, coalesce(rpa.quantitypacked, 0) quantitypacked,
       (rpa.quantitytobepacked - coalesce(rpa.quantitypacked, 0)) quantityshortage,
       lan.code LanguageCode, lan.language_id
  from routecontrolbulkpacking rpa
  join product p on rpa.product_link_id = p.product_id
  join productgroup pg on p.productgroup_id = pg.productgroup_id
  join sizedefinition sd on rpa.sizedefinition_link_id = sd.sizedefinition_id
  join routecontrol rc on rpa.routecontrol_id = rc.routecontrol_id
  join route r on rc.route_id = r.route_id
  left outer join depot de on r.depot_id = de.depot_id
  , businessunit bu
  join plant pl on bu.plant_id = pl.plant_id
  join languages lan on pl.language_id = lan.language_id
 where (rpa.quantitytobepacked - coalesce(rpa.quantitypacked, 0)) > 0
       and exists (select 1 from stop st, customer cu where st.routecontrol_id = rc.routecontrol_id
                  and st.customer_link_id = cu.customer_id and cu.defaultbusinessunit_id = bu.businessunit_id)
union all --not started RCBPA
select 2 linetype, bu.businessunit_id, bu.code processbucode, bu.description processbudescription,
       de.code depotcode, de.description depotdescription,
       r.routecode, r.routenumber, r.description routedescription, rc.drivingdate, rc.originaldrivingdate,
       pg.code productgroupcode, coalesce(pnl.customcode, p.code) productcode, sd.code sizecode,
       p.packingsequence sequencenumber, p.packingsequence prod_packingsequence,
       (select pgde.description
          from productgroup_desc pgde
         where pgde.productgroup_id = p.productgroup_id
           and pgde.language_id = lan.language_id) productgroupdesc,
       coalesce(pnl.customdescription,
               (select prde.description
                  from product_desc prde
                 where prde.product_id = p.product_id
                   and prde.language_id = lan.language_id)) productdescription,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedescription,
       (select col.code from color col where col.color_id = p.color_id) color,
       f_getrowlocationprodsizestock(p.product_id, sd.sizedefinition_id,
                             (select min(sr.stockroom_id)
                                from stockroom sr
                               where sr.managedbybu_id = bu.businessunit_id)) locationcode,
       rc.bulkputuproutecompleted, null type, pnl.tobedeliveredamount quantitytobepacked, 0 quantitypacked,
       pnl.tobedeliveredamount quantityshortage,
       lan.code LanguageCode, lan.language_id
  from packingnoteline pnl
  join packingnote pn on pnl.packingnote_id = pn.packingnote_id
  join businessunit bu on pn.processbusinessunit_id = bu.businessunit_id
  join plant pl on bu.plant_id = pl.plant_id
  join languages lan on pl.language_id = lan.language_id
  join product p on pnl.product_id = p.product_id
  join productgroup pg on p.productgroup_id = pg.productgroup_id
  join sizedefinition sd on pnl.sizedefinition_id = sd.sizedefinition_id
  join routecontrol rc on pn.routecontrol_id = rc.routecontrol_id
  join route r on rc.route_id = r.route_id
  left outer join depot de on r.depot_id = de.depot_id
 where pnl.putuptype in (2, 4) and pn.status_id <> 8
       and not exists (select 1 from routecontrolbulkpacking rpa where rpa.routecontrol_id = rc.routecontrol_id
                      and rpa.product_link_id = pnl.product_id and rpa.sizedefinition_link_id = pnl.sizedefinition_id
                      and rpa.finishingmethod_id = pnl.finishingmethod_id and (rpa.quantitytobepacked - coalesce(rpa.quantitypacked, 0)) >= 0)
union all --duplicate data for totals section for all routes
select 3 linetype, bu.businessunit_id, bu.code processbucode, bu.description processbudescription,
       null depotcode, null depotdescription,
       r.routecode, r.routenumber, r.description routedescription, rc.drivingdate, rc.originaldrivingdate,
       pg.code productgroupcode, coalesce(rpa.customproductcode, p.code) productcode, sd.code sizecode,
       rpa.sequencenumber, p.packingsequence prod_packingsequence,
       (select pgde.description
          from productgroup_desc pgde
         where pgde.productgroup_id = p.productgroup_id
           and pgde.language_id = lan.language_id) productgroupdesc,
       coalesce(rpa.customproductdescription,
               (select prde.description
                  from product_desc prde
                 where prde.product_id = p.product_id
                   and prde.language_id = lan.language_id)) productdescription,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedescription,
       (select col.code from color col where col.color_id = p.color_id) color,
       f_getrowlocationprodsizestock(p.product_id, sd.sizedefinition_id,
                             (select min(sr.stockroom_id)
                                from stockroom sr
                               where sr.managedbybu_id = bu.businessunit_id)) locationcode,
       rc.bulkputuproutecompleted, rpa.type, rpa.quantitytobepacked, coalesce(rpa.quantitypacked, 0) quantitypacked,
       (rpa.quantitytobepacked - coalesce(rpa.quantitypacked, 0)) quantityshortage,
       lan.code LanguageCode, lan.language_id
  from routecontrolbulkpacking rpa
  join product p on rpa.product_link_id = p.product_id
  join productgroup pg on p.productgroup_id = pg.productgroup_id
  join sizedefinition sd on rpa.sizedefinition_link_id = sd.sizedefinition_id
  join routecontrol rc on rpa.routecontrol_id = rc.routecontrol_id
  join route r on rc.route_id = r.route_id
  , businessunit bu
  join plant pl on bu.plant_id = pl.plant_id
  join languages lan on pl.language_id = lan.language_id
 where (rpa.quantitytobepacked - coalesce(rpa.quantitypacked, 0)) > 0
       and exists (select 1 from stop st, customer cu where st.routecontrol_id = rc.routecontrol_id
                  and st.customer_link_id = cu.customer_id and cu.defaultbusinessunit_id = bu.businessunit_id)
       and rc.bulkputuproutecompleted = 'N'
union all --not started RCBPA
select 4 linetype, bu.businessunit_id, bu.code processbucode, bu.description processbudescription,
       null depotcode, null depotdescription,
       r.routecode, r.routenumber, r.description routedescription, rc.drivingdate, rc.originaldrivingdate,
       pg.code productgroupcode, coalesce(pnl.customcode, p.code) productcode, sd.code sizecode,
       p.packingsequence sequencenumber, p.packingsequence prod_packingsequence,
       (select pgde.description
          from productgroup_desc pgde
         where pgde.productgroup_id = p.productgroup_id
           and pgde.language_id = lan.language_id) productgroupdesc,
       coalesce(pnl.customdescription,
               (select prde.description
                  from product_desc prde
                 where prde.product_id = p.product_id
                   and prde.language_id = lan.language_id)) productdescription,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedescription,
       (select col.code from color col where col.color_id = p.color_id) color,
       f_getrowlocationprodsizestock(p.product_id, sd.sizedefinition_id,
                             (select min(sr.stockroom_id)
                                from stockroom sr
                               where sr.managedbybu_id = bu.businessunit_id)) locationcode,
       rc.bulkputuproutecompleted, null type, pnl.tobedeliveredamount quantitytobepacked, 0 quantitypacked,
       pnl.tobedeliveredamount quantityshortage,
       lan.code LanguageCode, lan.language_id
  from packingnoteline pnl
  join packingnote pn on pnl.packingnote_id = pn.packingnote_id
  join businessunit bu on pn.processbusinessunit_id = bu.businessunit_id
  join plant pl on bu.plant_id = pl.plant_id
  join languages lan on pl.language_id = lan.language_id
  join product p on pnl.product_id = p.product_id
  join productgroup pg on p.productgroup_id = pg.productgroup_id
  join sizedefinition sd on pnl.sizedefinition_id = sd.sizedefinition_id
  join routecontrol rc on pn.routecontrol_id = rc.routecontrol_id
  join route r on rc.route_id = r.route_id
 where pnl.putuptype in (2, 4) and pn.status_id <> 8
       and not exists (select 1 from routecontrolbulkpacking rpa where rpa.routecontrol_id = rc.routecontrol_id
                      and rpa.product_link_id = pnl.product_id and rpa.sizedefinition_link_id = pnl.sizedefinition_id
                      and rpa.finishingmethod_id = pnl.finishingmethod_id and (rpa.quantitytobepacked - coalesce(rpa.quantitypacked, 0)) >= 0)
/

  CREATE OR REPLACE VIEW "V_DAILYDEPOSIT" ("REMITBATCH_ID", "REMITIDENTIFICATION", "ARTRANSACTION_ID", "PAYMENTTYPE", "TYPENUMBER", "ARTRANSACTIONTYPE_ID", "BILLTOCUSTOMER_LINK_ID", "BUSINESSUNITCODE", "BUSINESSUNITDESC", "TRANSACTIONREMITDATE", "REMITDATE", "BATCHNUMBER", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "CHECKREF", "PAYMENTREF", "PAYMENTNOTE", "TOTALAPPLIEDAMOUNT", "GROUPREFERENCE", "DELINQUENTMARKAFTER", "INVOICEAMOUNTDECIMALS", "ROUTENUMBER") AS 
  select /*version 1.0*/
       nvl(ar.remitbatch_id, -1) remitbatch_id, ar.remitidentification, ar.artransaction_id,
       ar.paymenttype, art.typenumber, ar.artransactiontype_id, ar.billtocustomer_link_id,
       bu.code businessunitcode, bu.description businessunitdesc,
       ar.artransactiondate transactionremitdate, rb.batchdate remitdate, rb.batchnumber,
       (select culb.customernumber
          from customer_link culb
         where ar.billtocustomer_link_id = culb.customer_link_id) billtocustomernumber,
       (select culb.name
          from customer_link culb
         where ar.billtocustomer_link_id = culb.customer_link_id) billtocustomername,
       ar.remitidentification checkref, ar.amount paymentref,
       ar.remark paymentnote, ar.totalappliedamount,
       (case when ar.remitidentification is null and ar.remark is null
             then ar.amount || ar.artransaction_id
             when ar.remitidentification is null and ar.remark is not null
             then ar.remark || ar.amount || ar.artransaction_id
             when ar.remitidentification is not null and ar.remark is null
             then ar.remitidentification || ar.amount || ar.artransaction_id
       else ar.remitidentification || ar.remark || ar.amount || ar.artransaction_id end) groupreference,
       (select cb.delinquentmarkafter
          from customerbillinginfo cb
         where ar.billtocustomer_link_id = cb.customer_id) delinquentmarkafter,
       (select cr.invoiceamountdecimals from currency cr where cr.currency_id = ar.currency_id) invoiceamountdecimals,
       (select ro.routenumber from route ro where ro.route_id = ar.route_id) routenumber
  from artransaction ar
       left join remitbatch rb on ar.remitbatch_id = rb.remitbatch_id
       join businessunit bu on ar.businessunit_id = bu.businessunit_id
       join artransactiontype art on ar.artransactiontype_id = art.artransactiontype_id
 where ar.debitcredit = 'C'
/

  CREATE OR REPLACE VIEW "V_DAILYDEPOSIT_DET" ("REMITBATCH_ID", "CLOSINGTRANSACTION_ID", "ARTRANSACTION_ID", "REMITIDENTIFICATION", "BILLTOCUSTOMER_LINK_ID", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "INVOICEDATE", "INVOICENUMBER", "INVOICEAMOUNT", "APPLIEDAMOUNT", "DISCOUNTAMOUNT", "ARTRANSACTIONTYPE_CODE") AS 
  select /*version 1.0*/
       nvl(ar.remitbatch_id, -1) remitbatch_id, ca.creditartransaction_id closingtransaction_id,
       ar.artransaction_id, nvl(ar.remitidentification, '') remitidentification,
       ar.billtocustomer_link_id,
       (select culd.customernumber
          from customer_link culd
         where ar.deltocustomer_link_id = culd.customer_link_id) deltocustomernumber,
       (select culd.name
          from customer_link culd
         where ar.deltocustomer_link_id = culd.customer_link_id) deltocustomername,
       ar.artransactiondate invoicedate, ar.invoicenumber, ar.amount invoiceamount,
       ca.amount appliedamount,
       nvl((select sum(ca1.amount)
              from cashapplication ca1
                   join artransaction ar1
                        join artransactiontype art1 on ar1.artransactiontype_id = art1.artransactiontype_id
                   on ca1.creditartransaction_id = ar1.artransaction_id
             where ar1.invoicenumber = ar.invoicenumber
               and ar1.businessunit_id = ar.businessunit_id
               and ar1.billtocustomer_link_id = ar.billtocustomer_link_id
               and art1.typenumber = 4
               and ca1.unapplied_yn = 'N'), 0) discountamount,
       (select art.code
          from artransactiontype art
         where art.artransactiontype_id = ar.artransactiontype_id) artransactiontype_code
  from cashapplication ca
       join artransaction ar on ca.debitartransaction_id = ar.artransaction_id
 where ar.debitcredit = 'D' and ca.unapplied_yn = 'N'
/

  CREATE OR REPLACE VIEW "V_DAY" ("DAYNUMBER", "CODE", "DESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP", "DAY_ID", "LANGUAGECODE") AS 
  SELECT DAY.DAYNUMBER,
(SELECT CODE FROM DAY_DESC A WHERE A.DAY_ID = DAY.DAY_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) CODE,
(SELECT DESCRIPTION FROM DAY_DESC B WHERE B.DAY_ID = DAY.DAY_ID AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) DESCRIPTION,
DAY.SYSTEMUSER_ID, DAY.TIMESTAMP, DAY.DAY_ID, LANGUAGES.CODE AS LANGUAGECODE
FROM DAY, LANGUAGES
/

  CREATE OR REPLACE VIEW "V_DELANDPICKCONTAINERS" ("DRIVINGDATE", "ROUTENUMBER", "STOPNUMBER", "STOP_ID", "CUSTOMERNUMBER", "CUSTNAME", "DELPOINTCODE", "DELPOINTDESC", "PERSONIDENTIFICATION", "SIGNATURE", "HASSIGNATURE", "DRIVERNAME", "SIGNATUREDATE", "SIGNATURETIME", "SIGNATURETIME24", "BARCODE", "BARCODEDATE", "BARCODETIME24", "SCANNEDYN", "NAME", "ZIPCODE", "CITY", "STREET", "DRIVDATEP", "SIGNATUREDATEP") AS 
  SELECT
rc.drivingdate, r.routenumber, stop.stopnumber, stop.stop_id ,
c.customernumber, c.name custname,
dp.code delpointcode, dp.description delpointdesc
, dsig.personidentification personidentification
, dsig.signature signature,
(case when length(dsig.signature) > 0 then 1
  else 0 end) hassignature,
( select max(empl.name) from  employee empl where  rc.drivernumber=empl.employeenumber)drivername,
 dsig.timestamp  signaturedate
, to_char(dsig.scantimestamp,'fmhhfm:MI.AM') signaturetime
, to_char(stop.departuretime,'fmhh24fm:MI')signaturetime24
, dsig.barcode
, dsig.scantimestamp Barcodedate
, to_char(dsig.scantimestamp,'fmhh24fm:MI') Barcodetime24,dsig.scannedyn,
pl.name, a.zipcode, a.city, a.street,
cast((to_char(rc.drivingdate,'DD.MM.YYYY'))as varchar2(12))DrivDateP,
cast((to_char(dsig.timestamp,'DD.MM.YYYY'))as varchar2(12))signaturedateP
from  customer c,
stop left outer join deliverysignature dsig on stop.stop_id=dsig.stop_id
left outer join deliverypoint dp on stop.deliverypoint_id=dp.deliverypoint_id
,routecontrol rc, route r, plant pl, address a
where stop.customer_link_id=c.customer_id
and stop.routecontrol_id=rc.routecontrol_id
and rc.route_id=r.route_id
and rc.plant_id=pl.plant_id
and pl.address_id=a.address_id
and nvl(dp.customer_id, c.customer_id)=c.customer_id
and rc.pocketpcstatus >= 2
and stop.emailstatuscntusagerpt > 0
and rc.emailstatuscntusagerpt > 0
/

  CREATE OR REPLACE VIEW "V_DELCONTAINERS" ("STOP_ID", "TIMESTAMP", "TIMECH24", "PRIMARYID", "CONTAINER_ID", "CODE", "CTYPEDESC", "NOTENUMBER", "DEPARTMENTNUMBER", "DEPARTDESCR") AS 
  SELECT
st.stop_id,rt.timestamp,
(to_char(rt.timestamp,'DD.MM.YYYY')|| ' ' ||to_char(rt.timestamp,'fmhh24fm:MI'))TIMECH24,
nvl(cnt.primaryid, rt.stringvalue1) primaryid, cnt.container_id, NVL(ct.code, 'Standard Container') code,
(select ct_desc.description from containertype_desc ct_desc where ct_desc.containertype_id=ct.containertype_id
and ct_desc.language_id=c.language_id) ctypedesc,
(select min(pn.notenumber) from  packingnote pn , packingnotecontainer pnc where  pn.packingnote_id=pnc.packingnote_id
        and pn.stop_id=st.stop_id and pnc.container_id=cnt.container_id)notenumber,
( select min(d.departmentnumber) from packingnote pn , packingnotecontainer pnc, distributionpoint dp, department d
         where  pn.packingnote_id=pnc.packingnote_id
        and pn.stop_id=st.stop_id and pnc.container_id=cnt.container_id
        and pn.distributionpoint_id=dp.distributionpoint_id and dp.department_id=d.department_id and d.customer_id=c.customer_id) departmentnumber,
(select d1.description from department d1 where d1.customer_id =c.customer_id
        and d1.departmentnumber=  (select min(d.departmentnumber) from packingnote pn , packingnotecontainer pnc, distributionpoint dp, department d
         where  pn.packingnote_id=pnc.packingnote_id and pn.stop_id=st.stop_id and pnc.container_id=cnt.container_id
         and pn.distributionpoint_id=dp.distributionpoint_id and dp.department_id=d.department_id and d.customer_id=c.customer_id))  departdescr
from  stop st ,routetransaction rt, container cnt, containertype ct, customer c
where st.routecontrol_id=rt.routecontrol_id
and st.stop_id=rt.stop_id
and st.customer_link_id=c.customer_id
and rt.routetransactiontype_id=212--unload
and rt.stringvalue1=cnt.primaryid(+)
and cnt.containertype_id=ct.containertype_id(+)
/

  CREATE OR REPLACE VIEW "V_DELHISTORY_YEAR_MONTH" ("CUSTOMER_ID", "YEAR_MONTH", "PROCESSBUSINESSUNIT_ID", "AMT_DELIVERED", "CUSTOMERNUMBER", "CUSTNAME", "CUSTOMERLANGUAGECODE", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINTNUMBER", "DIP_DESC", "PRODUCTGROUPCODE", "PRODUCTGROUPDESCRIPTION", "PRODUCTCODE", "TYPEOFMERCHANDISE", "PRODUCTDESCRIPTION", "PARENTPRODUCTCODE", "PARENTPRODUCTDESCRIPTION", "SIZECODE", "SIZEDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "PACKINDICATION", "LANGUAGE_CODE", "WIDTH_S", "LENGTH_S") AS 
  SELECT CL.CUSTOMER_ID,
       YEAR(h.deliverydate)*100+MONTH(h.deliverydate) Year_Month,
       H.PROCESSBUSINESSUNIT_ID,
       SUM(H.AMOUNTDELIVERED) AMT_DELIVERED,
       CL.CUSTOMERNUMBER, CL.NAME custname, cl.LANGUAGECODE CUSTOMERLANGUAGECODE,
       dl.departmentnumber, dl.description departmentdesc,
       dpl.distributionpointnumber, dpl.description dip_desc,
       pg.CODE productgroupcode,
       (SELECT A.DESCRIPTION FROM PRODUCTGROUP_DESC A WHERE A.PRODUCTGROUP_ID = pg.PRODUCTGROUP_ID
                AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productgroupdescription,
       pl.CODE productcode, PRODUCT.typeofmerchandise,
       (SELECT B.DESCRIPTION FROM PRODUCT_LINK_DESC B WHERE B.PRODUCT_LINK_ID = h.PRODUCT_LINK_ID
                AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
       parentproduct.CODE parentproductcode,
       (SELECT E.DESCRIPTION FROM PRODUCT_LINK_DESC E WHERE E.PRODUCT_LINK_ID = h.PARENTPRODUCT_LINK_ID
                AND E.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) parentproductdescription,
       sl.CODE sizecode,
       (SELECT C.DESCRIPTION FROM SIZEDEFINITION_LINK_DESC C WHERE C.SIZEDEFINITION_LINK_ID = h.SIZEDEFINITION_LINK_ID
                AND C.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEdescription,
       fm.CODE FINISHINGMETHODCODE,
       (SELECT D.DESCRIPTION FROM FINISHINGMETHOD_DESC D WHERE D.FINISHINGMETHOD_ID = h.FINISHINGMETHOD_ID
                AND D.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODdescription,
       h.packindication,
       languages.code language_code,
       s.WIDTH WIDTH_S,s.LENGTH LENGTH_S--CSW
FROM DELIVERYHISTORY H LEFT OUTER JOIN PRODUCT ON (H.PRODUCT_LINK_ID = PRODUCT.PRODUCT_ID)
     LEFT OUTER JOIN SIZEDEFINITION S ON (H.SIZEDEFINITION_LINK_ID = S.SIZEDEFINITION_ID),--CSW
     CUSTOMER_LINK CL, department_link dl, distributionpoint_link dpl,
     PRODUCT_LINK pl LEFT OUTER JOIN PRODUCTGROUP pg ON (pl.PRODUCTGROUPCODE = pg.CODE),
     PRODUCT_LINK parentproduct,
     sizedefinition_link sl, FINISHINGMETHOD fm,
     languages--, reportparam rp
WHERE H.CUSTOMER_LINK_ID = CL.CUSTOMER_LINK_ID
      and h.department_link_id = dl.department_link_id
      and h.distributionpoint_link_id = dpl.distributionpoint_link_id
      and h.product_link_id = pl.product_link_id
      and h.sizedefinition_link_id = sl.sizedefinition_link_id
      and h.finishingmethod_id = fm.finishingmethod_id
      AND h.PARENTPRODUCT_LINK_ID = parentproduct.PRODUCT_LINK_ID
GROUP BY
      CL.CUSTOMER_ID,
       YEAR(h.deliverydate)*100+MONTH(h.deliverydate),
       H.PROCESSBUSINESSUNIT_ID,
       CL.CUSTOMERNUMBER, CL.NAME, cl.LANGUAGECODE,
       dl.departmentnumber, dl.description,
       dpl.distributionpointnumber, dpl.description,
       pg.CODE,
       pg.PRODUCTGROUP_ID,
       LANGUAGES.LANGUAGE_ID,
       pl.CODE, PRODUCT.typeofmerchandise,
       h.PRODUCT_LINK_ID,
       parentproduct.CODE ,
       h.PARENTPRODUCT_LINK_ID,
       sl.CODE,
       h.SIZEDEFINITION_LINK_ID,
       fm.CODE,
       h.FINISHINGMETHOD_ID,
       h.packindication,
       languages.code,
       s.WIDTH,s.LENGTH
/

  CREATE OR REPLACE VIEW "V_DELINQUENCYLETTER_DET" ("BILLTOCUSTOMER_LINK_ID", "AMOUNT", "INVOICENUMBER", "INVOICEDATE", "ARTRANSACTIONDATE", "DUEDATE") AS 
  SELECT COALESCE(ART.BILLTOCUSTOMER_LINK_ID, ART.DELTOCUSTOMER_LINK_ID) BILLTOCUSTOMER_LINK_ID
, (ART.AMOUNT - ART.TOTALAPPLIEDAMOUNT) AMOUNT, ART.INVOICENUMBER
, ART.ARTRANSACTIONDATE INVOICEDATE, ART.ARTRANSACTIONDATE
, (SELECT MAX(I.PAYMENTTERMSDUEDATE) FROM INVOICEHEADEREXTRAINFO I
   WHERE ART.INVOICEHEADER_ID = I.INVOICEHEADER_ID) DUEDATE
FROM ARTRANSACTION ART
     INNER JOIN ARTRANSACTIONTYPE ARTT ON ART.ARTRANSACTIONTYPE_ID = ARTT.ARTRANSACTIONTYPE_ID
WHERE ART.DEBITCREDIT = 'D' AND ART.ISOPEN_YN = 'Y' AND ARTT.TYPENUMBER <> 2 AND
      (ART.PARENTARTRANSACTION_ID IS NULL OR ART.PARENTARTRANSACTION_ID = ART.ARTRANSACTION_ID)
/

  CREATE OR REPLACE VIEW "V_DELIVEREDCONTAINERS" ("LINETYPE", "CUSTOMERNUMBER", "NAME", "DEPARTMENTNUMBER", "DEP_NAME", "DISTRIBUTIONPOINTNUMBER", "DISTRIBPOINT_DESC", "DEFAULTBU_ID", "PROCBU_ID", "CONTAINERTYPE_CODE", "CONTAINERTYPE_ACTIVE", "CONTAINERTYPE_DESC", "CONTAINER_ID", "CONT_IN", "CONT_OUT", "AT_CUSTOMER", "SCANTIMESTAMP", "LANGUAGE_CODE") AS 
  select 1 linetype
, c.customernumber, c.name, dep.departmentnumber, dep.description Dep_name
, dp.distributionpointnumber, dp.description DistribPoint_desc
, bu.businessunit_id DefaultBU_id, bu.businessunit_id ProcBU_id -- parameters from the report, both with the same value (current BU)
, ct.code ContainerType_code, ct.active ContainerType_active
, (select ctd.description from containertype_desc ctd where ct.containertype_id=ctd.containertype_id and ctd.language_id=lan.language_id) ContainerType_desc
, co.container_id
, 1 cont_in, 0 cont_out, 0 at_customer
, cs.scantimestamp
, lan.code Language_code
from customer c, department dep, distributionpoint dp, container co
, containerscan cs
, containertype ct
, businessunit bu--, businessunit proc_bu
, languages lan
where -- coalesce(co.distributionpoint_id,co.lastdistributionpoint_link_id)=dp.distributionpoint_id
cs.distributionpoint_link_id = dp.distributionpoint_id
and dp.department_id=dep.department_id
and dep.customer_id=c.customer_id
and co.containertype_id = ct.containertype_id and co.container_id = cs.container_id
and cs.transactiontype_id in (1, 510, 511, 512) --inscan
and (c.defaultbusinessunit_id = bu.businessunit_id or
    exists (select 1 from customeractivities ca where
         (ca.processbusinessunit_id = bu.businessunit_id or ca.invoicebusinessunit_id=bu.businessunit_id
        or ca.internalprocessingbu_id=bu.businessunit_id)
        and ca.customer_id = c.customer_id))
union all --out
select 2 linetype
, c.customernumber, c.name, dep.departmentnumber, dep.description Dep_name
, dp.distributionpointnumber, dp.description DistribPoint_desc
, bu.businessunit_id DefaultBU_id, bu.businessunit_id ProcBU_id
, ct.code ContainerType_code, ct.active ContainerType_active
, (select ctd.description from containertype_desc ctd where ct.containertype_id=ctd.containertype_id and ctd.language_id=lan.language_id) ContainerType_desc
, co.container_id
, 0 cont_in, 1 cont_out, 0 at_customer
, cs.scantimestamp
, lan.code Language_code
from customer c, department dep, distributionpoint dp, container co
, containerscan cs, containertype ct
, businessunit bu--, businessunit proc_bu
, languages lan
where cs.distributionpoint_link_id = dp.distributionpoint_id and dp.department_id=dep.department_id
and dep.customer_id=c.customer_id
and co.containertype_id = ct.containertype_id and co.container_id = cs.container_id
and cs.transactiontype_id in (2, 540, 541, 542, 543, 545) --outscan
and (c.defaultbusinessunit_id = bu.businessunit_id or
    exists (select 1 from customeractivities ca where
        (ca.processbusinessunit_id = bu.businessunit_id or ca.invoicebusinessunit_id=bu.businessunit_id
        or ca.internalprocessingbu_id=bu.businessunit_id)
        and ca.customer_id = c.customer_id))
union all --at customer
select 3 linetype
, c.customernumber, c.name, dep.departmentnumber, dep.description Dep_name
, dp.distributionpointnumber, dp.description DistribPoint_desc
, bu.businessunit_id DefaultBU_id, bu.businessunit_id ProcBU_id
, ct.code ContainerType_code, ct.active ContainerType_active
, (select ctd.description from containertype_desc ctd where ct.containertype_id=ctd.containertype_id and ctd.language_id=lan.language_id) ContainerType_desc
, co.container_id
, 0 cont_in, 0 cont_out, 1 at_customer
, trunc(sysdate) scantimestamp
, lan.code Language_code
from customer c, department dep, distributionpoint dp, container co--, containerscan cs
, stay st, containertype ct
, businessunit bu--, businessunit proc_bu
, languages lan
where co.distributionpoint_id =dp.distributionpoint_id and dp.department_id=dep.department_id
and dep.customer_id=c.customer_id
and co.containertype_id = ct.containertype_id and co.stay_id=st.stay_id
   and st.staytype = 2 and st.staynr in( 20,21) --and cs.container_id = co.container_id
and (c.defaultbusinessunit_id = bu.businessunit_id or
    exists (select 1 from customeractivities ca where
         (ca.processbusinessunit_id = bu.businessunit_id or ca.invoicebusinessunit_id=bu.businessunit_id
        or ca.internalprocessingbu_id=bu.businessunit_id)
        and ca.customer_id = c.customer_id))
/

  CREATE OR REPLACE VIEW "V_DELIVEREDPIECESPERCLIENT" ("PROCESSBUSINESSUNIT_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "CLIENTNUMBER", "CLIENTNAME", "PRODUCTGROUPCODE", "PRODUCTGROUPDESCRIPTION", "PRODUCTCODE", "PRODUCTDESCRIPTION", "THEORETICALWEIGHT", "TYPEOFMERCHANDISE", "MODEL", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "DELIVERYDATE", "ROOMNUMBER", "DAYNUMBER", "YEARWEEK", "YEAR", "WEEK", "MONTH", "QUANTITY", "PRICE", "PROCESSBUCODE", "PROCESSBUDESCRIPTION", "CUSTOMERLANGUAGECODE", "LANGUAGECODE") AS 
  Select CDN.Processbusinessunit_Id, CL.CUSTOMER_ID,
       CL.CUSTOMERNUMBER, CL.NAME customername,
       coalesce(DEPT1.DEPARTMENTNUMBER, DEPT2.DEPARTMENTNUMBER) DEPARTMENTNUMBER, coalesce(DEPT1.DESCRIPTION, DEPT2.DESCRIPTION) departmentdescription,
       DP.DISTRIBUTIONPOINTNUMBER, DP.DESCRIPTION distributionpointdescription,
       CLI.CLIENTNUMBER, CLI.NAME CLIENTNAME,
       PG.CODE productgroupcode,
       (SELECT A.DESCRIPTION FROM PRODUCTGROUP_DESC A WHERE A.PRODUCTGROUP_ID = PG.PRODUCTGROUP_ID AND A.LANGUAGE_ID = LAN.LANGUAGE_ID) productgroupdescription,
       PR.CODE productcode,
       (SELECT B.DESCRIPTION FROM PRODUCT_DESC B WHERE B.PRODUCT_ID = PR.PRODUCT_ID AND B.LANGUAGE_ID = LAN.LANGUAGE_ID) productdescription,
       PR.THEORETICALWEIGHT, PR.typeofmerchandise, PR.MODEL,
       FM.CODE finishingmethodcode,
       (SELECT D.DESCRIPTION FROM FINISHINGMETHOD_DESC D WHERE D.FINISHINGMETHOD_ID = FM.FINISHINGMETHOD_ID AND D.LANGUAGE_ID = LAN.LANGUAGE_ID) FINISHINGMETHODdescription,
       CDN.Deliverydate, CDN.Roomnumber, getabsdaynumber(CDN.Deliverydate) DayNumber,
       (year(CDN.Deliverydate)*100 + getisoweek(CDN.Deliverydate)) YEARWEEK,
       year(CDN.Deliverydate) year, getisoweek(CDN.Deliverydate) WEEK,
       month(CDN.Deliverydate) month,
       (CDNL.Qtycountedout + CDNL.Qtyscannedout) Quantity, CDNL.Price,
       ProcBU.CODE processbucode, ProcBU.DESCRIPTION processbudescription,
       CL.LANGUAGECODE CUSTOMERLANGUAGECODE, LAN.CODE LANGUAGECODE
From ClientDeliveryNote CDN, BusinessUnit ProcBU, ClientDeliveryNoteLine CDNL, Customer_Link CL, Client_Link CLI
Left Outer Join (DepartmentRoom DR inner join Department DEPT1 on DEPT1.Department_ID = DR.Department_ID)
On DR.Departmentroom_Id = CLI.Departmentroom_Id
Left Outer Join (DeliveryPoint DelP
     inner join (DistributionPoint DP inner join Department DEPT2 On DEPT2.Department_ID = DP.Department_ID)
     on DP.DELIVERYPOINT_ID = DelP.Deliverypoint_Id)
on DelP.DeliveryPoint_ID = CLI.DeliveryPoint_Link_ID
, Product PR, ProductGroup PG, FinishingMethod FM, Languages LAN
Where CDN.ClosingDate is Not Null
      And CDN.Processbusinessunit_Id = ProcBU.Businessunit_Id
      And CL.Customer_Link_ID = CDN.Customer_Link_ID
      And CLI.Client_Link_ID = CDN.Client_Link_ID
      And CDNL.Clientdeliverinote_Id = CDN.ClientDeliveryNote_ID
      And PR.Product_ID = CDNL.Product_Link_ID
      And PG.ProductGroup_ID = PR.ProductGroup_ID
      And FM.FinishingMethod_ID = CDNL.Finishingmethod_Id
/

  CREATE OR REPLACE VIEW "V_DELIVEREDPRODUCTS" ("REPORTPARAM_ID", "PROCESSBU_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "PACKPRODUCTGROUPCODE", "PRODUCTGROUPCODE", "PRODUCTCODE", "PARENTPRODUCTCODE", "PACKINDICATION", "PACKCODE", "THEORETICALWEIGHT", "TYPEOFMERCHANDISE", "MODEL", "PRODSIZE_THEORETICALWEIGHT", "SIZECODE", "FINISHINGMETHODCODE", "DELIVERYDATE", "YEARWEEK", "WEEK", "YEAR", "REALMONTH", "REALYEAR", "DAYNUMBER", "AMOUNTORDERED", "AMOUNTDELIVERED", "AMOUNTSHORTAGE", "INTERNALPRICE", "DISCOUNT", "PARENTPACKPRODUCT_LINK_ID", "PARENTPRODUCT_LINK_ID", "PROCESSBUCODE", "PROCESSBUDESCRIPTION", "INVOICEBUCODE", "INVOICEBUDESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP", "DECIMALS", "INVOICEAMOUNTDECIMALS", "TAXABLE", "DEFAULTBUSINESSUNIT_ID", "CUSTOMERLANGUAGECODE", "LANGUAGECODE", "Q", "W", "E", "R", "T", "Y", "U", "PLANT_CODE", "PLANT_NAME", "WIDTH_S", "LENGTH_S", "PACKPRODUCTGROUPDESCRIPTION", "PRODUCTGROUPDESCRIPTION", "PRODUCTDESCRIPTION", "PARENTPRODUCTDESCRIPTION", "PACKDESCRIPTION", "ACTIVITYCODE", "THEORETICALWEIGHT_PLPC", "SIZEDESCRIPTION", "FINISHINGMETHODDESCRIPTION", "PRICE", "VATRATE", "PRICEWITHDISCOUNT", "DISCOUNTPERCENTAGE") AS 
  select /*version 3.0*/
       rp.reportparam_id, processbu.businessunit_id processbu_id, culk.customernumber, culk.name customername, deplk.departmentnumber, deplk.description departmentdescription,
       distlk.distributionpointnumber, distlk.description distributionpointdescription, packpg.code packproductgroupcode, pg.code productgroupcode,  prlk.code productcode,  parentpr.code parentproductcode,
       dh.packindication, pack.code packcode, pr.theoreticalweight, pr.typeofmerchandise, pr.model, prsz.theoreticalweight prodsize_theoreticalweight, sdlk.code sizecode,
       fm.code finishingmethodcode, dh.deliverydate, dh.year*100 + dh.week yearweek, dh.week, dh.year, month(dh.deliverydate) realmonth, year(dh.deliverydate) realyear,
       dh.daynumber, dh.amountordered, dh.amountdelivered, dh.amountshortage, dh.internalprice, dh.discount, dh.parentpackproduct_link_id, dh.parentproduct_link_id,
       processbu.code processbucode, processbu.description processbudescription, invoicebu.code invoicebucode, invoicebu.description invoicebudescription, dh.systemuser_id,
       dh.timestamp, cur.decimals, cur.invoiceamountdecimals, cu.taxable, bu.businessunit_id defaultbusinessunit_id, culk.languagecode customerlanguagecode, lan.code languagecode,
       rp.number_value q , cu.customer_id  w, pr.product_id e, sdlk.sizedefinition_id r, fm.finishingmethod_id t, dh.deliverydate y ,pr.typeofmerchandise u, pl.code plant_code,
       pl.name plant_name, sd.width width_s, sd.length length_s,
       (select a.description
          from productgroup_desc a
         where a.productgroup_id = packpg.productgroup_id
           and a.language_id = lan.language_id) packproductgroupdescription,
       (select a.description
          from productgroup_desc a
         where a.productgroup_id = pg.productgroup_id
           and a.language_id = lan.language_id) productgroupdescription,
       (select b.description
          from product_desc b
         where b.product_id = dh.product_link_id
           and b.language_id = lan.language_id) productdescription,
       (select e.description
          from product_link_desc e
         where e.product_link_id = dh.parentproduct_link_id
           and e.language_id = lan.language_id) parentproductdescription,
       (select f.description
          from product_link_desc f
         where f.product_link_id = dh.parentpackproduct_link_id
           and f.language_id = lan.language_id) packdescription,
       (select f.code
          from activity f
         where f.activity_id = pg.activity_id) activitycode,
       (select plpc.soilweight from productlistpercustomer plpc
         where plpc.customer_id=culk.customer_link_id
           and plpc.product_id=prlk.product_link_id
           and plpc.sizedefinition_id=sdlk.sizedefinition_id
           and plpc.finishingmethod_id=fm.finishingmethod_id
           and plpc.dateinactive >= sysdate) theoreticalweight_plpc,
       (select c.description
          from sizedefinition_link_desc c
         where c.sizedefinition_link_id = dh.sizedefinition_link_id
           and c.language_id = lan.language_id) sizedescription,
       (select d.description
          from finishingmethod_desc d
         where d.finishingmethod_id = dh.finishingmethod_id
           and d.language_id = lan.language_id) finishingmethoddescription,
       f_getdelprodprice(rp.number_value, cu.customer_id, pr.product_id, sdlk.sizedefinition_id, fm.finishingmethod_id, rp.date_value1, pr.typeofmerchandise) price,
       f_getvat(rp.number_value, (case when cu.taxable = 'Y' then cu.customer_id else null end), pr.product_id, (case when rp.number_value1 = -1 then cu.country_id else rp.number_value1  end), cu.country_id, rp.date_value1/*dh.deliverydate*/) vatrate,
       f_getdelprodpricewithdisc(cu.customer_id, pr.product_id, sdlk.sizedefinition_id, fm.finishingmethod_id, dh.deliverydate, pr.typeofmerchandise) pricewithdiscount,
       pack_price.wash_discount(cu.customer_id, pr.product_id, sdlk.sizedefinition_id, fm.finishingmethod_id,dh.deliverydate) discountpercentage
  from deliveryhistory dh
       left join product pr on dh.product_link_id = pr.product_id
       left join sizedefinition sd on dh.sizedefinition_link_id = sd.sizedefinition_id
       join productsize prsz on pr.product_id = prsz.product_id and sd.sizedefinition_id = prsz.sizedefinition_id
       join distributionpoint_link distlk
            join department_link deplk
                 join customer_link culk
                      left join customer cu on cu.customer_id = culk.customer_id
                 on deplk.customer_link_id = culk.customer_link_id
            on distlk.department_link_id = deplk.department_link_id
       on dh.distributionpoint_link_id = distlk.distributionpoint_link_id
       join sizedefinition_link sdlk on dh.sizedefinition_link_id = sdlk.sizedefinition_link_id
       join finishingmethod fm on dh.finishingmethod_id = fm.finishingmethod_id
       join businessunit processbu on dh.processbusinessunit_id = processbu.businessunit_id
       join businessunit invoicebu on dh.invoicebusinessunit_id = invoicebu.businessunit_id
       join product_link parentpr on dh.parentproduct_link_id = parentpr.product_link_id
       join product_link pack
            left join productgroup packpg on pack.productgroupcode = packpg.code
       on dh.parentpackproduct_link_id = pack.product_link_id
       join product_link prlk
            left join productgroup pg on prlk.productgroupcode = pg.code
       on dh.product_link_id = prlk.product_link_id
       join currency cur on dh.currency_id = cur.currency_id
       join businessunit bu
            join plant pl on bu.plant_id = pl.plant_id
       on dh.processbusinessunit_id = bu.businessunit_id
       ,reportparam rp, languages lan
 where (exists (select processbusinessunit_id
                  from customeractivities ca
                 where ca.customer_id = cu.customer_id
                   and ca.processbusinessunit_id = bu.businessunit_id)
        or bu.businessunit_id = cu.defaultbusinessunit_id)
    and processbu.plant_id = pl.plant_id
    and exists (select 1
                  from businessunitsperusergroup bug
                       join systemuser su on bug.usergroup_id = su.usergroup_id
                 where bug.businessunit_id=bu.businessunit_id
                   and su.systemuser_id = rp.systemuser_id)
/

  CREATE OR REPLACE VIEW "V_DELIVEREDPRODUCTSPERPLANT" ("PLANTCODE", "PLANTNAME", "PROCESSBUCODE", "PROCESSBUDESC", "MARKETSEGMENTCODE", "MARKETSEGMENTDESC", "PROCESSBUSINESSUNIT_ID", "PRODUCTGROUPCODE", "PRODUCTGROUPDESCRIPTION", "PRODUCTCODE", "PARENTPRODUCTCODE", "PACKINDICATION", "PACKCODE", "PRODUCTDESCRIPTION", "PARENTPRODUCTDESCRIPTION", "PACKDESCRIPTION", "ACTIVITYCODE", "THEORETICALWEIGHT", "TYPEOFMERCHANDISE", "MODEL", "PRODSIZE_THEORETICALWEIGHT", "SIZECODE", "FINISHINGMETHODCODE", "SIZEDESCRIPTION", "FINISHINGMETHODDESCRIPTION", "DELIVERYDATE", "YEARWEEK", "WEEK", "YEAR", "DAYNUMBER", "REALMONTH", "REALYEAR", "AMOUNTORDERED", "AMOUNTDELIVERED", "AMOUNTSHORTAGE", "PRICE", "INTERNALPRICE", "DISCOUNT", "LANGUAGECODE") AS 
  select
  plant.code plantCode, plant.name plantName
, processBU.Code processbuCode, processBU.description processbuDesc, marketsegment.code marketsegmentCode
, ( select marketsegment_desc.description from marketsegment_desc where marketsegment_desc.marketsegment_id = marketsegment.marketsegment_id
  and marketsegment_desc.language_id = languages.language_id ) marketsegmentDesc
, dh.processbusinessunit_id, productgroup.code productgroupcode
, ( select a.description from productgroup_desc a where a.productgroup_id = productgroup.productgroup_id
  and a.language_id = languages.language_id ) productgroupdescription
, product_link.code productcode, parentproduct.code parentproductcode, dh.packindication, pack.code packcode
, ( select b.description from product_link_desc b where b.product_link_id = dh.product_link_id
  and b.language_id = languages.language_id ) productdescription
, ( select e.description from product_link_desc e where e.product_link_id = dh.parentproduct_link_id
  and e.language_id = languages.language_id ) parentproductdescription
, ( select f.description from product_link_desc f where f.product_link_id = dh.parentpackproduct_link_id
  and f.language_id = languages.language_id ) packdescription
, ( select f.code from activity f where f.activity_id = productgroup.activity_id ) activitycode
, prd.theoreticalweight, prd.typeofmerchandise, prd.model, psz.theoreticalweight prodsize_theoreticalweight
, sizedefinition_link.code sizecode, finishingmethod.code finishingmethodcode
, ( select c.description from sizedefinition_link_desc c where c.sizedefinition_link_id = dh.sizedefinition_link_id
  and c.language_id = languages.language_id ) sizedescription
, ( select d.description from finishingmethod_desc d where d.finishingmethod_id = dh.finishingmethod_id
  and d.language_id = languages.language_id) finishingmethoddescription
, dh.deliverydate, dh.year*100 + dh.week yearweek, dh.week, dh.year, dh.daynumber
, MONTH(dh.deliverydate) realmonth, YEAR(dh.deliverydate) realyear
, dh.amountordered, dh.amountdelivered, dh.amountshortage, dh.price, dh.internalprice, dh.discount
, languages.code languagecode
from
   deliveryhistory dh
      left outer join product prd on dh.product_link_id = prd.product_id
      left outer join sizedefinition sz on dh.sizedefinition_link_id = sz.sizedefinition_id
, customer cu, department_link de, marketsegment, businessunit processbu, plant
, product_link parentproduct, product_link pack
, product_link
    left outer join productgroup on product_link.productgroupcode = productgroup.code
, sizedefinition_link, finishingmethod
, productsize psz, languages
where
  dh.department_link_id = de.department_link_id
    and de.customer_link_id = cu.customer_id
        and cu.marketsegment_id = marketsegment.marketsegment_id
and dh.Processbusinessunit_Id = processBu.Businessunit_Id
    and processBu.Plant_Id = plant.plant_id
and dh.product_link_id = product_link.product_link_id
and dh.parentproduct_link_id = parentproduct.product_link_id
and dh.parentpackproduct_link_id = pack.product_link_id
and dh.sizedefinition_link_id = sizedefinition_link.sizedefinition_link_id
and dh.finishingmethod_id = finishingmethod.finishingmethod_id
and prd.product_id = psz.product_id
    and psz.sizedefinition_id = sz.sizedefinition_id
/

  CREATE OR REPLACE VIEW "V_DELIVEREDQTY" ("CHAINCODE", "DELIVERYDATE", "CUSTOMERNUMBER", "PRODUCTCODE", "QUANTITY", "DELIVERYTYPE") AS 
  select /*view v_deliveredqty versoin 0.1*/
 v.chaincode,
 v.deliverydate,
 v.customernumber,
 v.productcode,
 v.quantity,
 v.deliverytype
from   (select t.chaincode, t.deliverydate, t.customernumber, t.productcode, t.deliveredqty,
                t.nochargeprevrejected, t.nochargeprevshortage, t.qtycorrected
         from   (select x.chaincode, x.deliverydate, x.customernumber, x.productcode,
                         (sum(x.deliveredqty) - sum(x.nochargeprevrejected) -
                          sum(x.nochargeprevshortage) - sum(x.qtycorrected)) deliveredqty,
                         sum(x.nochargeprevrejected) nochargeprevrejected,
                         sum(x.nochargeprevshortage) nochargeprevshortage,
                         sum(x.qtycorrected) qtycorrected
                  from   (select ch.code chaincode, pk.deliverydate, c.customernumber, p.code productcode,
                                  sum(pkl.deliveredamount) deliveredqty,
                                  sum(pkl.nochargeprevrejected) nochargeprevrejected,
                                  sum(pkl.nochargeprevshortage) nochargeprevshortage,
                                  sum(case
                                        when pkl.origin = 3 then
                                         pkl.deliveredamount
                                        else
                                         0
                                      end) qtycorrected
                           from   packingnote pk
                           join   packingnoteline pkl
                           on     pkl.packingnote_id = pk.packingnote_id
                           join   product p
                           on     p.product_id = pkl.product_id
                           join   status st
                           on     st.status_id = pk.status_id
                           join   deliverypoint delp
                           on     delp.deliverypoint_id = pk.deliverypoint_id
                           join   customer c
                           on     c.customer_id = delp.customer_id
                           join   chain ch
                           on     ch.chain_id = c.chain_id
                           where  st.code = '30'
                           and    pk.origin <> 3
                           group  by pk.deliverydate, c.customernumber, p.code, ch.code
                           union all
                           select ch.code chaincode, trunc(pk.processedtimestamp) deliverydate,
                                  c.customernumber, p.code productcode,
                                  sum(pkl.deliveredamount) deliveredqty,
                                  sum(pkl.nochargeprevrejected) nochargeprevrejected,
                                  sum(pkl.nochargeprevshortage) nochargeprevshortage,
                                  sum(case
                                         when pkl.origin = 3 then
                                          pkl.deliveredamount
                                         else
                                          0
                                       end) qtycorrected
                           from   packingnote pk
                           join   packingnoteline pkl
                           on     pkl.packingnote_id = pk.packingnote_id
                           join   product p
                           on     p.product_id = pkl.product_id
                           join   status st
                           on     st.status_id = pk.status_id
                           join   deliverypoint delp
                           on     delp.deliverypoint_id = pk.deliverypoint_id
                           join   customer c
                           on     c.customer_id = delp.customer_id
                           join   chain ch
                           on     ch.chain_id = c.chain_id
                           where  st.code = '30'
                           and    pk.origin = 3
                           group  by trunc(pk.processedtimestamp), c.customernumber, p.code, ch.code) x
                  group  by x.chaincode, x.deliverydate, x.customernumber, x.productcode) t)
 unpivot(quantity for
         deliverytype in (deliveredqty as 'O',
         nochargeprevrejected as 'R',
         nochargeprevshortage as 'S',
         qtycorrected as 'C')) v
where v.quantity <> 0
order  by 2, 3, 4
/

  CREATE OR REPLACE VIEW "V_DELIVERIESPEREMPLOYEE" ("PACKINGNOTE_ID", "DELIVERYDATE", "PLANTCODE", "PLANTNAME", "PROCESSBUCODE", "PROCESSBUDESC", "EMPLOYEENUMBER", "EMPLOYEENAME", "PRODUCTCODE", "PRODUCTDESC", "PACKINGNOTELINE_ID", "DELIVEREDAMOUNT", "LANGUAGECODE") AS 
  select
  pn.packingnote_id, pn.deliverydate deliverydate
, plant.code plantCode, plant.name plantName
, processBU.Code processBUcode, processBU.Description processBUdesc
, emp.employeenumber, emp.name employeeName, prd.code productCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, pnl.packingnoteline_id, pnl.deliveredamount
, languages.code languageCode
from
  packingnote pn, status, employee emp, businessunit processBU, plant, packingnoteline pnl
, product prd
, languages
where
    pn.status_id = status.status_id
and status.statustype = 'PN'
    and status.code = 30
and pn.employee_id = emp.employee_id
and pn.processbusinessunit_id = processBU.Businessunit_Id
    and processBU.Plant_Id = plant.Plant_Id
and pn.packingnote_id = pnl.packingnote_id
    and pnl.product_id = prd.product_id
/

  CREATE OR REPLACE VIEW "V_DELIVERYADDRESS" ("CITY", "STREET", "STREET2", "ZIPCODE", "DELIVERYPOINT_ID") AS 
  select a.city, a.street, a.street2, a.zipcode, d.deliverypoint_id
from address a, deliverypoint d
where a.address_id = d.deliveryaddress_id
/

  CREATE OR REPLACE VIEW "V_DELIVERYAMOUNT" ("REPORTPARAM_ID", "CUSTOMER_LINK_ID", "DISTRIBUTIONPOINT_LINK_ID", "FINISHINGMETHOD_ID", "PRODUCT_LINK_ID", "SIZEDEFINITION_LINK_ID", "AMOUNT") AS 
  select RP.REPORTPARAM_ID, a.customer_link_id, a.distributionpoint_link_id,
  a.finishingmethod_id, a.product_link_id,
  a.sizedefinition_link_id,
  sum(a.amountdelivered) amount
from deliveryhistory a, REPORTPARAM RP
where a.deliverydate >= RP.DATE_VALUE1-24*7
  and a.deliverydate <= RP.DATE_VALUE1
  and a.packindication>=1
  and a.packindication<=2
  AND A.CUSTOMER_LINK_ID = RP.NUMBER_VALUE
group by RP.REPORTPARAM_ID, a.customer_link_id, a.distributionpoint_link_id,
  a.finishingmethod_id, a.product_link_id, a.sizedefinition_link_id
/

  CREATE OR REPLACE VIEW "V_DELIVERYANDSOILCOUNTED" ("LINETYPE", "CUSTOMER_ID", "DEFAULTBUSINESSUNIT_ID", "BU_CODE", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "CHAINCODE", "PRODUCTCODE", "SIZEDEFINITIONCODE", "PRODUCTDESCRIPTION", "DELIVEREDAMOUNT", "PN_DELIVERYDATE", "NOTENUMBER", "LANGUAGECODE", "RC_CODE", "SOILCOUNTQTY", "CLEANRETURNQTY", "HEAVYSOILQTY", "INCREASEDQTY", "DECREASEDQTY", "DV_OUTSTANDING", "PROCESSBU_CODE", "CONSPOINTNUMBER", "CONSPOINTDESCR") AS 
  select 1 linetype,
       c.customer_id,
       c.defaultbusinessunit_id,
       (select bu.code
          from businessunit bu
         where bu.businessunit_id = c.defaultbusinessunit_id) bu_code,
       c.customernumber,
       c.name customername,
       d.departmentnumber,
       (select ch.code from chain ch where ch.chain_id = c.chain_id) chaincode,
       p.code productcode,
       sizdef.code sizedefinitioncode,
       (select description
          from product_desc
         where product_desc.product_id = p.product_id
           and product_desc.language_id = languages.language_id) productdescription,
       coalesce((select sum(pnl.deliveredamount)
          from packingnoteline pnl, packingnote pn1
         where pnl.packingnote_id = pn1.packingnote_id
           and pnl.product_id = dv.product_id
           and pnl.sizedefinition_id = dv.sizedefinition_id
           and pnl.finishingmethod_id = dv.finishingmethod_id
           and pn1.packingnote_id = pn.packingnote_id),0) deliveredamount,
       pn.deliverydate pn_deliverydate,
       pn.notenumber,
       languages.code languagecode,
       (select rc.code from reasoncode rc where rc.reasoncode_id = dv.reasoncode_id) rc_code,
       nvl(sum(case
                 when dv.origin = 1 and dv.soilcountsubtype in 1 then
                  dv.amount
                 else
                  0
               end),
           0) soilcountqty,
       nvl(sum(case
                 when dv.origin = 1 and dv.soilcountsubtype = 5 then
                  dv.amount
                 else
                  0
               end),
           0) cleanreturnqty,
       nvl(sum(case
                 when dv.origin = 1 and dv.soilcountsubtype = 4 then
                  dv.amount
                 else
                  0
               end),
           0) heavysoilqty,
       nvl(sum(case
                 when dv.origin = 3 and dv.amount > 0 then
                  dv.amount
                 else
                  0
               end),
           0) increasedqty,
       nvl(sum(case
                 when dv.origin in (3, 4, 5) and dv.amount < 0 then
                  dv.amount
                 else
                  0
               end),
           0) decreasedqty,
       (select sum(dv1.amount)
        from deliveryvariations dv1
        where dv1.causenote_id = pn.packingnote_id
        and dv1.product_id = dv.product_id
        and dv1.sizedefinition_id = dv.sizedefinition_id
        and dv1.finishingmethod_id = dv.finishingmethod_id
        and dv1.distributionpoint_id = dp.distributionpoint_id
        and dv1.reasoncode_id = dv.reasoncode_id
        ) dv_outstanding,
       (select bu.code
          from businessunit bu
         where pn.processbusinessunit_id = bu.businessunit_id) processbu_code,
       (select dp.distributionpointnumber
          from distributionpoint dp
         where dp.distributionpoint_id = pn.distributionpoint_id) conspointnumber,
       (select dp.description
          from distributionpoint dp
         where dp.distributionpoint_id = pn.distributionpoint_id) conspointdescr
  FROM customer           c,
       department         d,
       distributionpoint  dp,
       packingnote        pn,
       product            p,
       sizedefinition     sizdef,
       languages,
       deliveryvariations dv
 where c.customer_id = d.customer_id
   and d.department_id = dp.department_id
   and pn.distributionpoint_id = dp.distributionpoint_id
   and dv.packingnote_id = pn.packingnote_id
   and p.product_id = dv.product_id
   and dv.sizedefinition_id = sizdef.sizedefinition_id
   and pn.status_id not in (select s.status_id from status s where s.statustype = 'PN' and (s.code = 40 or s.code=60))
 group by c.customer_id,
          c.defaultbusinessunit_id,
          c.customernumber,
          c.name,
          d.departmentnumber,
          c.chain_id,
          p.code,
          sizdef.code,
          p.product_id,
          languages.language_id,
          languages.code,
          dv.reasoncode_id,
          dv.product_id,
          dv.sizedefinition_id,
          dv.finishingmethod_id,
          pn.packingnote_id,
          pn.notenumber,
          pn.deliverydate,
          pn.processbusinessunit_id,
          pn.distributionpoint_id,
          dp.distributionpoint_id
union
select 2 linetype,
       c.customer_id,
       c.defaultbusinessunit_id,
       (select bu.code
          from businessunit bu
         where bu.businessunit_id = c.defaultbusinessunit_id) bu_code,
       c.customernumber,
       c.name customername,
       d.departmentnumber,
       (select ch.code from chain ch where ch.chain_id = c.chain_id) chaincode,
       p.code productcode,
       sd.code sizedefinitioncode,
       (select description
          from product_desc
         where product_desc.product_id = p.product_id
           and product_desc.language_id = languages.language_id) productdescription,
      sum(pnl.deliveredamount) deliveredamount,
       pn.deliverydate pn_deliverydate,
       pn.notenumber,
       languages.code languagecode,
       '' rc_code,
       0 soilcountqty,
       0 cleanreturnqty,
       0 heavysoilqty,
       0 increasedqty,
       0 decreasedqty,
       0 dv_outstanding,
       (select bu.code
          from businessunit bu
         where pn.processbusinessunit_id = bu.businessunit_id) processbu_code,
       (select dp.distributionpointnumber
          from distributionpoint dp
         where dp.distributionpoint_id = pn.distributionpoint_id) conspointnumber,
       (select dp.description
          from distributionpoint dp
         where dp.distributionpoint_id = pn.distributionpoint_id) conspointdescr
  FROM customer           c,
       department         d,
       distributionpoint  dp,
       packingnote        pn,
       packingnoteline    pnl,
       product            p,
       sizedefinition     sd,
       languages
 where c.customer_id = d.customer_id
   and d.department_id = dp.department_id
   and pn.distributionpoint_id = dp.distributionpoint_id
   and pn.packingnote_id = pnl.packingnote_id
   and p.product_id = pnl.product_id
   and sd.sizedefinition_id = pnl.sizedefinition_id
   and pn.status_id not in (select s.status_id from status s where s.statustype = 'PN' and (s.code = 40 or s.code=60))
   and not exists (select dv.packingnote_id from deliveryvariations dv where dv.packingnote_id = pn.packingnote_id)
   group by c.customer_id,
          c.defaultbusinessunit_id,
          c.customernumber,
          c.name,
          d.departmentnumber,
          c.chain_id,
          p.code,
          sd.code,
          p.product_id,
          languages.language_id,
          languages.code,
          pn.notenumber,
          pn.deliverydate,
          pn.processbusinessunit_id,
          pn.distributionpoint_id
/

  CREATE OR REPLACE VIEW "V_DELIVERYBALANCE" ("DELIVERYDATE", "NOTENUMBER", "STATUS_CODE", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEP_DESC", "SIZECODE", "FMCODE", "PROD_CODE", "PRODGROUP_CODE", "PROD_DESC", "PRODGROUP_DESC", "REFERENCENR", "TRANSPORTARTICLE", "TOBEDELIVEREDAMOUNT", "DELIVEREDAMOUNT", "LANGUAGE_CODE") AS 
  SELECT pn.deliverydate, pn.notenumber, st.code status_code
       , cu.customernumber, cu.name customername, de.departmentnumber, de.description Dep_desc,
       (select sd.code from sizedefinition sd where sd.sizedefinition_id=pnl.sizedefinition_id) sizecode,
       (select fm.code from finishingmethod fm where fm.finishingmethod_id=pnl.finishingmethod_id) fmcode,
        pr.code Prod_Code, pg.code ProdGroup_Code
			 , (SELECT prd.description FROM product_desc prd WHERE prd.product_id = pr.product_id AND prd.language_id = lan.language_id) Prod_Desc
			 , (SELECT pgd.description FROM productgroup_desc pgd WHERE pgd.productgroup_id = pg.productgroup_id AND pgd.language_id = lan.language_id) ProdGroup_Desc
			 , (SELECT max(dv.reference) FROM deliveryvariations dv WHERE dv.packingnote_id = pn.packingnote_id) referencenr
			 , (SELECT tad.description FROM transportarticle_desc tad WHERE tad.transportarticle_id = pn.transportarticle_id AND tad.language_id = lan.language_id) transportarticle
			 , pnl.tobedeliveredamount, pnl.deliveredamount, lan.code Language_code
FROM packingnote pn, packingnoteline pnl, product pr
                 LEFT OUTER JOIN productgroup pg ON pr.productgroup_id = pg.productgroup_id
     , status st, distributionpoint dp, department de, customer cu
		 , languages lan
WHERE pn.packingnote_id = pnl.packingnote_id AND pnl.product_id = pr.product_id
      AND pn.status_id = st.status_id AND st.statustype = 'PN'
      AND pn.distributionpoint_id = dp.distributionpoint_id AND dp.department_id = de.department_id
			AND de.customer_id = cu.customer_id
/

  CREATE OR REPLACE VIEW "V_DELIVERYCOMPARISON" ("INVOICEHEADER_ID", "DRIVINGDATE", "DELWEEK", "DAY_DESC", "INVOICEBUSINESSUNIT_ID", "STOPNUMBER", "ROUTENUMBER", "ROUTEDESC", "PRODUCTCODE", "PRODUCTDESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "INVOICENUMBER", "DELIVERY_FREQUENCY", "PRICE", "MINQTY", "AMOUNTDELIVERED", "AMOUNT", "DELIVEREDQTY", "WTDAMOUNT", "AMOUNT1", "AMOUNT2", "AMOUNT3", "AMOUNT4", "AMOUNT5", "AMOUNT6", "AMOUNT7", "AMOUNT8", "AMOUNT9", "AMOUNT10", "AMOUNT11", "AMOUNT12", "AMOUNT13", "CIRCULATING_INVENTORY", "BILLINGMETHOD", "RQA_QUANTITY", "PRODUCTGROUPCODE", "REPORTPARAM_ID", "INVOICELINETYPE_ID", "LANGUAGECODE") AS 
  select ih.invoiceheader_id,
  ih.invoicedate drivingdate, getisoweek(ih.invoicedate) delweek,
 (select dd.description from day_desc dd where dd.day_id = getabsdaynumber(ih.invoicedate) and dd.language_id = lg.language_id) day_desc,
  ih.invoicebusinessunit_id,ih.stopnumber,
  ro.routenumber, ro.description routedesc,
  pr.code productcode,
  (select prd.description from product_desc prd where prd.product_id = pr.product_id and prd.language_id = lg.language_id) productdesc,
  ih.deltocustomernumber customernumber, ih.deltocustomername customername,
  ih.invoicenumber,
  cast(GET_DELCOMP_DELFRECV(rp.number_value, ih.deltocustomer_link_id, pr.product_id, ro.route_id, ih.invoicedate) as varchar2(7)) delivery_frequency,
  il.price,
  case when coalesce(ILP.MINIMUMQUANTITY, 0)=0 then coalesce((ILP.MINIMUMPERCENTAGE*ILP.INVENTORYQTY/100), 0)
  else ILP.MINIMUMQUANTITY
  end MINQTY
  --, ILP.MINIMUMQUANTITY , (ILP.MINIMUMPERCENTAGE*ILP.INVENTORYQTY/100) MINPERC
  ,ilp.deliveredqty amountdelivered, il.amount amount,ilp.deliveredqty,
  GET_AMOUNTDELIVERED(ih.deltocustomer_link_id, ilp.product_link_id, ilp.sizedefinition_link_id, ih.invoicedate, il.invoicelinetype_id) wtdamount,
 coalesce(GET_AMOUNTDELIVERED(ih.deltocustomer_link_id, ilp.product_link_id, ilp.sizedefinition_link_id, ih.invoicedate - 7, il.invoicelinetype_id), 0) amount1,
  coalesce(GET_AMOUNTDELIVERED(ih.deltocustomer_link_id, ilp.product_link_id, ilp.sizedefinition_link_id, ih.invoicedate - 7*2, il.invoicelinetype_id), 0) amount2,
  coalesce(GET_AMOUNTDELIVERED(ih.deltocustomer_link_id, ilp.product_link_id, ilp.sizedefinition_link_id, ih.invoicedate - 7*3, il.invoicelinetype_id), 0) amount3,
  coalesce(GET_AMOUNTDELIVERED(ih.deltocustomer_link_id, ilp.product_link_id, ilp.sizedefinition_link_id, ih.invoicedate - 7*4, il.invoicelinetype_id), 0) amount4,
  coalesce(GET_AMOUNTDELIVERED(ih.deltocustomer_link_id, ilp.product_link_id, ilp.sizedefinition_link_id, ih.invoicedate - 7*5, il.invoicelinetype_id), 0) amount5,
  coalesce(GET_AMOUNTDELIVERED(ih.deltocustomer_link_id, ilp.product_link_id, ilp.sizedefinition_link_id, ih.invoicedate - 7*6, il.invoicelinetype_id), 0) amount6,
  coalesce(GET_AMOUNTDELIVERED(ih.deltocustomer_link_id, ilp.product_link_id, ilp.sizedefinition_link_id, ih.invoicedate - 7*7, il.invoicelinetype_id), 0) amount7,
  coalesce(GET_AMOUNTDELIVERED(ih.deltocustomer_link_id, ilp.product_link_id, ilp.sizedefinition_link_id, ih.invoicedate - 7*8, il.invoicelinetype_id), 0) amount8,
  coalesce(GET_AMOUNTDELIVERED(ih.deltocustomer_link_id, ilp.product_link_id, ilp.sizedefinition_link_id, ih.invoicedate - 7*9, il.invoicelinetype_id), 0) amount9,
  coalesce(GET_AMOUNTDELIVERED(ih.deltocustomer_link_id, ilp.product_link_id, ilp.sizedefinition_link_id, ih.invoicedate - 7*10, il.invoicelinetype_id), 0) amount10,
  coalesce(GET_AMOUNTDELIVERED(ih.deltocustomer_link_id, ilp.product_link_id, ilp.sizedefinition_link_id, ih.invoicedate - 7*11, il.invoicelinetype_id), 0) amount11,
  coalesce(GET_AMOUNTDELIVERED(ih.deltocustomer_link_id, ilp.product_link_id, ilp.sizedefinition_link_id, ih.invoicedate - 7*12, il.invoicelinetype_id), 0) amount12,
  coalesce(GET_AMOUNTDELIVERED(ih.deltocustomer_link_id, ilp.product_link_id, ilp.sizedefinition_link_id, ih.invoicedate - 7*13, il.invoicelinetype_id), 0) amount13,
  ilp.inventoryqty circulating_inventory,
  (select max(plpc.billingmethod) from productlistpercustomer plpc
where plpc.customer_id=ih.deltocustomer_link_id and plpc.product_id=pr.product_id
and plpc.dateactive <= ih.invoicedate and plpc.dateinactive > ih.invoicedate ) billingmethod,
(select sum(rqa.quantity)from rentalqtyadjustment rqa, productlistperdistribpoint plpd, distributionpoint di, department d
   where rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id and plpd.product_id = pr.product_id
     and plpd.distributionpoint_id = di.distributionpoint_id and di.department_id = d.department_id
     and d.customer_id = ih.deltocustomer_link_id and rqa.adjustmentdate <= rp.date_value1)rqa_quantity
  , pg.code productgroupcode,  rp.reportparam_id
  , il.invoicelinetype_id
  , lg.code languagecode
from invoiceheader ih, invoiceline il left outer join invoicelineproduct ilp on il.invoiceline_id = ilp.invoiceline_id, product pr, route ro,
  languages lg, reportparam rp,
  productgroup pg, status st
where ih.invoiceheader_id = il.invoiceheader_id
  and il.invoiceline_id = ilp.invoiceline_id
  and pr.product_id = ilp.product_link_id
  and ih.route_id = ro.route_id
  and pr.typeofmerchandise in (1,3)
  and pr.productgroup_id = pg.productgroup_id
  and ih.status_id = st.status_id and st.statustype = 'IN' and st.code <> '3'
  and il.invoicelinetype_id in (1,2,5,8)
  and ilp.deliveredqty<>0
/

  CREATE OR REPLACE VIEW "V_DELIVERYHISTORY" ("PROCESSBUSINESSUNIT_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "PRODUCTGROUPCODE", "PRODUCTGROUPDESCRIPTION", "PRODUCTCODE", "PRODUCTDESCRIPTION", "PARENTPRODUCTCODE", "PARENTPRODUCTDESCRIPTION", "PACKINDICATION", "PACKCODE", "PACKDESCRIPTION", "ACTIVITYCODE", "THEORETICALWEIGHT", "TYPEOFMERCHANDISE", "MODEL", "PRODSIZE_THEORETICALWEIGHT", "SIZECODE", "SIZEDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "DELIVERYDATE", "YEARWEEK", "WEEK", "YEAR", "REALMONTH", "REALYEAR", "DAYNUMBER", "AMOUNTORDERED", "AMOUNTDELIVERED", "AMOUNTSHORTAGE", "PRICE", "INTERNALPRICE", "DISCOUNT", "PARENTPACKPRODUCT_LINK_ID", "PARENTPRODUCT_LINK_ID", "PROCESSBUCODE", "PROCESSBUDESCRIPTION", "INVOICEBUCODE", "INVOICEBUDESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP", "CUSTOMERLANGUAGECODE", "LANGUAGECODE", "WIDTH_S", "LENGTH_S") AS 
  select /* version 3.0*/
       dh.processbusinessunit_id, cl.customer_id, cl.customernumber, cl.name customername,
       dl.departmentnumber, dl.description departmentdescription,
       dpl.distributionpointnumber, dpl.description distributionpointdescription,
       pg.code productgroupcode,
       (select pgd.description from productgroup_desc pgd
         where pgd.productgroup_id = pg.productgroup_id
           and pgd.language_id = l.language_id) productgroupdescription,
       prl.code productcode,
       (select prld.description from product_link_desc prld where prld.product_link_id = dh.product_link_id and prld.language_id = l.language_id) productdescription,
       parp.code parentproductcode,
       (select pard.description from product_link_desc pard where pard.product_link_id = dh.parentproduct_link_id and pard.language_id = l.language_id) parentproductdescription,
       dh.packindication, pack.code packcode,
       (select parpd.description from product_link_desc parpd where parpd.product_link_id = dh.parentpackproduct_link_id and parpd.language_id = l.language_id) packdescription,
       (select act.code from activity act where act.activity_id = pg.activity_id) activitycode,
       p.theoreticalweight, p.typeofmerchandise, p.model,
       psz.theoreticalweight prodsize_theoreticalweight, szl.code sizecode,
       (select szld.description from sizedefinition_link_desc szld where szld.sizedefinition_link_id = dh.sizedefinition_link_id and szld.language_id = l.language_id) sizedescription,
       fm.code finishingmethodcode,
       (select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = dh.finishingmethod_id and fmd.language_id = l.language_id) finishingmethoddescription,
       dh.deliverydate, dh.year*100 + dh.week yearweek, dh.week, dh.year,
       month(dh.deliverydate) realmonth, year(dh.deliverydate) realyear,
       dh.daynumber, dh.amountordered, dh.amountdelivered,  dh.amountshortage, dh.price,
       dh.internalprice, dh.discount, dh.parentpackproduct_link_id, dh.parentproduct_link_id,
       pbu.code processbucode, pbu.description processbudescription,
       ibu.code invoicebucode, ibu.description invoicebudescription,
       dh.systemuser_id, dh.timestamp, cl.languagecode customerlanguagecode, l.code languagecode,
       sd.width width_s, sd.length length_s
  from deliveryhistory dh
       left join productsize psz on (dh.product_link_id = psz.product_id and dh.sizedefinition_link_id = psz.sizedefinition_id)
       left join product p on dh.product_link_id = p.product_id
       left join sizedefinition sd on dh.sizedefinition_link_id = sd.sizedefinition_id
       join businessunit pbu on dh.processbusinessunit_id = pbu.businessunit_id
       join businessunit ibu on dh.invoicebusinessunit_id = ibu.businessunit_id
       join distributionpoint_link dpl
            join department_link dl
                 join customer_link cl on dl.customer_link_id = cl.customer_link_id
            on dpl.department_link_id = dl.department_link_id
       on dh.distributionpoint_link_id = dpl.distributionpoint_link_id
       join product_link prl
            left join productgroup pg on prl.productgroupcode = pg.code
       on dh.product_link_id = prl.product_link_id
       join product_link parp on dh.parentproduct_link_id = parp.product_link_id
       join product_link pack on dh.parentpackproduct_link_id = pack.product_link_id
       join sizedefinition_link szl on dh.sizedefinition_link_id = szl.sizedefinition_link_id
       join finishingmethod fm on dh.finishingmethod_id = fm.finishingmethod_id
       cross join languages l
/

  CREATE OR REPLACE VIEW "V_DELIVERYHISTORY_YEAR" ("CUSTOMER_ID", "YEAR_PERIOD", "PROCESSBUSINESSUNIT_ID", "AMT_DELIVERED", "AMT_SHORTAGE", "AMT_ORDERED", "AMT_STANDARD", "MAX_WEEK", "CUSTOMERNUMBER", "CUSTNAME", "CUSTOMERLANGUAGECODE", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINTNUMBER", "DIP_DESC", "PRODUCTGROUPCODE", "PRODUCTGROUPDESCRIPTION", "PRODUCTCODE", "TYPEOFMERCHANDISE", "PRODUCTDESCRIPTION", "PARENTPRODUCTCODE", "PARENTPRODUCTDESCRIPTION", "SIZECODE", "SIZEDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "PACKINDICATION", "LANGUAGE_CODE", "WIDTH_S", "LENGTH_S") AS 
  SELECT cl.customer_id,
       (CASE
         WHEN H.week between  1 and  4 then H.YEAR*100 +  1
         WHEN H.week between  5 and  8 then H.YEAR*100 +  2
         WHEN H.week between  9 and 12 then H.YEAR*100 +  3
         WHEN H.week between 13 and 16 then H.YEAR*100 +  4
         WHEN H.week between 17 and 20 then H.YEAR*100 +  5
         WHEN H.week between 21 and 24 then H.YEAR*100 +  6
         WHEN H.week between 25 and 28 then H.YEAR*100 +  7
         WHEN H.week between 29 and 32 then H.YEAR*100 +  8
         WHEN H.week between 33 and 36 then H.YEAR*100 +  9
         WHEN H.week between 37 and 40 then H.YEAR*100 + 10
         WHEN H.week between 41 and 44 then H.YEAR*100 + 11
         WHEN H.week between 45 and 48 then H.YEAR*100 + 12
         WHEN H.week between 49 and 53 then H.YEAR*100 + 13
         else 0
       END) Year_Period,
       H.PROCESSBUSINESSUNIT_ID,
       SUM(H.AMOUNTDELIVERED) AMT_DELIVERED, SUM(H.AMOUNTSHORTAGE) AMT_SHORTAGE,
       SUM(H.AMOUNTORDERED) AMT_ORDERED,     SUM(H.AMOUNTSTANDARD) AMT_STANDARD,
       max(h.week) max_week,
       CL.CUSTOMERNUMBER, CL.NAME custname, cl.LANGUAGECODE CUSTOMERLANGUAGECODE,
       dl.departmentnumber, dl.description departmentdesc,
       dpl.distributionpointnumber, dpl.description dip_desc,
       pg.CODE productgroupcode,
       (SELECT A.DESCRIPTION FROM PRODUCTGROUP_DESC A WHERE A.PRODUCTGROUP_ID = pg.PRODUCTGROUP_ID
                AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productgroupdescription,
       pl.CODE productcode, PRODUCT.typeofmerchandise,
       (SELECT B.DESCRIPTION FROM PRODUCT_LINK_DESC B WHERE B.PRODUCT_LINK_ID = h.PRODUCT_LINK_ID
                AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
       parentproduct.CODE parentproductcode,
       (SELECT E.DESCRIPTION FROM PRODUCT_LINK_DESC E WHERE E.PRODUCT_LINK_ID = h.PARENTPRODUCT_LINK_ID
                AND E.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) parentproductdescription,
       sl.CODE sizecode,
       (SELECT C.DESCRIPTION FROM SIZEDEFINITION_LINK_DESC C WHERE C.SIZEDEFINITION_LINK_ID = h.SIZEDEFINITION_LINK_ID
                AND C.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEdescription,
       fm.CODE FINISHINGMETHODCODE,
       (SELECT D.DESCRIPTION FROM FINISHINGMETHOD_DESC D WHERE D.FINISHINGMETHOD_ID = h.FINISHINGMETHOD_ID
                AND D.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODdescription,
       h.packindication,
       languages.code language_code,
       s.WIDTH WIDTH_S,s.LENGTH LENGTH_S--CSW
FROM DELIVERYHISTORY H LEFT OUTER JOIN PRODUCT ON (H.PRODUCT_LINK_ID = PRODUCT.PRODUCT_ID)
     LEFT OUTER JOIN SIZEDEFINITION S ON (H.SIZEDEFINITION_LINK_ID = S.SIZEDEFINITION_ID),--CSW
     CUSTOMER_LINK CL, department_link dl, distributionpoint_link dpl,
     PRODUCT_LINK pl LEFT OUTER JOIN PRODUCTGROUP pg ON (pl.PRODUCTGROUPCODE = pg.CODE),
     PRODUCT_LINK parentproduct,
     sizedefinition_link sl, FINISHINGMETHOD fm,
     languages
WHERE H.CUSTOMER_LINK_ID = CL.CUSTOMER_LINK_ID
      and h.department_link_id = dl.department_link_id
      and h.distributionpoint_link_id = dpl.distributionpoint_link_id
      and h.product_link_id = pl.product_link_id
      and h.sizedefinition_link_id = sl.sizedefinition_link_id
      and h.finishingmethod_id = fm.finishingmethod_id
      AND h.PARENTPRODUCT_LINK_ID = parentproduct.PRODUCT_LINK_ID
GROUP BY
      H.PROCESSBUSINESSUNIT_ID, cl.customer_id,
      --H.CUSTOMER_LINK_ID,
      CL.CUSTOMERNUMBER, CL.NAME, cl.LANGUAGECODE,
      CL.CUSTOMER_LINK_ID,
      --H.DEPARTMENT_LINK_ID,
      dl.departmentnumber, dl.description,
      --H.DISTRIBUTIONPOINT_LINK_ID,
      dpl.distributionpointnumber, dpl.description,
      languages.code, LANGUAGES.LANGUAGE_ID,
      pg.CODE, pg.PRODUCTGROUP_ID,
      parentproduct.CODE, h.PARENTPRODUCT_LINK_ID,
      PRODUCT.typeofmerchandise, pl.CODE, sl.CODE, fm.CODE,
--      H.PARENTPACKPRODUCT_LINK_ID,
      H.PRODUCT_LINK_ID,
      H.SIZEDEFINITION_LINK_ID,
      H.FINISHINGMETHOD_ID,
      h.packindication,s.WIDTH,s.LENGTH,
      (CASE
         WHEN H.week between  1 and  4 then H.YEAR*100 +  1
         WHEN H.week between  5 and  8 then H.YEAR*100 +  2
         WHEN H.week between  9 and 12 then H.YEAR*100 +  3
         WHEN H.week between 13 and 16 then H.YEAR*100 +  4
         WHEN H.week between 17 and 20 then H.YEAR*100 +  5
         WHEN H.week between 21 and 24 then H.YEAR*100 +  6
         WHEN H.week between 25 and 28 then H.YEAR*100 +  7
         WHEN H.week between 29 and 32 then H.YEAR*100 +  8
         WHEN H.week between 33 and 36 then H.YEAR*100 +  9
         WHEN H.week between 37 and 40 then H.YEAR*100 + 10
         WHEN H.week between 41 and 44 then H.YEAR*100 + 11
         WHEN H.week between 45 and 48 then H.YEAR*100 + 12
         WHEN H.week between 49 and 53 then H.YEAR*100 + 13
         else 0
       END)
/

  CREATE OR REPLACE VIEW "V_DELIVERYHISTORY_YEAR_MONTH" ("PROCESSBUSINESSUNIT_ID", "AMOUNTDELIVERED", "AMOUNTSHORTAGE", "AMOUNTORDERED", "AMOUNTSTANDARD", "DELIVERYDATE", "CUSTOMERNUMBER", "CUSTNAME", "CUSTOMERLANGUAGECODE", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINTNUMBER", "DIP_DESC", "PRODUCTGROUPCODE", "PRODUCTGROUPDESCRIPTION", "PRODUCTCODE", "TYPEOFMERCHANDISE", "PRODUCTDESCRIPTION", "PARENTPRODUCTCODE", "PARENTPRODUCTDESCRIPTION", "SIZECODE", "SIZEDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "PACKINDICATION", "LANGUAGE_CODE") AS 
  SELECT
       H.PROCESSBUSINESSUNIT_ID,
        h.amountdelivered, h.amountshortage, h.amountordered, h.amountstandard,h.deliverydate,
        CL.CUSTOMERNUMBER, CL.NAME custname, cl.LANGUAGECODE CUSTOMERLANGUAGECODE,
       dl.departmentnumber, dl.description departmentdesc,
       dpl.distributionpointnumber, dpl.description dip_desc,
       pg.CODE productgroupcode,
       (SELECT A.DESCRIPTION FROM PRODUCTGROUP_DESC A WHERE A.PRODUCTGROUP_ID = pg.PRODUCTGROUP_ID
                AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productgroupdescription,
       pl.CODE productcode, PRODUCT.typeofmerchandise,
       (SELECT B.DESCRIPTION FROM PRODUCT_LINK_DESC B WHERE B.PRODUCT_LINK_ID = h.PRODUCT_LINK_ID
                AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
       parentproduct.CODE parentproductcode,
       (SELECT E.DESCRIPTION FROM PRODUCT_LINK_DESC E WHERE E.PRODUCT_LINK_ID = h.PARENTPRODUCT_LINK_ID
                AND E.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) parentproductdescription,
       sl.CODE sizecode,
       (SELECT C.DESCRIPTION FROM SIZEDEFINITION_LINK_DESC C WHERE C.SIZEDEFINITION_LINK_ID = h.SIZEDEFINITION_LINK_ID
                AND C.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEdescription,
       fm.CODE FINISHINGMETHODCODE,
       (SELECT D.DESCRIPTION FROM FINISHINGMETHOD_DESC D WHERE D.FINISHINGMETHOD_ID = h.FINISHINGMETHOD_ID
                AND D.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODdescription,
       h.packindication,
       languages.code language_code
FROM DELIVERYHISTORY H LEFT OUTER JOIN PRODUCT ON (H.PRODUCT_LINK_ID = PRODUCT.PRODUCT_ID),
     CUSTOMER_LINK CL, department_link dl, distributionpoint_link dpl,
     PRODUCT_LINK pl LEFT OUTER JOIN PRODUCTGROUP pg ON (pl.PRODUCTGROUPCODE = pg.CODE),
     PRODUCT_LINK parentproduct,
     sizedefinition_link sl, FINISHINGMETHOD fm,
     languages
WHERE H.CUSTOMER_LINK_ID = CL.CUSTOMER_LINK_ID
      and h.department_link_id = dl.department_link_id
      and h.distributionpoint_link_id = dpl.distributionpoint_link_id
      and h.product_link_id = pl.product_link_id
      and h.sizedefinition_link_id = sl.sizedefinition_link_id
      and h.finishingmethod_id = fm.finishingmethod_id
      AND h.PARENTPRODUCT_LINK_ID = parentproduct.PRODUCT_LINK_ID
/

  CREATE OR REPLACE VIEW "V_DELIVERYHISTORY_YEAR_PLANT" ("PLANTCODE", "PLANTNAME", "PROCESSBUCODE", "PROCESSBUDESC", "MARKETSEGMENTCODE", "MARKETSEGMENTDESC", "YEAR_PERIOD", "AMT_DELIVERED", "AMT_SHORTAGE", "AMT_ORDERED", "AMT_STANDARD", "PRODUCTGROUPCODE", "PRODUCTCODE", "TYPEOFMERCHANDISE", "PRODUCTGROUPDESCRIPTION", "PRODUCTDESCRIPTION", "PARENTPRODUCTCODE", "SIZECODE", "FINISHINGMETHODCODE", "PARENTPRODUCTDESCRIPTION", "SIZEDESCRIPTION", "FINISHINGMETHODDESCRIPTION", "PACKINDICATION", "LANGUAGECODE", "WIDTH_S", "LENGTH_S") AS 
  select
  plant.code plantCode, plant.name plantName
, processBU.Code processbuCode, processBU.description processbuDesc, marketsegment.code marketsegmentCode
, ( select marketsegment_desc.description from marketsegment_desc where marketsegment_desc.marketsegment_id = marketsegment.marketsegment_id
  and marketsegment_desc.language_id = languages.language_id ) marketsegmentDesc
, ( case
    when dh.week between 1  and 4  then dh.year*100 +1
    when dh.week between 5  and 8  then dh.year*100 +2
    when dh.week between 9  and 12 then dh.year*100 +3
    when dh.week between 13 and 16 then dh.year*100 +4
    when dh.week between 17 and 20 then dh.year*100 +5
    when dh.week between 21 and 24 then dh.year*100 +6
    when dh.week between 25 and 28 then dh.year*100 +7
    when dh.week between 29 and 32 then dh.year*100 +8
    when dh.week between 33 and 36 then dh.year*100 +9
    when dh.week between 37 and 40 then dh.year*100 + 10
    when dh.week between 41 and 44 then dh.year*100 + 11
    when dh.week between 45 and 48 then dh.year*100 + 12
    when dh.week between 49 and 53 then dh.year*100 + 13
    else 0 end
  ) year_period
, sum(dh.amountdelivered) amt_delivered, sum(dh.amountshortage) amt_shortage
, sum(dh.amountordered) amt_ordered, sum(dh.amountstandard) amt_standard
, pg.code productgroupcode, pl.code productcode, product.typeofmerchandise
, ( select a.description from productgroup_desc a where a.productgroup_id = pg.productgroup_id
  and a.language_id = languages.language_id) productgroupdescription
, ( select b.description from product_link_desc b where b.product_link_id = dh.product_link_id
  and b.language_id = languages.language_id) productdescription
, parentproduct.code parentproductcode, sl.code sizecode, fm.code finishingmethodcode
, ( select e.description from product_link_desc e where e.product_link_id = dh.parentproduct_link_id
  and e.language_id = languages.language_id) parentproductdescription
, ( select c.description from sizedefinition_link_desc c where c.sizedefinition_link_id = dh.sizedefinition_link_id
  and c.language_id = languages.language_id) sizedescription
, ( select d.description from finishingmethod_desc d where d.finishingmethod_id = dh.finishingmethod_id
  and d.language_id = languages.language_id) finishingmethoddescription
, dh.packindication
, languages.code languagecode,
s.WIDTH WIDTH_S,s.LENGTH LENGTH_S--CSW
from
  deliveryhistory dh
    left outer join product on dh.product_link_id = product.product_id
    LEFT OUTER JOIN SIZEDEFINITION S ON (dh.SIZEDEFINITION_LINK_ID = S.SIZEDEFINITION_ID)
, product_link pl
    left outer join productgroup pg on pl.productgroupcode = pg.code
, product_link parentproduct, sizedefinition_link sl, finishingmethod fm
, customer cu, marketsegment
, businessunit processBu, plant
, languages
where
    dh.customer_link_id = cu.customer_id
    and cu.marketsegment_id = marketsegment.marketsegment_id
and dh.product_link_id = pl.product_link_id
and dh.sizedefinition_link_id = sl.sizedefinition_link_id
and dh.finishingmethod_id = fm.finishingmethod_id
and dh.parentproduct_link_id = parentproduct.product_link_id
and dh.Processbusinessunit_Id = processBu.Businessunit_Id
    and processBu.Plant_Id = plant.plant_id
group by
  plant.code, plant.name, dh.processbusinessunit_id, processBU.Businessunit_Id
, processBU.Code, processBU.description, marketsegment.code, marketsegment.marketsegment_id
, languages.code, languages.language_id
, pg.code, pg.productgroup_id, parentproduct.code, dh.parentproduct_link_id
, product.typeofmerchandise, pl.code, sl.code, fm.code, dh.product_link_id
, dh.sizedefinition_link_id, dh.finishingmethod_id, dh.packindication,s.WIDTH,s.LENGTH
, ( case
    when dh.week between 1  and 4  then dh.year*100 +1
    when dh.week between 5  and 8  then dh.year*100 +2
    when dh.week between 9  and 12 then dh.year*100 +3
    when dh.week between 13 and 16 then dh.year*100 +4
    when dh.week between 17 and 20 then dh.year*100 +5
    when dh.week between 21 and 24 then dh.year*100 +6
    when dh.week between 25 and 28 then dh.year*100 +7
    when dh.week between 29 and 32 then dh.year*100 +8
    when dh.week between 33 and 36 then dh.year*100 +9
    when dh.week between 37 and 40 then dh.year*100 + 10
    when dh.week between 41 and 44 then dh.year*100 + 11
    when dh.week between 45 and 48 then dh.year*100 + 12
    when dh.week between 49 and 53 then dh.year*100 + 13
    else 0 end
  )
/

  CREATE OR REPLACE VIEW "V_DELIVERYNOTE" ("CORRECTEDNOTENUMBER", "NOTENUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "LEGALNAME", "CUSTOMERSTREET", "CUSTOMERSTREET2", "CUSTOMERZIP", "CUSTOMERCITY", "CUSTOMERSTATE", "CUSTCOUNTRY", "CUSTCOUNTRY_DESC", "CUSTOMERCOUNTY", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "DELIVERYPOINTCODE", "CUSTOMERSTREET3", "DELIVERYPOINTDESCRIPTION", "SEQUENCENUMBER", "OCCUPANCY", "EMPLOYEENAME", "DELIVERYDATE", "ORIGINALDELIVERYDATE", "REMARK", "PROCESSBUDESCRIPTION", "PLANTCODE", "PLANTNAME", "PLANTWEBSITE", "PLANTLOGO", "PLANTEMAIL", "PLANTSTREET", "PLANTZIPCODE", "PLANTCITY", "PLANTSTATE", "PLANTPHONENO", "PLANTFAXNO", "PLANTCOUNTRY_CODE", "PLANTCOUNTRY_DESC", "WEIGHTUNIT", "PRINTDELNOTEPERCONTAINER", "CONTAINERRECORDINGACTIVE", "PRINTDELNOTEZEROLINES", "ROUTENUMBER", "ROUTEDESCRIPTION", "LOADINGDOCK", "STOPNUMBER", "SYSTEMUSER_ID", "TIMESTAMP", "CREATIONTIMESTAMP", "PROCESSEDTIMESTAMP", "PACKINGNOTE_ID", "ENDDATEFORUSE", "ORIGIN", "DELIVERYLAYOUTCODE", "WEEK", "LANGUAGECODE", "CUSTOMERLANGUAGECODE", "PRODUCTIONDATE", "SCANSONDELIVERYNOTE", "USELOCKEROBLIGATED", "FIXEDNUMBERBANK", "NUMBEROFGARMENTSINLOCKER", "NUMBEROFLOCKERS", "YEAR", "PRICESCALCULATED", "TOTALAMOUNT", "TOTALAMOUNTEXCLUDINGVAT", "WEIGHINGTICKET_ID", "DECIMALS", "INVOICEAMOUNTDECIMALS", "CURRENCYCODE", "VATNUMBER", "REFERENCENUMBER", "INTERNALVATNUMBER", "SEARCHNAME", "PROCESSBUCODE", "PUTUPREPORTPERCUSTOMER", "SIGNATUREREQUIRED", "PERSONIDENTIFICATION", "SIGNATURE", "SIGNATUREDATE", "SIGNATURETIME", "SIGNATURETIME24", "DISTRIBUTIONPOINT_ID", "PROCESSBUSINESSUNIT_ID", "SIGNATUREBARCODE", "CONTAINERTYPEDESCRIPTION", "SCANTIMESTAMP", "PLANT_DEP_CODE", "PLANT_DEP_DESC", "FREEOFCHARGEREASON_ID", "DELNOTETOEMAIL", "SCANNEDYN", "CHARGESERVICE", "CHARGERENT", "PLANTSTREET2", "PLANTSTREET3", "CORRECTIONREASONCODE", "CORRECTIONREASONCODEDESC", "CORRECTIONDATE", "TRANSPORTARTICLEDESCRIPTION", "SERVICEREP", "DAYDESCRIPTION", "FREE_REASON_CODE", "FREE_REASON_CODE_DESC", "WOREFNUMBER", "DELIVERYNOTEREMARKDESC", "DV_REFERENCE", "NUMBEROFPOSSIBLELINESWITHSCANS", "NOOFCONTAINERS", "HASLOCKERANAGEMENT", "STATUS_CODE") AS 
  select /*version 2.2*/
       pn.correctednotenumber, pn.notenumber, cu.customernumber, cu.name customername, cu.legalname, ad.street customerstreet, ad.street2 customerstreet2, ad.zipcode customerzip,
       ad.city customercity, ad.state customerstate, cco.code custcountry, cco.description custcountry_desc, ad.county customercounty, de.departmentnumber,
       de.description departmentdescription, dp.distributionpointnumber, dp.description distributionpointdescription, delp.code deliverypointcode, ad.street3 customerstreet3,
       delp.description deliverypointdescription, pn.sequencenumber, pn.occupancy, emp.name employeename, pn.deliverydate, pn.originaldeliverydate, pn.remark,
       procbu.description processbudescription, pl.code plantcode, pl.name plantname, pl.website plantwebsite, pl.logo plantlogo, pl.email plantemail, pla.street plantstreet,
       pla.zipcode plantzipcode, pla.city plantcity, pla.state plantstate, pl.phoneno plantphoneno, pl.faxno plantfaxno, pco.code plantcountry_code, pco.description plantcountry_desc,
       ss.value weightunit, ss1.value printdelnotepercontainer, ss2.value containerrecordingactive, ss3.value printdelnotezerolines, ro.routenumber, ro.description routedescription,
       coalesce(rc.loadingdock, ro.loadingdock) loadingdock,  pn.stopnumber, pn.systemuser_id, pn.timestamp, pn.creationtimestamp, pn.processedtimestamp, pn.packingnote_id,
       pn.enddateforuse, pn.origin, fl.code deliverylayoutcode, pn.week week, lan.code languagecode, cula.code customerlanguagecode, pn.productiondate productiondate,
       cu.scansondeliverynote, clm.uselockerobligated, clm.fixednumberbank, pn.numberofgarmentsinlocker, pn.numberoflockers, pn.year, pn.pricescalculated, pn.totalamount,
       pn.totalamountexcludingvat, pn.weighingticket_id, curr.decimals, curr.invoiceamountdecimals, curr.code currencycode, invbu.vatnumber vatnumber, pn.referencenumber,
       invbu.internalvatnumber, cu.searchname, procbu.code processbucode, ro.putupreportpercustomer, cu.signaturerequired, dsig.personidentification personidentification,
       dsig.signature signature, rc.drivingdate signaturedate, to_char(st.departuretime, 'fmhhfm:MI:AM') signaturetime, to_char(st.departuretime, 'fmhh24fm:MI') signaturetime24,
       pn.distributionpoint_id, pn.processbusinessunit_id, delp.signaturebarcode, cast(ss4.value as varchar2(60)) containertypedescription, dsig.scantimestamp, pld.code plant_dep_code,
       pld.description plant_dep_desc, pn.freeofchargereason_id, de.delnotetoemail, decode (dsig.scannedyn, 'Y', 'Yes','N','No') scannedyn, clm.chargeservice, clm.chargerent,
       pla.street2 plantstreet2, pla.street3 plantstreet3,
       (select rsc.code
          from reasoncode rsc
         where rsc.reasoncode_id = pn.correctionreasoncode_id) correctionreasoncode,
       (select rdc.description
          from reasoncode_desc rdc
         where rdc.reasoncode_id = pn.correctionreasoncode_id
           and rdc.language_id = lan.language_id) correctionreasoncodedesc,
       (select cn.deliverydate
          from packingnote cn
         where pn.correctednotenumber = cn.notenumber
           and pn.correctednotenumber <> 0) correctiondate,
       (select tad.description
          from transportarticle_desc tad
         where tad.transportarticle_id = pn.transportarticle_id
           and tad.language_id = lan.language_id) transportarticledescription,
       (select ee.name
          from employee ee
         where ee.employee_id = cu.serviceemployee_id) servicerep,
       (select dd.description
          from day_desc dd
         where dd.language_id = lan.language_id
           and dd.day_id = pn.daynumber) daydescription,
       (select r.code
          from reasoncode r
         where r.reasoncode_id = pn.freeofchargereason_id) free_reason_code,
       (select rd.description
          from reasoncode_desc rd
         where rd.reasoncode_id = pn.freeofchargereason_id
           and rd.language_id = lan.language_id) free_reason_code_desc,
       (select max(wo.referencenumber)
          from deliveryscan ds
               join issuehistory ih on ds.uniqueitem_link_id = ih.uniqueitem_link_id
               join workorder wo on ih.workorder_id = wo.workorder_id
         where ih.issuehistory_id = (select max(ih2.issuehistory_id)
                                       from issuehistory ih2
                                      where ih2.uniqueitem_link_id = ds.uniqueitem_link_id)
           and ds.packingnote_id = pn.packingnote_id
           and wo.deliverfrom = 2) worefnumber,
       (select dnrd.description
          from deliverynoteremark_desc dnrd
         where dnrd.deliverynoteremark_id = pn.deliverynoteremark_id
           and dnrd.language_id = cula.language_id) deliverynoteremarkdesc,
       (select listagg(x.reference, CHR(13))  within group(order by x.deliverydate)
          from (select dv.reference, min(dv.deliverydate) deliverydate
                  from deliveryvariations dv
                 where dv.packingnote_id = pn.packingnote_id
                   and dv.reference is not null
                 group by dv.reference) x) dv_reference,
       coalesce((select max(ds.packingnote_id)
                   from deliveryscan ds
                  where ds.packingnote_id = pn.packingnote_id),
                (select max(o.packingnote_id)
                   from outofcirculationhistory o
                  where o.packingnote_id = pn.packingnote_id), 0) numberofpossiblelineswithscans,
       coalesce((select count(pnc.packingnote_id)
                   from packingnotecontainer pnc
                  where pnc.packingnote_id = pn.packingnote_id), 0) noofcontainers,
       case when clm.customer_id = null then 'N'
            else 'Y'
       end haslockeranagement, sta.code status_code
  from packingnote pn
       left join employee emp on pn.employee_id = emp.employee_id
       left join route ro on pn.route_id = ro.route_id
       left join stop st
                 left join routecontrol rc on st.routecontrol_id = rc.routecontrol_id
       on pn.stop_id = st.stop_id
       left join deliverysignature dsig on pn.stop_id = dsig.stop_id and pn.deliverysignature_id = dsig.stop_id
       join distributionpoint dp
            join department de
                 join customer cu
                      left join formlayout fl on cu.deliverynotelayout_id = fl.formlayout_id
                      left join customerlockermanagement clm on cu.customer_id = clm.customer_id
                      join country cco on cu.country_id = cco.country_id
                      join languages cula on cu.language_id = cula.language_id
                      join currency curr on cu.currency_id = curr.currency_id
                 on de.customer_id = cu.customer_id
            on dp.department_id = de.department_id
       on pn.distributionpoint_id = dp.distributionpoint_id
       join deliverypoint delp
            join address ad on delp.deliveryaddress_id = ad.address_id
       on pn.deliverypoint_id = delp.deliverypoint_id
       join status sta on pn.status_id = sta.status_id and sta.statustype = 'PN' and (sta.code in ('20', '25', '30') or (pn.origin = 14 and sta.code = '40'))
       join businessunit procbu
            join plant pl
                 left join systemsetting ss on pl.plant_id = ss.plant_id and ss.name = 'WEIGHTUNIT'
                 left join systemsetting ss1 on pl.plant_id = ss1.plant_id and ss1.name = 'PRINTDELNOTEPERCONTAINER'
                 left join systemsetting ss2 on pl.plant_id = ss2.plant_id and ss2.name = 'CONTAINERRECORDINGACTIVE'
                 left join systemsetting ss3 on pl.plant_id = ss3.plant_id and ss3.name = 'PRINTDELNOTEZEROLINES'
                 left join systemsetting ss4 on pl.plant_id = ss4.plant_id and ss4.name = 'CONTAINERTYPEUNQBRCLABEL'
                 join address pla on pl.address_id = pla.address_id
                 join country pco on pl.country_id = pco.country_id
            on procbu.plant_id = pl.plant_id
       on pn.processbusinessunit_id = procbu.businessunit_id
       join plantdepartment pld on pn.plantdepartment_id = pld.plantdepartment_id
       join businessunit invbu on pn.invoicebusinessunit_id = invbu.businessunit_id
       cross join languages lan
/

  CREATE OR REPLACE VIEW "V_DELIVERYNOTEAPPENDIX" ("LINETYPE", "DELNUMBER", "STREET", "ZIPCODE", "DELNAME", "CITY", "COUNTY", "STATE", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "INVOICEDATE", "INVOICEHEADER_ID", "INVOICENUMBER", "PACKINGNOTE_ID", "NOTENUMBER", "DELIVERYDATE", "SHOWONINVOICEAPPENDIX", "ORIGIN", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "CUSTOMCODE", "CUSTOMDESC", "SIZECODE", "DELIVEREDAMOUNT", "PACKINGNOTELINE_ID", "WEIGHT", "WEIGHTDECIMALS", "PRICE", "DISCOUNTPERCENTAGE", "CURRENCYCODE", "PRICEDECIMALS", "INVOICEDECIMALS", "PNNOTININVOICE", "REMARK", "WEIGHTUNIT", "DEP_NUMBER", "DEP_DESCRIPTION", "FREEOFCHARGEREASON_ID", "PRICEFACTOR", "INVOICEBUSINESSUNIT_ID", "PROCESSBUSINESSUNIT_ID", "LANGUAGECODE") AS 
  select /*version 2.0*/
       case when pr.typeofmerchandise = 3 then 3-- sales items
       else 1 end linetype, coalesce(ih.deltocustomernumber, ih.billtocustomernumber) delnumber, ih.street,
       ih.zipcode, coalesce(ih.deltocustomername, ih.billtocustomername) delname, ih.city, ih.county,
       ih.state, ih.billtocustomernumber, ih.billtocustomername, ih.invoicedate, ih.invoiceheader_id,
       ih.invoicenumber, pn.packingnote_id, pn.notenumber, pn.deliverydate, pn.showoninvoiceappendix,
       pn.origin, cons.distributionpointnumber, cons.description distributionpointdesc,
       nvl(pnl.customcode, pr.code) customcode,
       nvl(pnl.customdescription,
           (select prd.description
              from product_desc prd
             where prd.product_id = pnl.product_id
               and prd.language_id = lan.language_id)
          ) customdesc,
       (select sz.code from sizedefinition sz where pnl.sizedefinition_id = sz.sizedefinition_id) sizecode,
       pnl.deliveredamount, pnl.packingnoteline_id,
       (select sum(pnc.grossweight - pnc.tareweight)
          from packingnotecontainer pnc
         where pn.packingnote_id = pnc.packingnote_id) weight,
       (select max(pnc.weightdecimals)
          from packingnotecontainer pnc
         where pn.packingnote_id = pnc.packingnote_id) weightdecimals,
       coalesce(pnl.price,
                pack_price.wash_price(dep.customer_id, pnl.product_id, pnl.sizedefinition_id, pnl.finishingmethod_id, pn.deliverydate)
               ) price,
       case when pr.typeofmerchandise = 3 then 0
       else (select min(l.discountpercentage)
               from invoicelineproduct ilp, invoiceline l
              where l.invoiceheader_id = ih.invoiceheader_id
                and l.invoiceline_id = ilp.invoiceline_id
                and ilp.product_link_id = pnl.product_id
                and ilp.finishingmethod_id = pnl.finishingmethod_id
                and l.invoicelinetype_id = 2
                and (ilp.sizedefinition_link_id = pnl.sizedefinition_id or
                    ilp.sizedefinition_link_id =
                    (select sizedefinition.sizedefinition_id
                       from sizedefinition
                      where sizedefinition.code = '*')))
       end discountpercentage,
       cur.code currencycode, cur.decimals pricedecimals,
       cur.invoiceamountdecimals invoicedecimals, 0 pnnotininvoice, pn.remark,
       (select ss.value
          from systemsetting ss
         where pl.plant_id = ss.plant_id
           and ss.name = 'WEIGHTUNIT') weightunit,
       dep.departmentnumber dep_number, dep.description dep_description, pn.freeofchargereason_id,
       (select max(ilp.pricefactor)
          from invoicelineproduct ilp, invoiceline l
         where l.invoiceheader_id = ih.invoiceheader_id
           and l.invoiceline_id = ilp.invoiceline_id
           and ilp.product_link_id = pnl.product_id
           and ilp.finishingmethod_id = pnl.finishingmethod_id
           and (ilp.sizedefinition_link_id = pnl.sizedefinition_id or
                ilp.sizedefinition_link_id =
                (select sizedefinition.sizedefinition_id
                   from sizedefinition
                  where sizedefinition.code = '*'))) pricefactor,
       ih.invoicebusinessunit_id, pn.processbusinessunit_id, lan.code languagecode
  from packingnoteline pnl
       join packingnote pn
            join status spn on pn.status_id = spn.status_id and spn.statustype = 'PN' and spn.code = '30'
            join businessunit procbu
                 join plant pl on procbu.plant_id = pl.plant_id
            on pn.processbusinessunit_id = procbu.businessunit_id
            join distributionpoint cons
                 join department dep on cons.department_id = dep.department_id
            on pn.distributionpoint_id = cons.distributionpoint_id
       on pnl.packingnote_id = pn.packingnote_id
       join invoiceheader ih
            join status sih on ih.status_id = sih.status_id and sih.statustype = 'IN'
            join currency cur on ih.currency_id = cur.currency_id
       on pnl.invoiceheader_id = ih.invoiceheader_id
       join product pr on pnl.product_id = pr.product_id
       cross join languages lan
 where ih.documenttype = 1
 union all
select distinct 2 linetype, coalesce(ih.deltocustomernumber, ih.billtocustomernumber) delnumber,
       ih.street, ih.zipcode, coalesce(ih.deltocustomername, ih.billtocustomername) delname,
       ih.city, ih.county, ih.state, ih.billtocustomernumber, ih.billtocustomername,
       ih.invoicedate, ih.invoiceheader_id, ih.invoicenumber, pn.packingnote_id,
       pn.notenumber, pn.deliverydate, pn.showoninvoiceappendix, pn.origin,
       cons.distributionpointnumber, cons.description distributionpointdesc, '' customcode,
       '' customdesc, '' sizecode, 0 deliveredamount, 0 packingnoteline_id,
       (select sum(pncs.grossweight - pncs.tareweight)
          from packingnotecontainer pncs
         where pncs.packingnote_id = pn.packingnote_id) weight, pnc.weightdecimals, 0 price,
       0 discountpercentage, cur.code currencycode, cur.decimals pricedecimals,
       cur.invoiceamountdecimals invoicedecimals, 0 pnnotininvoice, pn.remark,
       (select ss.value
          from systemsetting ss
         where pl.plant_id = ss.plant_id
           and ss.name = 'WEIGHTUNIT') weightunit,
       dep.departmentnumber dep_number, dep.description dep_description,
       pn.freeofchargereason_id, 1 pricefactor, ih.invoicebusinessunit_id,
       pn.processbusinessunit_id, lan.code languagecode
  from packingnotecontainer pnc
       join packingnote pn
            join status spn on pn.status_id = spn.status_id and spn.statustype = 'PN' and spn.code = '30'
            join businessunit procbu
                 join plant pl on procbu.plant_id = pl.plant_id
            on pn.processbusinessunit_id = procbu.businessunit_id
            join distributionpoint cons
                 join department dep on cons.department_id = dep.department_id
            on pn.distributionpoint_id = cons.distributionpoint_id
       on pnc.packingnote_id = pn.packingnote_id
       join invoiceheader ih
            join status sih on ih.status_id = sih.status_id and sih.statustype = 'IN'
            join currency cur on ih.currency_id = cur.currency_id
       on pnc.invoiceheader_id = ih.invoiceheader_id
       cross join languages lan
 where ih.documenttype = 1
   and not exists (select 1 from packingnoteline pnl where pnl.packingnote_id = pn.packingnote_id)
/

  CREATE OR REPLACE VIEW "V_DELIVERYNOTEAPPENDIX_AUX" ("NOTENUMBER", "PACKINGNOTE_ID", "WEIGHINGCATEGORYCODE", "SHOWONINVOICEAPPENDIX", "ORIGIN", "CUSTOMERNUMBER", "WEIGHINGCATEGORYDESC", "WEIGHTQTY", "WEIGHTPRICE", "WEIGHTDISCOUNT", "LANGUAGECODE") AS 
  select /*version 2.0*/
       pn.notenumber, pnc.packingnote_id, wgh.code weighingcategorycode,
       pn.showoninvoiceappendix, pn.origin, cu.customernumber,
       (select wcd.description
          from weighingcategory_desc wcd
         where wcd.weighingcategory_id = wgh.weighingcategory_id
           and wcd.language_id = lan.language_id) weighingcategorydesc,
       (pnc.grossweight - pnc.tareweight) weightqty,
       pack_price.weight_price(cu.customer_id, wgh.weighingcategory_id, case
                                  when whgcu.invoicemethod = 4 then 'Y'
                                  else 'N' end, trunc(sysdate)) weightprice,
       coalesce(pack_price.weight_discount(cu.customer_id, wgh.weighingcategory_id, 'N', trunc(sysdate)), 0) weightdiscount,
       lan.code languagecode
  from packingnotecontainer pnc
       join weighingcategpercustomer whgcu
            join customer cu on whgcu.customer_id = cu.customer_id
       on pnc.weighingcategory_id = whgcu.weighingcategory_id
       join weighingcategory wgh on pnc.weighingcategory_id = wgh.weighingcategory_id
       join packingnote pn on pnc.packingnote_id = pn.packingnote_id
       cross join languages lan
 where ((whgcu.weightclean = 'Y' and whgcu.invoicemethod = 3)
       or (whgcu.weightclean = 'N' and whgcu.invoicemethod = 4))
   and sysdate between whgcu.dateactive and whgcu.dateinactive
/

  CREATE OR REPLACE VIEW "V_DELIVERYNOTEDETAIL" ("PACKINGNOTE_ID", "FROMSTOCK", "PRIMARYID", "WEARERNUMBER", "WEARERFULLNAME", "STAYTYPE", "STAYNR", "PRODUCTCODE", "SIZECODE", "REASON", "REPLACEMENTPRIMARYID", "LANGUAGE_CODE") AS 
  select ds.packingnote_id, ds.fromstock, ui.primaryid, wr.wearernumber, wr.fullname wearerfullname, st.staytype, st.staynr
       , (select pl.code from product_link pl where ds.product_link_id = pl.product_link_id) productcode
       , (select sl.code from sizedefinition_link sl where ds.sizedefinition_link_id = sl.sizedefinition_link_id) sizecode
       , (select rd.description from reasoncode_desc rd where ds.reasoncode_id = rd.reasoncode_id and rd.language_id = lan.language_id) reason
			 , (select rui.primaryid from workorderlinereplacement wolr, uniqueitem rui where ds.uniqueitem_link_id = wolr.replacementuniqueitem_link_id and wolr.uniqueitem_link_id = rui.uniqueitem_id) replacementprimaryid
			 , lan.code language_code
from deliveryscan ds, uniqueitem ui, stay st, weareremployment we, wearer wr, languages lan
where ds.weareremployment_link_id = we.weareremployment_id and we.wearer_id = wr.wearer_id and
      ds.uniqueitem_link_id = ui.uniqueitem_id and ui.prevstay_id = st.stay_id --and st.staytype = 1 and st.staynr in (3, 5)
/

  CREATE OR REPLACE VIEW "V_DELIVERYNOTELINE" ("PACKINGNOTENUMBER", "PRODUCTCODE", "PRODUCTCUSTOMCODE", "PRODUCTCUSTOMDESCRIPTION", "SIZECODE", "PACKINGSEQUENCE", "STANDARDAMOUNT", "VARIATIONAMOUNT", "DELIVEREDAMOUNT", "TOBEDELIVEREDAMOUNT", "REMARKFORPACKINGINSTRUCTIONS", "USERNAME", "TIMESTAMP", "LANGUAGECODE", "TYPEOFMERCHANDISE", "NOCHARGEFIRSTISSUE", "NOCHARGEACTIVESEASON", "NOCHARGENOTCOG", "LINE_ORIGIN", "PACKINGNOTELINE_ID", "AMOUNT", "TAXGROUPCODE", "NOCHARGEPREVSHORTAGE", "NOCHARGEPREVREJECTED", "DELIVERYSCHEME", "BU_CODE", "TRANSPORTARTICLEDESCRIPTION", "PRODUCTDESCRIPTION", "PRODUCTGROUPDESCRIPTION", "PGCUSTOMDESCRIPTION", "SIZEDESCRIPTION", "FINISHINGMETHODDESCRIPTION", "FREEOFCHARGEREASON", "FREEOFCHARGEREASON_DESC", "REGUNIT", "SEQUENCENUMBER", "FINISHINGMETHODCODE", "DELIVERYNOTELAYOUT", "PRODUCTLONGDESCRIPTION", "PRICE", "OLD_QTY", "PRICECOG", "DECIMALS", "AMOUNTDECIMALS") AS 
  select /*version 2.1*/
       pn.notenumber packingnotenumber, prd.code productcode, pnl.customcode productcustomcode, pnl.customdescription productcustomdescription,
       sd.code sizecode, pnl.packingsequence, pnl.standardamount, pnl.variationamount, pnl.deliveredamount, pnl.tobedeliveredamount,
       pnl.remarkforpackinginstructions, pnl.systemuser_id username, pnl.timestamp, lan.code languagecode, prd.typeofmerchandise,
       pnl.nochargefirstissue, pnl.nochargeactiveseason, pnl.deliveredcogqty nochargenotcog, pnl.origin line_origin, pnl.packingnoteline_id,
       pnl.amount, pnl.taxgroupcode,
       (pnl.nochargeprevshortage + coalesce((select sum(dv.amount)
                                                           from deliveryvariations dv
                                                          where dv.causenote_id = pnl.packingnote_id
                                                            and dv.product_id = pnl.product_id
                                                            and dv.sizedefinition_id = pnl.sizedefinition_id
                                                            and dv.finishingmethod_id = pnl.finishingmethod_id
                                                            and dv.origin = 1
                                                            and dv.soilcountsubtype = 2), 0)) nochargeprevshortage,
       (pnl.nochargeprevrejected + coalesce((select sum(dv.amount)
                                                           from deliveryvariations dv
                                                          where dv.causenote_id = pnl.packingnote_id
                                                            and dv.product_id = pnl.product_id
                                                            and dv.sizedefinition_id = pnl.sizedefinition_id
                                                            and dv.finishingmethod_id = pnl.finishingmethod_id
                                                            and dv.origin = 1
                                                            and dv.soilcountsubtype = 3), 0)) nochargeprevrejected,
       nvl((select min(ds.code)
              from productlistperdistribpoint plpd
                   join standarddeliveryline sdl on plpd.productlistperdistribpoint_id = sdl.productlistperdistribpoint_id
                   join deliveryscheme ds on sdl.deliveryscheme_id = ds.deliveryscheme_id
                   join seasonweek sw on sw.season_id = sdl.season_id
                   join standarddeliveryamount sda on sda.standarddeliveryline_id = sdl.standarddeliveryline_id
                  where plpd.distributionpoint_id = pn.distributionpoint_id
                    and plpd.product_id = pnl.product_id
                    and plpd.sizedefinition_id = pnl.sizedefinition_id
                    and plpd.finishingmethod_id = pnl.finishingmethod_id
                    and sdl.dateactive < pn.deliverydate
                     and sdl.dateinactive > pn.deliverydate
                     and sw.weeknumber = getisoweek(pn.deliverydate)
                     and sda.day_id = getdaynumber(pn.deliverydate)),
           (select min(ds.code)
              from productlistperdistribpoint plpd
                   join standarddeliveryline sdl
                        left join deliveryscheme ds on sdl.deliveryscheme_id = ds.deliveryscheme_id
                   on plpd.productlistperdistribpoint_id = sdl.productlistperdistribpoint_id
             where plpd.distributionpoint_id = pn.distributionpoint_id
               and plpd.product_id = pnl.product_id
               and plpd.sizedefinition_id = pnl.sizedefinition_id
               and plpd.finishingmethod_id = pnl.finishingmethod_id
               and sdl.dateactive < pn.deliverydate
               and sdl.dateinactive > pn.deliverydate)) deliveryscheme,
       (select bu.code
          from businessunit bu
         where bu.businessunit_id = pn.processbusinessunit_id) bu_code,
       (select tad.description
          from transportarticle_desc tad
         where tad.transportarticle_id = pn.transportarticle_id
           and tad.language_id = lan.language_id) transportarticledescription,
       (select pd.description
          from product_desc pd
         where pd.product_id = pnl.product_id
           and pd.language_id = lan.language_id) productdescription,
       (select ad.description
          from productgroup_desc ad
         where ad.productgroup_id = prd.productgroup_id
           and ad.language_id = lan.language_id) productgroupdescription,
       (select pgpc.customdescritpion
          from productgrouppercustomer pgpc
               join department dep on pgpc.customer_id = dep.customer_id
               join distributionpoint dp on dep.department_id = dp.department_id
         where pgpc.productgroup_id = prd.productgroup_id
           and dp.distributionpoint_id = pn.distributionpoint_id) pgcustomdescription,
       (select szd.description
          from sizedefinition_desc szd
         where szd.sizedefinition_id = pnl.sizedefinition_id
           and szd.language_id = lan.language_id) sizedescription,
       (select fmd.description
          from finishingmethod_desc fmd
         where fmd.finishingmethod_id = pnl.finishingmethod_id
           and fmd.language_id = lan.language_id) finishingmethoddescription,
       (select rc.code
          from reasoncode rc
         where rc.reasoncode_id = pnl.freeofchargereason_id) freeofchargereason,
       (select rd.description
          from reasoncode_desc rd
         where rd.reasoncode_id = pnl.freeofchargereason_id and
               rd.language_id = lan.language_id) freeofchargereason_desc,
       (select rg.code
          from registrationunit rg
         where rg.registrationunit_id = prd.registrationunit_id) regunit,
       (select max(psz.sequencenumber)
          from productsize psz
         where psz.product_id = prd.product_id
           and psz.sizedefinition_id = sd.sizedefinition_id) sequencenumber,
       (select fm.code
          from finishingmethod fm
         where fm.finishingmethod_id = pnl.finishingmethod_id) finishingmethodcode,
       (select fl.code
          from formlayout fl
               join customer c
                    join department dep
                         join distributionpoint dp on dep.department_id = dp.department_id
                    on  c.customer_id = dep.customer_id
               on fl.formlayout_id = c.deliverynotelayout_id
         where dp.distributionpoint_id = pn.distributionpoint_id) deliverynotelayout,
       (select pds.longdescription
          from product_desc pds
         where pds.product_id = pnl.product_id
           and pds.language_id = lan.language_id) productlongdescription,
       case when pnl.price is null then 0
            else pnl.price
        end price,
       case when pn.correctednotenumber = 0 then 0
            else (select sum(pal.deliveredamount)
                    from packingnote pa
                         join packingnoteline pal on pa.packingnote_id = pal.packingnote_id
                   where pal.product_id = pnl.product_id
                     and pal.sizedefinition_id = pnl.sizedefinition_id
                     and pal.finishingmethod_id = pnl.finishingmethod_id
                     and pa.notenumber = pn.correctednotenumber)
        end old_qty,
       case when pnl.pricecog is null then 0
            else pnl.pricecog
        end pricecog,
        (select crr.decimals
          from currency crr
               join customer cu
                    join department d
                         join distributionpoint dp on d.department_id = dp.department_id
                    on cu.customer_id = d.customer_id
               on crr.currency_id = cu.currency_id
         where dp.distributionpoint_id = pn.distributionpoint_id) decimals,
        (select crr.invoiceamountdecimals
          from currency crr
               join customer cu
                    join department d
                         join distributionpoint dp on d.department_id = dp.department_id
                    on cu.customer_id = d.customer_id
               on crr.currency_id = cu.currency_id
         where dp.distributionpoint_id = pn.distributionpoint_id) amountdecimals
   from packingnoteline pnl
        join packingnote pn on pnl.packingnote_id = pn.packingnote_id
        join product prd on pnl.product_id = prd.product_id
        join sizedefinition sd on pnl.sizedefinition_id = sd.sizedefinition_id
  cross join languages lan
/

  CREATE OR REPLACE VIEW "V_DELIVERYNOTELINE_PC" ("PACKINGNOTENUMBER", "PRODUCTCODE", "PRODUCTDESCRIPTION", "PRODUCTGROUPDESCRIPTION", "PGCUSTOMDESCRIPTION", "PRODUCTCUSTOMCODE", "PRODUCTCUSTOMDESCRIPTION", "SIZECODE", "SIZEDESCRIPTION", "FINISHINGMETHODDESCRIPTION", "PACKPROD_CODE", "PACKPROD_PROD_DESC", "PACKPROD_PACKSEQUENCE", "PACKPROD_SIZE_CODE", "PACKPROD_SIZE_DESC", "PACKPROD_FINMETH_DESC", "PACKPROD_REMARK", "PACKPROD_LOCATION", "PACKPROD_AMOUNT", "PACKINGSEQUENCE", "STANDARDAMOUNT", "VARIATIONAMOUNT", "DELIVEREDAMOUNT", "TOBEDELIVEREDAMOUNT", "REMARKFORPACKINGINSTRUCTIONS", "USERNAME", "TIMESTAMP", "LANGUAGECODE", "TYPEOFMERCHANDISE", "FREEOFCHARGEREASON", "FREEOFCHARGEREASON_DESC", "NOCHARGEFIRSTISSUE", "NOCHARGEACTIVESEASON", "NOCHARGENOTCOG", "LINE_ORIGIN", "PRICE", "AMOUNT", "TAXGROUPCODE", "REGUNIT", "OLD_QTY", "PRICECOG", "SEQUENCENUMBER", "FINISHINGMETHODCODE", "BU_CODE", "DECIMALS", "AMOUNTDECIMALS") AS 
  select /*version 2.0*/
       pn.notenumber packingnotenumber, pr.code productcode,
       (select description
           from product_desc p
          where p.product_id = pnl.product_id
            and p.language_id = lan.language_id) productdescription,
       (select description
           from productgroup_desc a
          where a.productgroup_id = pr.productgroup_id
            and a.language_id = lan.language_id) productgroupdescription,
       (select pgpc.customdescritpion
           from productgrouppercustomer pgpc, distributionpoint dp, department dep
          where pgpc.productgroup_id = pr.productgroup_id
            and pgpc.customer_id = dep.customer_id
            and dep.department_id = dp.department_id
            and dp.distributionpoint_id = pn.distributionpoint_id) pgcustomdescription, pnl.customcode productcustomcode,
       pnl.customdescription productcustomdescription, sd.code sizecode,
       (select description
           from sizedefinition_desc s
          where s.sizedefinition_id = pnl.sizedefinition_id
            and s.language_id = lan.language_id) sizedescription,
       (select description
           from finishingmethod_desc f
          where f.finishingmethod_id = pnl.finishingmethod_id
            and f.language_id = lan.language_id) finishingmethoddescription,
       (select p.code from product p where pc.product_id = p.product_id) packprod_code,
       (select pd.description
           from product_desc pd
          where pd.product_id = pc.product_id
            and pd.language_id = lan.language_id) packprod_prod_desc, pc.packsequence packprod_packsequence,
       (select sd.code from sizedefinition sd where sd.sizedefinition_id = pc.sizedefinition_id) packprod_size_code,
       (select sde.description
           from sizedefinition_desc sde
          where sde.sizedefinition_id = pc.sizedefinition_id
            and sde.language_id = lan.language_id) packprod_size_desc,
       (select fd.description
           from finishingmethod_desc fd
          where pc.finishingmethod_id = fd.finishingmethod_id
            and fd.language_id = lan.language_id) packprod_finmeth_desc, pc.remark packprod_remark, pc.location packprod_location,
       pc.amount packprod_amount, pnl.packingsequence packingsequence, pnl.standardamount standardamount, pnl.variationamount variationamount,
       pnl.deliveredamount deliveredamount, pnl.tobedeliveredamount tobedeliveredamount, pnl.remarkforpackinginstructions remarkforpackinginstructions,
       pnl.systemuser_id username, pnl.timestamp, lan.code languagecode, pr.typeofmerchandise typeofmerchandise,
       (select r.code from reasoncode r where r.reasoncode_id = pnl.freeofchargereason_id) freeofchargereason,
       (select description
           from reasoncode_desc rd
          where rd.reasoncode_id = pnl.freeofchargereason_id
            and rd.language_id = lan.language_id) freeofchargereason_desc, pnl.nochargefirstissue nochargefirstissue,
       pnl.nochargeactiveseason nochargeactiveseason, pnl.deliveredcogqty nochargenotcog, pnl.origin line_origin, pnl.price price, pnl.amount amount,
       pnl.taxgroupcode taxgroupcode, (select rg.code from registrationunit rg where rg.registrationunit_id = pr.registrationunit_id) regunit,
       (case
         when pn.correctednotenumber = 0 then
          0
         else
          (select sum(pal.deliveredamount)
             from packingnote pa, packingnoteline pal
            where pa.packingnote_id = pal.packingnote_id
              and pal.product_id = pnl.product_id
              and pal.sizedefinition_id = pnl.sizedefinition_id
              and pal.finishingmethod_id = pnl.finishingmethod_id
              and pa.notenumber = pn.correctednotenumber)
       end) old_qty, pnl.pricecog pricecog,
       (select max(psz.sequencenumber)
           from productsize psz
          where psz.product_id = pr.product_id
            and psz.sizedefinition_id = sd.sizedefinition_id) sequencenumber,
       (select code from finishingmethod f where f.finishingmethod_id = pnl.finishingmethod_id) finishingmethodcode, bu.code bu_code,
       (select crr.decimals
          from currency crr
               join customer cu
                    join department d
                         join distributionpoint dp on d.department_id = dp.department_id
                    on cu.customer_id = d.customer_id
               on crr.currency_id = cu.currency_id
         where dp.distributionpoint_id = pn.distributionpoint_id) decimals,
       (select crr.invoiceamountdecimals
          from currency crr
               join customer cu
                    join department d
                         join distributionpoint dp on d.department_id = dp.department_id
                    on cu.customer_id = d.customer_id
               on crr.currency_id = cu.currency_id
         where dp.distributionpoint_id = pn.distributionpoint_id) amountdecimals
  from packingnoteline pnl
  left join packcontents pc on pc.pack_id = pnl.product_id
  join packingnote pn
       join businessunit bu on pn.processbusinessunit_id = bu.businessunit_id
  on pnl.packingnote_id = pn.packingnote_id
  join product pr on pnl.product_id = pr.product_id
  join sizedefinition sd on pnl.sizedefinition_id = sd.sizedefinition_id
 cross join languages lan
/

  CREATE OR REPLACE VIEW "V_DELIVERYNOTES2SEND" ("PACKINGNOTE_ID", "NOTENUMBER", "BUSINESSUNIT_ID", "CODE", "CP_NUMBER", "CP_NAME", "CP_EMAIL", "CUSTOMERNUMBER", "CU_NAME", "CU_EMAIL", "ORIGIN", "DELIVERYDATE", "STOPSTATUS") AS 
  select pn.packingnote_id,
       pn.notenumber,
       bu.businessunit_id,
       bu.code,
       cc.contactpersonnumber cp_number,
       cc.name                cp_name,
       cc.email               cp_email,
       cu.customernumber,
       cu.name                cu_name,
       cu.email               cu_email,
       pn.origin,
       pn.deliverydate,
       (case when s.reasoncode_id != null then '0'
       else (case when s.arrivaltime is null then '1'
         else '2' end) end) as StopStatus
  from packingnote       pn left outer join stop s on s.stop_id = pn.stop_id,
       businessunit      bu,
       distributionpoint cp,
       department        dp,
       customer          cu,
       contactperson     cc
 where bu.businessunit_id = pn.processbusinessunit_id
   and cp.distributionpoint_id = pn.distributionpoint_id
   and dp.department_id = cp.department_id
   and cu.customer_id = dp.customer_id
   and cc.contactperson_id = dp.contactperson_id
   and dp.delnotetoemail = 'Y'
   and pn.emailstatus = 1
   and pn.emailmaybesent = 'Y'
   and pn.status_id = (select st.status_id from status st where st.statustype = 'PN' and st.code = '30')
   and pn.origin not in (6,7,11,12)
/

  CREATE OR REPLACE VIEW "V_DELIVERYNOTES2SENDCLIENT" ("PACKINGNOTE_ID", "NOTENUMBER", "BUSINESSUNIT_ID", "CODE", "CP_NUMBER", "CP_NAME", "CP_EMAIL", "CUSTOMERNUMBER", "CU_NAME", "CU_EMAIL", "ORIGIN") AS 
  select pn.packingnote_id,
       pn.notenumber,
       bu.businessunit_id,
       bu.code,
       cc.contactpersonnumber cp_number,
       cc.name                cp_name,
       cc.email               cp_email,
       cu.customernumber,
       cu.name                cu_name,
       cu.email               cu_email,
       pn.origin
  from packingnote       pn,
       businessunit      bu,
       distributionpoint cp,
       department        dp,
       customer          cu,
       contactperson     cc
 where bu.businessunit_id = pn.processbusinessunit_id
   and cp.distributionpoint_id = pn.distributionpoint_id
   and dp.department_id = cp.department_id
   and cu.customer_id = dp.customer_id
   and cc.contactperson_id = dp.contactperson_id
   and dp.delnotetoemail = 'Y'
   and pn.emailstatus = 1
   and pn.emailmaybesent = 'Y'
   and pn.status_id != (select st.status_id from status st where st.statustype = 'PN' and st.code = '40')
   and pn.origin not in (6,7)
/

  CREATE OR REPLACE VIEW "V_DELIVERYNOTESPECIAL" ("PACKINGNOTE_ID", "PRIMARYID", "WEARERNUMBER", "WEARERFULLNAME", "STAYTYPE", "STAYNR", "PRODUCTCODE") AS 
  select ds.packingnote_id, ui.primaryid, wr.wearernumber, wr.fullname wearerfullname, st.staytype, st.staynr
       , (select pl.code from product_link pl where ds.product_link_id = pl.product_link_id) productcode
from deliveryscan ds, uniqueitem ui, stay st, weareremployment we, wearer wr
where ds.weareremployment_link_id = we.weareremployment_id and we.wearer_id = wr.wearer_id and
      ds.uniqueitem_link_id = ui.uniqueitem_id and ui.prevstay_id = st.stay_id and st.staytype = 1 and st.staynr in (31, 32)
/

  CREATE OR REPLACE VIEW "V_DELIVERYNOTETAX" ("PACKINGNOTE_ID", "TAXGROUPCODE", "TAXGROUPDESCRIPTION", "TAXPERCENTAGE", "AMOUNT", "AMOUNTDECIMALS") AS 
  select /*version 1.0*/
       pt.packingnote_id, pt.taxgroupcode, pt.taxgroupdescription, pt.taxpercentage, pt.amount,
       (select crr.invoiceamountdecimals
          from currency crr
               join customer cu
                    join department d
                         join distributionpoint dp
                              join packingnote pn on dp.distributionpoint_id = pn.distributionpoint_id
                         on d.department_id = dp.department_id
                    on cu.customer_id = d.customer_id
               on crr.currency_id = cu.currency_id
         where pn.packingnote_id = pt.packingnote_id) amountdecimals
       from packingnotetax pt
/

  CREATE OR REPLACE VIEW "V_DELIVERYNOTE_KNT" ("PACKINGNOTE_ID", "SEQUENCENUMBER", "TAREWEIGHT", "GROSSWEIGHT", "SOILPORTION", "WEIGHTDECIMALS", "WEIGHINGSEQUENCENR", "WEIGHINGTIMESTAMP", "CONTAINERTYPE_CODE", "CONTAINERTYPE_DEFAULTTARAW", "CONTAINERTYPE_ACTIVE", "DISINFECTBEFOREDELIVERY", "WEIGHCAT_CODE", "WEIGHCAT_LEGACYCODE", "PRICE", "AMOUNT", "TAXGROUPCODE", "SPECIALQUANTITY", "SPECIALLENGTH", "SPECIALWIDTH", "LANGUAGECODE", "EXTRAINPUT", "WEIGHINGUSE", "CONTAINER_PRIMARYID", "WEIGHINGCATEGORYDESC", "CONTAINERTYPE_DESC", "SPREGUNIT", "REGUNITDECIMALS", "TRANSPORTARTICLEDESCRIPTION", "BU_CODE") AS 
  select --+index(pnc XAK1PACKINGNOTECONTAINER) index(CT XPKCONTAINERTYPE)
      /* version 1.1*/
       pnc.packingnote_id, pnc.sequencenumber, pnc.tareweight, pnc.grossweight, pnc.soilportion, pnc.weightdecimals, pnc.weighingsequencenr,
       pnc.weighingtimestamp, ct.code containertype_code, ct.defaulttaraweight containertype_defaulttaraw, ct.active containertype_active,
       ct.disinfectbeforedelivery, wc.code weighcat_code, wc.legacyweighingcategorycode weighcat_legacycode, pnc.price, pnc.amount, pnc.taxgroupcode,
       pnc.specialquantity, pnc.speciallength, pnc.specialwidth, lan.code languagecode, wc.extrainput, coalesce(wc.weighinguse,0) weighinguse,
       (select c.primaryid
          from container c
         where c.container_id = pnc.container_id) container_primaryid,
       (select wd.description
          from weighingcategory_desc wd
         where wd.weighingcategory_id = wc.weighingcategory_id
           and wd.language_id = lan.language_id) weighingcategorydesc,
       (select ctd.description
          from containertype_desc ctd
         where ctd.containertype_id = ct.containertype_id
           and ctd.language_id = lan.language_id) containertype_desc,
       (select rg.code
          from registrationunit rg
         where rg.registrationunit_id = wc.registrationunit_id) spregunit,
       (select rg.decimals
          from registrationunit rg
         where rg.registrationunit_id= wc.registrationunit_id) regunitdecimals,
       (select tad.description
          from transportarticle_desc tad
               join packingnote pn on tad.transportarticle_id = pn.transportarticle_id
         where pn.packingnote_id = pnc.packingnote_id
           and tad.language_id = lan.language_id) transportarticledescription,
       (select bu.code
          from businessunit bu
               join packingnote png on bu.businessunit_id = png.processbusinessunit_id
         where png.packingnote_id = pnc.packingnote_id) bu_code
  from packingnotecontainer pnc
       left join containertype ct on ct.containertype_id = pnc.containertype_id
       left join weighingcategory wc on wc.weighingcategory_id = pnc.weighingcategory_id
       cross join languages lan
/

  CREATE OR REPLACE VIEW "V_DELIVERYNOTE_PACKCONTENTS" ("PACKINGNOTENUMBER", "PACK_ID", "PACKCONTENTS_ID", "PACKSEQUENCE", "PRODUCT_ID", "PRODUCT_CODE", "PRODUCT_DESC", "SIZEDEFINITION_ID", "SIZE_CODE", "SIZE_DESC", "FINISHINGMETHOD_ID", "FINMETH_CODE", "FINMETH_DESC", "REMARK", "LOCATION", "AMOUNT", "LANGUAGE_CODE") AS 
  select (select pn.notenumber from packingnoteline pnl, packingnote pn where pnl.packingnote_id = pn.packingnote_id
        and pnl.product_id = pc.pack_id ) packingnotenumber
       , pc.pack_id, pc.packcontents_id, pc.packsequence
       , pc.product_id, p.code product_code
       , (select pd.description from product_desc pd where pd.product_id = p.product_id
                 and pd.language_id = l.language_id) product_desc
       , pc.sizedefinition_id, s.code size_code
       , (select sd.description from sizedefinition_desc sd where sd.sizedefinition_id = s.sizedefinition_id
                 and sd.language_id = l.language_id) size_desc
       , pc.finishingmethod_id, f.code finMeth_code
       , (select fd.description from finishingmethod_desc fd where fd.finishingmethod_id = f.finishingmethod_id
                 and fd.language_id = l.language_id) finMeth_desc
       , pc.remark, pc.location, pc.amount
       , l.code language_code
from packcontents pc, product p, sizedefinition s, finishingmethod f, languages l
where pc.product_id = p.product_id
      and pc.sizedefinition_id = s.sizedefinition_id
      and pc.finishingmethod_id = f.finishingmethod_id
/

  CREATE OR REPLACE VIEW "V_DELIVERYNOTE_POD" ("PACKINGNOTE_ID", "CONTAINERTYPE", "IDCODE", "DELIVERYSCANTIMESTAMP", "LANGUAGECODE") AS 
  SELECT  PC.PACKINGNOTE_ID,
       (SELECT CTD.DESCRIPTION FROM CONTAINERTYPE_DESC CTD
         WHERE CTD.CONTAINERTYPE_ID = PC.CONTAINERTYPE_ID
           AND CTD.LANGUAGE_ID=L.LANGUAGE_ID) CONTAINERTYPE,
       NVL(C.PRIMARYID,PC.BAGLABELIDCODE) IDCODE,
       PC.DELIVERYSCANTIMESTAMP,
       L.CODE LANGUAGECODE
 FROM PACKINGNOTECONTAINER PC
    LEFT OUTER JOIN CONTAINER C ON  PC.CONTAINER_ID=C.CONTAINER_ID,
          LANGUAGES L
where PC.CONTAINER_ID=C.CONTAINER_ID
/

  CREATE OR REPLACE VIEW "V_DELIVERYPERDAY" ("LINETYPE", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "PRODUCTGROUPCODE", "PRODUCTGROUPDESCRIPTION", "PRODUCTCODE", "PACKINDICATION", "PRODUCTDESCRIPTION", "TYPEOFMERCHANDISE", "SIZECODE", "SIZEDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "DATEACTIVE", "DATEINACTIVE", "YEARWEEK", "DAYNUMBER", "DELIVERYDATE", "CUST_DATEINACTIVE", "STD_AMOUNT", "AMOUNTDELIVERED", "CUSTOMERLANGUAGECODE", "LANGUAGECODE", "BUSINESSUNIT_ID") AS 
  select 1 linetype, cust.customer_id, cust.customernumber, cust.name customername,
       d.departmentnumber, d.description departmentdescription,
       dp.distributionpointnumber, dp.description distributionpointdescription,
       pg.code productgroupcode,
       (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pg.productgroup_id
          and pgd.language_id = lan.language_id) productgroupdescription,
       p.code productcode, 1 packindication,
       (select pdesc.description from product_desc pdesc where pdesc.product_id = p.product_id and pdesc.language_id = lan.language_id) productdescription,
       p.typeofmerchandise,
       szd.code sizecode,
       (select sdesc.description from sizedefinition_desc sdesc where sdesc.sizedefinition_id = szd.sizedefinition_id
          and sdesc.language_id = lan.language_id) sizedescription,
       fm.code finishingmethodcode,
       (select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
          and fmd.language_id = lan.language_id) finishingmethoddescription,
       sdl.dateactive,
       sdl.dateinactive,
       0 yearweek, sda.day_id daynumber, null deliverydate, cust.dateinactive cust_dateinactive,
       sda.amount std_amount, 0 amountdelivered,
       ' ' customerlanguagecode, lan.code languagecode, deforproc_bu.businessunit_id
from standarddeliveryamount sda
     join standarddeliveryline sdl on sda.standarddeliveryline_id = sdl.standarddeliveryline_id
     join standarddelivery sd on sdl.standarddelivery_id = sd.standarddelivery_id
     join productlistperdistribpoint plpd on sdl.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
     join distributionpoint dp on plpd.distributionpoint_id = dp.distributionpoint_id
     join department d on dp.department_id = d.department_id
     join customer cust on d.customer_id = cust.customer_id
     join product p on plpd.product_id = p.product_id
     join productgroup pg on p.productgroup_id = pg.productgroup_id
     join sizedefinition szd on plpd.sizedefinition_id = szd.sizedefinition_id
     join finishingmethod fm on plpd.finishingmethod_id = fm.finishingmethod_id
     , languages lan, businessunit deforproc_bu
where sda.amount <> 0
      and (cust.defaultbusinessunit_id = deforproc_bu.businessunit_id or
      exists (select 1 from customeractivities act where cust.customer_id = act.customer_id and act.processbusinessunit_id = deforproc_bu.businessunit_id))
union all
select /*+index(DH XSPEEDDELIVERYHISTORY3)*/
       2 linetype, cust.customer_id, cust.customernumber, cust.name customername,
       d.departmentnumber, d.description departmentdescription,
       dp.distributionpointnumber, dp.description distributionpointdescription,
       pg.code productgroupcode,
       (select a.description from productgroup_desc a where a.productgroup_id = pg.productgroup_id
          and a.language_id = lan.language_id) productgroupdescription,
       p.code productcode, dh.packindication,
       (select b.description from product_desc b where b.product_id = p.product_id and b.language_id = lan.language_id) productdescription,
       p.typeofmerchandise,
       szd.code sizecode,
       (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = szd.sizedefinition_id
          and sdd.language_id = lan.language_id) sizedescription,
       fm.code finishingmethodcode,
       (select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
          and fmd.language_id = lan.language_id) finishingmethoddescription,
       null dateactive,
       null dateinactive,
       (dh.year * 100 + dh.week) yearweek, dh.daynumber, dh.deliverydate, cust.dateinactive cust_dateinactive,
       0 std_amount, dh.amountdelivered,
       ' ' customerlanguagecode, lan.code languagecode, deforproc_bu.businessunit_id
from deliveryhistory dh
     join distributionpoint dp on dh.distributionpoint_link_id = dp.distributionpoint_id
     join department d on dp.department_id = d.department_id
     join customer cust on d.customer_id = cust.customer_id
     join product p on dh.product_link_id = p.product_id
     join productgroup pg on p.productgroup_id = pg.productgroup_id
     join sizedefinition szd on dh.sizedefinition_link_id = szd.sizedefinition_id
     join finishingmethod fm on dh.finishingmethod_id = fm.finishingmethod_id
     , languages lan, businessunit deforproc_bu
where dh.customer_link_id = cust.customer_id
      and dh.amountdelivered <> 0
      and (cust.defaultbusinessunit_id = deforproc_bu.businessunit_id or
      exists (select 1 from customeractivities act where cust.customer_id = act.customer_id and act.processbusinessunit_id = deforproc_bu.businessunit_id))
/

  CREATE OR REPLACE VIEW "V_DELIVERYPERDAY_AUX" ("PRODUCT_ID", "SIZEDEFINITION_ID", "FINISHINGMETHOD_ID", "CUSTOMER_ID", "DISTRIBUTIONPOINT_ID", "DATEACTIVE", "DATEINACTIVE", "YEARWEEK", "PACKINDICATION", "DAYNUMBER", "STD_AMOUNT", "AMOUNTDELIVERED") AS 
  SELECT e.product_id, e.sizedefinition_id, e.finishingmethod_id, e.customer_id, f.distributionpoint_id,
  b.dateactive, b.dateinactive,
  0 yearweek, 1 PACKINDICATION,
  d.daynumber, c.amount std_amount, 0 AMOUNTDELIVERED
FROM STANDARDDELIVERY a, STANDARDDELIVERYLINE b, STANDARDDELIVERYAMOUNT c, DAY d,
  productlistpercustomer e, productlistperdistribpoint f
WHERE a.standarddelivery_id = b.standarddelivery_id
  and b.standarddeliveryline_id = c.standarddeliveryline_id
  and c.day_id = d.day_id
  and b.productlistperdistribpoint_id = f.productlistperdistribpoint_id
  and b.productlistpercustomer_id = e.productlistpercustomer_id
union all
SELECT DELIVERYHISTORY.PRODUCT_LINK_ID product_id, DELIVERYHISTORY.SIZEDEFINITION_LINK_ID sizedefinition_id,
       DELIVERYHISTORY.FINISHINGMETHOD_ID finishingmethod_id,
       DELIVERYHISTORY.CUSTOMER_LINK_ID customer_id, DELIVERYHISTORY.DISTRIBUTIONPOINT_LINK_ID distributionpoint_id,
       NULL dateactive, null dateinactive,
       DELIVERYHISTORY.year*100 + DELIVERYHISTORY.week YEARWEEK,
       DELIVERYHISTORY.PACKINDICATION,
       DELIVERYHISTORY.DAYNUMBER, null std_amount,
       DELIVERYHISTORY.AMOUNTDELIVERED
 FROM DELIVERYHISTORY
/

  CREATE OR REPLACE VIEW "V_DELIVERYPOINT" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CODE", "DESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, DELIVERYPOINT.CODE, DELIVERYPOINT.DESCRIPTION, DELIVERYPOINT.SYSTEMUSER_ID, DELIVERYPOINT.TIMESTAMP
       FROM DELIVERYPOINT, CUSTOMER
       WHERE DELIVERYPOINT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
/

  CREATE OR REPLACE VIEW "V_DELIVERYSCAN" ("BU_CODE", "BU_DESC", "PRODUCT_CODE", "LEGACYPRODUCTCODE", "SIZE_CODE", "LEGACYSIZECODE", "FROMSTOCK", "PACKINGNOTE_ID", "SCANTIMESTAMP", "CHARGEWASHING", "PRIMARYID", "REASON_CODE", "WEARERNUMBER", "WEARERNAME", "WEARERSEARCHNAME", "EMPLOYMENT_NR", "TYPEOFMERCHANDISE", "CUPBOARD", "LOCKER", "LOCKERSTATUS", "LOCKER_REMARK", "LOCKER_SORTADDRESS", "WEAREREMPLOYMENT_LINK_ID") AS 
  select /*version 1.0*/
       bu.code bu_code, bu.description bu_desc, plk.code product_code, plk.legacyproductcode, sd.code size_code, sd.legacysizecode,
       ds.fromstock, ds.packingnote_id, ds.scantimestamp, ds.chargewashing, ri.primaryid, rc.code reason_code, w_link.wearernumber,
       w_link.wearername, w_link.wearersearchname, w_link.sequencenumber employment_nr, prod.typeofmerchandise, lck.bank cupboard,
       lck.locker, lck.lockerstatus, lck.remark locker_remark, lck.sortaddress locker_sortaddress, ds.weareremployment_link_id
  from deliveryscan ds
       left join reasoncode rc on ds.reasoncode_id = rc.reasoncode_id
       left join weareremployment_link w_link
                 left join weareremployment we
                           left join locker lck on we.locker_id = lck.locker_id
                  on we.weareremployment_id = w_link.weareremployment_id
       on w_link.weareremployment_link_id = ds.weareremployment_link_id
       join product_link plk
            left join product prod on plk.product_id = prod.product_id
       on ds.product_link_id = plk.product_link_id
       join businessunit bu on ds.businessunit_id = bu.businessunit_id
       join sizedefinition_link sd on ds.sizedefinition_link_id = sd.sizedefinition_link_id
       join uniqueitem_link ri_link
            join raggeditem ri on ri_link.raggeditem_id = ri.raggeditem_id
       on ds.uniqueitem_link_id =  ri_link.uniqueitem_link_id
union all -- unique items
select bu.code bu_code, bu.description bu_desc, plk.code product_code, plk.legacyproductcode, sd.code size_code, sd.legacysizecode,
       ds.fromstock, ds.packingnote_id, ds.scantimestamp, ds.chargewashing, ui.primaryid, rc.code reason_code, w_link.wearernumber,
       w_link.wearername, w_link.wearersearchname, w_link.sequencenumber employment_nr, prod.typeofmerchandise, lck.bank cupboard,
       lck.locker, lck.lockerstatus, lck.remark locker_remark, lck.sortaddress locker_sortaddress, ds.weareremployment_link_id
  from deliveryscan ds
       left join reasoncode rc on ds.reasoncode_id = rc.reasoncode_id
       left join weareremployment_link w_link
                 left join weareremployment we
                           left join locker lck on we.locker_id = lck.locker_id
                  on we.weareremployment_id = w_link.weareremployment_id
       on w_link.weareremployment_link_id = ds.weareremployment_link_id
       join product_link plk
            left join product prod on plk.product_id = prod.product_id
       on ds.product_link_id = plk.product_link_id
       join businessunit bu on ds.businessunit_id = bu.businessunit_id
       join sizedefinition_link sd on ds.sizedefinition_link_id = sd.sizedefinition_link_id
       join uniqueitem_link ri_link
            join uniqueitem ui on ri_link.uniqueitem_id = ui.uniqueitem_id
       on ds.uniqueitem_link_id =  ri_link.uniqueitem_link_id
/

  CREATE OR REPLACE VIEW "V_DELIVERYSCAN_ALL" ("BU_CODE", "BU_DESC", "PRODUCT_CODE", "LEGACYPRODUCTCODE", "PRODUCTDESCRIPTION", "SIZE_CODE", "LEGACYSIZECODE", "FROMSTOCK", "PACKINGNOTE_ID", "SCANTIMESTAMP", "CHARGEWASHING", "PRIMARYID", "REASON_CODE", "WEARERNUMBER", "WEARERNAME", "WEARERSEARCHNAME", "EMPLOYMENT_NR", "TYPEOFMERCHANDISE", "CUPBOARD", "LOCKER", "LOCKERSTATUS", "LOCKER_REMARK", "LOCKER_SORTADDRESS", "WEAREREMPLOYMENT_LINK_ID", "LANGUAGECODE", "FIRSTNAME", "SEARCHNAME", "FINISHMETHOD_DESC", "WONUMBER") AS 
  SELECT --+index(ds XIF11DELIVERYSCAN) index(ri_link XSPEEDUNIQUEITEM_LINK)
       bu.code BU_CODE, bu.description BU_DESC,
       p.code product_code, p.legacyproductcode,
       (SELECT a.description FROM PRODUCT_DESC A WHERE p.product_id = A.PRODUCT_ID
       AND A.LANGUAGE_ID = l.language_id) productdescription,
       s.code size_code, s.legacysizecode,
       ds.fromstock, ds.packingnote_id, ds.scantimestamp, ds.chargewashing,
       ri.primaryid, --r.code reason_code,
       (select rd.description from reasoncode_desc rd where rd.reasoncode_id = r.reasoncode_id
        and rd.language_id = l.language_id) reason_code,
       w_link.wearernumber, w_link.wearername, w_link.wearersearchname, w_link.sequencenumber employment_nr,
       prod.typeofmerchandise,
       locker.bank cupboard, locker.locker, locker.lockerstatus,
       locker.remark locker_remark, locker.sortaddress locker_sortaddress
       , ds.weareremployment_link_id, l.code languagecode, w.firstname, w.searchname,
       (SELECT fmd.description FROM finishingmethod_desc fmd WHERE fmd.finishingmethod_id = ds.finishingmethod_id
       AND fmd.LANGUAGE_ID = l.language_id) finishmethod_desc
       ,(select max(wo.workordernumber) from issuehistory ih join workorder wo on ih.workorder_id = wo.workorder_id
                where ih.uniqueitem_link_id = ds.uniqueitem_link_id
                and ih.issuehistory_id = (select max(ih2.issuehistory_id) from issuehistory ih2 where ih2.uniqueitem_link_id = ds.uniqueitem_link_id)
                and wo.deliverfrom=2
                ) wonumber
  FROM deliveryscan ds
       LEFT OUTER JOIN reasoncode r ON r.reasoncode_id = ds.reasoncode_id
       LEFT OUTER JOIN (weareremployment_link w_link left outer join
                  (weareremployment we left outer join locker on locker.locker_id = we.locker_id
                                                  join wearer w on we.wearer_id = w.wearer_id)
                  on we.weareremployment_id = w_link.weareremployment_id)
            on w_link.weareremployment_link_id = ds.weareremployment_link_id,
       product_link p LEFT OUTER JOIN product prod ON p.product_id = prod.product_id,
       businessunit bu, sizedefinition_link s,
       uniqueitem_link ri_link, raggeditem ri, languages l--, wearer w
 WHERE bu.businessunit_id = ds.businessunit_id and
       p.product_link_id = ds.product_link_id and
       s.sizedefinition_link_id = ds.sizedefinition_link_id and
       ri_link.uniqueitem_link_id = ds.uniqueitem_link_id AND
       ri.raggeditem_id = ri_link.raggeditem_id
       --we.wearer_id = w.wearer_id
UNION ALL-- UNIQUE ITEMS
SELECT --+index(ds XIF11DELIVERYSCAN)
       bu.code BU_CODE, bu.description BU_DESC,
       p.code product_code, p.legacyproductcode,
       (SELECT a.description FROM PRODUCT_DESC A WHERE p.product_id = A.PRODUCT_ID
       AND A.LANGUAGE_ID = l.language_id) productdescription,
       s.code size_code, s.legacysizecode,
       ds.fromstock, ds.packingnote_id, ds.scantimestamp, ds.chargewashing,
       ui.primaryid, --r.code reason_code,
       (select rd.description from reasoncode_desc rd where rd.reasoncode_id = r.reasoncode_id
        and rd.language_id = l.language_id) reason_code,
       w_link.wearernumber, w_link.wearername, w_link.wearersearchname, w_link.sequencenumber employment_nr,
       prod.typeofmerchandise,
       locker.bank cupboard, locker.locker, locker.lockerstatus,
       locker.remark locker_remark, locker.sortaddress locker_sortaddress
       , ds.weareremployment_link_id, l.code languagecode, w.firstname, w.searchname,
       (SELECT fmd.description FROM finishingmethod_desc fmd WHERE fmd.finishingmethod_id = ds.finishingmethod_id
       AND fmd.LANGUAGE_ID = l.language_id) finishmethod_desc
       ,(select max(wo.workordernumber) from issuehistory ih join workorder wo on ih.workorder_id = wo.workorder_id
                where ih.uniqueitem_link_id = ds.uniqueitem_link_id
                and ih.issuehistory_id = (select max(ih2.issuehistory_id) from issuehistory ih2 where ih2.uniqueitem_link_id = ds.uniqueitem_link_id)
                and wo.deliverfrom=2
                ) wonumber
  FROM deliveryscan ds
       LEFT OUTER JOIN reasoncode r ON r.reasoncode_id = ds.reasoncode_id
       LEFT OUTER JOIN (weareremployment_link w_link left outer join
                  (weareremployment we left outer join locker on locker.locker_id = we.locker_id
                                                  join wearer w on we.wearer_id = w.wearer_id)
                  on we.weareremployment_id = w_link.weareremployment_id)
            on w_link.weareremployment_link_id = ds.weareremployment_link_id,
       product_link p LEFT OUTER JOIN product prod ON p.product_id = prod.product_id,
       businessunit bu, sizedefinition_link s, uniqueitem_link ui_link, uniqueitem ui, languages l
 WHERE bu.businessunit_id = ds.businessunit_id and
       p.product_link_id = ds.product_link_id and
       s.sizedefinition_link_id = ds.sizedefinition_link_id and
       ui_link.uniqueitem_link_id = ds.uniqueitem_link_id and
       ui.uniqueitem_id = ui_link.uniqueitem_id
      -- we.wearer_id = w.wearer_id
union all -- return to stock from raggeditem
SELECT --+index(o XIE3OUTOFCIRCULATIONHISTORY)  index(ri_link XSPEEDUNIQUEITEM_LINK)  index(p XIF311PRODUCT_LINK)
       distinct bu.code BU_CODE, bu.description BU_DESC,
       p.code product_code, p.legacyproductcode,
       (SELECT a.description FROM PRODUCT_DESC A WHERE p.product_id = A.PRODUCT_ID
       AND A.LANGUAGE_ID = l.language_id) productdescription,
       s.code size_code, s.legacysizecode,
       'Z' fromstock, o.packingnote_id, o.outofcircdate scantimestamp, null chargewashing,
       ri.primaryid, --r.code reason_code,
      (select rd.description from ragreason_desc rd where rd.ragreason_id = r.ragreason_id
        and rd.language_id = l.language_id) reason_code,
       w_link.wearernumber, w_link.wearername, w_link.wearersearchname, w_link.sequencenumber employment_nr,
       prod.typeofmerchandise,
       locker.bank cupboard, locker.locker, locker.lockerstatus,
       locker.remark locker_remark, locker.sortaddress locker_sortaddress
       , o.weareremployment_link_id, l.code languagecode, w.firstname, w.searchname,
       (SELECT fmd.description FROM finishingmethod_desc fmd WHERE fmd.finishingmethod_id = ri.finishingmethod_id
       AND fmd.LANGUAGE_ID = l.language_id) finishmethod_desc
       , null wonumber
  FROM outofcirculationhistory o
       LEFT OUTER JOIN (weareremployment_link w_link left outer join
                  (weareremployment we left outer join locker on locker.locker_id = we.locker_id
                                                  join wearer w on we.wearer_id = w.wearer_id)
                  on we.weareremployment_id = w_link.weareremployment_id)
            on w_link.weareremployment_link_id = o.weareremployment_link_id,
       product_link p LEFT OUTER JOIN product prod ON p.product_id = prod.product_id,
       businessunit bu, sizedefinition_link s,
       uniqueitem_link ri_link, raggeditem ri, ragreason r, languages l
 WHERE bu.businessunit_id = o.processbusinessunit_id and
       p.product_link_id = o.product_link_id and
       s.sizedefinition_link_id = o.sizedefinition_link_id and
       ri_link.uniqueitem_link_id = o.uniqueitem_link_id AND
       ri.raggeditem_id = ri_link.raggeditem_id and
       r.ragreason_id = o.ragreason_id
       --we.wearer_id = w.wearer_id
union all -- return to stock from uniqueitem
SELECT --+index(o XIE3OUTOFCIRCULATIONHISTORY)
       distinct bu.code BU_CODE, bu.description BU_DESC,
       p.code product_code, p.legacyproductcode,
       (SELECT a.description FROM PRODUCT_DESC A WHERE p.product_id = A.PRODUCT_ID
       AND A.LANGUAGE_ID = l.language_id) productdescription,
       s.code size_code, s.legacysizecode,
       'Z' fromstock, o.packingnote_id, o.outofcircdate scantimestamp, null chargewashing,
       ui.primaryid, --null reason_code,
       (select rd.description from reasoncode_desc rd where rd.reasoncode_id = r.reasoncode_id
         and rd.language_id = l.language_id) reason_code,
       w_link.wearernumber, w_link.wearername, w_link.wearersearchname, w_link.sequencenumber employment_nr,
       prod.typeofmerchandise,
       locker.bank cupboard, locker.locker, locker.lockerstatus,
       locker.remark locker_remark, locker.sortaddress locker_sortaddress
       , o.weareremployment_link_id, l.code languagecode, w.firstname, w.searchname,
       (SELECT fmd.description FROM finishingmethod_desc fmd WHERE fmd.finishingmethod_id = ui.finishingmethod_id
       AND fmd.LANGUAGE_ID = l.language_id) finishmethod_desc
       , null wonumber
  FROM outofcirculationhistory o
       LEFT OUTER JOIN reasoncode r ON r.reasoncode_id = o.reasoncode_id
       LEFT OUTER JOIN (weareremployment_link w_link left outer join
                  (weareremployment we left outer join locker on locker.locker_id = we.locker_id
                                                  join wearer w on we.wearer_id = w.wearer_id)
                  on we.weareremployment_id = w_link.weareremployment_id)
            on w_link.weareremployment_link_id = o.weareremployment_link_id,
       product_link p LEFT OUTER JOIN product prod ON p.product_id = prod.product_id,
       businessunit bu, sizedefinition_link s, uniqueitem_link ui_link, uniqueitem ui, languages l
 WHERE bu.businessunit_id = o.processbusinessunit_id and
       p.product_link_id = o.product_link_id and
       s.sizedefinition_link_id = o.sizedefinition_link_id and
       ui_link.uniqueitem_link_id = o.uniqueitem_link_id and
       ui.uniqueitem_id = ui_link.uniqueitem_id and
       --we.wearer_id = w.wearer_id and
       o.ragreason_id is null
/

  CREATE OR REPLACE VIEW "V_DELIVERYSIGNATURE" ("PERSONIDENTIFICATION", "SIGNATURE", "CONSIGNMENTNOTE_ID", "SIGNATUREDATE", "SIGNATURETIME24", "SIGNATUREBARCODE", "HASSIGNATURE", "STOP_ID") AS 
  select dsig.personidentification, dsig.signature, pn.consignmentnote_id,
       (select rc.drivingdate
           from routecontrol rc
          where rc.routecontrol_id = stop.routecontrol_id) signaturedate,
       to_char(stop.departuretime, 'fmhh24fm:MI') signaturetime24,
       dp.signaturebarcode,
       (case when length(dsig.signature) > 0 then 1
       else 0 end) hassignature,
        dsig.stop_id
  from packingnote pn
  join stop on (pn.stop_id = stop.stop_id)
  join deliverypoint dp on pn.deliverypoint_id = dp.deliverypoint_id
  left outer join deliverysignature dsig on (dsig.stop_id = pn.stop_id and
                                 dsig.stop_id = pn.deliverysignature_id)
 where pn.packingnote_id =
       (select min(pn2.packingnote_id)
          from packingnote pn2
         where pn2.consignmentnote_id = pn.consignmentnote_id)
/

  CREATE OR REPLACE VIEW "V_DELIVERYSTATISTICS" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_ID", "COSTCENTERCODE", "COSTCENTERDESC", "INVOICEFREQUENCYNUMBER", "STARTYEAR", "ENDYEAR", "STARTMONTH", "ENDMONTH", "INVOICEYEARMONTH", "COSTREPORTYEAR", "COSTREPORTWEEK", "COSTREPORTYEARWEEK", "PRODUCTGROUPCODE", "PRODUCTGROUPDESC", "TYPEOFMERCHANDISE", "PRODWEIGHCODE", "PRODWEIGHDESC", "SIZECODE", "FINISHINGMETHODCODE", "SIZE_DESC", "FINISH_DESC", "INVOICELINETYPE", "ACTIVITYCODE", "PRICE", "QUANTITY", "AMOUNT", "DECIMALS", "PRICEFACTOR", "CUSTOMERLANGUAGE_ID", "LANGUAGE_ID", "LANGUAGECODE") AS 
  select cs.customernumber, cs.name customername, cs.customer_id,
  cc.code costcentercode, cc.description costcenterdesc,
  inf.invoicefrequencynumber,
  ih.startyear, ih.endyear, ih.startmonth, ih.endmonth, ih.startyear*100+ih.startmonth invoiceyearmonth,
  cri.year costreportyear, cri.week costreportweek, cri.year*100+cri.week costreportyearweek,
  prg.code productgroupcode,
  (select prgd.description from productgroup_desc prgd where prgd.productgroup_id = prg.productgroup_id
    and prgd.language_id = languages.language_id) productgroupdesc,
  pr.typeofmerchandise, pr.code prodweighcode,
  (select prd.description from product_desc prd where prd.product_id = pr.product_id
    and prd.language_id = languages.language_id) prodweighdesc,
  sz.code sizecode, fm.code finishingmethodcode,
  (select szd.description from sizedefinition_desc szd where sz.sizedefinition_id=szd.sizedefinition_id and szd.language_id=languages.language_id) Size_desc,
  (select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id=fm.finishingmethod_id and fmd.language_id=languages.language_id) Finish_desc,
  ilt.type invoicelinetype, ac.code activitycode,
  il.price, cri.quantity, cri.amount, cr.invoiceamountdecimals decimals, ilp.pricefactor,
  cs.language_id customerlanguage_id, languages.language_id, languages.code languagecode
from invoiceheader ih, invoiceline il, status st, invoicelinetype ilt,
  invoicelineproduct ilp, product pr, productgroup prg, finishingmethod fm, sizedefinition sz,
  customer cs, costreportinfo cri, costcenter cc, activity ac, currency cr,
  invoicefrequency inf, languages
where ih.invoiceheader_id = il.invoiceheader_id
  and ih.documenttype = 1 -- invoice
  and (ih.invoicetype = 1 or ih.invoicetype =4) -- generated, additional
  and ih.status_id = st.status_id
  and st.code = '2'
  and il.invoicelinetype_id = ilt.invoicelinetype_id
  and ilt.type = 2 -- wash
  and il.invoiceline_id = ilp.invoiceline_id
  and ih.deltocustomer_link_id = cs.customer_id
  and il.invoiceline_id = cri.invoiceline_id
  and cri.costcenter_link_id = cc.costcenter_id
  and ilp.product_link_id = pr.product_id
  and prg.productgroup_id = pr.productgroup_id
  and ilp.finishingmethod_id = fm.finishingmethod_id
  and ilp.sizedefinition_link_id = sz.sizedefinition_id
  and prg.activity_id = ac.activity_id
  and ih.invoicefrequency_id = inf.invoicefrequency_id
  and inf.invoicefrequencynumber <> 0 -- direct
  and inf.invoicefrequencynumber <> 200 -- manual
  and cs.currency_id = cr.currency_id
UNION ALL
select cs.customernumber, cs.name customername, cs.customer_id,
  cc.code costcentercode, cc.description costcenterdesc,
  inf.invoicefrequencynumber,
  ih.startyear, ih.endyear, ih.startmonth, ih.endmonth, ih.startyear*100+ih.startmonth invoiceyearmonth,
  cri.year costreportyear, cri.week costreportweek, cri.year*100+cri.week costreportyearweek,
  '' productgroupcode, '' productgroupdesc,
  1 typeofmerchandise,
  wc.code prodweighcode,
  (select wcd.description from weighingcategory_desc wcd where wcd.weighingcategory_id = wc.weighingcategory_id
    and wcd.language_id = languages.language_id) prodweighdesc,
  '' sizecode, '' finishingmethodcode,  '' Size_desc,  '' Finish_desc,
  ilt.type invoicelinetype, ac.code activitycode,
  il.price, cri.quantity, cri.amount, cr.invoiceamountdecimals decimals, ilp.pricefactor,
  cs.language_id customerlanguage_id, languages.language_id, languages.code languagecode
from invoiceheader ih, invoiceline il, status st, invoicelinetype ilt, invoicelineproduct ilp,
  weighingcategory wc, customer cs, costreportinfo cri, costcenter cc, activity ac, currency cr,
  invoicefrequency inf, languages
where ih.invoiceheader_id = il.invoiceheader_id
  and ih.documenttype = 1 -- invoice
  and (ih.invoicetype = 1 or ih.invoicetype =4) -- generated, additional
  and ih.status_id = st.status_id
  and st.code = '2'
  and il.invoicelinetype_id = ilt.invoicelinetype_id
  and ilt.type >=3 and ilt.type <=4 -- soil, clean
  and ih.deltocustomer_link_id = cs.customer_id
  and il.invoiceline_id = cri.invoiceline_id
  and cri.costcenter_link_id = cc.costcenter_id
  and il.invoiceline_id = ilp.invoiceline_id
  and ilp.weighingcategory_link_id = wc.weighingcategory_id
  and wc.activity_id = ac.activity_id
  and ih.invoicefrequency_id = inf.invoicefrequency_id
  and inf.invoicefrequencynumber <> 0 -- direct
  and inf.invoicefrequencynumber <> 200 -- manual
  and cs.currency_id = cr.currency_id
/

  CREATE OR REPLACE VIEW "V_DELIVERYVARIATIONS" ("CUSTOMERNUMBER", "CUSTOMERNAME", "PHONENO", "CUSTOMER_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "PACKINGNOTENUMBER", "PROCESSBUSINESSUNIT_ID", "DELIVERYDATE", "ORIGIN", "AMOUNT", "FIXEDAMOUNT", "REFERENCE", "PROCESSED", "CAUSENOTENUMBER", "CAUSENOTEDELIVERYDATE", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE", "SOILCOUNTSUBTYPE", "RC_CODE", "RC_DESCRIPTION", "ADJ_RC_CODE", "ADJ_RC_DESCRIPTION", "SYSTEMUSERFULLNAME", "STREET", "ZIPCODE", "CITY") AS 
  SELECT cu.CUSTOMERNUMBER, cu.NAME CUSTOMERNAME, cu.PHONENO, cu.CUSTOMER_ID,
  de.DEPARTMENTNUMBER, de.DESCRIPTION DEPARTMENTDESCRIPTION,
  dp.DISTRIBUTIONPOINTNUMBER, dp.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
  pr.CODE PRODUCTCODE,
  (SELECT p.DESCRIPTION FROM PRODUCT_DESC P WHERE P.PRODUCT_ID = pr.PRODUCT_ID
     AND P.LANGUAGE_ID = lan.LANGUAGE_ID)  PRODUCTDESCRIPTION,  --SIZEDEFINITION.CODE,
  (SELECT s.DESCRIPTION FROM SIZEDEFINITION_DESC S WHERE S.SIZEDEFINITION_ID = dv.SIZEDEFINITION_ID
     AND S.LANGUAGE_ID = lan.LANGUAGE_ID)  SIZEDESCRIPTION,
  fm.CODE FINISHINGMETHODCODE,
  (SELECT F.DESCRIPTION FROM FINISHINGMETHOD_DESC F WHERE F.FINISHINGMETHOD_ID = fm.FINISHINGMETHOD_ID
     AND F.LANGUAGE_ID = lan.LANGUAGE_ID)  FINISHINGMETHODDESCRIPTION,
  pn.NOTENUMBER PACKINGNOTENUMBER, pn.PROCESSBUSINESSUNIT_ID,
  dv.DELIVERYDATE, dv.ORIGIN, dv.AMOUNT, dv.FIXEDAMOUNT, dv.REFERENCE, dv.PROCESSED,
  CAUSENOTE.NOTENUMBER CAUSENOTENUMBER, CAUSENOTE.DELIVERYDATE CAUSENOTEDELIVERYDATE,
  dv.SYSTEMUSER_ID,
  coalesce((select max(io.orderdate) from internetorder IO, internetorderline iol
  where iol.deliveryvariations_id = dv.deliveryvariations_id and io.internetorder_id = iol.internetorder_id)
                   , trunc(dv.TIMESTAMP)) TIMESTAMP,
  lan.CODE LANGUAGECODE, dv.SOILCOUNTSUBTYPE,
  RC.CODE RC_CODE, (SELECT RC_DESC.DESCRIPTION FROM REASONCODE_DESC RC_DESC WHERE RC.REASONCODE_ID = RC_DESC.REASONCODE_ID AND RC_DESC.LANGUAGE_ID = lan.LANGUAGE_ID) RC_DESCRIPTION,
  ADJ_RC.CODE ADJ_RC_CODE, (SELECT ADJ_RC_DESC.DESCRIPTION FROM REASONCODE_DESC ADJ_RC_DESC WHERE ADJ_RC.REASONCODE_ID = ADJ_RC_DESC.REASONCODE_ID AND ADJ_RC_DESC.LANGUAGE_ID = lan.LANGUAGE_ID) ADJ_RC_DESCRIPTION,
  (select su.fullname from systemuser su where su.systemuser_id = dv.Systemuser_Id) systemuserfullname,
 adr.street, adr.zipcode, adr.city
FROM CUSTOMER cu, DEPARTMENT de, DISTRIBUTIONPOINT dp, ADDRESS adr,
  PRODUCT pr, FINISHINGMETHOD fm, LANGUAGES lan,
  DELIVERYVARIATIONS dv
    LEFT OUTER JOIN PACKINGNOTE pn ON (dv.PACKINGNOTE_ID = pn.PACKINGNOTE_ID)
    LEFT OUTER JOIN PACKINGNOTE CAUSENOTE ON (dv.CAUSENOTE_ID = CAUSENOTE.PACKINGNOTE_ID)
    LEFT OUTER JOIN REASONCODE RC ON (dv.REASONCODE_ID = RC.REASONCODE_ID)
    LEFT OUTER JOIN REASONCODE ADJ_RC ON (dv.ADJUSTMENTREASON_ID = ADJ_RC.REASONCODE_ID)
WHERE dv.DISTRIBUTIONPOINT_ID = dp.DISTRIBUTIONPOINT_ID
	AND dp.DEPARTMENT_ID = de.DEPARTMENT_ID
	AND de.CUSTOMER_ID = cu.CUSTOMER_ID
	AND dv.PRODUCT_ID = pr.PRODUCT_ID
  AND dv.FINISHINGMETHOD_ID = fm.FINISHINGMETHOD_ID
  AND de.ACTIVE = 'Y'-- DELIVERYVARIATIONS.RPT
  and adr.address_id = cu.Visitaddress_Id
/

  CREATE OR REPLACE VIEW "V_DEPOSITPOOLSTOCK" ("BUCODE", "BUDESCRIPTION", "PRODUCTCODE", "SIZECODE", "PGCODE", "PRODUCTDESC", "SIZEDESC", "PRIMARYID", "BUSINESSUNIT_ID", "STAYCHANGEDATE", "DEPOSITLOCATIONORCONTENTS", "LANGUAGECODE") AS 
  select bu.code bucode, bu.description budescription,
   prd.code productCode, sz.code sizeCode, pg.code pgcode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( select sizedefinition_desc.description from sizedefinition_desc where sizedefinition_desc.sizedefinition_id = sz.sizedefinition_id
  and sizedefinition_desc.language_id = languages.language_id ) sizeDesc
, uq.primaryid, uq.businessunit_id, uq.staychangedate,  bu.DepositLocationORContents  DepositLocationORContents, languages.code languageCode
from businessunit bu,  uniqueitem uq,stay, product prd, sizedefinition sz, productgroup pg, languages
where uq.businessunit_id=bu.businessunit_id
     and uq.stay_id = stay.stay_id
     and uq.product_id = prd.product_id
     and prd.productgroup_id=pg.productgroup_id
     and uq.sizedefinition_id = sz.sizedefinition_id
     and stay.staytype = 1 -- Garments
     and stay.staynr = 37 -- Deposit Stock
     and uq.poolitem=1
/

  CREATE OR REPLACE VIEW "V_DEPOSITSTOCK" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DEFAULTBUSINESSUNIT_ID", "CITY", "DEPARTMENTNUMBER", "WEARERNUMBER", "WEARERNAME", "INACTIVEWEARERS", "PRODUCTCODE", "SIZECODE", "PGCODE", "PRODUCTDESC", "SIZEDESC", "SEASONCODE", "SEASONTYPEDESC", "PRIMARYID", "BUSINESSUNIT_ID", "DEPOSITSTOCKLOCATION", "STAYCHANGEDATE", "STARTDATE", "LANGUAGECODE") AS 
  select
  cu.customernumber, cu.name customerName, cu.defaultbusinessunit_id, address.city, de.departmentnumber
, we.wearernumber, we.fullname wearerName
, case when ( we.dateinactive < trunc(sysdate) and wey.dateinactive < trunc(sysdate) ) then 'Y'
       else 'N'
            end InactiveWearers
, prd.code productCode, sz.code sizeCode,pg.code pgcode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( select sizedefinition_desc.description from sizedefinition_desc where sizedefinition_desc.sizedefinition_id = sz.sizedefinition_id
  and sizedefinition_desc.language_id = languages.language_id ) sizeDesc
, season.code seasonCode
, ( select seasontype_desc.description from seasontype_desc where season.seasontype_id = seasontype_desc.seasontype_id
  and seasontype_desc.language_id = languages.language_id ) seasontypeDesc
, uq.primaryid, uq.businessunit_id, uqnp.depositstocklocation, uq.staychangedate, uqf.startdate
, languages.code languageCode
from
  uniqueitem uq
      left outer join
           ( uniqueitemflag uqf join automaticflag
                                 on uqf.flag_id = automaticflag.flag_id
                                    and automaticflag.automaticflag_id = 10 -- Start of Season
                                     )
           on uq.uniqueitem_id = uqf.uniqueitem_id
, uniqueitemnonpool uqnp, stay
, wearerinventory wey
    left outer join season on wey.season_id = season.season_id
, weareremployment wemp, wearer we, customer cu, department de, distributionpoint dip
, product prd, sizedefinition sz,productgroup pg
, address, languages
where
    uq.uniqueitem_id = uqnp.uniqueitem_id
and uq.stay_id = stay.stay_id
    and stay.staytype = 1 -- Garments
        and stay.staynr = 37 -- Deposit Stock
and uqnp.wearerinventory_id = wey.wearerinventory_id
and uqnp.weareremployment_id = wemp.weareremployment_id
    and wemp.wearer_id = we.wearer_id
        and we.customer_id = cu.customer_id
            and cu.visitaddress_id = address.address_id
            and cu.customer_id = de.customer_id
                and de.department_id = dip.department_id
                    and dip.distributionpoint_id = wemp.distributionpoint_id
and uq.product_id = prd.product_id
and prd.productgroup_id=pg.productgroup_id
and uq.sizedefinition_id = sz.sizedefinition_id
/

  CREATE OR REPLACE VIEW "V_DEPOT" ("PLANTCODE", "PLANTNAME", "CODE", "DESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  SELECT PLANT.CODE, PLANT.NAME, DEPOT.CODE, DEPOT.DESCRIPTION, DEPOT.SYSTEMUSER_ID, DEPOT.TIMESTAMP
       FROM DEPOT, PLANT
       WHERE DEPOT.PLANT_ID = PLANT.PLANT_ID
/

  CREATE OR REPLACE VIEW "V_DETAILCOSTSPERPATIENT_PDPP" ("CUSTOMER_ID", "COSTCENTER_ID", "REPORTPARAM_ID", "PATIENTDAYS", "PATIENTS", "YEAR", "WEEK") AS 
  select c.customer_id, c.costcenter_id,
  rp.reportparam_id,
  sum(p.patientdays) patientdays, sum(p.patients) patients, p.year, p.week
from costcenter c, distributionpoint dp, patientday p, reportparam rp
where c.costcenter_id = dp.costcenter_id
  and dp.distributionpoint_id = p.distributionpoint_link_id
  and p.month = 0--and rp.number_value = p.year
  and p.year >= rp.number_value6
  and p.year <= rp.number_value7
  and p.week >= rp.number_value4
  and p.week <= rp.number_value5
  and c.budgetrelevant = 'Y'
group by c.customer_id, c.costcenter_id, rp.reportparam_id, p.year, p.week
/

  CREATE OR REPLACE VIEW "V_DETAILCOSTSPERPATIENT_SUMPP" ("REPORTPARAM_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CURRENCYCODE", "YEAR", "WEEK", "PRODUCTCODE", "PRODUCTDESC", "COSTCENTER_ID", "CCBUDGETRELEVANT", "COSTCENTERCODE", "COSTCENTERDESC", "INVOICED_AMOUNT", "INVOICED_TAX", "INVOICED_QUANTITY", "INVOICELINETYPE", "INVOICEAMOUNTDECIMALS") AS 
  select rp.reportparam_id,
  cu.customer_id, cu.customernumber, cu.name customername,
  cr.code currencycode,
  cri.year, cri.week,
  il.code productcode, il.description productdesc,
  cc.costcenter_id, cc.budgetrelevant ccbudgetrelevant,
  cc.code costcentercode, cc.description costcenterdesc,
  /*cri.quantity * coalesce(il.price, 0) * coalesce((select max(ilp.pricefactor) from invoicelineproduct ilp where ilp.invoiceline_id=il.invoiceline_id), 1) +
    (case when coalesce(il.price, 0) = 0 then cri.amount else 0 end)*/
     cri.amount invoiced_amount,
  /*coalesce(((cri.quantity * coalesce(il.price, 0) * coalesce((select max(ilp.pricefactor) from invoicelineproduct ilp where ilp.invoiceline_id=il.invoiceline_id), 1)) +
    (case when coalesce(il.price, 0) = 0 then cri.amount else 0 end))*
    (select tg.taxrate from taxgroup tg
      where il.taxgroupcode = tg.code
        and tg.country_id = cu.country_id)/100, 0)*/0 invoiced_tax,
  cri.quantity invoiced_quantity,
  ilt.type invoicelinetype, cr.invoiceamountdecimals
from invoiceheader ih, invoiceline il, costreportinfo cri, costcenter cc,
  customer cu, currency cr,
  status st, invoicelinetype ilt, reportparam rp
where ih.invoiceheader_id = il.invoiceheader_id
  and il.invoiceline_id = cri.invoiceline_id
  and cri.costcenter_link_id = cc.costcenter_id
  and cu.customer_id = ih.deltocustomer_link_id
  and cu.currency_id = cr.currency_id
  and ih.status_id = st.status_id
  and st.code = '2'
  and il.invoicelinetype_id = ilt.invoicelinetype_id
  and cu.customernumber >= rp.number_value8
  and cu.customernumber <= rp.number_value9
  and cc.code >= rp.string_value1
  and cc.code <= rp.string_value2
  and cri.year >= rp.number_value6
  and cri.year <= rp.number_value7
  and cri.week >= rp.number_value4
  and cri.week <= rp.number_value5
/

  CREATE OR REPLACE VIEW "V_DISMOUNTINGORDER" ("CUSTOMERNUMBER", "NAME", "STREET", "ZIPCODE", "CITY", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "WORKORDER_ID", "WORKORDERNUMBER", "REFERENCENUMBER", "REQUESTDATE", "NEEDEDDATE", "MOUNTINGDATE", "REMARK", "ROUTENUMBER", "ROUTEDESCRIPTION", "DAY_DESC", "PRODUCT_CODE", "PRODUCT_DESC", "SIZE_CODE", "FINISHING_CODE", "QUALITYGRADE_CODE", "QUANTITYORDERED", "TOBEMOUNTED", "LANGUAGE_CODE", "DISTRIBUTIONPOINT_ID") AS 
  select cu.customernumber, cu.name, addr.street, addr.zipcode, addr.city
, dis.distributionpointnumber, dis.description distributionpointdescription
, wo.workorder_id, wo.workordernumber, wo.referencenumber, wo.requestdate
, wo.neededdate, wo.mountingdate, wo.remark
, ro.routenumber, ro.description routedescription
, (select day_desc.description from day_desc where ro.drivingday_id=day_desc.day_id and day_desc.language_id = lan.language_id) day_desc
, prd.code product_code
, (select prdd.description from product_desc prdd where prdd.product_id=prd.product_id and prdd.language_id = lan.language_id) product_desc
, sd.code size_code, fm.code finishing_code, qg.code qualitygrade_code
, wol.quantityordered--, wol.quantityfirstdelivery, wol.salesitem, wol.startservice
, wol.tobemounted, lan.code language_code, dis.distributionpoint_id
from workorder wo
     left outer join route ro on wo.route_id = ro.route_id
     left outer join customer_link cul
          left outer join customer cu
               join address addr on cu.visitaddress_id = addr.address_id
          on cul.customer_id = cu.customer_id
     on wo.customer_link_id = cul.customer_link_id
, distributionpoint dis, workorderline wol, product prd, sizedefinition sd, finishingmethod fm, qualitygrade qg
--, sizedefinition_desc sdd, finishingmethod_desc fmd, modification mod
, languages lan
where wo.workorder_id = wol.workorder_id and wo.origin = 11
and dis.distributionpoint_id = wo.distributionpoint_link_id
and prd.product_id = wol.product_link_id
and sd.sizedefinition_id = wol.sizedefinition_link_id
and fm.finishingmethod_id = wol.finishingmethod_id
and qg.qualitygrade_id = wol.requestedgrade_id
/

  CREATE OR REPLACE VIEW "V_DISTRIBUTIONPOINT" ("CUSTOMERNUMBER", "NAME", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "COSTCENTERCODE", "COSTCENTERDESCRIPTION", "ACTIVE", "REMARKONPACKINGNOTE", "REMARKONDELIVERYNOTE", "PACKREMARKENDDATE", "DELIVERREMARKENDDATE", "DELIVERATCUSTOMERNUMBER", "DELIVERATCUSTOMERNAME", "DELIVERYPOINTCODE", "DELIVERYPOINTDESCRIPTION", "LEGACYDISTRIBUTIONPOINTNUMBER", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
 DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION  DISTRIBUTIONPOINTDESCRIPTION,
 COSTCENTER.CODE COSTCENTERCODE, COSTCENTER.DESCRIPTION COSTCENTERDESCRIPTION,
 DISTRIBUTIONPOINT.ACTIVE, DISTRIBUTIONPOINT.REMARKONPACKINGNOTE, DISTRIBUTIONPOINT.REMARKONDELIVERYNOTE,
 DISTRIBUTIONPOINT.PACKREMARKENDDATE, DISTRIBUTIONPOINT.DELIVERREMARKENDDATE,
 DELIVERATCUSTOMER.CUSTOMERNUMBER DELIVERATCUSTOMERNUMBER,
 DELIVERATCUSTOMER.NAME  DELIVERATCUSTOMERNAME,
 DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
 DISTRIBUTIONPOINT.LEGACYDISTRIBUTIONPOINTNUMBER,
 DELIVERYPOINT.SYSTEMUSER_ID, DISTRIBUTIONPOINT.TIMESTAMP
       FROM DISTRIBUTIONPOINT, CUSTOMER, DEPARTMENT, COSTCENTER, DELIVERYPOINT,
       CUSTOMER DELIVERATCUSTOMER
       WHERE DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
and DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
and DISTRIBUTIONPOINT.COSTCENTER_ID = COSTCENTER.COSTCENTER_ID
and DISTRIBUTIONPOINT.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
and DELIVERYPOINT.CUSTOMER_ID = DELIVERATCUSTOMER.CUSTOMER_ID
/

  CREATE OR REPLACE VIEW "V_DNREMARK" ("CONSIGNMENTNOTE_ID", "REMARK") AS 
  select distinct pn.consignmentnote_id, pn.remark
from  packingnote pn
/

  CREATE OR REPLACE VIEW "V_DPCOSTSPECIFICATION" ("INVOICEHEADER_ID", "LANGUAGE_CODE", "INVOICENUMBER", "INVOICEDATE", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "DELTOSTREET", "DELTOSTREET2", "DELTOCOUNTY", "DELTOSTATE", "DELTOCITY", "DELTOZIPCODE", "STREET", "STREET2", "COUNTY", "STATE", "CITY", "ZIPCODE", "ORIGINALCOLLECTIONTYPE", "TOTALAMOUNTEXCLVAT", "PAYTHISAMOUNT", "TAXAMOUNT", "INVLINESUBTYPE", "INVOICELINETYPE_ID", "INVOICELINETYPEDESC", "LINESEQUENCE", "LINEDESCRIPTION", "CODE", "DESCRIPTION", "EXTEND", "ADJUSTMENTREASON_ID", "PRODUCTGROUP_CODE", "PRODUCTGROUP_DESC", "BILLEDQTY", "AMOUNT", "DPBILLEDQTY", "DPAMOUNT", "ADJUSTMENTBILLEDQTY", "ADJUSTEDAMOUNT", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "INVOICEAMOUNTDECIMALS", "DECIMALS", "CURRENCYCODE", "CURRENCYDESC") AS 
  select ih.invoiceheader_id, lan.code Language_Code, ih.invoicenumber, ih.invoicedate,
       ih.deltocustomernumber, ih.deltocustomername, ih.billtocustomernumber, ih.billtocustomername,
       ih.deltostreet, ih.deltostreet2, ih.deltocounty, ih.deltostate, ih.deltocity, ih.deltozipcode,
       ih.street, ih.street2, ih.county, ih.state, ih.city, ih.zipcode,
       ih.originalcollectiontype, ih.totalamountexclvat, ih.paythisamount, (ih.paythisamount - ih.totalamountexclvat) TaxAmount,
       ist.factorydescription invlinesubtype, i.invoicelinetype_id,
       (select iltd.description from invoicelinetype_desc iltd where iltd.invoicelinetype_id = i.invoicelinetype_id and iltd.language_id = lan.language_id) invoicelinetypedesc,
       case when i.invoicelinetype_id = 11 then 'ZZZZZZZ' else pg.code end linesequence,
       case when i.invoicelinetype_id = 11 then ist.factorydescription-- 'GMP', 'GSP', 'GLP', 'GRP'
       else coalesce(pd.description, i.description) end linedescription,
       i.code, i.description, i.extend, i.adjustmentreason_id, pg.code productgroup_code, pd.description productgroup_desc,
       i.billedqty, i.amount, ildp.billedqty dpbilledqty, ildp.amount dpamount, i.adjustmentbilledqty, i.adjustedamount,
       coalesce(dep.departmentnumber, 999999999) departmentnumber, coalesce(dep.description, 'Other') departmentdesc,
       dp.distributionpointnumber, dp.description distributionpointdesc,
       cu.invoiceamountdecimals, cu.decimals, cu.code currencycode, cu.description currencydesc
from invoiceheader ih, invoiceline i
     left outer join invoicelinedp ildp
          inner join distributionpoint dp
                inner join department dep on dp.department_id = dep.department_id
          on ildp.distributionpoint_link_id = dp.distributionpoint_id
          inner join productgroup pg
                left outer join productgroup_desc pd on pd.productgroup_id = pg.productgroup_id
          on pg.productgroup_id = ildp.productgroup_id
     on ildp.invoiceline_id = i.invoiceline_id,
     invoicelinesubtype ist,  currency cu, languages lan
where ih.invoiceheader_id = i.invoiceheader_id and --i.extend = 'Y' and
      ist.invoicelinetype_id = i.invoicelinetype_id and ist.subtype = i.invoicelinesubtype and
      coalesce(pd.language_id, lan.language_id) = lan.language_id and ih.currency_id = cu.currency_id
/

  CREATE OR REPLACE VIEW "V_DVREFERENCE" ("CONSIGNMENTNOTE_ID", "REFERENCE") AS 
  select /*version 2.0*/
       distinct pn.consignmentnote_id, dv.reference
  from deliveryvariations dv
       join packingnote pn on dv.packingnote_id = pn.packingnote_id
/

  CREATE OR REPLACE VIEW "V_ECAPACKINGNOTE" ("NOTENUMBER", "PACKINGNOTE_ID", "DELIVERYDATE", "QTYREQUIRED", "LANGUAGECODE", "COUNTDATE", "CUSTOMERNUMBER", "CUSTOMERNAME", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTNAME", "DEPARTMENTNUMBER", "DEPARTMENTNAME", "SIZECODE", "PRODUCTCODE", "PLANTLOGO", "PRINTDATE", "PRODUCTDESCRIPTION") AS 
  select /*version 1.0*/
       pn.notenumber, pn.packingnote_id, pn.deliverydate, pnl.tobedeliveredamount qtyrequired, lan.code languagecode,
       pn.creationtimestamp countdate,
       c.customernumber, c.name customername, dp.distributionpointnumber, dp.description distributionpointname,
       dep.departmentnumber, dep.description departmentname, sd.code sizecode, pr.code productcode, p.logo plantlogo,
       (select rox.finalizationcompletetimestamp
          from routecontrolextrainfo rox
         where rox.routecontrol_id = pn.routecontrol_id) printdate,
       coalesce(plpc.customdescription, (select pds.description
                                           from product_desc pds
                                          where pds.product_id = pr.product_id
                                            and pds.language_id = lan.language_id)) productdescription
  from packingnote pn
       join packingnoteline pnl
            join product pr
                 join productlistpercustomer plpc on pr.product_id = plpc.product_id
            on pnl.product_id = pr.product_id
            join sizedefinition sd on pnl.sizedefinition_id = sd.sizedefinition_id
       on pn.packingnote_id = pnl.packingnote_id
       join distributionpoint dp
            join department dep
                 join customer c
                      join businessunit bu
                           join plant p on bu.plant_id = p.plant_id
                      on c.defaultbusinessunit_id = bu.businessunit_id
                 on dep.customer_id = c.customer_id
            on dp.department_id = dep.department_id
       on pn.distributionpoint_id = dp.distributionpoint_id
       cross join languages lan
 where plpc.customer_id = c.customer_id
   and pn.origin = 22
/

  CREATE OR REPLACE VIEW "V_EMBINFORMATION" ("PURCHASEORDERNUMBER", "ORDERDATE", "PRODUCTCODE", "PURCHASEORDERHEADER_ID", "QUANTITYORDERED", "PERSONNAME", "WORKORDERNUMBER", "WORKORDER_ID", "WORKORDERLINE_ID", "APPROVALTIMESTAMP", "SUPPLIERNUMBER", "PRODUCT_DESC") AS 
  select po.purchaseordernumber, po.orderdate, p.code productcode, po.purchaseorderheader_id, wol.quantityordered, wol.instructions personname,
       wo.workordernumber, wol.workorder_id, wol.workorderline_id, wo.approvaltimestamp,
       (select sp.suppliernumber
          from supplier sp
         where sp.supplier_id = po.supplier_id) suppliernumber,
       (select pd.description
          from product_desc pd
         where pd.product_id = wol.product_link_id
           and pd.language_id = lan.language_id) product_desc
  from workorderline wol
       join workorder wo on wol.workorder_id = wo.workorder_id
       join purchaseorderline pol on wol.purchaseorderline_id = pol.purchaseorderline_id
       join purchaseorderheader po on pol.purchaseorderheader_id = po.purchaseorderheader_id
       join product p on wol.product_link_id = p.product_id
       join productgroup pg on p.productgroup_id = pg.productgroup_id
       join businessunit bu on po.businessunit_id = bu.businessunit_id
       join plant pln on bu.plant_id = pln.plant_id
       join languages lan on pln.language_id = lan.language_id
 where wo.origin = 6 --sales note
   and wol.instructions is not null
   and pg.code = '08'
/

  CREATE OR REPLACE VIEW "V_EMBLEMHISTORY" ("LINETYPE", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "WEARERNUMBER", "WEARERNAME", "PRODUCTCODE", "PRODUCTDESC", "EMBLEMTEMPLATELINEDESC", "EMBLEMTEMPLATECODE", "EMBLEMTEMPLATEDESC", "SIZECODE", "QUANTITY", "AMOUNT", "UNIQUEITEM_LINK_ID", "EMBLEMSPECIFICATION", "PARENTINVOICEHEADER_ID", "INVOICEHEADER_ID", "LANGUAGECODE", "LANGUAGE_ID") AS 
  select 1 linetype
, f.customernumber, f.name customername, e.departmentnumber, e.description departmentdesc
, d.distributionpointnumber, d.description distributionpointdesc, w.wearernumber, w.wearername
, (select p.code from product p where a.emblemproduct_id = p.product_id) productcode
, (select pd.description from product_desc pd where a.emblemproduct_id = pd.product_id and pd.language_id = languages.language_id) productdesc
, (select etl.description from emblemtemplateline etl where a.emblemtemplateline_id = etl.emblemtemplateline_id) emblemtemplatelinedesc
, (select et.code from emblemtemplateline etl, emblemtemplate et where a.emblemtemplateline_id = etl.emblemtemplateline_id and etl.emblemtemplate_id = et.emblemtemplate_id) emblemtemplatecode
, (select et.description from emblemtemplateline etl, emblemtemplate et where a.emblemtemplateline_id = etl.emblemtemplateline_id and etl.emblemtemplate_id = et.emblemtemplate_id) emblemtemplatedesc
, (select sd.code from emblemtemplateline emb, sizedefinition sd where a.emblemtemplateline_id = emb.emblemtemplateline_id and emb.sizedefinition_id = sd.sizedefinition_id) sizecode
, a.quantity, a.amount, a.uniqueitem_link_id
, (select bill.emblemspecification from invoiceheader ih, customer bill where ih.invoiceheader_id = a.invoiceheader_id and ih.billtocustomer_link_id = bill.customer_id) emblemspecification
, (select i.parentinvoiceheader_id from invoiceheader i where i.invoiceheader_id = a.invoiceheader_id) parentinvoiceheader_id
, a.invoiceheader_id, languages.code languagecode,languages.language_id
from emblemhistory a, weareremployment_link w,
 distributionpoint_link d, department_link e, customer_link f, languages
where w.distributionpoint_link_id = d.distributionpoint_link_id--distrib point is taken via weareremployment
and d.department_link_id = e.department_link_id
and e.customer_link_id = f.customer_link_id --and a.status = 0
and a.weareremployment_link_id = w.weareremployment_link_id
and a.amount <> 0 --todo 24876(23122)
UNION ALL
select 2 linetype
, f.customernumber, f.name customername, e.departmentnumber, e.description departmentdesc
, d.distributionpointnumber, d.description distributionpointdesc, -1 wearernumber, '' wearername
, (select p.code from product p where a.emblemproduct_id = p.product_id) productcode
, (select pd.description from product_desc pd where a.emblemproduct_id = pd.product_id and pd.language_id = languages.language_id) productdesc
, (select etl.description from emblemtemplateline etl where a.emblemtemplateline_id = etl.emblemtemplateline_id) emblemtemplatelinedesc
, (select et.code from emblemtemplateline etl, emblemtemplate et where a.emblemtemplateline_id = etl.emblemtemplateline_id and etl.emblemtemplate_id = et.emblemtemplate_id) emblemtemplatecode
, (select et.description from emblemtemplateline etl, emblemtemplate et where a.emblemtemplateline_id = etl.emblemtemplateline_id and etl.emblemtemplate_id = et.emblemtemplate_id) emblemtemplatedesc
, (select sd.code from emblemtemplateline emb, sizedefinition sd where a.emblemtemplateline_id = emb.emblemtemplateline_id and emb.sizedefinition_id = sd.sizedefinition_id) sizecode
, a.quantity, a.amount, a.uniqueitem_link_id
, (select bill.emblemspecification from invoiceheader ih, customer bill where ih.invoiceheader_id = a.invoiceheader_id and ih.billtocustomer_link_id = bill.customer_id) emblemspecification
, (select i.parentinvoiceheader_id from invoiceheader i where i.invoiceheader_id = a.invoiceheader_id) parentinvoiceheader_id
, a.invoiceheader_id, languages.code languagecode, languages.language_id
from emblemhistory a,
 distributionpoint_link d, department_link e, customer_link f, languages
where a.distributionpoint_link_id = d.distributionpoint_link_id--distrib point is taken via emblemhistory
and d.department_link_id = e.department_link_id
and e.customer_link_id = f.customer_link_id--and a.status = 0
and a.weareremployment_link_id IS NULL
and a.amount <> 0 --todo 23122
/

  CREATE OR REPLACE VIEW "V_EMBLEMMODIFICATIONPICKLIST" ("PICKLIST_ID", "CODE", "DESCRIPTION", "LANGUAGECODE", "PRODUCTID") AS 
  SELECT DISTINCT PLT.PICKLIST_ID,
                (CASE
                  WHEN (X.PRODUCT_ID IS NOT NULL AND
                       X.EMBLEMTEMPLATELINE_ID IS NOT NULL) THEN
                   X.ETL_PR_CODE
                  WHEN (X.PRODUCT_ID IS NULL AND
                       X.EMBLEMTEMPLATELINE_ID IS NOT NULL) THEN
                   X.WOLE_PR_CODE
                  WHEN X.EMBLEMTEMPLATELINE_ID IS NULL THEN
                   X.ET_CODE
                END) CODE,
                /*CAST(*/
                (CASE
                  WHEN (X.PRODUCT_ID IS NOT NULL AND
                       X.EMBLEMTEMPLATELINE_ID IS NOT NULL) THEN
                   X.ETL_PRD_DESC
                  WHEN (X.PRODUCT_ID IS NULL AND
                       X.EMBLEMTEMPLATELINE_ID IS NOT NULL AND
                       WOLE_PRD_DESC IS NOT NULL) THEN
                   X.WOLE_PRD_DESC
                  ELSE
                   X.ET_DESC
                END) /* AS VARCHAR2(50))*/ DESCRIPTION,
                X.CODE LANGUAGECODE,
                SDI.PRODUCT_ID PRODUCTID
  FROM (SELECT WOLE.WORKORDERLINE_ID,
               WOLE.WORKORDERLINEEMBLEM_ID EMBLEMTEMPLATELINE_ID,
               ET.CODE ET_CODE,
               ET.DESCRIPTION ET_DESC,
               ETL.PRODUCT_ID PRODUCT_ID,
               ETL.DESCRIPTION ETL_DESC,
               PRT.CODE ETL_PR_CODE,
               (SELECT PRD.DESCRIPTION
                  FROM PRODUCT_DESC PRD
                 WHERE PRD.PRODUCT_ID = ETL.PRODUCT_ID
                   AND PRD.LANGUAGE_ID = LNG.LANGUAGE_ID) ETL_PRD_DESC,
               PR.CODE WOLE_PR_CODE,
               (SELECT PRD.DESCRIPTION
                  FROM PRODUCT_DESC PRD
                 WHERE PRD.PRODUCT_ID = WOLE.PRODUCT_ID
                   AND PRD.LANGUAGE_ID = LNG.LANGUAGE_ID) WOLE_PRD_DESC,
               LNG.CODE
          FROM WORKORDERLINEEMBLEM WOLE,
               EMBLEMTEMPLATELINE  ETL,
               EMBLEMTEMPLATE      ET,
               PRODUCT             PR,
               PRODUCT             PRT,
               LANGUAGES           LNG
         WHERE ETL.EMBLEMTEMPLATELINE_ID(+) = WOLE.EMBLEMTEMPLATELINE_ID
           AND ET.EMBLEMTEMPLATE_ID = ETL.EMBLEMTEMPLATE_ID
           AND PR.PRODUCT_ID(+) = WOLE.PRODUCT_ID
           AND PRT.PRODUCT_ID(+) = ETL.PRODUCT_ID) X,
       PICKLISTLINEORIGIN PLO,
       PICKLISTLINE PLN,
       PICKLIST PLT,
       stockreservationpergrade  SRG,
       stockdefinitionperitem    SDI
 WHERE X.WORKORDERLINE_ID = PLO.BASELINETABLE_LINK_ID
   AND PLN.PICKLISTLINE_ID = PLO.PICKLISTLINE_ID
   AND PLN.PICKLIST_ID = PLT.PICKLIST_ID
   AND SRG.STOCKRESERVATIONPERGRADE_ID = PLN.Stockreservationpergrade_Id
   AND SRG.STOCKDEFINITIONPERITEM_ID = SDI.STOCKDEFINITIONPERITEM_ID
   AND PLO.BASELINETYPE = 1
UNION ALL
SELECT DISTINCT PLT.PICKLIST_ID,
                MO.CODE,
                MD.DESCRIPTION,
                LNG.CODE LANGUAGECODE,
                SDI.PRODUCT_ID PRODUCTID
  FROM WORKORDERLINEMODIFICATION T,
       PICKLISTLINEORIGIN        PLO,
       MODIFICATION              MO,
       MODIFICATION_DESC         MD,
       LANGUAGES                 LNG,
       PICKLISTLINE              PLN,
       PICKLIST                  PLT,
       stockreservationpergrade  SRG,
       stockdefinitionperitem    SDI
 WHERE MO.MODIFICATION_ID = T.MODIFICATION_ID
   AND MD.MODIFICATION_ID = MO.MODIFICATION_ID
   AND MD.LANGUAGE_ID = LNG.LANGUAGE_ID
   AND T.WORKORDERLINE_ID = PLO.BASELINETABLE_LINK_ID
   AND PLN.PICKLISTLINE_ID = PLO.PICKLISTLINE_ID
   AND PLN.PICKLIST_ID = PLT.PICKLIST_ID
   AND SRG.STOCKRESERVATIONPERGRADE_ID = PLN.Stockreservationpergrade_Id
   AND SRG.STOCKDEFINITIONPERITEM_ID = SDI.STOCKDEFINITIONPERITEM_ID
   AND PLO.BASELINETYPE = 1
/

  CREATE OR REPLACE VIEW "V_EMBLEMTEMPLATE" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CODE", "DESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, EMBLEMTEMPLATE.CODE, EMBLEMTEMPLATE.DESCRIPTION,
 emblemtemplate.systemuser_id, EMBLEMTEMPLATE.TIMESTAMP
	FROM  EMBLEMTEMPLATE, CUSTOMER
	WHERE EMBLEMTEMPLATE.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
/

  CREATE OR REPLACE VIEW "V_EMPLOYEE" ("PLANTCODE", "PLANTNAME", "EMPLOYEENUMBER", "NAME", "SEARCHNAME", "DATEACTIVE", "DATEINACTIVE", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  SELECT PLANT.CODE, PLANT.NAME, EMPLOYEE.EMPLOYEENUMBER, EMPLOYEE.NAME, EMPLOYEE.SEARCHNAME,
 EMPLOYEE.DATEACTIVE, EMPLOYEE.DATEINACTIVE, EMPLOYEE.SYSTEMUSER_ID, EMPLOYEE.TIMESTAMP
       FROM PLANT, EMPLOYEE
       WHERE EMPLOYEE.PLANT_ID = PLANT.PLANT_ID
/

  CREATE OR REPLACE VIEW "V_ENHANCEDRETURNTOSTOCK" ("LINETYPE", "BUSINESSUNIT_ID", "BU_CODE", "BU_DESC", "DATEINACTIVE", "DATEACTIVE", "FLAG_STARTDATE", "WEINV_LOSSCHARGEDATE", "LOSSCHARGEDATE", "LOSSCHARGEDAYS", "MAXINVENTORY", "CIRCINVENTORY", "MAXFREEOFCHARGE", "FREEOFCHARGEQTY", "CHANGESPERWEEK", "SALESAREA_CODE", "ROUTENUMBER", "DRIVINGDAY_NUMBER", "DELIVERYTYPE", "DELIVERYDAY_NUMBER", "DELIVERYDAY_DESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "NAMEONLABEL", "CUSTDATEACTIVE", "CUSTDATEINACTIVE", "BILLINGDAYCODE", "MINBILLINGDAY", "SEARCHNAME", "WEARERNUMBER", "FULLNAME", "FIRSTNAME", "WEARER_DATEACTIVE", "WEARER_DATEINACTIVE", "PRODUCT_CODE", "PRODUCT_DESC", "SIZE_CODE", "COMMONCUSTOMERNUMBER", "BILLTOCUSTOMERNUMBER", "PAYBYCUSTOMERNUMBER", "MASTERACCOUNTNUMBER", "LANGUAGE_CODE", "CURRENTUSER_ID", "TIMESTAMP", "REPORTPARAM_ID", "PRIMARYID") AS 
  select 0 linetype --Layout per Customer with Billing Day ALL
, bu.businessunit_id, bu.code bu_code, bu.description bu_desc, wi.dateinactive, wi.dateactive, x.startdate flag_startdate, wi.losschargedate weinv_losschargedate
, coalesce(wi.losschargedate, x.losschargedate,
           case when getdaynumber(x.startdate) < (select min(d2.daynumber) from day d2, CUSTOMERDELIVERYDAY cdd2 where cu.customer_id = cdd2.customer_id
                                                  and cdd2.day_id = d2.day_id and cdd2.deliverytype = 'B' and cdd2.typeofmerchadise = 2)
                then x.startdate + 7*castVarcharAsNumber(coalesce((select ss.value from systemsetting ss where ss.plant_id = bu.plant_id and ss.name = 'WEEKSWARNLOSSCHARGE'), '0'))
                     - getdaynumber(x.startdate) + (select min(d2.daynumber) from day d2, CUSTOMERDELIVERYDAY cdd2 where cu.customer_id = cdd2.customer_id
                                                  and cdd2.day_id = d2.day_id and cdd2.deliverytype = 'B' and cdd2.typeofmerchadise = 2)
           else 7 + x.startdate + 7*castVarcharAsNumber(coalesce((select ss.value from systemsetting ss where ss.plant_id = bu.plant_id and ss.name = 'WEEKSWARNLOSSCHARGE'), '0'))
                - getdaynumber(x.startdate) + (select min(d2.daynumber) from day d2, CUSTOMERDELIVERYDAY cdd2 where cu.customer_id = cdd2.customer_id
                                                  and cdd2.day_id = d2.day_id and cdd2.deliverytype = 'B' and cdd2.typeofmerchadise = 2)
           end
  ) losschargedate
, 7*castVarcharAsNumber(coalesce((select ss.value from systemsetting ss where ss.plant_id = bu.plant_id and ss.name = 'WEEKSWARNLOSSCHARGE'), '0')) LossChargeDays
, wi.maxinventory, wi.circinventory, wi.maxfreeofcharge, wi.freeofchargeqty, wi.changesperweek
, sa.code SalesArea_Code
, ro.routenumber
, 0 drivingday_number
, 'B' deliverytype, 0 DeliveryDay_number
, ' ' deliveryday_desc
, cu.customernumber, cu.name CustomerName, cu.customermarkinggarment NameOnLabel, cu.dateactive CustDateActive, cu.dateinactive CustDateInactive
, (select ListAgg(castnumberasvarchar(d1.daynumber),',') WITHIN GROUP (order by d1.daynumber) from day d1, CUSTOMERDELIVERYDAY cdd1
  where cu.customer_id = cdd1.customer_id and cdd1.day_id = d1.day_id and cdd1.deliverytype = 'B' and cdd1.typeofmerchadise = 2)
BillingDayCode
, (select min(d2.daynumber) from day d2, CUSTOMERDELIVERYDAY cdd2
  where cu.customer_id = cdd2.customer_id and cdd2.day_id = d2.day_id and cdd2.deliverytype = 'B' and cdd2.typeofmerchadise = 2)
MinBillingDay
, w.searchname, w.wearernumber, w.fullname, w.firstname
, w.dateactive Wearer_DateActive, w.dateinactive Wearer_DateInactive
, (select p.code from product p where wi.product_id = p.product_id) product_code
, (select pd.description from product_desc pd where wi.product_id = pd.product_id and pd.language_id = lan.language_id) product_desc
, (select s.code from sizedefinition s where wi.sizedefinition_id = s.sizedefinition_id) size_code
, (select cc.customernumber from customer cc where cu.commoncustomer_id = cc.customer_id) CommonCustomerNumber
, (select bt.customernumber from customer bt where cu.debtor_id = bt.customer_id) BillToCustomerNumber
, (select pb.customernumber from customer pb, customerbillinginfo cbi
          where cbi.customer_id = cu.debtor_id and cbi.paybycustomer_link_id = pb.customer_id) PayByCustomerNumber
, (select ma.customernumber from customer ma where cu.masteraccount_id = ma.customer_id) MasterAccountNumber
, lan.code Language_Code, curr.systemuser_id currentuser_id, trunc(wi.timestamp) timestamp
, rp.reportparam_id
, x.primaryid
from wearerinventory wi
     inner join weareremployment we
           inner join wearer w
                 inner join customer cu
                       inner join businessunit bu on cu.defaultbusinessunit_id = bu.businessunit_id
                       inner join salesarea sa on cu.salesarea_id = sa.salesarea_id
                       inner join routestop rs
                             inner join route ro on rs.route_id = ro.route_id
                       on cu.customer_id = rs.customer_id
                 on w.customer_id = cu.customer_id
           on we.wearer_id = w.wearer_id
     on wi.weareremployment_id = we.weareremployment_id
     left outer join (select u.primaryid, un.wearerinventory_id, max(uif.losschargedate) losschargedate, min(uf.startdate) startdate
                   from   uniqueitemnonpool un
                          inner join uniqueitem u
                                inner join uniqueitemflag uf
                                      inner join automaticflag af on uf.flag_id = af.flag_id
                                      inner join flag fl on uf.flag_id = fl.flag_id
                                on u.uniqueitem_id = uf.uniqueitem_id
                                inner join uniqueitemfixedinfo uif on u.uniqueitem_id = uif.uniqueitem_id
                          on un.uniqueitem_id = u.uniqueitem_id
                   where  fl.code in ('REP', 'RTS2')
                   group  by u.primaryid, un.wearerinventory_id
                   having min(uf.startdate) < getABSMaxDate()) x
     on wi.wearerinventory_id = x.wearerinventory_id
     , languages lan, systemuser curr, reportparam rp
where rs.stopnumber in (select min(rs2.stopnumber) from routestop rs2 where rs2.customer_id = cu.customer_id and rs2.route_id = ro.route_id)
      and ro.drivingday_id in (select min(ro2.drivingday_id) from route ro2, routestop rs3 where ro2.plant_id = ro.plant_id
                           and ro2.routenumber = ro.routenumber and rs3.customer_id = cu.customer_id and rs3.route_id = ro2.route_id)
      AND EXISTS (SELECT 1 FROM CUSTOMERDELIVERYDAY CDD WHERE CDD.Deliverytype = 'B' and cu.customer_id = cdd.customer_id and cdd.typeofmerchadise = 2)
      and rp.number_value = 0 and rp.number_value1 = 0
      and cu.customernumber >= rp.number_value2 and cu.customernumber <= rp.number_value3
      and ro.routenumber >= rp.number_value4 and ro.routenumber <= rp.number_value5
      and lan.code = rp.string_value
      and sa.code >= rp.string_value1 and sa.code <= rp.string_value2
      and curr.systemuser_id = rp.number_value7
      and (/*(wi.dateinactive = getABSMaxDate() and wi.circinventory + wi.freeofchargeqty > wi.maxinventory + wi.maxfreeofcharge)
          or (wi.dateinactive >= rp.date_value1 and wi.dateinactive <= rp.date_value2)
          or*/ (case --quit wearer
                   when w.dateinactive >= rp.date_value1 and w.dateinactive <= rp.date_value2 and
                        wi.dateinactive = w.dateinactive and wi.maxinventory + wi.maxfreeofcharge > 0 then 1
                   --decrease item
                   when w.dateinactive > wi.dateinactive and wi.dateinactive >= rp.date_value1 and wi.dateinactive <= rp.date_value2
                        and wi.maxinventory + wi.maxfreeofcharge > 0 then 2
                   --decrease volume(max inventory)
                   when wi.dateinactive > rp.date_value2 and wi.maxinventory + wi.maxfreeofcharge > 0 and
                        wi.circinventory + wi.freeofchargeqty > wi.maxinventory + wi.maxfreeofcharge then 3
                   --replacement
                   when wi.dateinactive >= rp.date_value1 and wi.maxinventory + wi.maxfreeofcharge = 0 then 4
                   else 0 end <> 0))
union all
select 1 linetype--Layout per Customer with Billing Day something selected
, bu.businessunit_id, bu.code bu_code, bu.description bu_desc, wi.dateinactive, wi.dateactive, x.startdate flag_startdate, wi.losschargedate weinv_losschargedate
, coalesce(wi.losschargedate, x.losschargedate,
           case when getdaynumber(x.startdate) < (select min(d2.daynumber) from day d2, CUSTOMERDELIVERYDAY cdd2 where cu.customer_id = cdd2.customer_id
                                                  and cdd2.day_id = d2.day_id and cdd2.deliverytype = 'B' and cdd2.typeofmerchadise = 2)
                then x.startdate + 7*castVarcharAsNumber(coalesce((select ss.value from systemsetting ss where ss.plant_id = bu.plant_id and ss.name = 'WEEKSWARNLOSSCHARGE'), '0'))
                     - getdaynumber(x.startdate) + (select min(d2.daynumber) from day d2, CUSTOMERDELIVERYDAY cdd2 where cu.customer_id = cdd2.customer_id
                                                  and cdd2.day_id = d2.day_id and cdd2.deliverytype = 'B' and cdd2.typeofmerchadise = 2)
           else 7 + x.startdate + 7*castVarcharAsNumber(coalesce((select ss.value from systemsetting ss where ss.plant_id = bu.plant_id and ss.name = 'WEEKSWARNLOSSCHARGE'), '0'))
                - getdaynumber(x.startdate) + (select min(d2.daynumber) from day d2, CUSTOMERDELIVERYDAY cdd2 where cu.customer_id = cdd2.customer_id
                                                  and cdd2.day_id = d2.day_id and cdd2.deliverytype = 'B' and cdd2.typeofmerchadise = 2)
           end
  ) losschargedate
, 7*castVarcharAsNumber(coalesce((select ss.value from systemsetting ss where ss.plant_id = bu.plant_id and ss.name = 'WEEKSWARNLOSSCHARGE'), '0')) LossChargeDays
, wi.maxinventory, wi.circinventory, wi.maxfreeofcharge, wi.freeofchargeqty, wi.changesperweek
, sa.code SalesArea_Code
, ro.routenumber
, (select da.daynumber from day da where ro.drivingday_id = da.day_id) drivingday_number
, cdd.deliverytype, d.daynumber DeliveryDay_number
, (select dd.description from day_desc dd where d.day_id = dd.day_id and dd.language_id = lan.language_id) deliveryday_desc
, cu.customernumber, cu.name CustomerName, cu.customermarkinggarment NameOnLabel, cu.dateactive CustDateActive, cu.dateinactive CustDateInactive
, (select ListAgg(castnumberasvarchar(d1.daynumber),',') WITHIN GROUP (order by d1.daynumber) from day d1, CUSTOMERDELIVERYDAY cdd1
  where cu.customer_id = cdd1.customer_id and cdd1.day_id = d1.day_id and cdd1.deliverytype = 'B' and cdd1.typeofmerchadise = 2)
BillingDayCode
, (select min(d2.daynumber) from day d2, CUSTOMERDELIVERYDAY cdd2
  where cu.customer_id = cdd2.customer_id and cdd2.day_id = d2.day_id and cdd2.deliverytype = 'B' and cdd2.typeofmerchadise = 2)
MinBillingDay
, w.searchname, w.wearernumber, w.fullname, w.firstname
, w.dateactive Wearer_DateActive, w.dateinactive Wearer_DateInactive
, (select p.code from product p where wi.product_id = p.product_id) product_code
, (select pd.description from product_desc pd where wi.product_id = pd.product_id and pd.language_id = lan.language_id) product_desc
, (select s.code from sizedefinition s where wi.sizedefinition_id = s.sizedefinition_id) size_code
, (select cc.customernumber from customer cc where cu.commoncustomer_id = cc.customer_id) CommonCustomerNumber
, (select bt.customernumber from customer bt where cu.debtor_id = bt.customer_id) BillToCustomerNumber
, (select pb.customernumber from customer pb, customerbillinginfo cbi
          where cbi.customer_id = cu.debtor_id and cbi.paybycustomer_link_id = pb.customer_id) PayByCustomerNumber
, (select ma.customernumber from customer ma where cu.masteraccount_id = ma.customer_id) MasterAccountNumber
, lan.code Language_Code, curr.systemuser_id currentuser_id, trunc(wi.timestamp) timestamp
, rp.reportparam_id
, x.primaryid
from wearerinventory wi
     inner join weareremployment we
           inner join wearer w
                 inner join customer cu
                       inner join businessunit bu on cu.defaultbusinessunit_id = bu.businessunit_id
                       inner join salesarea sa on cu.salesarea_id = sa.salesarea_id
                       inner join routestop rs
                             inner join route ro on rs.route_id = ro.route_id
                       on cu.customer_id = rs.customer_id
                 on w.customer_id = cu.customer_id
           on we.wearer_id = w.wearer_id
     on wi.weareremployment_id = we.weareremployment_id
     left outer join (select u.primaryid, un.wearerinventory_id, max(uif.losschargedate) losschargedate, min(uf.startdate) startdate
                   from   uniqueitemnonpool un
                          inner join uniqueitem u
                                inner join uniqueitemflag uf
                                      inner join automaticflag af on uf.flag_id = af.flag_id
                                      inner join flag fl on uf.flag_id = fl.flag_id
                                on u.uniqueitem_id = uf.uniqueitem_id
                                inner join uniqueitemfixedinfo uif on u.uniqueitem_id = uif.uniqueitem_id
                          on un.uniqueitem_id = u.uniqueitem_id
                   where  fl.code in ('REP', 'RTS2')
                   group  by u.primaryid, un.wearerinventory_id
                   having min(uf.startdate) < getABSMaxDate()) x
     on wi.wearerinventory_id = x.wearerinventory_id
     , CUSTOMERDELIVERYDAY cdd, day d
     , languages lan, systemuser curr, reportparam rp
where cu.customer_id = cdd.customer_id and cdd.day_id = d.day_id and cdd.typeofmerchadise = 2 --and cdd.deliverytype = 'B'
      and rs.stopnumber in (select min(rs2.stopnumber) from routestop rs2 where rs2.customer_id = cu.customer_id and rs2.route_id = ro.route_id)
      and rp.number_value = 0 and rp.number_value1 <> 0
      and cu.customernumber >= rp.number_value2 and cu.customernumber <= rp.number_value3
      and ro.routenumber >= rp.number_value4 and ro.routenumber <= rp.number_value5
      and lan.code = rp.string_value
      and sa.code >= rp.string_value1 and sa.code <= rp.string_value2
      and curr.systemuser_id = rp.number_value7
      and (/*(wi.dateinactive = getABSMaxDate() and wi.circinventory + wi.freeofchargeqty > wi.maxinventory + wi.maxfreeofcharge)
          or (wi.dateinactive >= rp.date_value1 and wi.dateinactive <= rp.date_value2)
          or*/ (case --quit wearer
                   when w.dateinactive >= rp.date_value1 and w.dateinactive <= rp.date_value2 and
                        wi.dateinactive = w.dateinactive and wi.maxinventory + wi.maxfreeofcharge > 0 then 1
                   --decrease item
                   when w.dateinactive > wi.dateinactive and wi.dateinactive >= rp.date_value1 and wi.dateinactive <= rp.date_value2
                        and wi.maxinventory + wi.maxfreeofcharge > 0 then 2
                   --decrease volume(max inventory)
                   when wi.dateinactive > rp.date_value2 and wi.maxinventory + wi.maxfreeofcharge > 0 and
                        wi.circinventory + wi.freeofchargeqty > wi.maxinventory + wi.maxfreeofcharge then 3
                   --replacement
                   when wi.dateinactive >= rp.date_value1 and wi.maxinventory + wi.maxfreeofcharge = 0 then 4
                   else 0 end <> 0))
union all
select 2 linetype --Layout per Route OR Sales Area with Billing Day ALL
, bu.businessunit_id, bu.code bu_code, bu.description bu_desc, wi.dateinactive, wi.dateactive, x.startdate flag_startdate, wi.losschargedate weinv_losschargedate
, coalesce(wi.losschargedate, x.losschargedate,
           case when getdaynumber(x.startdate) < (select min(d2.daynumber) from day d2, CUSTOMERDELIVERYDAY cdd2 where cu.customer_id = cdd2.customer_id
                                                  and cdd2.day_id = d2.day_id and cdd2.deliverytype = 'B' and cdd2.typeofmerchadise = 2)
                then x.startdate + 7*castVarcharAsNumber(coalesce((select ss.value from systemsetting ss where ss.plant_id = bu.plant_id and ss.name = 'WEEKSWARNLOSSCHARGE'), '0'))
                     - getdaynumber(x.startdate) + (select min(d2.daynumber) from day d2, CUSTOMERDELIVERYDAY cdd2 where cu.customer_id = cdd2.customer_id
                                                  and cdd2.day_id = d2.day_id and cdd2.deliverytype = 'B' and cdd2.typeofmerchadise = 2)
           else 7 + x.startdate + 7*castVarcharAsNumber(coalesce((select ss.value from systemsetting ss where ss.plant_id = bu.plant_id and ss.name = 'WEEKSWARNLOSSCHARGE'), '0'))
                - getdaynumber(x.startdate) + (select min(d2.daynumber) from day d2, CUSTOMERDELIVERYDAY cdd2 where cu.customer_id = cdd2.customer_id
                                                  and cdd2.day_id = d2.day_id and cdd2.deliverytype = 'B' and cdd2.typeofmerchadise = 2)
           end
  ) losschargedate
, 7*castVarcharAsNumber(coalesce((select ss.value from systemsetting ss where ss.plant_id = bu.plant_id and ss.name = 'WEEKSWARNLOSSCHARGE'), '0')) LossChargeDays
, wi.maxinventory, wi.circinventory, wi.maxfreeofcharge, wi.freeofchargeqty, wi.changesperweek
, sa.code SalesArea_Code, ro.routenumber
, (select da.daynumber from day da where ro.drivingday_id = da.day_id) drivingday_number
, 'B' deliverytype, 0 DeliveryDay_number
, ' ' deliveryday_desc
, cu.customernumber, cu.name CustomerName, cu.customermarkinggarment NameOnLabel, cu.dateactive CustDateActive, cu.dateinactive CustDateInactive
, (select ListAgg(castnumberasvarchar(d1.daynumber),',') WITHIN GROUP (order by d1.daynumber) from day d1, CUSTOMERDELIVERYDAY cdd1
  where cu.customer_id = cdd1.customer_id and cdd1.day_id = d1.day_id and cdd1.deliverytype = 'B' and cdd1.typeofmerchadise = 2)
BillingDayCode
, (select min(d2.daynumber) from day d2, CUSTOMERDELIVERYDAY cdd2
  where cu.customer_id = cdd2.customer_id and cdd2.day_id = d2.day_id and cdd2.deliverytype = 'B' and cdd2.typeofmerchadise = 2)
MinBillingDay
, w.searchname, w.wearernumber, w.fullname, w.firstname
, w.dateactive Wearer_DateActive, w.dateinactive Wearer_DateInactive
, (select p.code from product p where wi.product_id = p.product_id) product_code
, (select pd.description from product_desc pd where wi.product_id = pd.product_id and pd.language_id = lan.language_id) product_desc
, (select s.code from sizedefinition s where wi.sizedefinition_id = s.sizedefinition_id) size_code
, (select cc.customernumber from customer cc where cu.commoncustomer_id = cc.customer_id) CommonCustomerNumber
, (select bt.customernumber from customer bt where cu.debtor_id = bt.customer_id) BillToCustomerNumber
, (select pb.customernumber from customer pb, customerbillinginfo cbi
          where cbi.customer_id = cu.debtor_id and cbi.paybycustomer_link_id = pb.customer_id) PayByCustomerNumber
, (select ma.customernumber from customer ma where cu.masteraccount_id = ma.customer_id) MasterAccountNumber
, lan.code Language_Code, curr.systemuser_id currentuser_id, trunc(wi.timestamp) timestamp
, rp.reportparam_id
, x.primaryid
from wearerinventory wi
     inner join weareremployment we
           inner join wearer w
                 inner join customer cu
                       inner join businessunit bu on cu.defaultbusinessunit_id = bu.businessunit_id
                       inner join salesarea sa on cu.salesarea_id = sa.salesarea_id
                       inner join routestop rs
                             inner join route ro on rs.route_id = ro.route_id
                       on cu.customer_id = rs.customer_id
                 on w.customer_id = cu.customer_id
           on we.wearer_id = w.wearer_id
     on wi.weareremployment_id = we.weareremployment_id
     left outer join (select u.primaryid, un.wearerinventory_id, max(uif.losschargedate) losschargedate, min(uf.startdate) startdate
                   from   uniqueitemnonpool un
                          inner join uniqueitem u
                                inner join uniqueitemflag uf
                                      inner join automaticflag af on uf.flag_id = af.flag_id
                                      inner join flag fl on uf.flag_id = fl.flag_id
                                on u.uniqueitem_id = uf.uniqueitem_id
                                inner join uniqueitemfixedinfo uif on u.uniqueitem_id = uif.uniqueitem_id
                          on un.uniqueitem_id = u.uniqueitem_id
                   where  fl.code in ('REP', 'RTS2')
                   group  by u.primaryid, un.wearerinventory_id
                   having min(uf.startdate) < getABSMaxDate()) x
     on wi.wearerinventory_id = x.wearerinventory_id
     , languages lan, systemuser curr, reportparam rp
where rs.stopnumber in (select min(rs2.stopnumber) from routestop rs2 where rs2.customer_id = cu.customer_id and rs2.route_id = ro.route_id)
      AND EXISTS (SELECT 1 FROM CUSTOMERDELIVERYDAY CDD WHERE CDD.Deliverytype = 'B' and cu.customer_id = cdd.customer_id
                 and cdd.typeofmerchadise = 2 and cdd.day_id = ro.drivingday_id)
      and rp.number_value <> 0 and rp.number_value1 = 0
      and cu.customernumber >= rp.number_value2 and cu.customernumber <= rp.number_value3
      and ro.routenumber >= rp.number_value4 and ro.routenumber <= rp.number_value5
      and lan.code = rp.string_value
      and sa.code >= rp.string_value1 and sa.code <= rp.string_value2
      and curr.systemuser_id = rp.number_value7
      and (/*(wi.dateinactive = getABSMaxDate() and wi.circinventory + wi.freeofchargeqty > wi.maxinventory + wi.maxfreeofcharge)
          or (wi.dateinactive >= rp.date_value1 and wi.dateinactive <= rp.date_value2)
          or*/ (case --quit wearer
                   when w.dateinactive >= rp.date_value1 and w.dateinactive <= rp.date_value2 and
                        wi.dateinactive = w.dateinactive and wi.maxinventory + wi.maxfreeofcharge > 0 then 1
                   --decrease item
                   when w.dateinactive > wi.dateinactive and wi.dateinactive >= rp.date_value1 and wi.dateinactive <= rp.date_value2
                        and wi.maxinventory + wi.maxfreeofcharge > 0 then 2
                   --decrease volume(max inventory)
                   when wi.dateinactive > rp.date_value2 and wi.maxinventory + wi.maxfreeofcharge > 0 and
                        wi.circinventory + wi.freeofchargeqty > wi.maxinventory + wi.maxfreeofcharge then 3
                   --replacement
                   when wi.dateinactive >= rp.date_value1 and wi.maxinventory + wi.maxfreeofcharge = 0 then 4
                   else 0 end <> 0))
union all
select 3 linetype --Layout per Route OR Sales Area with Billing Day something selected
, bu.businessunit_id, bu.code bu_code, bu.description bu_desc, wi.dateinactive, wi.dateactive, x.startdate flag_startdate, wi.losschargedate weinv_losschargedate
, coalesce(wi.losschargedate, x.losschargedate,
           case when getdaynumber(x.startdate) < (select min(d2.daynumber) from day d2, CUSTOMERDELIVERYDAY cdd2 where cu.customer_id = cdd2.customer_id
                                                  and cdd2.day_id = d2.day_id and cdd2.deliverytype = 'B' and cdd2.typeofmerchadise = 2)
                then x.startdate + 7*castVarcharAsNumber(coalesce((select ss.value from systemsetting ss where ss.plant_id = bu.plant_id and ss.name = 'WEEKSWARNLOSSCHARGE'), '0'))
                     - getdaynumber(x.startdate) + (select min(d2.daynumber) from day d2, CUSTOMERDELIVERYDAY cdd2 where cu.customer_id = cdd2.customer_id
                                                  and cdd2.day_id = d2.day_id and cdd2.deliverytype = 'B' and cdd2.typeofmerchadise = 2)
           else 7 + x.startdate + 7*castVarcharAsNumber(coalesce((select ss.value from systemsetting ss where ss.plant_id = bu.plant_id and ss.name = 'WEEKSWARNLOSSCHARGE'), '0'))
                - getdaynumber(x.startdate) + (select min(d2.daynumber) from day d2, CUSTOMERDELIVERYDAY cdd2 where cu.customer_id = cdd2.customer_id
                                                  and cdd2.day_id = d2.day_id and cdd2.deliverytype = 'B' and cdd2.typeofmerchadise = 2)
           end
  ) losschargedate
, 7*castVarcharAsNumber(coalesce((select ss.value from systemsetting ss where ss.plant_id = bu.plant_id and ss.name = 'WEEKSWARNLOSSCHARGE'), '0')) LossChargeDays
, wi.maxinventory, wi.circinventory, wi.maxfreeofcharge, wi.freeofchargeqty, wi.changesperweek
, sa.code SalesArea_Code, ro.routenumber
, (select da.daynumber from day da where ro.drivingday_id = da.day_id) drivingday_number
, cdd.deliverytype, d.daynumber DeliveryDay_number
, (select dd.description from day_desc dd where d.day_id = dd.day_id and dd.language_id = lan.language_id) deliveryday_desc
, cu.customernumber, cu.name CustomerName, cu.customermarkinggarment NameOnLabel, cu.dateactive CustDateActive, cu.dateinactive CustDateInactive
, (select ListAgg(castnumberasvarchar(d1.daynumber),',') WITHIN GROUP (order by d1.daynumber) from day d1, CUSTOMERDELIVERYDAY cdd1
  where cu.customer_id = cdd1.customer_id and cdd1.day_id = d1.day_id and cdd1.deliverytype = 'B' and cdd1.typeofmerchadise = 2)
BillingDayCode
, (select min(d2.daynumber) from day d2, CUSTOMERDELIVERYDAY cdd2
  where cu.customer_id = cdd2.customer_id and cdd2.day_id = d2.day_id and cdd2.deliverytype = 'B' and cdd2.typeofmerchadise = 2)
MinBillingDay
, w.searchname, w.wearernumber, w.fullname, w.firstname
, w.dateactive Wearer_DateActive, w.dateinactive Wearer_DateInactive
, (select p.code from product p where wi.product_id = p.product_id) product_code
, (select pd.description from product_desc pd where wi.product_id = pd.product_id and pd.language_id = lan.language_id) product_desc
, (select s.code from sizedefinition s where wi.sizedefinition_id = s.sizedefinition_id) size_code
, (select cc.customernumber from customer cc where cu.commoncustomer_id = cc.customer_id) CommonCustomerNumber
, (select bt.customernumber from customer bt where cu.debtor_id = bt.customer_id) BillToCustomerNumber
, (select pb.customernumber from customer pb, customerbillinginfo cbi
          where cbi.customer_id = cu.debtor_id and cbi.paybycustomer_link_id = pb.customer_id) PayByCustomerNumber
, (select ma.customernumber from customer ma where cu.masteraccount_id = ma.customer_id) MasterAccountNumber
, lan.code Language_Code, curr.systemuser_id currentuser_id, trunc(wi.timestamp) timestamp
, rp.reportparam_id
, x.primaryid
from wearerinventory wi
     inner join weareremployment we
           inner join wearer w
                 inner join customer cu
                       inner join businessunit bu on cu.defaultbusinessunit_id = bu.businessunit_id
                       inner join salesarea sa on cu.salesarea_id = sa.salesarea_id
                       inner join routestop rs
                             inner join route ro on rs.route_id = ro.route_id
                       on cu.customer_id = rs.customer_id
                 on w.customer_id = cu.customer_id
           on we.wearer_id = w.wearer_id
     on wi.weareremployment_id = we.weareremployment_id
     left outer join (select u.primaryid, un.wearerinventory_id, max(uif.losschargedate) losschargedate, min(uf.startdate) startdate
                   from   uniqueitemnonpool un
                          inner join uniqueitem u
                                inner join uniqueitemflag uf
                                      inner join automaticflag af on uf.flag_id = af.flag_id
                                      inner join flag fl on uf.flag_id = fl.flag_id
                                on u.uniqueitem_id = uf.uniqueitem_id
                                inner join uniqueitemfixedinfo uif on u.uniqueitem_id = uif.uniqueitem_id
                          on un.uniqueitem_id = u.uniqueitem_id
                   where  fl.code in ('REP', 'RTS2')
                   group  by u.primaryid, un.wearerinventory_id
                   having min(uf.startdate) < getABSMaxDate()) x
     on wi.wearerinventory_id = x.wearerinventory_id
     , CUSTOMERDELIVERYDAY cdd, day d
     , languages lan, systemuser curr, reportparam rp
where cu.customer_id = cdd.customer_id and cdd.day_id = d.day_id and cdd.typeofmerchadise = 2 --and cdd.deliverytype = 'B'
      and rs.stopnumber in (select min(rs2.stopnumber) from routestop rs2 where rs2.customer_id = cu.customer_id and rs2.route_id = ro.route_id)
      and rp.number_value <> 0 and rp.number_value1 <> 0
      and cu.customernumber >= rp.number_value2 and cu.customernumber <= rp.number_value3
      and ro.routenumber >= rp.number_value4 and ro.routenumber <= rp.number_value5
      and lan.code = rp.string_value
      and sa.code >= rp.string_value1 and sa.code <= rp.string_value2
      and curr.systemuser_id = rp.number_value7
      and (/*(wi.dateinactive = getABSMaxDate() and wi.circinventory + wi.freeofchargeqty > wi.maxinventory + wi.maxfreeofcharge)
          or (wi.dateinactive >= rp.date_value1 and wi.dateinactive <= rp.date_value2)
          or*/ (case --quit wearer
                   when w.dateinactive >= rp.date_value1 and w.dateinactive <= rp.date_value2 and
                        wi.dateinactive = w.dateinactive and wi.maxinventory + wi.maxfreeofcharge > 0 then 1
                   --decrease item
                   when w.dateinactive > wi.dateinactive and wi.dateinactive >= rp.date_value1 and wi.dateinactive <= rp.date_value2
                        and wi.maxinventory + wi.maxfreeofcharge > 0 then 2
                   --decrease volume(max inventory)
                   when wi.dateinactive > rp.date_value2 and wi.maxinventory + wi.maxfreeofcharge > 0 and
                        wi.circinventory + wi.freeofchargeqty > wi.maxinventory + wi.maxfreeofcharge then 3
                   --replacement
                   when wi.dateinactive >= rp.date_value1 and wi.maxinventory + wi.maxfreeofcharge = 0 then 4
                   else 0 end <> 0))
/

  CREATE OR REPLACE VIEW "V_EUDIRECTINVOICE" ("INVOICENUMBER", "PREBILLAMOUNT", "CUSTOMERNUMBER", "ROUTECONTROL_ID", "CURRENCYCODE", "INVOICEAMOUNTDECIMALS", "STOP_ID", "PAYTHISAMOUNT") AS 
  select i.invoicenumber, i.prebillamount, --c.customer_id,
c.customernumber, i.routecontrol_id, r.code currencycode, r.invoiceamountdecimals
,i.stop_id, i.paythisamount
--,i.stop_id, i.stopnumber
--, c.directinvdeliveries, c.directinvcleanweights, c.directinvsoilweights
from invoiceheader  i, customer c , currency r
where i.routecontrol_id is not null
and i.invoicefrequency_id in (0,5)
and i.deltocustomer_link_id =c.customer_id
and c.currency_id = r.currency_id
and (c.directinvdeliveries='Y' or c.directinvcleanweights ='Y' or c.directinvsoilweights='Y')
/

  CREATE OR REPLACE VIEW "V_EXCESSCHARGED" ("INVOICENUMBER", "INVOICEDATE", "BILLTODEFAULTBU", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "BILLEDQTY", "PRICE", "AMOUNT", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE") AS 
  select ih.invoicenumber,
       ih.invoicedate,
       (select bu.code from customer c,businessunit bu where c.customer_id = ih.billtocustomer_link_id and c.defaultbusinessunit_id = bu.businessunit_id) billtodefaultbu,
       (select c.customernumber from customer c where c.customer_id = ih.billtocustomer_link_id) billtocustomernumber,
       (select c.name from customer c where c.customer_id = ih.billtocustomer_link_id) billtocustomername,
       (select p.code from product p where p.product_id = ilp.product_link_id) productcode,
       (select pd.description from product_desc pd where pd.product_id = ilp.product_link_id and pd.language_id = l.language_id) productdesc,
       (select sd.code from sizedefinition sd where sd.sizedefinition_id = ilp.sizedefinition_link_id) sizecode,
       il.billedqty,
       il.price,
       il.amount,
       cr.invoiceamountdecimals,
       l.code languagecode
  from invoiceheader ih, invoiceline il, invoicelinetype ilt, invoicelineproduct ilp, languages l, currency cr
 where ih.invoiceheader_id = il.invoiceheader_id
   and il.invoicelinetype_id = ilt.invoicelinetype_id
   and ih.currency_id = cr.currency_id
   and il.invoiceline_id = ilp.invoiceline_id
   and ilt.type = 1
   and il.invoicelinesubtype = 43
/

  CREATE OR REPLACE VIEW "V_EXT_SUPLIER_PRODUCTS" ("SUPPLIERNUMBER", "SUPPLIERNAME", "PURCHASEPRICE", "CURRENCY_ID", "DELIVERYDAYS", "SUPPLIERDELDAY_ID", "MINORDERQTY", "BOXQUANTITY", "SUPPLIERPRODUCTCODE", "SUPPLIERPRODUCTDESCRIPTION", "SUPPLIERSIZECODE", "PRODUCT_ID", "SIZEDEFINITION_ID", "SUPPLIERTYPE", "SUPPLIER_ID", "SUPPLIERPRODUCT_ID", "UNIQUEITEM", "ACTIVE") AS 
  SELECT distinct
  Supplier.SupplierNumber,
  Supplier.Name,
  (select spp.purchaseprice
    from supplierproductprice spp
    where spp.supplierproduct_id = supplierproduct.supplierproduct_id
    and  spp.startdate = (select max(x.startdate)
                     from supplierproductprice x
                     where x.supplierproduct_id = supplierproduct.supplierproduct_id
                     and  x.startdate <= sysdate)) as purchaseprice,
Supplier.Currency_Id,
Supplierproduct.Deliverydays,
Supplierproduct.supplierdelday_id,
Supplierproduct.Minorderqty,
Supplierproduct.Boxquantity,
Supplierproductcode,
Supplierproductdescription,
Suppliersizecode,
Productsizepersupproduct.Product_Id,
Productsizepersupproduct.Sizedefinition_Id,
Suppliertype,
Supplier.Supplier_Id,
Supplierproduct.Supplierproduct_Id,
Supplierproduct.Uniqueitem,
SUPPLIERPRODUCT.active
FROM SUPPLIERPRODUCT , SUPPLIER , PRODUCTSIZEPERSUPPRODUCT
WHERE
 SUPPLIER.SUPPLIER_ID = SUPPLIERPRODUCT.SUPPLIER_ID
 and PRODUCTSIZEPERSUPPRODUCT.SUPPLIERPRODUCT_ID = SUPPLIERPRODUCT.SUPPLIERPRODUCT_ID
 and SUPPLIERPRODUCT.ACTIVE = 'Y'
 and SUPPLIER.SUPPLIERTYPE = 0
ORDER BY SUPPLIER.SUPPLIERNUMBER, SUPPLIERPRODUCTCODE, SUPPLIERSIZECODE
/

  CREATE OR REPLACE VIEW "V_FAILEDPROCESSES" ("LINE", "PLANT_ID", "PLANTCODE", "PLANTNAME", "CLUSTERCODE", "DESCRIPTION", "STATUS", "LASTRUN") AS 
  select 1 line, p.plant_id, p.code plantcode, p.name plantname,  apsc.code clustercode,
pr.description, pp.status, pp.lastrun
from plantprocess pp inner join plant p on pp.plant_id=p.plant_id
inner join appservercluster apsc on apsc.appservercluster_id=pp.appservercluster_id
inner join process pr on pp.process_id=pr.process_id
where pp.active='Y'
and pp.scheduleddatetime<sysdate
union all
select 0 line, p.plant_id, p.code plantcode, p.name plantname, apsc.code clustercode,
pr.description, pp.status, pp.lastrun
from plantprocess pp inner join plant p on pp.plant_id=p.plant_id
inner join appservercluster apsc on apsc.appservercluster_id=pp.appservercluster_id
inner join process pr on pp.process_id=pr.process_id
where pp.active='Y'
and pp.status>2
/

  CREATE OR REPLACE VIEW "V_FINISHINGMETHOD" ("CODE", "DESCRIPTION", "ACTIVE", "SYSTEMUSER_ID", "TIMESTAMP", "FINISHINGMETHOD_ID", "LANGUAGECODE") AS 
  SELECT FINISHINGMETHOD.CODE,
 (SELECT description FROM FINISHINGMETHOD_DESC A WHERE A.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID),
 FINISHINGMETHOD.ACTIVE, FINISHINGMETHOD.SYSTEMUSER_ID, FINISHINGMETHOD.TIMESTAMP,
 FINISHINGMETHOD.FINISHINGMETHOD_ID, LANGUAGES.CODE
FROM FINISHINGMETHOD, LANGUAGES
/

  CREATE OR REPLACE VIEW "V_FINMETHODSTICKER" ("CLIENTDELIVERYNOTELINE_ID", "CLIENTDELIVERYNOTENUMBER", "DELIVERYDATE", "ROOMNUMBER", "CLIENTNUMBER", "CLIENTNAME", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENT", "PRODUCTCODE", "PRODUCTDESC", "FINMETHCODE", "FINMETHDESC", "LANGUAGECODE") AS 
  select cdl.clientdeliverynoteline_id, cd.clientdeliverynotenumber, cd.deliverydate,
  cd.roomnumber,
  cl.clientnumber, cl.name clientname,
  cu.customernumber, cu.name customername,
  CAST((CASE
    WHEN coalesce(crs.customerclients, 1) = 0
      THEN (select CONCATENATE3(LTRIM(CASTNUMBERASVARCHARWITHFORMAT(d.departmentnumber, '999999999999')), '/', d.description)
            from clientresident cr, departmentroom dr, department d
            where cl.client_id = cr.client_id
              and cr.departmentroom_id = dr.departmentroom_id
              and dr.department_id = d.department_id)
      else (select CONCATENATE3(LTRIM(CASTNUMBERASVARCHARWITHFORMAT(d2.departmentnumber, '999999999999')), '/', d2.description)
            from clientprivateperson cp, distributionpoint dip, department d2
            where cl.client_id = cp.client_id
              and cp.distributionpoint_id = dip.distributionpoint_id
              and dip.department_id = d2.department_id)
      end) AS VARCHAR2(100)) department,
  pr.code productcode,
  (select prd.description from product_desc prd where pr.product_id = prd.product_id
     and prd.language_id = languages.language_id) productdesc,
  fm.code finmethcode,
  (select fmd.description from finishingmethod_desc fmd where fm.finishingmethod_id = fmd.finishingmethod_id
     and fmd.language_id = languages.language_id) finmethdesc,
  languages.code languagecode
from clientdeliverynote cd, client cl, clientdeliverynoteline cdl, product pr, finishingmethod fm,
  customer cu
    left outer join customerresidentialsettings crs on cu.customer_id = crs.customer_id,
  languages
where cd.clientdeliverynote_id = cdl.clientdeliverinote_id
  and cd.client_link_id = cl.client_id
  and cd.customer_link_id = cu.customer_id
  and cdl.product_link_id = pr.product_id
  and cdl.finishingmethod_id = fm.finishingmethod_id
/

  CREATE OR REPLACE VIEW "V_FIXEDQTYANALYSIS" ("CUSTOMER_ID", "PRODUCTLISTPERDISTRIBPOINT_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DELIVERYDATE", "PRODUCTCODE", "PRODUCTDESC", "REPORTPARAM_ID", "SOILQTY", "ADJUSTMENTS", "LANGUAGECODE", "DELIVERYVARIATIONS_ID") AS 
  select c.customer_id,
plpd.productlistperdistribpoint_id,
c.customernumber,
c.name customername,
dv.deliverydate,
(select p.code from product p where p.product_id = dv.product_id) productcode,
(select pd.description from product_desc pd where pd.product_id = dv.product_id and pd.language_id = l.language_id) productdesc,
rp.reportparam_id,
sum(dv.amount) soilqty,
(select sum(rqa.quantity) from rentalqtyadjustment rqa
 where rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
 and to_date(rqa.adjustmentdate,'dd-mm-yy') >= to_date(rp.date_value1,'dd-mm-yy') and to_date(rqa.adjustmentdate,'dd-mm-yy') <= to_date(rp.date_value2,'dd-mm-yy')
 and rqa.reasoncode_id = (select rc.reasoncode_id from reasoncode rc where rc.code = 'FIXED')
 ) adjustments,
l.code languagecode,
dv.deliveryvariations_id
from deliveryvariations dv, distributionpoint dp
, department d
, customer c
, productlistperdistribpoint plpd
, reportparam rp
, languages l
where dv.origin = 1
and dv.soilcountsubtype in (1, 4, 5)
and dv.distributionpoint_id = dp.distributionpoint_id
and dp.department_id = d.department_id
and d.customer_id = c.customer_id
and plpd.distributionpoint_id = dv.distributionpoint_id
and plpd.product_id = dv.product_id
and to_date(dv.deliverydate,'dd-mm-yy') >= to_date(rp.date_value1,'dd-mm-yy') and to_date(dv.deliverydate,'dd-mm-yy') <= to_date(rp.date_value2,'dd-mm-yy')
--and rp.reportparam_id = 39189 and c.customernumber = 530
group by c.customer_id, c.customernumber, c.name, dv.deliverydate, dv.product_id, l.language_id, l.code, rp.reportparam_id
, plpd.productlistperdistribpoint_id, rp.date_value1, rp.date_value2, dv.deliveryvariations_id
/

  CREATE OR REPLACE VIEW "V_FLAG" ("FLAGTYPE", "FLAGCODE", "DESCRIPTION", "PRIORITY", "COLOR", "SYSTEMUSER_ID", "TIMESTAMP", "FLAG_ID", "INCLUDEINCOMPLETNESSCHECK", "SHOWALWAYS", "LANGUAGECODE") AS 
  SELECT FLAG.FLAGTYPE, FLAG.CODE, FLAG_DESC.DESCRIPTION, FLAG.PRIORITY, FLAG.COLOR,
FLAG.SYSTEMUSER_ID, FLAG.TIMESTAMP, FLAG.FLAG_ID,flag.includeincompletnesscheck,flag.showalways, LANGUAGES.CODE
	FROM  FLAG, FLAG_DESC, LANGUAGES
	WHERE FLAG.FLAG_ID = FLAG_DESC.FLAG_ID
  AND FLAG_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID
/

  CREATE OR REPLACE VIEW "V_FLAGHISTORY" ("FLAGCODE", "WEARERNUMBER", "WEARERNAME", "PRIMARYID", "CUSTOMERNUMBER", "LANGUAGECODE", "SECONDARYID", "ASSIGNDATE", "FLAGDESCRIPTION", "PRODUCTCODE", "PRODUCTDESCRIPTION") AS 
  select f.code flagcode, we.wearernumber, we.wearername,
       s.primaryid,
       culk.customernumber, languages.code languagecode, s.secondaryid, to_date(sf.timestamp) AssignDate,
       (select flag_desc.description
           from flag_desc
          where flag_desc.flag_id = f.flag_id
            and flag_desc.language_id = languages.language_id) flagdescription,
       (select p.code from product p where p.product_id = s.product_link_id) productcode,
       (select pd.description
           from product_desc pd
          where pd.product_id = s.product_link_id
            and pd.language_id = languages.language_id) productdescription
  from scan s
  join scanflag sf on sf.scan_id = s.scan_id
  join flag f on f.flag_id = sf.flag_id
  left outer join weareremployment_link we on we.weareremployment_link_id = s.weareremployment_link_id
  left outer join customer_link culk on culk.customer_link_id = s.customer_link_id
 , languages
 where s.transactiontype_id in (75, 515)
   and f.flagtype = 1
/

  CREATE OR REPLACE VIEW "V_FLAGSORTINGSYSTEM" ("PLANTCODE", "FLAGCODE", "FLAGDESCRIPTION", "SORTADDRESS") AS 
  select distinct p.code plantcode,f.code flagcode,
(select d.description from flag_desc d where d.flag_id = f.flag_id and d.language_id = p.language_id) flagdescription,
 sa.sortaddress
from uniqueitem u,
uniqueitemflag uf, flag f, flagoptions o, businessunit b, plant p, sortaddressperflag sa
where u.uniqueitem_id = uf.uniqueitem_id
and uf.flag_id = f.flag_id
and f.flag_id= o.flag_id
and o.dialog_id in (select dialog_id from dialogs d where d.code = 'InScan' or d.code = 'CheckPointScan')
and u.businessunit_id = b.businessunit_id
and b.plant_id = p.plant_id
and sa.flag_id = f.flag_id
and sa.plant_id= p.plant_id
/

  CREATE OR REPLACE VIEW "V_FREEOFCHARGEDELIVERIES" ("DELIVERYDATE", "NOTENUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "PRODUCTCODE", "SIZECODE", "FINISHINGCODE", "REASONCODE", "PRODUCTDESC", "REASONDESC", "FREEOFCHARGEREASON_ID", "DELIVEREDAMOUNT", "LANGUAGE_ID", "CUSTOMERLANGUAGE_ID", "LANGUAGECODE", "PROCESSBUSINESSUNIT_ID", "PROCBUCODE", "PROCBUDESC", "INVOICEBUSINESSUNIT_ID", "INVBUCODE", "INVBUDESC", "INTERNALPROCESSINGBU_ID", "INTBUCODE", "INTBUDESC", "USERGROUP_ID") AS 
  select -- count(*) x
  pn.deliverydate, pn.notenumber, cu.customernumber, cu.name customerName, vad.city
, dep.departmentnumber, dep.description departmentDesc
, prd.code productCode, sz.code sizeCode, fm.code finishingCode, rc.code reasonCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = lan.language_id ) productDesc
, ( select reasoncode_desc.description from reasoncode_desc where reasoncode_desc.reasoncode_id = rc.reasoncode_id
  and reasoncode_desc.language_id = lan.language_id ) reasonDesc
, pnl.freeofchargereason_id, pnl.deliveredamount
, lan.language_id, cu.language_id customerLanguage_id, lan.code languageCode,
pn.processbusinessunit_id, procbu.code procbucode, procbu.description procbudesc,
pn.invoicebusinessunit_id, invbu.code invbucode, invbu.description invbudesc,
pn.internalprocessingbu_id,
intbu.code intbucode,
intbu.description intbudesc,
ug.usergroup_id
from packingnoteline pnl
     left outer join reasoncode rc on pnl.freeofchargereason_id = rc.reasoncode_id
      --  and rc.inventorytrigger = 5 -- it can be changed by the user in reasonCode form. Comment if problem ocour.
     inner join packingnote pn
           inner join status statusPN on pn.status_id = statusPN.status_id
                      and statusPN.statustype = 'PN' and statusPN.code = '30'
           inner join distributionpoint dip
                 inner join department dep
                       inner join customer cu
                             inner join address vad on cu.visitaddress_id = vad.address_id
                       on dep.customer_id = cu.customer_id
                 on dip.department_id = dep.department_id
            on pn.distributionpoint_id = dip.distributionpoint_id
            inner join businessunit procbu on pn.processbusinessunit_id = procbu.businessunit_id
            inner join businessunit invbu on pn.invoicebusinessunit_id = invbu.businessunit_id
            left outer join businessunit intbu on pn.internalprocessingbu_id = intbu.businessunit_id
     on pnl.packingnote_id = pn.packingnote_id
     inner join product prd on pnl.product_id = prd.product_id
     inner join sizedefinition sz on pnl.sizedefinition_id = sz.sizedefinition_id
     inner join finishingmethod fm on pnl.finishingmethod_id = fm.finishingmethod_id
, languages lan, usergroup ug
where exists (select 1 from businessunitsperusergroup bug where bug.usergroup_id = ug.usergroup_id and bug.businessunit_id = pn.processbusinessunit_id)
      and (pn.internalprocessingbu_id is null or exists (select 1 from businessunitsperusergroup bug2 where bug2.usergroup_id = ug.usergroup_id
                                and bug2.businessunit_id = pn.internalprocessingbu_id))
/

  CREATE OR REPLACE VIEW "V_FSTWORKATFACTORY" ("BUCODE", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DISTRIBUTIONPOINT_ID", "DISTRIBUTIONPOINTNUMBER", "DP_NAME", "DELIVERYDATE", "LANGUAGECODE", "PG_CODE", "DELIVERYVARIATIONS_ID", "ORIGIN", "BT_PRIMARYID", "BT_UNLOADEDDATE", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTDESC", "SIZEDEFINITION_ID", "AMOUNT", "SORTEDTIME") AS 
  select (select bu.code
          from businessunit bu
         where bu.businessunit_id = c.defaultbusinessunit_id) bucode,
       c.customer_id,
       c.customernumber,
       c.name customername,
       d.departmentnumber,
       dp.distributionpoint_id,
       dp.distributionpointnumber,
       dp.description dp_name,
       dv.deliverydate,
       l.code languagecode,
       (select pg.code
          from productgroup pg
         where pg.productgroup_id = p.productgroup_id) pg_code,
       dv.deliveryvariations_id,
       dv.origin,
       (select bt.primaryid from bagtag bt
       where bt.bagtag_id = sh.bagtag_id) bt_primaryid,
       (select bt.unloadeddate from bagtag bt
       where bt.bagtag_id = sh.bagtag_id) bt_unloadeddate,
       p.product_id,
       p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = p.product_id
           and pd.language_id = l.language_id) productdesc,
       dv.sizedefinition_id,
       dv.amount,
       dv.soilcountdate sortedtime
  from deliveryvariations dv,
       soilhistory        sh,
       product            p,
       distributionpoint  dp,
       department         d,
       customer           c,
       languages          l
 where dv.distributionpoint_id = dp.distributionpoint_id
   and d.department_id = dp.department_id
   and d.customer_id = c.customer_id
   and dv.origin = 1
   and dv.soilcountsubtype not in (2, 3)
   and dv.product_id = p.product_id
   and dv.packingnote_id is null
   and dv.amount <> 0
   and dv.scrutinystatus <> 30
           and sh.customer_link_id = c.customer_id
           and sh.product_link_id = dv.product_id
           and sh.sizedefinition_link_id = dv.sizedefinition_id
           and sh.processbusinessunit_id = c.defaultbusinessunit_id
           and sh.receivingdate = dv.soilcountdate
           and sh.distributionpoint_link_id = dv.distributionpoint_id
/

  CREATE OR REPLACE VIEW "V_GAINLOSTREASON" ("CODE", "DESCRIPTION", "GAINREASON", "LOSTREASON", "SYSTEMUSER_ID", "TIMESTAMP", "GAINLOSTREASON_ID", "LANGUAGECODE") AS 
  SELECT GAINLOSTREASON.CODE, GAINLOSTREASON_DESC.DESCRIPTION, GAINLOSTREASON.GAINREASON,
 GAINLOSTREASON.LOSTREASON, GAINLOSTREASON.SYSTEMUSER_ID, GAINLOSTREASON.TIMESTAMP, GAINLOSTREASON.GAINLOSTREASON_ID, LANGUAGES.CODE LANGUAGECODE
       FROM GAINLOSTREASON,  GAINLOSTREASON_DESC, LANGUAGES
       WHERE GAINLOSTREASON.GAINLOSTREASON_ID = GAINLOSTREASON_DESC.GAINLOSTREASON_ID
       AND GAINLOSTREASON_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID
/

  CREATE OR REPLACE VIEW "V_GARMENTANALYSIS" ("REPORTPARAM_ID", "SYSTEMUSER_ID", "DRIVINGDATE", "PLANT_CODE", "PLANT_NAME", "DEPOT_CODE", "DEPOT_DESC", "DISTRICT_CODE", "DISTRICT_DESC", "ROUTENUMBER", "ROUTE_DESC", "DRIVERNAME", "GR_ADJUSTED", "GR_AMOUNT", "ER_QUANTITY", "AR_QUANTITY", "NEW", "PERFECT", "IMAGE", "GENERAL", "UTILITY", "QUITISSUED", "QUITRETURN", "DAYS16", "DAYS713", "DAYS1420", "DAYS21") AS 
  select rp.reportparam_id, su.systemuser_id, rc.drivingdate, pl.code plant_code, pl.name plant_name,
       de.code depot_code, de.description depot_desc, di.code district_code,
       di.description district_desc, ro.routenumber, ro.description route_desc,
       (select drv.name from employee drv where ro.driver_id = drv.employee_id) drivername,
       (select sum(il1.adjustedamount)
         from   invoiceheader ih1, invoiceline il1, status st1, invoicelineproduct ilp1, product p1
         where  ih1.invoiceheader_id = il1.invoiceheader_id
         and    ih1.status_id = st1.status_id
         and    ih1.routecontrol_id = rc.routecontrol_id
         and    il1.invoiceline_id = ilp1.invoiceline_id
         and    ilp1.product_link_id = p1.product_id
         and    il1.adjustmentreason_id is not null
         and    il1.invoicelinetype_id = 1
         and    il1.extend = 'Y'
         and    st1.statustype = 'IN'
         and    st1.code = '2'
         and    ih1.route_id = ro.route_id
         and    p1.typeofmerchandise = 2) gr_adjusted,
       (select sum(il1.amount)
         from   invoiceheader ih1, invoiceline il1, status st1, invoicelineproduct ilp1, product p1
         where  ih1.invoiceheader_id = il1.invoiceheader_id
         and    ih1.status_id = st1.status_id
         and    ih1.routecontrol_id = rc.routecontrol_id
         and    il1.invoiceline_id = ilp1.invoiceline_id
         and    ilp1.product_link_id = p1.product_id
         and    il1.adjustmentreason_id is null
         and    il1.invoicelinetype_id = 1
         and    il1.extend = 'Y'
         and    st1.statustype = 'IN'
         and    st1.code = '2'
         and    ih1.route_id = ro.route_id
         and    p1.typeofmerchandise = 2) gr_amount,
       (select sum(ish1.quantity *
                     coalesce(f_purchaseprice(uifi1.supplier_id, ish1.product_link_id,
                                              ish1.sizedefinition_link_id, ish1.assigndate),
                              f_purchaseprice(prd1.supplier_id, ish1.product_link_id,
                                               ish1.sizedefinition_link_id, ish1.assigndate), 0))
         from   reasoncode rec1, businessunit bu1, issuehistory ish1
         left   outer join uniqueitemfixedinfo uifi1 on ish1.uniqueitem_link_id = uifi1.uniqueitem_id
         left   outer join product prd1 on ish1.product_link_id = prd1.product_id
         where  ish1.reasoncode_id = rec1.reasoncode_id
         and    ish1.processbusinessunit_id = bu1.businessunit_id
         and    rec1.code <> '11'
         and    bu1.plant_id = rc.plant_id
         and    rp.date_value1 <= ish1.assigndate
         and    ish1.assigndate <= rp.date_value2
         and    exists (select max(1)
                 from   stop st1
                 where  st1.routecontrol_id = rc.routecontrol_id
                 and    st1.customer_link_id = ish1.customer_link_id)
         and    (ish1.workorder_id is null or exists
                (select max(1)
                  from   workorder wok, status st2, qualitygrade qg
                  where  ish1.workorder_id = wok.workorder_id
                  and    wok.status_id = st2.status_id
                  and    st2.statustype = 'WO'
                  and    st2.code = '30'
                  and    ish1.issuegrade_id = qg.qualitygrade_id
                  and    qg.newgarment = 'N'))) er_quantity,
       (select sum(ish2.quantity *
                     coalesce(f_purchaseprice(uifi2.supplier_id, ish2.product_link_id,
                                              ish2.sizedefinition_link_id, ish2.assigndate),
                              f_purchaseprice(prd2.supplier_id, ish2.product_link_id,
                                               ish2.sizedefinition_link_id, ish2.assigndate), 0))
         from   businessunit bu2, issuehistory ish2
         left   outer join uniqueitemfixedinfo uifi2 on ish2.uniqueitem_link_id = uifi2.uniqueitem_id
         left   outer join product prd2 on ish2.product_link_id = prd2.product_id
         where  ish2.processbusinessunit_id = bu2.businessunit_id
         and    bu2.plant_id = rc.plant_id
         and    rp.date_value1 <= ish2.assigndate
         and    ish2.assigndate <= rp.date_value2
         and    exists (select max(1)
                 from   stop st2
                 where  st2.routecontrol_id = rc.routecontrol_id
                 and    st2.customer_link_id = ish2.customer_link_id)
         and    (ish2.workorder_id is null or exists
                (select max(1)
                  from   workorder wok2, status sta2, qualitygrade qg2
                  where  ish2.workorder_id = wok2.workorder_id
                  and    wok2.status_id = sta2.status_id
                  and    sta2.statustype = 'WO'
                  and    sta2.code = '30'
                  and    ish2.issuegrade_id = qg2.qualitygrade_id
                  and    qg2.newgarment = 'N'))) ar_quantity,
       coalesce((select sum(woln.quantityordered - woln.quantitycancelled)
                 from   workorder wokn, workorderline woln, qualitygrade qgn
                 where  wokn.workorder_id = woln.workorder_id
                 and    woln.requestedgrade_id = qgn.qualitygrade_id
                 and    qgn.priority = 1
                 and    wokn.route_id = rc.route_id
                 and    rp.date_value1 <= wokn.completiondate
                 and    wokn.completiondate <= rp.date_value2), 0) new,
       coalesce((select sum(wolp.quantityordered - wolp.quantitycancelled)
                 from   workorder wokp, workorderline wolp, qualitygrade qgp
                 where  wokp.workorder_id = wolp.workorder_id
                 and    wolp.requestedgrade_id = qgp.qualitygrade_id
                 and    qgp.priority = 2
                 and    wokp.route_id = rc.route_id
                 and    rp.date_value1 <= wokp.completiondate
                 and    wokp.completiondate <= rp.date_value2), 0) perfect,
       coalesce((select sum(woli.quantityordered - woli.quantitycancelled)
                 from   workorder woki, workorderline woli, qualitygrade qgi
                 where  woki.workorder_id = woli.workorder_id
                 and    woli.requestedgrade_id = qgi.qualitygrade_id
                 and    qgi.priority = 3
                 and    woki.route_id = rc.route_id
                 and    rp.date_value1 <= woki.completiondate
                 and    woki.completiondate <= rp.date_value2), 0) image,
       coalesce((select sum(wolg.quantityordered - wolg.quantitycancelled)
                 from   workorder wokg, workorderline wolg, qualitygrade qgg
                 where  wokg.workorder_id = wolg.workorder_id
                 and    wolg.requestedgrade_id = qgg.qualitygrade_id
                 and    qgg.priority = 4
                 and    wokg.route_id = rc.route_id
                 and    rp.date_value1 <= wokg.completiondate
                 and    wokg.completiondate <= rp.date_value2), 0) general,
       coalesce((select sum(wolu.quantityordered - wolu.quantitycancelled)
                 from   workorder woku, workorderline wolu, qualitygrade qgu
                 where  woku.workorder_id = wolu.workorder_id
                 and    wolu.requestedgrade_id = qgu.qualitygrade_id
                 and    qgu.priority = 5
                 and    woku.route_id = rc.route_id
                 and    rp.date_value1 <= woku.completiondate
                 and    woku.completiondate <= rp.date_value2), 0) utility,
       coalesce((select /*+index(wemp XIF683WEAREREMPLOYMENT)*/
                       sum(weinv.issuedquit) --sum(weinv.returnedqty)
                 from   wearerinventory weinv, weareremployment wemp, wearer we
                 where  weinv.weareremployment_id = wemp.weareremployment_id
                 and    wemp.wearer_id = we.wearer_id
                 and    we.customer_id in (select st5.customer_link_id
                         from   stop st5
                         where  st5.routecontrol_id = rc.routecontrol_id)
                 and    rp.date_value1 <= we.dateinactive
                 and    we.dateinactive <= rp.date_value2), 0) quitissued,
       coalesce((select /*+index(wemp2 XIF683WEAREREMPLOYMENT)*/
                        sum(weinv2.returnedqty)
                 from   wearerinventory weinv2, weareremployment wemp2, wearer we2
                 where  weinv2.weareremployment_id = wemp2.weareremployment_id
                 and    wemp2.wearer_id = we2.wearer_id
                 and    we2.customer_id in (select st6.customer_link_id
                         from   stop st6
                         where  st6.routecontrol_id = rc.routecontrol_id)
                 and    rp.date_value1 <= we2.dateinactive
                 and    we2.dateinactive <= rp.date_value2), 0) quitreturn,
       (select count(*)
         from   workorder wok16
         where  wok16.route_id = rc.route_id
         and    rp.date_value1 <= wok16.completiondate
         and    wok16.completiondate <= rp.date_value2
         and    getdatediff(wok16.completiondate, wok16.requestdate) <= 6) days16,
       (select count(*)
         from   workorder wok713
         where  wok713.route_id = rc.route_id
         and    rp.date_value1 <= wok713.completiondate
         and    wok713.completiondate <= rp.date_value2
         and    getdatediff(wok713.completiondate, wok713.requestdate) >= 7
         and    getdatediff(wok713.completiondate, wok713.requestdate) <= 13) days713,
       (select count(*)
         from   workorder wok1420
         where  wok1420.route_id = rc.route_id
         and    rp.date_value1 <= wok1420.completiondate
         and    wok1420.completiondate <= rp.date_value2
         and    getdatediff(wok1420.completiondate, wok1420.requestdate) >= 14
         and    getdatediff(wok1420.completiondate, wok1420.requestdate) <= 20) days1420,
       (select count(*)
         from   workorder wok21
         where  wok21.route_id = rc.route_id
         and    rp.date_value1 <= wok21.completiondate
         and    wok21.completiondate <= rp.date_value2
         and    getdatediff(wok21.completiondate, wok21.requestdate) >= 21) days21
from   routecontrol rc, plant pl, systemuser su, route ro
left   outer join depot de on ro.depot_id = de.depot_id
left   outer join district di on ro.district_id = di.district_id, reportparam rp
where  rc.plant_id = pl.plant_id --AND pl.plant_id = de.plant_id
and    rc.route_id = ro.route_id
and    su.systemuser_id = rp.systemuser_id
and    rp.date_value1 <= rc.drivingdate
and    rc.drivingdate <= rp.date_value2
and    rp.string_value1 <= pl.code
and    pl.code <= rp.string_value2
and    ((rp.string_value3 = ' ' and rp.string_value4 = 'ZZZZZZZZZZZZ') or
      (rp.string_value3 <= de.code and de.code <= rp.string_value4))
and    ((rp.string_value5 = ' ' and rp.string_value6 = 'ZZZZZZ') or
      (rp.string_value5 <= di.code and di.code <= rp.string_value6))
and    ro.routenumber between rp.number_value1 and rp.number_value2
and    ro.plant_id = pl.plant_id
and    exists (select 1
        from   businessunit bu, businessunitsperusergroup bug
        where  pl.plant_id = bu.plant_id
        and    bug.businessunit_id = bu.businessunit_id
        and    bug.usergroup_id = su.usergroup_id)
/

  CREATE OR REPLACE VIEW "V_GARMENTASSORTMENT" ("BILLNUMBER", "BILLNAME", "BILLSTREET", "BILLZIPCODE", "BILLCITY", "BILLPHONENO", "DELNUMBER", "DELNAME", "FUNCTIONCODE", "FUNCTIONDESCRIPTION", "PRODUCTCODE", "PRODUCTDESCRIPTION", "WEAREREMPLOYMENT", "WEARERDATEACTIVE", "WEARERDATEINACTIVE", "MAXINVENTORY", "PRICEDECIMALSBILL", "AMOUNTDECIMALSBILL", "CURRENCYCODEBILL", "PRICEDECIMALSDELL", "AMOUNTDECIMALSDELL", "CURRENCYCODEDELL", "LANGUAGECODE", "STANDARDINVENTORY_ID", "WEARERFUNCTION_ID", "PRODUCT_ID") AS 
  select
  bill.customernumber billNumber, bill.name billName, address.street billstreet, address.zipcode billzipcode
, address.city billcity, bill.phoneno billphoneno, del.customernumber delNumber, del.name delName
, wef.code FunctionCode, wef.description functionDescription, prd.code ProductCode
, (select description from product_desc where prd.product_id = product_desc.product_id
  and product_desc.language_id = languages.language_id) ProductDescription, wei.weareremployment_id weareremployment
, we.dateactive WearerDateActive, we.dateinactive WearerDateInActive, sty.putinuse MaxInventory
, currency.decimals PriceDecimalsBill
, currency.invoiceamountdecimals AmountDecimalsBill, currency.code currencyCodeBill
, c.decimals PriceDecimalsDell, c.invoiceamountdecimals AmountDecimalsDell
, c.code currencyCodeDell, languages.code languageCode,
sty.standardinventory_id, wef.wearerfunction_id, sty.product_id
from
  customer bill, customer del, address
, wearerfunction wef, standardinventory sty, product prd
, wearer we, weareremployment wei, currency, currency c
, languages
where
    del.garmentrentspecification = 6
and del.customer_id = wef.customer_id
and wef.wearerfunction_id = sty.wearerfunction_id
and sty.product_id = prd.product_id
and del.customer_id = we.customer_id
and we.wearer_id = wei.wearer_id
and wei.wearerfunction_id = wef.wearerfunction_id
and bill.customer_id = del.debtor_id
and address.address_id = bill.mailaddress_id
and currency.currency_id = bill.currency_id
and c.currency_id = del.currency_id
/

  CREATE OR REPLACE VIEW "V_GARMENTDELIVERY" ("DELIVERYDATE", "WEEK", "ROUTEDESC", "STOPNUMBER", "WEARERNAME", "CUSTOMER_ID", "CUSTOMERNUMBER", "TYPEOFMERCHANDISE", "CUSTOMERNAME", "CUSTOMERLEGALNAME", "PRODUCTCODE", "SIZECODE", "STREET", "ZIPCODE", "CITY", "BUSINESSUNIT_ID", "UNIQUEITEM_LINK_ID", "NOTENUMBER", "PLANTDEPARTMENTCODE", "CUPBOARD", "LOCKER", "LOCKER_REMARK", "LOCKER_SORTADDRESS", "LANGUAGECODE", "LOCKERSTATUS", "ROUTENUMBER", "WEARERNUMBER", "DAYDESC", "PRIMARYID", "PRODUCTDESC", "SIZEDESC", "SCANTIMESTAMP") AS 
  select /*version 2.0*/
       pn.deliverydate, pn.week week, ro.description routedesc, pn.stopnumber, weylk.wearername, cu.customer_id, cu.customernumber, prd.typeofmerchandise,
       cu.name customername, cu.legalname customerlegalname, prd.code productcode, sz.code sizecode, ads.street, ads.zipcode, ads.city,
       ds.businessunit_id, ds.uniqueitem_link_id, pn.notenumber, pld.code plantdepartmentcode, lck.bank cupboard, lck.locker,
       lck.remark locker_remark, lck.sortaddress locker_sortaddress, lan.code languagecode, lck.lockerstatus,
       coalesce(ro.routenumber, -1) routenumber,
       coalesce(weylk.wearernumber, -1) wearernumber,
       (select day_desc.description
          from day_desc
         where day_desc.day_id = pn.daynumber
           and day_desc.language_id = lan.language_id) daydesc,
       coalesce((select ragi.primaryid
                   from raggeditem ragi
                  where uqlk.raggeditem_id = ragi.raggeditem_id)
               ,(select uq.primaryid
                   from uniqueitem uq
                  where uqlk.uniqueitem_id = uq.uniqueitem_id)
               ,'') primaryid,
       (select product_desc.description
          from product_desc
         where product_desc.product_id = prd.product_id
           and product_desc.language_id = lan.language_id) productdesc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sz.sizedefinition_id
           and sdd.language_id = lan.language_id ) sizedesc,
       trunc((select max(deliveryscan.scantimestamp)
                from deliveryscan
               where deliveryscan.businessunit_id = ds.businessunit_id
                 and deliveryscan.uniqueitem_link_id = ds.uniqueitem_link_id
                 and trunc(deliveryscan.scantimestamp) <= pn.deliverydate)) scantimestamp
  from deliveryscan ds
       left join weareremployment_link weylk
                 left join weareremployment we
                           left join locker lck on we.locker_id = lck.locker_id
                 on weylk.weareremployment_id = we.weareremployment_id
       on ds.weareremployment_link_id = weylk.weareremployment_link_id
       join packingnote pn
            left join route ro on pn.route_id = ro.route_id and ro.active = 'Y'
            join status st on pn.status_id = st.status_id and st.statustype = 'PN' and st.code = '30'
            join distributionpoint dip
                 join department dep
                      join customer cu
                           join address ads on cu.visitaddress_id = ads.address_id
                           join languages lan on cu.language_id = lan.language_id
                      on dep.customer_id = cu.customer_id
                 on dip.department_id = dep.department_id
            on pn.distributionpoint_id = dip.distributionpoint_id
       on ds.packingnote_id = pn.packingnote_id
       join uniqueitem_link uqlk on ds.uniqueitem_link_id = uqlk.uniqueitem_link_id
       join product prd on ds.product_link_id = prd.product_id
       join sizedefinition sz on ds.sizedefinition_link_id = sz.sizedefinition_id
       join plantdepartment pld on ds.plantdepartment_id = pld.plantdepartment_id
/

  CREATE OR REPLACE VIEW "V_GARMENTDISPENSER" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CODE", "DESCRIPTION", "DELIVERYPOINTCODE", "DELIVERYPOINTDESCRIPTION", "DISPENSERNUMBER", "SORTADDRESS1", "SORTADDRESS2", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, GARMENTDISPENSER.CODE, GARMENTDISPENSER.DESCRIPTION,
 DELIVERYPOINT.CODE, DELIVERYPOINT.DESCRIPTION, GARMENTDISPENSER.DISPENSERNUMBER,
 GARMENTDISPENSER.SORTADDRESS1, GARMENTDISPENSER.SORTADDRESS2, GARMENTDISPENSER.SYSTEMUSER_ID, GARMENTDISPENSER.TIMESTAMP
	FROM  GARMENTDISPENSER, CUSTOMER, DELIVERYPOINT
	WHERE GARMENTDISPENSER.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND GARMENTDISPENSER.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
/

  CREATE OR REPLACE VIEW "V_GARMENTEXCHANGEFREQUENCY" ("CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "STREET", "CITY", "STATE", "ZIPCODE", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "COSTCENTERCODE", "COSTCENTERDESC", "WEARERNUMBER", "WEARERNAME", "CHANGESPERWEEK", "WEARERACTIVESTATUS", "SCANTIMESTAMP", "FUNCTIONCODE", "FUNCTIONDESC", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "TRANSACTIONTYPEID", "SCANYEAR", "SCANWEEK", "SCANYEARWEEK", "PRIMARYID", "UNIQUEITEMLINKID", "LANGUAGECODE", "SCAN_ID", "CIRCINVENTORY") AS 
  select -- this wearers are NOT deleted from wearer table (not exists only via weareremployment_link)
  cu.customer_id, cu.customernumber, cu.name CustomerName
, cast(CONCATENATEWITHBLANK((select a.street from address a where cu.visitaddress_id = a.address_id)
, (select a.street2 from address a where cu.visitaddress_id = a.address_id) ) as varchar2(255)) street--, address.city, ADDRESS.STATE, address.zipcode
,(select a.city from address a where cu.visitaddress_id = a.address_id) city
,(select a.STATE from address a where cu.visitaddress_id = a.address_id) STATE
,(select a.zipcode from address a where cu.visitaddress_id = a.address_id) zipcode
, de.departmentnumber, de.description departmentDesc
, coc.code costcenterCode, coc.description costcenterDesc
, we.wearernumber, we.fullname wearername, wei.changesperweek
, coalesce((select 'Y' from scan s where s.scan_id = scan.scan_id
                   and trunc(scan.scantimestamp) >= we.dateactive
                   and trunc(scan.scantimestamp)<= we.dateinactive),'N') WearerActiveStatus
, scan.scantimestamp  --, trunc(scan.scantimestamp) scantimestamp, trunc(we.dateactive), trunc(we.dateinactive), scan.scan_id
, wef.code FunctionCode, wef.description FunctionDesc
, coalesce(prd.code , prdlk.code)ProductCode
, coalesce((select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id)
  , (select product_link_desc.description from product_link_desc where product_link_desc.product_link_id = prdlk.product_link_id
     and product_link_desc.language_id = languages.language_id))
     ProductDesc
, coalesce(sz.code, szlk.code) SizeCode, scan.transactiontype_id transactiontypeID
, scan.year scanYear, scan.week scanWeek, (scan.year*100 + scan.week) ScanYearWeek
, scan.primaryid , scan.uniqueitem_link_id uniqueitemLinkID, languages.code LanguageCode
, scan.scan_id,wei.circinventory
from
  scan, customer cu, wearer we, wearerinventory wei, distributionpoint di, department de, costcenter coc
, weareremployment wey
    left outer join wearerfunction wef on wey.wearerfunction_id = wef.wearerfunction_id
, product_link prdlk left outer join product prd
                          on prdlk.product_id = prd.product_id
, sizedefinition_link szlk left outer join sizedefinition sz
                                on szlk.sizedefinition_id = sz.sizedefinition_id
--, address
, languages
where
    scan.transactiontype_id in (1,2)
and scan.customer_link_id = cu.customer_id
    --and cu.visitaddress_id = address.address_id
and scan.weareremployment_link_id = wey.weareremployment_id
    and wey.wearer_id = we.wearer_id
        and we.customer_id = cu.customer_id --
and scan.weareremployment_link_id = wei.weareremployment_id
    and scan.product_link_id = wei.product_id
        and scan.sizedefinition_link_id = wei.sizedefinition_id
and scan.distributionpoint_link_id = di.distributionpoint_id
    and di.costcenter_id = coc.costcenter_id --
    and di.department_id = de.department_id
        and de.customer_id = cu.customer_id
            and coc.customer_id = cu.customer_id  --
and scan.product_link_id = prdlk.product_link_id
and scan.sizedefinition_link_id = szlk.sizedefinition_link_id
    -- and prd.product_id = productsize.product_id
        -- and prdsz.sizedefinition_id = productsize.sizedefinition_id
UNION ALL
select  -- this wearers ARE deleted from wearer table (exists only via weareremployment_link)
  culk.customer_id, culk.customernumber, culk.name CustomerName, '' street, '' city, '' STATE,'' zipcode
, delk.departmentnumber, delk.description  departmentDesc
, colk.code costcenterCode, colk.description costcenterDesc
, welk.wearernumber, welk.wearername, wei.changesperweek
, 'N' WearerActiveStatus -- ! --
, scan.scantimestamp --, trunc(scan.scantimestamp) scantimestamp
, wef.code FunctionCode, wef.description FunctionDesc
, coalesce(prd.code , prdlk.code)ProductCode
, coalesce((select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id)
  , (select product_link_desc.description from product_link_desc where product_link_desc.product_link_id = prdlk.product_link_id
     and product_link_desc.language_id = languages.language_id))
     ProductDesc
, coalesce(sz.code, szlk.code) SizeCode, scan.transactiontype_id transactiontypeID
, scan.year ScanYear, scan.week ScanWeek, (scan.year*100 + scan.week) ScanYearWeek
, scan.primaryid, scan.uniqueitem_link_id uniqueitemLinkID, languages.code LanguageCode, scan.scan_id,wei.circinventory
from
  scan
, customer_link culk, wearerinventory wei, distributionpoint_link dilk, department_link delk, costcenter_link colk
, weareremployment_link welk
    left outer join (weareremployment wey left outer join wearerfunction wef
                                               on wey.wearerfunction_id = wef.wearerfunction_id)
         on welk.weareremployment_id = wey.weareremployment_id
, product_link prdlk left outer join product prd
                          on prdlk.product_id = prd.product_id
, sizedefinition_link szlk left outer join sizedefinition sz
                                on szlk.sizedefinition_id = sz.sizedefinition_id
, languages
where
    scan.transactiontype_id in (1,2)
and scan.customer_link_id = culk.customer_link_id
    and culk.customer_id is null  -- ! --
        and culk.customer_link_id = colk.customer_link_id
and scan.weareremployment_link_id = welk.weareremployment_link_id
    and welk.weareremployment_id is null --! --
and scan.distributionpoint_link_id = dilk.distributionpoint_link_id
    and dilk.distributionpoint_link_id is null -- ! --
        and welk.distributionpoint_link_id = dilk.distributionpoint_link_id
            and dilk.department_link_id = delk.department_link_id
and scan.product_link_id = prdlk.product_link_id
and scan.sizedefinition_link_id = szlk.sizedefinition_link_id
and wey.weareremployment_id = wei.weareremployment_id
    and prd.product_id = wei.product_id
        and sz.sizedefinition_id = wei.sizedefinition_id
/

  CREATE OR REPLACE VIEW "V_GARMENTHISTORY" ("YEAR", "WEEK", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "WEARERNUMBER", "WEARERNAME", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "QUANTITY", "SALESPRICE", "INVOICEHEADER_ID", "LANGUAGECODE", "LANGUAGE_ID", "DISCOUNTPERCENTAGE", "AMOUNT", "CUSTOMERREF") AS 
  select
 a.year, a.week,
 e.departmentnumber, e.description departmentdesc,
 w.wearernumber, w.wearername,
 p.code productcode,
 (select description from product_link_desc z where z.product_link_id = a.product_link_id
  and z.language_id = languages.language_id) productdesc,
 r.code sizecode, a.quantity, coalesce(a.salesprice, 0) salesprice, a.invoiceheader_id,
 languages.code languagecode, languages.language_id language_id,
 a.DiscountPercentage, a.amount,
 (select wo.referencenumber from workorder wo join workorderline wol on wo.workorder_id=wol.workorder_id where wol.workorderline_id=a.workorderline_id) customerref
from garmentsaleshistory a
 left outer join weareremployment_link w on (a.weareremployment_link_id = w.weareremployment_link_id),
 distributionpoint_link d, department_link e, product_link p,  sizedefinition_link r, languages
where a.distributionpoint_link_id = d.distributionpoint_link_id
 and d.department_link_id = e.department_link_id
 and a.product_link_id = p.product_link_id
 and a.sizedefinition_link_id = r.sizedefinition_link_id
 and a.status = 0 -- todo 3876
 and a.amount <> 0 --todo 23122
/

  CREATE OR REPLACE VIEW "V_GARMENTSALESDISCOUNT" ("WEARERNUMBER", "WEARERNAME", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "QUANTITY", "SALESPRICE", "INVOICEHEADER_ID", "LANGUAGECODE", "DISCOUNTPERCENTAGE", "AMOUNT", "CUSTOMERNUMBER", "CUSTOMERNAME", "REFERENCENUMBER", "INVOICENUMBER") AS 
  SELECT W.WEARERNUMBER, W.WEARERNAME,
 P.CODE PRODUCTCODE,
 (SELECT DESCRIPTION FROM PRODUCT_LINK_DESC Z WHERE Z.PRODUCT_LINK_ID = A.PRODUCT_LINK_ID
  AND Z.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESC,
 R.CODE SIZECODE, A.QUANTITY, COALESCE(A.SALESPRICE, 0) SALESPRICE, A.INVOICEHEADER_ID,
 LANGUAGES.CODE LANGUAGECODE,
 A.DISCOUNTPERCENTAGE, --A.AMOUNT,
 (A.QUANTITY * COALESCE(A.SALESPRICE, 0) * (100 - COALESCE(A.DISCOUNTPERCENTAGE, 0))/100) AMOUNT, --TODO6716
 CL.CUSTOMERNUMBER, CL.NAME CUSTOMERNAME,
 (SELECT MAX(WOK.REFERENCENUMBER) FROM WORKORDERLINE WOKL, WORKORDER WOK WHERE WOKL.WORKORDER_ID = WOK.WORKORDER_ID AND A.WORKORDERLINE_ID = WOKL.WORKORDERLINE_ID) REFERENCENUMBER,
 (SELECT MAX(IH.INVOICENUMBER) FROM INVOICEHEADER IH WHERE A.INVOICEHEADER_ID = IH.INVOICEHEADER_ID) INVOICENUMBER
FROM GARMENTSALESHISTORY A
 LEFT OUTER JOIN WEAREREMPLOYMENT_LINK W ON (A.WEAREREMPLOYMENT_LINK_ID = W.WEAREREMPLOYMENT_LINK_ID)
 LEFT OUTER JOIN CUSTOMER_LINK CL ON (A.CUSTOMER_LINK_ID = CL.CUSTOMER_LINK_ID),
 PRODUCT_LINK P,  SIZEDEFINITION_LINK R, LANGUAGES
WHERE A.PRODUCT_LINK_ID = P.PRODUCT_LINK_ID
 AND A.SIZEDEFINITION_LINK_ID = R.SIZEDEFINITION_LINK_ID
 AND A.STATUS = 0 -- TODO 3876
 --AND A.DISCOUNTPERCENTAGE > 0 --TAKEN OFF FOR TODO 6675
 AND A.WORKORDERLINE_ID IS NOT NULL
/

  CREATE OR REPLACE VIEW "V_GARMENTSHIPPING" ("CUSTOMERNUMBER", "CUSTOMERNAME", "STREET", "STREET2", "CITY", "STATE", "ZIPCODE", "PLANTNAME", "PLANTCODE", "PLANTPHONE", "PLANTFAX", "PLANTSTREET", "PLANTSTREET2", "PLANTCITY", "PLANTSTATE", "PLANTZIPCODE", "DEPOTCODE", "ROUTENUMBER", "STOPNUMBER", "SEQUENCENUMBER", "WEARERNUMBER", "CUSTOMEREMPLOYEENUMBER", "SEARCHNAME", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "CIRCINVENTORY", "DELIVERIES", "DEPARTMENTDESC", "BANK", "LOCKER", "EMBLEMNAME", "FUNCTIONCODE", "REPAIRS", "BUSINESSUNIT_ID", "DATEACTIVE_CUST", "DATEINACTIVE_CUST", "DRIVINGDAY_ID", "DATEACTIVE_WEARER", "DATEINACTIVE_WEARER", "DATEACTIVE_WINV", "DATEINACTIVE_WINV", "LOCKERMANAGEMENT", "REPORTPARAM_ID", "LANGUAGECODE") AS 
  select --WI.WEARERINVENTORY_ID,
-- header
  cu.customernumber, cu.name customername,
  ad.street, ad.street2, ad.city, ad.state, ad.zipcode,
  pl.name plantname, pl.code plantcode,
  pl.phoneno plantphone, pl.faxno plantfax,
  adp.street plantstreet, ADP.STREET2 plantstreet2,
  adp.city plantcity, adp.state plantstate, adp.zipcode plantzipcode,
  de.code depotcode,
  r.routenumber, rs.stopnumber,
  we.sequencenumber,
-- details
  w.wearernumber, w.customeremployeenumber, w.searchname,
  pr.code productcode,
  (select prd.description from product_desc prd where prd.product_id = pr.product_id
     and prd.language_id = languages.language_id) productdesc,
  sz.code sizecode,
  wi.circinventory,
  F_GETDELIVERIESNO(wi.wearerinventory_id, bu.businessunit_id, r.route_id, rs.stopnumber, rp.reportparam_id) deliveries,
  dp.description departmentdesc,
  lk.bank, lk.locker,
  w.emblemname,
  wf.code functioncode,
  F_GETREPAIRSNO(wi.wearerinventory_id, bu.businessunit_id, r.route_id, rs.stopnumber, rp.reportparam_id) repairs,
-- filter
  bu.businessunit_id,
  cu.dateactive dateactive_cust, cu.dateinactive dateinactive_cust,
  r.drivingday_id,
  w.dateactive dateactive_wearer, w.dateinactive dateinactive_wearer,
  wi.dateactive dateactive_winv, wi.dateinactive dateinactive_winv,
  cu.lockermanagement,
  rp.reportparam_id,
  languages.code languagecode
from customer cu, address ad, businessunit bu, plant pl, address adp,
  wearer w, wearerinventory wi,
  weareremployment we
    left outer join wearerfunction wf on we.wearerfunction_id = wf.wearerfunction_id
    left outer join locker lk on we.locker_id = lk.locker_id,
  distributionpoint dip, department dp,
  routestop rs,
  route r
    left outer join depot de on r.depot_id = de.depot_id,
  product pr, sizedefinition sz,
  reportparam rp, languages
where cu.customer_id = w.customer_id
  and w.wearer_id = we.wearer_id
  and we.weareremployment_id = wi.weareremployment_id
  and we.distributionpoint_id = dip.distributionpoint_id
  and dip.department_id = dp.department_id
  and rs.customer_id = cu.customer_id
  and rs.route_id = r.route_id
  and wi.product_id = pr.product_id
  and wi.sizedefinition_id = sz.sizedefinition_id
  and cu.visitaddress_id = ad.address_id
  and cu.defaultbusinessunit_id = bu.businessunit_id
  and bu.plant_id = pl.plant_id
  and pl.address_id = adp.address_id
  and r.active = 'Y'
/

  CREATE OR REPLACE VIEW "V_GARMENTSINCIRCPERCUSTOMER" ("BILLNUMBER", "BILLNAME", "BILLSTREET", "BILLZIP", "BILLCITY", "DELNUMBER", "DELNAME", "DELSTREET", "DELZIP", "DELCITY", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "PRODUCTCODE", "SIZECODE", "FINMETHCODE", "PRODUCTDESC", "SIZEDESC", "FINMETHDESC", "FABRICDESC", "CUSTOMEROWNED", "STATUSCODE", "LANGUAGECODE") AS 
  select -- count(*) t -- ui : 10515, uinp : 4900
  billto.customernumber billNumber, billto.name billName, ads_bil.street billStreet, ads_bil.zipcode billZip, ads_bil.city billCity
, delto.customernumber delNumber, delto.name delName, ads_del.street delStreet, ads_del.zipcode delZip, ads_del.city delCity
, de.departmentnumber, de.description departmentDesc
, prd.code productCode, sz.code sizeCode, fm.code finmethCode--, fabric.code fabricCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sz.sizedefinition_id
  and sdd.language_id = languages.language_id ) sizeDesc
, ( select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
  and fmd.language_id = languages.language_id ) finmethDesc
, ( select fabric_desc.description from fabric_desc where fabric_desc.fabric_id = prd.fabric_id
  and fabric_desc.language_id = languages.language_id ) fabricDesc
, ui.customerowned, st.code statusCode
, languages.code languageCode
from
  uniqueitem ui
    left outer join finishingmethod fm on ui.finishingmethod_id = fm.finishingmethod_id
, status st, uniqueitemnonpool uinp
, weareremployment wey, distributionpoint dip, department de, customer delto, customer billto
, product prd, sizedefinition sz--, fabric
, address ads_del, address ads_bil
, languages
where
    ui.poolitem = 2 -- non pool, garment
and ui.status_id = st.status_id
    and st.statustype = 'UI'
and ui.uniqueitem_id = uinp.uniqueitem_id
and uinp.weareremployment_id = wey.weareremployment_id
    and wey.distributionpoint_id = dip.distributionpoint_id
        and dip.department_id = de.department_id
            and de.customer_id = delto.customer_id
                and delto.debtor_id = billto.customer_id
and ui.product_id = prd.product_id--and prd.fabric_id = fabric.fabric_id
and ui.sizedefinition_id = sz.sizedefinition_id
and delto.visitaddress_id = ads_del.address_id
and billto.visitaddress_id = ads_bil.address_id
/

  CREATE OR REPLACE VIEW "V_GARMENTSPERSIGNAL" ("LINETYPE", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMERCYTY", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "FLAGCODE", "FLAGDESCRIPTION", "WEARERNUMBER", "WEARERFULLNAME", "WEARERFUNCTION", "EMPLOYMENTNUMBER", "IDCODE", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "FINISHINGMETHODCODE", "SIZEDESCRIPTION", "FINISHINGMETHODDESCRIPTION", "LASTISSUEDATE", "LASTSCANDATE", "STARTFLAG", "FREETEXTITEM", "COUNTFLAGS", "BUSINESSUNIT_ID", "TIMESTAMP", "DATEPUTFLAG", "LANGUAGECODE", "SYSTEM_USER", "LOCKER", "BANK") AS 
  select 1 linetype, cu.customer_id, cu.customernumber, cu.name customername, adr.city customercyty,
       dep.departmentnumber, dep.description departmentdescription, fg.code flagcode,
       (select fgd.description
          from flag_desc fgd
         where fgd.flag_id = fg.flag_id
           and fgd.language_id = lan.language_id) flagdescription, w.wearernumber, w.fullname wearerfullname,
       wf.code wearerfunction, we.sequencenumber employmentnumber, uq.primaryid idcode, pr.code productcode,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdescription,
       sd.code sizedefinitioncode, fm.code finishingmethodcode,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedescription,
       (select fmd.description
          from finishingmethod_desc fmd
         where fmd.finishingmethod_id = fm.finishingmethod_id
           and fmd.language_id = lan.language_id) finishingmethoddescription,
       coalesce(uqfi.lastissuedate, getabsmaxdate()) lastissuedate,
       coalesce(uq.lastscandate, getabsmaxdate()) lastscandate,
       coalesce(uif.startdate, getabsmaxdate()) startflag, uif.freetextitem,
       (select count(uf.flag_id) from uniqueitemflag uf where uf.uniqueitem_id = uq.uniqueitem_id) countflags, uq.businessunit_id, uq.timestamp,
       coalesce(trunc(uif.timestamp), getabsmaxdate()) dateputflag, lan.code languagecode,
       (select su.username from systemuser su where su.systemuser_id = uq.systemuser_id) system_user, lk.locker, lk.bank
  from uniqueitemnonpool uinp
  join uniqueitem uq
       left join finishingmethod fm on uq.finishingmethod_id = fm.finishingmethod_id
       join product pr on uq.product_id = pr.product_id
       join sizedefinition sd on uq.sizedefinition_id = sd.sizedefinition_id
       join uniqueitemfixedinfo uqfi on uq.uniqueitem_id = uqfi.uniqueitem_id
       join uniqueitemflag uif
            join flag fg on uif.flag_id = fg.flag_id
       on uq.uniqueitem_id = uif.uniqueitem_id
  on uinp.uniqueitem_id = uq.uniqueitem_id
  join weareremployment we
       left join wearerfunction wf on we.wearerfunction_id = wf.wearerfunction_id
       left join locker lk on we.locker_id = lk.locker_id
       join distributionpoint dip on we.distributionpoint_id = dip.distributionpoint_id
       join department dep on dip.department_id = dep.department_id
       join customer cu on dep.customer_id = cu.customer_id
       join address adr on cu.visitaddress_id = adr.address_id
       join wearer w on we.wearer_id = w.wearer_id
  on uinp.weareremployment_id = we.weareremployment_id
  , languages lan
 where w.customer_id = cu.customer_id
 union all-- Pool Items
select 2 linetype,
       (select max(cu.customer_id) from customer cu) customer_id,
       0 customernumber, null customername, null customercyty,
       0 departmentnumber, null departmentdescription, fg.code flagcode,
       (select fgd.description
          from flag_desc fgd
         where fgd.flag_id = fg.flag_id
           and fgd.language_id = lan.language_id) flagdescription, 0 wearernumber, null wearerfullname,
       null wearerfunction, 0 employmentnumber, uq.primaryid idcode, pr.code productcode,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdescription,
       sd.code sizedefinitioncode, fm.code finishingmethodcode,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedescription,
       (select fmd.description
          from finishingmethod_desc fmd
         where fmd.finishingmethod_id = fm.finishingmethod_id
           and fmd.language_id = lan.language_id) finishingmethoddescription,
       coalesce(uqfi.lastissuedate, getabsmaxdate()) lastissuedate,
       coalesce(uq.lastscandate, getabsmaxdate()) lastscandate,
       coalesce(uif.startdate, getabsmaxdate()) startflag, uif.freetextitem,
       (select count(uf.flag_id) from uniqueitemflag uf where uf.uniqueitem_id = uq.uniqueitem_id) countflags, uq.businessunit_id, uq.timestamp,
       coalesce(trunc(uif.timestamp), getabsmaxdate()) dateputflag, lan.code languagecode,
       (select su.username from systemuser su where su.systemuser_id = uq.systemuser_id) system_user, null locker, null bank
  from uniqueitem uq
  left join finishingmethod fm on uq.finishingmethod_id = fm.finishingmethod_id
  join product pr on uq.product_id = pr.product_id
  join sizedefinition sd on uq.sizedefinition_id = sd.sizedefinition_id
  join uniqueitemfixedinfo uqfi on uq.uniqueitem_id = uqfi.uniqueitem_id
  join uniqueitemflag uif
       join flag fg on uif.flag_id = fg.flag_id
  on uq.uniqueitem_id = uif.uniqueitem_id
  , languages lan
 where uq.poolitem = 1 -- pool
/

  CREATE OR REPLACE VIEW "V_GARMENTSPERSTAY" ("CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "WEARERFULLNAME", "DUMMYFORPOOL", "PERSONALIZEDGARMENT", "PRODUCTCODE", "SIZECODE", "FINISHINGCODE", "PRODUCTDESC", "GARMENTDISPENSERCODE", "GARMENTDISPENSERDESC", "PRIMARYID", "STAYNR", "FACTORYDESCRIPTION", "STAYCHANGEDATE", "LANGUAGECODE") AS 
  select
  cu.customernumber, cu.name CustomerName, we.wearernumber, we.fullname WearerFullName
, we.dummyforpool, winv.personalizedgarment, prd.code ProductCode, sz.code SizeCode, fm.code FinishingCode
, (select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) ProductDesc
, gadi.code GarmentdispenserCode, gadi.description GarmentdispenserDesc, uq.primaryid
, stay.staynr, stay.factorydescription, trunc(uq.staychangedate) StayChangeDate
, languages.code languageCode
from
  customer cu, wearer we, weareremployment wey, garmentdispenser gadi
, wearerinventory winv, product prd, sizedefinition sz, finishingmethod fm
, uniqueitemnonpool uqnp, uniqueitem uq, stay
, languages
where
    cu.customer_id = we.customer_id
and we.wearer_id = wey.wearer_id
and wey.weareremployment_id = winv.weareremployment_id
    and winv.product_id = prd.product_id
        and prd.typeofmerchandise = 2  -- garments
            and winv.sizedefinition_id = sz.sizedefinition_id
                and winv.finishingmethod_id = fm.finishingmethod_id
and wey.garmentdispenser_id = gadi.garmentdispenser_id
and wey.weareremployment_id = uqnp.weareremployment_id
and winv.wearerinventory_id = uqnp.wearerinventory_id
    and uqnp.uniqueitem_id = uq.uniqueitem_id
and prd.product_id = uq.product_id
    and sz.sizedefinition_id = uq.sizedefinition_id
        and fm.finishingmethod_id = uq.finishingmethod_id
            -- and cu.customer_id = uq.relatedcustomer_id
and uq.stay_id = stay.stay_id
and stay.staynr in (20,21,22,23,24,25,30,31,32,33,34,35,36)
/

  CREATE OR REPLACE VIEW "V_GARMENTSPERWEARER" ("LINETYPE", "PRODUCTCODE", "SIZECODE", "PRODUCTDESC", "SIZEDESC", "FUNCTIONCODE", "FUNCTIONDESC", "EMPLOYMENT", "BANKLOCKER", "GARMENTDISPENSER", "IDCODE", "SEQNUMBER", "ISSUEDATE", "WASHNO", "REPAIRNO", "REWASHNO", "FLAG", "UIFLAGCODE", "MODIFICATIONS", "REASON", "CUSTOMEROWNED", "FREEEXTRAGARMENT", "LASTSCANDATE", "LASTOUTSCANDATE", "LASTINSCAN", "FINMETHOD", "FINMETHODDESC", "INVOICEAMOUNTDECIMALS", "RESIDUALVALUE", "FLAGCODE", "STAY", "STAYNR", "STATUS", "ADMINNUMBER", "COSTCENTERCODE", "COSTCENTERDESC", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "PROCESSBUSINESSUNIT_ID", "INTPROCESSBUSINESSUNIT_ID", "CITY", "DEFAULTBUSINESSUNIT_ID", "WEARERNUMBER", "WEARERNAME", "WEARERSEARCHNAME", "WEARERFIRSTNAME", "WEARERACTIVE", "WEARERDATEACTIVE", "WEARERDATEINACTIVE", "LANGUAGECODE", "LANGUAGE_ID", "CUSTOMERLANGUAGE_ID", "SUBSTITUTEYN", "QUALITYGRADE_CODE", "LEASEWEEKS", "GARMENTS_TO_BE_RETURNED_FROM_ACTIVE_WEARERS", "SECONDARYID") AS 
  select /*version 2.1*/
 1 linetype, prd.code productcode, sz.code sizecode,
 (select pd.description
     from product_desc pd
    where pd.product_id = prd.product_id
      and pd.language_id = languages.language_id) productdesc,
 (select sdd.description
     from sizedefinition_desc sdd
    where sdd.sizedefinition_id = sz.sizedefinition_id
      and sdd.language_id = languages.language_id) sizedesc, wf.code functioncode, wf.description functiondesc, wey.sequencenumber employment,
 cast(concatenatewithblank(lk.bank, lk.locker) as varchar2(255)) banklocker, gd.code garmentdispenser,
 case
   when length(uq.primaryid) = 24 and nvl((select ss.value
                                            from systemsetting ss
                                           where ss.plant_id = bu.plant_id
                                             and ss.name = 'USEURICODE'), 0) = 1 then
    pack_epc_sgtin96.decode(uq.primaryid)
   else
    uq.primaryid
 end idcode, uq.idcodesequencenumber seqnumber, uqfx.lastissuedate issuedate, uq.washestotal washno, uq.repairstotal repairno, uq.rewashtotal rewashno,
 (select count(1)
     from uniqueitemflag uf
    where uf.uniqueitem_id = uq.uniqueitem_id
      and uf.startdate <= trunc(sysdate)) flag,
 (select max(fg.code)
     from uniqueitemflag uf
          join flag fg on uf.flag_id = fg.flag_id
    where uf.uniqueitem_id = uq.uniqueitem_id
      and uf.startdate <= trunc(sysdate)) uiflagcode,
 (select count(1) from uniqueitemmodification um where um.uniqueitem_id = uq.uniqueitem_id) modifications, r.code reason, uq.customerowned,
 uqnp.freeextragarment, trunc(uq.lastscandate) lastscandate, trunc(uq.lastoutscandate) lastoutscandate, trunc(uq.lastinscandate) lastinscan,
 fm.code finmethod,
 (select fmd.description
     from finishingmethod_desc fmd
    where fmd.finishingmethod_id = fm.finishingmethod_id
      and fmd.language_id = languages.language_id) finmethoddesc, cur.invoiceamountdecimals, uq.residualvalueamount residualvalue, flag.code flagcode,
 (select cast(sty.description as varchar2(10))
     from stay_desc sty
    where sty.stay_id = stay.stay_id
      and sty.language_id = languages.language_id) stay, stay.staynr,
 (select sd.description
     from status_desc sd
    where sd.status_id = uq.status_id
      and sd.language_id = languages.language_id) status, we.customeremployeenumber adminnumber, cc.code costcentercode, cc.description costcenterdesc,
 de.departmentnumber, de.description departmentdesc, cu.customernumber, cu.name customername,
 coalesce((select max(ca.processbusinessunit_id)
             from productgroup pg
                  join customeractivities ca on pg.activity_id = ca.activity_id
            where prd.productgroup_id = pg.productgroup_id
              and ca.customer_id = cu.customer_id), cu.defaultbusinessunit_id) processbusinessunit_id,
 coalesce((select max(ca.internalprocessingbu_id)
             from productgroup pg
                  join customeractivities ca on pg.activity_id = ca.activity_id
            where prd.productgroup_id = pg.productgroup_id
              and ca.customer_id = cu.customer_id), cu.defaultbusinessunit_id) intprocessbusinessunit_id, mad.city, cu.defaultbusinessunit_id,
 we.wearernumber, we.fullname wearername, we.searchname wearersearchname, we.firstname wearerfirstname,
 getdatediff(trunc(sysdate), we.dateactive) * getdatediff(we.dateinactive, trunc(sysdate)) weareractive, we.dateactive wearerdateactive,
 we.dateinactive wearerdateinactive, languages.code languagecode, languages.language_id, cu.language_id customerlanguage_id,
 case
   when uq.substituteforproduct_id is null then
    'N'
   else
    'Y'
 end substituteyn, coalesce(qg.code, '') qualitygrade_code, uq.leaseweeks leaseweeks,
 (case
   when exists (select 1
           from uniqueitemflag uf
                join automaticflag af on uf.flag_id = af.flag_id
          where uf.uniqueitem_id = uq.uniqueitem_id
            and uf.startdate <= trunc(sysdate)
            and af.automaticflag_id in (12, 4, 5, 7, 2)) then
    1
   else
    0
 end) garments_to_be_returned_from_active_wearers,
(select sui.secondaryid
 from secondaryuniqueitem sui
 where sui.uniqueitem_id = uq.uniqueitem_id) secondaryid
from uniqueitemnonpool uqnp
     join weareremployment wey
          left join garmentdispenser gd on wey.garmentdispenser_id = gd.garmentdispenser_id
          left join locker lk on wey.locker_id = lk.locker_id
          left join wearerfunction wf on wey.wearerfunction_id = wf.wearerfunction_id
          join wearer we
               left join flag on we.flag_id = flag.flag_id
               join customer cu
                    join address mad on cu.mailaddress_id = mad.address_id
                    join currency cur on cu.currency_id = cur.currency_id
                    join businessunit bu on cu.defaultbusinessunit_id = bu.businessunit_id
               on we.customer_id = cu.customer_id
          on wey.wearer_id = we.wearer_id
          join distributionpoint dip
               join department de on dip.department_id = de.department_id
               join costcenter cc on dip.costcenter_id = cc.costcenter_id
          on wey.distributionpoint_id = dip.distributionpoint_id
     on uqnp.weareremployment_id = wey.weareremployment_id
     join uniqueitem uq
          left join stay on uq.stay_id = stay.stay_id
          left join finishingmethod fm on uq.finishingmethod_id = fm.finishingmethod_id
          join product prd on uq.product_id = prd.product_id
          join sizedefinition sz on uq.sizedefinition_id = sz.sizedefinition_id
          join uniqueitemfixedinfo uqfx
               left join qualitygrade qg on uqfx.qualitygrade_id = qg.qualitygrade_id
               join reasoncode r on uqfx.reasoncode_id = r.reasoncode_id
          on uq.uniqueitem_id = uqfx.uniqueitem_id
     on uqnp.uniqueitem_id = uq.uniqueitem_id
cross join languages
union all
select 2 linetype, coalesce(subtprd.code, prd.code) productcode, coalesce(subtsz.code, sz.code) sizecode,
       coalesce((select description
                   from product_desc
                  where product_desc.product_id = subtprd.product_id
                    and product_desc.language_id = languages.language_id),
                (select description
                     from product_desc pd
                    where pd.product_id = prd.product_id
                      and pd.language_id = languages.language_id)) productdesc,
       (select sdd.description
           from sizedefinition_desc sdd
          where sdd.sizedefinition_id = coalesce(subtsz.sizedefinition_id, sz.sizedefinition_id)
            and sdd.language_id = languages.language_id) sizedesc, wf.code functioncode, wf.description functiondesc, wey.sequencenumber employment,
       cast(concatenatewithblank(lk.bank, lk.locker) as varchar2(255)) banklocker, gd.code garmentdispenser, null idcode, nuq.sequencenumber seqnumber,
       nuq.issuedate issuedate, null washno, null repairno, null rewashno, null flag, null uiflagcode,
       (select count(1) from wearerinventorymodification wim where wim.wearerinventory_id = weinv.wearerinventory_id) modifications, rc.code reason,
       'N' customerowned, 'X' freeextragarment, null lastscandate, null lastoutscandate, null lastinscandate, fm.code finmethod,
       (select fmd.description
           from finishingmethod_desc fmd
          where fmd.finishingmethod_id = fm.finishingmethod_id
            and fmd.language_id = languages.language_id) finmethoddesc, cur.invoiceamountdecimals, 0 residualvalue, flag.code flagcode, null stay,
       null staynr, null status, we.customeremployeenumber adminnumber, cc.code costcentercode, cc.description costcenterdesc, de.departmentnumber,
       de.description departmentdesc, cu.customernumber, cu.name customername,
       coalesce((select max(ca.processbusinessunit_id)
                   from productgroup pg join
                        customeractivities ca on pg.activity_id = ca.activity_id
                  where prd.productgroup_id = pg.productgroup_id
                    and ca.customer_id = cu.customer_id), cu.defaultbusinessunit_id) processbusinessunit_id,
       coalesce((select max(ca.internalprocessingbu_id)
                   from productgroup pg join customeractivities ca on pg.activity_id = ca.activity_id
                  where prd.productgroup_id = pg.productgroup_id
                    and ca.customer_id = cu.customer_id), cu.defaultbusinessunit_id) intprocessbusinessunit_id, mad.city, cu.defaultbusinessunit_id,
       we.wearernumber, we.fullname wearername, we.searchname wearersearchname, we.firstname wearerfirstname,
       getdatediff(trunc(sysdate), we.dateactive) * getdatediff(we.dateinactive, trunc(sysdate)) weareractive, we.dateactive wearerdateactive,
       we.dateinactive wearerdateinactive, languages.code languagecode, languages.language_id, cu.language_id customerlanguage_id,
       case
          when nuq.substituteforproduct_id is null then
           'N'
          else
           'Y'
        end substituteyn, '' qualitygrade_code, null leaseweeks, 0 garments_to_be_returned_from_active_wearers,
null secondaryid
from nonuniqueitem nuq
     left join product subtprd on nuq.substituteforproduct_id = subtprd.product_id
     left join sizedefinition subtsz on nuq.substituteforsizedefinition_id = subtsz.sizedefinition_id
     join wearerinventory weinv
          join weareremployment wey
               left join garmentdispenser gd on wey.garmentdispenser_id = gd.garmentdispenser_id
               left join locker lk on wey.locker_id = lk.locker_id
               left join wearerfunction wf on wey.wearerfunction_id = wf.wearerfunction_id
               join distributionpoint dip
                    join department de on dip.department_id = de.department_id
                    join costcenter cc on dip.costcenter_id = cc.costcenter_id
               on wey.distributionpoint_id = dip.distributionpoint_id
               join wearer we
                    left join flag on we.flag_id = flag.flag_id
                    join customer cu
                         join address mad on cu.mailaddress_id = mad.address_id
                         join currency cur on cu.currency_id = cur.currency_id
                    on we.customer_id = cu.customer_id
               on wey.wearer_id = we.wearer_id
          on weinv.weareremployment_id = wey.weareremployment_id
          join product prd on weinv.product_id = prd.product_id
          join sizedefinition sz on weinv.sizedefinition_id = sz.sizedefinition_id
          join finishingmethod fm on weinv.finishingmethod_id = fm.finishingmethod_id
      on nuq.wearerinventory_id = weinv.wearerinventory_id
      join reasoncode rc on nuq.reasoncode_id = rc.reasoncode_id
cross join languages
-- linetype 3 was removed during redesign
-- all rows previously returned by linetype 3 , should be returned by linetype1
union all --ABS-72412 Temporary Assigned Pool Garments
select 4 linetype, prd.code productcode, sz.code sizecode,
       (select pd.description
           from product_desc pd
          where pd.product_id = prd.product_id
            and pd.language_id = languages.language_id) productdesc,
       (select sdd.description
           from sizedefinition_desc sdd
          where sdd.sizedefinition_id = sz.sizedefinition_id
            and sdd.language_id = languages.language_id) sizedesc, wf.code functioncode, wf.description functiondesc, wey.sequencenumber employment,
       cast(concatenatewithblank(lk.bank, lk.locker) as varchar2(255)) banklocker, gd.code garmentdispenser,
       case
          when length(uq.primaryid) = 24 and nvl((select ss.value
                                                   from systemsetting ss
                                                  where ss.plant_id = bu.plant_id
                                                    and ss.name = 'USEURICODE'), 0) = 1 then
           pack_epc_sgtin96.decode(uq.primaryid)
          else
           uq.primaryid
        end idcode, uq.idcodesequencenumber seqnumber, wta.issuetowearerdate issuedate, uq.washestotal washno, uq.repairstotal repairno,
       uq.rewashtotal rewashno,
       (select count(1)
           from uniqueitemflag uf
                join automaticflag af on uf.flag_id = af.flag_id
          where uf.uniqueitem_id = uq.uniqueitem_id
            and uf.startdate <= trunc(sysdate)
            and af.automaticflag_id in (12, 4, 5, 7, 2)) flag,
       (select max(fg.code)
           from uniqueitemflag uf
                join flag fg on uf.flag_id = fg.flag_id
                join automaticflag af on uf.flag_id = af.flag_id
          where uf.uniqueitem_id = uq.uniqueitem_id
            and uf.startdate <= trunc(sysdate)
            and af.automaticflag_id in (12, 4, 5, 7, 2)) uiflagcode,
       (select count(1) from uniqueitemmodification um where um.uniqueitem_id = uq.uniqueitem_id) modifications, r.code reason, uq.customerowned,
       'N' freeextragarment, trunc(uq.lastscandate) lastscandate, trunc(uq.lastoutscandate) lastoutscandate, trunc(uq.lastinscandate) lastinscandate,
       fm.code finmethod,
       (select fmd.description
           from finishingmethod_desc fmd
          where fmd.finishingmethod_id = fm.finishingmethod_id
            and fmd.language_id = languages.language_id) finmethoddesc, cur.invoiceamountdecimals, uq.residualvalueamount residualvalue, flag.code flagcode,
       (select cast(sty.description as varchar2(10))
           from stay_desc sty
          where sty.stay_id = stay.stay_id
            and sty.language_id = languages.language_id) stay, stay.staynr,
       (select sd.description
           from status_desc sd
          where sd.status_id = uq.status_id
            and sd.language_id = languages.language_id) status, we.customeremployeenumber adminnumber, cc.code costcentercode,
       cc.description costcenterdesc, de.departmentnumber, de.description departmentdesc, cu.customernumber, cu.name customername,
       coalesce((select max(ca.processbusinessunit_id)
                   from productgroup pg
                        join customeractivities ca on pg.activity_id = ca.activity_id
                  where prd.productgroup_id = pg.productgroup_id
                    and ca.customer_id = cu.customer_id), cu.defaultbusinessunit_id) processbusinessunit_id,
       coalesce((select max(ca.internalprocessingbu_id)
                   from productgroup pg join
                        customeractivities ca on pg.activity_id = ca.activity_id
                  where prd.productgroup_id = pg.productgroup_id
                    and ca.customer_id = cu.customer_id), cu.defaultbusinessunit_id) intprocessbusinessunit_id, mad.city, cu.defaultbusinessunit_id,
       we.wearernumber, we.fullname wearername, we.searchname wearersearchname, we.firstname wearerfirstname,
       getdatediff(trunc(sysdate), we.dateactive) * getdatediff(we.dateinactive, trunc(sysdate)) weareractive, we.dateactive wearerdateactive,
       we.dateinactive wearerdateinactive, languages.code languagecode, languages.language_id, cu.language_id customerlanguage_id,
       case
          when uq.substituteforproduct_id is null then
           'N'
          else
           'Y'
        end substituteyn, coalesce(qg.code, '') qualitygrade_code, uq.leaseweeks leaseweeks, 0 garments_to_be_returned_from_active_wearers,
(select sui.secondaryid
 from secondaryuniqueitem sui
 where sui.uniqueitem_id = uq.uniqueitem_id) secondaryid
from wearertempassignment wta
     join weareremployment wey
          left join garmentdispenser gd on wey.garmentdispenser_id = gd.garmentdispenser_id
          left join locker lk on wey.locker_id = lk.locker_id
          left join wearerfunction wf on wey.wearerfunction_id = wf.wearerfunction_id
          join distributionpoint dip
               join department de on dip.department_id = de.department_id
               join costcenter cc on dip.costcenter_id = cc.costcenter_id
          on wey.distributionpoint_id = dip.distributionpoint_id
          join wearer we
               left join flag on we.flag_id = flag.flag_id
               join customer cu
                    join address mad on cu.mailaddress_id = mad.address_id
                    join currency cur on cu.currency_id = cur.currency_id
                    join businessunit bu on cu.defaultbusinessunit_id = bu.businessunit_id
               on we.customer_id = cu.customer_id
          on wey.wearer_id = we.wearer_id
      on wta.weareremployment_id = wey.weareremployment_id
      join uniqueitem uq
           left join stay on uq.stay_id = stay.stay_id
           left join finishingmethod fm on uq.finishingmethod_id = fm.finishingmethod_id
           join product prd on uq.product_id = prd.product_id
           join sizedefinition sz on uq.sizedefinition_id = sz.sizedefinition_id
           join uniqueitemfixedinfo uqfx
                left join qualitygrade qg on uqfx.qualitygrade_id = qg.qualitygrade_id
                join reasoncode r on uqfx.reasoncode_id = r.reasoncode_id
           on uq.uniqueitem_id = uqfx.uniqueitem_id
      on wta.uniqueitem_link_id = uq.uniqueitem_id
cross join languages
where wta.returnfromwearerdate is null
/

  CREATE OR REPLACE VIEW "V_GARMENTSPERWEARER_WITHMODIF" ("PRODUCTCODE", "PRODUCTDESC", "FUNCTIONCODE", "FUNCTIONDESC", "EMPLOYMENT", "SIZECODE", "BANKLOCKER", "GARMENTDISPENSER", "IDCODE", "ISSUEDATE", "WASHNO", "REPAIRNO", "REWASHNO", "FLAG", "REASON", "CUSTOMEROWNED", "LASTSCANDATE", "LASTOUTSCANDATE", "FINMETHOD", "INVOICEAMOUNTDECIMALS", "RESIDUALVALUE", "FLAGCODE", "STAY", "STAYNR", "STATUS", "ADMINNUMBER", "COSTCENTERCODE", "COSTCENTERDESC", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "PROCESSBUSINESSUNIT_ID", "INTPROCESSBUSINESSUNIT_ID", "CITY", "DEFAULTBUSINESSUNIT_ID", "WEARERNUMBER", "WEARERNAME", "WEARERSEARCHNAME", "WEARERACTIVE", "WEARERDATEACTIVE", "WEARERDATEINACTIVE", "LANGUAGECODE", "MODIFICATIONS") AS 
  select
  prd.CODE PRODUCTCODE
, ( SELECT description FROM product_desc pd WHERE pd.product_id = prd.product_id
  AND pd.LANGUAGE_ID = languages.LANGUAGE_ID) productdesc
, wf.code functioncode, wf.description functiondesc, wey.sequencenumber employment, sz.code sizecode
, cast(CONCATENATEWITHBLANK(lk.bank, lk.locker) as varchar2(255)) banklocker
, gd.code garmentdispenser
, case when length(uq.primaryid) = 24 and nvl((select ss.value from systemsetting ss where ss.plant_id = bu.plant_id and ss.name='USEURICODE'),0) = 1
    then pack_epc_sgtin96.decode(uq.primaryid)
    else uq.primaryid
  end idcode
, uqfx.lastissuedate issuedate, uq.washestotal washno, uq.repairstotal repairno, uq.rewashtotal rewashno
, ( SELECT COUNT(*) FROM UNIQUEITEMFLAG uf WHERE uf.UNIQUEITEM_ID = uq.UNIQUEITEM_ID) flag
, r.code reason, uq.customerowned
, trunc(uq.lastscandate) lastscandate, trunc(uq.lastoutscandate) lastoutscandate
, fm.code finmethod, currency.invoiceamountdecimals, uq.residualvalueAmount residualvalue, flag.code flagcode
, ( SELECT cast(sty.description as varchar2(10)) FROM stay_desc sty WHERE sty.stay_id = stay.stay_id
  AND sty.LANGUAGE_ID = languages.LANGUAGE_ID) stay, stay.staynr
, ( SELECT description FROM status_desc sd WHERE sd.status_id = uq.status_id
  AND sd.LANGUAGE_ID = languages.LANGUAGE_ID) status
, we.customeremployeenumber adminnumber,  cc.code costcentercode, cc.description costcenterdesc
, de.departmentnumber, de.description departmentdesc
, cu.customernumber, cu.name customername,
coalesce((select max(ca.processbusinessunit_id) from productgroup pg,  customeractivities ca
where prd.productgroup_id=pg.productgroup_id and pg.activity_id=ca.activity_id and ca.customer_id=cu.customer_id),cu.defaultbusinessunit_id) processbusinessunit_id,
coalesce((select max(ca.internalprocessingbu_id) from productgroup pg,  customeractivities ca
where prd.productgroup_id=pg.productgroup_id and pg.activity_id=ca.activity_id and ca.customer_id=cu.customer_id),cu.defaultbusinessunit_id) intprocessbusinessunit_id,
address.city, cu.defaultbusinessunit_id
, we.wearernumber, we.fullname wearername, we.searchname wearersearchname
, GETDATEDIFF(trunc(sysdate), we.dateactive)*GETDATEDIFF(we.dateinactive, trunc(sysdate)) weareractive
, we.dateactive WearerDateActive, we.dateinactive WearerDateInactive, languages.code languagecode
, cast(F_MODIFICATIONS(uq.uniqueitem_id, 'U') as varchar2(40)) MODIFICATIONS
from
  customer cu
, wearer we
    left outer join flag on we.flag_id = flag.flag_id
, weareremployment wey
    left outer join garmentdispenser gd on gd.garmentdispenser_id = wey.garmentdispenser_id
    left outer join locker lk on lk.locker_id = wey.locker_id
    left outer join wearerfunction wf on wey.wearerfunction_id = wf.wearerfunction_id
, uniqueitemnonpool uqnp
, uniqueitem uq
    left outer join stay on uq.stay_id = stay.stay_id
    left outer join finishingmethod fm on fm.finishingmethod_id = uq.finishingmethod_id
, uniqueitemfixedinfo uqfx, reasoncode r
, product prd,  sizedefinition sz
, distributionpoint dip, department de, costcenter cc
, address, currency, languages
, businessunit bu
where
    cu.customer_id = we.customer_id
and we.wearer_id = wey.wearer_id
and wey.weareremployment_id = uqnp.weareremployment_id
and uqnp.uniqueitem_id = uq.uniqueitem_id
    and uq.uniqueitem_id = uqfx.uniqueitem_id
        and uqfx.reasoncode_id = r.reasoncode_id
and uq.product_id = prd.product_id
and uq.sizedefinition_id = sz.sizedefinition_id
and wey.distributionpoint_id = dip.distributionpoint_id
    and dip.department_id = de.department_id
        and dip.costcenter_id = cc.costcenter_id
and cu.mailaddress_id = address.address_id
and cu.currency_id = currency.currency_id
and bu.businessunit_id = cu.defaultbusinessunit_id
Union all
select
  prd.CODE PRODUCTCODE
, ( SELECT description FROM product_desc pd WHERE pd.product_id = prd.product_id
  AND pd.LANGUAGE_ID = languages.LANGUAGE_ID) productdesc
, wf.code functioncode, wf.description functiondesc, wey.sequencenumber employment, sz.code sizecode
, cast(CONCATENATEWITHBLANK(lk.bank, lk.locker) as varchar2(255)) banklocker
, gd.code garmentdispenser, null idcode
, nuq.issuedate issuedate, null washno, null repairno, null rewashno, null flag
, rc.code reason, 'N' customerowned
, null lastscandate, null lastoutscandate
, fm.code finmethod, currency.invoiceamountdecimals, -1 residualvalue, flag.code flagcode
, null stay, null staynr, null status
, we.customeremployeenumber adminnumber, cc.code costcentercode, cc.description costcenterdesc
, de.departmentnumber, de.description departmentdesc
, cu.customernumber, cu.name customername,
coalesce((select max(ca.processbusinessunit_id) from productgroup pg,  customeractivities ca
where prd.productgroup_id=pg.productgroup_id and pg.activity_id=ca.activity_id and ca.customer_id=cu.customer_id),cu.defaultbusinessunit_id) processbusinessunit_id,
coalesce((select max(ca.internalprocessingbu_id) from productgroup pg,  customeractivities ca
where prd.productgroup_id=pg.productgroup_id and pg.activity_id=ca.activity_id and ca.customer_id=cu.customer_id),cu.defaultbusinessunit_id) intprocessbusinessunit_id,
address.city, cu.defaultbusinessunit_id
, we.wearernumber, we.fullname wearername, we.searchname wearersearchname
, GETDATEDIFF(trunc(sysdate), we.dateactive)*GETDATEDIFF(we.dateinactive, trunc(sysdate)) weareractive
, we.dateactive WearerDateActive, we.dateinactive WearerDateInactive, languages.code languagecode
, cast(F_MODIFICATIONS(weinv.wearerinventory_id, 'W') as varchar2(40)) MODIFICATIONS
from
  customer cu
, wearer we
    left outer join flag  on we.flag_id = flag.flag_id
, weareremployment wey
    left outer join garmentdispenser gd on gd.garmentdispenser_id = wey.garmentdispenser_id
    left outer join locker lk on lk.locker_id = wey.locker_id
    left outer join wearerfunction wf on wey.wearerfunction_id = wf.wearerfunction_id
, wearerinventory weinv
, nonuniqueitem nuq, product prd, sizedefinition sz, finishingmethod fm
, reasoncode rc
, distributionpoint dip, department de, costcenter cc
, address, currency, languages
where
    cu.customer_id = we.customer_id
and we.wearer_id = wey.wearer_id
and wey.weareremployment_id = weinv.weareremployment_id
AND weinv.product_id = prd.product_id
and weinv.sizedefinition_id = sz.sizedefinition_id
and weinv.finishingmethod_id = fm.finishingmethod_id
and weinv.wearerinventory_id = nuq.wearerinventory_id
    and nuq.reasoncode_id = rc.reasoncode_id
and wey.distributionpoint_id = dip.distributionpoint_id
    and dip.department_id = de.department_id
        and dip.costcenter_id = cc.costcenter_id
and cu.mailaddress_id = address.address_id
    and cu.currency_id = currency.currency_id
/

  CREATE OR REPLACE VIEW "V_GARMENTSREADYTOBESORTED" ("PLANTCODE", "ROUTEDATE", "ROUTENUMBER", "DAYNUMBER", "IDCODE", "DEPOTCODE", "STOPNUMBER", "CUSTOMERNUMBER", "WEARERNUMBER", "PRODUCTCODE", "SORTSTRING", "STACKCHANGESTRING", "DESTINATION", "FLAGS") AS 
  select /*+ index(ur XIF4UNIQUEITEMROUTE) index(u XPKUNIQUEITEM)
          index(un XPKUNIQUEITEMNONPOOL)
          index(we XPKWEAREREMPLOYMENT)
          index(dp XPKDISTRIBUTIONPOINT) index(w XPKWEARER)
          index(t XPKDEPARTMENT) index(delp XPKDELIVERYPOINT)
       */
 /*view v_garmentsreadytobesorted version 1.0*/
 pt.code plantcode, ur.plannedoutdate routedate, r.routenumber, r.drivingday_id daynumber,
 u.primaryid idcode, d.code depotcode,
 nvl((select rs.stopnumber   -- HVH To do 8178 make stop# 999999 in off week for EOW customers
   from   routestop rs
   where  rs.route_id = r.route_id
   and    rs.routestop_id =
          pack_sort.getroutestopforcustomer(r.plant_id, ur.plannedoutdate, w.customer_id,
                                             delp.deliverypoint_id)
   and rs.dateactive <=  ur.plannedoutdate --order 502746
   and ur.plannedoutdate  < rs.dateinactive
 ),999999) stopnumber,
 c.customernumber,
 w.wearernumber,
 p.code productcode,
 (pack_sort.buildsortstring(p.code, s.code, c.customernumber, c.customer_id, w.wearernumber,
                             w.fullname,
                             (select lpad(nvl(lo.bank, ' '), 6, ' ') ||
                                       lpad(nvl(lo.locker, ' '), 6, ' ')
                               from   locker lo
                               where  lo.locker_id = we.locker_id), t.departmentnumber,
                             we.sequencenumber, w.sex,
                             (select rpad(nvl(g.code, ' '), 6, ' ')
                               from   garmentdispenser g
                               where  g.garmentdispenser_id = we.garmentdispenser_id), delp.code,
                             nvl((select rs.stopnumber
                               from   routestop rs
                               where  rs.route_id = r.route_id
                               and    rs.routestop_id =
                                      pack_sort.getroutestopforcustomer(r.plant_id, ur.plannedoutdate,
                                                                         w.customer_id,
                                                                         delp.deliverypoint_id)),999999),
                             r.plant_id, u.customerowned, 0,null,null,null,null,null)) sortstring,
 (pack_sort.buildstackchangeinfo(p.code, s.code, c.customernumber, c.customer_id, w.wearernumber,
                                  w.fullname,
                                  (select lpad(nvl(lo.bank, ' '), 6, ' ') ||
                                            lpad(nvl(lo.locker, ' '), 6, ' ')
                                    from   locker lo
                                    where  lo.locker_id = we.locker_id), t.departmentnumber,
                                  we.sequencenumber, w.sex,
                                  (select rpad(nvl(g.code, ' '), 6, ' ')
                                    from   garmentdispenser g
                                    where  g.garmentdispenser_id = we.garmentdispenser_id), delp.code,
                                  nvl((select rs.stopnumber
                                    from   routestop rs
                                    where  rs.route_id = r.route_id
                                    and    rs.routestop_id =
                                           pack_sort.getroutestopforcustomer(r.plant_id,
                                                                              ur.plannedoutdate,
                                                                              w.customer_id,
                                                                              delp.deliverypoint_id)),999999),
                                  r.plant_id, u.customerowned,0,null,null,null,null,null)) stackchangestring,
 (select sf.sortaddress
   from   sortaddressperfinishingmeth sf
   where  sf.finishingmethod_id = u.finishingmethod_id
   and    sf.plant_id = r.plant_id) destination,
   fgetuniqueitemflags(u.uniqueitem_id,r.plant_id,we.wearer_id,un.weareremployment_id) flags
from   route r, uniqueitemroute ur, uniqueitem u, uniqueitemnonpool un, weareremployment we,
       distributionpoint dp, wearer w, deliverypoint delp, customer c, department t, depot d,
       plant pt, product p, sizedefinition s
where  ur.plannedoutroute_id = r.route_id
and    u.uniqueitem_id = ur.uniqueitem_id
and    un.uniqueitem_id = u.uniqueitem_id
and    un.weareremployment_id = we.weareremployment_id
and    we.distributionpoint_id = dp.distributionpoint_id
and    we.wearer_id = w.wearer_id
and    w.customer_id = c.customer_id
and    dp.department_id = t.department_id
and   delp.deliverypoint_id=coalesce(we.deliverypoint_id,(select l.deliverypoint_id from locker l where we.locker_id=l.locker_id),
(select gd.deliverypoint_id from garmentdispenser gd where we.garmentdispenser_id=gd.garmentdispenser_id))
and    t.customer_id = w.customer_id
and    t.customer_id = delp.customer_id
and    r.depot_id = d.depot_id(+)
and    r.plant_id = pt.plant_id
and    u.product_id = p.product_id
and    u.sizedefinition_id = s.sizedefinition_id
and    exists (select st.status_id
        from   status st
        where  st.status_id = u.status_id
        and    st.statustype = 'UI'
        and    st.code = '20')
and    exists (select sy.stay_id
        from   stay sy
        where  sy.stay_id = u.stay_id
        and    sy.staytype = 1
        and    sy.staynr in (30,33))  -- HVH Todo 8177 Include checkpoint scan Nr 33
/

  CREATE OR REPLACE VIEW "V_GARMENTSREADYTOBESORTEDALL" ("IDCODE", "CUSTOMERNUMBER", "WEARERNUMBER", "PRODUCTCODE", "DESTINATION", "FOLDPROGRAM", "FINISHPROGRAM", "FLAGS") AS 
  select u.primaryid idcode, c.customernumber, w.wearernumber, p.code productcode,
       (select sf.sortaddress
          from sortaddressperfinishingmeth sf
         where sf.finishingmethod_id = u.finishingmethod_id
           and sf.plant_id = b.plant_id) destination,
       (select f.foldingprogram
          from foldingprogramdefinition f
         where f.product_id = u.product_id
           and f.finishingmethod_id = u.finishingmethod_id
           and f.plant_id = b.plant_id) foldprogram,
       (select s.sortaddress
          from sortaddressperfinishingcode s
         where s.finishingcode_id = p.finishingcode_id
           and s.plant_id = b.plant_id) finishprogram,
       fgetuniqueitemflags(u.uniqueitem_id, b.plant_id, we.wearer_id, un.weareremployment_id) flags
from   uniqueitem u, uniqueitemnonpool un, weareremployment we, distributionpoint dp, wearer w,
       deliverypoint delp, customer c, department t, product p, sizedefinition s, businessunit b
where  un.uniqueitem_id = u.uniqueitem_id
and    un.weareremployment_id = we.weareremployment_id
and    we.distributionpoint_id = dp.distributionpoint_id
and    we.wearer_id = w.wearer_id
and    w.customer_id = c.customer_id
and    dp.department_id = t.department_id
and    dp.deliverypoint_id = delp.deliverypoint_id
and    t.customer_id = w.customer_id
and    t.customer_id = delp.customer_id
and    u.product_id = p.product_id
and    u.sizedefinition_id = s.sizedefinition_id
and    c.defaultbusinessunit_id = b.businessunit_id
and    exists (select st.status_id
        from   status st
        where  st.status_id = u.status_id
        and    st.statustype = 'UI'
        and    st.code in ('20','30'))
/

  CREATE OR REPLACE VIEW "V_GARMENTSREADYTOBESORTEDALLAF" ("IDCODE", "CUSTOMERNUMBER", "WEARERNUMBER", "PRODUCTCODE", "DESTINATION", "FOLDPROGRAM", "FINISHPROGRAM", "FLAGS") AS 
  select u.primaryid idcode, c.customernumber, w.wearernumber, p.code productcode,
       (select sf.sortaddress
          from sortaddressperfinishingmeth sf
         where sf.finishingmethod_id = u.finishingmethod_id
           and sf.plant_id = b.plant_id) destination,
       (select f.foldingprogram
          from foldingprogramdefinition f
         where f.product_id = u.product_id
           and f.finishingmethod_id = u.finishingmethod_id
           and f.plant_id = b.plant_id) foldprogram,
       (select s.sortaddress
          from sortaddressperfinishingcode s
         where s.finishingcode_id = p.finishingcode_id
           and s.plant_id = b.plant_id) finishprogram,
       fgetuniqueitemflags(u.uniqueitem_id, b.plant_id, we.wearer_id, un.weareremployment_id) flags
from   uniqueitem u, uniqueitemnonpool un, weareremployment we, distributionpoint dp, wearer w,
       deliverypoint delp, customer c, department t, product p, sizedefinition s, businessunit b
where  un.uniqueitem_id = u.uniqueitem_id
and    un.weareremployment_id = we.weareremployment_id
and    we.distributionpoint_id = dp.distributionpoint_id
and    we.wearer_id = w.wearer_id
and    w.customer_id = c.customer_id
and    dp.department_id = t.department_id
and    dp.deliverypoint_id = delp.deliverypoint_id
and    t.customer_id = w.customer_id
and    t.customer_id = delp.customer_id
and    u.product_id = p.product_id
and    u.sizedefinition_id = s.sizedefinition_id
and    c.defaultbusinessunit_id = b.businessunit_id
and    (exists (select st.status_id
        from   status st
        where  st.status_id = u.status_id
        and    st.statustype = 'UI'
        and    st.code in ('30'))
     or  exists (select 1 from uniqueitemflag uf, flagoptions o, dialogs dg, flag x, sortaddressperflag y
 where uf.uniqueitem_id = u.uniqueitem_id
   and uf.flag_id = o.flag_id
   and o.flag_id = x.flag_id
   and o.dialog_id = dg.dialog_id
   and upper(dg.code) in ('INSCAN', 'CHECKPOINTSCAN')
   and o.show = 'Y'
   and x.flag_id = y.flag_id
   and y.sortaddress is not null))
/

  CREATE OR REPLACE VIEW "V_GARMENTSSTILLINSOILAREA" ("PLANTCODE", "DAYOFWEEK", "ROUTENUMBER", "STOPNUMBER", "CUSTOMERNUMBER", "LASTINSCANDATE", "QTY_INSCAN", "QTY_CHECKPOINTSCAN") AS 
  select /*v_garmentsstillinsoilarea version 1.1*/
 pt.code plantcode, r.drivingday_id dayofweek, r.routenumber, stop.stopnumber, c.customernumber,
 trunc(u.lastinscandate) lastinscandate,
 count(case sy.staynr
          when 30 then
           1
          else
           0
        end) qty_inscan,
 count(case sy.staynr
          when 33 then
           1
          else
           0
        end) qty_checkpointscan
from   uniqueitemroute ur
join   uniqueitem u
on     u.uniqueitem_id = ur.uniqueitem_id
join   route r
on     r.route_id = ur.plannedoutroute_id
join   stop
on     stop.stop_id = ur.plannedoutstop_id
join   uniqueitemnonpool un
on     un.uniqueitem_id = ur.uniqueitem_id
join   weareremployment we
on     we.weareremployment_id = un.weareremployment_id
join   wearer w
on     w.wearer_id = we.wearer_id
join   customer c
on     c.customer_id = w.customer_id
join   plant pt
on     pt.plant_id = r.plant_id
join   stay sy
on     sy.stay_id = u.stay_id
where  exists (select st.status_id
        from   status st
        where  st.status_id = u.status_id
        and    st.statustype = 'UI'
        and    st.code = '20')
and    sy.staytype = 1
and    sy.staynr in (30, 33)
group  by pt.code, r.drivingday_id, r.routenumber, stop.stopnumber, c.customernumber,
          trunc(u.lastinscandate)
/

  CREATE OR REPLACE VIEW "V_GARMENTSTOCKRETURNNOTE" ("DRIVINGDATE", "ROUTENUMBER", "ROUTECONTROL_ID", "CUSTOMER_ID", "STOPNUMBER", "CUSTOMERNUMBER", "WEARERNUMBER", "WEARERNAME", "PRODUCTCODE", "FMCODE", "IDCODE", "DELP_STREET1", "DELP_STREET2", "DELP_ZIPCODE", "DELP_CITY", "FLAGSTARTDATE", "DELP_COUNTY", "DAYDESC", "FLAGID", "BANKLOCKER", "FLAGTRANSACTION") AS 
  select rc.drivingdate, ru.routenumber, rc.routecontrol_id, cu.customer_id,
       st.stopnumber, cu.customernumber, we.wearernumber, we.fullname wearername, p.code productcode, fm.code fmcode,
       ui.primaryid idcode, ad.street delp_street1, ad.street2 delp_street2, ad.zipcode delp_zipcode, ad.city delp_city, uif.startdate flagstartdate,
       ad.county delp_county, (select dd.description from day_desc dd where dd.day_id = ru.drivingday_id and dd.language_id = lan.language_id) daydesc, uif.flag_id flagID,
       (select concat(concat(lc.bank, '/'), lc.locker) from locker lc where lc.locker_id = wemp.locker_id) banklocker,
       (select fd.description
           from flag_desc fd
          where fd.flag_id = uif.flag_id
            and fd.language_id = lan.language_id) flagtransaction
  from routecontrol rc
  join route ru on rc.route_id = ru.route_id
  join stop st on st.routecontrol_id = rc.routecontrol_id
  left outer join (deliverypoint delp join address ad on delp.deliveryaddress_id = ad.address_id)
                  on delp.deliverypoint_id = st.deliverypoint_id
  join customer cu on cu.customer_id = st.customer_link_id
  join wearer we on we.customer_id = cu.customer_id
  join weareremployment wemp on wemp.wearer_id = we.wearer_id
  join uniqueitemnonpool uinp on uinp.weareremployment_id = wemp.weareremployment_id
  join uniqueitem ui on ui.uniqueitem_id = uinp.uniqueitem_id
  join uniqueitemflag uif on uif.uniqueitem_id = ui.uniqueitem_id
  join product p on p.product_id = ui.product_id
  join finishingmethod fm on fm.finishingmethod_id = ui.finishingmethod_id
  join languages lan on lan.language_id = cu.language_id
 where uif.flag_id in (select fl.flag_id from flag fl where fl.flagtype = 1 and fl.code in ('21', '51', '52', '53'))
/

  CREATE OR REPLACE VIEW "V_GARMENTWEARERSAPPENDIX" ("LINETYPE", "INVOICEHEADER_ID", "INVOICENUMBER", "INVOICEDATE", "STARTDATE", "ENDDATE", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMERACTIVE", "STREET", "STREET2", "ZIPCODE", "CITY", "STATE", "COUNTY", "HOUSENUMBER", "HOUSENUMBEREXT", "WEARERNUMBER", "FULLNAME", "SEARCHNAME", "DATEACTIVE", "DATEINACTIVE", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTDESCRIPTION", "MAXINVENTORY", "DELIVERYDATE", "PACKINGNOTELINE_ID", "WASHED") AS 
  select 1 linetype, --Wearer Inventory
         ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.startdate, ih.enddate,
         del.customernumber, del.name customername, del.active customeractive,
         adr.street, adr.street2, adr.zipcode, adr.city, adr.state, adr.county, adr.housenumber, adr.housenumberext,
         we.wearernumber, we.fullname, we.searchname, we.dateactive, we.dateinactive, pr.product_id, pr.code ProductCode,
         (select prd.description from product_desc prd where prd.product_id = pr.product_id and prd.language_id = del.language_id) ProductDescription,
         wi.maxinventory, null deliverydate, 0 packingnoteline_id, 0 Washed
    from invoiceheader ih
         join customer del on ih.deltocustomer_link_id = del.customer_id
         join address adr on del.visitaddress_id = adr.address_id
         join wearer we on del.customer_id = we.customer_id
         join weareremployment wey on we.wearer_id = wey.wearer_id
         join wearerinventory wi on wey.weareremployment_id = wi.weareremployment_id
         join product pr on wi.product_id = pr.product_id
   where wi.dateactive <= ih.enddate and we.dateactive < ih.enddate
         and wi.dateinactive >= ih.enddate and we.dateinactive >= ih.enddate
         and not exists (select 1 from packingnoteline pnl, deliveryscan ds where pnl.invoiceheader_id = ih.invoiceheader_id
                     and pnl.product_id = wi.product_id and pnl.sizedefinition_id = wi.sizedefinition_id
                     and pnl.finishingmethod_id = wi.finishingmethod_id
                     and pnl.packingnote_id = ds.packingnote_id and ds.weareremployment_link_id = wey.weareremployment_id
                     and ds.product_link_id = pnl.product_id and ds.sizedefinition_link_id = pnl.sizedefinition_id
                     and ds.finishingmethod_id = pnl.finishingmethod_id and ds.outscannodelivery in (0, 2))
group by ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.startdate, ih.enddate,
         del.customernumber, del.name, del.active,
         adr.street, adr.street2, adr.zipcode, adr.city, adr.state, adr.county, adr.housenumber, adr.housenumberext,
         we.wearernumber, we.fullname, we.searchname, we.dateactive, we.dateinactive, pr.product_id, pr.code,
         del.language_id, wi.maxinventory
union all
  select 2 linetype, --Outscans
         ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.startdate, ih.enddate,
         del.customernumber, del.name customername, del.active customeractive,
         adr.street, adr.street2, adr.zipcode, adr.city, adr.state, adr.county, adr.housenumber, adr.housenumberext,
         we.wearernumber, we.fullname, we.searchname, we.dateactive, we.dateinactive, pr.product_id, pr.code ProductCode,
         (select prd.description from product_desc prd where prd.product_id = pr.product_id and prd.language_id = del.language_id) ProductDescription,
         wi.maxinventory, pn.deliverydate, pnl.packingnoteline_id,
         (select count(1) from deliveryscan ds where ds.packingnote_id = pnl.packingnote_id
                     and ds.weareremployment_link_id = wey.weareremployment_id
                     and ds.product_link_id = pnl.product_id
                     and ds.sizedefinition_link_id = pnl.sizedefinition_id
                     and ds.finishingmethod_id = pnl.finishingmethod_id
                     and ds.outscannodelivery in (0, 2)) Washed
    from packingnoteline pnl
         join wearerinventory wi on pnl.product_id = wi.product_id and pnl.sizedefinition_id = wi.sizedefinition_id
                                and pnl.finishingmethod_id = wi.finishingmethod_id
         join weareremployment wey on wi.weareremployment_id = wey.weareremployment_id
         join wearer we on wey.wearer_id = we.wearer_id
         join packingnote pn on pnl.packingnote_id = pn.packingnote_id
         join invoiceheader ih on pnl.invoiceheader_id = ih.invoiceheader_id
         join customer del on ih.deltocustomer_link_id = del.customer_id
         join address adr on del.visitaddress_id = adr.address_id
         join product pr on pnl.product_id = pr.product_id
   where we.customer_id = del.customer_id
         and exists (select 1 from deliveryscan ds where pnl.packingnote_id = ds.packingnote_id
                     and ds.weareremployment_link_id = wey.weareremployment_id
                     and ds.product_link_id = pnl.product_id and ds.sizedefinition_link_id = pnl.sizedefinition_id
                     and ds.finishingmethod_id = pnl.finishingmethod_id and ds.outscannodelivery in (0, 2))
/

  CREATE OR REPLACE VIEW "V_GARMPERWEARER_CRPOS" ("PRODUCTCODE", "SIZECODE", "PRODUCTDESC", "FUNCTIONCODE", "FUNCTIONDESC", "EMPLOYMENT", "BANKLOCKER", "GARMENTDISPENSER", "IDCODE", "SEQNUMBER", "ISSUEDATE", "WASHNO", "REPAIRNO", "REWASHNO", "FLAG", "UIFLAGCODE", "MODIFICATIONS", "REASON", "CUSTOMEROWNED", "FREEEXTRAGARMENT", "LASTSCANDATE", "LASTOUTSCANDATE", "FINMETHOD", "FINMETHODDESC", "INVOICEAMOUNTDECIMALS", "RESIDUALVALUE", "FLAGCODE", "STAY", "STAYNR", "STATUS", "ADMINNUMBER", "COSTCENTERCODE", "COSTCENTERDESC", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEFAULTBUSINESSUNIT_ID", "CITY", "WEARERNUMBER", "WEARERNAME", "WEARERSEARCHNAME", "WEARERACTIVE", "WEARERDATEACTIVE", "WEARERDATEINACTIVE", "LANGUAGECODE", "LANGUAGE_ID", "CUSTOMERLANGUAGE_ID", "SUBSTITUTEYN", "QUALITYGRADE_CODE", "LEASEWEEKS", "BU_CODE", "BU_DESC") AS 
  select
  prd.code productcode
, sz.code sizecode
, ( SELECT description FROM product_desc pd WHERE pd.product_id = prd.product_id
  AND pd.LANGUAGE_ID = languages.LANGUAGE_ID) productdesc
, wf.code functioncode, wf.description functiondesc, wey.sequencenumber employment
, cast(CONCATENATEWITHBLANK(lk.bank, lk.locker) as varchar2(255)) banklocker
, gd.code garmentdispenser, uq.primaryid idcode, uq.idcodesequencenumber seqnumber
, uqfx.lastissuedate issuedate, uq.washestotal washno, uq.repairstotal repairno, uq.rewashtotal rewashno
, ( SELECT COUNT(*) FROM UNIQUEITEMFLAG uf WHERE uf.UNIQUEITEM_ID = uq.UNIQUEITEM_ID) flag
, ( SELECT max(fg.code) FROM UNIQUEITEMFLAG uf, flag fg WHERE uf.UNIQUEITEM_ID = uq.UNIQUEITEM_ID and uf.flag_id = fg.flag_id) uiflagcode
, ( select count(*) from uniqueitemmodification um where um.uniqueitem_id=uq.uniqueitem_id) modifications
, r.code reason, uq.customerowned, uqnp.freeextragarment
, trunc(uq.lastscandate) lastscandate, trunc(uq.lastoutscandate) lastoutscandate
, fm.code finmethod
, (select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
     and fmd.language_id = languages.language_id) finmethoddesc
, currency.invoiceamountdecimals, uq.residualvalueAmount residualvalue, flag.code flagcode
, ( SELECT cast(sty.description as varchar2(10)) FROM stay_desc sty WHERE sty.stay_id = stay.stay_id
  AND sty.LANGUAGE_ID = languages.LANGUAGE_ID) stay, stay.staynr
, ( SELECT description FROM status_desc sd WHERE sd.status_id = uq.status_id
  AND sd.LANGUAGE_ID = languages.LANGUAGE_ID) status
, we.customeremployeenumber adminnumber,  cc.code costcentercode, cc.description costcenterdesc
, de.departmentnumber, de.description departmentdesc
, cu.customernumber, cu.name customername, cu.defaultbusinessunit_id, address.city
, we.wearernumber, we.fullname wearername, we.searchname wearersearchname
, GETDATEDIFF(trunc(sysdate), we.dateactive)*GETDATEDIFF(we.dateinactive, trunc(sysdate)) weareractive
, we.dateactive WearerDateActive, we.dateinactive WearerDateInactive
, languages.code languagecode, languages.language_id, cu.language_id customerlanguage_id
, case when uq.substituteforproduct_id is null then 'N' else 'Y' end substituteYN
, coalesce(qg.code, '') QualityGrade_Code
, uq.leaseweeks leaseWeeks
, (select code from businessunit where businessunit_id = cu.defaultbusinessunit_id) BU_code
, (select description from businessunit where businessunit_id = cu.defaultbusinessunit_id) BU_desc
from
  customer cu
, wearer we
    left outer join flag on we.flag_id = flag.flag_id
, weareremployment wey
    left outer join garmentdispenser gd on gd.garmentdispenser_id = wey.garmentdispenser_id
    left outer join locker lk on lk.locker_id = wey.locker_id
    left outer join wearerfunction wf on wey.wearerfunction_id = wf.wearerfunction_id
, uniqueitemnonpool uqnp
, uniqueitem uq
    left outer join stay on uq.stay_id = stay.stay_id
    left outer join finishingmethod fm on fm.finishingmethod_id = uq.finishingmethod_id
, uniqueitemfixedinfo uqfx
    left outer join qualitygrade qg on uqfx.qualitygrade_id=qg.qualitygrade_id
, reasoncode r
, product prd,  sizedefinition sz
, distributionpoint dip, department de, costcenter cc
, address, currency, languages
where
    cu.customer_id = we.customer_id
and we.wearer_id = wey.wearer_id
and wey.weareremployment_id = uqnp.weareremployment_id
and uqnp.uniqueitem_id = uq.uniqueitem_id
    and uq.uniqueitem_id = uqfx.uniqueitem_id
        and uqfx.reasoncode_id = r.reasoncode_id
and uq.product_id = prd.product_id
and uq.sizedefinition_id = sz.sizedefinition_id
and wey.distributionpoint_id = dip.distributionpoint_id
    and dip.department_id = de.department_id
        and dip.costcenter_id = cc.costcenter_id
and cu.mailaddress_id = address.address_id
and cu.currency_id = currency.currency_id
Union all
select
  coalesce(subtPrd.Code, prd.code) productcode
, coalesce(subtSz.Code, sz.code) sizecode
, coalesce(
  ( SELECT description FROM product_desc WHERE product_desc.product_id = subtPrd.product_id
  AND product_desc.LANGUAGE_ID = languages.LANGUAGE_ID )
  , ( SELECT description FROM product_desc pd WHERE pd.product_id = prd.product_id
  AND pd.LANGUAGE_ID = languages.LANGUAGE_ID)
  ) productdesc
, wf.code functioncode, wf.description functiondesc, wey.sequencenumber employment
, cast(CONCATENATEWITHBLANK(lk.bank, lk.locker) as varchar2(255)) banklocker
, gd.code garmentdispenser, null idcode, nuq.sequencenumber seqnumber
, nuq.issuedate issuedate, null washno, null repairno, null rewashno, null flag, null uiflagcode
, ( SELECT count(*) FROM wearerinventorymodification wim WHERE wim.wearerinventory_id = weinv.wearerinventory_id) modifications
, rc.code reason, 'N' customerowned, 'X' freeextragarment
, null lastscandate, null lastoutscandate
, fm.code finmethod
, (select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
     and fmd.language_id = languages.language_id) finmethoddesc
, currency.invoiceamountdecimals, 0 residualvalue, flag.code flagcode
, null stay, null staynr, null status
, we.customeremployeenumber adminnumber, cc.code costcentercode, cc.description costcenterdesc
, de.departmentnumber, de.description departmentdesc
, cu.customernumber, cu.name customername, cu.defaultbusinessunit_id, address.city
, we.wearernumber, we.fullname wearername, we.searchname wearersearchname
, GETDATEDIFF(trunc(sysdate), we.dateactive)*GETDATEDIFF(we.dateinactive, trunc(sysdate)) weareractive
, we.dateactive WearerDateActive, we.dateinactive WearerDateInactive
, languages.code languagecode, languages.language_id, cu.language_id customerlanguage_id
, case when nuq.substituteforproduct_id is null then 'N' else 'Y' end substituteYN
, '' QualityGrade_Code
, null leaseWeeks
, (select code from businessunit where businessunit_id = cu.defaultbusinessunit_id) BU_code
, (select description from businessunit where businessunit_id = cu.defaultbusinessunit_id) BU_desc
from
  customer cu
, wearer we
    left outer join flag  on we.flag_id = flag.flag_id
, weareremployment wey
    left outer join garmentdispenser gd on gd.garmentdispenser_id = wey.garmentdispenser_id
    left outer join locker lk on lk.locker_id = wey.locker_id
    left outer join wearerfunction wf on wey.wearerfunction_id = wf.wearerfunction_id
, wearerinventory weinv
, nonuniqueitem nuq
    left outer join product subtPrd on subtPrd.product_id = nuq.substituteforproduct_id
    left outer join sizedefinition subtSz on subtSz.Sizedefinition_Id = nuq.substituteforsizedefinition_id
, product prd, sizedefinition sz, finishingmethod fm
, reasoncode rc
, distributionpoint dip, department de, costcenter cc
, address, currency, languages
where
    cu.customer_id = we.customer_id
and we.wearer_id = wey.wearer_id
and wey.weareremployment_id = weinv.weareremployment_id
AND weinv.product_id = prd.product_id
and weinv.sizedefinition_id = sz.sizedefinition_id
and weinv.finishingmethod_id = fm.finishingmethod_id
and weinv.wearerinventory_id = nuq.wearerinventory_id
    and nuq.reasoncode_id = rc.reasoncode_id
and wey.distributionpoint_id = dip.distributionpoint_id
    and dip.department_id = de.department_id
        and dip.costcenter_id = cc.costcenter_id
and cu.mailaddress_id = address.address_id
    and cu.currency_id = currency.currency_id
/

  CREATE OR REPLACE VIEW "V_GENERALDISCOUNTLIST" ("PRICETYPE", "CODE", "DESCRIPTION", "ACTIVE", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  SELECT
PRICETYPE, CODE,DESCRIPTION, ACTIVE, SYSTEMUSER_ID,TIMESTAMP
FROM
GENERALDISCOUNTLIST
/

  CREATE OR REPLACE VIEW "V_GENERALPRICELIST" ("PRICETYPE", "CODE", "DESCRIPTION", "ACTIVE", "AUTOPRICEUPDATE", "PRICEINDEXCODE", "CURRENCYCODE", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  SELECT
GENERALPRICELIST.PRICETYPE, GENERALPRICELIST.CODE, GENERALPRICELIST.DESCRIPTION,
GENERALPRICELIST.ACTIVE, GENERALPRICELIST.AUTOPRICEUPDATE,
GENERALPRICELIST.PRICEINDEXCODE, CURRENCY.CODE,
GENERALPRICELIST.SYSTEMUSER_ID, GENERALPRICELIST.TIMESTAMP
FROM GENERALPRICELIST, CURRENCY
 WHERE
 GENERALPRICELIST.CURRENCY_ID = CURRENCY.CURRENCY_ID
/

  CREATE OR REPLACE VIEW "V_GENERALRENTDISCOUNT" ("PRICETYPE", "CODE", "DESCRIPTION", "ACTIVE", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "TYPEOFRENT", "STARTDATE", "DISCOUNT", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT GENERALDISCOUNTLIST.PRICETYPE, GENERALDISCOUNTLIST.CODE, GENERALDISCOUNTLIST.DESCRIPTION,
 GENERALDISCOUNTLIST.ACTIVE,
 PRODUCT.CODE,
 (SELECT description FROM PRODUCT_DESC A WHERE A.PRODUCT_ID = GENERALRENTDISCOUNT.PRODUCT_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
 SIZEDEFINITION.CODE,
 (SELECT description FROM SIZEDEFINITION_DESC B WHERE B.SIZEDEFINITION_ID = GENERALRENTDISCOUNT.SIZEDEFINITION_ID
  AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) sizedefinitiondescription,
 FINISHINGMETHOD.CODE,
 (SELECT description FROM FINISHINGMETHOD_DESC C WHERE C.FINISHINGMETHOD_ID = GENERALRENTDISCOUNT.FINISHINGMETHOD_ID
  AND C.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddescription,
 GENERALRENTDISCOUNT.TYPEOFRENT,
 GENERALRENTDISCOUNT.STARTDATE,GENERALRENTDISCOUNT.DISCOUNT,
 GENERALRENTDISCOUNT.SYSTEMUSER_ID, GENERALRENTDISCOUNT.TIMESTAMP, LANGUAGES.CODE
FROM GENERALRENTDISCOUNT, GENERALDISCOUNTLIST, PRODUCT, SIZEDEFINITION, FINISHINGMETHOD, LANGUAGES
WHERE GENERALDISCOUNTLIST.GENERALDISCOUNTLIST_ID = GENERALRENTDISCOUNT.GENERALDISCOUNTLIST_ID
 AND GENERALRENTDISCOUNT.PRODUCT_ID = PRODUCT.PRODUCT_ID
 AND GENERALRENTDISCOUNT.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
 AND GENERALRENTDISCOUNT.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
/

  CREATE OR REPLACE VIEW "V_GENERALRENTPRICE" ("PRICETYPE", "CODE", "DESCRIPTION", "ACTIVE", "AUTOPRICEUPDATE", "PRICEINDEXCODE", "CURRENCYCODE", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "TYPEOFRENT", "CHANGESPERWEEK", "STARTDATE", "PRICE", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT
 GENERALPRICELIST.PRICETYPE, GENERALPRICELIST.CODE, GENERALPRICELIST.DESCRIPTION,
 GENERALPRICELIST.ACTIVE, GENERALPRICELIST.AUTOPRICEUPDATE,
 GENERALPRICELIST.PRICEINDEXCODE, CURRENCY.CODE,
 PRODUCT.CODE,
 (SELECT description FROM PRODUCT_DESC A WHERE A.PRODUCT_ID = GENERALRENTPRICE.PRODUCT_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
 SIZEDEFINITION.CODE,
 (SELECT description FROM SIZEDEFINITION_DESC B WHERE B.SIZEDEFINITION_ID = GENERALRENTPRICE.SIZEDEFINITION_ID
  AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) sizedefinitiondescription,
 FINISHINGMETHOD.CODE,
 (SELECT description FROM FINISHINGMETHOD_DESC C WHERE C.FINISHINGMETHOD_ID = GENERALRENTPRICE.FINISHINGMETHOD_ID
  AND C.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddescription,
 GENERALRENTPRICE.TYPEOFRENT, GENERALRENTPRICE.CHANGESPERWEEK,
 GENERALRENTPRICE.STARTDATE,GENERALRENTPRICE.PRICE,
 GENERALRENTPRICE.SYSTEMUSER_ID, GENERALRENTPRICE.TIMESTAMP, LANGUAGES.CODE
FROM GENERALPRICELIST, CURRENCY, PRODUCT, SIZEDEFINITION, FINISHINGMETHOD, GENERALRENTPRICE, LANGUAGES
WHERE GENERALPRICELIST.CURRENCY_ID = CURRENCY.CURRENCY_ID
 AND GENERALPRICELIST.GENERALPRICELIST_ID = GENERALRENTPRICE.GENERALPRICELIST_ID
 AND GENERALRENTPRICE.PRODUCT_ID = PRODUCT.PRODUCT_ID
 AND GENERALRENTPRICE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
 AND GENERALRENTPRICE.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
/

  CREATE OR REPLACE VIEW "V_GENERALREPLACEMENTPRICE" ("PRICETYPE", "CODE", "DESCRIPTION", "ACTIVE", "AUTOPRICEUPDATE", "PRICEINDEXCODE", "CURRENCYCODE", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESCRIPTION", "STARTDATE", "PRICE", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT
 GENERALPRICELIST.PRICETYPE, GENERALPRICELIST.CODE, GENERALPRICELIST.DESCRIPTION,
 GENERALPRICELIST.ACTIVE, GENERALPRICELIST.AUTOPRICEUPDATE,
 GENERALPRICELIST.PRICEINDEXCODE, CURRENCY.CODE,
 PRODUCT.CODE,
 (SELECT description FROM PRODUCT_DESC A WHERE A.PRODUCT_ID = GENERALREPLACEMENTPRICE.PRODUCT_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
 SIZEDEFINITION.CODE,
 (SELECT description FROM SIZEDEFINITION_DESC B WHERE B.SIZEDEFINITION_ID = GENERALREPLACEMENTPRICE.SIZEDEFINITION_ID
  AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) sizedefinitiondescription,
 GENERALREPLACEMENTPRICE.STARTDATE,GENERALREPLACEMENTPRICE.PRICE,
 GENERALREPLACEMENTPRICE.SYSTEMUSER_ID, GENERALREPLACEMENTPRICE.TIMESTAMP, LANGUAGES.CODE
FROM GENERALPRICELIST, CURRENCY, PRODUCT, SIZEDEFINITION, GENERALREPLACEMENTPRICE, LANGUAGES
WHERE GENERALPRICELIST.CURRENCY_ID = CURRENCY.CURRENCY_ID
 AND GENERALPRICELIST.GENERALPRICELIST_ID = GENERALREPLACEMENTPRICE.GENERALPRICELIST_ID
 AND GENERALREPLACEMENTPRICE.PRODUCT_ID = PRODUCT.PRODUCT_ID
 AND GENERALREPLACEMENTPRICE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
/

  CREATE OR REPLACE VIEW "V_GENERALSALESPRICE" ("PRICETYPE", "CODE", "DESCRIPTION", "ACTIVE", "AUTOPRICEUPDATE", "PRICEINDEXCODE", "CURRENCYCODE", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESCRIPTION", "STARTDATE", "PRICE", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT
 GENERALPRICELIST.PRICETYPE, GENERALPRICELIST.CODE, GENERALPRICELIST.DESCRIPTION,
 GENERALPRICELIST.ACTIVE, GENERALPRICELIST.AUTOPRICEUPDATE,
 GENERALPRICELIST.PRICEINDEXCODE, CURRENCY.CODE,
 PRODUCT.CODE,
 (SELECT description FROM PRODUCT_DESC A WHERE A.PRODUCT_ID = GENERALSALESPRICE.PRODUCT_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
 SIZEDEFINITION.CODE,
 (SELECT description FROM SIZEDEFINITION_DESC B WHERE B.SIZEDEFINITION_ID = GENERALSALESPRICE.SIZEDEFINITION_ID
  AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) sizedefinitiondescription,
 GENERALSALESPRICE.STARTDATE,GENERALSALESPRICE.PRICE,
 GENERALSALESPRICE.SYSTEMUSER_ID, GENERALSALESPRICE.TIMESTAMP, LANGUAGES.CODE
FROM GENERALPRICELIST, CURRENCY, PRODUCT, SIZEDEFINITION, GENERALSALESPRICE, LANGUAGES
WHERE GENERALPRICELIST.CURRENCY_ID = CURRENCY.CURRENCY_ID
 AND GENERALPRICELIST.GENERALPRICELIST_ID = GENERALSALESPRICE.GENERALPRICELIST_ID
 AND GENERALSALESPRICE.PRODUCT_ID = PRODUCT.PRODUCT_ID
 AND GENERALSALESPRICE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
/

  CREATE OR REPLACE VIEW "V_GENERALWASHDISCOUNT" ("PRICETYPE", "CODE", "DESCRIPTION", "ACTIVE", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "STARTDATE", "DISCOUNT", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT GENERALDISCOUNTLIST.PRICETYPE, GENERALDISCOUNTLIST.CODE, GENERALDISCOUNTLIST.DESCRIPTION,
 GENERALDISCOUNTLIST.ACTIVE,
 PRODUCT.CODE,
 (SELECT description FROM PRODUCT_DESC A WHERE A.PRODUCT_ID = GENERALWASHDISCOUNT.PRODUCT_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
 SIZEDEFINITION.CODE,
 (SELECT description FROM SIZEDEFINITION_DESC B WHERE B.SIZEDEFINITION_ID = GENERALWASHDISCOUNT.SIZEDEFINITION_ID
  AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) sizedefinitiondescription,
 FINISHINGMETHOD.CODE,
 (SELECT description FROM FINISHINGMETHOD_DESC C WHERE C.FINISHINGMETHOD_ID = GENERALWASHDISCOUNT.FINISHINGMETHOD_ID
  AND C.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddescription,
 GENERALWASHDISCOUNT.STARTDATE,GENERALWASHDISCOUNT.DISCOUNT,
 GENERALWASHDISCOUNT.SYSTEMUSER_ID, GENERALWASHDISCOUNT.TIMESTAMP, LANGUAGES.CODE
FROM GENERALWASHDISCOUNT, GENERALDISCOUNTLIST, PRODUCT, SIZEDEFINITION, FINISHINGMETHOD, LANGUAGES
WHERE GENERALDISCOUNTLIST.GENERALDISCOUNTLIST_ID = GENERALWASHDISCOUNT.GENERALDISCOUNTLIST_ID
 AND GENERALWASHDISCOUNT.PRODUCT_ID = PRODUCT.PRODUCT_ID
 AND GENERALWASHDISCOUNT.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
 AND GENERALWASHDISCOUNT.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
/

  CREATE OR REPLACE VIEW "V_GENERALWASHPRICE" ("PRICETYPE", "CODE", "DESCRIPTION", "ACTIVE", "AUTOPRICEUPDATE", "PRICEINDEXCODE", "CURRENCYCODE", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "STARTDATE", "PRICE", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT
 GENERALPRICELIST.PRICETYPE, GENERALPRICELIST.CODE, GENERALPRICELIST.DESCRIPTION,
 GENERALPRICELIST.ACTIVE, GENERALPRICELIST.AUTOPRICEUPDATE,
 GENERALPRICELIST.PRICEINDEXCODE, CURRENCY.CODE,
 PRODUCT.CODE,
 (SELECT description FROM PRODUCT_DESC A WHERE A.PRODUCT_ID = GENERALWASHPRICE.PRODUCT_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
 SIZEDEFINITION.CODE,
 (SELECT description FROM SIZEDEFINITION_DESC B WHERE B.SIZEDEFINITION_ID = GENERALWASHPRICE.SIZEDEFINITION_ID
  AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) sizedefinitiondescription,
 FINISHINGMETHOD.CODE,
 (SELECT description FROM FINISHINGMETHOD_DESC C WHERE C.FINISHINGMETHOD_ID = GENERALWASHPRICE.FINISHINGMETHOD_ID
  AND C.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddescription,
 GENERALWASHPRICE.STARTDATE,GENERALWASHPRICE.PRICE,
 GENERALWASHPRICE.SYSTEMUSER_ID, GENERALWASHPRICE.TIMESTAMP, LANGUAGES.CODE
FROM GENERALPRICELIST, CURRENCY, PRODUCT, SIZEDEFINITION, FINISHINGMETHOD, GENERALWASHPRICE, LANGUAGES
WHERE GENERALPRICELIST.CURRENCY_ID = CURRENCY.CURRENCY_ID
 AND GENERALPRICELIST.GENERALPRICELIST_ID = GENERALWASHPRICE.GENERALPRICELIST_ID
 AND GENERALWASHPRICE.PRODUCT_ID = PRODUCT.PRODUCT_ID
 AND GENERALWASHPRICE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
 AND GENERALWASHPRICE.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
/

  CREATE OR REPLACE VIEW "V_GENERALWEIGHTDISCOUNT" ("PRICETYPE", "CODE", "DESCRIPTION", "ACTIVE", "WEIGHINGCATEGORYCODE", "WEIGHINGCATEGORYDESCRIPTION", "SOIL", "STARTDATE", "DISCOUNT", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT GENERALDISCOUNTLIST.PRICETYPE, GENERALDISCOUNTLIST.CODE, GENERALDISCOUNTLIST.DESCRIPTION,
 GENERALDISCOUNTLIST.ACTIVE,
 WEIGHINGCATEGORY.CODE,
 (SELECT description FROM WEIGHINGCATEGORY_DESC A WHERE A.WEIGHINGCATEGORY_ID = GENERALWEIGHTDISCOUNT.WEIGHINGCATEGORY_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) weighingcategorydescription,
 GENERALWEIGHTDISCOUNT.SOIL,
 GENERALWEIGHTDISCOUNT.STARTDATE,GENERALWEIGHTDISCOUNT.DISCOUNT,
 GENERALWEIGHTDISCOUNT.SYSTEMUSER_ID, GENERALWEIGHTDISCOUNT.TIMESTAMP, LANGUAGES.CODE
FROM GENERALDISCOUNTLIST, WEIGHINGCATEGORY, GENERALWEIGHTDISCOUNT, LANGUAGES
WHERE GENERALDISCOUNTLIST.GENERALDISCOUNTLIST_ID = GENERALWEIGHTDISCOUNT.GENERALDISCOUNTLIST_ID
 AND GENERALWEIGHTDISCOUNT.WEIGHINGCATEGORY_ID = WEIGHINGCATEGORY.WEIGHINGCATEGORY_ID
/

  CREATE OR REPLACE VIEW "V_GENERALWEIGHTPRICE" ("PRICETYPE", "CODE", "DESCRIPTION", "ACTIVE", "AUTOPRICEUPDATE", "PRICEINDEXCODE", "CURRENCYCODE", "WEIGHINGCATEGORYCODE", "WEIGHINGCATEGORYDESCRIPTION", "SOIL", "STARTDATE", "PRICE", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT
 GENERALPRICELIST.PRICETYPE, GENERALPRICELIST.CODE, GENERALPRICELIST.DESCRIPTION,
 GENERALPRICELIST.ACTIVE, GENERALPRICELIST.AUTOPRICEUPDATE,
 GENERALPRICELIST.PRICEINDEXCODE, CURRENCY.CODE,
 WEIGHINGCATEGORY.CODE,
 (SELECT description FROM WEIGHINGCATEGORY_DESC A WHERE A.WEIGHINGCATEGORY_ID = GENERALWEIGHTPRICE.WEIGHINGCATEGORY_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) weighingcategorydescription,
 GENERALWEIGHTPRICE.SOIL,
 GENERALWEIGHTPRICE.STARTDATE,GENERALWEIGHTPRICE.PRICE,
 GENERALWEIGHTPRICE.SYSTEMUSER_ID, GENERALWEIGHTPRICE.TIMESTAMP, LANGUAGES.CODE
FROM GENERALPRICELIST, CURRENCY, WEIGHINGCATEGORY, GENERALWEIGHTPRICE, LANGUAGES
WHERE GENERALPRICELIST.CURRENCY_ID = CURRENCY.CURRENCY_ID
 AND GENERALPRICELIST.GENERALPRICELIST_ID = GENERALWEIGHTPRICE.GENERALPRICELIST_ID
 AND GENERALWEIGHTPRICE.WEIGHINGCATEGORY_ID = WEIGHINGCATEGORY.WEIGHINGCATEGORY_ID
/

  CREATE OR REPLACE VIEW "V_GMDGARMENTCOLLECTIONLIST" ("LINETYPE", "DELIVERYLOAD_ID", "DELIVERYLOAD_CODE", "DELIVERYDATE", "PLANTDEP_CODE", "PLANTDEP_DESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "WEARERNAME", "DELIVERYPOINT_CODE", "DELIVERYPOINT_DESC", "PRODUCT_CODE", "SEQUENCENUMBER", "SIZE_CODE", "STAYTYPE", "STAYNR", "PRODUCT_DESC", "SIZE_DESC", "STAY_DESC", "TODELIVERQUANTITY", "PERSONALIZEDAVAILABLEQTY", "PRIMARYID", "LANGUAGE_CODE", "LANGUAGE_ID") AS 
  select 1 linetype, --POOL
       dl.deliveryload_id, dl.code deliveryload_code, dl.deliverydate,
       pld.Code PlantDep_code, pld.Description PlantDep_desc,
       cu.CustomerNumber, cu.Name CustomerName, w.wearernumber, w.fullname WearerName,
       dp.Code deliverypoint_code, dp.Description deliverypoint_desc,
       pr.code Product_Code, ps.sequencenumber, sd.code Size_Code, null staytype, null staynr,
       (select prd.description from product_desc prd where prd.product_id = pr.product_id and prd.language_id = lan.language_id) Product_Desc,
       (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sd.sizedefinition_id and sdd.language_id = lan.language_id) Size_Desc,
       null Stay_Desc,
       DLd.Todeliverquantity, DLd.PersonalizedAvailableQty, null primaryid,
       lan.code language_code, lan.language_id
from DeliveryLoad DL
     inner join DeliveryLoadDetail DLD
           inner join WearerInventory WI
                 inner join WearerEmployment WE
                       inner join Wearer w on we.wearer_id = w.wearer_id
                 on wi.weareremployment_id = we.weareremployment_id
                 inner join product pr on wi.product_id = pr.product_id
                 inner join productsize ps on wi.product_id = ps.product_id and wi.sizedefinition_id = ps.sizedefinition_id
                 inner join sizedefinition sd on wi.sizedefinition_id = sd.sizedefinition_id
           on dld.wearerinventory_id = wi.wearerinventory_id
     on dl.deliveryload_id = dld.deliveryload_id
     inner join deliverypoint dp
           inner join customer cu on dp.customer_id = cu.customer_id
     on dl.deliverypoint_id = dp.deliverypoint_id
     left outer join plantdepartment pld on dl.plantdepartment_id = pld.plantdepartment_id
, languages lan
where DLD.TODELIVERQUANTITY > DLD.PersonalizedAvailableQty
union all  --Personalized Garments
select 2 linetype, dl.deliveryload_id, dl.code deliveryload_code, dl.deliverydate,
       pld.Code PlantDep_code, pld.Description PlantDep_desc,
       cu.CustomerNumber, cu.Name CustomerName, w.wearernumber, w.fullname WearerName,
       dp.Code deliverypoint_code, dp.Description deliverypoint_desc,
       pr.code Product_Code, ps.sequencenumber, sd.code Size_Code, st.staytype, st.staynr,
       (select prd.description from product_desc prd where prd.product_id = pr.product_id and prd.language_id = lan.language_id) Product_Desc,
       (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sd.sizedefinition_id and sdd.language_id = lan.language_id) Size_Desc,
       (select std.description from Stay_Desc std where std.stay_id = st.stay_id and std.language_id = lan.language_id) Stay_Desc,
       DLd.Todeliverquantity, DLd.PersonalizedAvailableQty, ui.primaryid,
       lan.code language_code, lan.language_id
from DeliveryLoad DL
     inner join DeliveryLoadDetail DLD
           inner join WearerInventory WI
                 inner join WearerEmployment WE
                       inner join Wearer w on we.wearer_id = w.wearer_id
                 on wi.weareremployment_id = we.weareremployment_id
                 inner join product pr on wi.product_id = pr.product_id
                 inner join productsize ps on wi.product_id = ps.product_id and wi.sizedefinition_id = ps.sizedefinition_id
                 inner join sizedefinition sd on wi.sizedefinition_id = sd.sizedefinition_id
                 inner join UniqueItemNonPool UINP
                      inner join UniqueItem UI
                           inner join stay st on ui.stay_id = st.stay_id
                      on UINP.uniqueitem_id = ui.uniqueitem_id
                 on WI.WEARERINVENTORY_ID = UINP.Wearerinventory_Id
           on dld.wearerinventory_id = wi.wearerinventory_id
     on dl.deliveryload_id = dld.deliveryload_id
     inner join deliverypoint dp
           inner join customer cu on dp.customer_id = cu.customer_id
     on dl.deliverypoint_id = dp.deliverypoint_id
     left outer join plantdepartment pld on dl.plantdepartment_id = pld.plantdepartment_id
, languages lan
where DLD.TODELIVERQUANTITY > DLD.PersonalizedAvailableQty
      and st.staynr in (10, 31, 32, 36, 40)--Stockroom, Rewash, Repair, Late, OnShelf
/

  CREATE OR REPLACE VIEW "V_GRADINGSUMMARY" ("SYSTEMUSER_ID", "OUTOFCIRCDATE", "RAGREASON_ID", "QUANTITY", "BU_CODE", "PLANT_CODE", "PLANT_NAME", "STOCKROOM_CODE", "STOCKROOM_DESC", "PRODUCTGROUP_CODE", "PRODUCTGROUP_DESC", "MARKETSEGMENT_CODE", "PRODUCT_CODE", "PRODUCT_DESC", "PRIORITY", "QUALITYGRADE_DESC", "EXPECTEDRETURNPERCENTAGE", "RAGGEDRETURNPERCENTAGE", "LANGUAGE_CODE", "OUTOFCIRCULATIONHISTORY_ID") AS 
  SELECT su.systemuser_id, och.outofcircdate, och.ragreason_id, och.quantity
, bu.code BU_Code, pl.code Plant_Code, pl.name Plant_Name
, (SELECT sr.code FROM stockroom sr WHERE sr.stockroom_id = och.stockroom_id) StockRoom_Code
, (SELECT sr.name FROM stockroom sr WHERE sr.stockroom_id = och.stockroom_id) StockRoom_Desc
, (SELECT pg.code FROM productgroup pg WHERE pg.productgroup_id = p.productgroup_id) ProductGroup_Code
, (SELECT pgd.description FROM productgroup_desc pgd WHERE pgd.productgroup_id = p.productgroup_id AND pgd.language_id = lan.language_id) ProductGroup_Desc
, (SELECT ms.code FROM customer cu, marketsegment ms WHERE och.customer_link_id = cu.customer_id AND cu.marketsegment_id = ms.marketsegment_id) MarketSegment_Code
, p.code Product_Code
, (SELECT pd.description FROM product_desc pd WHERE pd.product_id = p.product_id AND pd.language_id = lan.language_id) Product_Desc
, coalesce((SELECT qg.priority FROM qualitygrade qg WHERE och.qualitygrade_id = qg.qualitygrade_id), 10) Priority
, (SELECT qgd.description FROM qualitygrade_desc qgd WHERE och.qualitygrade_id = qgd.qualitygrade_id AND qgd.language_id = lan.language_id) QualityGrade_Desc
, (SELECT pqs.expectedreturnpercentage FROM plantqualitygradesettings pqs WHERE pqs.plant_id = pl.plant_id AND pqs.qualitygrade_id = och.qualitygrade_id) ExpectedReturnPercentage
, (SELECT sum(pqs2.expectedreturnpercentage) FROM plantqualitygradesettings pqs2 WHERE pqs2.plant_id = pl.plant_id) RaggedReturnPercentage
, lan.code Language_Code, och.outofcirculationhistory_id
FROM Outofcirculationhistory och LEFT OUTER JOIN product p ON och.product_link_id = p.product_id
     , businessunit bu, plant pl, Systemuser su, businessunitsperusergroup bug, languages lan
WHERE och.uniqueitem_link_id IS NOT NULL AND och.customerowned = 'N'
      AND bu.businessunit_id = och.processbusinessunit_id AND bu.plant_id = pl.plant_id
      AND bug.usergroup_id = su.usergroup_id AND bug.businessunit_id= och.processbusinessunit_id
      AND och.chargetype = 1
/

  CREATE OR REPLACE VIEW "V_HOURLYPRODUCTION" ("WEIGHINGCATEGORYCODE", "DELIVERYDATE", "DELIVERYDATE_CHAR", "DELIVERYTIME", "NETWEIGHT", "PACKINGNOTE_ID", "CONTAINER_ID", "PLANTNAME") AS 
  select wc.code weighingcategorycode, --weight shipped
       pn.processedtimestamp deliverydate, --de aici se ia si container id (1sg knt per DN)
       to_char(pn.processedtimestamp) deliverydate_char,
       to_char(pn.processedtimestamp,'fmhh24fm:MI:SS') deliverytime,
       (pnc.grossweight - pnc.tareweight) netweight,
       pn.packingnote_id, 0 container_id,
       (select p.name from plant p, businessunit bu where p.plant_id = bu.plant_id and bu.businessunit_id = pn.processbusinessunit_id) plantname
from weighingcategory_link wc,
     packingnote pn,
     packingnotecontainer pnc
where pn.packingnote_id = pnc.packingnote_id
      and pnc.weighingcategory_id = wc.weighingcategory_id
      and pn.status_id = (select s.status_id from status s where s.statustype = 'PN' and s.code = '30')
      and pnc.weighingtimestamp is not null
union all
select distinct 'STD' weighingcategorycode, --PN shipped
       pn.processedtimestamp deliverydate,
       to_char(pn.processedtimestamp) deliverydate_char,
       to_char(pn.processedtimestamp,'fmhh24fm:MI:SS') deliverytime,
       0netweight,
       pn.packingnote_id, null container_id,
       (select p.name from plant p, businessunit bu where p.plant_id = bu.plant_id and bu.businessunit_id = pn.processbusinessunit_id) plantname
from weighingcategory_link wc,
     packingnote pn,
     packingnotecontainer pnc
where pn.packingnote_id = pnc.packingnote_id
      and pnc.weighingcategory_id = wc.weighingcategory_id
      and pn.status_id = (select s.status_id from status s where s.statustype = 'PN' and s.code = '30')
      and pnc.weighingtimestamp is not null
      and wc.code in ('101','105','201','205')
union all
select distinct 'OR' weighingcategorycode, --number of PN shipped
       pn.processedtimestamp deliverydate,
       to_char(pn.processedtimestamp) deliverydate_char,
       to_char(pn.processedtimestamp,'fmhh24fm:MI:SS') deliverytime,
       0netweight,
       pn.packingnote_id, null container_id,
       (select p.name from plant p, businessunit bu where p.plant_id = bu.plant_id and bu.businessunit_id = pn.processbusinessunit_id) plantname
from weighingcategory_link wc,
     packingnote pn,
     packingnotecontainer pnc
where pn.packingnote_id = pnc.packingnote_id
      and pnc.weighingcategory_id = wc.weighingcategory_id
      and pn.status_id = (select s.status_id from status s where s.statustype = 'PN' and s.code = '30')
      and pnc.weighingtimestamp is not null
      and wc.code in ('102','103','202','203')
union all
select distinct 'COG' weighingcategorycode, --PN shipped
       pn.processedtimestamp deliverydate,
       to_char(pn.processedtimestamp) deliverydate_char,
       to_char(pn.processedtimestamp,'fmhh24fm:MI:SS') deliverytime,
       0netweight,
       pn.packingnote_id, null container_id,
       (select p.name from plant p, businessunit bu where p.plant_id = bu.plant_id and bu.businessunit_id = pn.processbusinessunit_id) plantname
from weighingcategory_link wc,
     packingnote pn,
     packingnotecontainer pnc
where pn.packingnote_id = pnc.packingnote_id
      and pnc.weighingcategory_id = wc.weighingcategory_id
      and pn.status_id = (select s.status_id from status s where s.statustype = 'PN' and s.code = '30')
      and pnc.weighingtimestamp is not null
      and wc.code in ('100','104','106','204','206')
union all
select '-1' weighingcategorycode, --soil received and knt received from weighing tickets (as in rpt recorded weights )
       wt.processedtimestamp deliverydate,
       to_char(wt.processedtimestamp) deliverydate_char,
       to_char(wt.processedtimestamp,'fmhh24fm:MI:SS') deliverytime,
       (wtl.grossweight - wtl.tareweight) netweight,
       null packingnote_id, wtl.container_id,
       (select p.name from plant p, businessunit bu where p.plant_id = bu.plant_id and bu.businessunit_id = wt.processbusinessunit_id) plantname
from weighingticket wt, weighingticketline wtl
where wt.weighingticket_id = wtl.weighingticket_id
      and wt.soilticket = 'Y'
      and wt.status_id = (select s.status_id from status s where s.statustype = 'WN' and s.code = '30')
union all
select '-2' weighingcategorycode, --packs assembled
       u.assembletimestamp deliverydate,
       to_char(u.assembletimestamp) deliverydate_char,
       to_char(u.assembletimestamp,'fmhh24fm:MI:SS') deliverytime,
       0 netweight,
       u.uniqueitem_id packingnote_id, null container_id,
       (select p.name from plant p, businessunit bu, uniqueitem ui
        where p.plant_id = bu.plant_id
              and u.uniqueitem_id = ui.uniqueitem_id
              and bu.businessunit_id = ui.businessunit_id) plantname
from uniqueorpack u
where u.assembleemployee_id is not null
union all
select '-3' weighingcategorycode, --packs sterilized
       us.sterilizationtimestamp deliverydate,
       to_char(us.sterilizationtimestamp) deliverydate_char,
       to_char(us.sterilizationtimestamp,'fmhh24fm:MI:SS') deliverytime,
       0 netweight,
       us.uniqueitem_id packingnote_id, us.sterilizationrun_id container_id,
       (select p.name from plant p, businessunit bu, uniqueitem ui
        where p.plant_id = bu.plant_id
              and us.uniqueitem_id = ui.uniqueitem_id
              and bu.businessunit_id = ui.businessunit_id) plantname
from uniqueorpacksterile us
union all
select '-4' weighingcategorycode,--hourly fill rate
       pn.processedtimestamp deliverydate,
       to_char(pn.processedtimestamp) deliverydate_char,
       to_char(pn.processedtimestamp,'fmhh24fm:MI:SS') deliverytime,
       0 netweight,
       pnl.tobedeliveredamount packingnote_id, pnl.deliveredamount container_id,
       (select p.name from plant p, businessunit bu where p.plant_id = bu.plant_id and bu.businessunit_id = pn.processbusinessunit_id) plantname
from packingnote pn, packingnoteline pnl
where pn.packingnote_id = pnl.packingnote_id
      and pn.status_id = (select s.status_id from status s where s.statustype = 'PN' and s.code = '30')
      and exists (select 1 from packingnotecontainer pnc where pnc.packingnote_id = pn.packingnote_id)
union all
select '-5' weighingcategorycode, --containers shipped
       pn.processedtimestamp deliverydate, --de aici se ia si container id (1sg knt per DN)
       to_char(pn.processedtimestamp) deliverydate_char,
       to_char(pn.processedtimestamp,'fmhh24fm:MI:SS') deliverytime,
       0 netweight,
       pn.packingnote_id packingnote_id,
       (select max(pnc.container_id) from packingnotecontainer pnc where pnc.packingnote_id = pn.packingnote_id) container_id,
       (select p.name from plant p, businessunit bu where p.plant_id = bu.plant_id and bu.businessunit_id = pn.processbusinessunit_id) plantname
from packingnote pn
where pn.status_id = (select s.status_id from status s where s.statustype = 'PN' and s.code = '30')
union all
select '-6' weighingcategorycode,--pn shipped
       pn.processedtimestamp deliverydate,
       to_char(pn.processedtimestamp) deliverydate_char,
       to_char(pn.processedtimestamp,'fmhh24fm:MI:SS') deliverytime,
       0 netweight,
       pn.packingnote_id, null container_id,
       (select p.name from plant p, businessunit bu where p.plant_id = bu.plant_id and bu.businessunit_id = pn.processbusinessunit_id) plantname
from packingnote pn
where pn.status_id = (select s.status_id from status s where s.statustype = 'PN' and s.code = '30')
/

  CREATE OR REPLACE VIEW "V_IMPORTDELNOTEERRORLIST" ("ABSLOGPROCESSJOB_ID", "ABSLOGPROCESSJOBPART_ID", "ABSLOGPROCESSJOBLINE_ID", "DATE_PJ", "TIMESTAMP", "MESSAGE") AS 
  select pj.abslogprocessjob_id,
       pjp.abslogprocessjobpart_id,
       pjl.abslogprocessjobline_id,
       pj.starttimestamp date_pj,
       pjl.timestamp,
       pjl.message
  from abslogprocessjob     pj,
       abslogprocessjobpart pjp,
       abslogprocessjobline pjl
 where pj.abslogprocessjob_id = pjp.abslogprocessjob_id
   and pjp.abslogprocessjobpart_id = pjl.abslogprocessjobpart_id
/

  CREATE OR REPLACE VIEW "V_INBOUNDSTOCKINVENTORY" ("CHIPSNUMERO", "CUSTNR", "YEARNR", "MONTHNR", "WEEKNR", "GARMENTCODE", "SIZECODE", "QUALITYCODE") AS 
  select u.primaryid chipsnumero,
       decode(u.lastdistributionpoint_link_id,
              null,
              (select c.customernumber
                 from weareremployment we, customer c, wearer w
                where we.weareremployment_id = u.lastweareremployment_link_id
                  and we.wearer_id = w.wearer_id
                  and w.customer_id = c.customer_id),
              (select c1.customernumber
                 from distributionpoint dip, department dept, customer c1
                where dip.distributionpoint_id =
                      u.lastdistributionpoint_link_id
                  and dip.department_id = dept.department_id
                  and dept.customer_id = c1.customer_id)) custnr,
       to_char(uif.firstissuedate, 'YYYY') yearnr,
       to_char(uif.firstissuedate, 'MM') monthnr,
       to_char(uif.firstissuedate, 'WW') weeknr,
       (select p.code from product p where p.product_id = u.product_id) garmentcode,
       (select sz.code
          from sizedefinition sz
         where sz.sizedefinition_id = u.sizedefinition_id) sizecode,
       (select q.code
          from qualitygrade q
         where uif.qualitygrade_id = q.qualitygrade_id) qualitycode
  from uniqueitem u, status s, stay st, uniqueitemfixedinfo uif
 where u.status_id = s.status_id
   and s.statustype = 'UI'
   and s.code = '10'
   and u.stay_id = st.stay_id
   and st.staytype = 1
   and st.staynr = 10
   and uif.uniqueitem_id = u.uniqueitem_id
/

  CREATE OR REPLACE VIEW "V_INBOUNDSTOCKSCANS" ("SCANDATE", "BARCODE", "YEARNR", "WEEKNR", "CUSTNR", "DEPTNR", "DAYNR", "PRODUCTCODE", "MUTATIONCODE") AS 
  select to_char(s.ScanTimeStamp, 'DD-MM-YYYY') scandate,
       s.primaryid barcode,
       s.year yearnr,
       s.week weeknr,
       decode(s.customer_link_id,
              null,
              0,
              (select c.customernumber
                 from customer c
                where c.customer_id = s.customer_link_id)) custnr,
       decode(s.distributionpoint_link_id,
              null,
              decode(s.weareremployment_link_id,
                     null,
                     0,
                     (select dept.departmentnumber
                        from weareremployment  we,
                             distributionpoint dip,
                             department        dept
                       where we.weareremployment_id =
                             s.weareremployment_link_id
                         and we.distributionpoint_id =
                             dip.distributionpoint_id
                         and dip.department_id = dept.department_id)),
              (select dept1.departmentnumber
                 from distributionpoint dip1, department dept1
                where dip1.distributionpoint_id = s.distributionpoint_link_id
                  and dip1.department_id = dept1.department_id)) deptnr,
       s.dayno daynr,
       (select p.code from product p where s.product_link_id = p.product_id) productcode,
       (select r.code
          from reasoncode r
         where r.reasoncode_id = s.reasoncode_id) mutationcode
  from scan s, transactiontype t
 where s.transactiontype_id = t.transactiontype_id
   and t.transactiontype_id in
       (10, 11, 12, 13, 15, 16, 22, 23, 32, 33, 40, 41, 44, 50, 54, 84, 93, 401, 402, 403, 404, 405, 406, 407, 408, 601)
/

  CREATE OR REPLACE VIEW "V_INCIDENTALINVENTORY" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESCR", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "PRODUCTCODE", "PRODUCTDESC", "INVENTORYDATE", "COUNTED", "AVERAGE", "STARTDATE", "ENDDATE", "NUMBEROFDELIVERIESSTOPPED", "STATUS", "LANGUAGECODE") AS 
  SELECT c.customernumber, c.name customername, c.customer_id
, d.departmentnumber, d.description departmentdescr
, dp.distributionpointnumber, dp.description distributionpointdesc
, p.code productCode
,(select psc.description from product_desc psc where psc.product_id = p.product_id and psc.language_id = l.language_id) productDesc
, ii.inventorydate, ii.counted, ii.Average, ii.StartDate, ii.EndDate, ii.NumberOfDeliveriesStopped, ii.status, l.code languagecode
from customer c, department d, distributionpoint dp, product p, incidentalinventory ii, languages l
where dp.department_id = d.department_id and d.customer_id = c.customer_id and ii.product_id = p.product_id
      and ii.customer_id = c.customer_id and ii.distributionpoint_id = dp.distributionpoint_id and ii.status = 1
/

  CREATE OR REPLACE VIEW "V_INDIVIDUALPRODUCTDELIVERY" ("INVOICEBUSINESSUNIT_ID", "BU_CODE", "BU_DESC", "PLANT_ID", "PL_CODE", "PL_NAME", "INVOICEDATE", "INVOICELINETYPE", "TURNOVERGROUP_CODE", "TURNOVERGROUP_DESC", "PRODUCT_DESC", "PRODUCT_CODE", "PRODUCTGROUPCODE", "PRODUCTGROUPDESCRIPTION", "ROUTENUMBER", "AMOUNT", "QUANTITY", "LANGUAGE_CODE") AS 
  select ih.invoicebusinessunit_id, bu.code Bu_code, bu.description Bu_desc, pl.plant_id, Pl.Code Pl_code, Pl.Name Pl_name,
       ih.invoicedate, ilt.type InvoicelineType, tg.code TurnoverGroup_code,
       (select tgd.description from turnovergroup_desc tgd where tg.turnovergroup_id = tgd.turnovergroup_id and tgd.language_id = lan.language_id) TurnoverGroup_desc,
       (select pd.description from product_desc pd where p.product_id = pd.product_id and pd.language_id = pl.language_id) Product_desc,
       p.code Product_code, ilp.productgroupcode productgroupcode, ilp.productgroupdescription productgroupdescription, ih.routenumber,
       case when il.adjustmentreason_id is null then il.amount else il.adjustedamount end Amount,
       case when il.adjustmentreason_id is null then ilp.deliveredqty else ilp.adjustmentdeliveredqty + ilp.deliveredqty  end Quantity,
       lan.code Language_code
from invoiceheader ih, status st, invoiceline il
       left outer join turnovergroup tg on il.turnovergroup_id = tg.turnovergroup_id,
     invoicelinetype ilt, invoicelineproduct ilp, product p, businessunit bu , plant pl, languages lan
where ih.documenttype = 1 and ih.status_id = st.status_id and st.statustype = 'IN' and st.code = 2
      and il.extend='Y'
      and ih.invoiceheader_id = il.invoiceheader_id
      and il.invoicelinetype_id = ilt.invoicelinetype_id
      and il.invoiceline_id=ilp.invoiceline_id---select only lines with ilp and with products linked to that ilp
      and ilp.product_link_id = p.product_id
      and ih.invoicebusinessunit_id = bu.businessunit_id
      and bu.plant_id = pl.plant_id
      and (ilt.type <>5 --sales
      or il.invoicelinesubtype<>0)
/

  CREATE OR REPLACE VIEW "V_INTERNALVALUECIRCINV" ("LINETYPE", "USERGROUP_ID", "BUSINESSUNITCODE", "BUSINESSUNITDESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEFAULTBUSINESSUNIT_ID", "WEARERNUMBER", "FULLNAME", "PRODUCTGROUPCODE", "PRODUCTCODE", "SIZECODE", "SEQUENCENUMBER", "PRODUCTDESC", "PRIMARYID", "WASHESTOTAL", "WEEKSUSED", "PRICE", "REPORTPARAM_ID", "PRICE_TYPE", "PRICE_CODE", "PRICE_DESC", "PERCENTAGE", "CURRENCYCODE", "DECIMALS", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE") AS 
  select 1 linetype, bug.usergroup_id, bu.code businessunitcode, bu.description businessunitdesc
, cu.customernumber, cu.name customerName, cu.defaultbusinessunit_id
, we.wearernumber, we.fullname, prdgr.code productgroupCode, prd.code productCode, sz.code sizeCode, -1 sequencenumber -- prdsz.sequencenumber
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ui.primaryid, ui.washestotal
, F_CEIL( coalesce(GETDATEDIFF(trunc(sysdate),uqfx.lastissuedate), uqfx.daysincircprevissue)  / 7 ) weeksUsed
, coalesce(
  case when rp.number_value1 = 1 then
            F_PRICEINTERNALMERCHANDIZE(plant.plant_id, prd.product_id, sz.sizedefinition_id, ui.finishingmethod_id )
       when rp.number_value1 = 2 then
            F_REPLACEMENT_INTERNAL_PRICE(rp.number_value2, prd.product_id, sz.sizedefinition_id)
       end
  , 0) price
, rp.reportparam_id, rp.number_value1 price_type, rp.string_value1 price_code, rp.string_value2 price_desc
, ROUND(ivh.percentage, 0) percentage
, cy.code currencyCode, cy.decimals, cy.invoiceamountdecimals, languages.code languageCode
from
  internalvaluehistory ivh
, uniqueitem ui
, product prd, productgroup prdgr, sizedefinition sz, productsize prdsz
, uniqueitemfixedinfo uqfx
, uniqueitemnonpool uqnp, weareremployment wey, wearer we, customer cu
, status st, businessunit bu, plant, businessunitsperusergroup bug
, reportparam rp, currency cy, languages
where
    ivh.year*100+ivh.week
      = ( select max(ivh_2.year*100+ivh_2.week) from internalvaluehistory ivh_2 where ivh_2.uniqueitem_id = ivh.uniqueitem_id )
and ui.uniqueitem_id = ivh.uniqueitem_id
and st.status_id = ui.status_id and st.statustype = 'UI' and st.code in ('20', '30') -- In Circulation, Assigned
and ui.customerowned = 'N' and ui.leaseweeks is null
and prd.product_id = ui.product_id
    and prdgr.productgroup_id = prd.productgroup_id
    and prdsz.product_id = prd.product_id
        and sz.sizedefinition_id = prdsz.sizedefinition_id
and sz.sizedefinition_id = ui.sizedefinition_id
and uqfx.uniqueitem_id = ui.uniqueitem_id
and uqnp.uniqueitem_id = ui.uniqueitem_id
    and wey.weareremployment_id = uqnp.weareremployment_id
        and we.wearer_id = wey.wearer_id
            and cu.customer_id = we.customer_id
                and bu.businessunit_id = cu.defaultbusinessunit_id
                    and plant.plant_id = bu.plant_id
and bu.businessunit_id = ui.businessunit_id
and bug.businessunit_id = bu.businessunit_id
and cy.currency_id =
    ( case when rp.number_value1 = 1 then
      ( select cpl.currency_id from costpricelistperplant cpp, costpricelist cpl
               where cpp.plant_id = plant.plant_id and cpp.pricetype = 1
               and cpp.priority = ( select min(costpricelistperplant.priority) from costpricelistperplant
                   where costpricelistperplant.plant_id = cpp.plant_id and costpricelistperplant.pricetype = 1 )
               and cpp.costpricelist_id = cpl.costpricelist_id )
      when rp.number_value1 = 2 then
( select gpl.currency_id from generalpricelist gpl where gpl.generalpricelist_id = rp.number_value2) end
    )
union all
select 2 linetype, bug.usergroup_id, bu.code businessunitcode, bu.description businessunitdesc
, cu.customernumber, cu.name customerName, cu.defaultbusinessunit_id
, we.wearernumber, we.fullname, prdgr.code productgroupCode
, coalesce(subtPrd.Code, prd.code) productCode, coalesce(subtSz.Code, sz.code) sizeCode
, -1 sequencenumber -- prdsz.sequencenumber
, coalesce(
  ( SELECT description FROM product_desc WHERE product_desc.product_id = subtPrd.product_id
  AND product_desc.LANGUAGE_ID = languages.LANGUAGE_ID )
  , ( SELECT description FROM product_desc pd WHERE pd.product_id = prd.product_id
  AND pd.LANGUAGE_ID = languages.LANGUAGE_ID)
  )  productDesc
, '-1' primaryid, 0 washestotal
, F_CEIL( GETDATEDIFF(trunc(sysdate), nui.issuedate) / 7 ) weeksUsed
, coalesce(
  case when rp.number_value1 = 1 then
            F_PRICEINTERNALMERCHANDIZE(plant.plant_id, coalesce(subtPrd.Product_Id, prd.product_id), coalesce(subtSz.Sizedefinition_Id, sz.sizedefinition_id), weiv.finishingmethod_id)
       when rp.number_value1 = 2 then
            F_REPLACEMENT_INTERNAL_PRICE(rp.number_value2, coalesce(subtPrd.Product_Id, prd.product_id), coalesce(subtSz.Sizedefinition_Id, sz.sizedefinition_id))
       end
  , 0) price
, rp.reportparam_id, rp.number_value1 price_type, rp.string_value1 price_code, rp.string_value2 price_desc
, ROUND(ivh.percentage, 0) percentage
, cy.code currencyCode, cy.decimals, cy.invoiceamountdecimals, languages.code languageCode
from internalvaluehistory ivh
, nonuniqueitem nui
    left outer join product subtPrd on subtPrd.product_id = nui.substituteforproduct_id
    left outer join sizedefinition subtSz on subtSz.Sizedefinition_Id = nui.substituteforsizedefinition_id
, wearerinventory weiv, weareremployment wey, wearer we, customer cu
, product prd, productgroup prdgr, sizedefinition sz, productsize prdsz
, businessunit bu, plant, businessunitsperusergroup bug
, reportparam rp, currency cy, languages
where
   ivh.year*100+ivh.week
      = ( select max(ivh_2.year*100+ivh_2.week) from internalvaluehistory ivh_2 where ivh.nonuniqueitem_id = ivh_2.nonuniqueitem_id )
and nui.nonuniqueitem_id = ivh.nonuniqueitem_id
and weiv.wearerinventory_id = nui.wearerinventory_id
and prd.product_id = weiv.product_id
    and prdgr.productgroup_id = prd.productgroup_id
        and prdsz.product_id = prd.product_id
        and sz.sizedefinition_id = prdsz.sizedefinition_id
and sz.sizedefinition_id = sz.sizedefinition_id
and wey.weareremployment_id = weiv.weareremployment_id
    and we.wearer_id = wey.wearer_id
            and cu.customer_id = we.customer_id
                and bu.businessunit_id = cu.defaultbusinessunit_id
                    and plant.plant_id = bu.plant_id
and bug.businessunit_id = bu.businessunit_id
and cy.currency_id =
    ( case when rp.number_value1 = 1 then
      ( select cpl.currency_id from costpricelistperplant cpp, costpricelist cpl
               where cpp.plant_id = plant.plant_id and cpp.pricetype = 1
               and cpp.priority = ( select min(costpricelistperplant.priority) from costpricelistperplant
                   where costpricelistperplant.plant_id = cpp.plant_id and costpricelistperplant.pricetype = 1 )
               and cpp.costpricelist_id = cpl.costpricelist_id )
     when rp.number_value1 = 2 then
( select gpl.currency_id from generalpricelist gpl where gpl.generalpricelist_id = rp.number_value2) end
    )
/

  CREATE OR REPLACE VIEW "V_INTERNALVALUESTOCK" ("USERGROUP_ID", "BUSINESSUNITCODE", "BUSINESSUNITDESC", "STOCKCODE", "CUSTOMERNUMBER", "PRODUCTGROUPCODE", "PRODUCTCODE", "SIZECODE", "SEQUENCENUMBER", "PRODUCTGROUPDESC", "PRODUCTDESC", "NEWGARMENT", "PRIORITY", "GRADECODE", "PERCENTAGE", "PRIMARYID", "WEEKSUSED", "WASHESTOTAL", "WEEKSSTOCK", "QTYNONUNIQUE", "PRICE", "REPORTPARAM_ID", "PRICE_TYPE", "PRICE_CODE", "PRICE_DESC", "BUSINESSUNIT_ID", "CURRENCYCODE", "DECIMALS", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE", "STOCKLOCAREACODE") AS 
  select distinct bug.usergroup_id, bu.code businessunitcode, bu.description businessunitdesc
, sk.code stockCode, coalesce(( select customer.customernumber from customer where customer.customer_id = ui.relatedcustomer_id ), -1) customernumber
, prdgr.code productgroupCode, prd.code productCode, sz.code sizeCode, prdsz.sequencenumber
, ( select productgroup_desc.description from productgroup_desc where productgroup_desc.productgroup_id = prdgr.productgroup_id
  and productgroup_desc.language_id = languages.language_id ) productgroupDesc
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, qg.newgarment, qg.priority, qg.code gradeCode
, IVH.PERCENTAGE percentage
, ui.primaryid
, F_CEIL( coalesce(uqfx.daysincircprevissue, GETDATEDIFF(trunc(sysdate),uqfx.lastissuedate)) / 7 ) weeksUsed
, ui.washestotal
, F_CEIL( coalesce(GETDATEDIFF(trunc(sysdate),uqfx.lastonstockdate), uqfx.daysinstockprevious)  / 7 ) weeksStock, 0 qtynonunique
, coalesce(
  case when rp.number_value1 = 1 then
            F_PRICEINTERNALMERCHANDIZE(plant.plant_id, prd.product_id, sz.sizedefinition_id, ui.finishingmethod_id )
       when rp.number_value1 = 2 then
            F_REPLACEMENT_INTERNAL_PRICE(rp.number_value2, prd.product_id, sz.sizedefinition_id)
       end
  , 0) price
, rp.reportparam_id, rp.number_value1 price_type, rp.string_value1 price_code, rp.string_value2 price_desc
, bu.businessunit_id
, cy.code currencyCode, cy.decimals, cy.invoiceamountdecimals, languages.code languageCode
, skl.areacode StockLocAreaCode
from
  internalvaluehistory ivh, uniqueitem ui
, product prd, productgroup prdgr, sizedefinition sz, productsize prdsz
, uniqueitemfixedinfo uqfx
    join qualitygrade qg on uqfx.qualitygrade_id = qg.qualitygrade_id
, stockroomlocation skl, stockroom sk
, status st, businessunit bu, plant, businessunitsperusergroup bug
, reportparam rp
, currency cy, languages
where
    ivh.year*100+ivh.week
      = ( select max(ivh_2.year*100+ivh_2.week) from internalvaluehistory ivh_2 where ivh.uniqueitem_id = ivh_2.uniqueitem_id )
and ivh.uniqueitem_id = ui.uniqueitem_id
and ui.status_id = st.status_id and st.statustype = 'UI' and st.code = '10' -- Stock
and ui.customerowned = 'N' and ui.leaseweeks is null
and ui.product_id = prd.product_id
    and prd.productgroup_id = prdgr.productgroup_id
    and prd.product_id = prdsz.product_id
        and prdsz.sizedefinition_id = sz.sizedefinition_id
and ui.sizedefinition_id = sz.sizedefinition_id
and ui.uniqueitem_id = uqfx.uniqueitem_id
    and uqfx.stockroomlocation_id = skl.stockroomlocation_id
        and skl.stockroom_id = sk.stockroom_id
            and sk.managedbybu_id =  bu.businessunit_id
                and bu.plant_id = plant.plant_id
and bu.businessunit_id = bug.businessunit_id
and cy.currency_id =
   ( case when rp.number_value1 = 1 then
      ( select cpl.currency_id from costpricelistperplant cpp, costpricelist cpl
               where cpp.plant_id = plant.plant_id and cpp.pricetype = 1
               and cpp.priority = ( select min(costpricelistperplant.priority) from costpricelistperplant
                   where costpricelistperplant.plant_id = cpp.plant_id and costpricelistperplant.pricetype = 1 )
               and cpp.costpricelist_id = cpl.costpricelist_id )
      when rp.number_value1 = 2 then
      ( select gpl.currency_id from generalpricelist gpl where gpl.generalpricelist_id = rp.number_value2) end
    )
union
select distinct bug.usergroup_id, bu.code businessunitcode, bu.description businessunitdesc
, sk.code stockCode, case when sdi.customer_id is null then -1 else cu.customernumber end customernumber
, prdgr.code productgroupCode
, prd.code productCode, sz.code sizeCode
, prdsz.sequencenumber
, ( select productgroup_desc.description from productgroup_desc where productgroup_desc.productgroup_id = prdgr.productgroup_id
  and productgroup_desc.language_id = languages.language_id ) productgroupDesc
, ( SELECT description FROM product_desc pd WHERE pd.product_id = prd.product_id
  AND pd.LANGUAGE_ID = languages.LANGUAGE_ID
  )  productDesc
, qg.newgarment, qg.priority, qg.code gradeCode, qg.internalvaluepercentage percentage
, '-1' primaryid, 0 weeksUsed
, 0 washestotal,  0 weeksStock
, (select sum(sq.qtynonunique) from stockquantity sq where sq.stockreservationpergrade_id = srg.stockreservationpergrade_id) qtynonunique
, coalesce(
  case when rp.number_value1 = 1 then
            F_PRICEINTERNALMERCHANDIZE(plant.plant_id, prd.product_id, sz.sizedefinition_id, 1)
       when rp.number_value1 = 2 then
            F_REPLACEMENT_INTERNAL_PRICE(rp.number_value2, prd.product_id, sz.sizedefinition_id)
       end
  , 0) price
, rp.reportparam_id, rp.number_value1 price_type, rp.string_value1 price_code, rp.string_value2 price_desc
, bu.businessunit_id
, cy.code currencyCode, cy.decimals, cy.invoiceamountdecimals, languages.code languageCode
, skl.areacode StockLocAreaCode
from
  stockroom sk, stockreservationpergrade srg, qualitygrade qg
, stockdefinitionperitem sdi
    left outer join customer cu on sdi.customer_id = cu.customer_id
, product prd, productgroup prdgr, sizedefinition sz, productsize prdsz
, businessunit bu, plant, businessunitsperusergroup bug
, reportparam rp, currency cy, languages
, stockroomlocation skl, stockquantity sq
where
    prd.productgroup_id = prdgr.productgroup_id
    and prd.product_id = prdsz.product_id
        and prdsz.sizedefinition_id = sz.sizedefinition_id
and prd.product_id = sdi.product_id
and sz.sizedefinition_id = sdi.sizedefinition_id
    and sdi.stockroom_id = sk.stockroom_id
        and sk.managedbybu_id = bu.businessunit_id
            and bu.plant_id = plant.plant_id
and bu.businessunit_id = bug.businessunit_id
and sdi.stockdefinitionperitem_id = srg.stockdefinitionperitem_id
    and srg.qualitygrade_id = qg.qualitygrade_id
and cy.currency_id =
   ( case when rp.number_value1 = 1 then
      ( select cpl.currency_id from costpricelistperplant cpp, costpricelist cpl
               where cpp.plant_id = plant.plant_id and cpp.pricetype = 1
               and cpp.priority = ( select min(costpricelistperplant.priority) from costpricelistperplant
                   where costpricelistperplant.plant_id = cpp.plant_id and costpricelistperplant.pricetype = 1 )
               and cpp.costpricelist_id = cpl.costpricelist_id )
      when rp.number_value1 = 2 then
      ( select gpl.currency_id from generalpricelist gpl where gpl.generalpricelist_id = rp.number_value2) end
    )
and skl.stockroom_id = sk.stockroom_id
and srg.stockreservationpergrade_id=sq.stockreservationpergrade_id
and sq.stockroomlocation_id=skl.stockroomlocation_id
/

  CREATE OR REPLACE VIEW "V_INTERNETORDERHEADER" ("INTERNETORDER_ID", "STATUS", "ORDERDATE", "DISTRIBUTIONPOINT_LINK_ID", "ORDERDATE_WEEKNUMBER", "DEPARTMENT_ACTIVE", "ORDERDATE_DAY_DESC", "DAY_OF_WEEK", "DISTRIBUTIONPOINTNUMBER", "DISTRIBPOINT_DESC", "DISTRIBPOINT_ACTIVE", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEPARTMENT_DESC", "DEPARTMENT_OCCUPANCY", "PLANT_CODE", "PLANT_NAME", "BU_CODE", "BU_DESCRIPTION", "DELIVERYPOINT_DESC", "LANGUAGECODE", "SHOWWEBORDERTOTALS", "ORDERDATE_CUST_DAY_DESC") AS 
  select /*version 2.0*/
       io.internetorder_id, io.status, io.orderdate, io.distributionpoint_link_id, getisoweek(io.orderdate) orderdate_weeknumber,
       dep.active department_active, cast(getdaydescription(io.orderdate) as varchar2(30)) orderdate_day_desc, getdaynumber(io.orderdate) day_of_week,
       dip.distributionpointnumber, dip.description distribpoint_desc, dip.active distribpoint_active, dip.department_id, dep.departmentnumber,
       dep.description department_desc, dep.occupancy department_occupancy, p.code plant_code, p.name plant_name, bu.code bu_code, bu.description bu_description,
       (select dp.description
          from deliverypoint dp
         where dp.deliverypoint_id = dip.deliverypoint_id) deliverypoint_desc,
       (select lan.code
          from languages lan
         where lan.language_id = c.language_id) languagecode,
       (select ss.value
          from systemsetting ss
         where ss.plant_id = p.plant_id
           and ss.name = 'SHOWWEBORDERTOTALS') showwebordertotals,
       (select dd.description
          from day_desc dd
         where dd.language_id = c.language_id
           and dd.day_id = getdaynumber(io.orderdate)) orderdate_cust_day_desc
  from internetorder io
       join distributionpoint dip
            join department dep
                 join customer c
                      join businessunit bu
                           join plant p on bu.plant_id = p.plant_id
                      on c.defaultbusinessunit_id = bu.businessunit_id
                 on dep.customer_id = c.customer_id
            on dip.department_id = dep.department_id
       on io.distributionpoint_link_id = dip.distributionpoint_id
 where exists (select 1
                 from stockcountscheduledept s
                 join stockcountscheduleday sd on s.stockcountschedule_id = sd.stockcountschedule_id
                where s.department_id = dep.department_id
                  and sd.day_id = getabsdaynumber(io.orderdate)
                union all
               select 1
                 from stockcountscheduledist scs
                 join stockcountscheduleday sd on scs.stockcountschedule_id = sd.stockcountschedule_id
                where scs.distributionpoint_id = dip.distributionpoint_id
                  and sd.day_id = getabsdaynumber(io.orderdate))
/

  CREATE OR REPLACE VIEW "V_INTERNETORDERLINE" ("INTERNETORDER_ID", "INTERNETORDERLINE_ID", "PRODUCT_LINK_ID", "FINISHINGMETHOD_ID", "FINMETH_CODE", "NORMSTOCKAMOUNT", "STANDARDDELIVERYAMOUNT", "PRODUCTCODE", "SIZEDEFINITION_LINK_ID", "SIZE_CODE", "TYPE", "QUANTITY", "FIXEDAMOUNT", "DELIVERYVARIATIONS_ID", "SYSTEMUSER_ID", "TIMESTAMP", "OCCUPANCYRELATED", "LANGUAGE_CODE", "PRODUCTDESCRIPTION", "SIZE_DESC", "FINMETH_DESC", "PN_STATUS_CODE", "PN_NOTENUMBER", "SEQ") AS 
  select /*version 2.0 */
       ioline.internetorder_id, ioline.internetorderline_id, ioline.product_link_id, ioline.finishingmethod_id, f.code finmeth_code,  ioline.normstockamount,
       ioline.standarddeliveryamount,  p.code productcode, ioline.sizedefinition_link_id, s.code size_code, ioline.type, ioline.quantity, ioline.fixedamount,
       ioline.deliveryvariations_id, ioline.systemuser_id, ioline.timestamp, p.occupancyrelated, l.code language_code,
       (select pd.description
          from product_desc pd
         where pd.product_id = p.product_id
           and pd.language_id = l.language_id) productdescription,
       (select sd.description
          from sizedefinition_desc sd
         where sd.sizedefinition_id = s.sizedefinition_id
           and sd.language_id = l.language_id) size_desc,
       (select fd.description
          from finishingmethod_desc fd
         where fd.finishingmethod_id = f.finishingmethod_id
           and fd.language_id = l.language_id) finmeth_desc,
       (select s.code
          from deliveryvariations dv, packingnote pn, status s
         where dv.packingnote_id = pn.packingnote_id
           and pn.status_id = s.status_id
           and dv.deliveryvariations_id = ioline.deliveryvariations_id) pn_status_code,
       (select pn.notenumber
          from deliveryvariations dv
               join packingnote pn on dv.packingnote_id = pn.packingnote_id
         where dv.deliveryvariations_id = ioline.deliveryvariations_id) pn_notenumber,
       (select dp.countsequence
          from distributionpoint_link dl
               join productlistperdistribpoint dp on dl.distributionpoint_id = dp.distributionpoint_id
         where io.distributionpoint_link_id = dl.distributionpoint_link_id
           and ioline.sizedefinition_link_id = dp.sizedefinition_id
           and ioline.finishingmethod_id = dp.finishingmethod_id
           and ioline.product_link_id = dp.product_id) seq
  from internetorderline ioline
       join internetorder io on ioline.internetorder_id = io.internetorder_id
       join product p on ioline.product_link_id = p.product_id
       join sizedefinition s on ioline.sizedefinition_link_id = s.sizedefinition_id
       join finishingmethod f on ioline.finishingmethod_id = f.finishingmethod_id
       cross join languages l
/

  CREATE OR REPLACE VIEW "V_INTERNET_DAY_COUNT_SCH" ("DEPARTMENT_ID", "DISTRIBUTIONPOINT_ID", "DAY_ID", "DAYNUMBER", "DAY_DESC", "LANGUAGE_CODE") AS 
  select distinct s.DEPARTMENT_ID DEPARTMENT_ID, null distributionpoint_id , sd.DAY_ID, d.daynumber,
       (select dd.description from day_desc dd where dd.day_id = d.day_id and dd.language_id = l.language_id) day_desc,
       l.code language_code
from STOCKCOUNTSCHEDULEDEPT s, STOCKCOUNTSCHEDULEDAY sd, day d, languages l
where s.STOCKCOUNTSCHEDULE_ID = sd.STOCKCOUNTSCHEDULE_ID
      and sd.day_id = d.day_id
UNION
select distinct null DEPARTMENT_ID, sdist.distributionpoint_id distributionpoint_id, sd.DAY_ID, d.daynumber,
       (select dd.description from day_desc dd where dd.day_id = d.day_id and dd.language_id = l.language_id) day_desc,
       l.code language_code
from STOCKCOUNTSCHEDULEDIST SDIST, STOCKCOUNTSCHEDULEDAY sd, day d, languages l
where SDIST.STOCKCOUNTSCHEDULE_ID = sd.STOCKCOUNTSCHEDULE_ID
      and sd.day_id = d.day_id
/

  CREATE OR REPLACE VIEW "V_INTRASTAT" ("RECEIVEDATE", "PURCHASEORDERNUMBER", "COUNTRYCODE", "COUNTRYDESC", "INTRASTATNUMBER", "INTRASTATDESC", "PRODUCTCODE", "PRODUCTDESC", "TYPEOFMERCHANDISE", "CURRENCYCODE", "DECIMALS", "SIZECODE", "QUANTITY", "THEORETICALWEIGHT", "PURCHASEPRICE", "LANGUAGECODE") AS 
  select trunc(r.receivedate) receivedate, ph.purchaseordernumber,
  co.code countrycode, co.description countrydesc,
  i.intrastatnumber, i.description intrastatdesc,
  prl.code productcode,
  (select prd.description from product_desc prd where prd.product_id = prl.product_id
    and prd.language_id = languages.language_id) productdesc,
  prl.typeofmerchandise,
  cr.code currencycode, cr.invoiceamountdecimals decimals, sl.code sizecode,
  r.quantity,
  F_GETTHEORETICALWEIGHT(prl.theoreticalweight, prl.product_id, sl.sizedefinition_link_id) theoreticalweight,
  pl.purchaseprice,
  languages.code languagecode
from receiveinstockhistory r, purchaseorderheader ph, purchaseorderline pl, product prl,
  sizedefinition_link sl, intrastat i,
  supplier c, country co, currency cr, languages
where r.purchaseordernumber = ph.purchaseordernumber
  and ph.purchaseordernumber is not null
  and ph.purchaseorderheader_id = pl.purchaseorderheader_id
  and pl.product_link_id = r.product_link_id
  and pl.sizedefinition_link_id = r.sizedefinition_link_id
  and r.product_link_id = prl.product_id
  and r.sizedefinition_link_id = sl.sizedefinition_link_id
  and prl.intrastat_id = i.intrastat_id
  and ph.supplier_id = c.supplier_id
  and c.country_id = co.country_id
  and ph.currency_id = cr.currency_id
/

  CREATE OR REPLACE VIEW "V_INT_SUPLIER_PRODUCTS" ("SUPPLIERNUMBER", "SUPPLIERNAME", "PURCHASEPRICE", "CURRENCY_ID", "DELIVERYDAYS", "MINORDERQTY", "BOXQUANTITY", "CALCULATEDQTY", "PRODUCT_CODE", "SIZEDEFINITION_CODE", "PRODUCT_ID", "SIZEDEFINITION_ID", "SUPPLIERTYPE", "SUPPLIER_ID", "STOCKROOM_ID") AS 
  SELECT distinct
Supplier.SupplierNumber,
Supplier.Name,
--Purchaserequest.purchaseprice ,
CASE (SELECT distinct STOCKVALUATIONMETHOD
      FROM QUALITYGRADE q
      WHERE q.QUALITYGRADE_ID = Purchaserequest.REQUESTEDGRADE_ID
      )
WHEN 0 THEN  --link with suplpierProduct, Standard (Historical purchase price)
F_PURCHASEPRICE ( Supplier.Supplier_Id,	Product.Product_Id, Productsize.SizeDefinition_ID, sysdate)
WHEN 1 THEN  --link with suplpierProduct, FIFO (First in First out)
F_PURCHASEPRICE ( Supplier.Supplier_Id,	Product.Product_Id, Productsize.SizeDefinition_ID, sysdate)
WHEN 2 THEN  --AVGPP (average purchase price)
(
SELECT t.avgpurchaseprice
FROM StockValueAVGPP t
WHERE t.transactiondate = (SELECT  MAX(s.transactiondate)
                           FROM StockValueAVGPP s, PRODUCT_LINK pl, SIZEDEFINITION_LINK sl, CUSTOMER_LINK cl
                           WHERE
                            s.product_link_id = pl.product_link_id
                            and s.sizedefinition_link_id = sl.sizedefinition_link_id
                            and s.customer_link_id = cl.customer_link_id
                            and pl.product_id = product.product_id
                            AND sl.sizedefinition_id = ProductSize.sizedefinition_id
                            AND cl.customer_id = purchaserequest.customer_id
                            AND s.customerowned in ('Y', 'N')
                            AND s.qualitygrade_id = purchaserequest.requestedgrade_id))
WHEN 3 THEN 0 --FSP (fixed settle price)
ELSE 0 END,
Supplier.Currency_ID,
supplier.defaultDeliveryDays,
1, --fixed minimum order qty
1, --fixed box qty
Purchaserequest.requestedstock + Purchaserequest.requesteddirectissue, --calculated qty
Product.CODE,
(select sd.code from sizedefinition sd where sd.SizeDefinition_ID=productsize.SizeDefinition_ID) as SizeDefinition_code,
Product.Product_ID,
ProductSize.SizeDefinition_ID,
Suppliertype,
Supplier.Supplier_Id,
Purchaserequest.Stockroom_Id
FROM Purchaserequest , Supplier , Productsize, Product, stockroom str, stockroomsupplier sp
WHERE Product.Product_ID = PurchaseRequest.Product_ID
and  Purchaserequest.Stockroom_Id=str.stockroom_id
and sp.stockroom_id=str.stockroom_id
and sp.supplier_id=Supplier.Supplier_Id
--and Supplier.Supplier_Id=Product.Supplier_Id
and Productsize.Product_Id=Product.Product_Id
and ProductSize.SizeDefinition_ID = PurchaseRequest.SizeDefinition_ID
and Product.Active = 'Y'
and Product.RecordPassiveStock = 'Y'
and Supplier.SupplierType = 1
and supplier.supplyingstockroom_id <> str.stockroom_id
ORDER BY SUPPLIER.SUPPLIERNUMBER
/

  CREATE OR REPLACE VIEW "V_INVCL_DELTOMAILADR" ("INVOICEHEADER_ID", "CUSTOMERNUMBER", "STREET", "ZIPCODE", "CITY", "STATE", "COUNTY", "STREET2", "HOUSENUMBER", "HOUSENUMBEREXT") AS 
  select ih.invoiceheader_id
,      c.customernumber
,      a.street
,      a.zipcode
,      a.city
,      a.state
,      a.county
,      a.street2
,      a.housenumber
,      a.housenumberext
from   invoiceheader ih
,      customer c
,      address a
where  ih.deltocustomer_link_id = c.customer_id
   and a.address_id = c.mailaddress_id
/

  CREATE OR REPLACE VIEW "V_INVENTORYCHANGES" ("DEFAULTBUSINESSUNIT_ID", "ADJUSTMENTDATE", "RENTALQTYADJUSTMENT_ID", "CUSTOMERNUMBER", "PRODUCT_CODE", "TYPEOFMERCHANDISE", "DEPARTMENTNUMBER", "DISTRIBUTIONPOINTNUMBER", "SIZEDEF_CODE", "FINISHING_CODE", "NAME", "DEP_DESC", "DISTRIB_DESC", "STREET", "STREET2", "ZIPCODE", "CITY", "REASON_CODE", "QUANTITY", "REASON_DESC", "FINISHING_DESC", "SIZEDEF_DESC", "PRODUCT_DESC", "SIZESEQ", "INVOICEHEADER_ID", "INVOICENUMBER", "INVOICEDATE", "STARTDATE", "ENDDATE", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "COSTCENTER_ID", "COSTCENTER_CODE", "COSTCENTER_DESC", "LANGUAGE_CODE", "REMARK", "TIMESTAMP", "RQA_QTY_HISTORICAL") AS 
  SELECT distinct cus.defaultbusinessunit_id, rqa.adjustmentdate, rqa.rentalqtyadjustment_id,
       cus.customernumber, p.code Product_code, p.typeofmerchandise, dep.departmentnumber, dp.distributionpointnumber,
       s.code Sizedef_code, f.code Finishing_code, cus.name, dep.description Dep_desc, dp.description Distrib_desc,
       a.street, a.street2, a.zipcode, a.city, r.code Reason_code, rqa.quantity,
       (SELECT B.DESCRIPTION FROM reasoncode_desc B WHERE b.reasoncode_id = r.reasoncode_id AND B.LANGUAGE_ID = l.LANGUAGE_ID) Reason_desc,
       (SELECT c.DESCRIPTION FROM finishingmethod_desc c WHERE c.finishingmethod_id = f.finishingmethod_id aND c.LANGUAGE_ID = l.LANGUAGE_ID) Finishing_desc,
       (SELECT d.DESCRIPTION FROM sizedefinition_desc d WHERE d.sizedefinition_id = s.sizedefinition_id aND d.LANGUAGE_ID = l.LANGUAGE_ID) Sizedef_desc,
       (SELECT e.DESCRIPTION FROM product_desc e WHERE e.product_id = p.product_id aND e.LANGUAGE_ID = l.LANGUAGE_ID) Product_desc,
       (select ps.sequencenumber from productsize ps where ps.product_id = p.product_id and ps.sizedefinition_id = s.sizedefinition_id) SizeSeq,
       ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.startdate, ih.enddate,
       ih.billtocustomernumber, ih.billtocustomername, ih.deltocustomernumber, ih.deltocustomername,
       cc.costcenter_id, cc.code costcenter_code, cc.description costcenter_desc,
       l.code Language_code, rqa.remark, rqa.timestamp,
       (select sum(rqa2.quantity) from rentalqtyadjustment rqa2 where rqa2.productlistperdistribpoint_id = pld.productlistperdistribpoint_id
       and rqa2.adjustmentdate <= ih.invoicedate) rqa_qty_historical
FROM rentalqtyadjustment rqa, reasoncode r, productlistperdistribpoint pld
     , distributionpoint dp, department dep, customer cus, address a
     , product p, sizedefinition s, finishingmethod f
     , invoiceheader ih, invoiceline il, invoicelineproduct ilp, costcenterinvoiceline ccil, costcenter cc
     , languages l
WHERE rqa.productlistperdistribpoint_id = pld.productlistperdistribpoint_id and
      rqa.reasoncode_id = r.reasoncode_id and pld.distributionpoint_id = dp.distributionpoint_id and
      dp.department_id = dep.department_id and  dep.customer_id = cus.customer_id and
      a.address_id = cus.visitaddress_id and pld.product_id = p.product_id and
      pld.sizedefinition_id = s.sizedefinition_id and pld.finishingmethod_id = f.finishingmethod_id and
      ih.deltocustomer_link_id = cus.customer_id and il.invoiceheader_id = ih.invoiceheader_id and
      ccil.invoiceline_id = il.invoiceline_id and ilp.invoiceline_id = il.invoiceline_id and
      cc.costcenter_id = ccil.costcenter_link_id and dp.costcenter_id = cc.costcenter_id and
      ilp.product_link_id = p.product_id and (ilp.sizedefinition_link_id = s.sizedefinition_id or
      (ilp.sizedefinition_link_id in (select szd.sizedefinition_id from sizedefinition szd where szd.code = '*'))) and
      ilp.finishingmethod_id = f.finishingmethod_id and
      rqa.adjustmentdate >= ih.startdate and rqa.adjustmentdate <= ih.enddate
/

  CREATE OR REPLACE VIEW "V_INVESTMENTFLATLINEN" ("CUSTOMERNUMBER", "CUSTOMERNAME", "PRODUCTCODE", "PRODUCTDESC", "PRODUCTGROUPCODE", "PRODUCTGROUPDESC", "SIZECODE", "REASONCODE", "REASONCODEDESC", "ADJUSTMENTDATE", "QUANTITY", "BUSINESSUNIT_ID", "PRICE", "LANGUAGECODE", "REPORTPARAM_ID", "LANGUAGE_ID", "CUSTOMERLANGUAGE_ID", "CUSTOMER_ID", "SUPPLIER_ID", "PRODUCT_ID", "SIZEDEFINITION_ID") AS 
  select cu.customernumber, cu.name customername,
  pr.code productcode,
  (select prd.description from product_desc prd where prd.product_id = pr.product_id
     and prd.language_id = l.language_id) productdesc,
  pg.code productgroupcode,
  (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pg.productgroup_id
     and pgd.language_id = l.language_id) productgroupdesc,
  sz.code sizecode,
  rc.code reasoncode,
  (select rcd.description from reasoncode_desc rcd where rcd.reasoncode_id = rc.reasoncode_id
     and rcd.language_id = l.language_id) reasoncodedesc,
  ra.adjustmentdate, ra.quantity, ca.processbusinessunit_id businessunit_id,
  F_GETPRICEFROMTYPE(rp.number_value1, rp.number_value2, cu.customer_id, pr.supplier_id, pr.product_id,
    sz.sizedefinition_id, ra.adjustmentdate, rp.date_value1) price,
  l.code languagecode, rp.reportparam_id, l.language_id, cu.language_id customerlanguage_id,
  cu.customer_id, pr.supplier_id, pr.product_id, sz.sizedefinition_id
from productlistperdistribpoint plpd, distributionpoint dp, department d, customer cu,
  product pr, productgroup pg, sizedefinition sz, rentalqtyadjustment ra, reasoncode rc,
  customeractivities ca,
  languages l, reportparam rp
where plpd.distributionpoint_id = dp.distributionpoint_id
  and dp.department_id = d.department_id
  and d.customer_id = cu.customer_id
  and rp.date_value2 between cu.dateactive and cu.dateinactive
  and cu.active = 'Y'
  and plpd.product_id = pr.product_id
  and pr.active = 'Y'
  and pr.productgroup_id = pg.productgroup_id
  and pg.active = 'Y'
  and plpd.sizedefinition_id = sz.sizedefinition_id
  and ra.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
  and ra.reasoncode_id = rc.reasoncode_id
  and rc.invoiceadjustment <> 1
  and (rc.linenreason = 'Y' or rc.garmentreason = 'Y')
  and ca.customer_id = cu.customer_id
  and ca.activity_id = pg.activity_id
  and ra.quantity > 0
  and pr.typeofmerchandise = 1
/

  CREATE OR REPLACE VIEW "V_INVESTMENTFLATLINENDEPOT" ("DEPOT", "CUSTOMERNUMBER", "CUSTOMERNAME", "PRODUCTCODE", "PRODUCTDESC", "PRODUCTGROUPCODE", "PRODUCTGROUPDESC", "REASONCODE", "SIZECODE", "REASONCODEDESC", "ADJUSTMENTDATE", "QUANTITY", "BUSINESSUNIT_ID", "PRICE", "LANGUAGECODE", "REPORTPARAM_ID", "LANGUAGE_ID", "CUSTOMERLANGUAGE_ID", "CUSTOMER_ID", "SUPPLIER_ID", "PRODUCT_ID") AS 
  select
  CAST(F_GETDEPOT(cu.customer_id, ca.processbusinessunit_id) AS VARCHAR2(42)) depot,
  cu.customernumber, cu.name customername,
  pr.code productcode,
  (select prd.description from product_desc prd where prd.product_id = pr.product_id
     and prd.language_id = l.language_id) productdesc,
  pg.code productgroupcode,
  (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pg.productgroup_id
     and pgd.language_id = l.language_id) productgroupdesc,
  rc.code reasoncode, sz.code sizecode,
  (select rcd.description from reasoncode_desc rcd where rcd.reasoncode_id = rc.reasoncode_id
     and rcd.language_id = l.language_id) reasoncodedesc,
  ra.adjustmentdate, ra.quantity, ca.processbusinessunit_id businessunit_id,
  F_GETPRICEFROMTYPE(rp.number_value1, rp.number_value2, cu.customer_id, pr.supplier_id, pr.product_id,
  sz.sizedefinition_id, ra.adjustmentdate, rp.date_value1) price,
  l.code languagecode, rp.reportparam_id, l.language_id, cu.language_id customerlanguage_id,
  cu.customer_id, pr.supplier_id, pr.product_id
from productlistperdistribpoint plpd, distributionpoint dp, department d, customer cu,
  product pr, productgroup pg, sizedefinition sz,
  rentalqtyadjustment ra, reasoncode rc,
  customeractivities ca,
  languages l, reportparam rp
where plpd.distributionpoint_id = dp.distributionpoint_id
  and dp.department_id = d.department_id
  and d.customer_id = cu.customer_id
  and rp.date_value2 between cu.dateactive and cu.dateinactive
  and cu.active = 'Y'
  and plpd.product_id = pr.product_id
  and pr.active = 'Y'
  and pr.productgroup_id = pg.productgroup_id
  and pg.active = 'Y'
  and ra.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
  and plpd.sizedefinition_id = sz.sizedefinition_id
  and ra.reasoncode_id = rc.reasoncode_id
  and rc.invoiceadjustment <> 1
  and (rc.linenreason = 'Y' or rc.garmentreason = 'Y')
  and ca.customer_id = cu.customer_id
  and ca.activity_id = pg.activity_id
  and ra.quantity > 0
  and pr.typeofmerchandise = 1
/

  CREATE OR REPLACE VIEW "V_INVESTMENTGARMENT" ("CUSTOMERNUMBER", "CUSTOMERNAME", "PRODUCTCODE", "PRODUCTDESC", "PRODUCTGROUPCODE", "PRODUCTGROUPDESC", "REASONCODE", "REASONCODEDESC", "ISSUEGRADECODE", "PRIORITY", "SIZECODE", "INCIRCDATE", "BUSINESSUNIT_ID", "QUANTITY", "PRICE", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE", "REPORTPARAM_ID", "LANGUAGE_ID", "CUSTOMERLANGUAGE_ID", "CUSTOMER_ID", "SUPPLIER_ID", "PRODUCT_ID", "SIZEDEFINITION_ID") AS 
  select cu.customernumber, cu.name customername,
  pr.code productcode,
  (select prd.description from product_desc prd where prd.product_id = pr.product_id
     and l.language_id = prd.language_id) productdesc,
  pg.code productgroupcode,
  (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pg.productgroup_id
     and l.language_id = pgd.language_id) productgroupdesc,
  rc.code reasoncode,
  (select rcd.description from reasoncode_desc rcd where rcd.reasoncode_id = rc.reasoncode_id
     and rcd.language_id = l.language_id) reasoncodedesc,
  qg.code issuegradecode, qg.priority, sz.code sizecode,
  ih.incircdate, ih.processbusinessunit_id businessunit_id, ih.quantity,
  F_GETPRICEFROMTYPE(rp.number_value1, rp.number_value2, cu.customer_id, pr.supplier_id, pr.product_id,
    sz.sizedefinition_id, ih.incircdate, rp.date_value1) price,
  cr.invoiceamountdecimals,
  l.code languagecode, rp.reportparam_id, l.language_id, cu.language_id customerlanguage_id,
  cu.customer_id, pr.supplier_id, pr.product_id, sz.sizedefinition_id
from issuehistory ih, customer cu, product pr, productgroup pg, reasoncode rc, qualitygrade qg,
  sizedefinition sz, currency cr,
  languages l, reportparam rp
where ih.customer_link_id = cu.customer_id
  and cu.active = 'Y'
  and (cu.defaultbusinessunit_id = ih.processbusinessunit_id
       or exists (SELECT CUSTOMER_ID FROM CUSTOMERACTIVITIES CA
                  WHERE (CA.INVOICEBUSINESSUNIT_ID = ih.processbusinessunit_id
                         OR CA.PROCESSBUSINESSUNIT_ID = ih.processbusinessunit_id)
                     and cu.customer_id = ca.customer_id)
       )
  and rp.date_value2 between cu.dateactive and cu.dateinactive
  and ih.product_link_id = pr.product_id
  and pr.active = 'Y'
  and pr.productgroup_id = pg.productgroup_id
  and ih.reasoncode_id = rc.reasoncode_id
  and rc.invoiceadjustment <> 1
  and (rc.linenreason = 'Y' or rc.garmentreason = 'Y')
  and ih.issuegrade_id = qg.qualitygrade_id
  and ih.sizedefinition_link_id = sz.sizedefinition_id
  and cu.currency_id = cr.currency_id
  and ih.quantity > 0
  and pr.typeofmerchandise = 2 -- only garments
/

  CREATE OR REPLACE VIEW "V_INVOICEADDITION" ("INVOICEHEADER_ID", "INVOICENUMBER", "INVOICEDATE", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "RENTPERIOD", "CODE", "DESCRIPTION", "WEARERNUMBER", "WEARERNAME", "MIN_YEAR_WEEKS", "INVOICEFREQUENCYNUMBER", "YEAR", "WEEK", "INVOICEQTYCOLUMN", "QUANTITY") AS 
  select
  ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate
, ih.deltocustomernumber, ih.deltocustomername, dell.rentperiod
, il.code, il.description
, welk.wearernumber, welk.wearername
--, cast(F_5_YEARWEEKS(il.invoiceline_id, ifq.invoicefrequencynumber) as varchar2(39)) min_year_weeks, ifq.invoicefrequencynumber
, cast(F_5_YEARWEEKS(il.invoiceheader_id, ifq.invoicefrequencynumber) as varchar2(39)) min_year_weeks, ifq.invoicefrequencynumber
, iladd.year, iladd.week, ilp.invoiceqtycolumn, iladd.quantity
from
  invoiceheader ih, customer_link dell_culk
                      left outer join customer dell on dell_culk.Customer_Id = dell.customer_id
, invoiceline il, invoicelineproduct ilp
, invoicelineaddition iladd
    left outer join weareremployment_link welk on iladd.weareremployment_link_id = welk.weareremployment_link_id
, invoicefrequency ifq -- can elimine this table invoicefrequencynumber = invoicefrequency_id
, status
where
   ih.documenttype = 1
and ih.status_id = status.status_id
    and status.statustype = 'IN'
        -- and status.code = '2'
and ih.deltocustomer_link_id = dell_culk.Customer_Link_Id
and ih.invoiceheader_id = il.invoiceheader_id
    and il.invoiceline_id = ilp.invoiceline_id
    and il.invoiceline_id = iladd.invoiceline_id
and ih.invoicefrequency_id = ifq.invoicefrequency_id
    and ifq.invoicefrequencynumber in (45, 110, 40)-- (todo 6980) Every 4 weeks
/

  CREATE OR REPLACE VIEW "V_INVOICEAGING" ("INVOICEHEADER_ID", "INVOICEDATE", "INVOICENUMBER", "BILLTOCUSTOMER_LINK_ID", "DELTOCUSTOMER_LINK_ID", "PREBILLAMOUNT", "CURRENTBALANCE", "DAYSTOTHIRTY", "DAYSTOSIXTY", "DAYSTONINETY", "DAYSTO120") AS 
  select /*version 1.1*/
       ih.invoiceheader_id, ih.invoicedate, ih.invoicenumber, ih.billtocustomer_link_id,
       ih.deltocustomer_link_id, ih.prebillamount,
       f_getaragingamountdelto(ih.deltocustomer_link_id, 0) currentbalance,
       f_getaragingamountdelto(ih.deltocustomer_link_id, 1) daystothirty,
       f_getaragingamountdelto(ih.deltocustomer_link_id, 2) daystosixty,
       f_getaragingamountdelto(ih.deltocustomer_link_id, 3) daystoninety,
       f_getaragingamountdelto(ih.deltocustomer_link_id, 4) daysto120
  from invoiceheader ih
 where ih.documenttype in (1, 8)
/

  CREATE OR REPLACE VIEW "V_INVOICEAPPENDIXCSV" ("INVOICEHEADER_ID", "BUSINESSUNIT_ID", "INVOICENUMBER", "BILLTOCUSTOMERNO", "DELTOCUSTOMERNO", "DELTOCUSTOMERNAME", "YEAR", "WEEK", "LINENUMBER", "COSTCENTERCODE", "COSTCENTERNAME", "COSTSPECFICATIONCODE", "COSTSPECFICATIONDESC", "INVOICELINETYPECODE", "INVOICELINETYPEDESC", "ACTIVITYCODE", "ACTIVITYDESC", "CODE", "SIZEDESCRIPTION", "FINISHINGMETHODDESCRIPTION", "QUANTITY", "REGISTRATIONUNITCODE", "PRICE", "AMOUNT", "DESCRIPTION", "TAXPERCENTAGE", "DISCOUNTPERCENTAGE") AS 
  select f.invoiceheader_id,f.invoicebusinessunit_id businessunit_id,
f.invoicenumber,f.billtocustomernumber billtocustomerno, f.deltocustomernumber deltocustomerno, f.deltocustomername,
 coalesce(cri.year,year(f.invoicedate)) year,
 coalesce(cri.week, to_number(getweeknumber(f.nextperiodstartdate)), to_number(getweeknumber(f.enddate)),f.invoiceweek)week,
a.linenumber,
(select cc.code from costcenter_link cc where cri.costcenter_link_id = cc.costcenter_link_id) costcentercode,
(select cc.description  from   costcenter_link cc where  cri.costcenter_link_id = cc.costcenter_link_id) costcentername,
f_getcustcostspeccode(b.product_link_id, b.sizedefinition_link_id, b.finishingmethod_id, f.invoicedate, b.weighingcategory_link_id, f.deltocustomer_link_id, a.invoicelinetype_id) costspecficationcode,
f_getcustcostspecdesc(b.product_link_id, b.sizedefinition_link_id, b.finishingmethod_id, f.invoicedate, b.weighingcategory_link_id, f.deltocustomer_link_id, a.invoicelinetype_id) costspecficationdesc,
(select e.type from invoicelinetype e where a.invoicelinetype_id = e.invoicelinetype_id) invoicelinetypecode,
(select description  from   invoicelinetype_desc z  where  z.invoicelinetype_id = a.invoicelinetype_id
         and z.language_id = languages.language_id) invoicelinetypedesc,
(select av.code from activity av where
  av.activity_id in (coalesce( (select pg.activity_id  from product p, productgroup pg
                           where  p.productgroup_id=pg.productgroup_id and p.product_id=b.product_link_id )
     ,(select  wg.activity_id  from weighingcategory wg  where wg. weighingcategory_id =b.weighingcategory_link_id)),''))activitycode
,(select ad.description from activity av, activity_desc ad where
  av.activity_id in (coalesce( (select pg.activity_id  from product p, productgroup pg
                           where  p.productgroup_id=pg.productgroup_id and p.product_id=b.product_link_id )
     ,(select  wg.activity_id  from weighingcategory wg  where wg. weighingcategory_id =b.weighingcategory_link_id)),'')
and av.activity_id=ad.activity_id and ad.language_id = languages.language_id)activitydesc
, case when ilt.invoicelinetype_id in (3,4) then  'W'||a.code
      when ilt.invoicelinetype_id = 16 then 'T'||a.code
      else a.code
      end code,
b.sizedescription,b.finishingmethoddescription,
case when ilt.invoicelinetype_id=18 then 0
  else coalesce(cri.quantity, a.billedqty)  end quantity,
(select ru.code from product p, registrationunit ru where p.registrationunit_id=ru.registrationunit_id and p.product_id=b.product_link_id) registrationunitcode,
a.price,
case when ilt.invoicelinetype_id=18 and f.parentinvoiceheader_id is null then
     (select ccil.amount from costcenterinvoiceline ccil where ccil.invoiceline_id = a.invoiceline_id
     and ccil.costcenter_link_id = cri.costcenter_link_id)
 else coalesce(cri.amount, a.amount)  end amount, a.description,
case when ilt.invoicelinetype_id=18 then c.percentage
  else
    (select  max(vv.percentage) from invoiceline iltax, invoicelinevarious vv
    where iltax.invoiceheader_id =coalesce(f.parentinvoiceheader_id, f.invoiceheader_id)
    and a.taxgroupcode=iltax.code
    and a.invoiceline_id <> iltax.invoiceline_id
    and iltax.invoiceline_id=vv.invoiceline_id
    and iltax.invoicelinetype_id=18)
  end taxpercentage,
 case when ilt.invoicelinetype_id=16 then c.percentage
 else a.discountpercentage end discountpercentage
from invoiceheader f, invoiceline a
  left outer join costreportinfo cri on a.invoiceline_id = cri.invoiceline_id
  left outer join invoicelineproduct b on (a.invoiceline_id = b.invoiceline_id)
  left outer join invoicelinevarious c on (a.invoiceline_id = c.invoiceline_id)
  ,businessunit bu, plant pl,invoicelinetype ilt, languages
where a.invoiceheader_id = f.invoiceheader_id
and f.documenttype = 1
and a.invoicelinetype_id=ilt.invoicelinetype_id
and f.invoicebusinessunit_id=bu.businessunit_id
and bu.plant_id=pl.plant_id
and pl.language_id=languages.language_id
/

  CREATE OR REPLACE VIEW "V_INVOICEAPPENDIXLOSSFORPOOL" ("UNIQUEITEMLOSS_ID", "UNIQUEITEM_LINK_ID", "CUSTOMERNUMBER", "NAME", "DEPARTMENTNUMBER", "DESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "COSTCENTERCODE", "COSTCENTERDESCRIPTION", "CREDITINVOICEHEADER_ID", "INVOICEHEADER_ID", "INVOICENUMBER", "INVOICEDATE", "STARTDATE", "ENDDATE", "INVOICEBUSINESSUNIT_ID", "INVOICEFREQUENCY_ID", "CLUSTER_ID", "CURRENCYCODE", "PERIODENDDATE", "YEAR", "PERIOD", "DAYSINPERIOD", "CHARGETYPE", "OUTSCANDATE", "RETURNEDDATE", "DAYSOFUSE", "PRODUCTCODE", "PRODUCTDESCRIPTION", "PRIMARYID", "AMOUNT", "LOSSCHARGETRIGGER", "LASTSCANDATE", "LOSSSTATUS", "SIZE_CODE", "SIZE_DESC", "LOSSGRACESCHEMECODE") AS 
  select /*version 2.1*/
       uil.uniqueitemloss_id, uil.uniqueitem_link_id, cl.customernumber, cl.name, dl.departmentnumber, --credit
       dl.description, dpl.distributionpointnumber, dpl.description distributionpointdescription,
       (select cc.code
          from costcenter cc join distributionpoint dp on cc.costcenter_id = dp.costcenter_id
         where dpl.distributionpoint_id = dp.distributionpoint_id) costcentercode,
       (select cc.description
          from costcenter cc join distributionpoint dp on cc.costcenter_id = dp.costcenter_id
         where dpl.distributionpoint_id = dp.distributionpoint_id) costcenterdescription,
       uil.creditinvoiceheader_id, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.startdate,
       ih.enddate, ih.invoicebusinessunit_id, ih.invoicefrequency_id, ih.cluster_id,
       (select cc.code
          from currency cc
         where cc.currency_id = ih.currency_id) currencycode,
       iflp.enddate periodenddate, iflp.year, iflp.period,
       coalesce(iflp.enddate-iflp.cutoffdate+ 1, (select max(plpc.chargelossuniquepooldays )
                                                    from productlistpercustomer plpc
                                                    where plpc.customer_id=cl.customer_id
                                                      and plpc.product_id = p.product_id
                                                      and plpc.sizedefinition_id = ui.sizedefinition_id
                                                      and plpc.finishingmethod_id = ui.finishingmethod_id
                                                      and plpc.dateactive <= sysdate and plpc.dateinactive > sysdate )) daysinperiod,
       1 chargetype, trunc(decode(uil.losschargetrigger, 1,uil.lastscandate, uil.outscandate)) outscandate,
       uil.returneddate,
       uil.returneddate - trunc(decode(uil.losschargetrigger, 1, uil.lastscandate, uil.outscandate)) + 1 daysofuse,
       p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = ui.product_id
           and pd.language_id = c.language_id) productdescription,
       ui.primaryid, uil.creditamount amount, uil.losschargetrigger, uil.lastscandate, uil.lossstatus, sd.code size_code,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = ui.sizedefinition_id
           and sdd.language_id = c.language_id) size_desc,
       (select lsg.code
          from lossgracescheme lsg
         where lsg.lossgracescheme_id = c.lossgracescheme_id) lossgraceschemecode
  from uniqueitemloss uil
       left join invoicefrequencylossperiod iflp on uil.invoicefrequencylossperiod_id = iflp.invoicefrequencylossperiod_id
       join invoiceheader ih on uil.creditinvoiceheader_id = ih.invoiceheader_id
       join customer_link cl
            left join customer c on cl.customer_id = c.customer_id
       on uil.customer_link_id = cl.customer_link_id
       join distributionpoint_link dpl
            join department_link dl on dpl.department_link_id = dl.department_link_id
       on uil.distributionpoint_link_id = dpl.distributionpoint_link_id
       join uniqueitem ui
            join product p on ui.product_id = p.product_id
            join sizedefinition sd on ui.sizedefinition_id = sd.sizedefinition_id
       on uil.uniqueitem_link_id = ui.uniqueitem_id
 where uil.lossstatus >= 2
union
select uil.uniqueitemloss_id, uil.uniqueitem_link_id, cl.customernumber, cl.name, dl.departmentnumber, --loss charges
       dl.description, dpl.distributionpointnumber, dpl.description distributionpointdescription,
       (select cc.code
          from costcenter cc join distributionpoint dp on cc.costcenter_id = dp.costcenter_id
         where dpl.distributionpoint_id = dp.distributionpoint_id) costcentercode,
       (select cc.description
          from costcenter cc join distributionpoint dp on cc.costcenter_id = dp.costcenter_id
         where dpl.distributionpoint_id = dp.distributionpoint_id) costcenterdescription,
       uil.lossinvoiceheader_id, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.startdate,
       ih.enddate, ih.invoicebusinessunit_id, ih.invoicefrequency_id, ih.cluster_id,
       (select cc.code
         from currency cc
        where cc.currency_id = ih.currency_id) currencycode,
       iflp.enddate periodenddate,
       iflp.year,
       iflp.period,
       coalesce(iflp.enddate-iflp.cutoffdate+ 1, (select max(plpc.chargelossuniquepooldays )
                                                    from productlistpercustomer plpc
                                                   where plpc.customer_id=cl.customer_id
                                                     and plpc.product_id = p.product_id
                                                     and plpc.sizedefinition_id = ui.sizedefinition_id
                                                     and plpc.finishingmethod_id = ui.finishingmethod_id
                                                     and plpc.dateactive <= sysdate
                                                     and plpc.dateinactive > sysdate )) daysinperiod,
       2 chargetype,
       trunc(decode(uil.losschargetrigger,1,uil.lastscandate,uil.outscandate)) outscandate, null returneddate,
       (case when uil.returneddate = to_date('31-12-2099', 'dd-mm-yyyy') then
                  trunc(coalesce(iflp.enddate, ih.enddate)) - trunc(decode(uil.losschargetrigger,1,uil.lastscandate,uil.outscandate)) + 1
             else uil.returneddate - trunc(decode(uil.losschargetrigger,1,uil.lastscandate,uil.outscandate)) + 1
         end) daysofuse,
       p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = ui.product_id
           and pd.language_id = c.language_id) productdescription,
       ui.primaryid, uil.lossamount amount, uil.losschargetrigger, uil.lastscandate, uil.lossstatus, sd.code size_code,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = ui.sizedefinition_id
           and sdd.language_id = c.language_id) size_desc,
       (select lsg.code
          from lossgracescheme lsg
         where lsg.lossgracescheme_id = c.lossgracescheme_id) lossgraceschemecode
  from uniqueitemloss uil
       left join invoicefrequencylossperiod iflp on uil.invoicefrequencylossperiod_id = iflp.invoicefrequencylossperiod_id
       join invoiceheader ih on uil.lossinvoiceheader_id = ih.invoiceheader_id
       join customer_link cl
            left join customer c on cl.customer_id = c.customer_id
       on uil.customer_link_id = cl.customer_link_id
       join distributionpoint_link dpl
            join department_link dl on dpl.department_link_id = dl.department_link_id
       on uil.distributionpoint_link_id = dpl.distributionpoint_link_id
       join uniqueitem ui
            join product p on ui.product_id = p.product_id
            join sizedefinition sd on ui.sizedefinition_id = sd.sizedefinition_id
       on uil.uniqueitem_link_id = ui.uniqueitem_id
 where uil.lossstatus <> 5
union
select uil.uniqueitemloss_id, uil.uniqueitem_link_id, cl.customernumber, cl.name, dl.departmentnumber, --credit ragged
       dl.description, dpl.distributionpointnumber, dpl.description distributionpointdescription,
       (select cc.code
          from costcenter cc join distributionpoint dp on cc.costcenter_id = dp.costcenter_id
         where dpl.distributionpoint_id = dp.distributionpoint_id) costcentercode,
       (select cc.description
          from costcenter cc join distributionpoint dp on cc.costcenter_id = dp.costcenter_id
         where dpl.distributionpoint_id = dp.distributionpoint_id) costcenterdescription,
       uil.creditinvoiceheader_id, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.startdate,
       ih.enddate, ih.invoicebusinessunit_id, ih.invoicefrequency_id, ih.cluster_id,
       (select cc.code
         from currency cc
        where cc.currency_id = ih.currency_id) currencycode,
       iflp.enddate periodenddate, iflp.year, iflp.period,
       coalesce(iflp.enddate-iflp.cutoffdate+ 1, (select max(plpc.chargelossuniquepooldays )
                                                    from productlistpercustomer plpc
                                                   where plpc.customer_id=cl.customer_id
                                                     and plpc.product_id = p.product_id
                                                     and plpc.sizedefinition_id = ri.sizedefinition_link_id
                                                     and plpc.dateactive <= sysdate
                                                     and plpc.dateinactive > sysdate )) daysinperiod,
       1 chargetype,
       trunc(decode(uil.losschargetrigger,1,uil.lastscandate,uil.outscandate)) outscandate, uil.returneddate,
       uil.returneddate - trunc(decode(uil.losschargetrigger,1,uil.lastscandate,uil.outscandate)) + 1 daysofuse,
       p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = ri.product_link_id
           and pd.language_id = c.language_id) productdescription,
       ri.primaryid, uil.creditamount amount, uil.losschargetrigger, uil.lastscandate, uil.lossstatus, sd.code size_code,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = ri.sizedefinition_link_id
           and sdd.language_id = c.language_id) size_desc,
       (select lsg.code
          from lossgracescheme lsg
         where lsg.lossgracescheme_id = c.lossgracescheme_id) lossgraceschemecode
  from uniqueitemloss uil
       left join invoicefrequencylossperiod iflp on uil.invoicefrequencylossperiod_id = iflp.invoicefrequencylossperiod_id
       join invoiceheader ih on uil.creditinvoiceheader_id = ih.invoiceheader_id
       join customer_link cl
            left join customer c on cl.customer_id = c.customer_id
       on uil.customer_link_id = cl.customer_link_id
       join distributionpoint_link dpl
            join department_link dl on dpl.department_link_id = dl.department_link_id
       on uil.distributionpoint_link_id = dpl.distributionpoint_link_id
       join raggeditem ri
            join product p on ri.product_link_id = p.product_id
            join sizedefinition sd on ri.sizedefinition_link_id = sd.sizedefinition_id
       on uil.uniqueitem_link_id = ri.raggeditem_id
 where uil.lossstatus >= 2
union
select uil.uniqueitemloss_id, uil.uniqueitem_link_id, cl.customernumber, cl.name, dl.departmentnumber, --loss charges ragged
       dl.description, dpl.distributionpointnumber, dpl.description distributionpointdescription,
       (select cc.code
          from costcenter cc join distributionpoint dp on cc.costcenter_id = dp.costcenter_id
         where dpl.distributionpoint_id = dp.distributionpoint_id) costcentercode,
       (select cc.description
          from costcenter cc join distributionpoint dp on cc.costcenter_id = dp.costcenter_id
         where dpl.distributionpoint_id = dp.distributionpoint_id) costcenterdescription,
       uil.lossinvoiceheader_id, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.startdate,
       ih.enddate, ih.invoicebusinessunit_id, ih.invoicefrequency_id, ih.cluster_id,
       (select cc.code
          from currency cc
         where cc.currency_id = ih.currency_id) currencycode,
       iflp.enddate periodenddate, iflp.year, iflp.period,
       coalesce(iflp.enddate-iflp.cutoffdate+ 1, (select max(plpc.chargelossuniquepooldays )
                                                    from productlistpercustomer plpc
                                                   where plpc.customer_id=cl.customer_id
                                                   and plpc.product_id = p.product_id
                                                   and plpc.sizedefinition_id = ri.sizedefinition_link_id
                                                   and plpc.dateactive <= sysdate
                                                   and plpc.dateinactive > sysdate )) daysinperiod,
       2 chargetype,
       trunc(decode(uil.losschargetrigger,1,uil.lastscandate,uil.outscandate)) outscandate, null returneddate,
       (case when uil.returneddate = to_date('31-12-2099', 'dd-mm-yyyy') then
                  trunc(coalesce(iflp.enddate, ih.enddate)) - trunc(decode(uil.losschargetrigger,1,uil.lastscandate,uil.outscandate)) + 1
             else uil.returneddate - trunc(decode(uil.losschargetrigger,1,uil.lastscandate,uil.outscandate)) + 1
         end) daysofuse,
       p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = ri.product_link_id
           and pd.language_id = c.language_id) productdescription,
       ri.primaryid, uil.lossamount amount, uil.losschargetrigger, uil.lastscandate, uil.lossstatus, sd.code size_code,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = ri.sizedefinition_link_id
           and sdd.language_id = c.language_id) size_desc,
       (select lsg.code
          from lossgracescheme lsg
         where lsg.lossgracescheme_id = c.lossgracescheme_id) lossgraceschemecode
  from uniqueitemloss uil
       left join invoicefrequencylossperiod iflp on uil.invoicefrequencylossperiod_id = iflp.invoicefrequencylossperiod_id
       join invoiceheader ih on uil.lossinvoiceheader_id = ih.invoiceheader_id
       join customer_link cl
            left join customer c on cl.customer_id = c.customer_id
       on uil.customer_link_id = cl.customer_link_id
       join distributionpoint_link dpl
            join department_link dl on dpl.department_link_id = dl.department_link_id
       on uil.distributionpoint_link_id = dpl.distributionpoint_link_id
       join raggeditem ri
            join product p on ri.product_link_id = p.product_id
            join sizedefinition sd on ri.sizedefinition_link_id = sd.sizedefinition_id
       on uil.uniqueitem_link_id = ri.raggeditem_id
 where uil.lossstatus <> 5
/
CREATE OR REPLACE VIEW V_INVOICECLIENT AS 
select /*version 5.3*/
       ih.invoicedate, ih.invoiceyear, ih.invoiceweek, ih.invoicedaynumber, ih.invoicebusinessunit_id, ih.invoicenumber, ih.activityreference, ih.documenttype,
       ibu.code invoicebusinessunitcode, ibu.description invoicebusinessunitdesc, ih.billtocustomernumber, ih.billtocustomername, ih.extraname1, ih.extraname2,
       ih.deltocustomernumber, ih.deltocustomername, ih.startweek, ih.endweek, ih.startmonth, ih.endmonth, ih.startyear, ih.endyear, ih.city billto_city,
       ih.county, ih.state, ih.zipcode, ih.street3 billto_street3, ih.street2 billto_street2, ih.street billto_street, ih.routenumber, ih.stopnumber, ih.depotcode,
       ih.contactpersonname, ih.contactpersonphone, ih.emailstatus, ih.emailaddress, ih.street, ih.street2, ih.street3, ih.city, ih.realcollectiontype,
       ih.originalcollectiontype, ih.invoicetype, ih.exported, ih.contractcode, ih.purchaseorder, ih.deliverinstructions, ih.invoicecomments, ih.totalminusadjustment,
       ih.totalplusadjustment, ih.cashcollected, ih.paythisamount, ih.prebillamount, ih.invoicefrequency_id invoicefrequencynumber, cur.code currencycode,
       cur.description currencydesc, s.statustype, s.code statuscode, s.factorydescription statusfactorydescription, p.code plantcode, p.name plantname,
       pad.street plantstreet, pad.street2 plantstreet2, pad.street3 plantstreet3, pad.zipcode plantzipcode, pad.city plantcity, pad.state plantstate, pad.county plantcounty,
       p.phoneno plantphone, ih.state billto_state, ih.zipcode billto_zipcode, ih.routecontrol_id, ih.adjustmentreason_id, ih.systemuser_id, ih.timestamp, ih.invoiceheader_id,
       ih.creditsqueezeamount, cur.invoiceamountdecimals, cur.description currencydescription, ih.totalamountexclvat, cur.decimals, ih.startdate, ih.enddate,
       ihextr.billtocountrydescription, ihextr.deltocountrydescription, ihextr.deltocustvatnumber, ihextr.customermarkinggarment, ihextr.taxable, ihextr.siccode,
       ihextr.invoicecopies, ihextr.attachinvoicecopies, ihextr.paymenttermsdescription paymentterms_desc, ihextr.formlayoutcode invoicelayoutcode, ibu.code default_bu_code,
       ih.splitupcode, ih.splitupdescription, ihs.personidentification, ihs.signature, ih.contractstartdate, ih.contractenddate, ihextr.bankaccount, ihextr.ibanno,
       cbank.idcode cust_bank_idcode, cbank.description cust_bank_desc, cbank.internalidcode cust_bank_internid, cbank.laundrybankaccount cust_lndrybankaccount,
       cbank.ibanno cust_ibanno, lbank.idcode lndry_bank_idcode, lbank.description lndry_bank_desc, lbank.internalidcode lndry_bank_internid,
       lbank.laundrybankaccount lndry_bank_lndrybankaccount, lbank.ibanno lndry_bank_ibanno, ih.paymentdiscountdays, ih.creditsqueezeperc, ih.netpaymentdays,
       ih.deltostreet, ih.deltostreet2, ih.deltostreet3, ih.deltocounty, ih.deltocity, ih.deltozipcode, ih.deltostate, pco.description plantcountrydescription, ihextr.paymenttype,
       ihextr.discountdays, ihextr.paymentdiscount, ihextr.discountdays2, ihextr.paymentdiscount2, p.invoiceremarkstartdate, p.invoiceremarkenddate, ibu.internalvatnumber,
       ibu.vatnumber, ihc.client_link_id, ihc.clientnumber ihclientnumber, ihc.name ihclientname, ihc.sendinvoiceto, ihc.roomnumber ihcroomnumber, ihc.clienttype ihcclienttype,
       ihc.clientinvoicetype, ihextr.paymenttermsduedate, deb.legalname bill_legal_name, deb.printtaxonappendix, deb.cocnumber, p.logo, ih.roundingamount,
       ih.nextperiodstartdate, ih.nextperiodenddate, ih.nextperiodnoweeks, cbi.sendinvoiceby, deb.vatnumber biltocustvatnumber,
       dco.code biltocustcountrycode, dco.description biltocustcountry,
       cast(fsget_custdeliveryscheme(ih.route_id, ih.deltocustomer_link_id) as varchar2(6)) custdeliveryscheme,
       cast(fsget_cust_delivery_days(ih.deltocustomer_link_id) as varchar2(7)) cust_delivery_days,
       cast(getsortusasc(ih.routenumber, ih.stopnumber, ih.deltocustomernumber, ih.invoicenumber) as varchar2(255)) as m_sort_us_asc,
       cast(getsortusdesc(ih.routenumber, ih.stopnumber, ih.deltocustomernumber, ih.invoicenumber) as varchar2(255)) as m_sort_us_desc,
       cast(fsget_min_5_yearweeks(ih.invoiceheader_id, ih.invoicefrequency_id) as varchar2(39)) min_year_weeks, ih.parentinvoiceheader_id,
       (select rtes.soiltickets
          from routestop rtes
         where rtes.route_id = ih.route_id
           and rtes.stopnumber = ih.stopnumber
           and rtes.customer_id = ih.deltocustomer_link_id) no_of_soiltickets, rc.code adjustment_reasoncode,
       (select ss.value from systemsetting ss
         where p.plant_id = ss.plant_id
           and ss.name = 'WEIGHTUNIT') weightunit,
       (select max(ilv.percentage)
          from invoiceline il, invoicelinevarious ilv
         where il.invoiceheader_id = ih.invoiceheader_id
           and ilv.invoiceline_id = il.invoiceline_id
           and il.invoicelinetype_id = 18) max_percentage,
       (select cast(ss1.value as numeric)
          from systemsetting ss1
         where p.plant_id = ss1.plant_id and ss1.name = 'WEIGHTDECIMALSMANUALINPUT') weightdecimalsmanualinput,
       (select empl.name
          from routecontrol rcntrl
          join employee empl on rcntrl.drivernumber = empl.employeenumber and rcntrl.plant_id = empl.plant_id
         where rcntrl.routecontrol_id = ih.routecontrol_id) drivername,
       case when (ihs.signature is null) then 'N'
            else 'Y'
        end hassignature,
       (select pldesc.invoiceremark
          from plantinvoiceremark_desc pldesc
         where pldesc.plant_id = p.plant_id
           and pldesc.language_id = p.language_id) generalinv_remark_plant,
       (select pldesc.invoiceremark
          from plantinvoiceremark_desc pldesc
         where pldesc.plant_id = p.plant_id
           and pldesc.language_id = (select c.language_id
                                       from customer c
                                      where c.customer_id = ih.deltocustomer_link_id)) generalinv_remark_customer,
       (select cbc.description
          from customerbillingcomment cbc
         where cbc.customer_id = ih.billtocustomer_link_id
           and cbc.type = 1
           and cbc.startdate = (select max(cbc2.startdate)
                                  from customerbillingcomment cbc2
                                 where cbc2.customer_id = cbc.customer_id
                                   and cbc2.type = cbc.type
                                   and cbc2.startdate <= ih.invoicedate)) custbilltocomment,
       (select cbc.description
          from customerbillingcomment cbc
         where cbc.customer_id = ih.deltocustomer_link_id
           and cbc.type = 1
           and cbc.startdate = (select max(cbc2.startdate)
                                  from customerbillingcomment cbc2
                                 where cbc2.customer_id = cbc.customer_id
                                   and cbc2.type = cbc.type
                                   and cbc2.startdate <= ih.invoicedate)) custdeltocomment,
       (select payt.code
          from paymentterms payt
         where payt.paymentterms_id = cbi.paymentterms_id) paymentterms_code,
       deb.taxable customertaxable, p.faxno plantfax, p.website plantwebsite, p.email plantemail,
       (select pc.phone
          from plantcompany pc
         where pc.plant_id = p.plant_id
           and pc.code = (select min(pc.code)
                            from plantcompany pc
                           where pc.plant_id = p.plant_id)) plantcompanyphone,
       ih.reference, ih.paidamount, ih.creditedinvoiceno,
       (select cih.invoicedate from invoiceheader cih
         where cih.invoiceheader_id = ih.creditedinvoiceheader_id) creditedinvoicedate,
       dell.invoiceaddress_id, dell.customer_id, dell.debtor_id, nvl(dell.language_id, deb.language_id) language_id,
       (select cast(ss2.value as numeric)
          from systemsetting ss2
         where p.plant_id = ss2.plant_id and ss2.name = 'CREDITSQUEEZETYPE') creditsqueezetype
  from invoiceheader ih
       left join customer dell on ih.deltocustomer_link_id = dell.customer_id
       left join reasoncode rc on ih.adjustmentreason_id = rc.reasoncode_id
       left join invoicesignature ihs on ih.invoiceheader_id = ihs.invoiceheader_id
       left join invoiceheaderclient ihc on ih.invoiceheader_id = ihc.invoiceheader_id
       join currency cur on ih.currency_id = cur.currency_id
       join status s on ih.status_id = s.status_id
       join businessunit ibu
            join plant p
                 join address pad on p.address_id = pad.address_id
                 join country pco on p.country_id = pco.country_id
            on ibu.plant_id = p.plant_id
       on ih.invoicebusinessunit_id = ibu.businessunit_id
       join invoiceheaderextrainfo ihextr
            left join bankinstitution cbank on ihextr.bankinstitution_id = cbank.bankinstitution_id
            left join bankinstitution lbank on ihextr.laundrybankinstitution_id = lbank.bankinstitution_id
       on ih.invoiceheader_id = ihextr.invoiceheader_id
       join customer deb
            join country dco on deb.country_id = dco.country_id
            join customerbillinginfo cbi on deb.customer_id = cbi.customer_id
       on ih.billtocustomer_link_id = deb.customer_id
 where ih.documenttype in (1, 3)
/
CREATE OR REPLACE VIEW V_INVOICECLIENTLAYOUTCWS AS 
select a.invoicedate, a.invoiceyear, a.invoiceweek, a.invoicedaynumber
, a.invoicenumber, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc
, a.billtocustomernumber, a.billtocustomername, a.extraname1, a.extraname2, a.deltocustomernumber
, coalesce (dp.description,dp.code) deltocustomername
, a.startweek, a.endweek, a.startmonth, a.endmonth, a.startyear, a.endyear
, a.city, a.county, a.state, a.zipcode,a.street2, a.street, a.routenumber, a.stopnumber,a.depotcode, a.contactpersonname, a.contactpersonphone
, a.emailstatus, a.emailaddress, a.realcollectiontype, a.originalcollectiontype, a.invoicetype, a.exported, a.contractcode, a.purchaseorder
, a.deliverinstructions, a.invoicecomments, a.totalminusadjustment, a.totalplusadjustment, a.cashcollected
, a.paythisamount, a.prebillamount, a.invoicefrequency_id invoicefrequencynumber
, b.code currencycode, b.description currencydesc, s.statustype, s.code statuscode, s.factorydescription statusfactorydescription
, p.code plantcode, p.name plantname, x.street plantstreet,x.street2 plantstreet2, x.zipcode plantzipcode
, x.city plantcity, x.state plantstate, x.county plantcounty, p.phoneno plantphone
, p.faxno plantfax, p.website plantwebsite, p.email plantemail, a.city billto_city, a.street billto_street
, a.street2 billto_street2, a.state billto_state, a.zipcode billto_zipcode, a.routecontrol_id,a.adjustmentreason_id, a.systemuser_id, a.timestamp, a.invoiceheader_id, a.creditsqueezeamount
, b.invoiceamountdecimals, b.description currencydescription, a.totalamountexclvat, b.decimals, a.startdate, a.enddate
, (select ih.enddate from invoiceheader ih where ih.invoiceheader_id = a.creditedinvoiceheader_id) originalenddate
, ihextr.billtocountrydescription, ihextr.deltocountrydescription, ihextr.deltocustvatnumber, ihextr.customermarkinggarment, ihextr.taxable, ihextr.siccode, ihextr.invoicecopies
, cast(fsget_custdeliveryscheme(a.route_id, a.deltocustomer_link_id) as varchar2(6)) custdeliveryscheme
, cast(fsget_cust_delivery_days(a.deltocustomer_link_id) as varchar2(7)) cust_delivery_days
, ihextr.attachinvoicecopies, ihextr.paymenttermsdescription paymentterms_desc
, (select ihextr.paymenttermsdescription from invoiceheaderextrainfo ihei where ihei.invoiceheader_id = a.creditedinvoiceheader_id) originalpaymentterms_desc
, ihextr.formlayoutcode invoicelayoutcode, e.code default_bu_code,  rc.code adjustment_reasoncode
, (select rtes.soiltickets from routestop rtes where rtes.route_id = a.route_id and rtes.stopnumber = a.stopnumber and rtes.customer_id = a.deltocustomer_link_id) no_of_soiltickets
, cast(getsortusasc(a.routenumber, a.stopnumber, a.deltocustomernumber, a.invoicenumber) as varchar2(255)) as m_sort_us_asc
, cast(getsortusdesc(a.routenumber, a.stopnumber, a.deltocustomernumber, a.invoicenumber) as varchar2(255)) as m_sort_us_desc
,a.splitupcode, a.splitupdescription, ihs.personidentification, ihs.signature
, cast(fsget_min_5_yearweeks(a.invoiceheader_id, a.invoicefrequency_id) as varchar2(39)) min_year_weeks
, a.parentinvoiceheader_id, a.contractstartdate, a.contractenddate, ihextr.bankaccount, ihextr.ibanno
, cbank.idcode cust_bank_idcode, cbank.description cust_bank_desc, cbank.internalidcode cust_bank_internid
, cbank.laundrybankaccount cust_lndrybankaccount, cbank.ibanno cust_ibanno
, lbank.idcode lndry_bank_idcode, lbank.description lndry_bank_desc, lbank.internalidcode lndry_bank_internid
, lbank.laundrybankaccount lndry_bank_lndrybankaccount, lbank.ibanno lndry_bank_ibanno, a.paymentdiscountdays, a.creditsqueezeperc, a.netpaymentdays
, coalesce (adp.street,  a.deltostreet)  deltostreet
, coalesce (adp.street2,a.deltostreet2) deltostreet2
, coalesce (adp.county,  a.deltocounty) deltocounty
, coalesce (adp.city, a.deltocity) deltocity
, coalesce(adp.zipcode, a.deltozipcode)  deltozipcode
, coalesce(adp.state,a.deltostate) deltostate
, country.description plantcountrydescription, ss.value weightunit
,(select max(ilv.percentage) from invoiceline il, invoicelinevarious ilv
               where il.invoiceheader_id = a.invoiceheader_id and
                     ilv.invoiceline_id = il.invoiceline_id and
                     il.invoicelinetype_id = 18) max_percentage
,a.roundingamount, a.nextperiodstartdate, a.nextperiodenddate, a.nextperiodnoweeks, ihextr.paymenttype, ihextr.discountdays, ihextr.paymentdiscount, ihextr.discountdays2, ihextr.paymentdiscount2
, cast(ss1.value as numeric) weightdecimalsmanualinput
, (select empl.name from routecontrol rcntrl, employee empl
          where rcntrl.routecontrol_id = a.routecontrol_id
                and empl.employeenumber = rcntrl.drivernumber
                and empl.plant_id = rcntrl.plant_id) drivername
, (case when (ihs.signature is null)
          then 'N'
          else 'Y'
   end)  hassignature
, (select pldesc.invoiceremark from plantinvoiceremark_desc pldesc where pldesc.plant_id = p.plant_id and pldesc.language_id = p.language_id) generalinv_remark_plant
, (select pldesc.invoiceremark from plantinvoiceremark_desc pldesc where pldesc.plant_id = p.plant_id and pldesc.language_id = (select c.language_id from customer c where c.customer_id = a.deltocustomer_link_id)) generalinv_remark_customer
, p.invoiceremarkstartdate, p.invoiceremarkenddate
, e.internalvatnumber, e.vatnumber
, ihc.client_link_id, ihc.clientnumber ihclientnumber, ihc.name ihclientname--501528
, ihc.sendinvoiceto, ihc.roomnumber ihcroomnumber, ihc.clienttype ihcclienttype--501528
, ihextr.paymenttermsduedate
, (select ihextr.paymenttermsduedate from invoiceheaderextrainfo ihei where ihei.invoiceheader_id = a.creditedinvoiceheader_id) originalpaymenttermsduedate
, bil.legalname bill_legal_name --todo6927
, getdatediff(a.nextperiodenddate, a.nextperiodstartdate)+1 noofdays
, b.exchangerate
, bil.phoneno billto_phoneno, bil.faxno billto_faxno, bil.email billto_email
, coalesce((select to_char(ihp.invoicenumber) from invoiceheader ihp where ihp.invoiceheader_id=a.parentinvoiceheader_id),'') parentinvnumber
, case when a.parentinvoiceheader_id is null or a.invoiceheader_id=a.parentinvoiceheader_id
       then null
       else replace (to_char(a.invoicenumber) ,(select to_char(ihp.invoicenumber) from invoiceheader ihp where ihp.invoiceheader_id=a.parentinvoiceheader_id))
       end childnumber
from  currency b,
      businessunit e, status s,
      plant p
        left outer join systemsetting ss on (p.plant_id = ss.plant_id and ss.name = 'WEIGHTUNIT')
             left outer join systemsetting ss1 on (p.plant_id = ss1.plant_id and ss1.name = 'WEIGHTDECIMALSMANUALINPUT'),
      address x, country,
      invoiceheader a
        left outer join reasoncode rc on (a.adjustmentreason_id = rc.reasoncode_id)
             left outer join invoicesignature ihs on (ihs.invoiceheader_id = a.invoiceheader_id)
                  left outer join invoiceheaderclient ihc on (a.invoiceheader_id = ihc.invoiceheader_id)
                       left outer join customer bil on (bil.customer_id=a.billtocustomer_link_id),
      invoiceheaderextrainfo ihextr
        left outer join bankinstitution cbank on (ihextr.bankinstitution_id = cbank.bankinstitution_id)
             left outer join bankinstitution lbank on (ihextr.laundrybankinstitution_id = lbank.bankinstitution_id),
        deliverypoint dp, address adp
where a.currency_id = b.currency_id
      and a.documenttype in (1, 3)
      and a.invoicebusinessunit_id = e.businessunit_id
      and a.status_id = s.status_id
      and e.plant_id = p.plant_id
      and p.address_id = x.address_id
      and p.country_id = country.country_id
      and a.invoiceheader_id = ihextr.invoiceheader_id
      and dp.customer_id=a.deltocustomer_link_id
      and dp.deliveryaddress_id=adp.address_id
      and dp.deliverypoint_id= ( select min(dp.deliverypoint_id) from deliverypoint dp where dp.customer_id=a.deltocustomer_link_id)
/

  CREATE OR REPLACE VIEW "V_INVOICECLIENTLINE" ("INVOICEDATE", "INVOICENUMBER", "LINENUMBER", "DISCOUNTPERCENTAGE", "PRICE", "BILLEDQTY", "TAXGROUPCODE", "TAXTYPE", "SUBJECTTOMINIMUM", "TURNOVERGROUPCODE", "SIZECODE", "SIZEDESCRIPTION", "FINISHINGMETHODCODE", "PRODUCTGROUPCODE", "PRODUCTGROUPDESCRIPTION", "PRODUCTSHORTDESCRIPTION", "INVOICELINESUBTYPE", "CODE", "FINISHINGMETHODDESCRIPTION", "INVOICEQTYCOLUMN", "INVENTORYQTY", "DELIVEREDQTY", "ABUSEDQUANTITY", "SOILQUANTITY", "SOILCOUNTMETHOD", "BILLINGMETHOD", "WEARERNUMBER", "WEARERNAME", "WEARERADMINNR", "WEARERBANK", "WEARERLOCKER", "TRANSACTIONTYPE", "TRANSACTIONDATE", "PERCENTAGE", "SYSTEMUSER_ID", "TIMESTAMP", "INVOICELINE_ID", "REMARK", "LANGUAGECODE", "INVOICEHEADER_ID", "OVERAMOUNT", "REPLACEMENTPRICE", "DESCRIPTION", "GENERATED", "ADJUSTEDAMOUNT", "ADJUSTEDPRICE", "ADJUSTMENTBILLEDQTY", "EXTEND", "MINIMUMQUANTITY", "MINIMUMPERCENTAGE", "INVOICESTARTDATE", "INVOICEENDATE", "ADJUSTMENTDELIVEREDQTY", "PRICEFACTOR", "TAXPERCENTAGE", "TAXAMOUNT", "TAXJURISDICTIONLAYER", "LANGUAGE_ID", "TAXCODE", "SHORTDESCRIPTION", "INVOICELINETYPE", "AMOUNT", "SUPRESSPRINTING", "INVOICELINETYPEDESC", "TURNOVERGROUPDESCRIPTION", "INVOICELINESUBTYPEDESC", "PRODUCTDESCRIPTION", "REGISTRATIONUNITDESCRIPTION", "ADJUSTMENTREASON_CODE", "INVOICELINE_SEQUENCENUMBER", "PRODUCTCUSTOMCODE", "PRODUCTLONGDESCRIPTION", "TYPEOFMERCHANDISE", "WCREGISTRATIONUNITCODE", "COSTCENTER_LINK_ID", "WEIGHINGCATEGORYCODE") AS 
  select /*version 5.0*/
       ih.invoicedate, ih.invoicenumber, il.linenumber, il.discountpercentage, il.price, il.billedqty, il.taxgroupcode, il.taxtype,
       il.subjecttominimum, tg.code turnovergroupcode, ilp.sizecode, ilp.sizedescription, ilp.finishingmethodcode, ilp.productgroupcode,
       ilp.productgroupdescription, ilp.productshortdescription,  il.invoicelinesubtype, il.code, ilp.finishingmethoddescription,
       ilp.invoiceqtycolumn, ilp.inventoryqty, ilp.deliveredqty, ilp.abusedquantity, ilp.soilquantity, ilp.soilcountmethod,
       ilp.billingmethod, ilp.wearernumber, ilp.wearername, ilp.weareradminnr, ilp.wearerbank, ilp.wearerlocker, ilv.transactiontype,
       ilv.transactiondate, ilv.percentage, il.systemuser_id, il.timestamp, il.invoiceline_id, il.remark, lan.code languagecode,
       il.invoiceheader_id, ilv.overamount, ilp.replacementprice, il.description, il.generated, il.adjustedamount, il.adjustedprice,
       il.adjustmentbilledqty, il.extend, ilp.minimumquantity, ilp.minimumpercentage, ih.startdate invoicestartdate,
       ih.enddate invoiceendate, ilp.adjustmentdeliveredqty, ilp.pricefactor, ilx.percentage taxpercentage, ilx.amount taxamount,
       ilx.jurisdictionlayer taxjurisdictionlayer, lan.language_id,
       cast(fsget_taxcode(ih.invoicenumber, il.linenumber) as varchar2(255)) taxcode,
       cast(fsget_code(ih.invoicenumber, il.linenumber) as varchar2(255)) shortdescription,
       case when ilt.type = 1 and il.invoicelinesubtype = 13 then 1.6
            else ilt.type
        end invoicelinetype,
       case when il.extend = 'Y' then il.amount
            else 0
        end amount,
       case (select pilt.suppressprinting
               from plantinvoicelinetype pilt, businessunit bu
              where ih.invoicebusinessunit_id = bu.businessunit_id
                and bu.plant_id = pilt.plant_id
                and pilt.invoicelinetype_id = il.invoicelinetype_id)
             when 0 then 0
             when 1 then 1
             when 2 then 2
             else ilt.supressprinting
        end supressprinting,
       (select z.description
          from invoicelinetype_desc z
         where z.invoicelinetype_id = il.invoicelinetype_id
           and z.language_id = lan.language_id) invoicelinetypedesc,
       (select tgd.description
          from turnovergroup_desc tgd
         where tgd.turnovergroup_id = il.turnovergroup_id
           and tgd.language_id = lan.language_id) turnovergroupdescription,
       (select ilstd.description
          from invoicelinesubtype_desc ilstd
               join invoicelinesubtype ilst on ilstd.invoicelinesubtype_id = ilst.invoicelinesubtype_id
         where ilst.invoicelinetype_id = il.invoicelinetype_id
           and ilst.subtype = il.invoicelinesubtype
           and ilstd.language_id = lan.language_id) invoicelinesubtypedesc,
       (select pd.description
          from product_link_desc pd
         where pd.product_link_id = ilp.product_link_id
           and pd.language_id = lan.language_id) productdescription,
       (select pd.registrationunitdescription
          from product_link_desc pd
         where pd.product_link_id = ilp.product_link_id
           and pd.language_id = lan.language_id) registrationunitdescription,
       (select rc.code
          from reasoncode rc
         where rc.reasoncode_id = il.adjustmentreason_id) adjustmentreason_code,
       (select pilt.sequencenumber
          from plantinvoicelinetype pilt
               join businessunit bu
                    join invoiceheader h on h.invoicebusinessunit_id = bu.businessunit_id
               on pilt.plant_id = bu.plant_id
         where il.invoiceheader_id = h.invoiceheader_id
           and pilt.invoicelinetype_id = il.invoicelinetype_id) invoiceline_sequencenumber,
       (select plpc.customcode
          from productlistpercustomer plpc
         where plpc.product_id = ilp.product_link_id
           and plpc.sizedefinition_id = ilp.sizedefinition_link_id
           and plpc.finishingmethod_id = ilp.finishingmethod_id
           and plpc.customer_id = nvl(ih.deltocustomer_link_id, ih.billtocustomer_link_id)
           and plpc.dateactive <= ih.invoicedate
           and plpc.dateinactive > ih.invoicedate) productcustomcode,
       (select pdesc.longdescription
          from product_desc pdesc
         where pdesc.product_id = ilp.product_link_id
           and pdesc.language_id = lan.language_id) productlongdescription,
       (select prd.typeofmerchandise
          from product prd
         where prd.product_id = ilp.product_link_id) typeofmerchandise,
       (select (case when (wc.weighinguse = 1) then (select ru.code from registrationunit ru where ru.registrationunit_id = wc.registrationunit_id)
                     else (select ss.value from systemsetting ss join businessunit bu on ss.plant_id = bu.plant_id and bu.businessunit_id = ih.invoicebusinessunit_id and ss.name = 'WEIGHTUNIT')
               end)
          from weighingcategory wc
         where wc.weighingcategory_id = ilp.weighingcategory_link_id) wcregistrationunitcode,
       (select max(ild.costcenter_link_id) from invoicelinedetail ild
         where ild.invoiceline_id = il.invoiceline_id and ild.invoiceheader_id = il.invoiceheader_id) costcenter_link_id,
       (select wcc.code
          from weighingcategory wcc
         where wcc.weighingcategory_id = ilp.weighingcategory_link_id) weighingcategorycode
  from invoiceline il
       left join invoicelineproduct ilp on il.invoiceline_id = ilp.invoiceline_id
       left join invoicelinevarious ilv on il.invoiceline_id = ilv.invoiceline_id
       left join turnovergroup tg on il.turnovergroup_id = tg.turnovergroup_id
       left join invoicelinetax ilx on il.invoiceline_id = ilx.invoiceline_id
       join invoicelinetype ilt on il.invoicelinetype_id = ilt.invoicelinetype_id
       join invoiceheader ih on il.invoiceheader_id = ih.invoiceheader_id
       cross join languages lan
 where ih.documenttype in (1, 3)
/

  CREATE OR REPLACE VIEW "V_INVOICECLIENTLINECRI" ("INVOICEDATE", "INVOICENUMBER", "LINENUMBER", "INVOICELINETYPE", "INVOICELINETYPEDESC", "CODE", "TAXCODE", "DESCRIPTION", "GENERATED", "ADJUSTEDAMOUNT", "ADJUSTEDPRICE", "ADJUSTMENTBILLEDQTY", "EXTEND", "AMOUNT", "DISCOUNTPERCENTAGE", "PRICE", "BILLEDQTY", "TAXGROUPCODE", "TAXTYPE", "SUBJECTTOMINIMUM", "TURNOVERGROUPCODE", "TURNOVERGROUPDESCRIPTION", "INVOICELINESUBTYPE", "INVOICELINESUBTYPEDESC", "PRODUCTGROUPCODE", "PRODUCTGROUPDESCRIPTION", "PRODUCTSHORTDESCRIPTION", "SHORTDESCRIPTION", "SIZECODE", "SIZEDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "INVOICEQTYCOLUMN", "INVENTORYQTY", "DELIVEREDQTY", "ABUSEDQUANTITY", "SOILQUANTITY", "SOILCOUNTMETHOD", "BILLINGMETHOD", "WEARERNUMBER", "WEARERNAME", "WEARERADMINNR", "WEARERBANK", "WEARERLOCKER", "TRANSACTIONTYPE", "TRANSACTIONDATE", "PERCENTAGE", "SYSTEMUSER_ID", "TIMESTAMP", "INVOICELINE_ID", "REMARK", "LANGUAGECODE", "INVOICEHEADER_ID", "OVERAMOUNT", "REPLACEMENTPRICE", "PRODUCTDESCRIPTION", "REGISTRATIONUNITDESCRIPTION", "ADJUSTMENTREASON_CODE", "INVOICELINE_SEQUENCENUMBER", "SUPRESSPRINTING", "ADJUSTMENTDELIVEREDQTY", "PRICEFACTOR", "CRIQUANTITY", "CRIWEEK", "CRIYEAR") AS 
  select --XPKINVOICELINE
f.invoicedate, f.invoicenumber, a.linenumber,
(CASE WHEN e.TYPE = 1 AND a.invoicelinesubtype = 13
      THEN 1.6
      ELSE e.TYPE
END)  invoicelinetype,
( SELECT DESCRIPTION FROM invoicelinetype_DESC z WHERE z.invoicelinetype_id = a.invoicelinetype_id AND z.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) invoicelinetypedesc,
a.code
, cast(FSGET_TAXCODE(f.invoicenumber, a.linenumber) as varchar2(255)) taxcode
, a.description,
a.generated,
a.adjustedamount, a.adjustedprice, a.adjustmentbilledqty, a.extend, a.amount, a.discountpercentage,
a.price, a.billedqty, a.taxgroupcode, a.taxtype, a.subjecttominimum,
 coalesce ( (select d.code from turnovergroup d where a.turnovergroup_id = d.turnovergroup_id),'')  turnovergroupcode,
( SELECT DESCRIPTION FROM TURNOVERGROUP_DESC T WHERE T.TURNOVERGROUP_ID = A.TURNOVERGROUP_ID AND T.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) turnovergroupdescription,
a.invoicelinesubtype,
(select ilstd.description
 from invoicelinesubtype_desc ilstd, invoicelinesubtype ilst
 where ilstd.invoicelinesubtype_id = ilst.invoicelinesubtype_id
       and ilst.invoicelinetype_id = a.invoicelinetype_id
       and ilst.subtype = a.invoicelinesubtype
       and ilstd.language_id = LANGUAGES.LANGUAGE_ID) invoicelinesubtypedesc,
b.productgroupcode, b.productgroupdescription,b.productshortdescription
, cast(FSGET_CODE(f.invoicenumber, a.linenumber) as varchar2(255)) shortdescription
, b.sizecode, b.sizedescription, b.finishingmethodcode, b.finishingmethoddescription, b.invoiceqtycolumn, b.inventoryqty,
b.deliveredqty, b.abusedquantity, b.soilquantity, b.soilcountmethod, b.billingmethod, b.wearernumber, b.wearername,
b.weareradminnr, b.wearerbank, b.wearerlocker,
(select c.transactiontype from invoicelinevarious c where  a.invoiceline_id = c.invoiceline_id) transactiontype ,
(select c.transactiondate from invoicelinevarious c where  a.invoiceline_id = c.invoiceline_id) transactiondate ,
(select c.percentage from invoicelinevarious c where  a.invoiceline_id = c.invoiceline_id) percentage ,
a.systemuser_id, a.timestamp, a.invoiceline_id, a.remark, LANGUAGES.CODE LANGUAGECODE,
a.invoiceheader_id,
(select c.overamount from invoicelinevarious c where  a.invoiceline_id = c.invoiceline_id) overamount ,
b.replacementprice,
 ( SELECT PD.DESCRIPTION FROM PRODUCT_LINK_DESC pd WHERE pd.product_link_id = b.product_link_id AND pd.language_id = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
 ( SELECT PD.REGISTRATIONUNITDESCRIPTION FROM PRODUCT_LINK_DESC pd WHERE pd.product_link_id = b.product_link_id AND pd.language_id = LANGUAGES.LANGUAGE_ID) REGISTRATIONUNITDESCRIPTION,
 ( SELECT rc.code FROM reasoncode rc WHERE rc.reasoncode_id = a.adjustmentreason_id) ADJUSTMENTREASON_CODE,
 ( SELECT pilt.sequencenumber
         from plantinvoicelinetype pilt, businessunit bu, invoiceheader h
         where a.invoiceheader_id = h.invoiceheader_id
               and h.invoicebusinessunit_id = bu.businessunit_id
               and bu.plant_id = pilt.plant_id
               and pilt.invoicelinetype_id = a.invoicelinetype_id) InvoiceLine_SequenceNumber,
( SELECT pilt.suppressprinting
         from plantinvoicelinetype pilt, businessunit bu, invoiceheader h
         where a.invoiceheader_id = h.invoiceheader_id
               and h.invoicebusinessunit_id = bu.businessunit_id
               and bu.plant_id = pilt.plant_id
               and pilt.invoicelinetype_id = a.invoicelinetype_id) supressprinting, --502161
b.adjustmentdeliveredqty, b.pricefactor,
cri.quantity criquantity, cri.week criweek, cri.year criyear
from invoiceline a
LEFT OUTER JOIN costreportinfo cri on cri.invoiceline_id = a.invoiceline_id
LEFT OUTER JOIN invoicelineproduct b ON (a.invoiceline_id = b.invoiceline_id),
invoicelinetype e,invoiceheader f, LANGUAGES
where a.invoicelinetype_id = e.invoicelinetype_id and
a.invoiceheader_id = f.invoiceheader_id
and  f.documenttype in (1, 3)
/

  CREATE OR REPLACE VIEW "V_INVOICECLIENTLINELAYOUTCWS" ("INVOICEDATE", "INVOICENUMBER", "LINENUMBER", "INVOICELINETYPE", "INVOICELINETYPEDESC", "CODE", "TAXCODE", "DESCRIPTION", "ADJUSTEDAMOUNT", "ADJUSTEDPRICE", "ADJUSTMENTBILLEDQTY", "EXTEND", "AMOUNT", "DISCOUNTPERCENTAGE", "PRICE", "BILLEDQTY", "TAXGROUPCODE", "TAXTYPE", "SUBJECTTOMINIMUM", "TURNOVERGROUPCODE", "TURNOVERGROUPDESCRIPTION", "INVOICELINESUBTYPE", "PRODUCTGROUPCODE", "PRODUCTGROUPDESCRIPTION", "PRODUCTSHORTDESCRIPTION", "SHORTDESCRIPTION", "SIZECODE", "SIZEDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "FINISHINGMETHOD_ID", "INVOICEQTYCOLUMN", "INVENTORYQTY", "DELIVEREDQTY", "ABUSEDQUANTITY", "SOILQUANTITY", "SOILCOUNTMETHOD", "BILLINGMETHOD", "WEARERNUMBER", "WEARERNAME", "WEARERADMINNR", "WEARERBANK", "WEARERLOCKER", "TRANSACTIONTYPE", "TRANSACTIONDATE", "PERCENTAGE", "SYSTEMUSER_ID", "TIMESTAMP", "INVOICELINE_ID", "REMARK", "LANGUAGECODE", "INVOICEHEADER_ID", "OVERAMOUNT", "REPLACEMENTPRICE", "PRODUCTDESCRIPTION", "REGISTRATIONUNITDESCRIPTION", "ADJUSTMENTREASON_CODE", "INVOICELINE_SEQUENCENUMBER", "SUPRESSPRINTING", "ADJUSTMENTDELIVEREDQTY", "PRICEFACTOR", "ACTIVITYCODE", "ACTIVITYDESC", "STARTDATE", "ENDDATE", "NOOFDAYS", "CORRECTED_INVOICEHEADER_ID", "PRODUCTCODE", "CORRECTEDINVOICE", "INVOICECORRECTIONTYPEDESC", "PRODUCT_LINK_ID", "SIZEDEFINITION_LINK_ID", "BILLTOCUSTOMER_LINK_ID", "DELTOCUSTOMER_LINK_ID", "RENTPERIODPRICETYPE", "INVPERIODPRICE", "DETAILLINETYPE") AS 
  select f.invoicedate, f.invoicenumber, a.linenumber,
(CASE WHEN e.TYPE = 1 AND a.invoicelinesubtype = 13
      THEN 1.6
      ELSE e.TYPE
END)  invoicelinetype, --e.type invoicelinetype,
( SELECT DESCRIPTION FROM invoicelinetype_DESC z WHERE z.invoicelinetype_id = a.invoicelinetype_id AND z.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) invoicelinetypedesc,
a.code
, cast(FSGET_TAXCODE(f.invoicenumber, a.linenumber) as varchar2(255)) taxcode
, a.description,
a.adjustedamount, a.adjustedprice, a.adjustmentbilledqty, a.extend, a.amount, a.discountpercentage,
a.price, a.billedqty, a.taxgroupcode, a.taxtype, a.subjecttominimum, d.code turnovergroupcode,
( SELECT DESCRIPTION FROM TURNOVERGROUP_DESC T WHERE T.TURNOVERGROUP_ID = A.TURNOVERGROUP_ID AND T.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) turnovergroupdescription,
a.invoicelinesubtype, b.productgroupcode, b.productgroupdescription,
b.productshortdescription
, cast(FSGET_CODE(f.invoicenumber, a.linenumber) as varchar2(255)) shortdescription
, b.sizecode, b.sizedescription, b.finishingmethodcode, b.finishingmethoddescription,b.finishingmethod_id, b.invoiceqtycolumn, b.inventoryqty,
b.deliveredqty, b.abusedquantity, b.soilquantity, b.soilcountmethod, b.billingmethod, b.wearernumber, b.wearername,
b.weareradminnr, b.wearerbank, b.wearerlocker, c.transactiontype, c.transactiondate, c.percentage,
a.systemuser_id, a.timestamp, a.invoiceline_id, a.remark, LANGUAGES.CODE LANGUAGECODE,
a.invoiceheader_id, c.overamount, b.replacementprice,
 ( SELECT PD.DESCRIPTION FROM PRODUCT_LINK_DESC pd WHERE pd.product_link_id = b.product_link_id AND pd.language_id = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
 ( SELECT PD.REGISTRATIONUNITDESCRIPTION FROM PRODUCT_LINK_DESC pd WHERE pd.product_link_id = b.product_link_id AND pd.language_id = LANGUAGES.LANGUAGE_ID) REGISTRATIONUNITDESCRIPTION,
 ( SELECT rc.code FROM reasoncode rc WHERE rc.reasoncode_id = a.adjustmentreason_id) ADJUSTMENTREASON_CODE,
 ( SELECT pilt.sequencenumber
         from plantinvoicelinetype pilt, businessunit bu, invoiceheader h
         where a.invoiceheader_id = h.invoiceheader_id
               and h.invoicebusinessunit_id = bu.businessunit_id
               and bu.plant_id = pilt.plant_id
               and pilt.invoicelinetype_id = a.invoicelinetype_id) InvoiceLine_SequenceNumber,
( SELECT pilt.suppressprinting
         from plantinvoicelinetype pilt, businessunit bu, invoiceheader h
         where a.invoiceheader_id = h.invoiceheader_id
               and h.invoicebusinessunit_id = bu.businessunit_id
               and bu.plant_id = pilt.plant_id
               and pilt.invoicelinetype_id = a.invoicelinetype_id) supressprinting, --502161
b.adjustmentdeliveredqty, b.pricefactor,
(select ac.code from activityperinvoice api, activity ac, productgroup pg where ac.activity_id = api.activity_id
and api.invoiceheader_id = f.invoiceheader_id and b.productgroupcode = pg.code and pg.activity_id=ac.activity_id) ActivityCode
,(select ad.description from activityperinvoice api, activity ac, productgroup pg, activity_desc ad where ac.activity_id = api.activity_id
and api.invoiceheader_id = f.invoiceheader_id and b.productgroupcode = pg.code and pg.activity_id=ac.activity_id
and ac.activity_id=ad.activity_id and ad.language_id=LANGUAGES.LANGUAGE_ID) ActivityDesc
, nvl(b.startdate, f.startdate) startdate,  nvl(b.enddate, f.enddate) enddate, getdatediff(b.enddate, b.startdate)+1 noofdays
, b.corrected_invoiceheader_id,
 ( SELECT PR.code FROM product pr WHERE pr.product_id = b.product_link_id) PRODUCTCODE
, (select ih.invoicenumber from invoiceheader ih where b.corrected_invoiceheader_id = ih.invoiceheader_id) CorrectedInvoice
, (select ictd.description from invoicecorrectiontype_desc ictd where ictd.invoicecorrectiontype_id = b.correctiontype_id and ictd.language_id=Languages.Language_Id) invoicecorrectiontypedesc
, b.product_link_id, b.sizedefinition_link_id, f.billtocustomer_link_id,f.deltocustomer_link_id,
(select max(ild.rentperiodpricetype) from invoicelinedetail ild where  a.invoiceheader_id=ild.invoiceheader_id
        and a.invoiceline_id=ild.invoiceline_id) rentperiodpricetype,
(select max(ild.invperiodprice) from invoicelinedetail ild
        where --ild.correctiontype_id is null and
        a.invoiceheader_id=ild.invoiceheader_id
        and a.invoiceline_id=ild.invoiceline_id) invperiodprice,
coalesce((select max(ild.detaillinetype) from invoicelinedetail ild
        where ild.correctiontype_id is null and a.invoiceheader_id=ild.invoiceheader_id
        and a.invoiceline_id=ild.invoiceline_id),0) detaillinetype
from  invoiceline a
LEFT OUTER JOIN invoicelineproduct b ON (a.invoiceline_id = b.invoiceline_id)
LEFT OUTER JOIN invoicelinevarious c ON (a.invoiceline_id = c.invoiceline_id)
LEFT OUTER JOIN turnovergroup d ON (a.turnovergroup_id = d.turnovergroup_id),
invoicelinetype e,invoiceheader f
,  LANGUAGES
where a.invoiceheader_id = f.invoiceheader_id and
a.invoicelinetype_id = e.invoicelinetype_id and
f.documenttype in (1, 3) -- 501528
/

  CREATE OR REPLACE VIEW "V_INVOICECOVERPAGE" ("INVOICEHEADER_ID", "INVOICEDATE", "INVOICENUMBER", "BILLTOCUSTOMERNUMBER", "DELTOCUSTOMERNUMBER", "CUSTOMER_LINK_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "USECOVERPAGE", "NAME", "EXTRANAME1", "EXTRANAME2", "CONTACTPERSON", "STREET", "STREET2", "STATE", "ZIPCODE", "CITY", "COUNTY", "COUNTRYCODE", "COUNTRY") AS 
  select h.invoiceheader_id,
       h.invoicedate,
       h.invoicenumber,
       h.billtocustomernumber,
       h.deltocustomernumber,
       cl.customer_link_id,
       c.customer_id,
       c.customernumber,
       c.usecoverpage,
       cp.name,
       cp.extraname1,
       cp.extraname2,
       cp.contactperson,
       cpa.street,
       cpa.street2,
       cpa.state,
       cpa.zipcode,
       cpa.city,
       cpa.county,
       coalesce((select ctry.code
                  from country ctry
                 where ctry.country_id = cp.country_id),
                cy.code) countrycode,
       coalesce((select ctry.description
                  from country ctry
                 where ctry.country_id = cp.country_id),
                cy.description) country
  from invoiceheader         h,
       customer_link         cl,
       customer              c,
       customercoverpageinfo cp,
       address               cpa,
       country               cy
 where c.customer_id = cp.customer_id
   and cp.address_id = cpa.address_id
   and c.customer_id = cl.customer_id
   and cl.customer_link_id = h.deltocustomer_link_id
   and c.country_id = cy.country_id
   and c.usecoverpage = 'Y'
   and h.documenttype = 1
/

  CREATE OR REPLACE VIEW "V_INVOICEDAMOUNTCOMPARISION" ("INVOICEDATE", "BUSINESSUNITCODE", "BUSINESSUNITDESC", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "DELTOCUSTOMERNUMBER", "DELTOCUSTNAME", "CITY", "MARKETSEGMENTCODE", "MARKETSEGMENTDESC", "INVOICELINETYPE", "INVOICELINESUBTYPE", "INVOICELINETYPEDESC", "PRODUCTCODE", "PRODUCTDESC", "INVOICELINECODE", "INVOICELINEDESC", "SIZECODE", "WEIGHINGCATEGORYCODE", "WEIGHINGCATEGORYDESC", "PRODUCTGROUPCODE", "PRODUCTGROUPDESC", "ACTIVITYCODE", "AMOUNT", "BILLEDQTY", "REGISTRATIONUNITDESC", "WEIGHTUNIT", "WEIGHTDECIMALSMANUALINPUT", "INVOICEAMOUNTDECIMALS", "PLANT_INVOICEAMOUNTDECIMALS", "REPORTPARAM_ID", "INVOICELINE_ID") AS 
  select ih.invoicedate, bu.code businessunitcode, bu.description businessunitdesc,
  bcu.customernumber billtocustomernumber, bcu.name billtocustomername,
  dcu.customernumber deltocustomernumber, dcu.name deltocustname, ad.city,
  ms.code marketsegmentcode,
  coalesce(
    (select msd.description from marketsegment_desc msd where msd.marketsegment_id = ms.marketsegment_id
       and msd.language_id = dcu.language_id),
    (select msd.description from marketsegment_desc msd where msd.marketsegment_id = ms.marketsegment_id
       and msd.language_id = pl.language_id)) marketsegmentdesc,
  ilt.type invoicelinetype, il.invoicelinesubtype,
  coalesce(
    (select iltd.description from invoicelinetype_desc iltd where iltd.invoicelinetype_id = ilt.invoicelinetype_id
       and iltd.language_id = dcu.language_id ),
    (select iltd.description from invoicelinetype_desc iltd where iltd.invoicelinetype_id = ilt.invoicelinetype_id
       and iltd.language_id = pl.language_id)) invoicelinetypedesc,
  pr.code productcode,
  coalesce(
    (select prd.description from product_desc prd where prd.product_id = pr.product_id
       and prd.language_id = dcu.language_id),
    (select prd.description from product_desc prd where prd.product_id = pr.product_id
       and prd.language_id = pl.language_id)) productdesc,
  il.code invoicelinecode, il.description invoicelinedesc, ilp.sizecode,
  wc.code weighingcategorycode,
  coalesce(
    (select wcd.description from weighingcategory_desc wcd where wcd.weighingcategory_id = wc.weighingcategory_id
       and wcd.language_id = dcu.language_id),
    (select wcd.description from weighingcategory_desc wcd where wcd.weighingcategory_id = wc.weighingcategory_id
       and wcd.language_id = pl.language_id)) weighingcategorydesc,
  prg.code productgroupcode,
  coalesce(
    (select prgd.description from productgroup_desc prgd where prgd.productgroup_id = prg.productgroup_id
       and prgd.language_id = dcu.language_id),
    (select prgd.description from productgroup_desc prgd where prgd.productgroup_id = prg.productgroup_id
       and prgd.language_id = pl.language_id)) productgroupdesc,
  ac.code activitycode,
  il.amount, il.billedqty,
  coalesce(
    (SELECT rd.description FROM registrationunit_desc rd WHERE rd.registrationunit_id = pr.registrationunit_id
       AND rd.language_id = dcu.LANGUAGE_ID),
    (SELECT rd.description FROM registrationunit_desc rd WHERE rd.registrationunit_id = pr.registrationunit_id
       AND rd.language_id = pl.LANGUAGE_ID)) REGISTRATIONUNITDESC,
(select SS.VALUE from SYSTEMSETTING SS where pl.PLANT_ID = SS.PLANT_ID AND SS.NAME = 'WEIGHTUNIT') WEIGHTUNIT,
(select cast(SS1.VALUE as numeric) from SYSTEMSETTING SS1
	        where pl.PLANT_ID = SS1.PLANT_ID AND SS1.NAME = 'WEIGHTDECIMALSMANUALINPUT') WEIGHTDECIMALSMANUALINPUT,
cr.invoiceamountdecimals, plcr.invoiceamountdecimals plant_invoiceamountdecimals,
rp.reportparam_id, il.invoiceline_id
from invoiceheader ih, status st, businessunit bu, customer bcu, customer dcu, marketsegment ms, currency cr,
  invoicelinetype ilt, address ad,
  invoiceline il
    left outer join (invoicelineproduct ilp
      left outer join (product pr
        left join (productgroup prg
          inner join activity ac on ac.activity_id = prg.activity_id)
        on prg.productgroup_id = pr.productgroup_id)
      on pr.product_id = ilp.product_link_id)
    on ilp.invoiceline_id = il.invoiceline_id
    left outer join weighingcategory wc on wc.weighingcategory_id = ilp.weighingcategory_link_id,
  plant pl,
  country ct, currency plcr, reportparam rp
where ih.invoiceheader_id = il.invoiceheader_id
  and ih.status_id = st.status_id
  and st.statustype = 'IN'
  and st.code = '2'
  and ih.invoicebusinessunit_id = bu.businessunit_id
  and ih.billtocustomer_link_id = bcu.customer_id
  and ih.deltocustomer_link_id = dcu.customer_id
  and dcu.marketsegment_id = ms.marketsegment_id
  and dcu.visitaddress_id = ad.address_id
  and il.invoicelinetype_id = ilt.invoicelinetype_id
  and ((ih.invoicedate between rp.date_value1 and rp.date_value2)
	     or (ih.invoicedate between rp.date_value3 and rp.date_value4))
  and ilt.type <= 27
  and bu.plant_id = pl.plant_id
  and dcu.currency_id = cr.currency_id
  and pl.country_id = ct.country_id
  and ct.defaultcurrency_id = plcr.currency_id
  and il.extend = 'Y'
/

  CREATE OR REPLACE VIEW "V_INVOICEDISTRIBUTION" ("QTY", "INVOICEHEADER_ID", "STATUSQUODATE", "EMPLOYERPERCENTAGE", "INVOICENUMBER", "INVOICEDATE", "INVOICECOMMENTS", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "PRODUCTCODE", "PRODUCTDESCRIPTION", "INVOICELINETYPE", "INVOICELINETYPEDESCRIPTION", "PRICE", "DISCOUNTPERCENTAGE", "INVOICEAMOUNTDECIMALS", "PLANTNAME", "PLANTSTREET", "PLANTZIPCODE", "PLANTCITY") AS 
  Select 1 qty,
       PNL.InvoiceHeader_ID,
       sysdate StatusQuoDate,
       WIC.EmployerPercentage,
       IH.InvoiceNumber,
       IH.InvoiceDate,
       IH.InvoiceComments,
       IH.DelToCustomerNumber,
       IH.DelToCustomerName,
       IL.Code ProductCode,
       IL.Description ProductDescription,
       (select ilt.Type
          from InvoiceLineType ilt
         where ilt.invoicelinetype_id = il.invoicelinetype_id) InvoiceLineType,
       (select iltd.description
          from InvoiceLineType_desc iltd, customer del
         where iltd.invoicelinetype_id = il.invoicelinetype_id
           and del.customer_id = ih.deltocustomer_link_id
           and iltd.language_id = del.language_id) InvoiceLineTypeDescription,
       IL.Price,
       IL.DiscountPercentage,
       curr.invoiceamountdecimals,
       p.name plantname,
       x.street plantstreet,
       x.zipcode plantzipcode,
       x.city plantcity
  From PackingNote           PN,
       PackingNoteLine       PNL,
       DeliveryScan          DS,
       WearerInvoiceCategory WIC,
       weareremployment      we,
       InvoiceHeader         IH,
       InvoiceLine           IL,
       InvoiceLineProduct    ILP,
       currency              curr,
       businessunit          e,
       plant                 p,
       address               x
 Where PNL.PackingNote_ID = PN.PackingNote_ID
   And DS.PackingNote_ID = PN.PackingNote_ID
   And DS.Product_Link_ID = PNL.Product_ID
   and ds.sizedefinition_link_id = pnl.sizedefinition_id
   and ds.finishingmethod_id = pnl.finishingmethod_id
   and ds.chargewashing = 'Y'
   and wic.wearerinvoicecategory_id = ds.WearerInvoiceCategory_ID
   and ds.weareremployment_link_id = we.weareremployment_id
   and pnl.invoiceheader_id = ih.invoiceheader_id
   and IH.InvoiceHeader_ID = IL.InvoiceHeader_ID
   And IL.InvoiceLineType_ID = 2
   And ILP.InvoiceLine_ID = IL.InvoiceLine_ID
   and curr.currency_id = ih.currency_id
   and ih.invoicebusinessunit_id = e.businessunit_id
   and e.plant_id = p.plant_id
   and p.address_id = x.address_id
   and pnl.product_id = ilp.product_link_id
   and (pnl.sizedefinition_id = ilp.sizedefinition_link_id or
       ilp.sizedefinition_link_id =
       (select sd.sizedefinition_id
           from sizedefinition sd
          where sd.code = '*'))
   and pnl.finishingmethod_id = ilp.finishingmethod_id
   and ih.deltocustomer_link_id = ds.customer_link_id
   and ih.invoicebusinessunit_id = pn.invoicebusinessunit_id
union all
Select (SQIC.QtyRentedPerPiece + sqic.beyondlifetimecirc) qty,
       ih.invoiceheader_id InvoiceHeader_ID,
       SQH.StatusQuoDate,
       nvl((select wic.employerpercentage
             from wearerinvoicecategory wic,
                  weareremployment      we,
                  wearerinventory       wi,
                  wearer                w
            where wic.wearerinvoicecategory_id =
                  wi.wearerinvoicecategory_id
              and wi.weareremployment_id = we.weareremployment_id
              and wi.product_id = sqic.product_link_id
              and wi.sizedefinition_id = sqic.sizedefinition_link_id
              and wi.finishingmethod_id = sqic.finishingmethod_id
              and w.wearer_id = we.wearer_id
              and we.weareremployment_id = sqic.weareremployment_link_id
              and w.customer_id = ih.billtocustomer_link_id),
           100) EmployerPercentage,
       IH.InvoiceNumber,
       IH.InvoiceDate,
       IH.InvoiceComments,
       IH.DelToCustomerNumber,
       IH.DelToCustomerName,
       IL.Code ProductCode,
       IL.Description ProductDescription,
       (select ilt.Type
          from InvoiceLineType ilt
         where ilt.invoicelinetype_id = il.invoicelinetype_id) InvoiceLineType,
       (select iltd.description
          from InvoiceLineType_desc iltd, customer del
         where iltd.invoicelinetype_id = il.invoicelinetype_id
           and del.customer_id = ih.deltocustomer_link_id
           and iltd.language_id = del.language_id) InvoiceLineTypeDescription,
       IL.Price,
       IL.DiscountPercentage,
       curr.invoiceamountdecimals,
       p.name plantname,
       x.street plantstreet,
       x.zipcode plantzipcode,
       x.city plantcity
  From StatusQuoHeader     SQH,
       sqitemincirculation SQIC,
       InvoiceHeader       IH,
       InvoiceLine         IL,
       InvoiceLineProduct  ILP,
       currency            curr,
       businessunit        e,
       plant               p,
       address             x
 Where SQIC.StatusQuoHeader_ID = SQH.StatusQuoHeader_ID
   And SQH.StatusQuoType = 1 --Items in circulation
   And SQH.SubType = 0 --regular
   and SQIC.QtyRentedPerPiece + sqic.beyondlifetimecirc <> 0
   and IH.InvoiceHeader_ID = IL.InvoiceHeader_ID
   And IL.InvoiceLineType_ID = 1
   And ILP.InvoiceLine_ID = IL.InvoiceLine_ID
   and curr.currency_id = ih.currency_id
   and ih.invoicebusinessunit_id = e.businessunit_id
   and e.plant_id = p.plant_id
   and p.address_id = x.address_id
   and sqh.statusquodate >= ih.startdate
   and sqh.statusquodate <= ih.enddate
   and sqic.product_link_id = ilp.product_link_id
   and (sqic.sizedefinition_link_id = ilp.sizedefinition_link_id or
       ilp.sizedefinition_link_id =
       (select sd.sizedefinition_id
           from sizedefinition sd
          where sd.code = '*'))
   and sqic.finishingmethod_id = ilp.finishingmethod_id
   and ih.deltocustomer_link_id = sqic.customer_link_id
   and ih.invoicebusinessunit_id = SQH.InvoiceBusinessUnit_ID
/
CREATE OR REPLACE VIEW V_INVOICEHEADER AS 
select /*version 3.3*/
       ih.invoicedate, ih.invoiceyear, ih.invoiceweek, ih.invoicedaynumber, ih.invoicenumber, ih.documenttype, bu.code invoicebusinessunitcode, ih.invoicebusinessunit_id,
       bu.description invoicebusinessunitdesc, ih.billtocustomernumber, ih.billtocustomername, ih.extraname1, ih.extraname2, ih.deltocustomernumber, ih.deltocustomername, ih.paidamount,
       ih.startweek, ih.endweek, ih.startmonth, ih.endmonth, ih.startyear, ih.endyear, ih.city, ih.county, ih.state, ih.zipcode, ih.street2, ih.street, ih.routenumber, ih.stopnumber,
       ih.depotcode, ih.contactpersonname, ih.contactpersonphone, ih.emailstatus, ih.emailaddress, ih.realcollectiontype, ih.originalcollectiontype, ih.invoicetype, ih.exported,
       ih.contractcode, ih.purchaseorder, ih.deliverinstructions, ih.invoicecomments, ih.totalminusadjustment, ih.totalplusadjustment, ih.cashcollected, ih.paythisamount, ih.prebillamount,
       ih.invoicefrequency_id invoicefrequencynumber, curr.code currencycode, curr.description currencydesc, s.statustype, s.code statuscode, s.factorydescription statusfactorydescription,
       p.code plantcode, p.name plantname, ad.street plantstreet, ad.street2 plantstreet2, ad.zipcode plantzipcode, ad.city plantcity, ad.state plantstate, ad.county plantcounty, ad.street3 plantstreet3,
       p.phoneno plantphone, p.faxno plantfax, p.website plantwebsite, p.email plantemail, ih.city billto_city, ih.street billto_street, ih.street2 billto_street2, ih.state billto_state,
       ih.zipcode billto_zipcode, ih.routecontrol_id, ih.adjustmentreason_id, ih.systemuser_id, ih.timestamp, ih.parentinvoiceheader_id, ih.contractstartdate, ih.contractenddate,
       ihextr.bankaccount, ihextr.ibanno, cbank.idcode cust_bank_idcode, cbank.description cust_bank_desc, cbank.internalidcode cust_bank_internid, cbank.laundrybankaccount cust_lndrybankaccount,
       cbank.ibanno cust_ibanno, lbank.idcode lndry_bank_idcode, lbank.description lndry_bank_desc, lbank.internalidcode lndry_bank_internid, lbank.laundrybankaccount lndry_bank_lndrybankaccount,
       lbank.ibanno lndry_bank_ibanno, ih.paymentdiscountdays, p.invoiceremarkstartdate, p.invoiceremarkenddate, bu.internalvatnumber, bu.vatnumber, ih.creditsqueezeperc, ih.netpaymentdays,
       ih.deltostreet, ih.deltostreet2, ih.deltocounty, ih.deltocity, ih.deltozipcode, ih.deltostate, co.description plantcountrydescription, ss.value weightunit, ih.roundingamount,
       ih.nextperiodstartdate, ih.nextperiodenddate, ih.nextperiodnoweeks, ihextr.paymenttype, ihextr.discountdays, ihextr.paymentdiscount, ihextr.discountdays2, ihextr.paymentdiscount2,
       ih.invoiceheader_id, ih.creditsqueezeamount, curr.invoiceamountdecimals, curr.description currencydescription, ih.totalamountexclvat, curr.decimals, ih.startdate, ih.enddate,
       ihextr.billtocountrydescription, ih.splitupcode, ih.splitupdescription, ihs.personidentification, ihs.signature, ihextr.deltocountrydescription, ihextr.deltocustvatnumber,
       rc.code adjustment_reasoncode, ihextr.customermarkinggarment, ihextr.taxable, ihextr.siccode, ihextr.invoicecopies, ihextr.attachinvoicecopies, ih.activityreference, ih.deltostreet3,
       ihextr.paymenttermsdescription paymentterms_desc, ihextr.formlayoutcode invoicelayoutcode, bu.code default_bu_code, ihextr.paymenttermsduedate, ih.reference, ih.street3 billto_street3,
       cad.street billto_invoicestreet, cad.street2 billto_invoicestreet2, cad.city billto_invoicecity, cad.state billto_invoicestate, cad.zipcode billto_invoicezipcode,
       cast(fsget_custdeliveryscheme(ih.route_id, ih.deltocustomer_link_id) as varchar2(6)) custdeliveryscheme,
       cast(fsget_cust_delivery_days(ih.deltocustomer_link_id) as varchar2(7)) cust_delivery_days,
       cast(getsortusasc(ih.routenumber, ih.stopnumber, ih.deltocustomernumber, ih.invoicenumber) as varchar2(255)) as m_sort_us_asc,
       cast(getsortusdesc(ih.routenumber, ih.stopnumber, ih.deltocustomernumber, ih.invoicenumber) as varchar2(255)) as m_sort_us_desc,
       cast(ss1.value as numeric) weightdecimalsmanualinput,
       cast(fsget_min_5_yearweeks(ih.invoiceheader_id, ih.invoicefrequency_id) as varchar2(39)) min_year_weeks,
       case when ih.cluster_id is null then (select max(c.code)
                                               from customerspercluster cpc, customercluster c
                                              where c.invoicefrequency_id = ih.invoicefrequency_id
                                                and cpc.cluster_id = c.cluster_id and cpc.customer_id = ih.billtocustomer_link_id)
            else (select cc.code
                    from customercluster cc
                   where cc.cluster_id = ih.cluster_id)
        end clustercode,
       case when (ihs.signature is null) then 'N'
            else 'Y'
        end hassignature,
       (select rtes.soiltickets
          from routestop rtes
         where rtes.route_id = ih.route_id
           and rtes.stopnumber = ih.stopnumber
           and rtes.customer_id = ih.deltocustomer_link_id) no_of_soiltickets,
       (select max(ilv.percentage)
          from invoiceline il
               join invoicelinevarious ilv on il.invoiceline_id = ilv.invoiceline_id
         where il.invoiceheader_id = ih.invoiceheader_id
           and il.invoicelinetype_id = 18) max_percentage,
       (select empl.name
          from routecontrol rcntrl
               join employee empl on rcntrl.drivernumber = empl.employeenumber and rcntrl.plant_id = empl.plant_id
         where rcntrl.routecontrol_id = ih.routecontrol_id) drivername,
       (select pldesc.invoiceremark
          from plantinvoiceremark_desc pldesc
         where pldesc.plant_id = p.plant_id
           and pldesc.language_id = p.language_id) generalinv_remark_plant,
       (select pldesc.invoiceremark
          from plantinvoiceremark_desc pldesc
         where pldesc.plant_id = p.plant_id
           and pldesc.language_id = (select c.language_id
                                       from customer c
                                      where c.customer_id = ih.deltocustomer_link_id)) generalinv_remark_customer,
       coalesce((select max(pa.packingnote_id)
                   from packingnote pa, packingnoteline pl
                  where pa.packingnote_id = pl.packingnote_id
                    and pl.invoiceheader_id = ih.invoiceheader_id
                    and ih.invoicefrequency_id = 0 and pa.origin = 5), 0) setspecial,  --0 is not based on special order, >0 is based on special order
       (select lan.code
          from languages lan join customer cu on lan.language_id = cu.language_id
         where ih.deltocustomer_link_id = cu.customer_id) deltocustlang,
       cu.printtaxonappendix,
       (select max(wo.referencenumber)
          from workorder wo
         where wo.invoiceheader_id = ih.invoiceheader_id
         group by wo.referencenumber) worefnr,
       cu.legalname  billto_legalname, cu.extraname1 billto_extraname1,
       (select lan.code
          from languages lan
         where cu.language_id = lan.language_id) customerlanguage,
       (select cast(ss2.value as numeric)
          from systemsetting ss2
         where p.plant_id = ss2.plant_id and ss2.name = 'CREDITSQUEEZETYPE') creditsqueezetype,
       (select cbc.description from customerbillingcomment cbc where cbc.customer_id = nvl(ih.deltocustomer_link_id, ih.billtocustomer_link_id)) custdeltocomment
  from invoiceheader ih
       left join reasoncode rc on ih.adjustmentreason_id = rc.reasoncode_id
       left join invoicesignature ihs on ih.invoiceheader_id = ihs.invoiceheader_id
       join invoiceheaderextrainfo ihextr
            left join bankinstitution cbank on ihextr.bankinstitution_id = cbank.bankinstitution_id
            left join bankinstitution lbank on ihextr.laundrybankinstitution_id = lbank.bankinstitution_id
       on ih.invoiceheader_id = ihextr.invoiceheader_id
       join currency curr on ih.currency_id = curr.currency_id
       join customer cu
            join address cad on cu.invoiceaddress_id = cad.address_id
       on ih.billtocustomer_link_id = cu.customer_id
       join businessunit bu
            join plant p
                 left join systemsetting ss on p.plant_id = ss.plant_id and ss.name = 'WEIGHTUNIT'
                 left join systemsetting ss1 on p.plant_id = ss1.plant_id and ss1.name = 'WEIGHTDECIMALSMANUALINPUT'
                 join address ad on p.address_id = ad.address_id
                 join country co on p.country_id = co.country_id
            on bu.plant_id = p.plant_id
       on ih.invoicebusinessunit_id = bu.businessunit_id
       join status s on ih.status_id = s.status_id
 where ih.documenttype in (1, 8)
/

  CREATE OR REPLACE VIEW "V_INVOICEJOURNAL" ("INVOICENUMBER", "INVOICEDATE", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "PAYMENTTYPE", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "BUSINESSUNITCODE", "BUSINESSUNITDESC", "CLUSTERCODE", "CLUSTERDESC", "MARKETSEGMENTCODE", "MARKETSEGMENTDESC", "SALESAREACODE", "SALESAREADESC", "CHAINCODE", "CHAINNAME", "NETAMOUNT", "GROSSAMOUNT", "CURRENCYCODE", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE", "SYSTEMUSER_ID") AS 
  SELECT A.INVOICENUMBER, A.INVOICEDATE,
  C.CUSTOMERNUMBER DELTOCUSTOMERNUMBER, C.NAME DELTOCUSTOMERNAME, C.PAYMENTTYPE,
  J.CUSTOMERNUMBER BILLTOCUSTOMERNUMBER, J.NAME BILLTOCUSTOMERNAME,
  D.CODE BUSINESSUNITCODE, D.DESCRIPTION BUSINESSUNITDESC,
  E.CODE CLUSTERCODE,
  E.DESCRIPTION CLUSTERDESC,
  F.CODE MARKETSEGMENTCODE,
  (SELECT X.DESCRIPTION FROM MARKETSEGMENT_DESC X WHERE X.MARKETSEGMENT_ID = F.MARKETSEGMENT_ID
     AND X.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) MARKETSEGMENTDESC,
  G.CODE SALESAREACODE,
  (SELECT Y.DESCRIPTION FROM SALESAREA_DESC Y WHERE Y.SALESAREA_ID = G.SALESAREA_ID
     AND Y.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SALESAREADESC,
  H.CODE CHAINCODE, H.NAME CHAINNAME,
  A.TOTALAMOUNTEXCLVAT NETAMOUNT, A.PAYTHISAMOUNT GROSSAMOUNT,
  CURR.CODE CURRENCYCODE, CURR.INVOICEAMOUNTDECIMALS, LANGUAGES.CODE LANGUAGECODE
  , s.systemuser_id
FROM INVOICEHEADER A
		LEFT OUTER JOIN CUSTOMERCLUSTER E ON A.CLUSTER_ID = E.CLUSTER_ID
  , CURRENCY CURR, CUSTOMER C
    LEFT OUTER JOIN CHAIN H ON C.CHAIN_ID = H.CHAIN_ID
  , BUSINESSUNIT D, MARKETSEGMENT F, SALESAREA G, STATUS I, CUSTOMER J, LANGUAGES
  , Systemuser s, businessunitsperusergroup bug
WHERE A.CURRENCY_ID = CURR.CURRENCY_ID
  AND A.BILLTOCUSTOMER_LINK_ID = J.CUSTOMER_ID
  AND A.DELTOCUSTOMER_LINK_ID = C.CUSTOMER_ID
  AND A.INVOICEBUSINESSUNIT_ID = D.BUSINESSUNIT_ID
  AND C.MARKETSEGMENT_ID = F.MARKETSEGMENT_ID
  AND C.SALESAREA_ID = G.SALESAREA_ID
  AND A.STATUS_ID = I.STATUS_ID
  AND I.STATUSTYPE = 'IN'
  AND I.CODE = 2
  AND (A.PARENTINVOICEHEADER_ID IS NULL OR A.PARENTINVOICEHEADER_ID = A.INVOICEHEADER_ID)
  AND s.usergroup_id = bug.usergroup_id AND d.businessunit_id = bug.businessunit_id
/

  CREATE OR REPLACE VIEW "V_INVOICELINETAX" ("INVOICEHEADER_ID", "AMOUNT", "INVOICELINETYPE_ID", "PERCENTAGE", "OVERAMOUNT") AS 
  select il.invoiceheader_id, il.amount, il.invoicelinetype_id, ilv.percentage, ilv.overamount
from invoiceline il, invoicelinevarious ilv
where il.invoiceline_id = ilv.invoiceline_id
/

  CREATE OR REPLACE VIEW "V_INVOICELINE_CCG" ("INVOICEDATE", "INVOICENUMBER", "LINENUMBER", "INVOICELINETYPE", "INVOICELINETYPEDESC", "CODE", "TAXCODE", "DESCRIPTION", "ADJUSTEDAMOUNT", "ADJUSTEDPRICE", "ADJUSTMENTBILLEDQTY", "EXTEND", "AMOUNT", "DISCOUNTPERCENTAGE", "PRICE", "BILLEDQTY", "TAXGROUPCODE", "TAXTYPE", "SUBJECTTOMINIMUM", "TURNOVERGROUPCODE", "TURNOVERGROUPDESCRIPTION", "INVOICELINESUBTYPE", "PRODUCTGROUPCODE", "PRODUCTGROUPDESCRIPTION", "PRODUCTSHORTDESCRIPTION", "SHORTDESCRIPTION", "SIZECODE", "SIZEDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "INVOICEQTYCOLUMN", "INVENTORYQTY", "DELIVEREDQTY", "ABUSEDQUANTITY", "SOILQUANTITY", "SOILCOUNTMETHOD", "BILLINGMETHOD", "WEARERNUMBER", "WEARERNAME", "WEARERADMINNR", "WEARERBANK", "WEARERLOCKER", "TRANSACTIONTYPE", "TRANSACTIONDATE", "PERCENTAGE", "SYSTEMUSER_ID", "TIMESTAMP", "INVOICELINE_ID", "REMARK", "LANGUAGECODE", "INVOICEHEADER_ID", "OVERAMOUNT", "REPLACEMENTPRICE", "PRODUCTDESCRIPTION", "REGISTRATIONUNITDESCRIPTION", "ADJUSTMENTREASON_CODE", "INVOICELINE_SEQUENCENUMBER", "SUPRESSPRINTING") AS 
  select f.invoicedate, f.invoicenumber, a.linenumber,
(CASE WHEN e.TYPE = 1 AND a.invoicelinesubtype = 8
      THEN 1.5
	    ELSE e.TYPE
END)  invoicelinetype,
(CASE WHEN e.TYPE = 1 AND a.invoicelinesubtype = 8
      THEN   'Addition/Replacement'
	    ELSE ( SELECT DESCRIPTION FROM invoicelinetype_DESC z WHERE z.invoicelinetype_id = a.invoicelinetype_id AND z.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
END) invoicelinetypedesc, a.code
, cast(FSGET_TAXCODE(f.invoicenumber, a.linenumber) as varchar2(255)) taxcode
, a.description,a.adjustedamount, a.adjustedprice, a.adjustmentbilledqty, a.extend, a.amount, a.discountpercentage,
a.price, a.billedqty, a.taxgroupcode, a.taxtype, a.subjecttominimum, d.code turnovergroupcode,
( SELECT DESCRIPTION FROM TURNOVERGROUP_DESC T WHERE T.TURNOVERGROUP_ID = A.TURNOVERGROUP_ID AND T.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) turnovergroupdescription,
a.invoicelinesubtype, b.productgroupcode, b.productgroupdescription, b.productshortdescription
, cast(FSGET_CODE(f.invoicenumber, a.linenumber) as varchar2(255)) shortdescription
, b.sizecode, b.sizedescription, b.finishingmethodcode, b.finishingmethoddescription, b.invoiceqtycolumn, b.inventoryqty,
b.deliveredqty, b.abusedquantity, b.soilquantity, b.soilcountmethod, b.billingmethod, b.wearernumber, b.wearername,
b.weareradminnr, b.wearerbank, b.wearerlocker, c.transactiontype, c.transactiondate, c.percentage,
a.systemuser_id, a.timestamp, a.invoiceline_id, a.remark, LANGUAGES.CODE LANGUAGECODE,
a.invoiceheader_id, c.overamount, b.replacementprice,
 ( SELECT PD.DESCRIPTION FROM PRODUCT_LINK_DESC pd WHERE pd.product_link_id = b.product_link_id AND pd.language_id = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
 ( SELECT PD.REGISTRATIONUNITDESCRIPTION FROM PRODUCT_LINK_DESC pd WHERE pd.product_link_id = b.product_link_id AND pd.language_id = LANGUAGES.LANGUAGE_ID) REGISTRATIONUNITDESCRIPTION,
 ( SELECT rc.code FROM reasoncode rc WHERE rc.reasoncode_id = a.adjustmentreason_id) ADJUSTMENTREASON_CODE,
 ( SELECT pilt.sequencenumber
         from plantinvoicelinetype pilt, businessunit bu, invoiceheader h
         where a.invoiceheader_id = h.invoiceheader_id
               and h.invoicebusinessunit_id = bu.businessunit_id
               and bu.plant_id = pilt.plant_id
               and pilt.invoicelinetype_id = a.invoicelinetype_id) InvoiceLine_SequenceNumber,
e.supressprinting
from invoiceline a
LEFT OUTER JOIN invoicelineproduct b ON (a.invoiceline_id = b.invoiceline_id)
LEFT OUTER JOIN invoicelinevarious c ON (a.invoiceline_id = c.invoiceline_id)
LEFT OUTER JOIN turnovergroup d ON (a.turnovergroup_id = d.turnovergroup_id),
invoicelinetype e, invoiceheader f, LANGUAGES
where a.invoicelinetype_id = e.invoicelinetype_id
and a.invoiceheader_id = f.invoiceheader_id
and f.documenttype = 1
/

  CREATE OR REPLACE VIEW "V_INVOICEVALIDATION" ("BU_CODE", "BU_DESC", "BUSINESSUNIT_ID", "ROUTENUMBER", "ROUTE_DESC", "INVOICEHEADER_ID", "INVOICENUMBER", "INVOICEDATE", "CREATIONTIMESTAMP", "DELTOCUSTOMER_LINK_ID", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "BILLTOCUSTOMER_LINK_ID", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "INVOICETYPE", "PREBILLAMOUNT", "CURRENCYCODE", "INVOICEAMOUNTDECIMALS", "DECIMALS", "LAST4WEEKSAVG") AS 
  select ibu.code bu_code, ibu.description bu_desc, ibu.businessunit_id,
       ro.routenumber, ro.description route_desc,
       ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.creationtimestamp,
       ih.deltocustomer_link_id, ih.deltocustomernumber, ih.deltocustomername,
       ih.billtocustomer_link_id, ih.billtocustomernumber, ih.billtocustomername,
       ih.invoicetype, ih.prebillamount, cur.code currencycode, cur.invoiceamountdecimals, cur.decimals,
       nvl((select sum(ih2.prebillamount) / count(1)
       from invoiceheader ih2 where ih2.deltocustomer_link_id = ih.deltocustomer_link_id
       and ih2.invoicedate >= (sysdate - 28) and ih2.invoicedate <= sysdate), 0) Last4WeeksAVG
  from invoiceheader ih
  join businessunit ibu on ih.invoicebusinessunit_id = ibu.businessunit_id
  join route ro on ih.route_id = ro.route_id
  join currency cur on ih.currency_id = cur.currency_id
  join status st on ih.status_id = st.status_id
 where st.code <> '3'
/

  CREATE OR REPLACE VIEW "V_INVOICEWASHDELIVERYNOTES" ("LINETYPE", "NOTENUMBER", "INVOICEHEADER_ID", "QTY", "DELIVERYDATE", "PRODUCT_ID", "SIZEDEFINITION_ID", "FINISHINGMETHOD_ID", "CUSTOMER_LINK_ID") AS 
  select 1 linetype, F_GetNoteNumbersOnDate(pn.deliverydate, pnl.invoiceheader_id, pnl.product_id, pnl.sizedefinition_id, pnl.finishingmethod_id) notenumber, pnl.invoiceheader_id,
(pnl.deliveredamount-pnl.nochargefirstissue) qty, pn.deliverydate, pnl.product_id, pnl.sizedefinition_id,pnl.finishingmethod_id
, (select dpt.customer_id from distributionpoint dp, department dpt
where pn.distributionpoint_id = dp.distributionpoint_id and dp.department_id = dpt.department_id) customer_link_id
from packingnote pn, packingnoteline pnl
where pn.packingnote_id = pnl.packingnote_id
and nvl(pnl.invoiceheader_id,0) > 0
union all
select 2 linetype, null notenumber, osia.invoiceheader_id, -sum(osia.quantity) qty,
osia.inventorydate  deliverydate,
p.product_id product_id,sd.sizedefinition_id,fm.finishingmethod_id, d.customer_id customer_link_id
from onsiteinventoryadjustment osia, productlistperdistribpoint plpd, distributionpoint dp,
department d, product p, sizedefinition sd, finishingmethod fm
where osia.productlistperdistribpoint_id=plpd.productlistperdistribpoint_id
and plpd.distributionpoint_id=dp.distributionpoint_id
and dp.department_id=d.department_id
and plpd.product_id=p.product_id
and plpd.sizedefinition_id=sd.sizedefinition_id
and plpd.finishingmethod_id=fm.finishingmethod_id
and osia.origin in (4,6)
and nvl(osia.invoiceheader_id,0) > 0
group by osia.invoiceheader_id,osia.inventorydate, p.product_id ,sd.sizedefinition_id,fm.finishingmethod_id, d.customer_id
/

  CREATE OR REPLACE VIEW "V_INVOICE_FOR_IMPORT_US" ("INVOICEHEADER_ID", "INVOICELINE_ID", "DOCUMENTTYPE", "INVOICENUMBER", "LINENUMBER", "CODE", "INVOICELINETYPE_ID", "DELTOCUSTOMER_LINK_ID", "BILLTOCUSTOMER_LINK_ID", "INVOICEDATE") AS 
  select a.invoiceheader_id, b.invoiceline_id, a.documenttype, a.invoicenumber,
    b.linenumber, b.code, b.invoicelinetype_id,
    a.deltocustomer_link_id, a.billtocustomer_link_id, a.invoicedate
	from invoiceheader a left outer join invoiceline b on a.invoiceheader_id = b.invoiceheader_id
/

  CREATE OR REPLACE VIEW "V_INVOICE_RECEIPT" ("INVOICEHEADER_ID", "INVOICENUMBER", "INVOICEDATE", "PREBILLAMOUNT", "PAYTHISAMOUNT", "CASHCOLLECTED", "TOTALAMOUNTEXCLVAT", "TOTALMINUSADJUSTMENT", "TOTALPLUSADJUSTMENT", "DELTOCUSTOMERNAME", "DELTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "BILLTOCUSTOMERNUMBER", "BUSINESSUNIT_CODE", "BUSINESSUNIT_DESC", "PLANT_CODE", "PLANT_NAME", "PLANT_CITY", "CURRENCY_CODE", "CURRENCY_DESC", "INVOICEAMOUNTDECIMALS", "VAT_PERCENTAGE") AS 
  select h.invoiceheader_id, h.invoicenumber, h.invoicedate,
       h.prebillamount, h.paythisamount, h.cashcollected,
       h.totalamountexclvat, h.totalminusadjustment, h.totalplusadjustment,
       h.deltocustomername, h.deltocustomernumber,
       h.billtocustomername, h.billtocustomernumber,
       businessunit.code businessunit_code, businessunit.description businessunit_desc,
       plant.code plant_code, plant.name plant_name, a.city plant_city,
       c.code currency_code, c.description currency_desc, c.invoiceamountdecimals,
       (select MAX(lv.percentage) from invoiceline l, invoicelinevarious lv, invoicelinetype t
               where l.invoiceheader_id = h.invoiceheader_id
                     and lv.invoiceline_id = l.invoiceline_id
                     and l.invoicelinetype_id = t.invoicelinetype_id
                     and t.type = 18) VAT_PERCENTAGE
from invoiceheader h, businessunit businessunit, plant, currency c, address a
where h.invoicebusinessunit_id = businessunit.businessunit_id
      and businessunit.plant_id = plant.plant_id
      and h.documenttype = 1
      and h.currency_id = c.currency_id
      and plant.address_id = a.address_id
/

  CREATE OR REPLACE VIEW "V_ISSUEDBARCODES" ("YEAR", "WEEK", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "WEARERNUMBER", "WEARERNAME", "PRODUCTCODE", "PRODUCTDESC", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESC", "QUANTITY", "PREPCHARGE", "INVOICEHEADER_ID", "INCIRCDATE", "BU_CODE", "BU_DESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "PRIMARYID", "REASONCODE", "REASONDESC", "TRANSACTIONTYPEDESC", "SCANTIMESTAMP", "CHAIN_CODE", "LANGUAGECODE") AS 
  select  -1 year, -1 week,
 subsel.departmentnumber, subsel.departmentdesc,
 subsel.wearernumber, subsel.wearername,
 subsel.productcode,
 (select z.description from product_link_desc z where z.product_link_id = subsel.product_link_id
  and z.language_id = subsel.language_id) productdesc, subsel.sizedefinitionCode,
 (select k.description from sizedefinition_link_desc k where k.sizedefinition_link_id = subsel.sizedefinition_link_id
 and k.language_id = subsel.language_id ) sizedefinitionDesc,
 subsel.quantity, subsel.prepcharge,subsel.invoiceheader_id,
 subsel.incircdate,
 subsel.bu_code, subsel.bu_desc, subsel.customernumber, subsel.customername,
 subsel.primaryid,
 coalesce((select rc.code from workorder wo, reasoncode rc where subsel.issuedbyworkorder_id=wo.workorder_id and wo.reasoncode_id = rc.reasoncode_id),
         (select rc.code from reasoncode rc where subsel.reasoncode_id = rc.reasoncode_id)) reasoncode,
 coalesce((select rd.description from workorder wo, reasoncode_desc rd where subsel.issuedbyworkorder_id=wo.workorder_id and wo.reasoncode_id = rd.reasoncode_id and rd.language_id = subsel.language_id),
         (select rd.description from reasoncode_desc rd where subsel.reasoncode_id = rd.reasoncode_id and rd.language_id = subsel.language_id)) reasondesc,
 (select max(ttd.description) from transactiontype_desc ttd, scan sc where sc.transactiontype_id = ttd.transactiontype_id and ttd.language_id = subsel.language_id and subsel.uniqueitem_id = sc.uniqueitem_link_id
 and sc.scantimestamp = MaxScanTime.scantimestamp) transactiontypedesc,
 MaxScanTime.scantimestamp,
(SELECT ch.code FROM chain ch, customer c WHERE c.customer_id = subsel.customer_id AND ch.chain_id = c.chain_id) chain_code,
 subsel.languagecode
FROM
(
select e.departmentnumber, e.description departmentdesc,
 w.wearernumber, w.wearername,
 p.code productcode, a.product_link_id, languages.language_id, s.code sizedefinitionCode,
 s.sizedefinition_link_id,
 a.quantity, --coalesce(a.prepcharge, 0) prepcharge, a.invoiceheader_id,
 0 prepcharge, -1 invoiceheader_id,
 coalesce((select uif.lastissuedate from uniqueitemfixedinfo uif where uif.uniqueitem_id = ui.uniqueitem_id), a.incircdate) incircdate,
 bu.code bu_code, bu.description bu_desc, f.customernumber, f.name customername,
 ui.primaryid, coalesce(a.workorder_id,-1) issuedbyworkorder_id, a.reasoncode_id,
 ui.uniqueitem_id,
 f.customer_id,
 languages.code languagecode
from issuehistory a
 left outer join weareremployment_link w
 on a.weareremployment_link_id = w.weareremployment_link_id,
 distributionpoint_link d, department_link e, customer_link f, product_link p,
 languages, sizedefinition_link s, businessunit bu, uniqueitem ui
where a.distributionpoint_link_id = d.distributionpoint_link_id
 and d.department_link_id = e.department_link_id
 and a.product_link_id = p.product_link_id
 and a.sizedefinition_link_id = s.sizedefinition_link_id-- and a.issuestatus = 0 -- todo 3876
 and a.processbusinessunit_id = bu.businessunit_id
 and a.customer_link_id = f.customer_link_id
 and ui.uniqueitem_id = a.uniqueitem_link_id
union
select e.departmentnumber, e.description departmentdesc,
 w.wearernumber, w.wearername,
 p.code productcode, p.product_link_id, languages.language_id, s.code sizedefinitionCode,
 s.sizedefinition_link_id,
 1 quantity, 0 prepcharge, -1 invoiceheader_id,
 uif.lastissuedate incircdate,
 bu.code bu_code, bu.description bu_desc, f.customernumber, f.name customername,
 ui.primaryid, coalesce(uif.issuedbyworkorder_id,-1) issuedbyworkorder_id, uif.reasoncode_id,
 ui.uniqueitem_id,
 f.customer_id,
 languages.code languagecode
from weareremployment_link w
     inner join uniqueitemnonpool unp
     on unp.weareremployment_id = w.weareremployment_link_id,
 distributionpoint_link d, department_link e, customer_link f, product_link p,
 languages, sizedefinition_link s, businessunit bu, uniqueitem ui, uniqueitemfixedinfo uif
where w.distributionpoint_link_id = d.distributionpoint_link_id
 and d.department_link_id = e.department_link_id
 and ui.product_id = p.product_link_id
 and ui.sizedefinition_id = s.sizedefinition_link_id
 and ui.businessunit_id = bu.businessunit_id
 and e.customer_link_id = f.customer_link_id
 and ui.uniqueitem_id = unp.uniqueitem_id
 and uif.uniqueitem_id = ui.uniqueitem_id
 ) subsel,
 (select sc2.uniqueitem_link_id, max(sc2.scantimestamp) scantimestamp
  from scan sc2 group by sc2.uniqueitem_link_id) MaxScanTime
where subsel.uniqueitem_id = MaxScanTime.uniqueitem_link_id
/

  CREATE OR REPLACE VIEW "V_ISSUEHISTORY" ("YEAR", "WEEK", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "WEARERNUMBER", "WEARERNAME", "PRODUCTCODE", "PRODUCTDESC", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESC", "QUANTITY", "PREPCHARGE", "INVOICEHEADER_ID", "LANGUAGECODE", "LANGUAGE_ID") AS 
  select
 a.assignyear year, a.assignweek week,
 e.departmentnumber, e.description departmentdesc,
 w.wearernumber, w.wearername,
 p.code productcode,
 (select description from product_link_desc z where z.product_link_id = a.product_link_id
  and z.language_id = languages.language_id) productdesc, s.code sizedefinitionCode,
 (select description from sizedefinition_link_desc k where k.sizedefinition_link_id = s.sizedefinition_link_id
 and k.language_id = languages.language_id ) sizedefinitionDesc,
 a.quantity, coalesce(a.prepcharge, 0) prepcharge, a.invoiceheader_id, languages.code languagecode,languages.language_id
from issuehistory a
 left outer join weareremployment_link w on (a.weareremployment_link_id = w.weareremployment_link_id),
 distributionpoint_link d, department_link e, product_link p, languages, sizedefinition_link s
where a.distributionpoint_link_id = d.distributionpoint_link_id
 and d.department_link_id = e.department_link_id
 and a.product_link_id = p.product_link_id
 and a.sizedefinition_link_id = s.sizedefinition_link_id
 and a.issuestatus = 0
 and ((a.quantity*coalesce(a.prepcharge, 0)) <> 0) --todo 23122
/

  CREATE OR REPLACE VIEW "V_ITEMACTIVITY" ("LINETYPE", "DATEACTIVE_CUST", "DATEINACTIVE_CUST", "DEFAULTBUSINESSUNIT_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "STREET", "CITY", "ZIPCODE", "PHONENO", "PAYMENTMETHOD", "MINIMUMINVOICEAMOUNT", "DATEACTIVE_PLPC", "DATEINACTIVE_PLPC", "BILLINGMETHOD", "PRODUCTGROUPCODE", "PRODUCTCODE", "TYPEOFMERCHANDISE", "SIZECODE", "PRODUCTDESC", "CUST_DELIVERY_DAYS", "CUST_DELIVERY_ROUTES", "DELIVERYSCHEME_CODE", "PROD_DELIVERY_DAYS", "SRCMETHOD", "SRCPERCENTAGESOILCOUNT", "SRCPERCENTAGEINVENTORY", "MINIMUMTURNAROUND", "FIXED", "INVENTORY", "UNITPRICE", "LANGUAGECODE", "REPORTPARAM_ID", "PRODUCT_ID", "SIZEDEFINITION_ID", "FINISHINGMETHOD_ID", "CUSTOMER_ID", "LAST_8_DELIVERIES", "DATE_VALUE1", "NUMBER_VALUE1", "NUMBER_VALUE2", "STRING_VALUE1", "STRING_VALUE2", "STRING_VALUE3", "STRING_VALUE4") AS 
  SELECT P.TYPEOFMERCHANDISE LINETYPE, CU.DATEACTIVE DATEACTIVE_CUST,
       CU.DATEINACTIVE DATEINACTIVE_CUST, CU.DEFAULTBUSINESSUNIT_ID, CU.CUSTOMERNUMBER,
       CU.NAME CUSTOMERNAME, ADR.STREET, ADR.CITY, ADR.ZIPCODE, CU.PHONENO, CU.PAYMENTMETHOD,
       CU.MINIMUMINVOICEAMOUNT, PLPC.DATEACTIVE DATEACTIVE_PLPC, PLPC.DATEINACTIVE DATEINACTIVE_PLPC,
       PLPC.BILLINGMETHOD, PG.CODE PRODUCTGROUPCODE, P.CODE PRODUCTCODE, P.TYPEOFMERCHANDISE,
  (SELECT SD.CODE FROM SIZEDEFINITION SD WHERE SD.SIZEDEFINITION_ID = PLPC.SIZEDEFINITION_ID) SIZECODE,
 (SELECT PD.DESCRIPTION
         FROM   PRODUCT_DESC PD
         WHERE  P.PRODUCT_ID = PD.PRODUCT_ID
         AND    PD.LANGUAGE_ID = LAN.LANGUAGE_ID) PRODUCTDESC,
       GET_CUST_DELIVERY_DAYS(CU.CUSTOMER_ID) CUST_DELIVERY_DAYS,
       GET_CUST_DELIVERY_ROUTES(CU.CUSTOMER_ID) CUST_DELIVERY_ROUTES,
       GET_DELIVERYSCHEME_CODE(CU.CUSTOMER_ID, PLPC.PRODUCT_ID, PLPC.SIZEDEFINITION_ID,
                                PLPC.FINISHINGMETHOD_ID) DELIVERYSCHEME_CODE,
       GET_PROD_DELIVERY_DAYS(PLPC.PRODUCTLISTPERCUSTOMER_ID) PROD_DELIVERY_DAYS, PLPC.SRCMETHOD,
       PLPC.SRCPERCENTAGESOILCOUNT, PLPC.SRCPERCENTAGEINVENTORY, PLPC.MINIMUMTURNAROUND,
       CASE
         WHEN (P.TYPEOFMERCHANDISE = 1 AND PLPC.BILLINGMETHOD = 1) THEN
          (SELECT SUM(SDL.FIXEDRENTQUANTITY)
           FROM   STANDARDDELIVERYLINE SDL, PRODUCTLISTPERDISTRIBPOINT PLPD, DISTRIBUTIONPOINT DP,
                  DEPARTMENT DEP
           WHERE  SDL.DATEACTIVE <= RP.DATE_VALUE1
           AND    SDL.DATEINACTIVE > RP.DATE_VALUE1
           AND    SDL.PRODUCTLISTPERDISTRIBPOINT_ID = PLPD.PRODUCTLISTPERDISTRIBPOINT_ID
           AND    DP.DISTRIBUTIONPOINT_ID = PLPD.DISTRIBUTIONPOINT_ID
           AND    DP.DEPARTMENT_ID = DEP.DEPARTMENT_ID
           AND    DEP.CUSTOMER_ID = CU.CUSTOMER_ID
           AND    PLPD.PRODUCT_ID = PLPC.PRODUCT_ID)
         ELSE -1
       END FIXED,
       CASE
         WHEN (P.TYPEOFMERCHANDISE = 2 AND PLPC.BILLINGMETHOD = 2 AND PLPC.MINIMUMQUANTITY > 0) THEN
          PLPC.MINIMUMQUANTITY
         WHEN (P.TYPEOFMERCHANDISE = 2 AND PLPC.BILLINGMETHOD = 2 AND PLPC.MINIMUMQUANTITY = 0) THEN
          (SELECT PLPC.MINIMUMTURNAROUND * SUM(RQA.QUANTITY) / 100
           FROM   RENTALQTYADJUSTMENT RQA, PRODUCTLISTPERDISTRIBPOINT PLPD, DISTRIBUTIONPOINT DP,
                  DEPARTMENT DEP
           WHERE  RQA.ADJUSTMENTDATE <= RP.DATE_VALUE1
           AND    RQA.PRODUCTLISTPERDISTRIBPOINT_ID = PLPD.PRODUCTLISTPERDISTRIBPOINT_ID
           AND    DP.DISTRIBUTIONPOINT_ID = PLPD.DISTRIBUTIONPOINT_ID
           AND    DP.DEPARTMENT_ID = DEP.DEPARTMENT_ID
           AND    DEP.CUSTOMER_ID = CU.CUSTOMER_ID
           AND    PLPD.PRODUCT_ID = PLPC.PRODUCT_ID)
         WHEN (P.TYPEOFMERCHANDISE = 2 AND PLPC.BILLINGMETHOD = 3 AND PLPC.INVENTORYBILLINGTYPE = 0) THEN
          (SELECT SUM(RQA.QUANTITY)
           FROM   RENTALQTYADJUSTMENT RQA, PRODUCTLISTPERDISTRIBPOINT PLPD, DISTRIBUTIONPOINT DP,
                  DEPARTMENT DEP
           WHERE  RQA.ADJUSTMENTDATE <= RP.DATE_VALUE1
           AND    RQA.PRODUCTLISTPERDISTRIBPOINT_ID = PLPD.PRODUCTLISTPERDISTRIBPOINT_ID
           AND    DP.DISTRIBUTIONPOINT_ID = PLPD.DISTRIBUTIONPOINT_ID
           AND    DP.DEPARTMENT_ID = DEP.DEPARTMENT_ID
           AND    DEP.CUSTOMER_ID = CU.CUSTOMER_ID
           AND    PLPD.PRODUCT_ID = PLPC.PRODUCT_ID
					 AND    ((PLPD.SIZEDEFINITION_ID = PLPC.SIZEDEFINITION_ID) OR (PLPC.SIZEDEFINITION_ID IN (SELECT SD.SIZEDEFINITION_ID FROM SIZEDEFINITION SD WHERE SD.CODE = '*')))
					 AND    PLPD.FINISHINGMETHOD_ID = PLPC.FINISHINGMETHOD_ID)
         WHEN (P.TYPEOFMERCHANDISE = 1 AND PLPC.BILLINGMETHOD = 3 ) THEN
          (SELECT SUM(RQA.QUANTITY)
           FROM   RENTALQTYADJUSTMENT RQA, PRODUCTLISTPERDISTRIBPOINT PLPD, DISTRIBUTIONPOINT DP,
                  DEPARTMENT DEP
           WHERE  RQA.ADJUSTMENTDATE <= RP.DATE_VALUE1
           AND    RQA.PRODUCTLISTPERDISTRIBPOINT_ID = PLPD.PRODUCTLISTPERDISTRIBPOINT_ID
           AND    DP.DISTRIBUTIONPOINT_ID = PLPD.DISTRIBUTIONPOINT_ID
           AND    DP.DEPARTMENT_ID = DEP.DEPARTMENT_ID
           AND    DEP.CUSTOMER_ID = CU.CUSTOMER_ID
           AND    PLPD.PRODUCT_ID = PLPC.PRODUCT_ID
					 AND    ((PLPD.SIZEDEFINITION_ID = PLPC.SIZEDEFINITION_ID) OR (PLPC.SIZEDEFINITION_ID IN (SELECT SD.SIZEDEFINITION_ID FROM SIZEDEFINITION SD WHERE SD.CODE = '*')))
					 AND    PLPD.FINISHINGMETHOD_ID = PLPC.FINISHINGMETHOD_ID)
         WHEN (P.TYPEOFMERCHANDISE = 2 AND PLPC.BILLINGMETHOD = 3 AND PLPC.INVENTORYBILLINGTYPE = 1) THEN
          (SELECT SUM(WI.CIRCINVENTORY)
           FROM   WEARERINVENTORY WI, WEAREREMPLOYMENT WE, WEARER W
           WHERE  WI.WEAREREMPLOYMENT_ID = WE.WEAREREMPLOYMENT_ID
           AND    WE.WEARER_ID = W.WEARER_ID
           AND    W.CUSTOMER_ID = CU.CUSTOMER_ID
           AND    WI.PRODUCT_ID = P.PRODUCT_ID
           AND    (WI.SIZEDEFINITION_ID = PLPC.SIZEDEFINITION_ID OR
                 WI.SIZEDEFINITION_ID IN
                 (SELECT SD.SIZEDEFINITION_ID FROM SIZEDEFINITION SD WHERE SD.CODE = '*')))
         WHEN (P.TYPEOFMERCHANDISE = 2 AND PLPC.BILLINGMETHOD = 3 AND PLPC.INVENTORYBILLINGTYPE = 2) THEN
          (SELECT SUM(WI.MAXINVENTORY)
           FROM   WEARERINVENTORY WI, WEAREREMPLOYMENT WE, WEARER W
           WHERE  WI.WEAREREMPLOYMENT_ID = WE.WEAREREMPLOYMENT_ID
           AND    WE.WEARER_ID = W.WEARER_ID
           AND    W.CUSTOMER_ID = CU.CUSTOMER_ID
           AND    WI.PRODUCT_ID = P.PRODUCT_ID
           AND    (WI.SIZEDEFINITION_ID = PLPC.SIZEDEFINITION_ID OR
                 WI.SIZEDEFINITION_ID IN
                 (SELECT SD.SIZEDEFINITION_ID FROM SIZEDEFINITION SD WHERE SD.CODE = '*')))
         ELSE
          -1
       END INVENTORY,
       CASE
         WHEN P.TYPEOFMERCHANDISE = 3 THEN
          pack_price.Sales_Price(CU.CUSTOMER_ID, P.PRODUCT_ID, PLPC.SIZEDEFINITION_ID, RP.DATE_VALUE1)
         WHEN P.TYPEOFMERCHANDISE IN (1, 2) AND PLPC.BILLINGMETHOD = 4 THEN
          pack_price.Wash_Price(CU.CUSTOMER_ID, P.PRODUCT_ID, PLPC.SIZEDEFINITION_ID, PLPC.FINISHINGMETHOD_ID, RP.DATE_VALUE1, 1)
         ELSE
           case when cu.invoicefrequency_id = 112 then
            nvl(pack_price.Rent_Price(CU.CUSTOMER_ID, P.PRODUCT_ID, PLPC.SIZEDEFINITION_ID, PLPC.FINISHINGMETHOD_ID, RP.DATE_VALUE1, 0) *
                (select crp.contractcoefficient
                 from customerrentprice crp where crp.productlistpercustomer_id = plpc.productlistpercustomer_id
                      and crp.customerrentprice_id = pack_price.CustomerRent_PriceID(CU.CUSTOMER_ID, P.PRODUCT_ID, PLPC.SIZEDEFINITION_ID, PLPC.FINISHINGMETHOD_ID, RP.DATE_VALUE1, 0)),
                pack_price.Rent_Price(CU.CUSTOMER_ID, P.PRODUCT_ID, PLPC.SIZEDEFINITION_ID, PLPC.FINISHINGMETHOD_ID, RP.DATE_VALUE1, 0) *
                 cu.contractcoefficient)
           else
             pack_price.Rent_Price(CU.CUSTOMER_ID, P.PRODUCT_ID, PLPC.SIZEDEFINITION_ID, PLPC.FINISHINGMETHOD_ID, RP.DATE_VALUE1, 0)
           end
       END UNITPRICE, LAN.CODE LANGUAGECODE, RP.REPORTPARAM_ID, PLPC.PRODUCT_ID,
       PLPC.SIZEDEFINITION_ID, PLPC.FINISHINGMETHOD_ID, PLPC.CUSTOMER_ID,
       COALESCE(F_GETITEMACTIVITY_DELIVERIES(RP.DATE_VALUE1, CU.CUSTOMER_ID, P.PRODUCT_ID,
                                              PLPC.SIZEDEFINITION_ID, PLPC.FINISHINGMETHOD_ID), ' ') LAST_8_DELIVERIES,
       RP.DATE_VALUE1, RP.NUMBER_VALUE1, RP.NUMBER_VALUE2, RP.STRING_VALUE1, RP.STRING_VALUE2,
       RP.STRING_VALUE3, RP.STRING_VALUE4
FROM   PRODUCTLISTPERCUSTOMER PLPC, CUSTOMER CU, ADDRESS ADR, PRODUCT P, PRODUCTGROUP PG,
       LANGUAGES LAN, REPORTPARAM RP
WHERE  PLPC.PRODUCT_ID = P.PRODUCT_ID
AND    P.PRODUCTGROUP_ID = PG.PRODUCTGROUP_ID
AND    PLPC.CUSTOMER_ID = CU.CUSTOMER_ID
AND    CU.VISITADDRESS_ID = ADR.ADDRESS_ID
AND    ((RP.NUMBER_VALUE1 = 0 AND RP.NUMBER_VALUE2 = 999999) OR
      (CU.CUSTOMERNUMBER >= RP.NUMBER_VALUE1 AND CU.CUSTOMERNUMBER <= RP.NUMBER_VALUE2))
AND    ((RP.STRING_VALUE1 = ' ' AND RP.STRING_VALUE2 = 'ZZZZZZ') OR
      (PG.CODE >= RP.STRING_VALUE1 AND PG.CODE <= RP.STRING_VALUE2))
AND    ((RP.STRING_VALUE3 = ' ' AND RP.STRING_VALUE4 = 'ZZZZZZZZZZZZ') OR
      (P.CODE >= RP.STRING_VALUE3 AND P.CODE <= RP.STRING_VALUE4))
AND    LAN.CODE = RP.STRING_VALUE8
AND    CU.DEFAULTBUSINESSUNIT_ID = RP.NUMBER_VALUE3
AND    RP.DATE_VALUE1 BETWEEN PLPC.DATEACTIVE AND PLPC.DATEINACTIVE
AND    RP.DATE_VALUE1 BETWEEN CU.DATEACTIVE AND CU.DATEINACTIVE
AND    RP.STRING_VALUE5 IS NOT NULL
AND    P.TYPEOFMERCHANDISE IN (1, 2, 3)
AND PLPC.DATEACTIVE IN (SELECT MAX(PLPC2.DATEACTIVE) FROM PRODUCTLISTPERCUSTOMER PLPC2 WHERE PLPC2.CUSTOMER_ID = PLPC.CUSTOMER_ID AND PLPC2.PRODUCT_ID = PLPC.PRODUCT_ID AND PLPC2.SIZEDEFINITION_ID = PLPC.SIZEDEFINITION_ID AND PLPC2.FINISHINGMETHOD_ID = PLPC.FINISHINGMETHOD_ID)
/

  CREATE OR REPLACE VIEW "V_ITEMACTIVITY_DELIVERIES" ("DELIVERYDATE", "REPORTPARAM_ID", "DELIVEREDAMOUNT", "PRODUCT_ID", "SIZEDEFINITION_ID", "FINISHINGMETHOD_ID", "CUSTOMER_ID") AS 
  SELECT "DELIVERYDATE","REPORTPARAM_ID","DELIVEREDAMOUNT","PRODUCT_ID","SIZEDEFINITION_ID","FINISHINGMETHOD_ID","CUSTOMER_ID" FROM
(SELECT PN.DELIVERYDATE, RP.REPORTPARAM_ID, SUM(PNL.DELIVEREDAMOUNT) DELIVEREDAMOUNT,
       PNL.PRODUCT_ID, PNL.SIZEDEFINITION_ID, PNL.FINISHINGMETHOD_ID, DEP.CUSTOMER_ID
FROM PACKINGNOTE PN, PACKINGNOTELINE PNL, REPORTPARAM RP, DISTRIBUTIONPOINT DP, DEPARTMENT DEP
WHERE PN.PACKINGNOTE_ID=PNL.PACKINGNOTE_ID AND PN.DELIVERYDATE <= RP.DATE_VALUE1
      AND PN.DISTRIBUTIONPOINT_ID = DP.DISTRIBUTIONPOINT_ID AND DP.DEPARTMENT_ID = DEP.DEPARTMENT_ID
GROUP BY PN.DELIVERYDATE, RP.REPORTPARAM_ID, PNL.PRODUCT_ID, PNL.SIZEDEFINITION_ID, PNL.FINISHINGMETHOD_ID, DEP.CUSTOMER_ID
ORDER BY PN.DELIVERYDATE DESC)
WHERE ROWNUM <=8
/

  CREATE OR REPLACE VIEW "V_ITEMSONSTOCKPERLASTUSER" ("BUSINESSUNIT_ID", "CUSTOMER_ID", "RELATEDCUSTOMER_ID", "PRIMARYID", "WASHESTOTAL", "STOCKROOM_CODE", "ROWCODE", "LOCATIONCODE", "PRODUCT_CODE", "PRODUCT_DESC", "WEARERNUMBER", "WEARERNAME", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEEKSINCIRC", "LANGUAGE_CODE") AS 
  select ui.businessunit_id, depl.customer_link_id customer_id
, ui.relatedcustomer_id, ui.primaryid, ui.washestotal
, sr.code Stockroom_code, srl.rowcode, srl.locationcode
, p.code Product_code
, (select pd.description from Product_Desc pd where p.product_id=pd.product_id and pd.language_id=l.language_id) Product_desc
, wel.wearernumber, wel.wearername
, cu.customernumber, cu.name customername
, GETROUNDTOINTEGER((uif.daysincircprevissue + 6) / 7) WeeksInCirc
, l.code Language_code
from uniqueitem ui
     left outer join weareremployment_link wel
          join distributionpoint_link dpl
               join department_link depl
                    left outer join customer cu on depl.customer_link_id = cu.customer_id
               on dpl.department_link_id = depl.department_link_id
          on wel.distributionpoint_link_id = dpl.distributionpoint_link_id
     on ui.lastweareremployment_link_id = wel.weareremployment_id
, status st, product p, uniqueitemfixedinfo uif
                   left outer join stockroomlocation srl
                        join stockroom sr on srl.stockroom_id = sr.stockroom_id
                   on uif.stockroomlocation_id = srl.stockroomlocation_id
, languages l
where ui.status_id = st.status_id
and ui.product_id = p.product_id
and ui.uniqueitem_id = uif.uniqueitem_id
and st.statustype = 'UI' and st.code = 10
/

  CREATE OR REPLACE VIEW "V_ITEMSPERWEARER" ("LINETYPE", "PRODUCTCODE", "SIZECODE", "PRODUCTDESC", "SIZEDESC", "FUNCTIONCODE", "FUNCTIONDESC", "EMPLOYMENT", "BANKLOCKER", "IDCODE", "SEQNUMBER", "ISSUEDATE", "WASHNO", "REPAIRNO", "REWASHNO", "FLAG", "UIFLAGCODE", "MODIFICATIONS", "CUSTOMEROWNED", "FREEEXTRAGARMENT", "LASTSCANDATE", "LASTOUTSCANDATE", "LASTINSCAN", "RESIDUALVALUE", "FLAGCODE", "STAY", "STAYNR", "STATUS", "ADMINNUMBER", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DEBTORNUMBER", "DEBTORNAME", "CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "DEFAULTBUSINESSUNIT_ID", "WEARERNUMBER", "WEARERNAME", "WEARERSEARCHNAME", "WEARERFIRSTNAME", "WEARERACTIVE", "WEARERDATEACTIVE", "WEARERDATEINACTIVE", "LANGUAGECODE", "LANGUAGE_ID", "CUSTOMERLANGUAGE_ID", "SUBSTITUTEYN", "LEASEWEEKS", "WEEKSINCIRC", "LASTOUTSCANDATE2", "LASTOUTSCANDATE3") AS 
  select 1 linetype, prd.code productcode, sz.code sizecode
, ( SELECT pd.description FROM product_desc pd WHERE pd.product_id = prd.product_id
  AND pd.LANGUAGE_ID = languages.LANGUAGE_ID) productdesc
, ( SELECT sdd.description FROM sizedefinition_desc sdd WHERE sdd.sizedefinition_id = sz.sizedefinition_id
  AND sdd.LANGUAGE_ID = languages.LANGUAGE_ID) sizedesc
, wf.code functioncode, wf.description functiondesc, wey.sequencenumber employment
, cast(CONCATENATEWITHBLANK(coalesce(lk.bank, ''), coalesce(lk.locker, '')) as varchar2(255)) banklocker
, case when length(uq.primaryid) = 24 and nvl((select ss.value from systemsetting ss
                                 where ss.plant_id = bu.plant_id and ss.name = 'USEURICODE'), 0) = 1
    then pack_epc_sgtin96.decode(uq.primaryid)
    else uq.primaryid end idcode
, uq.idcodesequencenumber seqnumber
, uqfx.lastissuedate issuedate, uq.washestotal washno, uq.repairstotal repairno, uq.rewashtotal rewashno
, ( SELECT COUNT(1) FROM UNIQUEITEMFLAG uf WHERE uf.UNIQUEITEM_ID = uq.UNIQUEITEM_ID) flag
, ( SELECT max(fg.code) FROM UNIQUEITEMFLAG uf, flag fg WHERE uf.UNIQUEITEM_ID = uq.UNIQUEITEM_ID and uf.flag_id = fg.flag_id) uiflagcode
, ( select count(1) from uniqueitemmodification um where um.uniqueitem_id = uq.uniqueitem_id) modifications
, uq.customerowned, uqnp.freeextragarment
, trunc(uq.lastscandate) lastscandate, trunc(uq.lastoutscandate) lastoutscandate, trunc(uq.lastinscandate) lastinscan
, uq.residualvalueAmount residualvalue, flag.code flagcode
, ( SELECT cast(sty.description as varchar2(10)) FROM stay_desc sty WHERE sty.stay_id = stay.stay_id
  AND sty.LANGUAGE_ID = languages.LANGUAGE_ID) stay, stay.staynr
, ( SELECT description FROM status_desc sd WHERE sd.status_id = uq.status_id
  AND sd.LANGUAGE_ID = languages.LANGUAGE_ID) status
, we.customeremployeenumber adminnumber, de.departmentnumber, de.description departmentdesc
, deb.customernumber debtornumber, deb.name debtorname
, cu.customernumber, cu.name customername, address.city, cu.defaultbusinessunit_id
, we.wearernumber, we.fullname wearername, we.searchname wearersearchname, we.firstname wearerfirstname
, GETDATEDIFF(trunc(sysdate), we.dateactive) * GETDATEDIFF(we.dateinactive, trunc(sysdate)) weareractive
, we.dateactive WearerDateActive, we.dateinactive WearerDateInactive
, languages.code languagecode, languages.language_id, cu.language_id customerlanguage_id
, case when uq.substituteforproduct_id is null then 'N' else 'Y' end substituteYN
, uq.leaseweeks leaseWeeks
, GETROUNDTOINTEGER((trunc(sysdate)-trunc(uqfx.lastissuedate) + 1) / 7) WeeksInCirc-- GETROUNDTOINTEGER((uqfx.daysincircprevissue + 6) / 7)
, (select max(trunc(s.scantimestamp)) from scan s where s.uniqueitem_link_id = uq.uniqueitem_id
   and s.transactiontype_id in (2, 8, 9, 95, 540, 541, 542, 543, 545, 640)--OutScans
   and trunc(s.scantimestamp) < trunc(uq.lastoutscandate)) lastoutscandate2
, (select max(trunc(s2.scantimestamp)) from scan s2 where s2.uniqueitem_link_id = uq.uniqueitem_id
   and s2.transactiontype_id in (2, 8, 9, 95, 540, 541, 542, 543, 545, 640)--OutScans
   and trunc(s2.scantimestamp) < (select max(trunc(s1.scantimestamp)) from scan s1 where s1.uniqueitem_link_id = uq.uniqueitem_id
                                       and s1.transactiontype_id in (2, 8, 9, 95, 540, 541, 542, 543, 545, 640)--OutScans
                                       and trunc(s1.scantimestamp) < trunc(uq.lastoutscandate))) lastoutscandate3
from customer deb, customer cu, wearer we
    left outer join flag on we.flag_id = flag.flag_id
, weareremployment wey
    left outer join locker lk on lk.locker_id = wey.locker_id
    left outer join wearerfunction wf on wey.wearerfunction_id = wf.wearerfunction_id
, uniqueitemnonpool uqnp, uniqueitem uq
    left outer join stay on uq.stay_id = stay.stay_id
, uniqueitemfixedinfo uqfx
, product prd, sizedefinition sz, distributionpoint dip, department de
, address, languages, businessunit bu
where cu.debtor_id = deb.customer_id and cu.customer_id = we.customer_id
and we.wearer_id = wey.wearer_id
and wey.weareremployment_id = uqnp.weareremployment_id
and uqnp.uniqueitem_id = uq.uniqueitem_id
    and uq.uniqueitem_id = uqfx.uniqueitem_id
and uq.product_id = prd.product_id
and uq.sizedefinition_id = sz.sizedefinition_id
and wey.distributionpoint_id = dip.distributionpoint_id
    and dip.department_id = de.department_id
and cu.mailaddress_id = address.address_id
and bu.businessunit_id = cu.defaultbusinessunit_id
Union all
select 2 linetype, coalesce(subtPrd.Code, prd.code) productcode, coalesce(subtSz.Code, sz.code) sizecode
, coalesce(
 ( SELECT prde.description FROM product_desc prde WHERE prde.product_id = subtPrd.product_id
  AND prde.LANGUAGE_ID = languages.LANGUAGE_ID )
 , ( SELECT pd.description FROM product_desc pd WHERE pd.product_id = prd.product_id
  AND pd.LANGUAGE_ID = languages.LANGUAGE_ID)
  ) productdesc
, ( SELECT sdd.description FROM sizedefinition_desc sdd WHERE sdd.sizedefinition_id = coalesce(subtSz.sizedefinition_id, sz.sizedefinition_id)
  AND sdd.LANGUAGE_ID = languages.LANGUAGE_ID) sizedesc
, wf.code functioncode, wf.description functiondesc, wey.sequencenumber employment
, cast(CONCATENATEWITHBLANK(coalesce(lk.bank, ''), coalesce(lk.locker, '')) as varchar2(255)) banklocker
, null idcode, nuq.sequencenumber seqnumber
, nuq.issuedate issuedate, null washno, null repairno, null rewashno, null flag, null uiflagcode
, ( SELECT count(1) FROM wearerinventorymodification wim WHERE wim.wearerinventory_id = weinv.wearerinventory_id) modifications
, 'N' customerowned, 'X' freeextragarment
, null lastscandate, null lastoutscandate, null lastinscandate
, 0 residualvalue, flag.code flagcode
, null stay, null staynr, null status
, we.customeremployeenumber adminnumber, de.departmentnumber, de.description departmentdesc
, deb.customernumber debtornumber, deb.name debtorname
, cu.customernumber, cu.name customername, address.city, cu.defaultbusinessunit_id
, we.wearernumber, we.fullname wearername, we.searchname wearersearchname, we.firstname wearerfirstname
, GETDATEDIFF(trunc(sysdate), we.dateactive) * GETDATEDIFF(we.dateinactive, trunc(sysdate)) weareractive
, we.dateactive WearerDateActive, we.dateinactive WearerDateInactive
, languages.code languagecode, languages.language_id, cu.language_id customerlanguage_id
, case when nuq.substituteforproduct_id is null then 'N' else 'Y' end substituteYN
, null leaseWeeks
, GETROUNDTOINTEGER((trunc(sysdate)-trunc(nuq.issuedate) + 1) / 7) WeeksInCirc
, null lastoutscandate2
, null lastoutscandate3
from customer deb, customer cu, wearer we
    left outer join flag  on we.flag_id = flag.flag_id
, weareremployment wey
    left outer join locker lk on lk.locker_id = wey.locker_id
    left outer join wearerfunction wf on wey.wearerfunction_id = wf.wearerfunction_id
, wearerinventory weinv, nonuniqueitem nuq
    left outer join product subtPrd on subtPrd.product_id = nuq.substituteforproduct_id
    left outer join sizedefinition subtSz on subtSz.Sizedefinition_Id = nuq.substituteforsizedefinition_id
, product prd, sizedefinition sz
, distributionpoint dip, department de, address, languages
where cu.debtor_id = deb.customer_id and cu.customer_id = we.customer_id
and we.wearer_id = wey.wearer_id
and wey.weareremployment_id = weinv.weareremployment_id
AND weinv.product_id = prd.product_id
and weinv.sizedefinition_id = sz.sizedefinition_id
and weinv.wearerinventory_id = nuq.wearerinventory_id
and wey.distributionpoint_id = dip.distributionpoint_id
    and dip.department_id = de.department_id
and cu.mailaddress_id = address.address_id/*
Union all --20013161 Show also garments that need to be replaced or returned.
select 3 linetype, prd.code productcode, sz.code sizecode
, ( SELECT description FROM product_desc pd WHERE pd.product_id = prd.product_id
  AND pd.LANGUAGE_ID = languages.LANGUAGE_ID) productdesc
, ( SELECT sdd.description FROM sizedefinition_desc sdd WHERE sdd.sizedefinition_id = sz.sizedefinition_id
  AND sdd.LANGUAGE_ID = languages.LANGUAGE_ID) sizedesc
, wf.code functioncode, wf.description functiondesc, wey.sequencenumber employment
, cast(CONCATENATEWITHBLANK(coalesce(lk.bank, ''), coalesce(lk.locker, '')) as varchar2(255)) banklocker
, case when length(uq.primaryid) = 24 and nvl((select ss.value from systemsetting ss
                                 where ss.plant_id = bu.plant_id and ss.name = 'USEURICODE'), 0) = 1
    then pack_epc_sgtin96.decode(uq.primaryid)
    else uq.primaryid end idcode
, uq.idcodesequencenumber seqnumber
, uqfx.lastissuedate issuedate, uq.washestotal washno, uq.repairstotal repairno, uq.rewashtotal rewashno
, (SELECT COUNT(1) FROM UNIQUEITEMFLAG uf, automaticflag af WHERE uf.UNIQUEITEM_ID = uq.UNIQUEITEM_ID and af.flag_id = uf.flag_id
           and uf.startdate <= trunc(sysdate) and af.automaticflag_id in (12, 4, 5, 7, 2)) flag
, (SELECT max(fg.code) FROM UNIQUEITEMFLAG uf, flag fg, automaticflag af WHERE uf.UNIQUEITEM_ID = uq.UNIQUEITEM_ID and uf.flag_id = fg.flag_id and af.flag_id = uf.flag_id
           and uf.startdate <= trunc(sysdate) and af.automaticflag_id in (12, 4, 5, 7, 2)) uiflagcode
, (select count(1) from uniqueitemmodification um where um.uniqueitem_id = uq.uniqueitem_id) modifications
, uq.customerowned, uqnp.freeextragarment
, trunc(uq.lastscandate) lastscandate, trunc(uq.lastoutscandate) lastoutscandate, trunc(uq.lastinscandate) lastinscandate
, uq.residualvalueAmount residualvalue, flag.code flagcode
, (SELECT cast(sty.description as varchar2(10)) FROM stay_desc sty WHERE sty.stay_id = stay.stay_id
  AND sty.LANGUAGE_ID = languages.LANGUAGE_ID) stay, stay.staynr
, (SELECT sd.description FROM status_desc sd WHERE sd.status_id = uq.status_id
  AND sd.LANGUAGE_ID = languages.LANGUAGE_ID) status
, we.customeremployeenumber adminnumber, de.departmentnumber, de.description departmentdesc
, cu.customernumber, cu.name customername, address.city, cu.defaultbusinessunit_id
, we.wearernumber, we.fullname wearername, we.searchname wearersearchname, we.firstname wearerfirstname
, GETDATEDIFF(trunc(sysdate), we.dateactive)*GETDATEDIFF(we.dateinactive, trunc(sysdate)) weareractive--select only active wearers
, we.dateactive WearerDateActive, we.dateinactive WearerDateInactive
, languages.code languagecode, languages.language_id, cu.language_id customerlanguage_id
, case when uq.substituteforproduct_id is null then 'N' else 'Y' end substituteYN
, uq.leaseweeks leaseWeeks
, GETROUNDTOINTEGER((uqfx.daysincircprevissue + 6) / 7) WeeksInCirc
, (select max(trunc(uq2.lastoutscandate)) from uniqueitem uq2 where uq2.primaryid = uq.primaryid
  and uq2.lastoutscandate < uq.lastoutscandate) lastoutscandate2
, (select max(trunc(uq3.lastoutscandate)) from uniqueitem uq2, uniqueitem uq3 where uq2.primaryid = uq.primaryid
  and uq2.lastoutscandate < uq.lastoutscandate and uq3.primaryid = uq.primaryid and uq3.lastoutscandate < uq2.lastoutscandate) lastoutscandate3
from customer cu, wearer we
    left outer join flag on we.flag_id = flag.flag_id
, weareremployment wey
    left outer join locker lk on lk.locker_id = wey.locker_id
    left outer join wearerfunction wf on wey.wearerfunction_id = wf.wearerfunction_id
, uniqueitemnonpool uqnp, uniqueitem uq
    left outer join stay on uq.stay_id = stay.stay_id
, uniqueitemfixedinfo uqfx
, product prd,  sizedefinition sz, distributionpoint dip, department de
, address, languages, businessunit bu
where cu.customer_id = we.customer_id
and we.wearer_id = wey.wearer_id
and wey.weareremployment_id = uqnp.weareremployment_id
and uqnp.uniqueitem_id = uq.uniqueitem_id
    and uq.uniqueitem_id = uqfx.uniqueitem_id
and uq.product_id = prd.product_id
and uq.sizedefinition_id = sz.sizedefinition_id
and wey.distributionpoint_id = dip.distributionpoint_id
    and dip.department_id = de.department_id
and cu.mailaddress_id = address.address_id
and bu.businessunit_id = cu.defaultbusinessunit_id
and exists (SELECT 1 FROM UNIQUEITEMFLAG uf, automaticflag af WHERE uf.UNIQUEITEM_ID = uq.UNIQUEITEM_ID and af.flag_id = uf.flag_id
           and uf.startdate <= trunc(sysdate) and af.automaticflag_id in (12, 4, 5, 7, 2) )*/
/

  CREATE OR REPLACE VIEW "V_LANGUAGES" ("CODE", "DESCRIPTION", "LEGACYLANGUAGECODE", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  SELECT LANGUAGES.CODE, LANGUAGES.DESCRIPTION, LANGUAGES.LEGACYLANGUAGECODE, LANGUAGES.SYSTEMUSER_ID, LANGUAGES.TIMESTAMP
       FROM LANGUAGES
/

  CREATE OR REPLACE VIEW "V_LAST12WEEKS" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMERSEARCHNAME", "STREET", "ZIPCODE", "CITY", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "PRODUCTGROUPCODE", "PRODUCTGROUPDESCRIPTION", "PRODUCTCODE", "PRODUCTDESCRIPTION", "TYPEOFMERCHANDISE", "SIZECODE", "SIZEDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "YEARWEEK", "WEEK", "DELIVERYDATE", "DELIVEREDQTY", "LANGUAGECODE", "REPORTPARAM_ID") AS 
  select /*version 1.0*/
       cu.customernumber, cu.name customername, cu.searchname customersearchname,
       cast(concatenatewithblank(vad.street, coalesce(vad.street2, ' ')) as varchar2(255)) street,
       vad.zipcode, vad.city, del.departmentnumber, del.description departmentdescription,
       dpl.distributionpointnumber, dpl.description distributionpointdescription,
       pg.code productgroupcode,
       (select pgd.description
          from productgroup_desc pgd
         where pgd.productgroup_id = pg.productgroup_id
           and pgd.language_id = lan.language_id) productgroupdescription, pr.code productcode,
       (select prd.description
          from product_link_desc prd
         where prd.product_link_id = dh.product_link_id
           and prd.language_id = lan.language_id) productdescription,
       pr.typeofmerchandise, szl.code sizecode,
       (select szd.description
          from sizedefinition_link_desc szd
         where szd.sizedefinition_link_id = dh.sizedefinition_link_id
           and szd.language_id = lan.language_id) sizedescription, fm.code finishingmethodcode,
       (select fmd.description
          from finishingmethod_desc fmd
         where fmd.finishingmethod_id = dh.finishingmethod_id
           and fmd.language_id = lan.language_id) finishingmethoddescription,
       (dh.year * 100 + dh.week) yearweek, dh.week, dh.deliverydate,
       sum(dh.amountdelivered) deliveredqty,
       lan.code languagecode, rp.reportparam_id
  from deliveryhistory dh
       join distributionpoint_link dpl
            join department_link del
                 join customer cu
                      join address vad on cu.visitaddress_id = vad.address_id
                 on del.customer_link_id = cu.customer_id
            on dpl.department_link_id = del.department_link_id
       on dh.distributionpoint_link_id = dpl.distributionpoint_link_id
       join product pr
            join productgroup pg on pr.productgroup_id = pg.productgroup_id
       on dh.product_link_id = pr.product_id
       join sizedefinition_link szl on dh.sizedefinition_link_id = szl.sizedefinition_link_id
       join finishingmethod fm on dh.finishingmethod_id = fm.finishingmethod_id,
       languages lan, reportparam rp
 where dh.deliverydate >= trunc(rp.date_value1)
   and dh.deliverydate <= trunc(rp.date_value2)
   and dpl.distributionpointnumber >= rp.number_value8
   and dpl.distributionpointnumber <= rp.number_value9
   and del.departmentnumber >= rp.number_value6
   and del.departmentnumber <= rp.number_value7
   and cu.customernumber = rp.number_value4 --   and cu.customernumber <= rp.number_value5
   and lan.code = rp.string_value
   and pg.code >= rp.string_value1
   and pg.code <= rp.string_value2
   and pr.code >= rp.string_value3
   and pr.code <= rp.string_value4
   and fm.code >= rp.string_value5
   and fm.code <= rp.string_value6
   and dh.packindication in (1, 2)
 group by cu.customernumber, cu.name, cu.searchname, vad.street, vad.street2, vad.zipcode, vad.city,
          del.departmentnumber, del.description, dpl.distributionpointnumber, dpl.description,
          pg.code, pg.productgroup_id, lan.language_id, pr.code, dh.product_link_id,
          pr.typeofmerchandise, szl.code, dh.sizedefinition_link_id, fm.code, dh.finishingmethod_id,
          dh.year, dh.week, dh.deliverydate, lan.code, rp.reportparam_id
/

  CREATE OR REPLACE VIEW "V_LEASEBUYOUTVALUE" ("CUSTOMERNUMBER", "CUSTOMERNAME", "STREET", "ZIPCODE", "CITY", "WEARERNUMBER", "WEARERFULLNAME", "PRODUCTCODE", "SIZECODE", "DATEACTIVE", "DATEINACTIVE", "PRODUCTDESC", "UNIQUEITEM_ID", "PRIMARYID", "LASTISSUEDATE", "LASTSCANDATE", "LEASEWEEKS", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE") AS 
  select
  cu.customernumber, cu.name customerName, address.street, address.zipcode, address.city
, we.wearernumber, we.fullname wearerfullname
, prd.code productCode, sz.code sizeCode
, weinv.dateactive, weinv.dateinactive
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, UQ.UNIQUEITEM_ID, uq.primaryid, uqfx.lastissuedate, uq.lastscandate, uq.leaseweeks
, currency.invoiceamountdecimals, languages.code languageCode
from
  uniqueitem uq, uniqueitemfixedinfo uqfx, product prd, sizedefinition sz
, uniqueitemnonpool uqnp
, wearerinventory weinv, weareremployment wey, wearer we, customer cu
, address, currency
, languages
where
    uq.leaseweeks is not null -- report is only for Lease items
and uq.poolitem = 2 -- Non-pool
and uq.uniqueitem_id = uqfx.uniqueitem_id
and uq.product_id = prd.product_id
and uq.sizedefinition_id = sz.sizedefinition_id
and uq.uniqueitem_id = uqnp.uniqueitem_id
    and uqnp.wearerinventory_id = weinv.wearerinventory_id
        and uqnp.weareremployment_id = wey.weareremployment_id
            and wey.wearer_id = we.wearer_id
                and we.customer_id = cu.customer_id
and cu.visitaddress_id = address.address_id
and cu.currency_id = currency.currency_id
UNION
select
  cu.customernumber, cu.name customerName, address.street, address.zipcode, address.city
, -1 wearernumber, ' ' wearerfullname
, prd.code productCode, sz.code sizeCode
, null  dateactive, null  dateinactive
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, UQ.UNIQUEITEM_ID, uq.primaryid, uqfx.lastissuedate, uq.lastscandate, uq.leaseweeks
, currency.invoiceamountdecimals, languages.code languageCode
from
  uniqueitem uq, uniqueitemfixedinfo uqfx, product prd, sizedefinition sz
, distributionpoint dip, department de, customer cu
, address, currency
, languages
where
    uq.leaseweeks is not null
and uq.poolitem = 1 -- Pool
and uq.uniqueitem_id = uqfx.uniqueitem_id
and uq.product_id = prd.product_id
and uq.sizedefinition_id = sz.sizedefinition_id
and uq.distributionpoint_id = dip.distributionpoint_id
    and dip.department_id = de.department_id
        and de.customer_id = cu.customer_id
and cu.visitaddress_id = address.address_id
and cu.currency_id = currency.currency_id
UNION
select
  cu.customernumber, cu.name customerName, address.street, address.zipcode, address.city
, we.wearernumber, we.fullname wearerfullname
, prd.code productCode, sz.code sizeCode
, weinv.dateactive, weinv.dateinactive
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, UQ.UNIQUEITEM_ID, uq.primaryid, uqfx.lastissuedate, uq.lastscandate, uq.leaseweeks
, currency.invoiceamountdecimals, languages.code languageCode
from
  uniqueitem uq, uniqueitemfixedinfo uqfx, product prd, sizedefinition sz
, wearerinventory weinv, weareremployment_link weylk, weareremployment wey
, wearer we, customer cu
, address, currency
, languages
where
    uq.leaseweeks is not null
and uq.poolitem = 0 -- Stock -- and uq.lastweareremployment_link_id in not null
and uq.uniqueitem_id = uqfx.uniqueitem_id
and uq.product_id = prd.product_id
and uq.sizedefinition_id = sz.sizedefinition_id
and uq.lastweareremployment_link_id =  weylk.weareremployment_link_id
    and weylk.weareremployment_id = wey.weareremployment_id
        and wey.weareremployment_id = weinv.weareremployment_id
        and wey.wearer_id = we.wearer_id
                and we.customer_id = cu.customer_id
and cu.visitaddress_id = address.address_id
and cu.currency_id = currency.currency_id
UNION
select
  cu.customernumber, cu.name customerName, address.street, address.zipcode, address.city
, -1 wearernumber, ' ' wearerfullname
, prd.code productCode, sz.code sizeCode
, null  dateactive, null  dateinactive
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, UQ.UNIQUEITEM_ID, uq.primaryid, uqfx.lastissuedate, uq.lastscandate, uq.leaseweeks
, currency.invoiceamountdecimals, languages.code languageCode
from
  uniqueitem uq, uniqueitemfixedinfo uqfx, product prd, sizedefinition sz
, distributionpoint_link diplk, distributionpoint dip, department de, customer cu
, address, currency
, languages
where
    uq.leaseweeks is not null
and uq.poolitem = 0 -- Stock
and uq.lastweareremployment_link_id is null -- verify previous block
and uq.uniqueitem_id = uqfx.uniqueitem_id
and uq.product_id = prd.product_id
and uq.sizedefinition_id = sz.sizedefinition_id
and uq.lastdistributionpoint_link_id = diplk.distributionpoint_link_id
    and diplk.distributionpoint_link_id = dip.distributionpoint_id
        and dip.department_id = de.department_id
            and de.customer_id = cu.customer_id
and cu.visitaddress_id = address.address_id
and cu.currency_id = currency.currency_id
UNION
select
  cu.customernumber, cu.name customerName, address.street, address.zipcode, address.city
, -1 wearernumber, ' ' wearerfullname
, prd.code productCode, sz.code sizeCode
, null dateactive, null dateinactive
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, UQ.UNIQUEITEM_ID, uq.primaryid, uqfx.lastissuedate, uq.lastscandate, uq.leaseweeks
, currency.invoiceamountdecimals, languages.code languageCode
from
  uniqueitem uq , uniqueitemfixedinfo uqfx
, product prd, sizedefinition sz
, customer cu
, address, currency
, languages
where
    uq.leaseweeks is not null
and uq.poolitem = 0 -- Stock   -- "in anny other previous cases"
and coalesce(uq.lastweareremployment_link_id, uq.lastdistributionpoint_link_id) is null
and uq.uniqueitem_id = uqfx.uniqueitem_id
and uq.product_id = prd.product_id
and uq.sizedefinition_id = sz.sizedefinition_id
and uq.relatedcustomer_id = cu.customer_id
    and cu.visitaddress_id = address.address_id
    and cu.currency_id = currency.currency_id
/

  CREATE OR REPLACE VIEW "V_LEGALENTITY" ("PLANT_ID", "PLANTCODE", "PLANTNAME", "PLANTPHONENO", "PLANTFAXNO", "PLANTEMAIL", "PLANTWEBSITE", "PLANTCOUNTRYNAME", "PLANTLOGO", "PLANTSTREET", "PLANTSTREET2", "PLANTZIPCODE", "PLANTCITY", "PLANTSTATE", "PLANTCOUNTY", "BUSINESSUNIT_ID", "BU_CODE", "BU_DESC", "BU_INTERNALVATNR", "BU_VATNR", "LEGALENTITY_ID", "LEGALENTITY_CODE", "LEGALENTITY_NAME", "LEGALENTITY_EXTRANAME1", "LEGALENTITY_EXTRANAME2", "LEGALENTITY_LEGALNAME", "LEGALENTITY_COCNR", "LEGALENTITY_VATNR", "LEGALENTITY_PHONE", "LEGALENTITY_FAX", "LEGALENTITY_EMAIL", "LEGALENTITY_WEBSITE", "SENDINV_STREET", "SENDINV_STREET2", "SENDINV_ZIPCODE", "SENDINV_CITY", "SENDINV_STATE", "SENDINV_COUNTY", "LEGENTAD_STREET", "LEGENTAD_STREET2", "LEGENTAD_ZIPCODE", "LEGENTAD_CITY", "LEGENTAD_STATE", "LEGENTAD_COUNTY", "BANKINST_CODE1", "BANKINST_NAME1", "INTERNALIDCODE1", "LAUNDRYBANKACCOUNT1", "IBANNO1", "BANKINST_STREET1", "BANKINST_ZIPCODE1", "BANKINST_CITY1", "BANKINST_NAME2", "INTERNALIDCODE2", "LAUNDRYBANKACCOUNT2", "IBANNO2", "SENDINV_NAME", "SENDINV_EXTRANAME1", "SENDINV_EXTRANAME2", "LEGALENTITY_CDN_IMAGE", "LEGALENTITY_INV_IMAGE", "LEGALENTITY_DINV_IMAGE", "LEGALENTITY_COUNTRY") AS 
  select /*version 2.2*/
       pl.plant_id, pl.code plantcode, pl.name plantname, pl.phoneno plantphoneno, pl.faxno plantfaxno, pl.email plantemail, pl.website plantwebsite,
       (select c.description from country c where c.country_id = pl.country_id) plantcountryname,
       pl.logo plantlogo, pad.street plantstreet, pad.street2 plantstreet2, pad.zipcode plantzipcode, pad.city plantcity, pad.state plantstate, pad.county plantcounty,
       bu.businessunit_id, bu.code bu_code, bu.description bu_desc, bu.internalvatnumber bu_internalvatnr, bu.vatnumber bu_vatnr, le.legalentity_id, le.code legalentity_code,
       le.name legalentity_name, le.extraname1 legalentity_extraname1, le.extraname2 legalentity_extraname2, le.legalname legalentity_legalname, le.cocnumber legalentity_cocnr,
       le.vatnumber legalentity_vatnr, le.phone legalentity_phone, le.fax legalentity_fax, le.email legalentity_email, le.website legalentity_website, siad.street sendinv_street,
       siad.street2 sendinv_street2, siad.zipcode sendinv_zipcode, siad.city sendinv_city, siad.state sendinv_state, siad.county sendinv_county, ad.street legentad_street,
       ad.street2 legentad_street2, ad.zipcode legentad_zipcode, ad.city legentad_city, ad.state legentad_state, ad.county legentad_county, bi1.idcode bankinst_code1,
       bi1.description bankinst_name1, bi1.internalidcode internalidcode1, bi1.laundrybankaccount laundrybankaccount1, bi1.ibanno ibanno1, bi1ad.street bankinst_street1,
       bi1ad.zipcode bankinst_zipcode1, bi1ad.city bankinst_city1, bi2.description bankinst_name2, bi2.internalidcode internalidcode2, bi2.laundrybankaccount laundrybankaccount2,
       bi2.ibanno ibanno2, le.sendinvoicetoname sendinv_name, le.sendinvoicetoextraname1 sendinv_extraname1, le.sendinvoicetoextraname2 sendinv_extraname2,
       (select cdi.image
          from image cdi
         where cdi.image_id = le.csdeliverynoteimage_id) legalentity_cdn_image,
       (select ini.image
          from image ini
         where ini.image_id = le.csinvoiceimage_id) legalentity_inv_image,
       (select diri.image
          from image diri
         where diri.image_id = le.csdirectinvoiceimage_id) legalentity_dinv_image,
       (select lec.code from country lec
         where lec.country_id = le.country_id) legalentity_country
  from businessunit bu
       left join legalentity le
            left join bankinstitution bi2 on le.bankinstitution2_id = bi2.bankinstitution_id
            left join address siad on le.sendinvoicetoaddress_id = siad.address_id
            join address ad on le.address_id = ad.address_id
            join bankinstitution bi1
                 join address bi1ad on bi1.address_id = bi1ad.address_id
            on le.bankinstitution_id = bi1.bankinstitution_id
       on bu.legalentity_id = le.legalentity_id
       join plant pl
            join address pad on pl.address_id = pad.address_id
       on bu.plant_id = pl.plant_id
/

  CREATE OR REPLACE VIEW "V_LOAN_UNRELATED_SO_LINES" ("PACKINGNOTE_ID", "PACKINGNOTELINE_ID", "PRODUCT_ID", "VARIATIONAMOUNT", "SIZEDEFINITION_ID") AS 
  select distinct PNL.PACKINGNOTE_ID, PNL.PACKINGNOTELINE_ID, PNL.PRODUCT_ID, PNL.VARIATIONAMOUNT, PNL.SIZEDEFINITION_ID
 FROM PACKINGNOTELINE PNL, INVOICELINEPRODUCT ILP, INVOICELINE IL WHERE
            PNL.PRODUCT_ID = ILP.PRODUCT_LINK_ID AND
            PNL.SIZEDEFINITION_ID = ILP.SIZEDEFINITION_LINK_ID AND PNL.FINISHINGMETHOD_ID = ILP.FINISHINGMETHOD_ID AND
-- loans unrelated invoice line means: ILP.RELATEDPRODUCT = 2 and  IL.INVOICELINETYPE_ID = 1(rent)
--            ILP.RELATEDPRODUCT = 2 AND
            ILP.INVOICELINE_ID = IL.INVOICELINE_ID
--            AND IL.INVOICELINETYPE_ID = 1
/

  CREATE OR REPLACE VIEW "V_LOCKER" ("CUSTOMERNUMBER", "CUSTOMERNAME", "BANK", "LOCKER", "DELIVERYPOINTCODE", "DELIVERYPOINTDESCRIPTION", "LOCKERSTATUS", "REMARK", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, LOCKER.BANK, LOCKER.LOCKER, DELIVERYPOINT.CODE, DELIVERYPOINT.DESCRIPTION, LOCKER.LOCKERSTATUS, LOCKER.REMARK, LOCKER.SYSTEMUSER_ID, LOCKER.TIMESTAMP
	FROM  LOCKER, CUSTOMER, DELIVERYPOINT
	WHERE LOCKER.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND LOCKER.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
/

  CREATE OR REPLACE VIEW "V_LOCKERLABEL" ("LOCKER", "CUSTOMER_ID", "LOCKERSTATUS", "BANK", "WEARERNUMBER", "FULLNAME", "FIRSTNAME", "SEARCHNAME", "DEPARTMENTNUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "CHANGESPERWEEKPRODDESC", "MYCOUNT", "SKIPPEDSECTIONS") AS 
  select /*version 2.1*/
       lr.locker, lr.customer_id, lr.lockerstatus,lr.bank, wr.wearernumber, wr.fullname, wr.firstname, wr.searchname, d.departmentnumber, c.customernumber, c.name customername,
       case when (select max(cast(lpad(replace(pcv.version, '.', ''), 3) as numeric)) from product_component_version pcv) >= 112
            then case when (select max(dbs.code) from databasesettings dbs) = 'CIW'
                      then (select listagg((castnumberasvarchar(wi.changesperweek) || '   ' || pr.shortdescription),', ')
                                   within group (order by wi.changesperweek, pr.shortdescription)
                              from wearerinventory wi, product pr
                             where wi.weareremployment_id = we.weareremployment_id
                               and wi.product_id = pr.product_id
                               and wi.changesperweek <> 0)
                      else (select listagg((castnumberasvarchar(wi.changesperweek) || '   ' || pr.shortdescription),', ')
                                   within group (order by wi.changesperweek, pr.shortdescription)
                              from wearerinventory wi, product pr
                             where wi.weareremployment_id = we.weareremployment_id
                               and wi.product_id = pr.product_id
                               and wi.changesperweek <> 0)
                  end
            else 'Only from Oracle version 11 Release 2' end changesperweekproddesc,
       x.mycount, 0 skippedsections
  from locker lr
       left join weareremployment we
                 join distributionpoint dp
                      join department d on dp.department_id = d.department_id
                 on we.distributionpoint_id = dp.distributionpoint_id
                 join wearer wr on we.wearer_id = wr.wearer_id
       on we.locker_id = lr.locker_id
       join customer c on lr.customer_id = c.customer_id,
       (select rownum mycount
          from systemsetting--all_objects--
         where rownum <= 100) x
union all
select ' ' locker, 0 customer_id, 0 lockerstatus, ' ' bank, 0 wearernumber, ' ' fullname, ' ' firstname, ' ' searchname, 0 departmentnumber,
       0 customernumber, ' '  customername, ' ' changesperweekproddesc, 0 mycount, x.mycount skippedsections
  from (select rownum mycount
          from systemsetting--all_objects--
         where rownum <= 100) x
/

  CREATE OR REPLACE VIEW "V_LOSSCHARGES" ("INVOICEDATE", "BU_CODE", "BU_DESC", "SALESJOURNALGROUP_CODE", "PRODUCTGROUPCODE", "PRODUCTGROUPDESCRIPTION", "INVOICELINETYPE_ID", "AMOUNT", "SYSTEMUSER_ID", "LANGUAGECODE", "INVOICEAMOUNTDECIMALS", "SALESJOURNALGROUP_DESC") AS 
  select /*version 2.1*/
       ih.invoicedate, bu.code bu_code, bu.description bu_desc, sjg.code salesjournalgroup_code, ilp.productgroupcode,
       ilp.productgroupdescription, il.invoicelinetype_id, il.amount, su.systemuser_id, lan.code languagecode,
       (select curr.invoiceamountdecimals
          from currency curr
         where ih.currency_id = curr.currency_id) invoiceamountdecimals,
       (select sjgd.description
          from salesjournalgroup_desc sjgd
         where sjgd.salesjournalgroup_id = sjg.salesjournalgroup_id
           and sjgd.language_id = lan.language_id) salesjournalgroup_desc
  from invoiceheader ih
       join invoiceline il
            join turnovergroup tg
                 join salesjournalgroup sjg on tg.salesjournalgroup_id = sjg.salesjournalgroup_id
            on il.turnovergroup_id = tg.turnovergroup_id
            join invoicelineproduct ilp on il.invoiceline_id = ilp.invoiceline_id
       on ih.invoiceheader_id = il.invoiceheader_id
       join businessunit bu on ih.invoicebusinessunit_id = bu.businessunit_id
       cross join systemuser su
       cross join languages lan
 where ilp.productgroupcode is not null
       and ih.status_id = (select st.status_id
                             from status st
                            where st.code = '2'
                              and st.statustype = 'IN')
       and exists (select 1
                     from businessunitsperusergroup bug
                    where bug.usergroup_id = su.usergroup_id
                      and bug.businessunit_id = bu.businessunit_id)
/

  CREATE OR REPLACE VIEW "V_LOSSFORPOOLPERPRODCONS" ("CUSTOMERNUMBER", "NAME", "DISTRIBUTIONPOINTNUMBER", "DPL_DESCRIPTION", "STARTDATE", "ENDDATE", "CURRENCYCODE", "DEPARTMENTNUMBER", "DESCRIPTION", "INVOICEHEADER_ID", "INVOICENUMBER", "INVOICEDATE", "INVOICEBUSINESSUNIT_ID", "CLUSTER_ID", "INVOICEFREQUENCY_ID", "PERIODENDDATE", "YEAR", "PERIOD", "DAYSINPERIOD", "CHARGETYPE", "PRODUCTCODE", "PRODUCTDESCRIPTION", "AMOUNT", "QTY", "LOSSSTATUS", "SIZE_CODE", "SIZE_DESC", "LOSSGRACESCHEMECODE") AS 
  select /*version 2.1*/
       cl.customernumber, cl.name, dpl.distributionpointnumber, dpl.description dpl_description, ih.startdate, ih.enddate,
       (select cc.code
          from currency cc
         where cc.currency_id = ih.currency_id) currencycode,
       dl.departmentnumber, dl.description, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.invoicebusinessunit_id,
       ih.cluster_id, ih.invoicefrequency_id, iflp.enddate periodenddate, iflp.year, iflp.period,
       coalesce(iflp.enddate - iflp.cutoffdate + 1, (select max(plpc.chargelossuniquepooldays )
                                                       from productlistpercustomer plpc
                                                      where plpc.customer_id = cl.customer_id
                                                        and plpc.product_id = ui.product_id
                                                        and plpc.sizedefinition_id = ui.sizedefinition_id
                                                        and plpc.finishingmethod_id = ui.finishingmethod_id
                                                        and plpc.dateactive <= sysdate
                                                        and plpc.dateinactive > sysdate )) daysinperiod,
       1 chargetype, p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = ui.product_id
           and pd.language_id = c.language_id) productdescription,
       sum(uil.creditamount) amount, count(1) qty, uil.lossstatus,
       (select sd.code
          from sizedefinition sd
         where sd.sizedefinition_id = ui.sizedefinition_id) size_code,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = ui.sizedefinition_id
           and sdd.language_id = c.language_id) size_desc,
       (select lsg.code
          from lossgracescheme lsg
         where lsg.lossgracescheme_id = c.lossgracescheme_id) lossgraceschemecode
 from uniqueitemloss uil
      left join invoicefrequencylossperiod iflp on uil.invoicefrequencylossperiod_id = iflp.invoicefrequencylossperiod_id
      join invoiceheader ih on uil.creditinvoiceheader_id = ih.invoiceheader_id
      join customer_link cl
           left join customer c on c.customer_id = cl.customer_id
      on uil.customer_link_id = cl.customer_link_id
      join distributionpoint_link dpl
           join department_link dl on dpl.department_link_id = dl.department_link_id
      on uil.distributionpoint_link_id = dpl.distributionpoint_link_id
      join uniqueitem ui
           join product p on ui.product_id = p.product_id
      on uil.uniqueitem_link_id = ui.uniqueitem_id
where uil.lossstatus >= 2
group by cl.customernumber, cl.name, ih.currency_id, dl.departmentnumber, dl.description, dpl.distributionpointnumber, dpl.description, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate,
         ih.invoicebusinessunit_id, ih.cluster_id, ih.invoicefrequency_id, ih.startdate, ih.enddate, iflp.enddate, iflp.year, iflp.period, iflp.enddate - iflp.cutoffdate + 1, p.code,
         ui.product_id, ui.sizedefinition_id, ui.finishingmethod_id, cl.customer_id, uil.creditamount, uil.lossstatus, c.language_id, c.lossgracescheme_id
union all
select cl.customernumber, cl.name, dpl.distributionpointnumber, dpl.description dpl_description, ih.startdate, ih.enddate,
       (select cc.code
          from currency cc
         where cc.currency_id = ih.currency_id) currencycode,
       dl.departmentnumber, dl.description, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.invoicebusinessunit_id,
       ih.cluster_id, ih.invoicefrequency_id, iflp.enddate periodenddate, iflp.year, iflp.period,
       coalesce(iflp.enddate - iflp.cutoffdate + 1, (select max(plpc.chargelossuniquepooldays )
                                                       from productlistpercustomer plpc
                                                      where plpc.customer_id = cl.customer_id
                                                        and plpc.product_id = ui.product_id
                                                        and plpc.sizedefinition_id = ui.sizedefinition_id
                                                        and plpc.finishingmethod_id = ui.finishingmethod_id
                                                        and plpc.dateactive <= sysdate
                                                        and plpc.dateinactive > sysdate )) daysinperiod,
       2 chargetype, p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = ui.product_id
           and pd.language_id = c.language_id) productdescription,
       sum(uil.lossamount) amount, count(1) qty, uil.lossstatus,
       (select sd.code
          from sizedefinition sd
         where sd.sizedefinition_id = ui.sizedefinition_id) size_code,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = ui.sizedefinition_id
           and sdd.language_id = c.language_id) size_desc,
       (select lsg.code
          from lossgracescheme lsg
         where lsg.lossgracescheme_id = c.lossgracescheme_id) lossgraceschemecode
 from uniqueitemloss uil
      left join invoicefrequencylossperiod iflp on uil.invoicefrequencylossperiod_id = iflp.invoicefrequencylossperiod_id
      join invoiceheader ih on uil.lossinvoiceheader_id = ih.invoiceheader_id
      join customer_link cl
           left join customer c on c.customer_id = cl.customer_id
      on uil.customer_link_id = cl.customer_link_id
      join distributionpoint_link dpl
           join department_link dl on dpl.department_link_id = dl.department_link_id
      on uil.distributionpoint_link_id = dpl.distributionpoint_link_id
      join uniqueitem ui
           join product p on ui.product_id = p.product_id
      on uil.uniqueitem_link_id = ui.uniqueitem_id
group by cl.customernumber, cl.name, ih.currency_id, dl.departmentnumber, dl.description, dpl.distributionpointnumber, dpl.description, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate,
         ih.invoicebusinessunit_id, ih.cluster_id, ih.invoicefrequency_id, ih.startdate, ih.enddate, iflp.enddate, iflp.year, iflp.period, iflp.enddate - iflp.cutoffdate + 1, p.code,
         ui.product_id, ui.sizedefinition_id, ui.finishingmethod_id, cl.customer_id, uil.lossamount, uil.lossstatus, c.language_id, c.lossgracescheme_id
union all
select cl.customernumber, cl.name, dpl.distributionpointnumber, dpl.description dpl_description, ih.startdate, ih.enddate,
       (select cc.code
          from currency cc
         where cc.currency_id = ih.currency_id) currencycode,
       dl.departmentnumber, dl.description, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.invoicebusinessunit_id,
       ih.cluster_id, ih.invoicefrequency_id, iflp.enddate periodenddate, iflp.year, iflp.period,
       coalesce(iflp.enddate - iflp.cutoffdate + 1, (select max(plpc.chargelossuniquepooldays )
                                                       from productlistpercustomer plpc
                                                      where plpc.customer_id = cl.customer_id
                                                        and plpc.product_id = ri.product_link_id
                                                        and plpc.sizedefinition_id = ri.sizedefinition_link_id
                                                        and plpc.dateactive <= sysdate
                                                        and plpc.dateinactive > sysdate )) daysinperiod,
       1 chargetype, p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = ri.product_link_id
           and pd.language_id = c.language_id) productdescription,
       sum(uil.creditamount) amount, count(1) qty, uil.lossstatus,
       (select sd.code
          from sizedefinition sd
         where sd.sizedefinition_id = ri.sizedefinition_link_id) size_code,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = ri.sizedefinition_link_id
           and sdd.language_id = c.language_id) size_desc,
       (select lsg.code
          from lossgracescheme lsg
         where lsg.lossgracescheme_id = c.lossgracescheme_id) lossgraceschemecode
 from uniqueitemloss  uil
      left join invoicefrequencylossperiod iflp on uil.invoicefrequencylossperiod_id = iflp.invoicefrequencylossperiod_id
      join invoiceheader ih on uil.creditinvoiceheader_id = ih.invoiceheader_id
      join customer_link cl
           left join customer c on c.customer_id = cl.customer_id
      on uil.customer_link_id = cl.customer_link_id
      join distributionpoint_link dpl
           join department_link dl on dpl.department_link_id = dl.department_link_id
      on uil.distributionpoint_link_id = dpl.distributionpoint_link_id
      join raggeditem ri
           join product p on ri.product_link_id = p.product_id
      on uil.uniqueitem_link_id = ri.raggeditem_id
where uil.lossstatus >= 2
group by cl.customernumber, cl.name, ih.currency_id, dl.departmentnumber, dl.description, dpl.distributionpointnumber, dpl.description, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.invoicebusinessunit_id,
         ih.cluster_id, ih.invoicefrequency_id, ih.startdate, ih.enddate, iflp.enddate, iflp.year, iflp.period, iflp.enddate - iflp.cutoffdate + 1, p.code,
         ri.product_link_id, ri.sizedefinition_link_id, cl.customer_id, uil.creditamount, uil.lossstatus, c.language_id, c.lossgracescheme_id
union all
select cl.customernumber, cl.name, dpl.distributionpointnumber, dpl.description dpl_description, ih.startdate, ih.enddate,
       (select cc.code
          from currency cc
         where cc.currency_id = ih.currency_id) currencycode,
       dl.departmentnumber, dl.description, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.invoicebusinessunit_id,
       ih.cluster_id, ih.invoicefrequency_id, iflp.enddate periodenddate, iflp.year, iflp.period,
       coalesce(iflp.enddate - iflp.cutoffdate + 1, (select max(plpc.chargelossuniquepooldays )
                                                       from productlistpercustomer plpc
                                                      where plpc.customer_id = cl.customer_id
                                                        and plpc.product_id = ri.product_link_id
                                                        and plpc.sizedefinition_id = ri.sizedefinition_link_id
                                                        and plpc.dateactive <= sysdate
                                                        and plpc.dateinactive > sysdate )) daysinperiod,
       2 chargetype, p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = ri.product_link_id
           and pd.language_id = c.language_id) productdescription,
       sum(uil.lossamount) amount, count(1) qty, uil.lossstatus,
       (select sd.code
          from sizedefinition sd
         where sd.sizedefinition_id = ri.sizedefinition_link_id) size_code,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = ri.sizedefinition_link_id
           and sdd.language_id = c.language_id) size_desc,
       (select lsg.code
          from lossgracescheme lsg
         where lsg.lossgracescheme_id = c.lossgracescheme_id) lossgraceschemecode
from uniqueitemloss uil
     left join invoicefrequencylossperiod iflp on uil.invoicefrequencylossperiod_id = iflp.invoicefrequencylossperiod_id
     join invoiceheader ih on uil.lossinvoiceheader_id = ih.invoiceheader_id
      join customer_link cl
           left join customer c on c.customer_id = cl.customer_id
      on uil.customer_link_id = cl.customer_link_id
      join distributionpoint_link dpl
           join department_link dl on dpl.department_link_id = dl.department_link_id
      on uil.distributionpoint_link_id = dpl.distributionpoint_link_id
      join raggeditem ri
           join product p on ri.product_link_id = p.product_id
      on uil.uniqueitem_link_id = ri.raggeditem_id
group by cl.customernumber, cl.name, ih.currency_id, dl.departmentnumber, dl.description, dpl.distributionpointnumber, dpl.description, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.invoicebusinessunit_id,
         ih.cluster_id, ih.invoicefrequency_id, ih.startdate, ih.enddate, iflp.enddate, iflp.year, iflp.period, iflp.enddate - iflp.cutoffdate + 1, p.code,
         ri.product_link_id, ri.sizedefinition_link_id, cl.customer_id, uil.lossamount, uil.lossstatus, c.language_id, c.lossgracescheme_id
/

  CREATE OR REPLACE VIEW "V_LOSSFORPOOLPERPRODUCT" ("CUSTOMERNUMBER", "NAME", "INVOICEHEADER_ID", "CURRENCYCODE", "INVOICENUMBER", "INVOICEDATE", "INVOICEBUSINESSUNIT_ID", "INVOICEFREQUENCY_ID", "CLUSTER_ID", "PERIODENDDATE", "STARTDATE", "ENDDATE", "YEAR", "PERIOD", "DAYSINPERIOD", "CHARGETYPE", "PRODUCTCODE", "PRODUCTDESCRIPTION", "AMOUNT", "QTY", "LOSSSTATUS", "SIZE_CODE", "SIZE_DESC", "LOSSGRACESCHEMECODE") AS 
  select /*version 2.1*/
       cl.customernumber, cl.name, ih.invoiceheader_id,
       (select cc.code
          from currency cc
         where cc.currency_id = ih.currency_id) currencycode,
       ih.invoicenumber, ih.invoicedate, ih.invoicebusinessunit_id, ih.invoicefrequency_id, ih.cluster_id, iflp.enddate periodenddate,
       ih.startdate, ih.enddate, iflp.year, iflp.period,
       coalesce(iflp.enddate-iflp.cutoffdate+ 1, (select max(plpc.chargelossuniquepooldays )
                                                    from productlistpercustomer plpc
                                                   where plpc.customer_id=cl.customer_id
                                                     and plpc.product_id = ui.product_id
                                                     and plpc.sizedefinition_id = ui.sizedefinition_id
                                                     and plpc.finishingmethod_id = ui.finishingmethod_id
                                                     and plpc.dateactive <= sysdate
                                                     and plpc.dateinactive > sysdate )) daysinperiod,
       1 chargetype,  p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = ui.product_id
           and pd.language_id = c.language_id) productdescription,
       sum(uil.creditamount) amount, count(1) qty, uil.lossstatus,
       (select sd.code
          from sizedefinition sd
         where sd.sizedefinition_id = ui.sizedefinition_id) size_code,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = ui.sizedefinition_id
           and sdd.language_id = c.language_id) size_desc,
       (select lsg.code
          from lossgracescheme lsg
         where lsg.lossgracescheme_id = c.lossgracescheme_id) lossgraceschemecode
 from uniqueitemloss uil
      left join invoicefrequencylossperiod iflp on uil.invoicefrequencylossperiod_id = iflp.invoicefrequencylossperiod_id
      join invoiceheader ih on uil.creditinvoiceheader_id = ih.invoiceheader_id
      join customer_link cl
           left join customer c on c.customer_id = cl.customer_id
      on uil.customer_link_id = cl.customer_link_id
      join uniqueitem ui
           join product p on ui.product_id = p.product_id
      on uil.uniqueitem_link_id = ui.uniqueitem_id
where uil.lossstatus >= 2
group by cl.customernumber, cl.name, ih.invoiceheader_id, ih.currency_id,  ih.invoicenumber, ih.invoicedate, ih.invoicebusinessunit_id, ih.invoicefrequency_id,
         ih.cluster_id, iflp.enddate, ih.startdate, ih.enddate, iflp.year, iflp.period, iflp.enddate-iflp.cutoffdate+ 1,  p.code,
         ui.product_id, ui.sizedefinition_id, ui.finishingmethod_id, cl.customer_id, uil.lossstatus, c.language_id, c.lossgracescheme_id
union all
select cl.customernumber, cl.name, ih.invoiceheader_id,
       (select cc.code
          from currency cc
         where cc.currency_id = ih.currency_id) currencycode,
       ih.invoicenumber, ih.invoicedate, ih.invoicebusinessunit_id, ih.invoicefrequency_id, ih.cluster_id,
       iflp.enddate periodenddate, ih.startdate, ih.enddate, iflp.year, iflp.period,
       coalesce(iflp.enddate-iflp.cutoffdate+ 1, (select max(plpc.chargelossuniquepooldays )
                                                    from productlistpercustomer plpc
                                                   where plpc.customer_id=cl.customer_id
                                                     and plpc.product_id = ui.product_id
                                                     and plpc.sizedefinition_id = ui.sizedefinition_id
                                                     and plpc.finishingmethod_id = ui.finishingmethod_id
                                                     and plpc.dateactive <= sysdate
                                                     and plpc.dateinactive > sysdate )) daysinperiod,
       2 chargetype, p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = ui.product_id
           and pd.language_id = c.language_id) productdescription,
       sum(uil.lossamount) amount, count(1) qty, uil.lossstatus,
       (select sd.code
          from sizedefinition sd
         where sd.sizedefinition_id = ui.sizedefinition_id) size_code,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = ui.sizedefinition_id
           and sdd.language_id = c.language_id) size_desc,
       (select lsg.code
          from lossgracescheme lsg
         where lsg.lossgracescheme_id = c.lossgracescheme_id) lossgraceschemecode
 from uniqueitemloss uil
      left join invoicefrequencylossperiod iflp on uil.invoicefrequencylossperiod_id = iflp.invoicefrequencylossperiod_id
      join invoiceheader ih on uil.lossinvoiceheader_id = ih.invoiceheader_id
      join customer_link cl
           left join customer c on c.customer_id = cl.customer_id
      on uil.customer_link_id = cl.customer_link_id
      join uniqueitem ui
           join product p on ui.product_id = p.product_id
      on uil.uniqueitem_link_id = ui.uniqueitem_id
group by cl.customernumber, cl.name, ih.invoiceheader_id, ih.currency_id,  ih.invoicenumber, ih.invoicedate, ih.invoicebusinessunit_id, ih.invoicefrequency_id,
         ih.cluster_id, iflp.enddate, ih.startdate, ih.enddate, iflp.year, iflp.period, iflp.enddate-iflp.cutoffdate+ 1,  p.code,
         ui.product_id, ui.sizedefinition_id, ui.finishingmethod_id, cl.customer_id, uil.lossstatus, c.language_id, c.lossgracescheme_id
union all
select cl.customernumber, cl.name, ih.invoiceheader_id,
       (select cc.code
          from currency cc
         where cc.currency_id = ih.currency_id) currencycode,
       ih.invoicenumber, ih.invoicedate, ih.invoicebusinessunit_id, ih.invoicefrequency_id, ih.cluster_id,
       iflp.enddate periodenddate, ih.startdate, ih.enddate, iflp.year, iflp.period,
       coalesce(iflp.enddate-iflp.cutoffdate+ 1, (select max(plpc.chargelossuniquepooldays )
                                                    from productlistpercustomer plpc
                                                   where plpc.customer_id=cl.customer_id
                                                     and plpc.product_id = ri.product_link_id
                                                     and plpc.sizedefinition_id = ri.sizedefinition_link_id
                                                     and plpc.dateactive <= sysdate
                                                     and plpc.dateinactive > sysdate )) daysinperiod,
       1 chargetype, p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = ri.product_link_id
           and pd.language_id = c.language_id) productdescription,
       sum(uil.creditamount) amount, count(1) qty, uil.lossstatus,
       (select sd.code
          from sizedefinition sd
         where sd.sizedefinition_id = ri.sizedefinition_link_id) size_code,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = ri.sizedefinition_link_id
           and sdd.language_id = c.language_id) size_desc,
       (select lsg.code
          from lossgracescheme lsg
         where lsg.lossgracescheme_id = c.lossgracescheme_id) lossgraceschemecode
 from uniqueitemloss uil
      left join invoicefrequencylossperiod iflp on uil.invoicefrequencylossperiod_id = iflp.invoicefrequencylossperiod_id
      join invoiceheader ih on uil.creditinvoiceheader_id = ih.invoiceheader_id
      join customer_link cl
           left join customer c on c.customer_id = cl.customer_id
      on uil.customer_link_id = cl.customer_link_id
      join raggeditem ri
           join product p on ri.product_link_id = p.product_id
      on uil.uniqueitem_link_id = ri.raggeditem_id
where uil.lossstatus >= 2
group by cl.customernumber, cl.name, ih.invoiceheader_id, ih.currency_id, ih.invoicenumber, ih.invoicedate, ih.invoicebusinessunit_id, ih.invoicefrequency_id,
         ih.cluster_id, iflp.enddate, ih.startdate, ih.enddate, iflp.year, iflp.period, iflp.enddate-iflp.cutoffdate+ 1,  p.code,
         ri.product_link_id, ri.sizedefinition_link_id, cl.customer_id, uil.lossstatus, c.language_id, c.lossgracescheme_id
union all
select cl.customernumber, cl.name, ih.invoiceheader_id,
       (select cc.code
          from currency cc
         where cc.currency_id = ih.currency_id) currencycode,
       ih.invoicenumber, ih.invoicedate,  ih.invoicebusinessunit_id,ih.invoicefrequency_id, ih.cluster_id,
       ih.startdate, ih.enddate, iflp.enddate periodenddate, iflp.year, iflp.period,
       coalesce(iflp.enddate-iflp.cutoffdate+ 1, (select max(plpc.chargelossuniquepooldays )
                                                    from productlistpercustomer plpc
                                                   where plpc.customer_id=cl.customer_id
                                                     and plpc.product_id = ri.product_link_id
                                                     and plpc.sizedefinition_id = ri.sizedefinition_link_id
                                                     and plpc.dateactive <= sysdate
                                                     and plpc.dateinactive > sysdate )) daysinperiod,
       2 chargetype,  p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = ri.product_link_id
           and pd.language_id = c.language_id) productdescription,
       sum(uil.lossamount) amount, count(1) qty, uil.lossstatus,
       (select sd.code
          from sizedefinition sd
         where sd.sizedefinition_id = ri.sizedefinition_link_id) size_code,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = ri.sizedefinition_link_id
           and sdd.language_id = c.language_id) size_desc,
       (select lsg.code
          from lossgracescheme lsg
         where lsg.lossgracescheme_id = c.lossgracescheme_id) lossgraceschemecode
 from uniqueitemloss uil
      left join invoicefrequencylossperiod iflp on uil.invoicefrequencylossperiod_id = iflp.invoicefrequencylossperiod_id
      join invoiceheader ih on uil.lossinvoiceheader_id = ih.invoiceheader_id
      join customer_link cl
           left join customer c on c.customer_id = cl.customer_id
      on uil.customer_link_id = cl.customer_link_id
      join raggeditem ri
           join product p on ri.product_link_id = p.product_id
      on uil.uniqueitem_link_id = ri.raggeditem_id
group by cl.customernumber, cl.name, ih.invoiceheader_id, ih.currency_id, ih.invoicenumber, ih.invoicedate, ih.invoicebusinessunit_id, ih.invoicefrequency_id,
         ih.cluster_id, iflp.enddate, ih.startdate, ih.enddate, iflp.year, iflp.period, iflp.enddate-iflp.cutoffdate+ 1,  p.code,
         ri.product_link_id, ri.sizedefinition_link_id, cl.customer_id, uil.lossstatus, c.language_id, c.lossgracescheme_id
/

  CREATE OR REPLACE VIEW "V_LOSSFORPOOLPERPRODUCTDEPT" ("CUSTOMERNUMBER", "NAME", "CURRENCYCODE", "DEPARTMENTNUMBER", "DESCRIPTION", "INVOICEHEADER_ID", "INVOICENUMBER", "INVOICEDATE", "INVOICEBUSINESSUNIT_ID", "CLUSTER_ID", "INVOICEFREQUENCY_ID", "PERIODENDDATE", "YEAR", "PERIOD", "DAYSINPERIOD", "CHARGETYPE", "PRODUCTCODE", "PRODUCTDESCRIPTION", "AMOUNT", "QTY", "LOSSSTATUS", "SIZE_CODE", "SIZE_DESC", "LOSSGRACESCHEMECODE") AS 
  select /*version 2.1*/
       cl.customernumber, cl.name,
       (select cc.code
          from currency cc
         where cc.currency_id = ih.currency_id) currencycode,
       dl.departmentnumber, dl.description, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.invoicebusinessunit_id,
       ih.cluster_id, ih.invoicefrequency_id, iflp.enddate periodenddate, iflp.year, iflp.period,
       coalesce(iflp.enddate - iflp.cutoffdate + 1, (select max(plpc.chargelossuniquepooldays )
                                                       from productlistpercustomer plpc
                                                      where plpc.customer_id = cl.customer_id
                                                        and plpc.product_id = ui.product_id
                                                        and plpc.sizedefinition_id = ui.sizedefinition_id
                                                        and plpc.finishingmethod_id = ui.finishingmethod_id
                                                        and plpc.dateactive <= sysdate
                                                        and plpc.dateinactive > sysdate )) daysinperiod,
       1 chargetype, p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = ui.product_id
           and pd.language_id = c.language_id) productdescription,
       sum(uil.creditamount) amount, count(1) qty, uil.lossstatus,
       (select sd.code
          from sizedefinition sd
         where sd.sizedefinition_id = ui.sizedefinition_id) size_code,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = ui.sizedefinition_id
           and sdd.language_id = c.language_id) size_desc,
       (select lsg.code
          from lossgracescheme lsg
         where lsg.lossgracescheme_id = c.lossgracescheme_id) lossgraceschemecode
 from uniqueitemloss uil
      left join invoicefrequencylossperiod iflp on uil.invoicefrequencylossperiod_id = iflp.invoicefrequencylossperiod_id
      join invoiceheader ih on uil.creditinvoiceheader_id = ih.invoiceheader_id
      join customer_link cl
           left join customer c on c.customer_id = cl.customer_id
      on uil.customer_link_id = cl.customer_link_id
      join distributionpoint_link dpl
           join department_link dl on dpl.department_link_id = dl.department_link_id
      on uil.distributionpoint_link_id = dpl.distributionpoint_link_id
      join uniqueitem ui
           join product p on ui.product_id = p.product_id
      on uil.uniqueitem_link_id = ui.uniqueitem_id
where uil.lossstatus >= 2
group by cl.customernumber, cl.name, ih.currency_id, dl.departmentnumber, dl.description, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate,
         ih.invoicebusinessunit_id, ih.cluster_id, ih.invoicefrequency_id, iflp.enddate, iflp.year, iflp.period, iflp.enddate - iflp.cutoffdate + 1, p.code,
         ui.product_id, ui.sizedefinition_id, ui.finishingmethod_id, cl.customer_id, uil.creditamount, uil.lossstatus, c.language_id, c.lossgracescheme_id
union all
select cl.customernumber, cl.name,
       (select cc.code
          from currency cc
         where cc.currency_id = ih.currency_id) currencycode,
       dl.departmentnumber, dl.description, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.invoicebusinessunit_id,
       ih.cluster_id, ih.invoicefrequency_id, iflp.enddate periodenddate, iflp.year, iflp.period,
       coalesce(iflp.enddate - iflp.cutoffdate + 1, (select max(plpc.chargelossuniquepooldays )
                                                       from productlistpercustomer plpc
                                                      where plpc.customer_id = cl.customer_id
                                                        and plpc.product_id = ui.product_id
                                                        and plpc.sizedefinition_id = ui.sizedefinition_id
                                                        and plpc.finishingmethod_id = ui.finishingmethod_id
                                                        and plpc.dateactive <= sysdate
                                                        and plpc.dateinactive > sysdate )) daysinperiod,
       2 chargetype, p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = ui.product_id
           and pd.language_id = c.language_id) productdescription,
       sum(uil.lossamount) amount, count(1) qty, uil.lossstatus,
       (select sd.code
          from sizedefinition sd
         where sd.sizedefinition_id = ui.sizedefinition_id) size_code,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = ui.sizedefinition_id
           and sdd.language_id = c.language_id) size_desc,
       (select lsg.code
          from lossgracescheme lsg
         where lsg.lossgracescheme_id = c.lossgracescheme_id) lossgraceschemecode
 from uniqueitemloss uil
      left join invoicefrequencylossperiod iflp on uil.invoicefrequencylossperiod_id = iflp.invoicefrequencylossperiod_id
      join invoiceheader ih on uil.lossinvoiceheader_id = ih.invoiceheader_id
      join customer_link cl
           left join customer c on c.customer_id = cl.customer_id
      on uil.customer_link_id = cl.customer_link_id
      join distributionpoint_link dpl
           join department_link dl on dpl.department_link_id = dl.department_link_id
      on uil.distributionpoint_link_id = dpl.distributionpoint_link_id
      join uniqueitem ui
           join product p on ui.product_id = p.product_id
      on uil.uniqueitem_link_id = ui.uniqueitem_id
group by cl.customernumber, cl.name, ih.currency_id, dl.departmentnumber, dl.description, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate,
         ih.invoicebusinessunit_id, ih.cluster_id, ih.invoicefrequency_id, iflp.enddate, iflp.year, iflp.period, iflp.enddate - iflp.cutoffdate + 1, p.code,
         ui.product_id, ui.sizedefinition_id, ui.finishingmethod_id, cl.customer_id, uil.lossamount, uil.lossstatus, c.language_id, c.lossgracescheme_id
union all
select cl.customernumber, cl.name,
       (select cc.code
          from currency cc
         where cc.currency_id = ih.currency_id) currencycode,
       dl.departmentnumber, dl.description, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.invoicebusinessunit_id,
       ih.cluster_id, ih.invoicefrequency_id, iflp.enddate periodenddate, iflp.year, iflp.period,
       coalesce(iflp.enddate - iflp.cutoffdate + 1, (select max(plpc.chargelossuniquepooldays )
                                                       from productlistpercustomer plpc
                                                      where plpc.customer_id = cl.customer_id
                                                        and plpc.product_id = ri.product_link_id
                                                        and plpc.sizedefinition_id = ri.sizedefinition_link_id
                                                        and plpc.dateactive <= sysdate
                                                        and plpc.dateinactive > sysdate )) daysinperiod,
       1 chargetype, p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = ri.product_link_id
           and pd.language_id = c.language_id) productdescription,
       sum(uil.creditamount) amount, count(1) qty, uil.lossstatus,
       (select sd.code
          from sizedefinition sd
         where sd.sizedefinition_id = ri.sizedefinition_link_id) size_code,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = ri.sizedefinition_link_id
           and sdd.language_id = c.language_id) size_desc,
       (select lsg.code
          from lossgracescheme lsg
         where lsg.lossgracescheme_id = c.lossgracescheme_id) lossgraceschemecode
 from uniqueitemloss  uil
      left join invoicefrequencylossperiod iflp on uil.invoicefrequencylossperiod_id = iflp.invoicefrequencylossperiod_id
      join invoiceheader ih on uil.creditinvoiceheader_id = ih.invoiceheader_id
      join customer_link cl
           left join customer c on c.customer_id = cl.customer_id
      on uil.customer_link_id = cl.customer_link_id
      join distributionpoint_link dpl
           join department_link dl on dpl.department_link_id = dl.department_link_id
      on uil.distributionpoint_link_id = dpl.distributionpoint_link_id
      join raggeditem ri
           join product p on ri.product_link_id = p.product_id
      on uil.uniqueitem_link_id = ri.raggeditem_id
where uil.lossstatus >= 2
group by cl.customernumber, cl.name, ih.currency_id, dl.departmentnumber, dl.description, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.invoicebusinessunit_id,
         ih.cluster_id, ih.invoicefrequency_id, iflp.enddate, iflp.year, iflp.period, iflp.enddate - iflp.cutoffdate + 1, p.code,
         ri.product_link_id, ri.sizedefinition_link_id, cl.customer_id, uil.creditamount, uil.lossstatus, c.language_id, c.lossgracescheme_id
union all
select cl.customernumber, cl.name,
       (select cc.code
          from currency cc
         where cc.currency_id = ih.currency_id) currencycode,
       dl.departmentnumber, dl.description, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.invoicebusinessunit_id,
       ih.cluster_id, ih.invoicefrequency_id, iflp.enddate periodenddate, iflp.year, iflp.period,
       coalesce(iflp.enddate - iflp.cutoffdate + 1, (select max(plpc.chargelossuniquepooldays )
                                                       from productlistpercustomer plpc
                                                      where plpc.customer_id = cl.customer_id
                                                        and plpc.product_id = ri.product_link_id
                                                        and plpc.sizedefinition_id = ri.sizedefinition_link_id
                                                        and plpc.dateactive <= sysdate
                                                        and plpc.dateinactive > sysdate )) daysinperiod,
       2 chargetype, p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = ri.product_link_id
           and pd.language_id = c.language_id) productdescription,
       sum(uil.lossamount) amount, count(1) qty, uil.lossstatus,
       (select sd.code
          from sizedefinition sd
         where sd.sizedefinition_id = ri.sizedefinition_link_id) size_code,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = ri.sizedefinition_link_id
           and sdd.language_id = c.language_id) size_desc,
       (select lsg.code
          from lossgracescheme lsg
         where lsg.lossgracescheme_id = c.lossgracescheme_id) lossgraceschemecode
from uniqueitemloss uil
     left join invoicefrequencylossperiod iflp on uil.invoicefrequencylossperiod_id = iflp.invoicefrequencylossperiod_id
     join invoiceheader ih on uil.lossinvoiceheader_id = ih.invoiceheader_id
      join customer_link cl
           left join customer c on c.customer_id = cl.customer_id
      on uil.customer_link_id = cl.customer_link_id
      join distributionpoint_link dpl
           join department_link dl on dpl.department_link_id = dl.department_link_id
      on uil.distributionpoint_link_id = dpl.distributionpoint_link_id
      join raggeditem ri
           join product p on ri.product_link_id = p.product_id
      on uil.uniqueitem_link_id = ri.raggeditem_id
group by cl.customernumber, cl.name, ih.currency_id, dl.departmentnumber, dl.description, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.invoicebusinessunit_id,
         ih.cluster_id, ih.invoicefrequency_id, iflp.enddate, iflp.year, iflp.period, iflp.enddate - iflp.cutoffdate + 1, p.code,
         ri.product_link_id, ri.sizedefinition_link_id, cl.customer_id, uil.lossamount, uil.lossstatus, c.language_id, c.lossgracescheme_id
/

  CREATE OR REPLACE VIEW "V_LOSSPERPRODCONS" ("CUSTOMERNUMBER", "NAME", "CURRENCYCODE", "DEPARTMENTNUMBER", "DESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DPL_DESCRIPTION", "INVOICEHEADER_ID", "INVOICENUMBER", "INVOICEDATE", "STARTDATE", "ENDDATE", "PERIODENDDATE", "YEAR", "PERIOD", "DAYSINPERIOD", "CHARGETYPE", "PRODUCTCODE", "PRODUCTDESCRIPTION", "AMOUNT", "QTY", "LOSSSTATUS", "SIZE_CODE", "SIZE_DESC") AS 
  select cl.customernumber,
       cl.name,
       (select c.code from currency c where c.currency_id = ih.currency_id) currencycode,
       dl.departmentnumber,
       dl.description,
       dpl.distributionpointnumber,
       dpl.description dpl_description,
       ih.invoiceheader_id,
       ih.invoicenumber,
       ih.invoicedate,
       ih.startdate,
       ih.enddate,
       iflp.enddate periodenddate,
       iflp.year,
       iflp.period,
       coalesce(iflp.enddate-iflp.cutoffdate+ 1, (select max(plpc.chargelossuniquepooldays )
             from productlistpercustomer plpc where plpc.customer_id=cl.customer_id and plpc.product_id = ui.product_id
                  and plpc.sizedefinition_id = ui.sizedefinition_id and plpc.finishingmethod_id = ui.finishingmethod_id
                  and plpc.dateactive <= sysdate and plpc.dateinactive > sysdate )) daysinperiod,
       1 chargetype,
       p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = ui.product_id
           and pd.language_id = c.language_id) productdescription,
       sum(uil.creditamount) amount, count(1) qty, uil.lossstatus,
       (select sd.code from sizedefinition sd where sd.sizedefinition_id = ui.sizedefinition_id) size_code,
       (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = ui.sizedefinition_id and sdd.language_id = c.language_id) size_desc
from uniqueitemloss         uil
       left outer join invoicefrequencylossperiod iflp on uil.invoicefrequencylossperiod_id = iflp.invoicefrequencylossperiod_id,
       invoiceheader          ih,
       customer_link          cl
       left outer join customer c on c.customer_id = cl.customer_id,
       distributionpoint_link dpl,
       department_link        dl,       --lossperiods            lp,
       uniqueitem             ui,
       product                p
where uil.creditinvoiceheader_id = ih.invoiceheader_id
   and uil.customer_link_id = cl.customer_link_id
   and uil.distributionpoint_link_id = dpl.distributionpoint_link_id
   and dpl.department_link_id = dl.department_link_id   --and uil.lossperiods_id = lp.lossperiods_id
   and uil.uniqueitem_link_id = ui.uniqueitem_id
   and ui.product_id = p.product_id
   and uil.lossstatus<>5
group by cl.customernumber,
       cl.name,
       ih.currency_id,
       dl.departmentnumber,
       dl.description,
       dpl.distributionpointnumber,
       dpl.description,
       ih.invoiceheader_id,
       ih.invoicenumber,
       ih.invoicedate,
       ih.startdate,
       ih.enddate,
       iflp.enddate,
       iflp.year,
       iflp.period,
       iflp.enddate-iflp.cutoffdate+ 1,
       p.code,
       ui.product_id, ui.sizedefinition_id, ui.finishingmethod_id, cl.customer_id, /*uil.creditamount,*/ uil.lossstatus, c.language_id
union all
select cl.customernumber,
       cl.name,
(select c.code from currency c where c.currency_id = ih.currency_id) currencycode,
       dl.departmentnumber,
       dl.description,
       dpl.distributionpointnumber,
       dpl.description dpl_description,
       ih.invoiceheader_id,
       ih.invoicenumber,
       ih.invoicedate,
       ih.startdate,
       ih.enddate,
       iflp.enddate periodenddate,
       iflp.year,
       iflp.period,
       coalesce(iflp.enddate-iflp.cutoffdate+ 1, (select max(plpc.chargelossuniquepooldays )
             from productlistpercustomer plpc where plpc.customer_id=cl.customer_id and plpc.product_id = ui.product_id
                  and plpc.sizedefinition_id = ui.sizedefinition_id and plpc.finishingmethod_id = ui.finishingmethod_id
                  and plpc.dateactive <= sysdate and plpc.dateinactive > sysdate )) daysinperiod,
       2 chargetype,
       p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = ui.product_id
           and pd.language_id = c.language_id) productdescription,
       sum(uil.lossamount) amount, count(1) qty, uil.lossstatus,
       (select sd.code from sizedefinition sd where sd.sizedefinition_id = ui.sizedefinition_id) size_code,
       (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = ui.sizedefinition_id and sdd.language_id = c.language_id) size_desc
from uniqueitemloss         uil
       left outer join invoicefrequencylossperiod iflp on uil.invoicefrequencylossperiod_id = iflp.invoicefrequencylossperiod_id,
       invoiceheader          ih,
       customer_link          cl
       left outer join customer c on c.customer_id = cl.customer_id,
       distributionpoint_link dpl,
       department_link        dl,       --lossperiods            lp,
       uniqueitem             ui,
       product                p
where uil.lossinvoiceheader_id = ih.invoiceheader_id
   and uil.customer_link_id = cl.customer_link_id
   and uil.distributionpoint_link_id = dpl.distributionpoint_link_id
   and dpl.department_link_id = dl.department_link_id   --and uil.lossperiods_id = lp.lossperiods_id
   and uil.uniqueitem_link_id = ui.uniqueitem_id
   and ui.product_id = p.product_id
   and uil.lossstatus<>5
group by cl.customernumber,
       cl.name,
       ih.currency_id,
       dl.departmentnumber,
       dl.description,
       dpl.distributionpointnumber,
       dpl.description,
       ih.invoiceheader_id,
       ih.invoicenumber,
       ih.invoicedate,
       ih.startdate,
       ih.enddate,
       iflp.enddate,
       iflp.year,
       iflp.period,
       iflp.enddate-iflp.cutoffdate+ 1,
       p.code,
       ui.product_id, ui.sizedefinition_id, ui.finishingmethod_id, cl.customer_id, /*uil.lossamount,*/ uil.lossstatus, c.language_id
union all
select cl.customernumber,
       cl.name,
       (select c.code from currency c where c.currency_id = ih.currency_id) currencycode,
       dl.departmentnumber,
       dl.description,
       dpl.distributionpointnumber,
       dpl.description dpl_description,
       ih.invoiceheader_id,
       ih.invoicenumber,
       ih.invoicedate,
       ih.startdate,
       ih.enddate,
       iflp.enddate periodenddate,
       iflp.year,
       iflp.period,
       coalesce(iflp.enddate-iflp.cutoffdate+ 1, (select max(plpc.chargelossuniquepooldays )
             from productlistpercustomer plpc where plpc.customer_id=cl.customer_id and plpc.product_id = ri.product_link_id
                  and plpc.sizedefinition_id = ri.sizedefinition_link_id --and plpc.finishingmethod_id = any
                  and plpc.dateactive <= sysdate and plpc.dateinactive > sysdate )) daysinperiod,
       1 chargetype,
       p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = ri.product_link_id
           and pd.language_id = c.language_id) productdescription,
       sum(uil.creditamount) amount, count(1) qty, uil.lossstatus,
       (select sd.code from sizedefinition sd where sd.sizedefinition_id = ri.sizedefinition_link_id) size_code,
       (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = ri.sizedefinition_link_id and sdd.language_id = c.language_id) size_desc
from uniqueitemloss         uil
       left outer join invoicefrequencylossperiod iflp on uil.invoicefrequencylossperiod_id = iflp.invoicefrequencylossperiod_id,
       invoiceheader          ih,
       customer_link          cl
       left outer join customer c on c.customer_id = cl.customer_id,
       distributionpoint_link dpl,
       department_link        dl,       --lossperiods            lp,
       raggeditem             ri,
       product                p
where uil.creditinvoiceheader_id = ih.invoiceheader_id
   and uil.customer_link_id = cl.customer_link_id
   and uil.distributionpoint_link_id = dpl.distributionpoint_link_id
   and dpl.department_link_id = dl.department_link_id   --and uil.lossperiods_id = lp.lossperiods_id
   and uil.uniqueitem_link_id = ri.raggeditem_id
   and ri.product_link_id = p.product_id
   and uil.lossstatus<>5
group by  cl.customernumber,
       cl.name,
       ih.currency_id,
       dl.departmentnumber,
       dl.description,
       dpl.distributionpointnumber,
       dpl.description,
       ih.invoiceheader_id,
       ih.invoicenumber,
       ih.invoicedate,
       ih.startdate,
       ih.enddate,
       iflp.enddate,
       iflp.year,
       iflp.period,
       iflp.enddate-iflp.cutoffdate+ 1,
       p.code,
       ri.product_link_id, ri.sizedefinition_link_id, cl.customer_id, /*uil.creditamount,*/ uil.lossstatus, c.language_id
union all
select cl.customernumber,
       cl.name,
       (select c.code from currency c where c.currency_id = ih.currency_id) currencycode,
       dl.departmentnumber,
       dl.description,
       dpl.distributionpointnumber,
       dpl.description dpl_description,
       ih.invoiceheader_id,
       ih.invoicenumber,
       ih.invoicedate,
       ih.startdate,
       ih.enddate,
       iflp.enddate periodenddate,
       iflp.year,
       iflp.period,
       coalesce(iflp.enddate-iflp.cutoffdate+ 1, (select max(plpc.chargelossuniquepooldays )
             from productlistpercustomer plpc where plpc.customer_id=cl.customer_id and plpc.product_id = ri.product_link_id
                  and plpc.sizedefinition_id = ri.sizedefinition_link_id --and plpc.finishingmethod_id = any
                  and plpc.dateactive <= sysdate and plpc.dateinactive > sysdate )) daysinperiod,
       2 chargetype,
       p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = ri.product_link_id
           and pd.language_id = c.language_id) productdescription,
       sum(uil.lossamount) amount, count(1) qty, uil.lossstatus,
       (select sd.code from sizedefinition sd where sd.sizedefinition_id = ri.sizedefinition_link_id) size_code,
       (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = ri.sizedefinition_link_id and sdd.language_id = c.language_id) size_desc
from uniqueitemloss         uil
       left outer join invoicefrequencylossperiod iflp on uil.invoicefrequencylossperiod_id = iflp.invoicefrequencylossperiod_id,
       invoiceheader          ih,
       customer_link          cl
       left outer join customer c on c.customer_id = cl.customer_id,
       distributionpoint_link dpl,
       department_link        dl,       --lossperiods            lp,
       raggeditem             ri,
       product                p
where uil.lossinvoiceheader_id = ih.invoiceheader_id
   and uil.customer_link_id = cl.customer_link_id
   and uil.distributionpoint_link_id = dpl.distributionpoint_link_id
   and dpl.department_link_id = dl.department_link_id   --and uil.lossperiods_id = lp.lossperiods_id
   and uil.uniqueitem_link_id = ri.raggeditem_id
   and ri.product_link_id = p.product_id
   and uil.lossstatus<>5
group by cl.customernumber,
       cl.name,
       ih.currency_id,
       dl.departmentnumber,
       dl.description,
       dpl.distributionpointnumber,
       dpl.description,
       ih.invoiceheader_id,
       ih.invoicenumber,
       ih.invoicedate,
       ih.startdate,
       ih.enddate,
       iflp.enddate,
       iflp.year,
       iflp.period,
       iflp.enddate-iflp.cutoffdate+ 1,
       p.code,
       ri.product_link_id, ri.sizedefinition_link_id, cl.customer_id, /*uil.lossamount,*/ uil.lossstatus, c.language_id
/

  CREATE OR REPLACE VIEW "V_LOSTBUSINESS_CPC" ("CUSTOMER_ID", "DATEACTIVE", "REPORTPARAM_ID") AS 
  select /*version 1.0*/
       cpc.customer_id, max(cpc.dateactive) dateactive, rp.reportparam_id
  from contractspercustomer cpc
       left join competitor co on cpc.lostcompetitor_id = co.competitor_id
       left join gainlostreason gr on cpc.lostreason_id = gr.gainlostreason_id
       cross join reportparam rp
 where ((co.code between rp.string_value5 and rp.string_value6) or co.code is null)
   and ((gr.code between rp.string_value7 and rp.string_value8) or gr.code is null)
 group by cpc.customer_id, rp.reportparam_id
/

  CREATE OR REPLACE VIEW "V_LOSTBUSINESS_PROD" ("CUSTOMER_ID", "DATEINACTIVE", "ACTIVITYCODE", "ACTIVITYDESC", "PRODUCTCODE", "PRODUCTDESC", "COMPETITORCODE", "LOSTREASONDESC", "LANGUAGECODE", "REPORTPARAM_ID") AS 
  select /*version 1.0*/
       distinct plpc.customer_id, plpc.dateinactive, ac.code activitycode,
       (select acd.description
          from activity_desc acd
         where acd.activity_id = ac.activity_id
           and acd.language_id = l.language_id) activitydesc, pr.code productcode,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = l.language_id) productdesc, co.code competitorcode,
       (select gld.description
          from gainlostreason_desc gld
         where gld.gainlostreason_id = gl.gainlostreason_id
           and gld.language_id = l.language_id) lostreasondesc,
       l.code languagecode, rp.reportparam_id
  from productlistpercustomer plpc
       left join competitor co on plpc.lostcompetitor_id = co.competitor_id
       left join gainlostreason gl on plpc.lostreason_id = gl.gainlostreason_id
       join product pr on plpc.product_id = pr.product_id
       join productgroup pg on pr.productgroup_id = pg.productgroup_id
       join customeractivities ca
            join businessunitsperusergroup bug on ca.invoicebusinessunit_id = bug.businessunit_id
            join activity ac on ca.activity_id = ac.activity_id
       on plpc.customer_id = ca.customer_id and pg.activity_id = ca.activity_id
       cross join languages l
       cross join reportparam rp
 where bug.usergroup_id = rp.number_value1
   and plpc.dateinactive >= rp.date_value1
   and plpc.dateinactive <= rp.date_value2
   and ((co.code between rp.string_value5 and rp.string_value6) or co.code is null)
   and ((gl.code between rp.string_value7 and rp.string_value8) or gl.code is null)
/

  CREATE OR REPLACE VIEW "V_LOSTCUSTOMER" ("CUSTOMERNUMBER", "CUSTOMERNAME", "LOSTDATE", "CONTRACTWEEKSLEFT", "LOSTREVENUEAMOUNT", "PRICEDECIMALS", "AMOUNTDECIMALS", "CITY", "PRODUCTCODE", "PRODUCTDESC", "RESIDUALVALUEPERCENTAGE", "PRICE", "LANGUAGECODE", "CUSTOMER_ID", "PRODUCT_ID") AS 
  select c.customernumber, c.name customername, c.lostdate, c.contractweeksleft, c.lostrevenueamount,
  cr.decimals pricedecimals, cr.invoiceamountdecimals amountdecimals,
  ad.city,
  pr.code productcode,
  (select prd.description from product_desc prd where prd.product_id = pr.product_id
     and prd.language_id = languages.language_id) productdesc,
  rvlc.residualvaluepercentage, rvlc.price,
  languages.code languagecode,
  c.customer_id, pr.product_id
from residualvaluelostcustomer rvlc, customer c, address ad, product pr,
  weareremployment_link wel, currency cr,
  languages
where rvlc.customer_link_id = c.customer_id
  and c.visitaddress_id = ad.address_id
  and rvlc.product_link_id = pr.product_id
  and rvlc.weareremployment_link_id = wel.weareremployment_link_id
  and c.currency_id = cr.currency_id
/

  CREATE OR REPLACE VIEW "V_LOSTCUSTOMER_DET" ("CUSTOMER_ID", "PRODUCT_ID", "WEARERNAME", "WEARERNUMBER", "ISSUEDATE", "RESIDUALVALUEPERCENTAGE", "PRICE", "PRICEDECIMALS", "AMOUNTDECIMALS", "PRIMARYID") AS 
  select c.customer_id, rvlc.product_link_id product_id,
  wel.wearername, wel.wearernumber,
  rvlc.issuedate, rvlc.residualvaluepercentage, rvlc.price,
  cr.decimals pricedecimals, CR.INVOICEAMOUNTDECIMALS amountdecimals,
  ui.primaryid
from residualvaluelostcustomer rvlc, weareremployment_link wel, uniqueitem ui, customer c, currency cr
where rvlc.weareremployment_link_id = wel.weareremployment_link_id
  and rvlc.uniqueitem_link_id = ui.uniqueitem_id
  and rvlc.customer_link_id = c.customer_id
  and c.currency_id = cr.currency_id
union all
select c.customer_id, rvlc.product_link_id product_id,
  wel.wearername, wel.wearernumber,
  rvlc.issuedate, rvlc.residualvaluepercentage, rvlc.price,
  cr.decimals pricedecimals, CR.INVOICEAMOUNTDECIMALS amountdecimals,
  ri.primaryid
from residualvaluelostcustomer rvlc, weareremployment_link wel, raggeditem ri, customer c, currency cr
where rvlc.weareremployment_link_id = wel.weareremployment_link_id
  and rvlc.uniqueitem_link_id = ri.raggeditem_id
  and rvlc.customer_link_id = c.customer_id
  and c.currency_id = cr.currency_id
/

  CREATE OR REPLACE VIEW "V_LOTNUMBERRECEIVED" ("BUSINESSUNIT", "PRODUCT_LINK_ID", "SIZEDEFINITION_LINK_ID", "LOTNUMBER", "QUANTITY") AS 
  select r.processbusinessunit_id Businessunit,
       r.product_link_id Product_link_id,
       r.sizedefinition_link_id Sizedefinition_link_id,
       r.lotnumber Lotnumber,
       sum(r.quantity) Quantity
  from receiveinstockhistory r
 where r.lotnumber is not null
 group by r.processbusinessunit_id,
          r.product_link_id,
          r.sizedefinition_link_id,
          r.lotnumber
 order by r.processbusinessunit_id,
          r.product_link_id,
          r.sizedefinition_link_id,
          r.lotnumber
/

  CREATE OR REPLACE VIEW "V_LOTNUMBERUSED" ("BUSINESSUNIT_ID", "PRODUCT_ID", "SIZEDEFINITION_ID", "LOTNUMBER", "QUANTITY") AS 
  select ui.businessunit_id businessunit_id, uorp.product_id product_id, uorp.sizedefinition_id sizedefinition_id
, uorp.lotnumber lotnumber, sum(uorp.qtynonunique) quantity
from uniqueorpackcontents uorp, uniqueitem ui, status s
where uorp.lotnumber is not null
and ui.uniqueitem_id = uorp.uniqueitem_id
and ui.status_id = s.status_id
and s.code <> 60
and s.code <> 70
group by ui.businessunit_id , uorp.product_id , uorp.sizedefinition_id , uorp.lotnumber
/

  CREATE OR REPLACE VIEW "V_MATAVAIALBILITY" ("BUSINESSUNITCODE", "BUSINEESUNITDESSC", "ACTIVITYCODE", "PRODUCTCODE", "PRODUCTDESC", "STOREACTIVESTOCKLOCATION", "SIZECODE", "PRODUCTGROUPCODE", "PRODUCTGROUPDESC", "NEEDED1", "NEEDED2", "EXPECTED_RETURNS1", "EXPECTED_RETURNS2", "ACTIVE_STOCK", "LANGUAGECODE", "REPORTPARAM_ID", "PRODUCTLISTPERDISTRIBPOINT_ID") AS 
  select bu.code businessunitcode, bu.description busineesunitdessc,
  ac.code activitycode,
  pr.code productcode,
  (select prd.description from product_desc prd where prd.product_id = pr.product_id
     and prd.language_id = languages.language_id) productdesc,
  pr.storeactivestocklocation,
  sz.code sizecode,
  pg.code productgroupcode,
  (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pg.productgroup_id
    and pgd.language_id = languages.language_id) productgroupdesc,
  GET_NEEDED(1, rp.reportparam_id, pldp.productlistperdistribpoint_id) needed1,
  GET_NEEDED(2, rp.reportparam_id, pldp.productlistperdistribpoint_id) needed2,
  GET_EXPECTED_RETURNS(1, rp.reportparam_id, pldp.productlistperdistribpoint_id, bu.businessunit_id) expected_returns1,
  GET_EXPECTED_RETURNS(2, rp.reportparam_id, pldp.productlistperdistribpoint_id, bu.businessunit_id) expected_returns2,
  GET_ACTIVE_STOCK(pr.product_id, sz.sizedefinition_id, pr.storeactivestocklocation) active_stock,
  languages.code languagecode, RP.REPORTPARAM_ID, pldp.productlistperdistribpoint_id
from businessunit bu, customeractivities ca,
  department de, distributionpoint dp,
  product pr, productgroup pg, sizedefinition sz, activity ac,
  productlistperdistribpoint pldp,
  languages, reportparam rp
where ca.processbusinessunit_id = bu.businessunit_id
  and ca.customer_id = de.customer_id
  and de.department_id = dp.department_id
  and ca.activity_id = pg.activity_id
  and pr.productgroup_id = pg.productgroup_id
  and pg.activity_id = ac.activity_id
  and pldp.product_id = pr.product_id
  and pldp.sizedefinition_id = sz.sizedefinition_id
  and pldp.distributionpoint_id = dp.distributionpoint_id
/

  CREATE OR REPLACE VIEW "V_MATCHING_PACKS" ("MULTIREADSCANBATCH_ID", "PACK_ID", "DISSIMILARITYFACTOR") AS 
  select z.multireadscanbatch_id, z.pack_id,
--       p.code,
--       sum(z.missingproducts) missingproducts,
--       sum(z.exceedingproducts) exceedingproducts,
--       sum(z.missingqty) missingqty,
--       sum(z.exceedingqty) exceedingqty,
       sum(z.missingproducts)*0.6 + sum(z.otherproducts)*1.2 + sum(z.missingqty) + sum(z.exceedingqty)*1.1 as dissimilarityfactor
  from
(
select y.multireadscanbatch_id,
       y.pack_id,
       y.product_id,
       y.sizedefinition_id,
       case when sum(case when type = 'Pack' then 1 else 0 end) > sum(case when type = 'Scan' then 1 else 0 end)
        then sum(case when type = 'Pack' then 1 else 0 end) - sum(case when type = 'Scan' then 1 else 0 end)
        else 0
       end missingproducts,
       case when sum(case when type = 'Scan' then 1 else 0 end) > sum(case when type = 'Pack' then 1 else 0 end)
        then sum(case when type = 'Scan' then 1 else 0 end) - sum(case when type = 'Pack' then 1 else 0 end)
        else 0
       end otherproducts,
       sum(y.pack_qty) pack_qty,
       sum(y.scan_qty) scan_qty,
       case when sum(y.pack_qty) > sum(y.scan_qty)
        then sum(y.pack_qty) - sum(y.scan_qty)
        else 0
       end missingqty,
       case when sum(y.scan_qty) > sum(y.pack_qty)
        then sum(y.scan_qty) - sum(y.pack_qty)
        else 0
       end exceedingqty
from
(
select mb.multireadscanbatch_id, 'Pack' type, pc.pack_id, pc.product_id, pc.sizedefinition_id, sum(trunc(pc.amount)) pack_qty, 0 scan_qty
  from packcontents pc,
       multireadscanbatch mb
where pc.pack_id in
      (select distinct pct.pack_id
        from packcontents pct, multireadscanbatchcontents m
       where m.multireadscanbatch_id = mb.multireadscanbatch_id
         and m.product_id = pct.product_id
         and m.sizedefinition_id = pct.sizedefinition_id
         and pct.uniquelycoded='Y')
  and pc.uniquelycoded='Y'
group by mb.multireadscanbatch_id, pc.pack_id, pc.product_id, pc.sizedefinition_id
union all
select mb.multireadscanbatch_id, 'Scan' type, x.pack_id, mb.product_id, mb.sizedefinition_id, 0 pack_qty, count(1) scan_qty
  from multireadscanbatchcontents mb,
       (select m.multireadscanbatch_id, pct.pack_id
          from packcontents pct, multireadscanbatchcontents m
         where m.product_id = pct.product_id
           and m.sizedefinition_id = pct.sizedefinition_id
           and pct.uniquelycoded='Y'
         group by m.multireadscanbatch_id, pct.pack_id) x
where x.multireadscanbatch_id = mb.multireadscanbatch_id
  and mb.product_id is not null
group by mb.multireadscanbatch_id, x.pack_id, mb.product_id, mb.sizedefinition_id) y
group by y.multireadscanbatch_id, y.pack_id, y.product_id, y.sizedefinition_id) z
   join product p on p.product_id = z.pack_id
group by z.multireadscanbatch_id, z.pack_id, p.code
order by sum(z.missingproducts)*1.1 + sum(z.otherproducts)*1.2 + sum(z.missingqty) + sum(z.exceedingqty)*1.1, p.code
/

  CREATE OR REPLACE VIEW "V_MATDELIVERYNOTE" ("NOTENUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "LEGALNAME", "CUSTOMERSTREET", "CUSTOMERZIP", "CUSTOMERCITY", "CUSTOMERSTATE", "CUSTCOUNTRY", "CUSTCOUNTRY_DESC", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "DELIVERYPOINTCODE", "DELIVERYPOINTDESCRIPTION", "SEQUENCENUMBER", "OCCUPANCY", "EMPLOYEENAME", "DELIVERYDATE", "ORIGINALDELIVERYDATE", "REMARK", "PROCESSBUDESCRIPTION", "PLANTSTREET", "PLANTZIPCODE", "PLANTCITY", "PLANTPHONENO", "PLANTFAXNO", "PLANTCOUNTRY_CODE", "PLANTCOUNTRY_DESC", "ROUTENUMBER", "ROUTEDESCRIPTION", "LOADINGDOCK", "STOPNUMBER", "SYSTEMUSER_ID", "TIMESTAMP", "CREATIONTIMESTAMP", "PACKINGNOTE_ID", "ENDDATEFORUSE", "ORIGIN", "DELIVERYLAYOUTCODE", "DAYDESCRIPTION", "WEEK", "LANGUAGECODE", "CUSTOMERLANGUAGECODE", "PRODUCTIONDATE", "SCANSONDELIVERYNOTE", "HASLOCKERANAGEMENT", "CHARGESERVICE", "CHARGERENT", "USELOCKEROBLIGATED", "FIXEDNUMBERBANK", "NUMBEROFGARMENTSINLOCKER", "NUMBEROFLOCKERS", "PLANT_DEP_CODE", "PLANT_DEP_DESC", "FREEOFCHARGEREASON_ID", "DELNOTEFORBULKPUTUPITEMS", "DEPOT_PHONENUMBER") AS 
  SELECT
PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME,
ADDRESS.street CUSTOMERSTREET, ADDRESS.zipcode CUSTOMERZIP, ADDRESS.city CUSTOMERCITY, ADDRESS.State CUSTOMERSTATE,
C1.CODE CUSTCOUNTRY, C1.DESCRIPTION CUSTCOUNTRY_DESC,
DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
PACKINGNOTE.SEQUENCENUMBER,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, PACKINGNOTE.REMARK, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANT.phoneno PLANTPHONENO, PLANT.faxno PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
  ROUTE.ROUTENUMBER, ROUTE.description ROUTEDESCRIPTION, ROUTE.LOADINGDOCK, PACKINGNOTE.STOPNUMBER,
packingnote.systemuser_id, PACKINGNOTE.TIMESTAMP, PACKINGNOTE.CREATIONTIMESTAMP,
PACKINGNOTE.packingnote_id, packingnote.enddateforuse, packingnote.origin,
formlayout.code deliverylayoutcode,
 (SELECT DESCRIPTION FROM DAY_DESC
         WHERE DAY_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID
         AND DAY_DESC.DAY_ID = PACKINGNOTE.DAYNUMBER) DAYDESCRIPTION
, cast(PACKINGNOTE.Week as varchar2(2)) WEEK
, languages.code languagecode, customerlanguage.code customerlanguagecode,
    PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE, CUSTOMER.SCANSONDELIVERYNOTE,
CASE WHEN clm.customer_id IS  null THEN  'N' ELSE  'Y' END hasLockeranagement,
    clm.chargeservice, clm.chargerent, clm.uselockerobligated, clm.fixednumberbank,
    packingnote.numberofgarmentsinlocker, packingnote.numberoflockers,
plantdepartment.code plant_dep_code, plantdepartment.description plant_dep_desc,
packingnote.freeofchargereason_id, CUSTOMER.DELNOTEFORBULKPUTUPITEMS
, nvl((select dpt.phoneno from depot dpt where dpt.depot_id = route.depot_id), plant.phoneno) depot_phonenumber
FROM  CUSTOMER
        left outer join formlayout on ( customer.deliverynotelayout_id = formlayout.formlayout_id)
        left outer join customerlockermanagement clm on (customer.customer_id = clm.customer_id),
        ADDRESS, DEPARTMENT, DISTRIBUTIONPOINT, PLANT, ADDRESS PLANTADDRESS,
        BUSINESSUNIT PROCESSBU, DELIVERYPOINT,
        STATUS, COUNTRY C1, COUNTRY C2, plantdepartment, status st,
        PACKINGNOTE
          LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
        left outer join route on (packingnote.route_id = route.route_id),LANGUAGES customerlanguage, languages
  WHERE PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
	AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
	AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND DELIVERYPOINT.DELIVERYADDRESS_ID = ADDRESS.address_id
	AND PACKINGNOTE.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
	AND PACKINGNOTE.STATUS_ID = STATUS.STATUS_ID
	AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.address_id = PLANTADDRESS.ADDRESS_ID
  AND CUSTOMER.COUNTRY_ID = C1.COUNTRY_ID
  AND PLANT.COUNTRY_ID = C2.COUNTRY_ID
  and customer.language_id = customerlanguage.language_id
  and packingnote.plantdepartment_id = plantdepartment.plantdepartment_id
  and st.status_id = PACKINGNOTE.Status_Id
  and st.statustype = 'PN' and st.code <> '40' -- status NOT Cancelled
  AND EXISTS (SELECT * FROM PACKINGNOTELINE L  --at least one BULK packingnote line
      WHERE L.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID AND (L.PUTUPTYPE = 2 or L.PUTUPTYPE = 4) and l.deliveredamount <> 0)
/

  CREATE OR REPLACE VIEW "V_MATDELIVERYNOTELINE" ("PACKINGNOTE_ID", "PRODUCT_CODE", "PRODUCT_DESC", "PRODUCTGROUP_DESC", "CUSTOM_CODE", "CUSTOM_DESC", "SIZE_CODE", "SIZE_DESC", "FIN_METHOD_DESC", "PACKINGSEQUENCE", "STANDARDAMOUNT", "VARIATIONAMOUNT", "DELIVEREDAMOUNT", "TOBEDELIVEREDAMOUNT", "REMARKFORPACKINGINSTRUCTIONS", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGE_CODE", "TYPEOFMERCHANDISE", "NOCHARGEFIRSTISSUE", "NOCHARGEACTIVESEASON", "DELIVEREDCOGQTY", "PUTUPTYPE", "BULKPUTUP", "PACKINGNOTELINE_ID") AS 
  SELECT PACKINGNOTELINE.PACKINGNOTE_ID packingnote_ID,
  PRODUCT.CODE product_code,
  (SELECT DESCRIPTION FROM PRODUCT_DESC P WHERE P.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  product_desc,
  (SELECT DESCRIPTION FROM productgroup_desc A WHERE A.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productgroup_desc,
  packingnoteline.customcode custom_code, packingnoteline.customdescription custom_desc,
  SIZEDEFINITION.CODE SIZE_CODE,
  (SELECT DESCRIPTION FROM SIZEDEFINITION_DESC S WHERE S.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  SIZE_desc,
  (SELECT DESCRIPTION FROM FINISHINGMETHOD_DESC F WHERE F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID AND F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  FIN_METHOD_desc,
  PACKINGNOTELINE.PACKINGSEQUENCE, PACKINGNOTELINE.STANDARDAMOUNT, PACKINGNOTELINE.VARIATIONAMOUNT,
  PACKINGNOTELINE.DELIVEREDAMOUNT, PACKINGNOTELINE.TOBEDELIVEREDAMOUNT,
  PACKINGNOTELINE.remarkforpackinginstructions,
  PACKINGNOTELINE.SYSTEMUSER_ID, PACKINGNOTELINE.TIMESTAMP, LANGUAGES.CODE LANGUAGE_CODE,
  PRODUCT.TYPEOFMERCHANDISE,
  PACKINGNOTELINE.Nochargefirstissue, PACKINGNOTELINE.Nochargeactiveseason, PACKINGNOTELINE.Deliveredcogqty,
  PACKINGNOTELINE.PUTUPTYPE
, case when PACKINGNOTELINE.PUTUPTYPE = 2 then 'Y' else 'N' end bulkputup,
  PACKINGNOTELINE.PACKINGNOTELINE_ID
  FROM PACKINGNOTELINE, PRODUCT, SIZEDEFINITION, LANGUAGES
  WHERE PACKINGNOTELINE.PRODUCT_ID = PRODUCT.PRODUCT_ID
      AND PACKINGNOTELINE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
/

  CREATE OR REPLACE VIEW "V_MATHIVE" ("BUSINESSUNIT_ID", "BU_CODE", "BU_DESC", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "SECTION", "LOCATION", "UNIQUEID", "PRIORITY", "ACTIVE", "PRIMARYID", "IDCODESEQUENCENUMBER", "LASTINSCANDATE", "LASTOUTSCANDATE", "PROD_CODE", "PROD_DESC", "FIXEDINVENTORY", "CIRCINVENTORY", "SCANDATE", "DELIVEREDQTY") AS 
  select --+index(ui XIE4UNIQUEITEM)
       /*version 1.1*/
       bu.businessunit_id, bu.code bu_code, bu.description bu_desc,
       cu.customer_id, cu.customernumber, cu.name customername,
       asl.section, asl.location, asl.uniqueid, asl.priority, asl.active,
       ui.primaryid, ui.idcodesequencenumber, ui.lastinscandate, ui.lastoutscandate,
       (select pr.code
          from product pr
         where pr.product_id = ui.product_id) prod_code,
       (select prd.description
          from product_desc prd
         where prd.product_id = ui.product_id
           and prd.language_id = cu.language_id) prod_desc,
       (select sum(sdl.fixedrentquantity)
          from standarddeliveryline sdl
               join productlistpercustomer plpc on sdl.productlistpercustomer_id = plpc.productlistpercustomer_id
         where plpc.customer_id = ui.relatedcustomer_id
           and plpc.product_id = ui.product_id
           and plpc.sizedefinition_id = ui.sizedefinition_id
           and plpc.finishingmethod_id = ui.finishingmethod_id
           and sdl.dateactive <= sysdate and sdl.dateinactive >= sysdate) fixedinventory,
       (select sum(rqa.quantity)
          from rentalqtyadjustment rqa
               join productlistperdistribpoint plpd
                    join distributionpoint dp
                         join department dep on dp.department_id = dep.department_id
                    on plpd.distributionpoint_id = dp.distributionpoint_id
               on rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
         where dep.customer_id = ui.relatedcustomer_id
           and plpd.product_id = ui.product_id
           and plpd.sizedefinition_id = ui.sizedefinition_id
           and plpd.finishingmethod_id = ui.finishingmethod_id) circinventory,
       (select max(trunc(sc.scantimestamp))
          from scan sc
         where sc.uniqueitem_link_id = ui.uniqueitem_id
           and sc.customer_link_id = ui.relatedcustomer_id
           and sc.transactiontype_id = 7--Storage Scan
       ) scandate,
       (select sum(sda.amount)
          from standarddeliveryamount sda
               join standarddeliveryline sdl
                    join productlistpercustomer plpc on sdl.productlistpercustomer_id = plpc.productlistpercustomer_id
               on sda.standarddeliveryline_id = sdl.standarddeliveryline_id
         where plpc.customer_id = ui.relatedcustomer_id
           and plpc.product_id = ui.product_id
           and plpc.sizedefinition_id = ui.sizedefinition_id
           and plpc.finishingmethod_id = ui.finishingmethod_id
           and sdl.dateactive <= sysdate and sdl.dateinactive >= sysdate) deliveredqty
  from activestocklocation asl
       left join uniqueitem ui
            join customer cu on ui.relatedcustomer_id = cu.customer_id
       on asl.activestocklocation_id = ui.activestocklocation_id and asl.businessunit_id = ui.businessunit_id
       join businessunit bu on asl.businessunit_id = bu.businessunit_id
/

  CREATE OR REPLACE VIEW "V_MATREQUIREMENTS" ("SHOWLEVEL", "BUSINESSUNITCODE", "BUSINEESUNITDESSC", "ACTIVITYCODE", "PRODUCTGROUPCODE", "PRODUCTCODE", "SIZECODE", "PRODUCTDESC", "PRODUCTGROUPDESC", "LANGUAGECODE", "REPORTPARAM_ID", "PRODUCTLISTPERDISTRIBPOINT_ID", "DATE_VALUE1", "ROUTENUMBER", "ROUTE_DESC", "WEEKNR", "QTYWEEK1", "QTYWEEK2", "QTYWEEK3", "QTYWEEK4", "QTYWEEK5", "QTYWEEK6", "QTYWEEK7", "QTYWEEK8", "QTYWEEK9", "QTYWEEK10", "QTYWEEK11", "QTYWEEK12") AS 
  select /*version 3.0*/
       1 showlevel, bu.code businessunitcode, bu.description busineesunitdessc,
       ac.code activitycode, pg.code productgroupcode, pr.code productcode, sz.code sizecode,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id and prd.language_id = l.language_id) productdesc,
       (select pgd.description
          from productgroup_desc pgd
         where pgd.productgroup_id = pg.productgroup_id
           and pgd.language_id = l.language_id) productgroupdesc,
       l.code languagecode, rp.reportparam_id, pldp.productlistperdistribpoint_id, rp.date_value1,
       0 routenumber, ' ' route_desc, getisoweek(rp.date_value1) weeknr,
       get_reqmats(rp.date_value1, pldp.productlistperdistribpoint_id) qtyweek1,
       case when rp.number_value1 >= 2
       then get_reqmats(rp.date_value1+7, pldp.productlistperdistribpoint_id)
         else 0 end qtyweek2,
       case when rp.number_value1 >= 3
         then get_reqmats(rp.date_value1+14, pldp.productlistperdistribpoint_id)
         else 0 end qtyweek3,
       case when rp.number_value1 >= 4
         then get_reqmats(rp.date_value1+21, pldp.productlistperdistribpoint_id)
         else 0 end qtyweek4,
       case when rp.number_value1 >= 5
         then get_reqmats(rp.date_value1+28, pldp.productlistperdistribpoint_id)
         else 0 end qtyweek5,
       case when rp.number_value1 >= 6
         then get_reqmats(rp.date_value1+35, pldp.productlistperdistribpoint_id)
         else 0 end qtyweek6,
       case when rp.number_value1 >= 7
         then get_reqmats(rp.date_value1+42, pldp.productlistperdistribpoint_id)
         else 0 end qtyweek7,
       case when rp.number_value1 >= 8
         then get_reqmats(rp.date_value1+49, pldp.productlistperdistribpoint_id)
         else 0 end qtyweek8,
       case when rp.number_value1 >= 9
         then get_reqmats(rp.date_value1+56, pldp.productlistperdistribpoint_id)
         else 0 end qtyweek9,
       case when rp.number_value1 >= 10
         then get_reqmats(rp.date_value1+63, pldp.productlistperdistribpoint_id)
         else 0 end qtyweek10,
       case when rp.number_value1 >= 11
         then get_reqmats(rp.date_value1+70, pldp.productlistperdistribpoint_id)
         else 0 end qtyweek11,
       case when rp.number_value1 >= 12
         then get_reqmats(rp.date_value1+77, pldp.productlistperdistribpoint_id)
         else 0 end qtyweek12
  from productlistperdistribpoint pldp
       join product pr
            join productgroup pg
                 join activity ac on pg.activity_id = ac.activity_id
            on pr.productgroup_id = pg.productgroup_id
       on pldp.product_id = pr.product_id
       join sizedefinition sz on pldp.sizedefinition_id = sz.sizedefinition_id
       join distributionpoint dp
            join department de on de.department_id = dp.department_id
       on pldp.distributionpoint_id = dp.distributionpoint_id,
       businessunit bu, reportparam rp, languages l
 where bu.code between rp.string_value and rp.string_value1
   and exists (select ca.customer_id from customeractivities ca
                where ca.activity_id = pg.activity_id and ca.customer_id = de.customer_id
                  and ca.processbusinessunit_id = bu.businessunit_id)
 union all--showlevel per routes
select 2 showlevel, bu.code businessunitcode, bu.description busineesunitdessc,
       ac.code activitycode, pg.code productgroupcode, pr.code productcode, sz.code sizecode,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id and prd.language_id = l.language_id) productdesc,
       (select pgd.description
          from productgroup_desc pgd
         where pgd.productgroup_id = pg.productgroup_id
           and pgd.language_id = l.language_id) productgroupdesc,
       l.code languagecode, rp.reportparam_id, pldp.productlistperdistribpoint_id, rp.date_value1,
       ro.routenumber routenumber, ro.description route_desc,
       getisoweek(rp.date_value1) weeknr,
       get_reqmats(rp.date_value1, pldp.productlistperdistribpoint_id) qtyweek1,
       case when rp.number_value1 >= 2
       then get_reqmats(rp.date_value1+7, pldp.productlistperdistribpoint_id)
         else 0 end qtyweek2,
       case when rp.number_value1 >= 3
         then get_reqmats(rp.date_value1+14, pldp.productlistperdistribpoint_id)
         else 0 end qtyweek3,
       case when rp.number_value1 >= 4
         then get_reqmats(rp.date_value1+21, pldp.productlistperdistribpoint_id)
         else 0 end qtyweek4,
       case when rp.number_value1 >= 5
         then get_reqmats(rp.date_value1+28, pldp.productlistperdistribpoint_id)
         else 0 end qtyweek5,
       case when rp.number_value1 >= 6
         then get_reqmats(rp.date_value1+35, pldp.productlistperdistribpoint_id)
         else 0 end qtyweek6,
       case when rp.number_value1 >= 7
         then get_reqmats(rp.date_value1+42, pldp.productlistperdistribpoint_id)
         else 0 end qtyweek7,
       case when rp.number_value1 >= 8
         then get_reqmats(rp.date_value1+49, pldp.productlistperdistribpoint_id)
         else 0 end qtyweek8,
       case when rp.number_value1 >= 9
         then get_reqmats(rp.date_value1+56, pldp.productlistperdistribpoint_id)
         else 0 end qtyweek9,
       case when rp.number_value1 >= 10
         then get_reqmats(rp.date_value1+63, pldp.productlistperdistribpoint_id)
         else 0 end qtyweek10,
       case when rp.number_value1 >= 11
         then get_reqmats(rp.date_value1+70, pldp.productlistperdistribpoint_id)
         else 0 end qtyweek11,
       case when rp.number_value1 >= 12
         then get_reqmats(rp.date_value1+77, pldp.productlistperdistribpoint_id)
         else 0 end qtyweek12
  from productlistperdistribpoint pldp
       join product pr
            join productgroup pg
                 join activity ac on pg.activity_id = ac.activity_id
            on pr.productgroup_id = pg.productgroup_id
       on pldp.product_id = pr.product_id
       join sizedefinition sz on pldp.sizedefinition_id = sz.sizedefinition_id
       join distributionpoint dp
            join department de
                 join routestop rs
                      join route ro on rs.route_id = ro.route_id
                 on de.customer_id = rs.customer_id
            on de.department_id = dp.department_id
       on pldp.distributionpoint_id = dp.distributionpoint_id,
       businessunit bu, reportparam rp, languages l
 where bu.code between rp.string_value and rp.string_value1
   and exists (select ca.customer_id from customeractivities ca
                where ca.activity_id = pg.activity_id and ca.customer_id = de.customer_id
                  and ca.processbusinessunit_id = bu.businessunit_id)
/

  CREATE OR REPLACE VIEW "V_MATSCANHISTORY" ("PLANTCODE", "PLANTNAME", "BUCODE", "BUDESC", "BUSINESSUNIT_ID", "CUSTOMERNUMBER", "DISTRIBUTIONPOINTNUMBER", "DEPARTMENTNUMBER", "PRODUCTCODE", "TYPEOFMERCHANDISE", "BULKPACKINGACTIVESTOCKTYPE", "SIZECODE", "IDCODE", "SCANTIMESTAMP", "TRANSACTIONTYPE_ID", "LASTSCANDATE", "ACTIVESTOCKLOCATION_ID", "REASONCODE", "USERGROUP_ID", "SYSTEMUSER_ID", "LANGUAGECODE", "STAYLOCATION", "STAYTYPE", "STAYNR", "PRODUCTDESCRIPTION", "REASONCODEDESCRIPTION", "QUALITYGRADECODE", "PRODUCTSEQUENCENUMBER") AS 
  select p.code plantcode, p.name plantname,  bu.code bucode, bu.description budesc, bu.businessunit_id
     , culk.customernumber, dp.distributionpointnumber, d.departmentnumber
     , pr.code productcode, pr.typeofmerchandise,  pr.bulkpackingactivestocktype, sd.code sizecode, ui.primaryid idcode, ui.lastscandate scantimestamp, tt.transactiontype_id
     , ui.lastscandate, ui.activestocklocation_id, rc.code reasoncode, bug.usergroup_id, su.systemuser_id, lan.code languagecode
     , st.location  staylocation, st.staytype, st.staynr
     , (select pd.description from product_desc pd where pd.product_id = pr.product_id and pd.language_id = lan.language_id) productdescription
     , (select rcd.description from reasoncode_desc rcd where rcd.reasoncode_id = rc.reasoncode_id and rcd.language_id = lan.language_id) reasoncodedescription
     , (select gr.code from qualitygrade gr where gr.qualitygrade_id = scan.qualitygrade_id) qualitygradecode
     , (select ps.sequencenumber from productsize ps where ps.product_id = pr.product_id and ps.sizedefinition_id = sd.sizedefinition_id) productsequencenumber
from scan
     join uniqueitem ui on ui.uniqueitem_id = scan.uniqueitem_link_id
          left outer join customer_link culk on culk.customer_id = scan.customer_link_id
          left outer join (distributionpoint dp join department d on d.department_id = dp.department_id)
          on dp.distributionpoint_id = scan.distributionpoint_link_id
     join reasoncode rc on (rc.reasoncode_id = scan.reasoncode_id and rc.linenreason = 'Y')
     join businessunitsperusergroup bug on bug.businessunit_id = scan.businessunit_id
     join systemuser su on su.usergroup_id = bug.usergroup_id
     join businessunit bu on bu.businessunit_id = bug.businessunit_id
     join plant p on p.plant_id = bu.plant_id
     join transactiontype tt on  tt.transactiontype_id = scan.transactiontype_id
     join product pr on pr.product_id = scan.product_link_id
     join sizedefinition sd on sd.sizedefinition_id = scan.sizedefinition_link_id
     join stay st on st.stay_id = ui.stay_id and st.staytype = 1,
     languages lan
where pr.typeofmerchandise = 1
and pr.bulkpackingactivestocktype <> 0
/

  CREATE OR REPLACE VIEW "V_MATSCANNINGSTATUS" ("BUCODE", "ROUTECONTROL_ID", "DELIVERYDATE", "ROUTENUMBER", "DEPOTDESCRIPTION", "PRODUCTCODE", "PRODUCTDESC", "SIZEDEF", "QUANTITYREQUESTED", "QUANTITYDELIVERED", "LANGUAGECODE") AS 
  select (select bu.code from businessunit bu where bu.businessunit_id = asd.businessunit_id) bucode,
rc.routecontrol_id,
rc.drivingdate deliverydate,
r.routenumber,
(select d.description from depot d where d.depot_id = r.depot_id) depotdescription,
(select p.code from product p where p.product_id = asd.product_link_id) productcode,
(select pd.description from product_desc pd where pd.product_id = asd.product_link_id and pd.language_id = l.language_id) productdesc,
(select sd.code from sizedefinition sd where sd.sizedefinition_id = asd.sizedefinition_link_id) sizedef,
asd.quantityrequested,
asd.quantitydelivered,
l.code languagecode
from activestockdelivery asd
inner join routecontrol rc
      inner join route r on r.route_id = rc.route_id
on rc.routecontrol_id = asd.routecontrol_id,
languages l
/

  CREATE OR REPLACE VIEW "V_MATSCANNINGSTATUSLABELS" ("BUCODE", "CUSTOMERNUMBER", "CUSTOMERNAME", "ROUTECONTROL_ID", "DELIVERYDATE", "ROUTENUMBER", "DEPOTDESCRIPTION", "PRODUCTCODE", "PRODUCTDESC", "SIZEDEF", "QUANTITYREQUESTED", "QUANTITYDELIVERED", "QUANTITYSUBSTITUTED", "LANGUAGECODE") AS 
  select (select bu.code from businessunit bu where bu.businessunit_id = asd.businessunit_id) bucode,
(select c.customernumber from customer c where c.customer_id = asd.relatedcustomer_id) customernumber,
(select c.name from customer c where c.customer_id = asd.relatedcustomer_id) customername,
rc.routecontrol_id,
rc.drivingdate deliverydate,
r.routenumber,
(select d.description from depot d where d.depot_id = r.depot_id) depotdescription,
(select p.code from product p where p.product_id = asd.product_link_id) productcode,
(select pd.description from product_desc pd where pd.product_id = asd.product_link_id and pd.language_id = l.language_id) productdesc,
(select sd.code from sizedefinition sd where sd.sizedefinition_id = asd.sizedefinition_link_id) sizedef,
asd.quantityrequested,
asd.quantitydelivered,
(select sum(asd1.quantitysubstituted)
 from activestockdelivery asd1 where asd1.routecontrol_id = asd.routecontrol_id) quantitysubstituted,
l.code languagecode
from activestockdelivery asd
inner join routecontrol rc
      inner join route r on r.route_id = rc.route_id
on rc.routecontrol_id = asd.routecontrol_id
, languages l
/

  CREATE OR REPLACE VIEW "V_MATSHIPMENTLIST" ("PRODUCTCODE", "SIZECODE", "LANGUAGECODE", "LANGUAGE_ID", "COMPLETIONSTATUS", "SHIPMENTLISTNUMBER", "SHIPMENTLISTMAT_ID", "RECEIVETIMESTAMP", "PRIMARYID", "SHIPMENTSTATUS", "SEQUENCENUMBER", "THEORETICALWEIGHT", "PRODUCTDESCRIPTION", "SIZEDESCRIPTION", "CONTAINERNUMBER", "CONTAINERCODE", "CONTAINERTYPEDESCRIPTION", "SHIPFROMCODE", "SHIPFROMDESCRIPTION", "SHIPTOCODE", "SHIPTODESCRIPTION", "SHIPTOSTREET", "SHIPTOCITYZIPCODE") AS 
  select p.code productcode, sd.code sizecode, lan.code languagecode, lan.language_id
     , slml.completionstatus, slm.shipmentlistnumber, slm.shipmentlistmat_id, slml.receivetimestamp, ui.primaryid
     , (select st.code from status st where st.status_id = slm.status_id and st.statustype = 'SL') shipmentstatus
     , nvl(ps.sequencenumber,0) sequencenumber, nvl(ps.theoreticalweight, p.theoreticalweight) theoreticalweight
     , (select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = lan.language_id) productdescription
     , (select sdc.description from sizedefinition_desc sdc where sdc.sizedefinition_id = sd.sizedefinition_id and sdc.language_id = lan.language_id) sizedescription
     , ctn.primaryid containernumber
     , (select ctp.code from containertype ctp where ctn.containertype_id = ctp.containertype_id ) containercode
     , (select ctpd.description from containertype_desc ctpd where ctn.containertype_id = ctpd.containertype_id and ctpd.language_id = lan.language_id) containertypedescription
     , (case when slm.shipfromstockroom_id is null then (select bu.code from businessunit bu where bu.businessunit_id = slm.shipfrombusinessunit_id)
                  else (select stk.code from stockroom stk where stk.stockroom_id = slm.shipfromstockroom_id)
       end) shipfromcode
     , (case when slm.shipfromstockroom_id is null then (select bu.description from businessunit bu where bu.businessunit_id = slm.shipfrombusinessunit_id)
                  else (select stk.name from stockroom stk where stk.stockroom_id = slm.shipfromstockroom_id)
       end) shipfromdescription
     , (case when slm.shiptostockroom_id is null then (select bu.code from businessunit bu where bu.businessunit_id = slm.shiptobusinessunit_id)
                  else (select stk.code from stockroom stk where stk.stockroom_id = slm.shiptostockroom_id)
       end) shiptocode
     , (case when slm.shiptostockroom_id is null then (select bu.description from businessunit bu where bu.businessunit_id = slm.shiptobusinessunit_id)
                  else (select stk.name from stockroom stk where stk.stockroom_id = slm.shiptostockroom_id)
       end) shiptodescription
     , (case when slm.shiptostockroom_id is null then (select ads.street from address ads join plant plt on plt.address_id = ads.address_id
                                                                                         join businessunit bu on bu.plant_id = plt.plant_id and bu.businessunit_id = slm.shipfrombusinessunit_id)
                  else (select ads.street from address ads join stockroom stk on stk.deliveryaddress_id = ads.address_id and stk.stockroom_id = slm.shiptostockroom_id)
       end) shiptostreet
     , (case when slm.shiptostockroom_id is null then (select ads.city || ' ' || ads.zipcode from address ads join plant plt on plt.address_id = ads.address_id
                                                                                            join businessunit bu on bu.plant_id = plt.plant_id and bu.businessunit_id = slm.shipfrombusinessunit_id)
                  else (select ads.city || ' ' || ads.zipcode from address ads join stockroom stk on stk.deliveryaddress_id = ads.address_id and stk.stockroom_id = slm.shiptostockroom_id)
       end) shiptocityzipcode
from shipmentlistmat slm join shipmentlistmatline slml on slml.shipmentlistmat_id = slm.shipmentlistmat_id
                         join container ctn on ctn.container_id = slml.container_id
                         left outer join shipmentlistmatlinedetail slmld on slmld.shipmentlistmatline_id = slml.shipmentlistmatline_id
                         left outer join uniqueitem ui on ui.uniqueitem_id = slmld.uniqueitem_link_id
                         left outer join product p on p.product_id = ui.product_id
                         left outer join sizedefinition sd on sd.sizedefinition_id = ui.sizedefinition_id
                         left outer join productsize ps on (ps.product_id = p.product_id and ps.sizedefinition_id = sd.sizedefinition_id), languages lan
/

  CREATE OR REPLACE VIEW "V_MATSHORTAGES" ("CUSTOMERNUMBER", "CUSTOMERNAME", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "SIZEDESC", "QTY_NEEDED", "QTY_AVAILABLE", "ROUTENUMBER", "ROUTEDESC", "STOPNUMBER", "DRIVINGDATE", "DRIVINGDAY", "PUTUPREPORTROUTESTOP", "ACTIVESTOCKCOMPLETED", "BUSINESSUNIT_ID", "LANGUAGECODE", "REPORTPARAM_ID") AS 
  select cu.customernumber, cu.name customername,
  pr.code productcode,
  (select prd.description from product_desc prd where prd.product_id = pr.product_id
     and prd.language_id = l.language_id) productdesc,
  sz.code sizecode,
  (select szd.description from sizedefinition_desc szd where szd.sizedefinition_id = sz.sizedefinition_id
     and szd.language_id = l.language_id) sizedesc,
  (pnl.standardamount + pnl.variationamount) qty_needed,
  (select count(*)
   from uniqueitem ui,activestocklocation asl
   where ui.product_id = pnl.product_id
     and ui.sizedefinition_id = pnl.sizedefinition_id
     and ui.relatedcustomer_id = sp.customer_link_id
     and ui.activestocklocation_id = asl.activestocklocation_id
     and ui.businessunit_id = asl.businessunit_id
     and ui.businessunit_id = rp.number_value1
     and not exists
       (select uif.flag_id
        from uniqueitemflag uif
        where ui.uniqueitem_id = uif.uniqueitem_id
          and uif.flag_id = rp.number_value2 --Quit mat - event from automaticflag
          and uif.startdate <= trunc(sysdate))) qty_available,
  ru.routenumber, ru.description routedesc, sp.stopnumber, rc.drivingdate,
  (select dd.description from day_desc dd where dd.day_id = ru.drivingday_id
     and dd.language_id = l.language_id) drivingday,
  ru.putupreportroutestop, rc.activestockcompleted,
  rp.number_value1 businessunit_id,
  l.code languagecode, rp.reportparam_id
from packingnote pn, status st, routecontrol rc, packingnoteline pnl, product pr, sizedefinition sz,
  stop sp, route ru, customer cu,
  languages l, reportparam rp
where rp.number_value = rc.routecontrol_id
  and pn.status_id = st.status_id
  and st.statustype = 'PN'
  and st.code in ('10', '20')
  and pn.routecontrol_id = rc.routecontrol_id
  and pn.packingnote_id = pnl.packingnote_id
  and pnl.product_id = pr.product_id
  and pr.storeactivestocklocation = 'Y'
  and pnl.sizedefinition_id = sz.sizedefinition_id
  and pn.stop_id = sp.stop_id
  and rc.route_id = ru.route_id
  and sp.customer_link_id = cu.customer_id
/

  CREATE OR REPLACE VIEW "V_MATSSCAN" ("REPORTPARAM_ID", "ROUTENUMBER", "ROUTEDESC", "DRIVINGDATE", "DAYOFWEEK", "ACTIVESTOCKCOMPLETED", "STOPNUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "PUTUPREPORTROUTESTOP", "DETAILINFO", "UNIQUEID", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "SIZEDESC", "QUANTITYREQUESTED", "QUANTITYDELIVERED", "LANGUAGECODE") AS 
  select distinct rp.reportparam_id, ru.routenumber, ru.description routedesc, rc.drivingdate,
  (select dd.description from day_desc dd where dd.day_id = day.day_id and lg.language_id = dd.language_id) dayofweek,
  rc.activestockcompleted, asd.stopnumber, cul.customernumber, cul.name customername,
  ru.putupreportroutestop, asdd.detailinfo, asdd.uniqueid, prl.code productcode,
  (select prld.description from product_link_desc prld where prl.product_link_id = prld.product_link_id and
     prld.language_id = lg.language_id) productdesc,
  szl.code sizecode,
  (select szld.description from sizedefinition_link_desc szld
     where szl.sizedefinition_link_id = szld.sizedefinition_link_id
     and szld.language_id = lg.language_id) sizedesc,
  asd.quantityrequested, asd.quantitydelivered,
  lg.code languagecode
from activestockdelivery asd
    left outer join customer_link cul on cul.customer_link_id = asd.customer_link_id,
  product_link prl, sizedefinition_link szl,
  activestockdeliverydetail asdd,
  routecontrol rc, route ru, day,
  languages lg, reportparam rp
where asd.activestockdelivery_id = asdD.activestockdelivery_id
  and asd.routecontrol_id = rc.routecontrol_id
  and rc.route_id = ru.route_id
  and rc.routecontrol_id = rp.number_value
  and ru.drivingday_id = day.day_id
  and asd.product_link_id = prl.product_link_id
  and asd.sizedefinition_link_id = szl.sizedefinition_link_id
  and asd.deliverfrom in (1, 3)
  and asdd.detailinfo in (1, 2, 5)
/

  CREATE OR REPLACE VIEW "V_MATSTICKER" ("UNIQUEITEM_ID", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "CUSTOMERNUMBER", "CUSTOMERNAME", "STAYNR", "STAYTYPE", "LANGUAGECODE", "COMPANYNAME") AS 
  select ui.uniqueitem_id,
pr.code productcode,
(select pd.description from product_desc pd where pd.product_id = pr.product_id and pd.language_id = l.language_id) productdesc,
sd.code sizecode,
c.customernumber,
c.name customername,
st.staynr,
st.staytype,
l.code languagecode,
(select pc.name from plantcompany pc where pc.plant_id = bu.plant_id and pc.code = 'REMIT TO') companyname
from uniqueitem ui left outer join customer c
on ui.relatedcustomer_id = c.customer_id,
product pr,
sizedefinition sd,
stay st,
languages l,
businessunit bu
where ui.product_id = pr.product_id
and ui.sizedefinition_id = sd.sizedefinition_id
and ui.stay_id = st.stay_id
and ui.businessunit_id = bu.businessunit_id
/

  CREATE OR REPLACE VIEW "V_MENUACCESSRIGHTS" ("GROUPNAME", "GROUPDESC", "PLANTCODE", "MENUDESC", "MENUGROUPDESC", "MENUITEMDESC", "DIALOGDESC", "READONLY", "DEFAULTMENU", "MS1", "MS2", "MS3", "MS4", "MS5") AS 
  select /*view view v_menuaccessrights  version 0.1*/
 ug.groupname, ug.description groupdesc, pt.code plantcode,
 (select description
   from   menu_desc mmd
   where  mmd.menu_id = mm.menu_id
   and    mmd.language_id = pt.language_id) menudesc,
 (select description
   from   menugroup_desc mgd
   where  mgd.menugroup_id = mg.menugroup_id
   and    mgd.language_id = pt.language_id) menugroupdesc,
 coalesce((select description
           from   menuitem_desc mid
           where  mid.menuitem_id = mi.menuitem_id
           and    mid.language_id = pt.language_id), d.code) menuitemdesc,
 coalesce(case substr(l.code, 1, 2)
             when 'DE' then
              (select dd.description
               from   dialogs_desc dd
               join   license_languages lan
               on     lan.license_language_id = dd.license_language_id
               where  lan.code = 'DE_DE'
               and    dd.dialog_id = d.dialog_id)
             when 'NL' then
              (select dd.description
               from   dialogs_desc dd
               join   license_languages lan
               on     lan.license_language_id = dd.license_language_id
               where  lan.code = 'NL_NL'
               and    dd.dialog_id = d.dialog_id)
             else
              (select dd.description
               from   dialogs_desc dd
               join   license_languages lan
               on     lan.license_language_id = dd.license_language_id
               where  lan.code = 'EN_US'
               and    dd.dialog_id = d.dialog_id)
           end, d.code) dialogdesc,
 coalesce((select a.readonly
           from   accessrightsperusergroup a
           where  a.menuitem_id = mi.menuitem_id
           and    a.usergroup_id = mpu.usergroup_id), 'N') readonly, mpu.defaultmenu,
 mm.sequence ms1, mpu.menu_id ms2, mg.sequence ms3, mg.menugroup_id ms4, mi.sequence ms5
from   menusperusergroup mpu
join   usergroup ug
on     ug.usergroup_id = mpu.usergroup_id
join   menu mm
on     mm.menu_id = mpu.menu_id
join   plant pt
on     pt.plant_id = mm.plant_id
join   languages l
on     l.language_id = pt.language_id
join   menugroup mg
on     mg.menu_id = mm.menu_id
join   menuitem mi
on     mi.menugroup_id = mg.menugroup_id
join   dialogs d
on     d.dialog_id = mi.dialog_id
where  not exists (select mug.menugroup_id
        from   menugroupsperusergroup mug
        where  mug.usergroup_id = mpu.usergroup_id
        and    mug.menugroup_id = mg.menugroup_id)
and    not exists (select aug.menuitem_id
        from   accessrightsperusergroup aug
        where  aug.usergroup_id = mpu.usergroup_id
        and    aug.menuitem_id = mi.menuitem_id
        and    aug.visible = 'N')
/

  CREATE OR REPLACE VIEW "V_MERCHANDISEREQUIREMENTSOR" ("REPORTPARAM_ID", "BUSINESSUNIT_ID", "PROCBUID", "BUCODE", "DESCRIPTION", "DELIVERYDATE", "PRODUCTIONDATE", "PRODCODE", "PDESC", "STERILE", "SDCODE", "FMCODE", "QTY", "CODE", "DELIVERYWEEK", "DAYNAME", "FMDESC") AS 
  select rp.reportparam_id,
       bu.businessunit_id,
       procbu.businessunit_id procbuid,
       procbu.code bucode,
       bu.description,
       pn.deliverydate,
       pn.productiondate,
       p.code prodcode,
       (select pdesc.description
          from product_desc pdesc
         where p.product_id = pdesc.product_id
           and pdesc.language_id = lan.language_id) pdesc,
       pop.sterile,
       sd.code sdcode,
       fm.code fmcode,
       (pnl.tobedeliveredamount - pnl.deliveredamount) qty,
       lan.code,
       getisoweek(pn.deliverydate) deliveryweek,
       (select dd.description
          from day_desc dd
         where dd.day_id = getdaynumber(pn.deliverydate)
           and dd.language_id = lan.language_id) dayName,
       (select fmd.description
          from finishingmethod_desc fmd
         where fmd.finishingmethod_id = fm.finishingmethod_id
           and fmd.language_id = lan.language_id) fmdesc
  from packingnote     pn,
       packingnoteline pnl,
       status          s,
       businessunit    bu,
       product         p,
       productorpack   pop,
       sizedefinition  sd,
       finishingmethod fm,
       businessunit    procbu,
       languages       lan,
       reportparam     rp
 where pn.packingnote_id = pnl.packingnote_id
   and pnl.product_id = p.product_id
   and p.product_id = pop.product_id
   and p.packtype = 2 --ORS packs
   and pn.status_id = s.status_id
   and s.statustype = 'PN'
   and s.code in ('10', '20')
   and pnl.deliveredamount < pnl.tobedeliveredamount
   and pnl.sizedefinition_id = sd.sizedefinition_id
   and pnl.finishingmethod_id = fm.finishingmethod_id
   and pn.processbusinessunit_id in
       (select ordbu.delivertobusinessunit_id
          from ordeliverbusinessunit ordbu
         where ordbu.orbusinessunit_id = bu.businessunit_id)
   and pn.processbusinessunit_id = procbu.businessunit_id
   and rp.number_value = pn.packingnote_id -- filter per selected PN
   and rp.string_value = lan.code -- lan code
   and (rp.number_value1 = 0 or rp.number_value1 = procbu.businessunit_id) --bu filter from interface
   and (rp.number_value2 = 0 or rp.number_value2 = p.product_id) --filter per product from interface
   and (rp.number_value4 = 2 or rp.number_value4 = pop.sterile) --filter per sterile from interface
   and (rp.date_value1 is null or rp.date_value1 = pn.productiondate) --filter per productiondate from interface
   and trunc(rp.number_value3) = bu.businessunit_id -- filter per current bu- OR business unit
union
select rp.reportparam_id,
       bu.businessunit_id,
       procbu.businessunit_id procbuid,
       procbu.code bucode,
       bu.description,
       pn.deliverydate,
       pn.productiondate,
       p.code prodcode,
       (select pdesc.description
          from product_desc pdesc
         where p.product_id = pdesc.product_id
           and pdesc.language_id = lan.language_id) pdesc,
       pop.sterile,
       sd.code sdcode,
       fm.code fmcode,
       (pnl.tobedeliveredamount - pnl.deliveredamount) * pnlc.quantity qty,
       lan.code,
       getisoweek(pn.deliverydate) deliveryweek,
       (select dd.description
          from day_desc dd
         where dd.day_id = getdaynumber(pn.deliverydate)
           and dd.language_id = lan.language_id) dayName,
       (select fmd.description
          from finishingmethod_desc fmd
         where fmd.finishingmethod_id = fm.finishingmethod_id
           and fmd.language_id = lan.language_id) fmdesc
  from packingnote            pn,
       packingnoteline        pnl,
       packingnotelinecontent pnlc,
       status                 s,
       businessunit           bu,
       product                p,
       productorpack          pop,
       sizedefinition         sd,
       finishingmethod        fm,
       businessunit           procbu,
       languages              lan,
       reportparam            rp
 where pn.packingnote_id = pnl.packingnote_id
   and pnl.packingnoteline_id = pnlc.packingnoteline_id
   and pnlc.product_id = p.product_id
   and p.product_id = pop.product_id
   and p.packtype = 2 --ORS packs
   and pn.status_id = s.status_id
   and s.statustype = 'PN'
   and s.code in ('10', '20')
   and pnl.deliveredamount < pnl.tobedeliveredamount
   and pnlc.sizedefinition_id = sd.sizedefinition_id
   and pnl.finishingmethod_id = fm.finishingmethod_id
   and pn.processbusinessunit_id in
       (select ordbu.delivertobusinessunit_id
          from ordeliverbusinessunit ordbu
         where ordbu.orbusinessunit_id = bu.businessunit_id)
   and pn.processbusinessunit_id = procbu.businessunit_id
   and rp.number_value = pn.packingnote_id -- filter per selected PN
   and rp.string_value = lan.code -- lan code
   and (rp.number_value1 = 0 or rp.number_value1 = procbu.businessunit_id) --bu filter from interface
   and (rp.number_value2 = 0 or rp.number_value2 = p.product_id) --filter per product from interface
   and (rp.number_value4 = 2 or rp.number_value4 = pop.sterile) --filter per sterile from interface
   and (rp.date_value1 is null or rp.date_value1 = pn.productiondate) --filter per productiondate from interface
   and trunc(rp.number_value3) = bu.businessunit_id -- filter per current bu- OR business unit
/

  CREATE OR REPLACE VIEW "V_MICROSSCUSTOMER" ("CUSTOMERID", "CODE", "NAME", "LOADINGPROGRAM", "ADDRESS1", "ADDRESS2", "ZIPCODE", "CITY", "STATE", "CONTACT", "PHONE", "FAX", "EMAIL") AS 
  select
c.legacycustomernumber customerid,
--c.searchname code,
CASTVARCHARASNUMBERINT(GETSUBSTRINGONLENGTH(c.customernumber,1,10)) code,
c.name,
c.loadingprogram,
a.street address1,
a.street2 address2,
a.zipcode,
a.city,
a.state,
(select GETSUBSTRINGONLENGTH(min(cp.name),1,32)--substr(min(cp.name),1,32)
from contactperson cp where cp.customer_id = c.customer_id) contact,
c.phoneno phone,
c.faxno fax,
c.email
from
customer c, address a
where c.visitaddress_id = a.address_id
and c.legacycustomernumber is not null
/

  CREATE OR REPLACE VIEW "V_MICROSSCUSTOMERPRODUCT" ("CUSTOMERID", "PRODUCTID") AS 
  select distinct
c.legacycustomernumber customerid,
p.legacyproductcode productid
from
productlistpercustomer plpc, customer c, product p
where plpc.customer_id = c.customer_id
and plpc.product_id = p.product_id
and c.legacycustomernumber is not null
and p.legacyproductcode is not null
and plpc.dateinactive>=sysdate
and plpc.dateactive<=sysdate
/

  CREATE OR REPLACE VIEW "V_MICROSSDECSTOCKDELQTY" ("PACKINGNOTELINE_ID", "NOTENUMBER", "DELIVERYDATE", "CUSTOMERID", "CUSTOMERCODE", "PRODUCTID", "PRODUCT_DESCRIPTION", "DELIVEREDQTY") AS 
  select /*version 1.2  ABS-62006*/
 pkl.packingnoteline_id, pk.notenumber, pk.deliverydate, c.legacycustomernumber customerid,
 substr(to_char(c.customernumber), 1, 10) customercode, p.legacyproductcode productid,
 (select pd.description
   from   product_desc pd
   where  p.product_id = pd.product_id
   and    pd.language_id =
          (select plant.language_id
            from   plant
            where  plant.plant_id = (select min(plant_id) from plant))) product_description,
 pkl.deliveredamount deliveredqty
from   packingnoteline pkl
join   product p
on     p.product_id = pkl.product_id
join   sizedefinition s
on     s.sizedefinition_id = pkl.sizedefinition_id
join   packingnote pk
on     pk.packingnote_id = pkl.packingnote_id
join   deliverypoint dp
on     dp.deliverypoint_id = pk.deliverypoint_id
join   customer c
on     c.customer_id = dp.customer_id
join   productgroup pg
on     p.productgroup_id = pg.productgroup_id
join   packingdepartmentdefinition pdd
on     pdd.productgroup_id = pg.productgroup_id
where  pk.status_id = (select st.status_id
                       from   status st
                       where  st.code = '30' /*processed*/
                       and    st.statustype = 'PN')
and    pkl.deliveredamount > 0
and    pk.deliverydate > current_date - 3
and    p.typeofmerchandise = 1
and    pdd.plantdepartment_id = 21
and    p.putuptype = 1
and    pg.code not in ('REJ', 'EXT', 'ADMIN', 'LAUBAG')
/

  CREATE OR REPLACE VIEW "V_MICROSSPRODUCT" ("PRODUCTID", "CODE", "DESCRIPTION", "STORAGELINE", "OVERFLOWLINE", "OVERFLOWLINE2", "CLEANLINE", "AMBERWEIGHT", "REDWEIGHT", "OVERWEIGHT", "PIECEWEIGHT", "WASHPROGRAM", "DRYPROGRAM", "PACKQUANTITY", "RENTAL") AS 
  SELECT
p.legacyproductcode productid,
GETSUBSTRINGONLENGTH(p.code,1,4) code, --first 4 characters from shortdescription of product??
(select pd.description from product_desc pd
where p.product_id = pd.product_id
and pd.language_id = l.language_id) description,--long description
pm.storageline,
pm.overflowline,
pm.overflowline2,
pm.cleanline,
pm.amberweight*10 amberweight,
pm.redweight*10 redweight,
pm.overweight*10 overweight,
p.theoreticalweight*1000 pieceweight,--theoreticalweight*1000
w.sortaddress washprogram,
pm.dryprogram,
(case when p.packingamount>1 then p.packingamount else 0 end) packquantity,
---(case when pg.code='999' then 999 else 0 end ) rental --0=customer owned goods, 999=rental
wc.code rental --0=customer owned goods, 999=rental
FROM product p,
productdetailmicross pm,
sortaddressperwashprocess w,
productgroup pg,
WEIGHINGCATEGORY wc,
languages l
where  p.product_id = pm.product_id
and p.WEIGHINGCATEGORY_ID = wc.WEIGHINGCATEGORY_ID
and p.washingprocess_id = w.washingprocess_id
and p.productgroup_id = pg.productgroup_id
and p.legacyproductcode IS NOT NULL
and l.language_id = (select plant.language_id from plant where plant.plant_id =(select min(plant_id) from plant))
/

  CREATE OR REPLACE VIEW "V_MINCUSTFREQUENCY" ("CUSTOMER_ID", "FREQUENCY") AS 
  SELECT X.CUSTOMER_ID, MIN(Y.FREQUENCY) FREQUENCY
FROM CUSTOMERDELIVERYSCHEME X, DELIVERYSCHEME Y
WHERE X.DELIVERYSCHEME_ID = Y.DELIVERYSCHEME_ID
GROUP BY X.CUSTOMER_ID
/

  CREATE OR REPLACE VIEW "V_MINIMUMRENTINCOME" ("PROCESSBUSINESSUNIT_ID", "BUSINESSUNITCODE", "BUSINESSUNITDESC", "MASTERACCOUNT_ID", "MASTERACCOUNTNUMBER", "MASTERACCOUNTNAME", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEARER_ID", "WEARERNUMBER", "WEARERNAME", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITION_ID", "SIZECODE", "SIZEDESCRIPTION", "FINISHINGMETHOD_ID", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "PRIMARYID", "OUTOFCIRCDATE", "RENTYEAR", "RENTWEEK", "RENTPRICESTARTDATE", "RENTPRICEENDDATE", "RENTPRICE", "LANGUAGE_ID", "LANGUAGECODE") AS 
  SELECT C.DEFAULTBUSINESSUNIT_ID PROCESSBUSINESSUNIT_ID,
       BU.CODE BUSINESSUNITCODE,
       BU.DESCRIPTION BUSINESSUNITDESC,
       C.MASTERACCOUNT_ID MASTERACCOUNT_ID,
       (SELECT CU.CUSTOMERNUMBER
          FROM CUSTOMER CU
         WHERE CU.CUSTOMER_ID = C.MASTERACCOUNT_ID) MASTERACCOUNTNUMBER,
       (SELECT CUS.NAME
          FROM CUSTOMER CUS
         WHERE CUS.CUSTOMER_ID = C.MASTERACCOUNT_ID) MASTERACCOUNTNAME,
       UIR.CUSTOMER_LINK_ID CUSTOMER_ID,
       CL.CUSTOMERNUMBER CUSTOMERNUMBER,
       CL.NAME CUSTOMERNAME,
       WE.WEARER_ID WEARER_ID,
       WEL.WEARERNUMBER WEARERNUMBER,
       WEL.WEARERNAME WEARERNAME,
       UIR.PRODUCT_LINK_ID PRODUCT_ID,
       PDL.CODE PRODUCTCODE,
       (SELECT PLD.DESCRIPTION
          FROM PRODUCT_LINK_DESC PLD
         WHERE PLD.PRODUCT_LINK_ID = UIR.PRODUCT_LINK_ID
           AND PLD.LANGUAGE_ID = LG.LANGUAGE_ID) PRODUCTDESCRIPTION,
       UIR.SIZEDEFINITION_LINK_ID SIZEDEFINITION_ID,
       SDL.CODE SIZECODE,
       (SELECT SLD.DESCRIPTION
          FROM SIZEDEFINITION_LINK_DESC SLD
         WHERE SLD.SIZEDEFINITION_LINK_ID = UIR.SIZEDEFINITION_LINK_ID
           AND SLD.LANGUAGE_ID = LG.LANGUAGE_ID) SIZEDESCRIPTION,
       UIR.FINISHINGMETHOD_ID FINISHINGMETHOD_ID,
       FM.CODE FINISHINGMETHODCODE,
       (SELECT FMD.DESCRIPTION
          FROM FINISHINGMETHOD_DESC FMD
         WHERE FMD.FINISHINGMETHOD_ID = UIR.FINISHINGMETHOD_ID
           AND FMD.LANGUAGE_ID = LG.LANGUAGE_ID) FINISHINGMETHODDESCRIPTION,
       COALESCE((SELECT UI.PRIMARYID
                  FROM UNIQUEITEM UI, UNIQUEITEM_LINK UIL
                 WHERE UI.UNIQUEITEM_ID = UIL.UNIQUEITEM_ID
                   AND UIL.UNIQUEITEM_ID IS NOT NULL
                   AND UIL.RAGGEDITEM_ID IS NULL
                   AND UIL.UNIQUEITEM_LINK_ID = UIR.UNIQUEITEM_LINK_ID),
                (SELECT RI.PRIMARYID
                   FROM UNIQUEITEM_LINK UIL, RAGGEDITEM RI
                  WHERE RI.RAGGEDITEM_ID = UIL.RAGGEDITEM_ID
                    AND UIL.UNIQUEITEM_ID IS NULL
                    AND UIL.RAGGEDITEM_ID IS NOT NULL
                    AND UIL.UNIQUEITEM_LINK_ID = UIR.UNIQUEITEM_LINK_ID)) PRIMARYID,
       UIR.OUTOFCIRCDATE OUTOFCIRCDATE,
       UIR.RENTYEAR RENTYEAR,
       UIR.RENTWEEK RENTWEEK,
       GETDATEFORWEEKYEAR(1, UIR.RENTWEEK, UIR.RENTYEAR) RENTPRICESTARTDATE,
       GETDATEFORWEEKYEAR(7, UIR.RENTWEEK, UIR.RENTYEAR) RENTPRICEENDDATE,
       PACK_PRICE.RENT_PRICE(UIR.CUSTOMER_LINK_ID,
                             UIR.PRODUCT_LINK_ID,
                             UIR.SIZEDEFINITION_LINK_ID,
                             UIR.FINISHINGMETHOD_ID,
                             GETDATEFORWEEKYEAR(7,
                                                UIR.RENTWEEK,
                                                UIR.RENTYEAR)) RENTPRICE,
       LG.LANGUAGE_ID LANGUAGE_ID,
       LG.CODE LANGUAGECODE
  FROM CUSTOMER              C,
       CUSTOMER_LINK         CL,
       BUSINESSUNIT          BU,
       UNIQUEITEMRETURNRENT  UIR,
       WEAREREMPLOYMENT      WE,
       WEAREREMPLOYMENT_LINK WEL,
       WEARER                W,
       PRODUCT_LINK          PDL,
       SIZEDEFINITION_LINK   SDL,
       FINISHINGMETHOD       FM,
       LANGUAGES             LG
 WHERE C.CUSTOMER_ID = CL.CUSTOMER_LINK_ID
   AND UIR.CUSTOMER_LINK_ID = CL.CUSTOMER_LINK_ID
   AND BU.BUSINESSUNIT_ID = C.DEFAULTINVOICEBUSINESSUNIT_ID
   AND C.CUSTOMER_ID = W.CUSTOMER_ID
   AND W.WEARER_ID = WE.WEARER_ID
   AND WE.WEAREREMPLOYMENT_ID = WEL.WEAREREMPLOYMENT_ID
   AND WEL.WEAREREMPLOYMENT_LINK_ID = UIR.WEAREREMPLOYMENT_LINK_ID
   AND UIR.PRODUCT_LINK_ID = PDL.PRODUCT_LINK_ID
   AND UIR.SIZEDEFINITION_LINK_ID = SDL.SIZEDEFINITION_LINK_ID
   AND UIR.FINISHINGMETHOD_ID = FM.FINISHINGMETHOD_ID
   AND UIR.RETURNRENTTYPE = 2
/

  CREATE OR REPLACE VIEW "V_MIN_DAY_ROUTE_STOP_DEPOT" ("DAY", "ROUTE_NR", "ROUTE_DESC", "DEPOT_CODE", "DEPOT_DESC", "CUSTOMER_ID", "STOPNUMBER") AS 
  select --r.drivingday_id day,
 min(r.drivingday_id) day,
 r.routenumber route_nr, r.description route_desc,
 d.code depot_code,  d.description depot_desc,
 s.customer_id customer_id, s.stopnumber stopnumber--, r.driver_id driver_id
from route r, routestop s, depot d
where r.route_id = s.route_id and r.depot_id=d.depot_id and r.plant_id = d.plant_id
  and r.active = 'Y'
group by s.customer_id, r.routenumber, r.description, d.code,  d.description, s.customer_id, s.stopnumber--, r.driver_id
/

  CREATE OR REPLACE VIEW "V_MISCELLANEOUSCHARGES" ("BUSINESSUNITID", "BUSINESSUNITCODE", "BUSINESSUNITDESCRIPTION", "CUSTOMERNUMBER", "CUSTOMERNAME", "INVOICENUMBER", "DESCRIPTION", "CREATIONDATE", "QUANTITY", "AMOUNT", "CHARGESTATUS", "INVOICEAMOUNTDECIMALS", "REASONCODE", "REASONCODEDESC", "TURNOVERGROUPDESC", "TURNOVERGROUPCODE", "ROUTEID", "ROUTENUMBER", "ROUTEDESC", "DISTRICTCODE", "DISTRICTDESC", "SYSTEMUSERID", "USERNAME", "LANGUAGECODE", "ROUTEMANAGERNUMBER", "ROUTEMANAGERNAME") AS 
  select /*version 2.0*/
       bu.businessunit_id businessunitid, bu.code businessunitcode, bu.description businessunitdescription,
       cl.customernumber customernumber, cl.name customername, ih.invoicenumber invoicenumber,
       mc.description, mc.creationdate, mc.quantity, mc.amount, mc.chargestatus, cur.invoiceamountdecimals, rc.code reasoncode,
       (select description from reasoncode_desc x where x.reasoncode_id = rc.reasoncode_id and x.language_id = l.language_id) reasoncodedesc,
       (select description from turnovergroup_desc y where y.turnovergroup_id = tg.turnovergroup_id and y.language_id = l.language_id) turnovergroupdesc,
       tg.code turnovergroupcode, r.route_id routeid, r.routenumber routenumber, r.description routedesc,
       (select d.code from district d where d.district_id = r.district_id) districtcode,
       (select d.description from district d where d.district_id = r.district_id) districtdesc,
       s2.systemuser_id systemuserid, s.username, l.code languagecode,
       (select em.employeenumber from employee em where em.employee_id = r.routemanager_id) routemanagernumber,
       (select em.name  from employee em where em.employee_id = r.routemanager_id) routemanagername
  from miscellaneouscharge mc
       left join reasoncode rc on mc.reasoncode_id = rc.reasoncode_id
       left join turnovergroup tg on mc.turnovergroup_id = tg.turnovergroup_id
       join businessunit bu
            join businessunitsperusergroup bugroup
                 join systemuser s2 on bugroup.usergroup_id = s2.usergroup_id
            on bu.businessunit_id = bugroup.businessunit_id
       on mc.invoicebusinessunit_id = bu.businessunit_id
       join customer_link cl on mc.customer_link_id = cl.customer_link_id
       join invoiceheader ih
            left join route r on ih.route_id = r.route_id
            join currency cur on ih.currency_id = cur.currency_id
       on mc.invoiceheader_id = ih.invoiceheader_id
       join systemuser s on mc.creationuser_id = s.systemuser_id
       , languages l
union all
select bu.businessunit_id businessunitid,  bu.code businessunitcode, bu.description businessunitdescription,
       cl.customernumber customernumber, cl.name customername, -1 invoicenumber,
       mc.description, mc.creationdate, mc.quantity, mc.amount, mc.chargestatus,
       (select currency.invoiceamountdecimals from currency, customer c where currency.currency_id = c.currency_id and c.customer_id = cl.customer_id) invoiceamountdecimals,
       rc.code reasoncode,
       (select description from reasoncode_desc x where x.reasoncode_id = rc.reasoncode_id  and x.language_id = l.language_id) reasoncodedesc,
       (select description from turnovergroup_desc y where y.turnovergroup_id = tg.turnovergroup_id and y.language_id = l.language_id) turnovergroupdesc,
       tg.code turnovergroupcode, -1 routeid, -1 routenumber, null routedesc, null districtcode, null districtdesc,
       s2.systemuser_id systemuserid, s.username, l.code languagecode, -1 routemanagernumber, '' routemanagername
  from miscellaneouscharge mc
       left join reasoncode rc on mc.reasoncode_id = rc.reasoncode_id
       left join turnovergroup tg on mc.turnovergroup_id = tg.turnovergroup_id
       join businessunit bu
            join businessunitsperusergroup bugroup
                 join systemuser s2 on bugroup.usergroup_id = s2.usergroup_id
            on bu.businessunit_id = bugroup.businessunit_id
       on mc.invoicebusinessunit_id = bu.businessunit_id
       join customer_link cl on mc.customer_link_id = cl.customer_link_id
       join systemuser s on mc.creationuser_id = s.systemuser_id
       , languages l
where mc.invoiceheader_id is null
/

  CREATE OR REPLACE VIEW "V_MISSINGPRODUCTS" ("CODEUNIQUE", "BATCH_ID", "YEAR", "WEEK", "BATCHNUMBER", "BATCHCODE", "DAYDESCRIPTION", "CUSTOMERNUMBER", "CUSTOMERNAME", "CLIENTNUMBER", "CLIENTNAME", "CLIENTFIRSTNAME", "CLIENT_ID", "PRIMARYID", "PRODUCTDESC", "PRODUCTCODE", "LASTSTAYDESCRIPTION", "LANGUAGECODE", "LASTSTAYDATE", "PRESORTNUMBER", "FMCODE", "PRESORTBATCH", "OUTBATCH_ID", "OUTBATCHYEAR", "OUTBATCHWEEK", "OUTBATCHNUMBER", "OUTBATCHCODE", "OUTBATCHDAYDESC", "QUANTITY") AS 
  select 1 codeunique, b.batch_id, b.year, b.week, b.batchnumber, b.batchcode,
       (select dd.description from day_desc dd where b.day_id = dd.day_id and dd.language_id = languages.language_id) DayDescription,
       c.customernumber, c.name customername,
       cl.clientnumber, cl.name clientname, cl.firstname clientfirstname, cl.client_id,
       uri.primaryid,
       (select pdesc.description from product_desc pdesc where p.product_id = pdesc.product_id and pdesc.language_id = languages.language_id) ProductDesc,
       p.code ProductCode,
       (select sdesc.description from stay_desc sdesc where uri.stay_id = sdesc.stay_id and sdesc.language_id = languages.language_id) LastStayDescription,
       languages.code languagecode, uri.laststaydate,
       cdn.presortnumber,
       ( select fm.code from finishingmethod fm where urip.finishingmethod_id=fm.finishingmethod_id)fmcode,
     coalesce((select crs.presortcustomer from  customerresidentialsettings crs where b.customer_link_id=crs.customer_id),'N') presortbatch,
     -1 outbatch_id, -1 outbatchyear, -1 outbatchweek, -1 outbatchnumber, '' outbatchcode, ''outbatchdaydesc,
     1 quantity
from uniqueresidentialitem uri,
     uniqueresidentialitemproduct urip,
     stay s,
     clientdeliverynote cdn, clientdeliverynoteline cdnl, clientdelnotelinescan cdns,
     customer c, client cl, product p,
     batch b,
     languages
where uri.uniqueresidentialitem_id = urip.uniqueresidentialitem_id
      and uri.stay_id = s.stay_id
      and s.staynr in (10, 70) --in, late
      and s.staytype = 5 -- residential
      and uri.client_id = cl.client_id
      and cl.customer_id = c.customer_id
      and cl.client_id = cdn.client_link_id -- link on CDN CLIENT
      and cdn.clientdeliverynote_id = cdnl.clientdeliverinote_id
      and cdnl.product_link_id = p.product_id
      and cdn.batch_id = b.batch_id
      and cdns.inscanclientdelnoteline_id = cdnl.clientdeliverynoteline_id
      and cdns.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id
      and ( uri.lastinscandate is null or getdatediff(trunc(sysdate), uri.lastinscandate) <
      coalesce((select to_number(ss.value) from SYSTEMSETTING ss, businessunit bu
               where ss.name = 'PWBMAXCOMPLETENESSDAYS' and ss.plant_id = bu.plant_id and bu.businessunit_id = uri.businessunit_id ),100))
      and not exists (select 1 from specialscans ss where ss.stay_id=s.stay_id)
union
select 1 codeunique, b.batch_id, b.year, b.week, b.batchnumber, b.batchcode,
       (select dd.description from day_desc dd where b.day_id = dd.day_id and dd.language_id = languages.language_id) DayDescription,
       c.customernumber, c.name customername,
       cl.clientnumber, cl.name clientname, cl.firstname clientfirstname, cl.client_id,
       uri.primaryid,
       (select pdesc.description from product_desc pdesc where p.product_id = pdesc.product_id and pdesc.language_id = languages.language_id) ProductDesc,
       p.code ProductCode,
       (select sdesc.description from stay_desc sdesc where uri.stay_id = sdesc.stay_id and sdesc.language_id = languages.language_id) LastStayDescription,
       languages.code languagecode, uri.laststaydate,
       cdn.presortnumber,
       ( select fm.code from finishingmethod fm where urip.finishingmethod_id=fm.finishingmethod_id)fmcode,
       coalesce((select crs.presortcustomer from  customerresidentialsettings crs where b.customer_link_id=crs.customer_id),'N') presortbatch,
       ( case when exists( select 1 from
        clientdeliverynote cdn, clientdeliverynoteline cdnl, clientdelnotelinescan cdns
                           where cdn.clientdeliverynote_id = cdnl.clientdeliverinote_id
              and cdnl.product_link_id = p.product_id
              and cdn.batch_id = b.batch_id
              and cdns.inscanclientdelnoteline_id = cdnl.clientdeliverynoteline_id
              and cdns.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id) then -1
       else 0  end )outbatch_id,
        -1 outbatchyear, -1 outbatchweek, -1 outbatchnumber, '' outbatchcode, ''outbatchdaydesc,
        1 quantity
from uniqueresidentialitem uri,
     uniqueresidentialitemproduct urip,
     stay s,
     clientdeliverynote cdn,
     customer c, client cl, product p,
     batch b,
     languages
where uri.uniqueresidentialitem_id = urip.uniqueresidentialitem_id
      and uri.stay_id = s.stay_id
      and s.staynr = 60 --delay
      and s.staytype = 5 -- residential
      and uri.client_id = cl.client_id
      and cl.customer_id = c.customer_id
      and cl.client_id = cdn.client_link_id -- link on CDN CLIENT
      and urip.product_id = p.product_id
      and cdn.batch_id = b.batch_id
      and ((select ss.value
          from SYSTEMSETTING ss, businessunit bu
               where ss.name = 'SHOWDELAYEDCOMPLETCHECK' and ss.plant_id = bu.plant_id and bu.businessunit_id = uri.businessunit_id )='Y')
      and ( uri.lastinscandate is null or getdatediff(trunc(sysdate), uri.lastinscandate) <
      coalesce((select to_number(ss.value) from SYSTEMSETTING ss, businessunit bu
               where ss.name = 'PWBMAXCOMPLETENESSDAYS' and ss.plant_id = bu.plant_id and bu.businessunit_id = uri.businessunit_id ),100))
      and not exists (select 1 from specialscans ss where ss.stay_id=s.stay_id)
 union
select 1 codeunique, b.batch_id, b.year, b.week, b.batchnumber, b.batchcode,
       (select dd.description from day_desc dd where b.day_id = dd.day_id and dd.language_id = languages.language_id) DayDescription,
       c.customernumber, c.name customername,
       cl.clientnumber, cl.name clientname, cl.firstname clientfirstname, cl.client_id,
       uri.primaryid,
       (select pdesc.description from product_desc pdesc where p.product_id = pdesc.product_id and pdesc.language_id = languages.language_id) ProductDesc,
       p.code ProductCode,
       (select sdesc.description from stay_desc sdesc where uri.stay_id = sdesc.stay_id and sdesc.language_id = languages.language_id) LastStayDescription,
       languages.code languagecode, uri.laststaydate,
       cdn.presortnumber,
       ( select fm.code from finishingmethod fm where urip.finishingmethod_id=fm.finishingmethod_id)fmcode,
       coalesce((select crs.presortcustomer from  customerresidentialsettings crs where b.customer_link_id=crs.customer_id),'N') presortbatch,
       ( case when exists( select 1 from
        clientdeliverynote cdn, clientdeliverynoteline cdnl, clientdelnotelinescan cdns
                           where cdn.clientdeliverynote_id = cdnl.clientdeliverinote_id
              and cdnl.product_link_id = p.product_id
              and cdn.batch_id = b.batch_id
              and cdns.inscanclientdelnoteline_id = cdnl.clientdeliverynoteline_id
              and cdns.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id) then -1
       else 0  end )outbatch_id,
        -1 outbatchyear, -1 outbatchweek, -1 outbatchnumber, '' outbatchcode, ''outbatchdaydesc,
        1 quantity
from uniqueresidentialitem uri,
     uniqueresidentialitemproduct urip,
     stay s,
     clientdeliverynote cdn,
     customer c, client cl, product p,
     batch b,
     languages
where uri.uniqueresidentialitem_id = urip.uniqueresidentialitem_id
      and uri.stay_id = s.stay_id
      and s.staynr = 50 --rewash
      and s.staytype = 5 -- residential
      and uri.client_id = cl.client_id
      and cl.customer_id = c.customer_id
      and cl.client_id = cdn.client_link_id -- link on CDN CLIENT
      and urip.product_id = p.product_id
      and cdn.batch_id = b.batch_id
      and ( uri.lastinscandate is null or getdatediff(trunc(sysdate), uri.lastinscandate) <
      coalesce((select to_number(ss.value) from SYSTEMSETTING ss, businessunit bu
               where ss.name = 'PWBMAXCOMPLETENESSDAYS' and ss.plant_id = bu.plant_id and bu.businessunit_id = uri.businessunit_id ),100))
      and not exists (select 1 from specialscans ss where ss.stay_id=s.stay_id)
 union
 select 1 codeunique, b.batch_id, b.year, b.week, b.batchnumber, b.batchcode,
       (select dd.description from day_desc dd where b.day_id = dd.day_id and dd.language_id = languages.language_id) DayDescription,
       c.customernumber, c.name customername,
       cl.clientnumber, cl.name clientname, cl.firstname clientfirstname, cl.client_id,
       uri.primaryid,
       (select pdesc.description from product_desc pdesc where p.product_id = pdesc.product_id and pdesc.language_id = languages.language_id) ProductDesc,
       p.code ProductCode,
       (select sdesc.description from stay_desc sdesc where uri.stay_id = sdesc.stay_id and sdesc.language_id = languages.language_id) LastStayDescription,
       languages.code languagecode, uri.laststaydate,
       cdn.presortnumber,
       ( select fm.code from finishingmethod fm where urip.finishingmethod_id=fm.finishingmethod_id)fmcode,
     coalesce((select crs.presortcustomer from  customerresidentialsettings crs where b.customer_link_id=crs.customer_id),'N') presortbatch,
     bo.batch_id outbatch_id, bo.year outbatchyear, bo.week outbatchweek, bo.batchnumber outbatchnumber, bo.batchcode outbatchcode,
     (select dd.description from day_desc dd where bo.day_id = dd.day_id and dd.language_id = languages.language_id) outbatchdaydesc,
     1 quantity
from uniqueresidentialitem uri,
     uniqueresidentialitemproduct urip,
     stay s,
     clientdeliverynote cdn, clientdeliverynoteline cdnl, clientdelnotelinescan cdns,
     customer c, client cl, product p,
     batch b,
     clientdeliverynote cdno, clientdeliverynoteline cdnlo,batch bo,
     languages
where uri.uniqueresidentialitem_id = urip.uniqueresidentialitem_id
      and uri.stay_id = s.stay_id
      and s.staynr =20 --outscan
      and s.staytype = 5 -- residential
      and uri.client_id = cl.client_id
      and cl.customer_id = c.customer_id
      and cl.client_id = cdn.client_link_id -- link on CDN CLIENT
      and cdn.clientdeliverynote_id = cdnl.clientdeliverinote_id
      and cdnl.product_link_id = p.product_id
      and cdn.batch_id = b.batch_id
      and cdns.inscanclientdelnoteline_id = cdnl.clientdeliverynoteline_id
      and cdns.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id
      and cdns.inscanclientdelnoteline_id <> cdns.outscanclientdelnoteline_id
      and cdns.outscanclientdelnoteline_id =cdnlo.clientdeliverynoteline_id
      and cdnlo.clientdeliverinote_id=cdno.clientdeliverynote_id
      and cdn.client_link_id=cdno.client_link_id
      and cdn.customer_link_id=cdno.customer_link_id
      and cdno.batch_id=bo.batch_id
      and bo.batch_id > b.batch_id
union
select 1 codeunique, b.batch_id, b.year, b.week, b.batchnumber, b.batchcode,
       (select dd.description from day_desc dd where b.day_id = dd.day_id and dd.language_id = languages.language_id) DayDescription,
       c.customernumber, c.name customername,
       cl.clientnumber, cl.name clientname, cl.firstname clientfirstname, cl.client_id,
       uri.primaryid,
       (select pdesc.description from product_desc pdesc where p.product_id = pdesc.product_id and pdesc.language_id = languages.language_id) ProductDesc,
       p.code ProductCode,
       (select sdesc.description from stay_desc sdesc where uri.stay_id = sdesc.stay_id and sdesc.language_id = languages.language_id) LastStayDescription,
       languages.code languagecode, uri.laststaydate,
       cdn.presortnumber,
       ( select fm.code from finishingmethod fm where urip.finishingmethod_id=fm.finishingmethod_id)fmcode,
       coalesce((select crs.presortcustomer from  customerresidentialsettings crs where b.customer_link_id=crs.customer_id),'N') presortbatch,
         -1 outbatch_id, -1 outbatchyear, -1 outbatchweek, -1 outbatchnumber, '' outbatchcode,''outbatchdaydesc,
         1 quantity
from uniqueresidentialitem uri,
     uniqueresidentialitemproduct urip,
     stay s,
     clientdeliverynote cdn, --clientdeliverynoteline cdnl,
     customer c, client cl, product p,
     batch b,
     languages
where uri.uniqueresidentialitem_id = urip.uniqueresidentialitem_id
      and uri.stay_id = s.stay_id
      and s.Stay_ID--staynr
          in (Select SS.Stay_ID from SpecialScans SS where SS.Stay_ID is not null) --special scans
      and uri.timestamp < sysdate - numtodsinterval((coalesce((select castvarcharasnumber(ss.value)
          from SYSTEMSETTING ss, businessunit bu
               where ss.name = 'SHOWSPECIALSCANSAFTER' and ss.plant_id = bu.plant_id and bu.businessunit_id = uri.businessunit_id )
                     , 0)), 'hour')
      and trunc(uri.timestamp) > sysdate - coalesce((select castvarcharasnumber(ss.value)
          from SYSTEMSETTING ss, businessunit bu
               where ss.name = 'SPECIALSCANSEXPIRATION' and ss.plant_id = bu.plant_id and bu.businessunit_id = uri.businessunit_id )
                     , 0)
      and uri.client_id = cl.client_id
      and cl.customer_id = c.customer_id
      and c.customer_id = cdn.customer_link_id
      and urip.product_id = p.product_id
      and cdn.batch_id = b.batch_id
       and ( uri.lastinscandate is null or getdatediff(trunc(sysdate), uri.lastinscandate) <
      coalesce((select to_number(ss.value) from SYSTEMSETTING ss, businessunit bu
               where ss.name = 'PWBMAXCOMPLETENESSDAYS' and ss.plant_id = bu.plant_id and bu.businessunit_id = uri.businessunit_id ),100))
union
      select 2 codeunique,b.batch_id, b.year, b.week, b.batchnumber, b.batchcode,
       (select dd.description from day_desc dd where b.day_id = dd.day_id and dd.language_id = languages.language_id) DayDescription,
       c.customernumber, c.name customername,
       cl.clientnumber, cl.name clientname, cl.firstname clientfirstname, cl.client_id,
       '-1' primaryid,
       (select pdesc.description from product_desc pdesc where p.product_id = pdesc.product_id and pdesc.language_id = languages.language_id) ProductDesc,
       p.code ProductCode, '' LastStayDescription,
       languages.code languagecode, sysdate laststaydate,
       cdn.presortnumber,
       ( select fm.code from finishingmethod fm where cdnl.finishingmethod_id=fm.finishingmethod_id)fmcode,
     coalesce((select crs.presortcustomer from  customerresidentialsettings crs where b.customer_link_id=crs.customer_id),'N') presortbatch,
      -1 outbatch_id, -1 outbatchyear, -1 outbatchweek, -1 outbatchnumber, '' outbatchcode, ''outbatchdaydesc,
      (cdnl.qtycountedin-cdnl.qtycountedout) quantity
from clientdeliverynote cdn, clientdeliverynoteline cdnl,
     customer c, client cl, product p, batch b,
     languages
where cl.customer_id = c.customer_id
      and cl.client_id = cdn.client_link_id -- link on CDN CLIENT
      and cdn.clientdeliverynote_id = cdnl.clientdeliverinote_id
      and cdnl.product_link_id = p.product_id
      and cdn.batch_id = b.batch_id
      and b.customer_link_id=c.customer_id
      and cdnl.qtycountedin-cdnl.qtycountedout > 0
      and ((select ss.value
          from SYSTEMSETTING ss, businessunit bu
               where ss.name = 'PWBCOMPCHECKNONUNIQUE' and ss.plant_id = bu.plant_id and bu.businessunit_id = b.businessunit_id )=0)
union
      select 2 codeunique,b.batch_id, b.year, b.week, b.batchnumber, b.batchcode,
       (select dd.description from day_desc dd where b.day_id = dd.day_id and dd.language_id = languages.language_id) DayDescription,
       c.customernumber, c.name customername,
       cl.clientnumber, cl.name clientname, cl.firstname clientfirstname, cl.client_id,
       '-1' primaryid,
       (select pdesc.description from product_desc pdesc where p.product_id = pdesc.product_id and pdesc.language_id = languages.language_id) ProductDesc,
       p.code ProductCode, '' LastStayDescription,
       languages.code languagecode, sysdate laststaydate,
       cdn.presortnumber,
       ( select fm.code from finishingmethod fm where cdnl.finishingmethod_id=fm.finishingmethod_id)fmcode,
     coalesce((select crs.presortcustomer from  customerresidentialsettings crs where b.customer_link_id=crs.customer_id),'N') presortbatch,
      0 outbatch_id, -1 outbatchyear, -1 outbatchweek, -1 outbatchnumber, '' outbatchcode, ''outbatchdaydesc,
      (cdnl.qtycountedin-cdnl.qtycountedout) quantity
from clientdeliverynote cdn, clientdeliverynoteline cdnl,
     customer c, client cl, product p, batch b,batch oldbatch,
     languages
where cl.customer_id = c.customer_id
      and cl.client_id = cdn.client_link_id -- link on CDN CLIENT
      and cdn.clientdeliverynote_id = cdnl.clientdeliverinote_id
      and cdnl.product_link_id = p.product_id
      and cdn.batch_id=oldbatch.batch_id
      and cdn.customer_link_id=c.customer_id
      and oldbatch.closingdate is not null
      and cdn.batch_id <> b.batch_id
      and oldbatch.origin <> 8
      and cdnl.qtycountedin-cdnl.qtycountedout > 0
      and ((select ss.value
          from SYSTEMSETTING ss, businessunit bu
               where ss.name = 'PWBCOMPCHECKNONUNIQUE' and ss.plant_id = bu.plant_id and bu.businessunit_id = b.businessunit_id )=0)
     and exists (select 1 from clientdeliverynote a where a.client_link_id=cl.client_id and a.batch_id=b.batch_id)
/

  CREATE OR REPLACE VIEW "V_MISSINGPRODUCTS_HIST" ("BATCH_ID", "YEAR", "WEEK", "BATCHNUMBER", "BATCHCODE", "DAYDESCRIPTION", "CUSTOMERNUMBER", "CUSTOMERNAME", "CLIENTNUMBER", "CLIENTNAME", "CLIENTFIRSTNAME", "CLIENT_ID", "PRIMARYID", "LASTSTAYDATE", "LASTSTAYDATETRUNC", "PRODUCTDESC", "PRODUCTCODE", "CLIENTDELIVERYNOTE_ID", "LASTSTAYDESCRIPTION", "LANGUAGECODE") AS 
  select b.batch_id, b.year, b.week, b.batchnumber, b.batchcode,
       (select dd.description from day_desc dd where b.day_id = dd.day_id and dd.language_id = languages.language_id) DayDescription,
       c.customernumber, c.name customername,
       cl.clientnumber, cl.name clientname, cl.firstname clientfirstname, cl.client_id,
       uri.primaryid, uri.laststaydate, trunc(uri.laststaydate) laststaydatetrunc,
       (select pdesc.description from product_desc pdesc where p.product_id = pdesc.product_id and pdesc.language_id = languages.language_id) ProductDesc,
       p.code ProductCode, cdn.clientdeliverynote_id,
       (select sdesc.description from stay_desc sdesc where uri.stay_id = sdesc.stay_id and sdesc.language_id = languages.language_id) LastStayDescription,
       languages.code languagecode
from uniqueresidentialitem uri,
     uniqueresidentialitemproduct urip,
     stay s,
     clientdeliverynote cdn, clientdeliverynoteline cdnl, clientdelnotelinescan cdns,
     customer c, client cl, product p,
     batch b,
     languages
where uri.uniqueresidentialitem_id = urip.uniqueresidentialitem_id
      and uri.stay_id = s.stay_id
      and s.staynr in (10, 60, 70) --in, late, delay
      and s.staytype = 5 -- residential
      and uri.client_id = cl.client_id
      and cl.customer_id = c.customer_id
      and cl.client_id = cdn.client_link_id
      and cdn.clientdeliverynote_id = cdnl.clientdeliverinote_id
      and cdnl.product_link_id = p.product_id
      and cdn.batch_id = b.batch_id
      and cdns.inscanclientdelnoteline_id = cdnl.clientdeliverynoteline_id
			and cdns.outscanclientdelnoteline_id is null
      and cdns.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id
			and b.status = 4
			and b.origin < 6
/

  CREATE OR REPLACE VIEW "V_MODIFICATION" ("CODE", "LEGACYMODIFICATIONCODE", "MODIFICATION_DESC", "STOCKWITHSTANDARDSIZE", "SYSTEMUSER_ID", "LANGUAGECODE", "TIMESTAMP", "MODIFICATION_ID") AS 
  SELECT MODIFICATION.CODE, MODIFICATION.LEGACYMODIFICATIONCODE,
(SELECT DESCRIPTION FROM MODIFICATION_DESC A WHERE A.MODIFICATION_ID = MODIFICATION.MODIFICATION_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) MODIFICATION_DESC,
 MODIFICATION.STOCKWITHSTANDARDSIZE, MODIFICATION.SYSTEMUSER_ID,LANGUAGES.CODE LANGUAGECODE,
 MODIFICATION.TIMESTAMP, MODIFICATION.MODIFICATION_ID
	FROM  MODIFICATION, LANGUAGES
/

  CREATE OR REPLACE VIEW "V_MODIFICATIONGROUP" ("CODE", "MODIFICATIONGROUP_DESC", "SYSTEMUSER_ID", "TIMESTAMP", "MODIFICATIONGROUP_ID", "LANGUAGECODE") AS 
  SELECT MODIFICATIONGROUP.CODE,
(SELECT DESCRIPTION FROM MODIFICATIONGROUP_DESC A WHERE A.MODIFICATIONGROUP_ID = MODIFICATIONGROUP.MODIFICATIONGROUP_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  MODIFICATIONGROUP_DESC,
MODIFICATIONGROUP.SYSTEMUSER_ID, MODIFICATIONGROUP.TIMESTAMP, MODIFICATIONGROUP.MODIFICATIONGROUP_ID, LANGUAGES.CODE LANGUAGECODE
	FROM  MODIFICATIONGROUP,   LANGUAGES
/

  CREATE OR REPLACE VIEW "V_MODIFWOL" ("MODIFICATION_ID", "PURCHASEORDERLINE_ID") AS 
  select distinct wolm.modification_id, wol.purchaseorderline_id
from workorderline wol inner join workorderlinemodification wolm on wol.workorderline_id=wolm.workorderline_id
/

  CREATE OR REPLACE VIEW "V_MODIF_WO_INSET" ("PRODUCTCODE", "WORKORDERNUMBER", "WEARERNUMBER", "WEARERNAME", "MODIFCODE", "IDCODE", "ISSUEDATE", "CUSTOWNED", "LANGUAGECODE", "BU_CODE", "BU_DESC", "CUSTNUMBER", "CUSTNAME", "PRODUCT_DESC", "SIZECODE", "REASONCODE", "REASONCODE_DESCR") AS 
  select /*version 1.2*/
       p.code productcode, w.workordernumber, wear.wearernumber, wear.fullname wearername,
       m.code modifcode, ui.primaryid idcode, ufi.lastissuedate issuedate,
       ui.customerowned custowned, lan.code languagecode,
       bu.code bu_code, bu.description bu_desc, c.customernumber custnumber, c.name custname,
       (select pd.description
          from product_desc pd
         where pd.product_id = p.product_id
           and pd.language_id = lan.language_id) product_desc,
       (select sd.code from sizedefinition sd where sd.sizedefinition_id = ui.sizedefinition_id) sizecode,
       (select rcd.code from reasoncode rcd where rcd.reasoncode_id = w.reasoncode_id) reasoncode,
       (select rcdd.description
          from reasoncode_desc rcdd
         where rcdd.reasoncode_id = w.reasoncode_id
           and rcdd.language_id = lan.language_id) reasoncode_descr
  from uniqueitem ui
       left join uniqueitemfixedinfo ufi
            left join workorder w on (ufi.issuedbyworkorder_id = w.workorder_id
                                      and w.workordernumber is not null)
       on ui.uniqueitem_id = ufi.uniqueitem_id
       join product p on ui.product_id = p.product_id
       join businessunit bu on ui.businessunit_id = bu.businessunit_id
       join uniqueitemmodification uim
            join modification m on uim.modification_id = m.modification_id
       on ui.uniqueitem_id = uim.uniqueitem_id
       join uniqueitemnonpool unp
            join weareremployment wemp
                 join wearer wear
                      join customer c on wear.customer_id = c.customer_id
                 on wemp.wearer_id = wear.wearer_id
            on unp.weareremployment_id = wemp.weareremployment_id
       on ui.uniqueitem_id = unp.uniqueitem_id
       cross join languages lan
 where ui.customerowned = 'N'
   and w.reasoncode_id in (select reasoncode_id from reasoncode rc where rc.code in
   ('20', '21', '30', '40', '50', '51', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '70', '71', '87', '88', '90', '91', '92', '97', '98', '200'))
/

  CREATE OR REPLACE VIEW "V_MONTHINVUTIL_ANG_OLDWEBAPP" ("CUSTOMERNUMBER", "CUSTOMER_ID", "CUSTOMERNAME", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "WEBSESSION_ID", "WEBUSER_ID", "WEB_DEPARTMENT_ID", "DEPARTMENT_LINK_ID", "DISTRIBUTIONPOINT_LINK_ID", "REPORTPARAM_ID", "DISTRIBUTIONNUMBER", "DISTRIBUTIONDESC", "PATIENTDAYSDSP", "PATIENTDAYSDEP", "ACTIVITY_ID", "ACTIVITYCODE", "PRODUCTGROUP_ID", "PRODUCTGROUPCODE", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "FINISHINGCODE", "SIZEDESC", "FINISHINGDESC", "AMOUNTSTANDARD", "AMOUNTDELIVERED", "PRICE", "PRICEDETAIL", "POUNDPRICE", "SOILWEIGHT", "PARLEVEL_1", "USED_1", "INVOICEAMOUNTDECIMALS", "DECIMALS", "CURRENCYCODE", "LANGUAGECODE") AS 
  select
  cu.customernumber, cu.customer_id , cu.name customerName, delk.department_id, delk.departmentnumber, delk.description departmentDesc
, websession.websession_id, wcu.webuser_id, wde.department_id web_department_id, delk.department_link_id, dilk.distributionpoint_link_id, rp.reportparam_id
, dilk.distributionpointnumber distributionNumber, dilk.description distributionDesc
, coalesce(( select SUM(pdy.patientdays) from patientday pdy where dilk.distributionpoint_link_id = pdy.distributionpoint_link_id
--              and pdy.year = rp.number_value and pdy.month between rp.number_value1 and rp.number_value2
              and pdy.year*100+pdy.month between (RP.NUMBER_VALUE*100+RP.NUMBER_VALUE1) and (RP.NUMBER_VALUE4*100+RP.NUMBER_VALUE2)
              group by dilk.distributionpoint_link_id),0) patientdaysDsp
, coalesce(( select sum(pdy.patientdays) from patientday pdy, distributionpoint_link
              where distributionpoint_link.department_link_id = delk.department_link_id
              and distributionpoint_link.distributionpoint_link_id = pdy.distributionpoint_link_id
--              and pdy.year = rp.number_value and pdy.month between rp.number_value1 and rp.number_value2
              and pdy.year*100+pdy.month between (RP.NUMBER_VALUE*100+RP.NUMBER_VALUE1) and (RP.NUMBER_VALUE4*100+RP.NUMBER_VALUE2)
              group by distributionpoint_link.department_link_id),0) patientdaysDep
, activity.activity_id ACTIVITY_ID, activity.code activityCode, prdgr.productgroup_id PRODUCTGROUP_ID, prdgr.code productgroupCode, prd.product_id, prd.code productCode
, ( select product_link_desc.description from product_link_desc where product_link_desc.product_link_id = prd.product_id
              and product_link_desc.language_id = languages.language_id ) productDesc
, szlk.code sizeCode, fm.code Finishingcode
, ( select sizedefinition_desc.description from sizedefinition_desc where sizedefinition_desc.sizedefinition_id = szlk.sizedefinition_link_id
              and sizedefinition_desc.language_id = languages.language_id ) sizeDesc
, ( select finishingmethod_desc.description from finishingmethod_desc where finishingmethod_desc.finishingmethod_id = fm.finishingmethod_id
              and finishingmethod_desc.language_id = languages.language_id ) FinishingDesc
, coalesce(sum(dh.amountstandard),0) amountstandard
, coalesce(sum(dh.amountdelivered),0) amountdelivered
, coalesce(sum(F_RESTOCKINGPRICE_ANG(dh.customer_link_id, dh.product_link_id, dh.sizedefinition_link_id, dh.finishingmethod_id, rp.date_value1, prd.typeofmerchandise)),0) price
, F_RESTOCKINGPRICE_ANG(cu.customer_id, prd.product_id, szlk.sizedefinition_link_id, fm.finishingmethod_id, rp.date_value1, prd.typeofmerchandise) priceDetail
--, coalesce(sum(
--  dh.amountstandard * F_RESTOCKINGPRICE(dh.customer_link_id, dh.product_link_id, dh.sizedefinition_link_id, dh.finishingmethod_id, rp.date_value1, prd.typeofmerchandise)
--      ),0) ParLevel_1
--, coalesce(sum(
--  dh.amountdelivered * F_RESTOCKINGPRICE(dh.customer_link_id, dh.product_link_id, dh.sizedefinition_link_id, dh.finishingmethod_id, rp.date_value1, prd.typeofmerchandise)
--      ),0) Used_1
, F_GETPOUNDPRICE(prd.product_id, fm.finishingmethod_id, szlk.sizedefinition_link_id, cu.customer_id, prd.weighingcategory_id, rp.date_value1) poundprice
--, F_GETSOILWEIGHT(cu.customer_id, prd.product_id, szlk.sizedefinition_link_id, fm.finishingmethod_id, rp.date_value1) SOILWEIGHT
, coalesce(sum(dh.pieceweight),0) soilweight
, coalesce(
  SUM(dh.amountstandard *
         ( round(dh.pieceweight * F_GETPOUNDPRICE(prd.product_id, fm.finishingmethod_id, szlk.sizedefinition_link_id, cu.customer_id, prd.weighingcategory_id, rp.date_value1),currency.invoiceamountdecimals)
           +
           F_RESTOCKINGPRICE_ANG(dh.customer_link_id, dh.product_link_id, dh.sizedefinition_link_id, dh.finishingmethod_id, rp.date_value1, prd.typeofmerchandise)
         )
     ), 0) ParLevel_1
, coalesce(
  SUM(dh.amountdelivered *
         ( round(dh.pieceweight * F_GETPOUNDPRICE(prd.product_id, fm.finishingmethod_id, szlk.sizedefinition_link_id, cu.customer_id, prd.weighingcategory_id, rp.date_value1),currency.invoiceamountdecimals)
           +
           F_RESTOCKINGPRICE_ANG(dh.customer_link_id, dh.product_link_id, dh.sizedefinition_link_id, dh.finishingmethod_id, rp.date_value1, prd.typeofmerchandise)
         )
     ), 0) Used_1
, currency.invoiceamountdecimals, currency.decimals, currency.code currencyCode
, languages.code languageCode
from
  deliveryhistory dh
, webusercustomer wcu left outer join webuserdepartment wde on wcu.webusercustomer_id = wde.webusercustomer_id
, websession
, customer cu, department_link delk, distributionpoint_link dilk
, product prd left outer join
                        ( productgroup prdgr join activity on prdgr.activity_id = activity.activity_id )
                    on prd.productgroup_id = prdgr.productgroup_id
, sizedefinition_link szlk, finishingmethod fm, customermonth cm
, currency, reportparam rp , languages
where
    dh.packindication <> 2
and dh.customer_link_id = cu.customer_id
and dh.customer_link_id= wcu.customer_id
and dh.customer_link_id = websession.customer_id
and dh.department_link_id = delk.department_link_id
and dh.distributionpoint_link_id = dilk.distributionpoint_link_id
and dh.product_link_id = prd.product_id
and dh.sizedefinition_link_id = szlk.sizedefinition_link_id
and dh.finishingmethod_id = fm.finishingmethod_id
and dh.customer_link_id = cm.customer_id
--AND RP.NUMBER_VALUE = CM.YEAR
--AND CM.MONTH BETWEEN RP.NUMBER_VALUE1 AND RP.NUMBER_VALUE2
and CM.YEAR*100+CM.MONTH between (RP.NUMBER_VALUE*100+RP.NUMBER_VALUE1) and (RP.NUMBER_VALUE4*100+RP.NUMBER_VALUE2)
and dh.deliverydate between cm.startdate and cm.enddate
and cu.currency_id = currency.currency_id
group by
  cu.customernumber, cu.customer_id, cu.name , delk.department_id, delk.departmentnumber, delk.description
, websession.websession_id, wcu.webuser_id, wde.department_id, delk.department_link_id
, dilk.distributionpoint_link_id, dilk.distributionpointnumber, dilk.description
, activity.activity_id, activity.code, prdgr.productgroup_id, prdgr.code, prd.product_id, prd.code
, szlk.code, szlk.sizedefinition_link_id, fm.finishingmethod_id, fm.code
, prd.weighingcategory_id, prd.typeofmerchandise
, currency.invoiceamountdecimals, currency.decimals, currency.code
, languages.language_id, languages.code
, rp.reportparam_id, rp.number_value, rp.number_value1, rp.number_value2, rp.date_value1, rp.number_value4
/

  CREATE OR REPLACE VIEW "V_MONTHLYINVENTORYUTILIZATION" ("CUSTOMERNUMBER", "CUSTOMER_ID", "CUSTOMERNAME", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "WEBSESSION_ID", "WEBUSER_ID", "WEB_DEPARTMENT_ID", "DEPARTMENT_LINK_ID", "DISTRIBUTIONPOINT_LINK_ID", "REPORTPARAM_ID", "DISTRIBUTIONNUMBER", "DISTRIBUTIONDESC", "PATIENTDAYSDSP", "PATIENTDAYSDEP", "ACTIVITY_ID", "ACTIVITYCODE", "PRODUCTGROUP_ID", "PRODUCTGROUPCODE", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "FINISHINGCODE", "FINISHINGDESC", "AMOUNTSTANDARD", "AMOUNTDELIVERED", "PRICE", "PARLEVEL_1", "USED_1", "INVOICEAMOUNTDECIMALS", "DECIMALS", "CURRENCYCODE", "LANGUAGECODE") AS 
  select
  cu.customernumber, cu.customer_id , cu.name customerName, delk.department_id, delk.departmentnumber, delk.description departmentDesc
, webusersession.websession_id, wcu.webuser_id, wde.department_id web_department_id, delk.department_link_id, dilk.distributionpoint_link_id, rp.reportparam_id
, dilk.distributionpointnumber distributionNumber, dilk.description distributionDesc
, coalesce(( select SUM(pdy.patientdays) from patientday pdy where dilk.distributionpoint_link_id = pdy.distributionpoint_link_id
--  and pdy.year = rp.number_value and pdy.month between rp.number_value1 and rp.number_value2
  and pdy.year*100+pdy.month between (RP.NUMBER_VALUE*100+RP.NUMBER_VALUE1) and (RP.NUMBER_VALUE4*100+RP.NUMBER_VALUE2)
  group by dilk.distributionpoint_link_id),0) patientdaysDsp
, coalesce(( select sum(pdy.patientdays) from patientday pdy, distributionpoint_link
  where distributionpoint_link.department_link_id = delk.department_link_id
  and distributionpoint_link.distributionpoint_link_id = pdy.distributionpoint_link_id
--  and pdy.year = rp.number_value and pdy.month between rp.number_value1 and rp.number_value2
  and pdy.year*100+pdy.month between (RP.NUMBER_VALUE*100+RP.NUMBER_VALUE1) and (RP.NUMBER_VALUE4*100+RP.NUMBER_VALUE2)
  group by distributionpoint_link.department_link_id),0) patientdaysDep
, activity.activity_id ACTIVITY_ID, activity.code activityCode, prdgr.productgroup_id PRODUCTGROUP_ID, prdgr.code productgroupCode, prd.product_id PRODUCT_ID, prd.code productCode
, ( select product_link_desc.description from product_link_desc where product_link_desc.product_link_id = prd.product_id
  and product_link_desc.language_id = languages.language_id ) productDesc
, szlk.code sizeCode, fm.code Finishingcode
, ( select finishingmethod_desc.description from finishingmethod_desc where finishingmethod_desc.finishingmethod_id = fm.finishingmethod_id
  and finishingmethod_desc.language_id = languages.language_id ) FinishingDesc
, coalesce(sum(dh.amountstandard),0) amountstandard
, coalesce(sum(dh.amountdelivered),0) amountdelivered
, coalesce(sum(F_RESTOCKINGPRICE(dh.customer_link_id, dh.product_link_id, dh.sizedefinition_link_id, dh.finishingmethod_id, rp.date_value1, prd.typeofmerchandise)),0) price
, coalesce(sum(
  dh.amountstandard * F_RESTOCKINGPRICE(dh.customer_link_id, dh.product_link_id, dh.sizedefinition_link_id, dh.finishingmethod_id, rp.date_value1, prd.typeofmerchandise)
      ),0) ParLevel_1
, coalesce(sum(
  dh.amountdelivered * F_RESTOCKINGPRICE(dh.customer_link_id, dh.product_link_id, dh.sizedefinition_link_id, dh.finishingmethod_id, rp.date_value1, prd.typeofmerchandise)
      ),0) Used_1
, currency.invoiceamountdecimals, currency.decimals, currency.code currencyCode
, languages.code languageCode
from
  deliveryhistory dh
, webusercustomer wcu left outer join webuserdepartment wde on wcu.webusercustomer_id = wde.webusercustomer_id
, webusersession
, customer cu, department_link delk, distributionpoint_link dilk
, product prd left outer join
                        ( productgroup prdgr join activity on prdgr.activity_id = activity.activity_id )
                    on prd.productgroup_id = prdgr.productgroup_id
, sizedefinition_link szlk, finishingmethod fm, customermonth cm
, currency, reportparam rp , languages
where
    dh.packindication <> 2
and dh.customer_link_id = cu.customer_id
and dh.customer_link_id= wcu.customer_id
and dh.customer_link_id = webusersession.customer_id
and dh.department_link_id = delk.department_link_id
and dh.distributionpoint_link_id = dilk.distributionpoint_link_id
and dh.product_link_id = prd.product_id
and dh.sizedefinition_link_id = szlk.sizedefinition_link_id
and dh.finishingmethod_id = fm.finishingmethod_id
and dh.customer_link_id = cm.customer_id
--AND RP.NUMBER_VALUE = CM.YEAR
--AND CM.MONTH BETWEEN RP.NUMBER_VALUE1 AND RP.NUMBER_VALUE2
and CM.YEAR*100+CM.MONTH between (RP.NUMBER_VALUE*100+RP.NUMBER_VALUE1) and (RP.NUMBER_VALUE4*100+RP.NUMBER_VALUE2)
and dh.deliverydate between cm.startdate and cm.enddate
and cu.currency_id = currency.currency_id
group by
  cu.customernumber, cu.customer_id, cu.name , delk.department_id, delk.departmentnumber, delk.description
, webusersession.websession_id, wcu.webuser_id, wde.department_id, delk.department_link_id
, dilk.distributionpoint_link_id, dilk.distributionpointnumber, dilk.description
, activity.activity_id, activity.code, prdgr.productgroup_id, prdgr.code, prd.product_id,prd.product_id, prd.code
, szlk.code, fm.finishingmethod_id, fm.code
, currency.invoiceamountdecimals, currency.decimals, currency.code
, languages.language_id, languages.code
, rp.reportparam_id, rp.number_value, rp.number_value1, rp.number_value2, rp.number_value4
/

  CREATE OR REPLACE VIEW "V_MONTHLYINVENTUTILIZ_OLDAPP" ("CUSTOMERNUMBER", "CUSTOMER_ID", "CUSTOMERNAME", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "WEBSESSION_ID", "WEBUSER_ID", "WEB_DEPARTMENT_ID", "DEPARTMENT_LINK_ID", "DISTRIBUTIONPOINT_LINK_ID", "REPORTPARAM_ID", "DISTRIBUTIONNUMBER", "DISTRIBUTIONDESC", "PATIENTDAYSDSP", "PATIENTDAYSDEP", "ACTIVITY_ID", "ACTIVITYCODE", "PRODUCTGROUP_ID", "PRODUCTGROUPCODE", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "FINISHINGCODE", "FINISHINGDESC", "AMOUNTSTANDARD", "AMOUNTDELIVERED", "PRICE", "PARLEVEL_1", "USED_1", "INVOICEAMOUNTDECIMALS", "DECIMALS", "CURRENCYCODE", "LANGUAGECODE") AS 
  select
  cu.customernumber, cu.customer_id , cu.name customerName, delk.department_id, delk.departmentnumber, delk.description departmentDesc
, websession.websession_id, wcu.webuser_id, wde.department_id web_department_id, delk.department_link_id, dilk.distributionpoint_link_id, rp.reportparam_id
, dilk.distributionpointnumber distributionNumber, dilk.description distributionDesc
, coalesce(( select SUM(pdy.patientdays) from patientday pdy where dilk.distributionpoint_link_id = pdy.distributionpoint_link_id
--  and pdy.year = rp.number_value and pdy.month between rp.number_value1 and rp.number_value2
  and pdy.year*100+pdy.month between (RP.NUMBER_VALUE*100+RP.NUMBER_VALUE1) and (RP.NUMBER_VALUE4*100+RP.NUMBER_VALUE2)
  group by dilk.distributionpoint_link_id),0) patientdaysDsp
, coalesce(( select sum(pdy.patientdays) from patientday pdy, distributionpoint_link
  where distributionpoint_link.department_link_id = delk.department_link_id
  and distributionpoint_link.distributionpoint_link_id = pdy.distributionpoint_link_id
--  and pdy.year = rp.number_value and pdy.month between rp.number_value1 and rp.number_value2
  and pdy.year*100+pdy.month between (RP.NUMBER_VALUE*100+RP.NUMBER_VALUE1) and (RP.NUMBER_VALUE4*100+RP.NUMBER_VALUE2)
  group by distributionpoint_link.department_link_id),0) patientdaysDep
, activity.activity_id ACTIVITY_ID, activity.code activityCode, prdgr.productgroup_id PRODUCTGROUP_ID, prdgr.code productgroupCode, prd.product_id PRODUCT_ID, prd.code productCode
, ( select product_link_desc.description from product_link_desc where product_link_desc.product_link_id = prd.product_id
  and product_link_desc.language_id = languages.language_id ) productDesc
, szlk.code sizeCode, fm.code Finishingcode
, ( select finishingmethod_desc.description from finishingmethod_desc where finishingmethod_desc.finishingmethod_id = fm.finishingmethod_id
  and finishingmethod_desc.language_id = languages.language_id ) FinishingDesc
, coalesce(sum(dh.amountstandard),0) amountstandard
, coalesce(sum(dh.amountdelivered),0) amountdelivered
, coalesce(sum(F_RESTOCKINGPRICE(dh.customer_link_id, dh.product_link_id, dh.sizedefinition_link_id, dh.finishingmethod_id, rp.date_value1, prd.typeofmerchandise)),0) price
, coalesce(sum(
  dh.amountstandard * F_RESTOCKINGPRICE(dh.customer_link_id, dh.product_link_id, dh.sizedefinition_link_id, dh.finishingmethod_id, rp.date_value1, prd.typeofmerchandise)
      ),0) ParLevel_1
, coalesce(sum(
  dh.amountdelivered * F_RESTOCKINGPRICE(dh.customer_link_id, dh.product_link_id, dh.sizedefinition_link_id, dh.finishingmethod_id, rp.date_value1, prd.typeofmerchandise)
      ),0) Used_1
, currency.invoiceamountdecimals, currency.decimals, currency.code currencyCode
, languages.code languageCode
from
  deliveryhistory dh
, webusercustomer wcu left outer join webuserdepartment wde on wcu.webusercustomer_id = wde.webusercustomer_id
, websession
, customer cu, department_link delk, distributionpoint_link dilk
, product prd left outer join
                        ( productgroup prdgr join activity on prdgr.activity_id = activity.activity_id )
                    on prd.productgroup_id = prdgr.productgroup_id
, sizedefinition_link szlk, finishingmethod fm, customermonth cm
, currency, reportparam rp , languages
where
    dh.packindication <> 2
and dh.customer_link_id = cu.customer_id
and dh.customer_link_id= wcu.customer_id
and dh.customer_link_id = websession.customer_id
and dh.department_link_id = delk.department_link_id
and dh.distributionpoint_link_id = dilk.distributionpoint_link_id
and dh.product_link_id = prd.product_id
and dh.sizedefinition_link_id = szlk.sizedefinition_link_id
and dh.finishingmethod_id = fm.finishingmethod_id
and dh.customer_link_id = cm.customer_id
--AND RP.NUMBER_VALUE = CM.YEAR
--AND CM.MONTH BETWEEN RP.NUMBER_VALUE1 AND RP.NUMBER_VALUE2
and CM.YEAR*100+CM.MONTH between (RP.NUMBER_VALUE*100+RP.NUMBER_VALUE1) and (RP.NUMBER_VALUE4*100+RP.NUMBER_VALUE2)
and dh.deliverydate between cm.startdate and cm.enddate
and cu.currency_id = currency.currency_id
group by
  cu.customernumber, cu.customer_id, cu.name , delk.department_id, delk.departmentnumber, delk.description
, websession.websession_id, wcu.webuser_id, wde.department_id, delk.department_link_id
, dilk.distributionpoint_link_id, dilk.distributionpointnumber, dilk.description
, activity.activity_id, activity.code, prdgr.productgroup_id, prdgr.code, prd.product_id,prd.product_id, prd.code
, szlk.code, fm.finishingmethod_id, fm.code
, currency.invoiceamountdecimals, currency.decimals, currency.code
, languages.language_id, languages.code
, rp.reportparam_id, rp.number_value, rp.number_value1, rp.number_value2, rp.number_value4
/

  CREATE OR REPLACE VIEW "V_MONTHLYUSAGEANG" ("DEPARTMENT_ID", "REPORTPARAM_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "ACTIVITYCODE", "PRODUCTGROUPCODE", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "SIZEDESC", "FINISHINGCODE", "FINISHINGDESC", "PATIENTDAYSDSP", "PATIENTDAYSDEP", "QUANTITY", "WEIGHT", "PRICE", "SOILWEIGHT", "POUNDPRICE", "COSTPRICE", "INVOICEAMOUNTDECIMALS", "PRICEDECIMALS", "CURRENCYCODE", "LANGUAGECODE") AS 
  select dpl.department_id, rp.reportparam_id,
  cu.customernumber, cu.name customername,
  -- cc.code costcentre_code, cc.description costcentre_desc,
  dpl.departmentnumber, dpl.description departmentdesc,
  dspl.distributionpointnumber, dspl.description distributionpointdesc,
  ac.code activityCode, prdgr.code productgroupCode, prd.code productCode,
  (select product_link_desc.description from product_link_desc
   where product_link_desc.product_link_id = DH.PRODUCT_LINK_ID
     and product_link_desc.language_id = languages.language_id ) productDesc,
  szl.code sizeCode,
 (select szd.description from sizedefinition_desc szd where szd.sizedefinition_id = szl.sizedefinition_link_id
     and szd.language_id = languages.language_id) sizedesc,
  fm.code Finishingcode,
  (select finishingmethod_desc.description from finishingmethod_desc
   where finishingmethod_desc.finishingmethod_id = fm.finishingmethod_id
     and finishingmethod_desc.language_id = languages.language_id ) FinishingDesc,
  coalesce((select SUM(pdy.patientdays) from patientday pdy where dspl.distributionpoint_link_id = pdy.distributionpoint_link_id
     and pdy.year = rp.copy_number and pdy.month between rp.number_value1 and rp.number_value2
     and pdy.week = 0
   GROUP BY dspl.distributionpoint_link_id),0) patientdaysDsp,
  coalesce((select sum(pdy.patientdays) from patientday pdy, distributionpoint_link
   where distributionpoint_link.department_link_id = dpl.department_link_id
     and distributionpoint_link.distributionpoint_link_id = pdy.distributionpoint_link_id
     and pdy.year = rp.copy_number and pdy.month between rp.number_value1 and rp.number_value2
     and pdy.week = 0
   group by distributionpoint_link.department_link_id),0) patientdaysDep,
  coalesce(sum(dh.amountdelivered),0) quantity,
  coalesce(sum(dh.amountdelivered *
    F_GETTHEORETICALWEIGHT(prd.theoreticalweight, prd.product_id, szl.sizedefinition_id)),0) weight,
  coalesce(
    F_RESTOCKINGPRICE_ANG(dh.customer_link_id, DH.PRODUCT_LINK_ID, szl.sizedefinition_link_id, fm.finishingmethod_id,
    rp.date_value1, prd.typeofmerchandise),0) price,
--  F_GETSOILWEIGHT(dh.customer_link_id, DH.PRODUCT_LINK_ID, szl.sizedefinition_link_id, fm.finishingmethod_id, rp.date_value1) soilweight,
  coalesce(max(dh.pieceweight),0) soilweight,
  F_GETPOUNDPRICE(DH.PRODUCT_LINK_ID, fm.finishingmethod_id, szl.sizedefinition_link_id,
    dh.customer_link_id, prd.weighingcategory_id, rp.date_value1) poundprice,
  coalesce(
  F_GETCOSTREPORTPRICE(DH.CUSTOMER_LINK_ID, prd.product_id, SZL.SIZEDEFINITION_LINK_ID, fm.finishingmethod_id, rp.date_value1,
    prd.typeofmerchandise, prd.weighingcategory_id, cur.decimals),0) costprice,
  cur.invoiceamountdecimals, cur.decimals pricedecimals,
  cur.code currencycode, languages.code languagecode
from deliveryhistory dh, customer_link cul, customer cu
  , distributionpoint_link dspl, distributionpoint dsp, costcenter cc,
  department_link dpl, sizedefinition_link szl, finishingmethod fm,
  product prd
    left outer join (productgroup prdgr join activity ac on prdgr.activity_id = ac.activity_id )
    on prd.productgroup_id = prdgr.productgroup_id,
  currency cur, languages, reportparam rp
where dh.customer_link_id = cul.customer_link_id
  and cul.customer_id = cu.customer_id
  --and cu.customer_id = cum.customer_id
  --AND RP.NUMBER_VALUE = CUM.YEAR
  --AND CUM.MONTH BETWEEN RP.NUMBER_VALUE1 AND RP.NUMBER_VALUE2
  and dh.distributionpoint_link_id = dspl.distributionpoint_link_id
  and dh.department_link_id = dpl.department_link_id
  and dh.sizedefinition_link_id = szl.sizedefinition_link_id
  and dh.finishingmethod_id = fm.finishingmethod_id
  and dh.product_link_id = prd.product_id
  and cu.currency_id = cur.currency_id
 -- and wc.customer_id = cu.customer_id
 -- and dh.deliverydate between cum.startdate and cum.enddate
  and dh.deliverydate between rp.date_value2 and rp.date_value1
  and dh.packindication <> 2
  and dspl.distributionpoint_id = dsp.distributionpoint_id
  and dsp.costcenter_id = cc.costcenter_id
  and cc.costcenter_id = rp.number_value
group by
  dpl.department_id, cu.customernumber, cu.name, dh.customer_link_id,
  cc.costcenter_id, cc.code, cc.description,
  dpl.departmentnumber, dpl.description, prd.weighingcategory_id,
  dspl.distributionpointnumber, dspl.description,
  DH.PRODUCT_LINK_ID, fm.finishingmethod_id, szl.sizedefinition_link_id,
  dspl.distributionpoint_link_id,ac.activity_id, ac.code,prdgr.productgroup_id, prdgr.code, prd.product_id, prd.code, szl.code, fm.code,
  cur.invoiceamountdecimals, languages.code, languages.language_id,
  dpl.department_link_id, prd.typeofmerchandise, cur.decimals, cur.code,
  rp.reportparam_id, rp.number_value, rp.number_value1, rp.number_value2, dh.deliverydate,
  rp.copy_number, rp.number_value6, rp.number_value3, rp.date_value1
/

  CREATE OR REPLACE VIEW "V_MONTHSPECCOSTSPERCOSTCENTER" ("DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "STREET", "ZIPCODE", "CITY", "COUNTY", "INVOICENUMBER", "INVOICEDATE", "TYPE", "STARTMONTH", "ENDMONTH", "STARTYEAR", "ENDYEAR", "COSTCENTERCODE", "COSTCENTERDESC", "INVOICELINE_ID", "COSTCENTER_ID", "CURRENCYCODE", "INVOICEAMOUNTDECIMALS") AS 
  select
  ih.deltocustomernumber, ih.deltocustomername
, cast(CONCATENATEWITHBLANK(ih.deltostreet, ih.deltostreet2) as varchar2(255)) street
  , ih.deltozipcode zipcode, ih.deltocity city, ih.deltocounty county
, ih.invoicenumber, ih.invoicedate, ilty.type
, ih.startmonth, ih.endmonth, ih.startyear, ih.endyear
, cc.code costcenterCode, cc.description costcenterDesc
, il.invoiceline_id, cc.costcenter_id
, currency.code currencyCode, currency.invoiceamountdecimals
from
  invoiceheader ih, invoiceline il
, invoicefrequency ifq, invoicelinetype ilty, status, costcenterinvoiceline ccil, costcenter cc
, currency
where
    ih.documenttype = 1   -- invoice
and (ih.invoicetype = 1 or ih.invoicetype = 4)  -- generated
and ih.status_id = status.status_id
    and status.statustype = 'IN' and status.code = '2' -- Settled (US) / Final Invoice (EU)
and ih.invoicefrequency_id = ifq.invoicefrequency_id
    and ifq.invoicefrequencynumber = 110   -- monthly
and ih.invoiceheader_id = il.invoiceheader_id
and il.invoicelinetype_id = ilty.invoicelinetype_id
    and il.invoiceline_id = ccil.invoiceline_id
        and ccil.costcenter_link_id = cc.costcenter_id
and ih.currency_id = currency.currency_id
/

  CREATE OR REPLACE VIEW "V_MONTH_INVENT_UTILIZATIONNEW" ("CUSTOMERNUMBER", "CUSTOMER_ID", "CUSTOMERNAME", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "WEBSESSION_ID", "WEBUSER_ID", "WEB_DEPARTMENT_ID", "DEPARTMENT_LINK_ID", "DISTRIBUTIONPOINT_LINK_ID", "REPORTPARAM_ID", "DISTRIBUTIONNUMBER", "DISTRIBUTIONDESC", "PATIENTDAYSDSP", "PATIENTDAYSDEP", "PATIENTDAYSCUST", "ACTIVITY_ID", "ACTIVITYCODE", "PRODUCTGROUP_ID", "PRODUCTGROUPCODE", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "FINISHINGCODE", "SIZEDESC", "FINISHINGDESC", "AMOUNTSTANDARD", "AMOUNTDELIVERED", "PRICE", "PRICEDETAIL", "POUNDPRICE", "SOILWEIGHT", "PARLEVEL_1", "USED_1", "COSTREPORTPRICE", "INVOICEAMOUNTDECIMALS", "DECIMALS", "CURRENCYCODE", "LANGUAGECODE", "BUDGETRELEVANT") AS 
  select
  cu.customernumber, cu.customer_id , cu.name customerName, delk.department_id, delk.departmentnumber, delk.description departmentDesc
, webusersession.websession_id, wcu.webuser_id, wde.department_id web_department_id, delk.department_link_id, dilk.distributionpoint_link_id, rp.reportparam_id
, dilk.distributionpointnumber distributionNumber, dilk.description distributionDesc
, coalesce(( select SUM(pdy.patientdays) from patientday pdy where dilk.distributionpoint_link_id = pdy.distributionpoint_link_id
              and pdy.year*100+pdy.month between (RP.NUMBER_VALUE*100+RP.NUMBER_VALUE1) and (RP.NUMBER_VALUE4*100+RP.NUMBER_VALUE2)
              group by dilk.distributionpoint_link_id),0) patientdaysDsp
,  coalesce((  select sum(pdy.patientdays) from patientday pdy, distributionpoint dp
              where pdy.customer_link_id=cu.customer_id
              and pdy.distributionpoint_link_id=dp.distributionpoint_id
              and dp.department_id=delk.department_id
              and pdy.year*100+pdy.month between (RP.NUMBER_VALUE*100+RP.NUMBER_VALUE1) and (RP.NUMBER_VALUE4*100+RP.NUMBER_VALUE2)
              ),0)  patientdaysDep,
coalesce(( select SUM(pdy.patientdays) from patientday pdy where pdy.customer_link_id=cu.customer_id
              and pdy.year*100+pdy.month between (RP.NUMBER_VALUE*100+RP.NUMBER_VALUE1) and (RP.NUMBER_VALUE4*100+RP.NUMBER_VALUE2)
              and pdy.distributionpoint_link_id is not null),0) patientdayscust
, activity.activity_id ACTIVITY_ID, activity.code activityCode, prdgr.productgroup_id PRODUCTGROUP_ID, prdgr.code productgroupCode, prd.product_id, prd.code productCode
, ( select product_link_desc.description from product_link_desc where product_link_desc.product_link_id = prd.product_id
              and product_link_desc.language_id = languages.language_id ) productDesc
, szlk.code sizeCode, fm.code Finishingcode
, ( select sizedefinition_desc.description from sizedefinition_desc where sizedefinition_desc.sizedefinition_id = szlk.sizedefinition_link_id
              and sizedefinition_desc.language_id = languages.language_id ) sizeDesc
, ( select finishingmethod_desc.description from finishingmethod_desc where finishingmethod_desc.finishingmethod_id = fm.finishingmethod_id
              and finishingmethod_desc.language_id = languages.language_id ) FinishingDesc
, coalesce(sum(dh.amountstandard),0) amountstandard
, coalesce(sum(dh.amountdelivered),0) amountdelivered
, coalesce(sum(F_RESTOCKINGPRICE_ANG(dh.customer_link_id, dh.product_link_id, dh.sizedefinition_link_id, dh.finishingmethod_id, rp.date_value1, prd.typeofmerchandise)),0) price
, F_RESTOCKINGPRICE_ANG(cu.customer_id, prd.product_id, szlk.sizedefinition_link_id, fm.finishingmethod_id, rp.date_value1, prd.typeofmerchandise) priceDetail
, F_GETPOUNDPRICE(prd.product_id, fm.finishingmethod_id, szlk.sizedefinition_link_id, cu.customer_id, prd.weighingcategory_id, rp.date_value1) poundprice
, coalesce(sum(dh.pieceweight),0) soilweight
, coalesce(
  SUM(dh.amountstandard  --* costreportprice --to be multiplied inside the report
     ), 0) ParLevel_1
, coalesce(
  SUM(dh.amountdelivered --* costreportprice --to be multiplied inside the report
     ), 0) Used_1
, F_GETCOSTREPORTPRICE(cu.customer_id, prd.product_id, szlk.sizedefinition_link_id, fm.finishingmethod_id, dh.deliverydate,
            prd.typeofmerchandise, prd.weighingcategory_id, currency.decimals) costreportprice
, currency.invoiceamountdecimals, currency.decimals, currency.code currencyCode
, languages.code languageCode
, plpc.budgetrelevant
from
  deliveryhistory dh
, webusercustomer wcu left outer join webuserdepartment wde on wcu.webusercustomer_id = wde.webusercustomer_id
, webusersession
, customer cu, department_link delk, distributionpoint_link dilk
, product prd, productgroup prdgr, activity
, sizedefinition_link szlk, finishingmethod fm, customermonth cm
, currency, reportparam rp , languages, productlistpercustomer plpc
where dh.packindication <> 2
and dh.customer_link_id = cu.customer_id
and dh.customer_link_id= wcu.customer_id
and dh.customer_link_id = webusersession.customer_id
and dh.department_link_id = delk.department_link_id
and dilk.department_link_id=delk.department_id
--and dh.distributionpoint_link_id = dilk.distributionpoint_link_id
and dh.product_link_id = prd.product_id
and dh.sizedefinition_link_id = szlk.sizedefinition_link_id
and dh.finishingmethod_id = fm.finishingmethod_id
and dh.customer_link_id = cm.customer_id
and CM.YEAR*100+CM.MONTH between (RP.NUMBER_VALUE*100+RP.NUMBER_VALUE1) and (RP.NUMBER_VALUE4*100+RP.NUMBER_VALUE2)
and dh.deliverydate between cm.startdate and cm.enddate
and cu.currency_id = currency.currency_id
and dh.product_link_id = plpc.product_id
and dh.customer_link_id = plpc.customer_id
and szlk.sizedefinition_id=plpc.sizedefinition_id
and fm.finishingmethod_id = plpc.finishingmethod_id
and prdgr.activity_id = activity.activity_id
and prd.productgroup_id = prdgr.productgroup_id
and plpc.dateactive <= rp.date_value1
and plpc.dateinactive >= rp.date_value2
group by
  cu.customernumber, cu.customer_id, cu.name , delk.department_id, delk.departmentnumber, delk.description
, webusersession.websession_id, wcu.webuser_id, wde.department_id, delk.department_link_id
, dilk.distributionpoint_link_id, dilk.distributionpointnumber, dilk.description
, activity.activity_id, activity.code, prdgr.productgroup_id, prdgr.code, prd.product_id, prd.code
, szlk.code, szlk.sizedefinition_link_id, fm.finishingmethod_id, fm.code
, prd.weighingcategory_id, prd.typeofmerchandise
, currency.invoiceamountdecimals, currency.decimals, currency.code
, languages.language_id, languages.code, plpc.budgetrelevant
, rp.reportparam_id, rp.number_value, rp.number_value1, rp.number_value2, rp.date_value1, rp.number_value4
, dh.deliverydate
/

  CREATE OR REPLACE VIEW "V_MOUNTINGORDER" ("CUSTOMERNUMBER", "NAME", "STREET", "ZIPCODE", "CITY", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "WORKORDER_ID", "WORKORDERNUMBER", "REFERENCENUMBER", "REQUESTDATE", "NEEDEDDATE", "MOUNTINGDATE", "REMARK", "ROUTENUMBER", "ROUTEDESCRIPTION", "DAY_DESC", "PRODUCT_CODE", "PRODUCT_DESC", "SIZE_CODE", "FINISHING_CODE", "QUALITYGRADE_CODE", "QUANTITYORDERED", "QUANTITYFIRSTDELIVERY", "SALESITEM", "STARTSERVICE", "TOBEMOUNTED", "LANGUAGE_CODE", "EMP_EMPLOYEENUMBER", "EMP_NAME", "EMP_PHONENO", "EMP_MOBILENO", "EMP_FAXNO", "EMP_EMAIL", "EMP_REMARK", "SALES1_EMPLOYEENUMBER", "SALES1_NAME", "SALES1_PHONENO", "SALES1_MOBILENO", "SALES1_FAXNO", "SALES1_EMAIL", "SALES1_REMARK", "SALES2_EMPLOYEENUMBER", "SALES2_NAME", "SALES2_PHONENO", "SALES2_MOBILENO", "SALES2_FAXNO", "SALES2_EMAIL", "SALES2_REMARK", "CODE", "DESCRIPTION", "DELIVERYPOINT_STREET", "DELIVERYPOINT_ZIPCODE", "DELIVERYPOINT_CITY", "DAY_ID", "STARTTIME", "ENDTIME", "BREAKSTARTTIME", "BREAKENDTIME", "DISTRIBUTIONPOINT_ID") AS 
  select cu.customernumber, cu.name, addr.street, addr.zipcode, addr.city
, dis.distributionpointnumber, dis.description distributionpointdescription
, wo.workorder_id, wo.workordernumber, wo.referencenumber, wo.requestdate
, wo.neededdate, wo.mountingdate, wo.remark
, ro.routenumber, ro.description routedescription
, (select day_desc.description from day_desc where ro.drivingday_id=day_desc.day_id and day_desc.language_id = lan.language_id) day_desc
, prd.code product_code
, (select prdd.description from product_desc prdd where prdd.product_id=prd.product_id and prdd.language_id = lan.language_id) product_desc
, sd.code size_code, fm.code finishing_code, qg.code qualitygrade_code
, wol.quantityordered, wol.quantityfirstdelivery, wol.salesitem, wol.startservice, wol.tobemounted
, lan.code language_code
, emp.employeenumber emp_employeenumber, emp.name emp_name, emp.phoneno emp_phoneno, emp.mobileno emp_mobileno, emp.faxno emp_faxno, emp.email emp_email, emp.remark emp_remark
, sales1_emp.employeenumber sales1_employeenumber, sales1_emp.name  sales1_name, sales1_emp.phoneno sales1_phoneno, sales1_emp.mobileno sales1_mobileno, sales1_emp.faxno sales1_faxno, sales1_emp.email sales1_email, sales1_emp.remark sales1_remark
, sales2_emp.employeenumber sales2_employeenumber, sales2_emp.name sales2_name, sales2_emp.phoneno sales2_phoneno, sales2_emp.mobileno sales2_mobileno, sales2_emp.faxno sales2_faxno, sales2_emp.email sales2_email, sales2_emp.remark sales2_remark
, dp.code, dp.description
, adr.street deliverypoint_street, adr.zipcode deliverypoint_zipcode, adr.city deliverypoint_city
, getabsdaynumber(wo.neededdate) day_id,
( select dpoh.starttime from deliverypointopeninghour dpoh  where  dp.deliverypoint_id=dpoh.deliverypoint_id
   and dis.deliverypoint_id=dp.deliverypoint_id and dpoh.day_id = getabsdaynumber(wo.neededdate))starttime,
( select dpoh.endtime from deliverypointopeninghour dpoh  where  dp.deliverypoint_id=dpoh.deliverypoint_id
   and dis.deliverypoint_id=dp.deliverypoint_id and dpoh.day_id = getabsdaynumber(wo.neededdate))endtime,
 dp.breakstarttime, dp.breakendtime, dis.distributionpoint_id
from workorder wo
     left outer join route ro on wo.route_id = ro.route_id
     left outer join customer_link cul
          left outer join customer cu
               join address addr on cu.visitaddress_id = addr.address_id
          on cul.customer_id = cu.customer_id
     on wo.customer_link_id = cul.customer_link_id
 left outer join systemuser su on wo.creationuser_id=su.systemuser_id
 left outer join employee emp on su.employee_id=emp.employee_id
left outer join employee sales1_emp on  sales1_emp.employee_id=wo.salesemployee1_id
left outer join employee sales2_emp on  sales2_emp.employee_id=wo.salesemployee2_id
, distributionpoint dis, workorderline wol, product prd, sizedefinition sd, finishingmethod fm, qualitygrade qg
--, sizedefinition_desc sdd, finishingmethod_desc fmd, modification mod
, languages lan
, deliverypoint dp
left outer join address  adr on dp.deliveryaddress_id=adr.address_id
where wo.workorder_id = wol.workorder_id and wo.origin = 10
and dis.distributionpoint_id = wo.distributionpoint_link_id
and prd.product_id = wol.product_link_id
and sd.sizedefinition_id = wol.sizedefinition_link_id
and fm.finishingmethod_id = wol.finishingmethod_id
and qg.qualitygrade_id = wol.requestedgrade_id
and dis.deliverypoint_id=dp.deliverypoint_id
/

  CREATE OR REPLACE VIEW "V_MULTIREADEXCEPTIONWITHBUNDLE" ("MULTIREADSCANBATCH_ID", "LANGUAGE_ID", "ERRORCODE", "DESCRIPTION", "BUNDLEID", "QTY") AS 
  select x.multireadscanbatch_id,
       l.language_id,
       x.multireadexception_id as errorcode,
       nvl((select ed.description
             from multireadexceptionreason_desc ed
            where ed.multireadexceptionreason_id = x.multireadexception_id
              and ed.language_id = l.language_id),
           (select e.factorydescription
              from multireadexceptionreason e
             where e.multireadexceptionreason_id = x.multireadexception_id)) description,
       x.bundleid,
       x.qty
from (
      -- uniqueitem exceptions
      select m.multireadscanbatch_id, m.multireadexception_id, substr(b.bundleprimaryid,-4,4) bundleid, count(*) qty
        from multireadscanbatchcontents m
             left outer join (uniqueitem u left outer join uhfbundle b on (b.uhfbundle_id = u.uhfbundle_id)) on (u.uniqueitem_id = m.uniqueitem_id)
       where m.multireadexception_id is not null
      group by m.multireadscanbatch_id, m.multireadexception_id, substr(b.bundleprimaryid,-4,4)
      -- container exceptions
      union all
      select m.multireadscanbatch_id, m.multireadexception_id, null bundleid, count(*) qty
        from multireadscanbatchcontknt m
       where m.multireadexception_id is not null
      group by m.multireadscanbatch_id, m.multireadexception_id
      ) x,
      languages l
/

  CREATE OR REPLACE VIEW "V_MULTIREADINSCANCONT" ("MULTIREADSCANBATCH_ID", "SUBBATCHNUMBER", "SCANTIMESTAMP", "IDCODE", "LANGUAGE_ID", "MULTIREADEXCEPTION_ID", "INFO") AS 
  select x.multireadscanbatch_id,
       x.subbatchnumber,
       x.scantimestamp,
       x.idcode,
       x.language_id,
       x.multireadexception_id,
       case when x.product_id is null
        then x.exception_desc
        else x.product_desc || x.size_desc || x.exception_desc
       end info
   from (
          select m.multireadscanbatch_id,
                 m.subbatchnumber,
                 m.scantimestamp,
                 m.idcode,
                 l.language_id,
                 m.product_id,
                 m.multireadexception_id,
                 (select pd.description || ' '  from product_desc pd where pd.product_id=m.product_id and pd.language_id=l.language_id) product_desc,
                 (select sd.description || ' '  from sizedefinition_desc sd where sd.sizedefinition_id=m.sizedefinition_id and sd.language_id=l.language_id) size_desc,
                 nvl((select ed.description || ' '  from multireadexceptionreason_desc ed where ed.multireadexceptionreason_id = m.multireadexception_id
                  and ed.language_id = 1),
                     (select e.factorydescription || ' '  from multireadexceptionreason e where e.multireadexceptionreason_id = m.multireadexception_id)) exception_desc
            from multireadscanbatchcontents m,
                 languages l
            union all
          select mk.multireadscanbatch_id,
                 mk.subbatchnumber,
                 mk.scantimestamp,
                 mk.idcode,
                 l.language_id,
                 mk.containertype_id * -1 product_id,
                 mk.multireadexception_id,
                 (select cd.description || ' '  from containertype_desc cd where cd.containertype_id = mk.containertype_id and cd.language_id=l.language_id) product_desc,
                 null size_desc,
                 nvl((select ed.description || ' '  from multireadexceptionreason_desc ed where ed.multireadexceptionreason_id = mk.multireadexception_id
                  and ed.language_id = 1),
                     (select e.factorydescription || ' '  from multireadexceptionreason e where e.multireadexceptionreason_id = mk.multireadexception_id)) exception_desc
            from multireadscanbatchcontknt mk,
                 languages l
                 ) x
/

  CREATE OR REPLACE VIEW "V_MULTIREADPACKING" ("MULTIREADSCANBATCH_ID", "PACKINGNOTELINE_ID", "LANGUAGE_ID", "PACKINGSEQUENCE", "PACKPRODUCTCODE", "CODE", "PRODDESC", "SIZEDESC", "FINMDESC", "ORDEREDQTY", "DELIVEREDQTY", "SCANNEDQTY", "SCANNEDBUNDLES", "BUNDLEQTY", "UNIQUEPOOLITEM") AS 
  select /*version 1.0*/
     z.multireadscanbatch_id,
       z.packingnoteline_id,
       z.language_id,
       z.packingsequence,
       z.packproductcode,
       z.code,
       z.proddesc,
       z.sizedesc,
       z.finmdesc,
       z.orderedqty,
       z.deliveredqty,
       z.scannedqty,
       z.scannedbundles,
       z.bundleqty,
       z.uniquepoolitem
  from (select y.multireadscanbatch_id,
               l.language_id,
               y.packingnoteline_id,
               y.packingsequence,
               y.packproductcode,
               p.code,
               p.uniquepoolitem,
               substr(y.packproductcode ||
                      (select pd.description
                         from product_desc pd
                        where pd.product_id = y.product_id
                          and pd.language_id = l.language_id),
                      1,
                      30) proddesc,
               (select sd.description
                  from sizedefinition_desc sd
                 where sd.sizedefinition_id = y.sizedefinition_id
                   and sd.language_id = l.language_id) sizedesc,
               (select fd.description
                  from finishingmethod_desc fd
                 where fd.finishingmethod_id = y.finishingmethod_id
                   and fd.language_id = l.language_id) finmdesc,
               y.orderedqty,
               case
                   when  p.uniquepoolitem = 'Y' then
                         y.scannedqty
                   else
                         y.deliveredqty
               end deliveredqty,
               y.scannedqty,
               y.scannedbundles,
               y.bundleqty
          from (select x.multireadscanbatch_id,
                       x.packingsequence,
                       x.packproductcode,
                       x.product_id,
                       x.sizedefinition_id,
                       x.finishingmethod_id,
                       x.packingnoteline_id,
                       max(orderedqty) orderedqty,
                       sum(deliveredqty) deliveredqty,
                       sum(scannedqty) scannedqty,
                       sum(scannedbundles) scannedbundles,
                       max(bundleqty) bundleqty
                  from (
                        -- 1) packingnote lines previously recorded qty and ordered qty
                        select m.multireadscanbatch_id,
                                pl.packingsequence,
                                pl.packingnoteline_id,
                                null                    packproductcode,
                                pl.product_id,
                                pl.sizedefinition_id,
                                pl.finishingmethod_id,
                                pl.tobedeliveredamount  orderedqty,
                                pl.deliveredamount      deliveredqty,
                                pl.scannedqty           scannedqty,
                                pl.scannedbundles       scannedbundles,
                                pl.bundleqty            bundleqty
                          from packingnoteline    pl,
                                multireadscanbatch m
                         where pl.packingnote_id = m.packingnote_id
                        union
                        -- 2) packingnote lines in current batch, now recorded qty
                        select /*+ ordered */
                         mbc.multireadscanbatch_id,
                          pl.packingsequence packingsequence,
                          pl.packingnoteline_id,
                          null packproductcode,
                          pl.product_id,
                          pl.sizedefinition_id,
                          pl.finishingmethod_id,
                          0 orderedqty,
                          count(*) deliveredqty,
                          count(*) scannedqty,
                          sum(pl.scannedbundles)       scannedbundles,
                          max(pl.bundleqty)            bundleqty
                          from multireadscanbatchcontents mbc,
                                packingnoteline            pl
                         where pl.packingnoteline_id = mbc.packingnoteline_id
                           and mbc.partofpackyn <> 'Y'
                           and mbc.processedyn <> 'Y'
                           and mbc.multireadexception_id is null
                         group by mbc.multireadscanbatch_id,
                                   pl.packingsequence,
                                   pl.packingnoteline_id,
                                   pl.product_id,
                                   pl.sizedefinition_id,
                                   pl.finishingmethod_id
                        union
                        -- 3) packingnote lines in current batch, now approved qty
                        select c.multireadscanbatch_id,
                                c.packingsequence,
                                c.packingnoteline_id,
                                case
                                  when c.partofpackyn = 'Y' then
                                   (select pp.code || ' '
                                      from product pp, packingnoteline pl
                                     where pl.packingnoteline_id =
                                           c.packingnoteline_id
                                       and pp.product_id = pl.product_id)
                                  else
                                   null
                                end packproductcode,
                                c.product_id,
                                c.sizedefinition_id,
                                c.finishingmethod_id,
                                0 orderedqty,
                                0 deliveredqty,
                                0 scannedqty,
                                0 scannedbundles,
                                0 bundleqty
                          from multireadscanbatchcontents c
                         where c.processedyn = 'Y'
                           and c.multireadexception_id is null
                         group by c.multireadscanbatch_id,
                                   c.packingsequence,
                                   c.packingnoteline_id,
                                   c.partofpackyn,
                                   c.product_id,
                                   c.sizedefinition_id,
                                   c.finishingmethod_id
                        union
                        -- 4) in current batch, not packingnote lines yet
                        select c.multireadscanbatch_id,
                                c.packingsequence,
                                0,
                                null packproductcode,
                                c.product_id,
                                c.sizedefinition_id,
                                c.finishingmethod_id,
                                0 orderedqty,
                                count(*) deliveredqty,
                                count(*) scannedqty,
                                0 scannedbundles,
                                0 bundleqty
                          from multireadscanbatchcontents c
                         where c.packingnoteline_id is null
                           and c.multireadexception_id is null
                           and c.processedyn <> 'y'
                         group by c.multireadscanbatch_id,
                                   c.packingsequence,
                                   c.product_id,
                                   c.sizedefinition_id,
                                   c.finishingmethod_id
                        ) x
                 group by x.multireadscanbatch_id,
                          x.packingnoteline_id,
                          x.packingsequence,
                          x.packproductcode,
                          x.product_id,
                          x.sizedefinition_id,
                          x.finishingmethod_id) y
         inner join product p
            on (p.product_id = y.product_id)
         cross join languages l) z
 order by z.packingsequence, z.packproductcode, z.code
/

  CREATE OR REPLACE VIEW "V_MULTIREADPOOLBATCH" ("MULTIREADSCANBATCH_ID", "LANGUAGE_ID", "PACKINGSEQUENCE", "PACKPRODUCTCODE", "CODE", "PRODDESC", "SIZEDESC", "FINMDESC", "ORDEREDQTY", "DELIVEREDQTY", "SCANNEDQTY", "BALANCE", "APPROVEDQTY", "ACTUALDELIVERY", "BALANCEBASEDONACTUALDELIVERY") AS 
  select z.multireadscanbatch_id,
       z.language_id,
       z.packingsequence,
       z.packproductcode,
       z.code,
       z.proddesc,
       z.sizedesc,
       z.finmdesc,
       z.orderedqty,
       z.deliveredqty,
       z.scannedqty,
       z.balance,
       z.approvedqty,
       z.actualdelivery,
       z.balancebasedonactualdelivery
  from
(select y.multireadscanbatch_id,
       l.language_id,
       y.packingsequence,
       y.packproductcode,
       p.code,
       substr(y.packproductcode || (select pd.description from product_desc pd where pd.product_id = y.product_id and pd.language_id = l.language_id),1,30) proddesc,
       (select sd.description from sizedefinition_desc sd where sd.sizedefinition_id = y.sizedefinition_id and sd.language_id = l.language_id) sizedesc,
       (select fd.description from finishingmethod_desc fd where fd.finishingmethod_id = y.finishingmethod_id and fd.language_id = l.language_id) finmdesc,
       y.orderedqty,
       y.scannedqty deliveredqty,
       y.scannedqty,
       y.orderedqty - y.scannedqty balance,
       y.approvedqty,
       y.actualdelivery,
       y.actualdelivery - y.scannedqty balancebasedonactualdelivery
  from (select x.multireadscanbatch_id,
               x.packingsequence,
               x.packproductcode,
               x.product_id,
               x.sizedefinition_id,
               x.finishingmethod_id,
               max(orderedqty) orderedqty,
               sum(deliveredqty) deliveredqty,
               sum(scannedqty) scannedqty,
               sum(approvedqty) approvedqty,
               max(actualdelivery) actualdelivery
          from (
                -- 1a) packingnote lines previously recorded qty and ordered qty
                select m.multireadscanbatch_id,
                             pl.packingsequence,
                             pl.packingnoteline_id,
                             null packproductcode,
                             pl.product_id,
                             pl.sizedefinition_id,
                             pl.finishingmethod_id,
                             pl.tobedeliveredamount orderedqty,
                             pl.deliveredamount deliveredqty,
                             pl.scannedqty scannedqty,
                             0 approvedqty,
                             pl.actualdelivery actualdelivery
                        from packingnoteline pl, multireadscanbatch m, product pr
                       where pl.packingnote_id = m.packingnote_id
                         and pr.product_id = pl.product_id
                         and pr.uniquepoolitem = 'Y'
                union
                -- 1b) packingnote lines contents previously scanned qty and ordered qty
                select m.multireadscanbatch_id,
                       pl.packingsequence,
                       pl.packingnoteline_id,
                       pp.code || ' ' packproductcode,
                       plc.product_id,
                       plc.sizedefinition_id,
                       plc.finishingmethod_id,
                       sum(pl.tobedeliveredamount*plc.quantity) orderedqty,
                       sum(nvl(plc.scannedqty,0)) deliveredqty,
                       sum(nvl(plc.scannedqty,0)) scannedqty,
                       0 approvedqty,
                       sum(pl.actualdelivery*plc.quantity) actualdelivery
                  from packingnoteline pl, packingnotelinecontent plc, multireadscanbatch m, product pr, product pp
                 where pl.packingnote_id = m.packingnote_id
                   and plc.packingnoteline_id = pl.packingnoteline_id
                   and pr.product_id = plc.product_id
                   and pr.uniquepoolitem = 'Y'
                   and pp.product_id = pl.product_id
                 group by m.multireadscanbatch_id,
                          pl.packingsequence,
                          pl.packingnoteline_id,
                          pp.code,
                          plc.product_id,
                          plc.sizedefinition_id,
                          plc.finishingmethod_id
                union
                -- 2a) packingnote lines in current batch, now recorded qty
                select /*+ ORDERED */
                       mbc.multireadscanbatch_id,
                       pl.packingsequence packingsequence,
                       pl.packingnoteline_id,
                       null packproductcode,
                       pl.product_id,
                       pl.sizedefinition_id,
                       pl.finishingmethod_id,
                       0 orderedqty,
                       count(*) deliveredqty,
                       count(*) scannedqty,
                       count(*) approvedqty,
                       0 actualdelivery
                  from multireadscanbatchcontents mbc, packingnoteline pl
                 where pl.packingnoteline_id = mbc.packingnoteline_id
                   and mbc.partofpackyn <> 'Y'
                   and mbc.processedyn <> 'Y'
                   and mbc.multireadexception_id is null
                 group by mbc.multireadscanbatch_id,
                          pl.packingsequence,
                          pl.packingnoteline_id,
                          pl.product_id,
                          pl.sizedefinition_id,
                          pl.finishingmethod_id
                union
                -- 2b) packingnote lines in current batch, now recorded qty for pack contents
                select /*+ ORDERED */
                       mbc.multireadscanbatch_id,
                       pl.packingsequence packingsequence,
                       pl.packingnoteline_id,
                       pp.code || ' ' packproductcode,
                       plc.product_id,
                       plc.sizedefinition_id,
                       plc.finishingmethod_id,
                       0 orderedqty,
                       count(*) deliveredqty,
                       count(*) scannedqty,
                       count(*) approvedqty,
                       0 actualdelivery
                  from multireadscanbatchcontents mbc, packingnoteline pl, packingnotelinecontent plc, product pp
                 where pl.packingnoteline_id = mbc.packingnoteline_id
                   and plc.packingnoteline_id = pl.packingnoteline_id
                   and plc.product_id = mbc.product_id
                   and plc.sizedefinition_id = mbc.sizedefinition_id
                   and plc.finishingmethod_id = mbc.finishingmethod_id
                   and pp.product_id = pl.product_id
                   and mbc.partofpackyn = 'Y'
                   and mbc.processedyn <> 'Y'
                   and mbc.multireadexception_id is null
                 group by mbc.multireadscanbatch_id,
                          pl.packingsequence,
                          pl.packingnoteline_id,
                          pp.code,
                          plc.product_id,
                          plc.sizedefinition_id,
                          plc.finishingmethod_id
                union
                -- 3) packingnote lines in current batch, now approved qty
                select c.multireadscanbatch_id,
                       c.packingsequence,
                       c.packingnoteline_id,
                       case when c.partofpackyn='Y'
                       then (select pp.code || ' '
                               from product pp, packingnoteline pl
                              where pl.packingnoteline_id = c.packingnoteline_id
                                and pp.product_id = pl.product_id)
                       else null
                       end packproductcode,
                       c.product_id,
                       c.sizedefinition_id,
                       c.finishingmethod_id,
                       0 orderedqty,
                       0 deliveredqty,
                       0 scannedqty,
                       count(*) approvedqty,
                       0 actualdelivery
                  from multireadscanbatchcontents c
                 where c.processedyn = 'Y'
                   and c.multireadexception_id is null
                 group by c.multireadscanbatch_id,
                          c.packingsequence,
                          c.packingnoteline_id,
                          c.partofpackyn,
                          c.product_id,
                          c.sizedefinition_id,
                          c.finishingmethod_id
                union
                -- 4) in current batch, not packingnote lines yet
                select c.multireadscanbatch_id,
                       c.packingsequence,
                       0,
                       null packproductcode,
                       c.product_id,
                       c.sizedefinition_id,
                       c.finishingmethod_id,
                       0 orderedqty,
                       count(*) deliveredqty,
                       count(*) scannedqty,
                       count(*) approvedqty,
                       0 actualdelivery
                  from multireadscanbatchcontents c
                 where c.packingnoteline_id is null
                   and c.multireadexception_id is null
                   and c.processedyn <> 'Y'
                 group by c.multireadscanbatch_id,
                          c.packingsequence,
                          c.product_id,
                          c.sizedefinition_id,
                          c.finishingmethod_id
                          ) x
         group by x.multireadscanbatch_id,
                  x.packingsequence,
                  x.packproductcode,
                  x.product_id,
                  x.sizedefinition_id,
                  x.finishingmethod_id) y
       inner join product p on (p.product_id = y.product_id)
       cross join languages l
 union all
select y.multireadscanbatch_id,
       l.language_id,
       9999999 packingsequence,
       null packproductcode,
       ct.code,
       (select ctd.description from containertype_desc ctd where ctd.containertype_id = y.containertype_id and ctd.language_id = l.language_id) proddesc,
       null sizedesc,
       null finmdesc,
       0 orderedqty,
       y.deliveredqty,
       y.scannedqty,
       0 balance,
       y.approvedqty,
       0 actualdelivery,
       0 balancebasedonactualdelivery
  from (select  x.multireadscanbatch_id,
                x.containertype_id,
                sum(x.deliveredqty) deliveredqty,
                sum(x.scannedqty) scannedqty,
                sum(x.approvedqty) approvedqty
          from (
                -- 1) packingnotecontainer lines previously added
                select /*+index(pnc XIF1PACKINGNOTECONTAINER) */
                       m.multireadscanbatch_id,
                       pnc.containertype_id,
                       count(*) deliveredqty,
                       count(*) scannedqty,
                       0 approvedqty
                  from packingnotecontainer pnc,
                       multireadscanbatch m,
                       container c
                 where pnc.packingnote_id = m.packingnote_id
                   and pnc.container_id = c.container_id
                   and length(c.primaryid) = 24 -- show only containers with UHF tags
                 group by m.multireadscanbatch_id,
                          pnc.containertype_id
                union
                -- 2) containers in current batch, now recorded qty, not processed
                select mbc.multireadscanbatch_id,
                       mbc.containertype_id,
                       count(*) deliveredqty,
                       count(*) scannedqty,
                       count(*) approvedqty
                  from multireadscanbatchcontknt mbc
                 where mbc.multireadexception_id is null
                   and mbc.containertype_id is not null
                   and mbc.containerscan_id is null -- not processed
                 group by mbc.multireadscanbatch_id,
                          mbc.containertype_id
                union
                -- 3) containers in current batch, now recorded qty, already processed
                select mbc.multireadscanbatch_id,
                       mbc.containertype_id,
                       0 deliveredqty,
                       0 scannedqty,
                       count(*) approvedqty
                  from multireadscanbatchcontknt mbc
                 where mbc.multireadexception_id is null
                   and mbc.containertype_id is not null
                   and mbc.containerscan_id is not null -- processed
                 group by mbc.multireadscanbatch_id,
                          mbc.containertype_id) x
         group by x.multireadscanbatch_id,
                  x.containertype_id) y
       inner join containertype ct on (ct.containertype_id = y.containertype_id)
       cross join languages l
   ) z
 order by z.packingsequence, z.packproductcode, z.code
/

  CREATE OR REPLACE VIEW "V_MULTIREADPOOLBATCH_SCANTIME" ("MULTIREADSCANBATCH_ID", "LANGUAGE_ID", "PACKINGSEQUENCE", "PACKPRODUCTCODE", "CODE", "PRODDESC", "SIZEDESC", "FINMDESC", "ORDEREDQTY", "DELIVEREDQTY", "SCANNEDQTY", "BALANCE", "APPROVEDQTY", "ACTUALDELIVERY", "BALANCEBASEDONACTUALDELIVERY", "LASTTIMESTAMP") AS 
  select z.multireadscanbatch_id,
       z.language_id,
       z.packingsequence,
       z.packproductcode,
       z.code,
       z.proddesc,
       z.sizedesc,
       z.finmdesc,
       z.orderedqty,
       z.deliveredqty,
       z.scannedqty,
       z.balance,
       z.approvedqty,
       z.actualdelivery,
       z.balancebasedonactualdelivery,
       z.lasttimestamp
  from
(select y.multireadscanbatch_id,
       l.language_id,
       y.packingsequence,
       y.packproductcode,
       p.code,
       substr(y.packproductcode || (select pd.description from product_desc pd where pd.product_id = y.product_id and pd.language_id = l.language_id),1,30) proddesc,
       (select sd.description from sizedefinition_desc sd where sd.sizedefinition_id = y.sizedefinition_id and sd.language_id = l.language_id) sizedesc,
       (select fd.description from finishingmethod_desc fd where fd.finishingmethod_id = y.finishingmethod_id and fd.language_id = l.language_id) finmdesc,
       y.orderedqty,
       y.deliveredqty,
       y.scannedqty,
       y.orderedqty - y.deliveredqty balance,
       y.approvedqty,
       y.actualdelivery,
       y.deliveredqty - y.actualdelivery balancebasedonactualdelivery,
       y.lasttimestamp
  from (select X.MULTIREADSCANBATCH_ID,
       X.PACKINGSEQUENCE,
       X.PACKPRODUCTCODE,
       X.PRODUCT_ID,
       X.SIZEDEFINITION_ID,
       X.FINISHINGMETHOD_ID,
       max(ORDEREDQTY) ORDEREDQTY,
       sum(DELIVEREDQTY) DELIVEREDQTY,
       sum(SCANNEDQTY) SCANNEDQTY,
       sum(APPROVEDQTY) APPROVEDQTY,
       max(ACTUALDELIVERY) ACTUALDELIVERY,
       max(lasttimestamp)  lasttimestamp
  from (
        -- 1a) packingnote lines previously recorded qty and ordered qty
        select M.MULTIREADSCANBATCH_ID,
                PL.PACKINGSEQUENCE,
                PL.PACKINGNOTELINE_ID,
                null                    PACKPRODUCTCODE,
                PL.PRODUCT_ID,
                PL.SIZEDEFINITION_ID,
                PL.FINISHINGMETHOD_ID,
                PL.TOBEDELIVEREDAMOUNT  ORDEREDQTY,
                PL.DELIVEREDAMOUNT      DELIVEREDQTY,
                PL.SCANNEDQTY           SCANNEDQTY,
                0                       APPROVEDQTY,
                PL.ACTUALDELIVERY       ACTUALDELIVERY,
                null lasttimestamp
          from PACKINGNOTELINE PL, MULTIREADSCANBATCH M, PRODUCT PR
         where PL.PACKINGNOTE_ID = M.PACKINGNOTE_ID
           and PR.PRODUCT_ID = PL.PRODUCT_ID
           and PR.UNIQUEPOOLITEM = 'Y'
        union
        -- 1b) packingnote lines contents previously scanned qty and ordered qty
        select M.MULTIREADSCANBATCH_ID,
                PL.PACKINGSEQUENCE,
                PL.PACKINGNOTELINE_ID,
                PP.CODE || ' ' PACKPRODUCTCODE,
                PLC.PRODUCT_ID,
                PLC.SIZEDEFINITION_ID,
                PLC.FINISHINGMETHOD_ID,
                sum(PL.TOBEDELIVEREDAMOUNT * PLC.QUANTITY) ORDEREDQTY,
                sum(NVL(PLC.SCANNEDQTY, 0)) DELIVEREDQTY,
                sum(NVL(PLC.SCANNEDQTY, 0)) SCANNEDQTY,
                0 APPROVEDQTY,
                sum(PL.ACTUALDELIVERY * PLC.QUANTITY) ACTUALDELIVERY,
                null lasttimestamp
          from PACKINGNOTELINE        PL,
                PACKINGNOTELINECONTENT PLC,
                MULTIREADSCANBATCH     M,
                PRODUCT                PR,
                PRODUCT                PP
         where PL.PACKINGNOTE_ID = M.PACKINGNOTE_ID
           and PLC.PACKINGNOTELINE_ID = PL.PACKINGNOTELINE_ID
           and PR.PRODUCT_ID = PLC.PRODUCT_ID
           and PR.UNIQUEPOOLITEM = 'Y'
           and PP.PRODUCT_ID = PL.PRODUCT_ID
         group by M.MULTIREADSCANBATCH_ID,
                   PL.PACKINGSEQUENCE,
                   PL.PACKINGNOTELINE_ID,
                   PP.CODE,
                   PLC.PRODUCT_ID,
                   PLC.SIZEDEFINITION_ID,
                   PLC.FINISHINGMETHOD_ID
        union
        -- 2a) packingnote lines in current batch, now recorded qty
        select /*+ ORDERED */
         MBC.MULTIREADSCANBATCH_ID,
          PL.PACKINGSEQUENCE PACKINGSEQUENCE,
          PL.PACKINGNOTELINE_ID,
          null PACKPRODUCTCODE,
          PL.PRODUCT_ID,
          PL.SIZEDEFINITION_ID,
          PL.FINISHINGMETHOD_ID,
          0 ORDEREDQTY,
          count(*) DELIVEREDQTY,
          count(*) SCANNEDQTY,
          count(*) APPROVEDQTY,
          0 ACTUALDELIVERY,
          max(MBC.SCANTIMESTAMP) lasttimestamp
          from MULTIREADSCANBATCHCONTENTS MBC, PACKINGNOTELINE PL
         where PL.PACKINGNOTELINE_ID = MBC.PACKINGNOTELINE_ID
           and MBC.PARTOFPACKYN <> 'Y'
           and MBC.PROCESSEDYN <> 'Y'
           and MBC.MULTIREADEXCEPTION_ID is null
         group by MBC.MULTIREADSCANBATCH_ID,
                   PL.PACKINGSEQUENCE,
                   PL.PACKINGNOTELINE_ID,
                   PL.PRODUCT_ID,
                   PL.SIZEDEFINITION_ID,
                   PL.FINISHINGMETHOD_ID
        union
        -- 2b) packingnote lines in current batch, now recorded qty for pack contents
        select /*+ ORDERED */
         MBC.MULTIREADSCANBATCH_ID,
          PL.PACKINGSEQUENCE PACKINGSEQUENCE,
          PL.PACKINGNOTELINE_ID,
          PP.CODE || ' ' PACKPRODUCTCODE,
          PLC.PRODUCT_ID,
          PLC.SIZEDEFINITION_ID,
          PLC.FINISHINGMETHOD_ID,
          0 ORDEREDQTY,
          count(*) DELIVEREDQTY,
          count(*) SCANNEDQTY,
          count(*) APPROVEDQTY,
          0 ACTUALDELIVERY,
          max(MBC.SCANTIMESTAMP) lasttimestamp
          from MULTIREADSCANBATCHCONTENTS MBC,
                PACKINGNOTELINE            PL,
                PACKINGNOTELINECONTENT     PLC,
                PRODUCT                    PP
         where PL.PACKINGNOTELINE_ID = MBC.PACKINGNOTELINE_ID
           and PLC.PACKINGNOTELINE_ID = PL.PACKINGNOTELINE_ID
           and PLC.PRODUCT_ID = MBC.PRODUCT_ID
           and PLC.SIZEDEFINITION_ID = MBC.SIZEDEFINITION_ID
           and PLC.FINISHINGMETHOD_ID = MBC.FINISHINGMETHOD_ID
           and PP.PRODUCT_ID = PL.PRODUCT_ID
           and MBC.PARTOFPACKYN = 'Y'
           and MBC.PROCESSEDYN <> 'Y'
           and MBC.MULTIREADEXCEPTION_ID is null
         group by MBC.MULTIREADSCANBATCH_ID,
                   PL.PACKINGSEQUENCE,
                   PL.PACKINGNOTELINE_ID,
                   PP.CODE,
                   PLC.PRODUCT_ID,
                   PLC.SIZEDEFINITION_ID,
                   PLC.FINISHINGMETHOD_ID
        union
        -- 3) packingnote lines in current batch, now approved qty
        select C.MULTIREADSCANBATCH_ID,
                C.PACKINGSEQUENCE,
                C.PACKINGNOTELINE_ID,
                case
                  when C.PARTOFPACKYN = 'Y' then
                   (select PP.CODE || ' '
                      from PRODUCT PP, PACKINGNOTELINE PL
                     where PL.PACKINGNOTELINE_ID = C.PACKINGNOTELINE_ID
                       and PP.PRODUCT_ID = PL.PRODUCT_ID)
                  else
                   null
                end PACKPRODUCTCODE,
                C.PRODUCT_ID,
                C.SIZEDEFINITION_ID,
                C.FINISHINGMETHOD_ID,
                0 ORDEREDQTY,
                0 DELIVEREDQTY,
                0 SCANNEDQTY,
                count(*) APPROVEDQTY,
                0 ACTUALDELIVERY,
                max(C.SCANTIMESTAMP) lasttimestamp
          from MULTIREADSCANBATCHCONTENTS C
         where C.PROCESSEDYN = 'Y'
           and C.MULTIREADEXCEPTION_ID is null
         group by C.MULTIREADSCANBATCH_ID,
                   C.PACKINGSEQUENCE,
                   C.PACKINGNOTELINE_ID,
                   C.PARTOFPACKYN,
                   C.PRODUCT_ID,
                   C.SIZEDEFINITION_ID,
                   C.FINISHINGMETHOD_ID
        union
        -- 4) in current batch, not packingnote lines yet
        select C.MULTIREADSCANBATCH_ID,
                C.PACKINGSEQUENCE,
                0,
                null PACKPRODUCTCODE,
                C.PRODUCT_ID,
                C.SIZEDEFINITION_ID,
                C.FINISHINGMETHOD_ID,
                0 ORDEREDQTY,
                count(*) DELIVEREDQTY,
                count(*) SCANNEDQTY,
                count(*) APPROVEDQTY,
                0 ACTUALDELIVERY,
                max(C.SCANTIMESTAMP) lasttimestamp
          from MULTIREADSCANBATCHCONTENTS C
         where C.PACKINGNOTELINE_ID is null
           and C.MULTIREADEXCEPTION_ID is null
           and C.PROCESSEDYN <> 'Y'
         group by C.MULTIREADSCANBATCH_ID,
                   C.PACKINGSEQUENCE,
                   C.PRODUCT_ID,
                   C.SIZEDEFINITION_ID,
                   C.FINISHINGMETHOD_ID) x
  group by x.multireadscanbatch_id,
                  x.packingsequence,
                  x.packproductcode,
                  x.product_id,
                  x.sizedefinition_id,
                  x.finishingmethod_id) y
       inner join product p on (p.product_id = y.product_id)
       cross join languages l
 union all
select y.multireadscanbatch_id,
       l.language_id,
       9999999 packingsequence,
       null packproductcode,
       ct.code,
       (select ctd.description from containertype_desc ctd where ctd.containertype_id = y.containertype_id and ctd.language_id = l.language_id) proddesc,
       null sizedesc,
       null finmdesc,
       0 orderedqty,
       y.deliveredqty,
       y.scannedqty,
       0 balance,
       y.approvedqty,
       0 actualdelivery,
       0 balancebasedonactualdelivery,
       y.lasttimestamp lasttimestamp
  from (select  x.multireadscanbatch_id,
                x.containertype_id,
                sum(x.deliveredqty) deliveredqty,
                sum(x.scannedqty) scannedqty,
                sum(x.approvedqty) approvedqty,
                max(x.lasttimestamp) lasttimestamp
          from (
                -- 1) packingnotecontainer lines previously added
                select /*+index(pnc XIF1PACKINGNOTECONTAINER) */
                       m.multireadscanbatch_id,
                       pnc.containertype_id,
                       count(*) deliveredqty,
                       count(*) scannedqty,
                       0 approvedqty,
                       null lasttimestamp
                  from packingnotecontainer pnc,
                       multireadscanbatch m,
                       container c
                 where pnc.packingnote_id = m.packingnote_id
                   and pnc.container_id = c.container_id
                   and length(c.primaryid) = 24 -- show only containers with UHF tags
                 group by m.multireadscanbatch_id,
                          pnc.containertype_id
                union
                -- 2) containers in current batch, now recorded qty, not processed
                select mbc.multireadscanbatch_id,
                       mbc.containertype_id,
                       count(*) deliveredqty,
                       count(*) scannedqty,
                       count(*) approvedqty,
                       max(mbc.scantimestamp) lasttimestamp
                  from multireadscanbatchcontknt mbc
                 where mbc.multireadexception_id is null
                   and mbc.containertype_id is not null
                   and mbc.containerscan_id is null -- not processed
                 group by mbc.multireadscanbatch_id,
                          mbc.containertype_id
                union
                -- 3) containers in current batch, now recorded qty, already processed
                select mbc.multireadscanbatch_id,
                       mbc.containertype_id,
                       0 deliveredqty,
                       0 scannedqty,
                       count(*) approvedqty,
                       max(mbc.scantimestamp) lasttimestamp
                  from multireadscanbatchcontknt mbc
                 where mbc.multireadexception_id is null
                   and mbc.containertype_id is not null
                   and mbc.containerscan_id is not null -- processed
                 group by mbc.multireadscanbatch_id,
                          mbc.containertype_id) x
         group by x.multireadscanbatch_id,
                  x.containertype_id) y
       inner join containertype ct on (ct.containertype_id = y.containertype_id)
       cross join languages l
   ) z
 order by z.packingsequence, z.packproductcode, z.code
/

  CREATE OR REPLACE VIEW "V_MULTIREADPOOLBATCH_TRACKONLY" ("MULTIREADSCANBATCH_ID", "LANGUAGE_ID", "PACKINGSEQUENCE", "CODE", "PRODDESC", "SIZEDESC", "FINMDESC", "SCANNEDQTY", "APPROVEDQTY") AS 
  select z.multireadscanbatch_id,
       z.language_id,
       z.packingsequence,
       z.code,
       z.proddesc,
       z.sizedesc,
       z.finmdesc,
       z.scannedqty,
       z.approvedqty
  from
(select y.multireadscanbatch_id,
       l.language_id,
       0 packingsequence,
       p.code,
       (select pd.description from product_desc pd where pd.product_id = y.product_id and pd.language_id = l.language_id) proddesc,
       (select sd.description from sizedefinition_desc sd where sd.sizedefinition_id = y.sizedefinition_id and sd.language_id = l.language_id) sizedesc,
       (select fd.description from finishingmethod_desc fd where fd.finishingmethod_id = y.finishingmethod_id and fd.language_id = l.language_id) finmdesc,
       y.scannedqty,
       y.approvedqty
  from (select x.multireadscanbatch_id,
               x.product_id,
               x.sizedefinition_id,
               x.finishingmethod_id,
               sum(scannedqty) scannedqty,
               sum(approvedqty) approvedqty
          from (
                select c.multireadscanbatch_id,
                       c.product_id,
                       c.sizedefinition_id,
                       c.finishingmethod_id,
                       count(*) scannedqty,
                       count(*) approvedqty
                  from multireadscanbatchcontents c
                 where c.multireadexception_id is null
                 group by c.multireadscanbatch_id,
                          c.product_id,
                          c.sizedefinition_id,
                          c.finishingmethod_id
                          ) x
         group by x.multireadscanbatch_id,
                  x.product_id,
                  x.sizedefinition_id,
                  x.finishingmethod_id) y
       inner join product p on (p.product_id = y.product_id)
       cross join languages l
 union all
select y.multireadscanbatch_id,
       l.language_id,
       9999999 packingsequence,
       ct.code,
       (select ctd.description from containertype_desc ctd where ctd.containertype_id = y.containertype_id and ctd.language_id = l.language_id) proddesc,
       null sizedesc,
       null finmdesc,
       y.scannedqty,
       y.approvedqty
  from (select  x.multireadscanbatch_id,
                x.containertype_id,
                sum(x.scannedqty) scannedqty,
                sum(x.approvedqty) approvedqty
          from (
                -- 1) packingnotecontainer lines previously added
                select /*+index(pnc XIF1PACKINGNOTECONTAINER) */
                       m.multireadscanbatch_id,
                       pnc.containertype_id,
                       count(*) deliveredqty,
                       count(*) scannedqty,
                       0 approvedqty
                  from packingnotecontainer pnc,
                       multireadscanbatch m,
                       container c
                 where pnc.packingnote_id = m.packingnote_id
                   and pnc.container_id = c.container_id
                   and length(c.primaryid) = 24 -- show only containers with UHF tags
                 group by m.multireadscanbatch_id,
                          pnc.containertype_id
                union
                -- 2) containers in current batch, now recorded qty, not processed
                select mbc.multireadscanbatch_id,
                       mbc.containertype_id,
                       count(*) deliveredqty,
                       count(*) scannedqty,
                       count(*) approvedqty
                  from multireadscanbatchcontknt mbc
                 where mbc.multireadexception_id is null
                   and mbc.containertype_id is not null
                   and mbc.containerscan_id is null -- not processed
                 group by mbc.multireadscanbatch_id,
                          mbc.containertype_id
                union
                -- 3) containers in current batch, now recorded qty, already processed
                select mbc.multireadscanbatch_id,
                       mbc.containertype_id,
                       0 deliveredqty,
                       0 scannedqty,
                       count(*) approvedqty
                  from multireadscanbatchcontknt mbc
                 where mbc.multireadexception_id is null
                   and mbc.containertype_id is not null
                   and mbc.containerscan_id is not null -- processed
                 group by mbc.multireadscanbatch_id,
                          mbc.containertype_id) x
         group by x.multireadscanbatch_id,
                  x.containertype_id) y
       inner join containertype ct on (ct.containertype_id = y.containertype_id)
       cross join languages l
   ) z
 order by z.packingsequence, z.code
/

  CREATE OR REPLACE VIEW "V_MULTIREADPOOLCONTAINERCONT" ("MULTIREADSCANBATCH_ID", "LANGUAGE_ID", "PACKINGSEQUENCE", "PACKPRODUCTCODE", "CODE", "PRODDESC", "SIZEDESC", "FINMDESC", "QTYSCANNED") AS 
  select z.multireadscanbatch_id,
       z.language_id,
       z.packingsequence,
       z.packproductcode,
       z.code,
       z.proddesc,
       z.sizedesc,
       z.finmdesc,
       z.qtyscanned
  from
(select y.multireadscanbatch_id,
       l.language_id,
       y.packingsequence,
       y.packproductcode,
       p.code,
       substr(y.packproductcode || (select pd.description from product_desc pd where pd.product_id = y.product_id and pd.language_id = l.language_id),1,30) proddesc,
       (select sd.description from sizedefinition_desc sd where sd.sizedefinition_id = y.sizedefinition_id and sd.language_id = l.language_id) sizedesc,
       (select fd.description from finishingmethod_desc fd where fd.finishingmethod_id = y.finishingmethod_id and fd.language_id = l.language_id) finmdesc,
       y.qtyscanned
  from (select x.multireadscanbatch_id,
               x.packingsequence,
               x.packproductcode,
               x.product_id,
               x.sizedefinition_id,
               x.finishingmethod_id,
               sum(qtyscanned) qtyscanned
          from (
                -- 1a) packingnote lines in current batch, now recorded qty
                select /*+ ORDERED */
                       mbc.multireadscanbatch_id,
                       pl.packingsequence packingsequence,
                       null packproductcode,
                       pl.product_id,
                       pl.sizedefinition_id,
                       pl.finishingmethod_id,
                       count(*) qtyscanned
                  from multireadscanbatchcontents mbc, packingnoteline pl
                 where pl.packingnoteline_id = mbc.packingnoteline_id
                   and mbc.partofpackyn <> 'Y'
                   and mbc.processedyn <> 'Y'
                   and mbc.multireadexception_id is null
                 group by mbc.multireadscanbatch_id,
                          pl.packingsequence,
                          pl.product_id,
                          pl.sizedefinition_id,
                          pl.finishingmethod_id
                union
                -- 1b) packingnote lines in current batch, now recorded qty for pack contents
                select /*+ ORDERED */
                       mbc.multireadscanbatch_id,
                       pl.packingsequence packingsequence,
                       pp.code || ' ' packproductcode,
                       plc.product_id,
                       plc.sizedefinition_id,
                       plc.finishingmethod_id,
                       count(*) qtyscanned
                  from multireadscanbatchcontents mbc, packingnoteline pl, packingnotelinecontent plc, product pp
                 where pl.packingnoteline_id = mbc.packingnoteline_id
                   and plc.packingnoteline_id = pl.packingnoteline_id
                   and plc.product_id = mbc.product_id
                   and plc.sizedefinition_id = mbc.sizedefinition_id
                   and plc.finishingmethod_id = mbc.finishingmethod_id
                   and pp.product_id = pl.product_id
                   and mbc.partofpackyn = 'Y'
                   and mbc.processedyn <> 'Y'
                   and mbc.multireadexception_id is null
                 group by mbc.multireadscanbatch_id,
                          pl.packingsequence,
                          pp.code,
                          plc.product_id,
                          plc.sizedefinition_id,
                          plc.finishingmethod_id
                union
                -- 2) packingnote lines in current batch, now approved qty
                select c.multireadscanbatch_id,
                       c.packingsequence,
                       case when c.partofpackyn='Y'
                       then (select pp.code || ' '
                               from product pp, packingnoteline pl
                              where pl.packingnoteline_id = c.packingnoteline_id
                                and pp.product_id = pl.product_id)
                       else null
                       end packproductcode,
                       c.product_id,
                       c.sizedefinition_id,
                       c.finishingmethod_id,
                       count(*) qtyscanned
                  from multireadscanbatchcontents c
                 where c.processedyn = 'Y'
                   and c.multireadexception_id is null
                 group by c.multireadscanbatch_id,
                          c.packingsequence,
                          c.packingnoteline_id,
                          c.partofpackyn,
                          c.product_id,
                          c.sizedefinition_id,
                          c.finishingmethod_id
                union
                -- 3) in current batch, not packingnote lines yet
                select c.multireadscanbatch_id,
                       c.packingsequence,
                       null packproductcode,
                       c.product_id,
                       c.sizedefinition_id,
                       c.finishingmethod_id,
                       count(*) scannedqty
                  from multireadscanbatchcontents c
                 where c.packingnoteline_id is null
                   and c.multireadexception_id is null
                   and c.processedyn <> 'Y'
                 group by c.multireadscanbatch_id,
                          c.packingsequence,
                          c.product_id,
                          c.sizedefinition_id,
                          c.finishingmethod_id
                union all
                -- 4) Items that where previously scanned for this container, on this packingnote
                select zz.multireadscanbatch_id,
                       pl.packingsequence packingsequence,
                       case when pl.product_id <> u.product_id
                       then (select pp.code || ' '
                               from product pp
                              where pp.product_id = pl.product_id)
                       else null
                       end packproductcode,
                       u.product_id,
                       u.sizedefinition_id,
                       u.finishingmethod_id,
                       count(*) qtyscanned
                  from (select m.multireadscanbatch_id, pncc.packingnoteline_id, pncc.uniqueitem_link_id
                          from multireadscanbatch m,
                               packingnotecontainer pnc,
                               packingnotecontainercontent pncc,
                               (select mc.multireadscanbatch_id,
                                       min(mc.container_id) container_id
                                  from multireadscanbatchcontknt mc
                                 where (mc.multireadexception_id is null or
                                       mc.multireadexception_id = 20)
                                   and mc.container_id is not null
                                 group by mc.multireadscanbatch_id
                                having min(mc.container_id) = max(mc.container_id)) cnt -- current container, only if there is only 1
                         where pnc.packingnote_id = m.packingnote_id
                           and pnc.container_id = cnt.container_id
                           and pncc.packingnotecontainer_id = pnc.packingnotecontainer_id
                           and cnt.multireadscanbatch_id = m.multireadscanbatch_id
                        minus -- minus the ones that are now scanned
                        select m2.multireadscanbatch_id, m2.packingnoteline_id, m2.uniqueitem_id
                          from multireadscanbatchcontents m2
                         where m2.uniqueitem_id is not null) zz,
                       uniqueitem u,
                       packingnoteline pl
                 where u.uniqueitem_id = zz.uniqueitem_link_id
                   and pl.packingnoteline_id = zz.packingnoteline_id
                 group by zz.multireadscanbatch_id,
                          pl.packingsequence,
                          pl.product_id,
                          u.product_id,
                          u.sizedefinition_id,
                          u.finishingmethod_id
                          ) x
         group by x.multireadscanbatch_id,
                  x.packingsequence,
                  x.packproductcode,
                  x.product_id,
                  x.sizedefinition_id,
                  x.finishingmethod_id) y
       inner join product p on (p.product_id = y.product_id)
       cross join languages l
   ) z
 order by z.packingsequence, z.packproductcode, z.code
/

  CREATE OR REPLACE VIEW "V_MULTIREADPOOLPNLINES" ("PACKINGNOTE_ID", "LANGUAGE_ID", "PACKINGSEQUENCE", "PACKPRODUCTCODE", "CODE", "PRODDESC", "SIZEDESC", "FINMDESC", "ORDEREDQTY", "DELIVEREDQTY", "SCANNEDQTY", "BALANCE", "ACTUALDELIVERY", "BALANCEBASEDONACTUALDELIVERY") AS 
  select z.packingnote_id,
       z.language_id,
       z.packingsequence,
       z.packproductcode,
       z.code,
       z.proddesc,
       z.sizedesc,
       z.finmdesc,
       z.orderedqty,
       z.deliveredqty,
       z.scannedqty,
       z.balance,
       z.actualdelivery,
       z.balancebasedonactualdelivery
  from
(select y.packingnote_id,
       l.language_id,
       y.packingsequence,
       y.packproductcode,
       p.code,
       substr(y.packproductcode || (select pd.description from product_desc pd where pd.product_id = y.product_id and pd.language_id = l.language_id),1,30) proddesc,
       (select sd.description from sizedefinition_desc sd where sd.sizedefinition_id = y.sizedefinition_id and sd.language_id = l.language_id) sizedesc,
       (select fd.description from finishingmethod_desc fd where fd.finishingmethod_id = y.finishingmethod_id and fd.language_id = l.language_id) finmdesc,
       y.orderedqty,
       y.scannedqty deliveredqty,
       y.scannedqty,
       y.orderedqty - y.scannedqty balance,
       y.actualdelivery,
       y.actualdelivery - y.scannedqty balancebasedonactualdelivery
  from (select x.packingnote_id,
               x.packingsequence,
               x.packproductcode,
               x.product_id,
               x.sizedefinition_id,
               x.finishingmethod_id,
               max(orderedqty) orderedqty,
               sum(deliveredqty) deliveredqty,
               sum(scannedqty) scannedqty,
               max(actualdelivery) actualdelivery
          from (
                -- 1a) packingnote lines previously recorded qty and ordered qty
                select pl.packingnote_id,
                       pl.packingsequence,
                       pl.packingnoteline_id,
                       null packproductcode,
                       pl.product_id,
                       pl.sizedefinition_id,
                       pl.finishingmethod_id,
                       pl.tobedeliveredamount orderedqty,
                       pl.deliveredamount deliveredqty,
                       pl.scannedqty scannedqty,
                       pl.actualdelivery actualdelivery
                  from packingnoteline pl, product pr
                 where pr.product_id = pl.product_id
                   and pr.uniquepoolitem = 'Y'
                union
                -- 1b) packingnote lines contents previously scanned qty and ordered qty
                select pl.packingnote_id,
                       pl.packingsequence,
                       pl.packingnoteline_id,
                       pp.code || ' ' packproductcode,
                       plc.product_id,
                       plc.sizedefinition_id,
                       plc.finishingmethod_id,
                       sum(pl.tobedeliveredamount*plc.quantity) orderedqty,
                       sum(nvl(plc.scannedqty,0)) deliveredqty,
                       sum(nvl(plc.scannedqty,0)) scannedqty,
                       sum(pl.actualdelivery*plc.quantity) actualdelivery
                  from packingnoteline pl, packingnotelinecontent plc, product pr, product pp
                 where plc.packingnoteline_id = pl.packingnoteline_id
                   and pr.product_id = plc.product_id
                   and pr.uniquepoolitem = 'Y'
                   and pp.product_id = pl.product_id
                 group by pl.packingnote_id,
                          pl.packingsequence,
                          pl.packingnoteline_id,
                          pp.code,
                          plc.product_id,
                          plc.sizedefinition_id,
                          plc.finishingmethod_id
                          ) x
         group by x.packingnote_id,
                  x.packingsequence,
                  x.packproductcode,
                  x.product_id,
                  x.sizedefinition_id,
                  x.finishingmethod_id) y
       inner join product p on (p.product_id = y.product_id)
       cross join languages l
 union all
select y.packingnote_id,
       l.language_id,
       9999999 packingsequence,
       null packproductcode,
       ct.code,
       (select ctd.description from containertype_desc ctd where ctd.containertype_id = y.containertype_id and ctd.language_id = l.language_id) proddesc,
       null sizedesc,
       null finmdesc,
       0 orderedqty,
       y.deliveredqty,
       y.scannedqty,
       0 balance,
       0 actualdelivery,
       0 balancebasedonactualdelivery
  from (select pnc.packingnote_id,
                       pnc.containertype_id,
                       count(*) deliveredqty,
                       count(*) scannedqty
                  from packingnotecontainer pnc,
                       container c
                 where pnc.container_id = c.container_id
                   and length(c.primaryid) = 24 -- show only containers with UHF tags
                 group by pnc.packingnote_id,
                          pnc.containertype_id) y
       inner join containertype ct on (ct.containertype_id = y.containertype_id)
       cross join languages l
   ) z
 order by z.packingsequence, z.packproductcode, z.code
/

  CREATE OR REPLACE VIEW "V_MULTIREADREWASHSCANCONT" ("MULTIREADSCANBATCH_ID", "SUBBATCHNUMBER", "SCANTIMESTAMP", "IDCODE", "LANGUAGE_ID", "MULTIREADEXCEPTION_ID", "INFO") AS 
  select x.multireadscanbatch_id,
       x.subbatchnumber,
       x.scantimestamp,
       x.idcode,
       x.language_id,
       x.multireadexception_id,
       case when x.product_id is null
        then x.exception_desc
        else x.product_desc || x.size_desc || x.exception_desc
       end info
   from (
          select m.multireadscanbatch_id,
                 m.subbatchnumber,
                 m.scantimestamp,
                 m.idcode,
                 l.language_id,
                 m.product_id,
                 m.multireadexception_id,
                 (select pd.description || ' '  from product_desc pd where pd.product_id=m.product_id and pd.language_id=l.language_id) product_desc,
                 (select sd.description || ' '  from sizedefinition_desc sd where sd.sizedefinition_id=m.sizedefinition_id and sd.language_id=l.language_id) size_desc,
                 nvl((select ed.description || ' '  from multireadexceptionreason_desc ed where ed.multireadexceptionreason_id = m.multireadexception_id
                  and ed.language_id = 1),
                     (select e.factorydescription || ' '  from multireadexceptionreason e where e.multireadexceptionreason_id = m.multireadexception_id)) exception_desc
            from multireadscanbatchcontents m,
                 languages l) x
/

  CREATE OR REPLACE VIEW "V_MULTIREADSTACK" ("MULTIREADSCANBATCH_ID", "SUBBATCHNUMBER", "IDCODE", "LANGUAGE_ID", "CUSTOMER_ID", "PRODUCT_ID", "SIZEDEFINITION_ID", "STACKCHECKSTACKSIZE", "STACKCHECKPACK", "STACKCHECKPRODUCTIDENTIFIED", "MULTIREADEXCEPTION_ID", "MESSAGE", "OTHER_PRODUCTS_QTY", "HEADER_DESC", "ITEMSPARTLYTAGGED") AS 
  select x.multireadscanbatch_id,
       x.subbatchnumber,
       x.idcode,
       x.language_id,
       x.customer_id,
       x.product_id,
       x.sizedefinition_id,
       x.stackcheckstacksize,
       x.stackcheckpack,
	     x.stackcheckproductidentified,
       x.multireadexception_id,
       case when x.product_id is null
        then x.idcode || ' ' || x.exception_desc
        else x.customername || x.product_desc || x.size_desc || x.exception_desc
       end message,
       x.other_products_qty,
       x.header_desc,
       x.itemspartlytagged
   from (
          select m.multireadscanbatch_id,
                 mbc.subbatchnumber,
                 mbc.idcode,
                 l.language_id,
                 mbc.relatedcustomer_id customer_id,
                 mbc.poolitemyn,
                 mbc.product_id,
                 mbc.sizedefinition_id,
                 mbc.multireadexception_id,
                 (select c.name || ' '  from customer c where c.customer_id = mbc.relatedcustomer_id) customername,
                 (select pd.description || ' '  from product_desc pd where pd.product_id=mbc.product_id and pd.language_id=l.language_id) product_desc,
                 (select sd.description || ' '  from sizedefinition_desc sd where sd.sizedefinition_id=mbc.sizedefinition_id and sd.language_id=l.language_id) size_desc,
                 nvl((select ed.description || ' '  from multireadexceptionreason_desc ed where ed.multireadexceptionreason_id = mbc.multireadexception_id
                  and ed.language_id = l.language_id),
                     (select e.factorydescription || ' '  from multireadexceptionreason e where e.multireadexceptionreason_id = mbc.multireadexception_id)) exception_desc,
                 m.stackcheckstacksize stackcheckstacksize,
                 m.stackcheckpack,
				         m.stackcheckproductidentified,
                 case when m.mixedproductsallowed = 'Y'
                   then 0
                   else
                     case when mbc.product_id is not null
                      then
                       case when m.stackcheckpack = 'N'
                         then
                           case when mbc.product_id = m.stackcheckproduct_id and mbc.sizedefinition_id = m.stackchecksize_id
                             then 0
                             else 1
                           end
                         else
                          nvl((select 0
                                 from packcontents pc
                                where pc.pack_id = m.stackcheckproduct_id
                                  and pc.product_id = mbc.product_id
                                  and pc.sizedefinition_id = mbc.sizedefinition_id),1)
                       end
                      else 0
                     end
                 end other_products_qty,
                 case when m.stackcheckpack = 'Y'
                  then
                    (select p.code from product p where p.product_id = m.stackcheckproduct_id) || ' ' ||
                    (select pd.description || ' '  from product_desc pd where pd.product_id=m.stackcheckproduct_id and pd.language_id=l.language_id)
                  else
                    (select p.code from product p where p.product_id = m.stackcheckproduct_id) || ' ' ||
                    (select pd.description || ' '  from product_desc pd where pd.product_id=m.stackcheckproduct_id and pd.language_id=l.language_id) || ' ' ||
                    (select sd.description || ' '  from sizedefinition_desc sd where sd.sizedefinition_id=m.stackchecksize_id and sd.language_id=l.language_id)
                 end header_desc,
                 m.itemspartlytagged
            from multireadscanbatch m,
                 multireadscanbatchcontents mbc,
                 languages l
           where mbc.multireadscanbatch_id = m.multireadscanbatch_id
           ) x
/

  CREATE OR REPLACE VIEW "V_MULTIREADSTACKEXCEPTIONS" ("MULTIREADSCANBATCH_ID", "IDCODE", "LANGUAGE_ID", "MULTIREADEXCEPTION_ID", "PRODUCT_DESC", "SIZE_DESC", "EXCEPTION_DESC", "PRODUCT_ID") AS 
  select m.multireadscanbatch_id,
       m.idcode,
       l.language_id,
       m.multireadexception_id,
       (select pd.description
          from product_desc pd
         where pd.product_id = m.product_id
           and pd.language_id = l.language_id) product_desc,
       (select sd.description
          from sizedefinition_desc sd
         where sd.sizedefinition_id = m.sizedefinition_id
           and sd.language_id = l.language_id) size_desc,
       nvl((select ed.description
             from multireadexceptionreason_desc ed
            where ed.multireadexceptionreason_id = m.multireadexception_id
              and ed.language_id = l.language_id),
           (select e.factorydescription
              from multireadexceptionreason e
             where e.multireadexceptionreason_id = m.multireadexception_id)) exception_desc,
			 m.product_id
  from multireadscanbatchcontents m, languages l
 where m.multireadexception_id is not null
/

  CREATE OR REPLACE VIEW "V_MULTIREADSTACKORPACK" ("MULTIREADSCANBATCH_ID", "LANGUAGE_ID", "STACKCHECKPACK", "STACKCHECKPRODUCTIDENTIFIED", "HEADER_DESC", "STACKCHECKSTACKSIZE", "PRODUCT_DESC", "SIZE_DESC", "PACK_QTY", "SCAN_QTY", "STATUS_NUMBER", "STATUS_QTY", "MISSING_QTY", "OTHER_PRODUCTS_QTY", "MIXED_CUSTOMERS", "PRODUCT_ID", "RELATEDCUSTOMER_ID", "CUSTOMERNAME", "STACKPRODUCT_ID", "STACKSIZE_ID", "MIXED_CUSTOMERS_IGNORE_POOL") AS 
  select m.multireadscanbatch_id,
       l.language_id,
       m.stackcheckpack,
       m.stackcheckproductidentified,
       case when m.stackcheckpack = 'Y'
        then
          (select p.code from product p where p.product_id = m.stackcheckproduct_id) || ' ' ||
          (select pd.description || ' '  from product_desc pd where pd.product_id=m.stackcheckproduct_id and pd.language_id=l.language_id)
        else
          (select p.code from product p where p.product_id = m.stackcheckproduct_id) || ' ' ||
          (select pd.description || ' '  from product_desc pd where pd.product_id=m.stackcheckproduct_id and pd.language_id=l.language_id) || ' ' ||
          (select sd.description || ' '  from sizedefinition_desc sd where sd.sizedefinition_id=m.stackchecksize_id and sd.language_id=l.language_id)
       end header_desc,
       m.stackcheckstacksize,
       (select pd.description || ' '  from product_desc pd where pd.product_id=z.product_id and pd.language_id=l.language_id) product_desc,
       (select sd.description || ' '  from sizedefinition_desc sd where sd.sizedefinition_id=z.sizedefinition_id and sd.language_id=l.language_id) size_desc,
       z.pack_qty pack_qty,
       z.scan_qty scan_qty,
       case when laundrycode = 'PED'
        then
         case when m.stackcheckproduct_id is null
           then 4 -- exception
           else
             case when z.pack_qty = 0 and m.mixedproductsallowed <> 'Y' -- not in pack
               then 3 -- other products
               else case when z.pack_qty = z.scan_qty or (m.itemspartlytagged = 'Y' and z.pack_qty > z.scan_qty) or (z.total_scanned = m.stackcheckstacksize)
                     then 0 -- okay
                     else case when z.pack_qty > z.scan_qty
                           then 1 -- missing qty
                           else 2 -- exceeding qty
                          end
                    end
             end
         end
       else
         case when m.mixedproductsallowed = 'Y' then 0
           else
             case when m.stackcheckproduct_id is null
               then 4 -- exception
               else
                 case when z.pack_qty = 0  -- not in pack
                   then 3 -- other products
                   else case when z.pack_qty = z.scan_qty or (m.itemspartlytagged = 'Y' and z.pack_qty > z.scan_qty)
                         then 0 -- okay
                         else case when z.pack_qty > z.scan_qty
                               then 1 -- missing qty
                               else 2 -- exceeding qty
                              end
                        end
                 end
            end
         end
       end status_number,
       case when (m.itemspartlytagged = 'Y' and z.pack_qty > z.scan_qty) or
                 (m.mixedproductsallowed = 'Y' and laundrycode <> 'PED') or
                 (m.stackcheckstacksize = z.total_scanned and laundrycode = 'PED')
         then 0
         else abs(z.pack_qty - z.scan_qty)
       end status_qty,
       case when m.stackcheckproduct_id is null or
                 (m.itemspartlytagged = 'Y' and (z.pack_qty > z.scan_qty or z.pack_qty=0)) or
                 (m.mixedproductsallowed = 'Y' and laundrycode <> 'PED') or
                 (m.stackcheckstacksize = z.total_scanned and laundrycode = 'PED')
         then 0
         else z.pack_qty - z.scan_qty
       end missing_qty,  -- negative when exceeding
       case when m.stackcheckproduct_id is null or m.mixedproductsallowed = 'Y'
         then 0
         else  case when z.pack_qty = 0 -- not in pack
                  then z.scan_qty
                  else 0
               end
       end other_products_qty,
       z.mixed_customers,
       z.product_id,
       m.relatedcustomer_id,
      (select c.searchname from customer c where c.customer_id = m.relatedcustomer_id) customername,
       m.stackcheckproduct_id as stackproduct_id,
       m.stackchecksize_id as stacksize_id,
       z.mixed_customers_ignore_pool
 from multireadscanbatch m,
      languages l,
(select y.multireadscanbatch_id,
       y.product_id,
       y.sizedefinition_id,
       sum(y.pack_qty) pack_qty,
       sum(y.scan_qty) scan_qty,
       sum(case when nvl(y.relatedcustomer_id,-1) <> nvl(y.headercustomer_id,-1) then 1 else 0 end) mixed_customers,
       sum(case when nvl(y.relatedcustomer_id,-1) <> nvl(y.headercustomer_id,-1) and nvl(y.relatedcustomer_id,-1) <> -1 then 1 else 0 end) mixed_customers_ignore_pool,
       (select min(d.code) from databasesettings d) laundrycode,
       (select count(*) from multireadscanbatchcontents mb where mb.multireadscanbatch_id = y.multireadscanbatch_id) total_scanned
from
(
-- Union of 3 parts :
-- part 1: pack contents when it is a pack
select mb.multireadscanbatch_id, 'Pack' type, pc.product_id, pc.sizedefinition_id, trunc(pc.amount) pack_qty, 0 scan_qty,
       null relatedcustomer_id, null headercustomer_id
  from multireadscanbatch mb,
       packcontents pc
where pc.pack_id = mb.stackcheckproduct_id
  and mb.stackcheckpack = 'Y'
  and pc.uniquelycoded = 'Y'
union all
-- part 2: stack info when it is a not a pack
select mb.multireadscanbatch_id, 'Stack' type, mb.stackcheckproduct_id, mb.stackchecksize_id, mb.stackcheckstacksize pack_qty, 0 scan_qty,
       null relatedcustomer_id, null headercustomer_id
  from multireadscanbatch mb
where mb.stackcheckpack = 'N'
-- part 3: scanned items in batch
union all
select mb.multireadscanbatch_id, 'Scan' type,  mbc.product_id, mbc.sizedefinition_id, 0 pack_qty, 1 scan_qty,
       mbc.relatedcustomer_id relatedcustomer_id, mb.relatedcustomer_id headercustomer_id
  from multireadscanbatch mb,
       multireadscanbatchcontents mbc
 where mbc.multireadscanbatch_id = mb.multireadscanbatch_id
) y
group by y.multireadscanbatch_id, y.product_id, y.sizedefinition_id) z
where z.multireadscanbatch_id = m.multireadscanbatch_id
order by 7,8
/

  CREATE OR REPLACE VIEW "V_NAMELABEL_PLPC" ("CUSTOMER_ID") AS 
  select plpc.customer_id
  from wearerinventory wi, productlistpercustomer plpc, uniqueitem  ui
 where ui.lastweareremployment_link_id = wi.weareremployment_id
   and wi.product_id = plpc.product_id
   and wi.sizedefinition_id = plpc.sizedefinition_id
   and wi.finishingmethod_id = plpc.finishingmethod_id
   and plpc.emblemtemplate_id is not null
/

  CREATE OR REPLACE VIEW "V_NETIDHISTORY" ("NETID", "LASTOUTSCANDATE", "LASTISSUEDATE", "BUSINESSUNIT_ID", "CLEANCYCLES", "DISTRIBUTIONPOINTNUMBER", "DEPARTMENTNUMBER", "CUSTOMERNUMBER", "CUSTOMER_ID", "NAME", "STREET", "STREET2", "CITY", "STATE", "ZIPCODE", "WEARERNUMBER", "DATEACTIVE", "DATEINACTIVE", "ROOM", "BED", "ISRAG", "PLANTCODE", "PLANTNAME", "PLANTPHONE", "PLANTFAX", "PLANTWEBSITE", "PLANTSTREET", "PLANTSTREET2", "PLANTCITY", "PLANTCOUNTY", "PLANTZIP", "PLANTSTATE") AS 
  select ui.primaryid NetID, ui.lastoutscandate, uif.lastissuedate, ui.businessunit_id
       , (ui.washestotal + uinp.washesthisissue)  cleanCycles
       , dp.distributionpointnumber, d.departmentnumber
       , c.customernumber, c.customer_id, c.name, a.street, a.street2, a.city, a.state, a.zipcode
       , w.wearernumber, w.dateactive, w.dateinactive
       , coalesce(lk.bank,'') Room, coalesce(lk.locker,'') Bed, 0 isRag
       , pl.code plantcode, pl.name plantname, pl.phoneno plantphone, pl.faxno plantfax, pl.website plantwebsite
       , pla.street plantstreet, pla.street2 plantstreet2, pla.city plantcity, pla.county plantcounty
       , pla.zipcode plantzip, pla.state plantstate
from uniqueitem ui, uniqueitemnonpool uinp, uniqueitemfixedinfo uif
     , wearer w, customer c, address a, weareremployment we
     left outer join locker lk on we.locker_id = lk.locker_id
     , distributionpoint dp, department d
     , businessunit bu, plant pl, address pla
where ui.uniqueitem_id = uinp.uniqueitem_id
      and ui.uniqueitem_id = uif.uniqueitem_id
      and uinp.weareremployment_id = we.weareremployment_id
      and we.wearer_id = w.wearer_id
      and we.distributionpoint_id = dp.distributionpoint_id
      and dp.department_id = d.department_id
      and d.customer_id = c.customer_id
      and c.visitaddress_id = a.address_id
      and ui.businessunit_id = bu.businessunit_id
      and bu.plant_id = pl.plant_id
      and pl.address_id = pla.address_id
UNION ALL
select ri.primaryid NetID, ri.ragtimestamp lastoutscandate, ri.lastissuedate, ri.businessunit_id
       , (ri.washestotal)  cleanCycles
       , dp.distributionpointnumber, d.departmentnumber
       , c.customernumber, c.customer_id, c.name, a.street, a.street2, a.city, a.state, a.zipcode
       , w.wearernumber, w.dateactive, w.dateinactive
       , coalesce(lk.bank,'') Room, coalesce(lk.locker,'') Bed, 1 isRag
       , pl.code plantcode, pl.name plantname, pl.phoneno plantphone, pl.faxno plantfax, pl.website plantwebsite
       , pla.street plantstreet, pla.street2 plantstreet2, pla.city plantcity, pla.county plantcounty
       , pla.zipcode plantzip, pla.state plantstate
from raggeditem ri, wearer w, customer c, address a
     , weareremployment we
     left outer join locker lk on we.locker_id = lk.locker_id
     , distributionpoint dp, department d
     , businessunit bu, plant pl, address pla
where ri.weareremployment_link_id = we.weareremployment_id
      and we.wearer_id = w.wearer_id
      and we.distributionpoint_id = dp.distributionpoint_id
      and dp.department_id = d.department_id
      and d.customer_id = c.customer_id
      and c.visitaddress_id = a.address_id
      and ri.businessunit_id = bu.businessunit_id
      and bu.plant_id = pl.plant_id
      and pl.address_id = pla.address_id
/

  CREATE OR REPLACE VIEW "V_NETVOLUME" ("ARTRANSACTION_ID", "DEBITCREDIT", "SALESJOURNALCODE", "ARTRANSACTIONDATE", "PAYMENTTYPE", "BUSINESSUNITCODE", "BUSINESSUNITDESC", "AMOUNT", "ROUTENUMBER") AS 
  select d.artransaction_id, D.debitcredit, a.code salesjournalcode, d.artransactiondate artransactiondate, d.paymenttype,
  f.code businessunitcode, f.description businessunitdesc, c.amount, e.routenumber
from salesjournalgroup a, turnovergroup b, artransactiondetail c, artransaction d, route e,
  businessunit f, artransactiontype g
where a.salesjournalgroup_id = b.salesjournalgroup_id
  and b.turnovergroup_id = c.turnovergroup_id
  and c.artransaction_id = d.artransaction_id
  and d.businessunit_id = f.businessunit_id
  and d.route_id = e.route_id
  and d.artransactiontype_id = g.artransactiontype_id
  and g.typenumber = 1
  and g.debitcredit = 'D'
/

  CREATE OR REPLACE VIEW "V_NEWCUSTOMERANALYSIS" ("BUSINESSUNITCODE", "MARKETSEGMENTCODE", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMERDATEACTIVE", "INVOICEDATE", "INVOICENUMBER", "EMPLOYEENUMBER", "EMPLOYEENAME", "MASTERACCOUNT", "CHAINCODE", "SALESAREACODE", "MASTERNUMBER", "TURNOVERGROUPCODE", "TURNOVERGROUPDESCRIPTION", "AMOUNT", "COMMISSIONPERCENTAGE", "COMMISSIONAMOUNT", "ROUTENUMBER", "ROUTEDESC", "CURRENCYCODE", "CURRENCYDECIMALS", "LANGUAGECODE", "PROC_BU_CODE") AS 
  select
  bu.code businessunitCode,marketsegment.code marketsegmentCode, cu.customernumber, cu.name CustomerName
, cu.dateactive CustomerDateActive, invoiceheader.invoicedate
, invoiceheader.invoicenumber, employee.employeenumber
, employee.name employeeName, cu.masteraccount , chain.code chainCode, salesarea.code salesareaCode
, ( select customer.customernumber from customer where customer.customer_id = cu.masteraccount_id
  and cu.masteraccount <> 1 ) MasterNumber
, turnovergroup.code turnovergroupCode
, ( select description from turnovergroup_desc where turnovergroup_desc.turnovergroup_id = turnovergroup.turnovergroup_id
  and turnovergroup_desc.language_id = languages.language_id ) turnovergroupdescription
, artd.amount,  plantturnovergroup.commissionpercentage
, ( artd.amount * plantturnovergroup.commissionpercentage / 100 ) CommissionAmount
/* , (select turnovergroup.turnovergroup_id from states where states.turnovergroup_id = turnovergroup.turnovergroup_id
group by turnovergroup.turnovergroup_id ) taxes, turnovergroup.turnovergroup_id */
, case when F_ROUTEID(cu.customer_id) = -1 then -1
         else ( select route.routenumber from route where F_ROUTEID(cu.customer_id) = route.route_id ) -- msSql compatibility
               end routenumber -- -1 = multiple , null = No route , any other value = route number
, ( select route.description from route where F_ROUTEID(cu.customer_id) = route.route_id ) routeDesc -- msSql comptibility
, currency.code currencyCode, currency.decimals currencyDecimals, languages.code languageCode
, procbu.code Proc_BU_Code
from
  artransaction art, artransactiondetail artd, turnovergroup, plantturnovergroup, invoiceheader
, businessunit bu, currency, artransactiontype arty
, customer cu
    left outer join chain on cu.chain_id = chain.chain_id
    -- msSql compatibility -- left outer join route on F_ROUTEID(cu.customer_id) = route.route_id -- -1 = multiple, -2 = No route, any other value = route_id
, salesarea, employee, marketsegment
, languages
, businessunit procbu
where
    art.debitcredit = 'D'
and art.artransactiontype_id = arty.artransactiontype_id
and arty.debitcredit = 'D'
and arty.typenumber = 1
and turnovergroup.turnovergroup_id <> /* remove turnovergroups used for taxes */
    coalesce ( ( select turnovergroup.turnovergroup_id from states
                   where states.turnovergroup_id = turnovergroup.turnovergroup_id
                   group by turnovergroup.turnovergroup_id ), -13)
and art.artransaction_id = artd.artransaction_id
    and artd.turnovergroup_id = turnovergroup.turnovergroup_id
        and turnovergroup.turnovergroup_id = plantturnovergroup.turnovergroup_id
--        and bu.plant_id = plantturnovergroup.plant_id --todo4364
        and procbu.plant_id = plantturnovergroup.plant_id --501622
and art.invoiceheader_id = invoiceheader.invoiceheader_id
and art.businessunit_id = bu.businessunit_id
and art.deltocustomer_link_id = cu.customer_id
    and cu.marketsegment_id = marketsegment.marketsegment_id
    and cu.salesarea_id = salesarea.salesarea_id
        and salesarea.responsibleemployee_id = employee.employee_id
and art.currency_id = currency.currency_id
and art.processbusinessunit_id = procbu.businessunit_id
/

  CREATE OR REPLACE VIEW "V_NEXTDELIVERYDATE" ("CUSTOMERNUMBER", "NEXTDELIVERYDATE", "ROUTENUMBER", "LEGACYCUSTOMERNUMBER", "CUSTOMER_ID", "DRIVINGDAY_ID", "STOPNUMBER") AS 
  select /*view v_nextdeliverydate version 0.2*/
x.customernumber, x.nextdeliverydate, nvl(y.routenumber, z.routenumber) routenumber,
x.legacycustomernumber, x.customer_id, x.drivingday_id, nvl(y.stopnumber, z.stopnumber) stopnumber
from   (select z.customernumber, z.customer_id, z.legacycustomernumber, z.nextdeliverydate,
                getabsdaynumber(z.nextdeliverydate) drivingday_id
         from   (select c.customernumber, c.customer_id, c.legacycustomernumber,
                         f_getnextdeliverydate(trunc(sysdate + 1), c.customer_id, 1, null) nextdeliverydate
                  from   customer c
                  where  c.active = 'Y') z) x
left   outer join (select max(r.routenumber) routenumber, rs.customer_id,
                          max(rs.stopnumber) stopnumber, r.drivingday_id
                   from   routestop rs
                   join   route r
                   on     r.route_id = rs.route_id
                   where  trunc(sysdate + 1) between rs.dateactive and rs.dateinactive
                   and    r.active = 'Y'
                   group  by rs.customer_id, r.drivingday_id) y
on     y.customer_id = x.customer_id
and    y.drivingday_id = x.drivingday_id
left   outer join (select max(r.routenumber) routenumber, rs.customer_id,
                          max(rs.stopnumber) stopnumber, r.drivingday_id
                   from   routestop rs
                   join   route r
                   on     r.route_id = rs.route_id
                   where  rs.dateinactive >= trunc(sysdate + 1)
                   and    r.active = 'Y'
                   group  by rs.customer_id, r.drivingday_id) z
on     z.customer_id = x.customer_id
and    z.drivingday_id = x.drivingday_id
/

  CREATE OR REPLACE VIEW "V_NONBUSINESSDAY" ("CUSTOMERNUMBER", "NAME", "DEPARTMENTNUMBER", "DESCRIPTION", "NONBUSINESSDAY", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION,
 NONBUSINESSDAY.NONBUSINESSDAY, NONBUSINESSDAY.SYSTEMUSER_ID, NONBUSINESSDAY.TIMESTAMP
       FROM NONBUSINESSDAY, CUSTOMER, DEPARTMENT
       WHERE NONBUSINESSDAY.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
and NONBUSINESSDAY.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
/

  CREATE OR REPLACE VIEW "V_NONGARMENTZERORENTQTY" ("LINETYPE", "BUSINESSUNIT_ID", "INVBUCODE", "INVBUDESC", "CLUSTER_ID", "CLUSTERCODE", "CLUSTERDESC", "INVOICEFREQUENCY_ID", "INVOICEFREQUENCYNUMBER", "FACTORYDESCRIPTION", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "CUSTOMERNUMBER", "NAME", "PRODUCTCODE", "SIZECODE", "FINISHINGCODE", "PRODUCTDESC", "SIZEDESC", "FINISHINGDESC", "DELIVSCHEMEDESC", "DATEACTIVE", "DATEINACTIVE", "ZERORENTQUANTITY", "LAGUAGECODE", "REPORTPARAM_ID") AS 
  select 1 linetype,
       ibu.businessunit_id, ibu.code InvBuCode, ibu.description InvBuDesc,
       cc.cluster_id, cc.code ClusterCode, cc.description ClusterDesc,
       -1 invoicefrequency_id, -1 invoicefrequencynumber, '' factorydescription,
       dep.departmentnumber, dep.description DepartmentDesc, dis.distributionpointnumber, dis.description DistributionpointDesc,
       cu.customernumber, cu.name, p.code ProductCode, sd.code SizeCode, fm.code FinishingCode,
       (select pd.description from product_desc pd where p.product_id = pd.product_id and pd.language_id = lan.language_id) ProductDesc,
       (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sd.sizedefinition_id and sdd.language_id = lan.language_id) SizeDesc,
       (select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id =fm.finishingmethod_id and fmd.language_id = lan.language_id) FinishingDesc,
       (select dsd.description from deliveryscheme_desc dsd where dsd.deliveryscheme_id = sdl.deliveryscheme_id and dsd.language_id = lan.language_id) DelivSchemeDesc,
       sdl.dateactive, sdl.dateinactive,
       case when plpc.billingmethod = 1 then sdl.fixedrentquantity
       else coalesce((select sum(rqa.quantity) from rentalqtyadjustment rqa where rqa.productlistperdistribpoint_id = sdl.productlistperdistribpoint_id), 0)
       end ZeroRentQuantity,
       lan.code LaguageCode, rp.reportparam_id
from businessunit ibu, customer cu, customercluster cc, customerspercluster cpc
     , department dep, distributionpoint dis, standarddelivery st
     , productlistpercustomer plpc, standarddeliveryline sdl
     , product p, sizedefinition sd, finishingmethod fm, languages lan
     , reportparam rp
where p.typeofmerchandise = 1 and plpc.billingmethod in (1, 3)
      and dis.department_id = dep.department_id and dep.customer_id = cu.customer_id
      and cu.active='Y' and cu.dateactive<=trunc(sysdate) and cu.dateinactive>trunc(sysdate)
      and cpc.cluster_id = cc.cluster_id and cpc.customer_id = cu.customer_id and dis.distributionpoint_id = st.distributionpoint_id
      and cu.customer_id = plpc.customer_id and plpc.product_id = p.product_id
      and plpc.sizedefinition_id = sd.sizedefinition_id and plpc.finishingmethod_id = fm.finishingmethod_id
      and sdl.productlistpercustomer_id = plpc.productlistpercustomer_id and sdl.standarddelivery_id = st.standarddelivery_id
      and exists (select * from customeractivities ca where ca.customer_id = cu.customer_id and ca.invoicebusinessunit_id = ibu.businessunit_id)
       AND SDL.DATEACTIVE <= rp.date_value1
       AND SDL.DATEINACTIVE >= rp.date_value1
       AND (sdl.season_id is null or
           (sdl.season_id is not null and
           EXISTS (select season.season_id from seasonweek sw, season
                  where season.season_id = sdl.season_id and sw.season_id = SEASON.Season_Id
                  and sw.weeknumber = getisoweek(rp.date_value1))))
  AND ISTEMPORARYDELIVERYSTOP3(getyearofweek(rp.date_value1), getisoweek(rp.date_value1), sdl.standarddeliveryline_id) + ISTEMPORARYDELIVERYSTOP_DATE(rp.date_value1, sdl.standarddeliveryline_id) = 0
union all
select 2 linetype,
       ibu.businessunit_id, ibu.code InvBuCode, ibu.description InvBuDesc,
       -1 cluster_id, '' ClusterCode, '' ClusterDesc,
       if.invoicefrequency_id, if.invoicefrequencynumber, if.factorydescription,
       dep.departmentnumber, dep.description DepartmentDesc, dis.distributionpointnumber, dis.description DistributionpointDesc,
       cu.customernumber, cu.name, p.code ProductCode, sd.code SizeCode, fm.code FinishingCode,
       (select pd.description from product_desc pd where p.product_id = pd.product_id and pd.language_id = lan.language_id) ProductDesc,
       (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sd.sizedefinition_id and sdd.language_id = lan.language_id) SizeDesc,
       (select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id =fm.finishingmethod_id and fmd.language_id = lan.language_id) FinishingDesc,
       (select dsd.description from deliveryscheme_desc dsd where dsd.deliveryscheme_id = sdl.deliveryscheme_id and dsd.language_id = lan.language_id) DelivSchemeDesc,
       sdl.dateactive, sdl.dateinactive,
       case when plpc.billingmethod = 1 then sdl.fixedrentquantity
       else coalesce((select sum(rqa.quantity) from rentalqtyadjustment rqa where rqa.productlistperdistribpoint_id = sdl.productlistperdistribpoint_id), 0)
       end ZeroRentQuantity,
       lan.code LaguageCode, rp.reportparam_id
from businessunit ibu, customer cu, invoicefrequency if, department dep, distributionpoint dis
     , productlistpercustomer plpc, standarddeliveryline sdl, standarddelivery st
     , product p, sizedefinition sd, finishingmethod fm, languages lan
     , reportparam rp
where p.typeofmerchandise = 1 and plpc.billingmethod in (1, 3)
      and dis.department_id = dep.department_id and dep.customer_id = cu.customer_id
      and cu.invoicefrequency_id = if.invoicefrequency_id and dis.distributionpoint_id = st.distributionpoint_id
      and cu.customer_id = plpc.customer_id and plpc.product_id = p.product_id
      and cu.active='Y' and cu.dateactive<=trunc(sysdate) and cu.dateinactive>trunc(sysdate)
      and plpc.sizedefinition_id = sd.sizedefinition_id and plpc.finishingmethod_id = fm.finishingmethod_id
      and sdl.productlistpercustomer_id = plpc.productlistpercustomer_id and sdl.standarddelivery_id = st.standarddelivery_id
      AND cu.dateactive <= rp.date_value1
      AND cu.dateinactive >= rp.date_value1
      and exists (select * from customeractivities ca where ca.customer_id = cu.customer_id and ca.invoicebusinessunit_id = ibu.businessunit_id)
      AND SDL.DATEACTIVE <= rp.date_value1
      AND SDL.DATEINACTIVE >= rp.date_value1
      AND (sdl.season_id is null or
           (sdl.season_id is not null and
           EXISTS (select season.season_id from seasonweek sw, season
                  where season.season_id = sdl.season_id and sw.season_id = SEASON.Season_Id
                  and sw.weeknumber = getisoweek(rp.date_value1))))
  AND ISTEMPORARYDELIVERYSTOP3(getyearofweek(rp.date_value1), getisoweek(rp.date_value1), sdl.standarddeliveryline_id) + ISTEMPORARYDELIVERYSTOP_DATE(rp.date_value1, sdl.standarddeliveryline_id) = 0
/

  CREATE OR REPLACE VIEW "V_NONWEARERPRODUCTPRESENTATION" ("PRODUCT_ID", "SIZEDEFINITION_ID", "FINISHINGMETHOD_ID", "CUSTOMERID", "ENDDATE", "PRODUCTCODE", "SIZECODE", "FINMETHCODE", "BILLINGMETHOD", "CHANGESPERWEEK", "RENTPRICEPERFREQUENCY", "MINIMUMTURNAROUND", "MINIMUMQUANTITY", "DELAYEDEVENEXCHANGE", "STARTDATE", "LANGUAGECODE", "RENTALPRICE", "WASHPRICE", "DELIVERYDAY", "PRODUCTDESCRIPTION", "CIRCULATINGINVENTORY", "SIZE_DESC", "CUSTOMERLASTINCREASE", "GENERALLASTINCREASE", "CURRENCYDECIMALS") AS 
  select /* version 2.2*/
       prd.product_id, sd.sizedefinition_id, fm.finishingmethod_id, plpc.customer_id customerid, plpc.dateinactive enddate,
       prd.code productcode, sd.code sizecode ,fm.code finmethcode, plpc.billingmethod, plpc.changesperweek, plpc.rentpriceperfrequency,
       plpc.minimumturnaround, plpc.minimumquantity, plpc.delayedevenexchange, plpc.dateactive startdate, lan.code languagecode,
       pack_price.rent_price(plpc.customer_id, prd.product_id, sd.sizedefinition_id, fm.finishingmethod_id, null, 1) rentalprice,
       pack_price.wash_price(plpc.customer_id, prd.product_id, sd.sizedefinition_id, fm.finishingmethod_id, null, 1) washprice,
       cast(f_productdeliverydays(plpc.productlistpercustomer_id, lan.language_id) as varchar2(7)) deliveryday,
       (select prds.description
          from product_desc prds
         where prds.product_id = prd.product_id
           and prds.language_id = lan.language_id) productdescription,
       (select sum(rqa.quantity)
          from rentalqtyadjustment rqa
               join productlistperdistribpoint pldip
                    join distributionpoint dip
                         join department de on dip.department_id = de.department_id
                    on pldip.distributionpoint_id = dip.distributionpoint_id
               on rqa.productlistperdistribpoint_id = pldip.productlistperdistribpoint_id
         where de.customer_id = plpc.customer_id
           and plpc.product_id = pldip.product_id
           and plpc.sizedefinition_id = pldip.sizedefinition_id
           and plpc.finishingmethod_id = pldip.finishingmethod_id
           and rqa.adjustmentdate <= trunc(sysdate)) circulatinginventory,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and lan.language_id=sdd.language_id) size_desc,
       case when substr(pack_price.rent_price_details(plpc.customer_id, prd.product_id, sd.sizedefinition_id, fm.finishingmethod_id, null, 1),22,1) ='C'
            then to_date(substr(pack_price.rent_price_details(plpc.customer_id, prd.product_id, sd.sizedefinition_id, fm.finishingmethod_id, null, 1),14,8),'YYYYMMDD')
            else null
        end customerlastincrease,
       case when substr(pack_price.rent_price_details(plpc.customer_id, prd.product_id, sd.sizedefinition_id, fm.finishingmethod_id, null, 1),22,1) ='G'
            then to_date(substr(pack_price.rent_price_details(plpc.customer_id, prd.product_id, sd.sizedefinition_id, fm.finishingmethod_id, null, 1),14,8),'YYYYMMDD')
            else null
        end generallastincrease,
       (select cur.decimals
          from currency cur
               join customer cu on cur.currency_id = cu.currency_id
         where cu.customer_id = plpc.customer_id) currencydecimals
  from productlistpercustomer plpc
       join product prd on plpc.product_id = prd.product_id
       join sizedefinition sd on plpc.sizedefinition_id = sd.sizedefinition_id
       join finishingmethod fm on plpc.finishingmethod_id = fm.finishingmethod_id
       cross join languages lan
/

  CREATE OR REPLACE VIEW "V_NOTSCANNEDITEMS_OUTERRV" ("UNIQUEITEM_ID", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "REPORTPARAM_ID", "LANGUAGELANGUAGEID") AS 
  select uq.uniqueitem_id
, finishingmethod.code finishingmethodCode
, (select finishingmethod_desc.description from finishingmethod_desc
where finishingmethod_desc.finishingmethod_id =  finishingmethod.finishingmethod_id
and finishingmethod_desc.language_id = languages.language_id) finishingmethodDescription
--, flag.code flagCode
, rp.reportparam_id
, languages.language_id languageLanguageID
from
  uniqueitem uq
   left outer join finishingmethod  on finishingmethod.finishingmethod_id = uq.finishingmethod_id
   left outer join (uniqueitemflag uqf join flag on uqf.flag_id = flag.flag_id    )
                  on uq.uniqueitem_id = uqf.uniqueitem_id
, languages, reportparam rp
where ((rp.string_value1 = ' ' and rp.string_value2 = 'ZZZZZZ')
      or
      (flag.code >= rp.string_value1 and flag.code <= rp.string_value2))
/

  CREATE OR REPLACE VIEW "V_NRWASHESPERPRODUCT" ("CUSTOMERNUMBER", "CUSTOMERNAME", "BUSINESSUNITCODE", "BUSINESSUNIT_ID", "CITY", "PRODUCTGROUPCODE", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "SIZEDESC", "WASHESTOTAL", "REWASHTOTAL", "MAXWASHES", "LANGUAGECODE") AS 
  select
  cu.customernumber, cu.name customerName, bu.code businessunitCode, BU.BUSINESSUNIT_ID, address.city
, productgroup.code productgroupCode, prd.code productCode
, (select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, sz.code SizeCode
, (select sizedefinition_desc.description from sizedefinition_desc where sizedefinition_desc.sizedefinition_id = sz.sizedefinition_id
  and sizedefinition_desc.language_id = languages.language_id  ) SizeDesc
, uq.washestotal, uq.rewashtotal, prd.maxwashes, languages.code languageCode
from
  uniqueitem uq, product prd, productgroup , sizedefinition sz, status, businessunit bu, uniqueitemnonpool uqnp
, weareremployment weem, distributionpoint dip, department dep, customer cu, address
, languages
where
    uq.poolitem = 2
and uq.businessunit_id = bu.businessunit_id
and uq.status_id = status.status_id
    and status.code = '20'
        and status.statustype = 'UI'
and uq.product_id = prd.product_id
    and prd.productgroup_id = productgroup.productgroup_id
and uq.sizedefinition_id = sz.sizedefinition_id
and uq.uniqueitem_id = uqnp.uniqueitem_id
    and uqnp.weareremployment_id = weem.weareremployment_id
        and weem.distributionpoint_id = dip.distributionpoint_id
            and dip.department_id = dep.department_id
                and dep.customer_id = cu.customer_id
                    and uq.businessunit_id = cu.defaultbusinessunit_id
and cu.visitaddress_id = address.address_id
   /* UNION ALL  -- this is for Pool
select
  customer.customernumber, customer.name customerName, bu.code businessunitCode, address.city
, productgroup.code productgroupCode, prd.code productCode
, (select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, sz.code SizeCode
, (select sizedefinition_desc.description from sizedefinition_desc where sizedefinition_desc.sizedefinition_id = sz.sizedefinition_id
  and sizedefinition_desc.language_id = languages.language_id  ) SizeDesc
, uq.washestotal, uq.rewashtotal, prd.maxwashes, languages.code languageCode
from
uniqueitem uq, customer, product prd, productgroup, sizedefinition sz
, status, businessunit bu, address, languages
where
uq.poolitem = 1
and
(
uq.relatedcustomer_id is not null
   or uq.distributionpoint_id is not null
       or uq.lastdistributionpoint_link_id is not null
)
and
    customer.customer_id =
(
Select cu.customer_id from customer cu, distributionpoint dip, department dep
where
    cu.customer_id = dep.customer_id
and dep.department_id = dip.department_id
and
cu.customer_id =
    case uq.relatedcustomer_id
         when cu.customer_id  then cu.customer_id
                              else
                   case uq.distributionpoint_id
                        when dip.distributionpoint_id then dep.customer_id
                                                      else
                               case uq.lastdistributionpoint_link_id
                                    when dip.distributionpoint_id then dep.customer_id
                               end
                   end
    end
group by cu.customer_id
)
and uq.businessunit_id = bu.businessunit_id
and uq.status_id = status.status_id
    and status.code = '20'
        and status.statustype = 'UI'
and uq.product_id = prd.product_id
    and prd.productgroup_id = productgroup.productgroup_id
and uq.sizedefinition_id = sz.sizedefinition_id
and customer.visitaddress_id = address.address_id
and uq.businessunit_id = customer.defaultbusinessunit_id
    UNION ALL
select
  -1 customernumber, ' '  customerName, bu.code businessunitCode, ' ' city
, productgroup.code productgroupCode, prd.code productCode
, (select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, sz.code SizeCode
, (select sizedefinition_desc.description from sizedefinition_desc where sizedefinition_desc.sizedefinition_id = sz.sizedefinition_id
  and sizedefinition_desc.language_id = languages.language_id  ) SizeDesc
, uq.washestotal, uq.rewashtotal, prd.maxwashes, languages.code languageCode
from
uniqueitem uq, product prd, productgroup, sizedefinition sz, status, businessunit bu, languages
where
    uq.poolitem = 1
and
(
uq.relatedcustomer_id is null
   and uq.distributionpoint_id is null
       and uq.lastdistributionpoint_link_id is null
)
and uq.businessunit_id = bu.businessunit_id
and uq.status_id = status.status_id
    and status.code = '20'
        and status.statustype = 'UI'
and uq.product_id = prd.product_id
    and prd.productgroup_id = productgroup.productgroup_id
and uq.sizedefinition_id = sz.sizedefinition_id
*/
/

  CREATE OR REPLACE VIEW "V_NRWASHESPERWEARER" ("CUSTOMERNUMBER", "CUSTOMERNAME", "BUSINESSUNITCODE", "BUSINESSUNIT_ID", "CITY", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "WEARERNUMBER", "WEARERNAME", "PRODUCTGROUPCODE", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "SIZEDESC", "WASHESTOTAL", "REWASHTOTAL", "MAXWASHES", "LANGUAGECODE") AS 
  select /*version 2.0*/
       cu.customernumber, cu.name customername, bu.code businessunitcode, bu.businessunit_id,
       addr.city, dep.departmentnumber, dep.description departmentdesc, w.wearernumber,
       w.fullname wearername, pg.code productgroupcode, prd.code productcode,
       (select product_desc.description
          from product_desc
         where product_desc.product_id = prd.product_id
           and product_desc.language_id = lan.language_id) productdesc, sz.code sizecode,
       (select sizedefinition_desc.description
          from sizedefinition_desc
         where sizedefinition_desc.sizedefinition_id = sz.sizedefinition_id
           and sizedefinition_desc.language_id = lan.language_id) sizedesc, uq.washestotal,
       uq.rewashtotal, prd.maxwashes, lan.code languagecode
  from uniqueitem uq
       join product prd
            join productgroup pg on prd.productgroup_id = pg.productgroup_id
       on uq.product_id = prd.product_id
       join sizedefinition sz on uq.sizedefinition_id = sz.sizedefinition_id
       join status st on uq.status_id = st.status_id
       join businessunit bu on uq.businessunit_id = bu.businessunit_id
       join uniqueitemnonpool uqnp
            join weareremployment weem
                 join distributionpoint dip
                      join department dep
                           join customer cu
                                join address addr on cu.visitaddress_id = addr.address_id
                           on dep.customer_id = cu.customer_id
                      on dip.department_id = dep.department_id
                 on weem.distributionpoint_id = dip.distributionpoint_id
                 join wearer w on weem.wearer_id = w.wearer_id
            on uqnp.weareremployment_id = weem.weareremployment_id
       on uq.uniqueitem_id = uqnp.uniqueitem_id
 cross join languages lan
 where uq.poolitem = 2 -- nonpol
   and st.code = '20' -- in circulation
   and st.statustype = 'UI' -- unique item
   and uq.businessunit_id = cu.defaultbusinessunit_id
/

  CREATE OR REPLACE VIEW "V_NSFCHECKREPORT" ("BUSINESSUNIT_ID", "BUSINESSUNIT_CODE", "BUSINESSUNIT_DESC", "BILLTO_ID", "BILLTO_NR", "BILLTO_NAME", "ARTRANSACTION_ID", "INVOICEHEADER_ID", "INVOICENUMBER", "ARTRANSACTIONDATE", "AMOUNT", "REMITIDENTIFICATION", "REMARK", "TOTALAPPLIEDAMOUNT", "CLOSINGAMOUNT", "CLOSINGDATE", "ISOPEN_YN", "DEBIT_INVOICEHEADER_ID", "DEBIT_INVOICENUMBER", "DEBIT_ARTRANSACTIONDATE", "DEBIT_AMOUNT", "DEBIT_REMITIDENTIFICATION", "DEBIT_REMARK", "DEBIT_TOTALAPPLIEDAMOUNT", "DEBIT_CLOSINGAMOUNT", "DEBIT_CLOSINGDATE", "DEBIT_ISOPEN_YN", "DEBIT_TRANSACTION_ID", "APPLYDATE_NSF", "APPLYDATE", "CASHAPP_AMOUNT", "UNAPPLIED_YN", "UNAPPLYDATE", "CHECKK", "REGIONCODE", "REGIONDESC") AS 
  select --based on DWH_FACT_AR_TRANSACTIONS
       bu.businessunit_id, bu.code businessunit_code, bu.description businessunit_desc,
       cl.customer_id billto_id, cl.customernumber billto_nr, cl.name billto_name, a.artransaction_id,
       a.invoiceheader_id, a.invoicenumber, a.artransactiondate, a.amount, a.remitidentification, a.remark,
       a.totalappliedamount, a.closingamount, a.closingdate, a.isopen_yn,
       dt.invoiceheader_id debit_invoiceheader_id, dt.invoicenumber debit_invoicenumber, dt.artransactiondate debit_artransactiondate,
       dt.amount debit_amount, dt.remitidentification debit_remitidentification, dt.remark debit_remark,
       dt.totalappliedamount debit_totalappliedamount, dt.closingamount debit_closingamount,
       dt.closingdate debit_closingdate, dt.isopen_yn debit_isopen_yn, dt.artransaction_id debit_transaction_id,
       ca.applydate applydate_nsf, ca2.applydate, ca2.amount cashapp_amount, ca2.unapplied_yn, ca2.unapplydate,
       coalesce((select pay.remitidentification from artransaction pay where pay.artransaction_id = ca2.creditartransaction_id), a.remitidentification) checkk,
       (select re.code from region re where re.region_id = bu.region_id) regioncode,
       (select red.description from region_desc red where red.region_id = bu.region_id and red.language_id =
               (select cu.language_id from customer cu where cu.customer_id = cl.customer_id)) regiondesc
from artransaction a
     left outer join cashapplication ca
          inner join artransaction dt
                left outer join cashapplication ca2 on dt.artransaction_id = ca2.debitartransaction_id and ca2.unapplied_yn = 'N'
          on ca.debitartransaction_id = dt.artransaction_id
     on a.originaltransaction_id = ca.creditartransaction_id
     inner join artransactiontype at on a.artransactiontype_id = at.artransactiontype_id
     inner join businessunit bu on a.businessunit_id = bu.businessunit_id
     inner join customer_link cl on a.billtocustomer_link_id = cl.customer_link_id
where at.code = 'NSF' and at.typenumber <> 2 and dt.artransaction_id <> a.artransaction_id
  and a.artransaction_id = coalesce(a.parentartransaction_id, a.artransaction_id)
  and a.artransactiondate >= (SELECT year_start_date from dwh_settings where dwh_settings_id = 1)
  and a.artransactiondate <= (SELECT year_start_date+number_of_years*365 from dwh_settings where dwh_settings_id = 1)
  and exists (select 1 from artransaction dt2, cashapplication ca3 where dt2.isopen_yn = 'Y'
              and a.originaltransaction_id = ca3.creditartransaction_id and ca3.debitartransaction_id = dt2.artransaction_id)
/

  CREATE OR REPLACE VIEW "V_ONSITEINVENTORY" ("CUSTOMERNUMBER", "CUSTOMERNAME", "STREET", "ZIPCODE", "CITY", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "PRODUCTCODE", "SIZECODE", "PRODUCTDESC", "SIZEDESC", "SIZESEQ", "PRODUCTGROUPCODE", "PRODUCTGROUPDESC", "INVENTORYDATE", "QUANTITY", "LANGUAGECODE", "DATEACTIVE", "DATEINACTIVE") AS 
  select
  cu.customernumber, cu.name CustomerName
, cast(CONCATENATEWITHBLANK(address.street, address.street2) as varchar2(255)) street
, address.zipcode, address.city
, de.departmentnumber, de.description departmentDesc
, di.distributionpointnumber, di.description distributionpointDesc
, prd.code ProductCode, sz.code SizeCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) ProductDesc
, (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sz.sizedefinition_id
    and sdd.language_id = languages.language_id) sizedesc
, (select ps.sequencenumber from productsize ps where ps.product_id = prd.product_id and ps.sizedefinition_id = sz.sizedefinition_id) sizeseq
, pg.code productgroupcode
, (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pg.productgroup_id
    and pgd.language_id = languages.language_id) productgroupdesc
, onsi.inventorydate, onsi.quantity, languages.Code languageCode,cu.dateactive dateactive,cu.dateinactive dateinactive
from
  onsiteinventoryadjustment onsi, productlistperdistribpoint prdi, productlistpercustomer plpc
, distributionpoint di, department de
, customer cu, product prd, sizedefinition sz, productgroup pg
, address, languages
where
    onsi.productlistperdistribpoint_id = prdi.productlistperdistribpoint_id
and prdi.product_id = prd.product_id
and prdi.sizedefinition_id = sz.sizedefinition_id
and prdi.distributionpoint_id = di.distributionpoint_id
    and di.department_id = de.department_id
        and de.customer_id = cu.customer_id
            and cu.visitaddress_id = address.address_id
                and cu.customer_id = plpc.customer_id
and plpc.onsiteinventorycount = 'Y'
and plpc.product_id = prd.product_id
and plpc.sizedefinition_id =
    ( case sz.sizedefinition_id
           when plpc.sizedefinition_id then sz.sizedefinition_id
                else
                ( select sizedefinition.sizedefinition_id from sizedefinition where sizedefinition.code = '*' )
                         end )
and plpc.finishingmethod_id = prdi.finishingmethod_id
and pg.productgroup_id = prd.productgroup_id
/

  CREATE OR REPLACE VIEW "V_ONSITEINVENTORYCHECK" ("SEL", "QUANTITY", "CUSTOMERNUMBER", "CUSTOMERNAME", "STREET", "ZIPCODE", "CITY", "STATE", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "PRODUCTCODE", "SIZECODE", "FINISHINGCODE", "PRODUCTDESC", "SIZEDESC", "SIZESEQ", "FINISHINGDESC", "LANGUAGECODE", "REPORTPARAM_ID") AS 
  select 1 sel, f_onsiqty(onsi.productlistperdistribpoint_id, rp.date_value1) quantity,
  cu.customernumber, cu.name CustomerName
, cast(CONCATENATEWITHBLANK(address.street, address.street2) as varchar2(255)) street
, address.zipcode, address.city, address.state
, de.departmentnumber, de.description departmentDesc, di.distributionpointnumber, di.description distributionpointDesc
, prd.code ProductCode, sz.code SizeCode, fm.code FinishingCode
, (select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id) ProductDesc
, (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sz.sizedefinition_id
    and sdd.language_id = languages.language_id) sizedesc
, (select ps.sequencenumber from productsize ps where ps.product_id = prd.product_id and ps.sizedefinition_id = sz.sizedefinition_id) sizeseq
, (select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
    and fmd.language_id = languages.language_id) FinishingDesc
, languages.Code languageCode, rp.reportparam_id
from
  onsiteinventoryadjustment onsi, productlistperdistribpoint prdi, productlistpercustomer plpc
, distributionpoint di, department de
, customer cu, product prd, sizedefinition sz, finishingmethod fm
, address, languages, reportparam rp
where
    onsi.productlistperdistribpoint_id = prdi.productlistperdistribpoint_id
and prdi.product_id = prd.product_id
    and prdi.sizedefinition_id = sz.sizedefinition_id
        and prdi.finishingmethod_id = fm.finishingmethod_id
and prdi.distributionpoint_id = di.distributionpoint_id
and di.department_id = de.department_id
and de.customer_id = cu.customer_id
and cu.visitaddress_id = address.address_id
    and cu.customer_id = plpc.customer_id
    and prd.product_id = plpc.product_id
and plpc.sizedefinition_id =
    ( case sz.sizedefinition_id
           when plpc.sizedefinition_id then sz.sizedefinition_id
                else
                ( select sizedefinition.sizedefinition_id from sizedefinition where sizedefinition.code = '*' )
                         end )
    and fm.finishingmethod_id = plpc.finishingmethod_id
        and plpc.onsiteinventorycount = 'Y'
        and (onsi.inventorydate<rp.date_value1 OR (onsi.inventorydate=rp.date_value1 AND onsi.origin<>7))
group by cu.customer_id, onsi.productlistperdistribpoint_id, rp.date_value1, address.street, address.street2, address.zipcode, address.city, address.state,
 de.departmentnumber, de.description, di.distributionpointnumber, di.description
, prd.code, sz.code, fm.code,  prd.product_id, languages.language_id, languages.Code,   cu.customernumber, cu.name , rp.reportparam_id, fm.finishingmethod_id, sz.sizedefinition_id
UNION ALL
select 2 sel, sum(onsi.quantity) quantity,
cu.customernumber, cu.name CustomerName
, cast(CONCATENATEWITHBLANK(address.street, address.street2) as varchar2(255)) street
, address.zipcode, address.city, address.state
, de.departmentnumber, de.description departmentDesc, di.distributionpointnumber, di.description distributionpointDesc
, prd.code ProductCode, sz.code SizeCode, fm.code FinishingCode
, (select product_desc.description from product_desc where product_desc.product_id = prd.product_id
and product_desc.language_id = languages.language_id) ProductDesc
, (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sz.sizedefinition_id
  and sdd.language_id = languages.language_id) sizedesc
, (select ps.sequencenumber from productsize ps where ps.product_id = prd.product_id and ps.sizedefinition_id = sz.sizedefinition_id) sizeseq
, (select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
  and fmd.language_id = languages.language_id) FinishingDesc
, languages.Code languageCode, rp.reportparam_id
from
onsiteinventoryadjustment onsi, productlistperdistribpoint prdi, productlistpercustomer plpc
, distributionpoint di, department de
, customer cu, product prd, sizedefinition sz, finishingmethod fm
, address, languages, reportparam rp
where
  onsi.productlistperdistribpoint_id = prdi.productlistperdistribpoint_id
and prdi.product_id = prd.product_id
  and prdi.sizedefinition_id = sz.sizedefinition_id
      and prdi.finishingmethod_id = fm.finishingmethod_id
and prdi.distributionpoint_id = di.distributionpoint_id
and di.department_id = de.department_id
and de.customer_id = cu.customer_id
and cu.visitaddress_id = address.address_id
  and cu.customer_id = plpc.customer_id
  and prd.product_id = plpc.product_id
and plpc.sizedefinition_id =
  ( case sz.sizedefinition_id
         when plpc.sizedefinition_id then sz.sizedefinition_id
              else
              ( select sizedefinition.sizedefinition_id from sizedefinition where sizedefinition.code = '*' )
                       end )
  and fm.finishingmethod_id = plpc.finishingmethod_id
      and plpc.onsiteinventorycount = 'Y'
      and onsi.origin=7
      and onsi.inventorydate=rp.date_value1
group by cu.customer_id,onsi.productlistperdistribpoint_id, rp.date_value1, address.street, address.street2, address.zipcode, address.city, address.state,
de.departmentnumber, de.description, di.distributionpointnumber, di.description
, prd.code, sz.code, fm.code,  prd.product_id, languages.language_id, languages.Code,   cu.customernumber, cu.name , rp.reportparam_id,fm.finishingmethod_id, sz.sizedefinition_id
/

  CREATE OR REPLACE VIEW "V_ONSITESOILSCAN" ("DRIVINGDATE", "STOP_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "PRIMARYID", "DELPOINTCODEDESC", "DELPOINTCODE", "DELPOINTDESC", "LANGUAGECODE", "TRANSACTIONTYPE") AS 
  select rc.drivingdate, s.stop_id,
       cl.customernumber, cl.name customername,
       (select prl.code from product_link prl where prl.product_link_id = scan.product_link_id) productcode,
       (select prd.description from product_link_desc prd where prd.product_link_id = scan.product_link_id and prd.language_id = lan.language_id) productdesc,
       (select sd.code from sizedefinition sd where sd.sizedefinition_id = scan.sizedefinition_link_id) sizecode,
       scan.primaryid,
       case
         when ((s.routestop_id is null or
                (select rs.deliverypoint_id from routestop rs where s.routestop_id = rs.routestop_id) is null)
                and
                ((select count(dl.deliverypoint_id)
                  from deliverypoint dl
                  where dl.customer_id = s.customer_link_id) = 1))
          then ((select dl.code || ', ' || dl.description
                  from deliverypoint dl
                  where dl.customer_id = s.customer_link_id))
         else null
       end delpointcodedesc,
       dlp.code delpointcode,
       dlp.description delpointdesc,
       lan.code languagecode, scan.transactiontype_id TransactionType
from routecontrol rc,
     stop s left outer join deliverypoint dlp on s.deliverypoint_id = dlp.deliverypoint_id
            left outer join routestop rs on s.routestop_id = rs.routestop_id,
     scan, customer_link cl, languages lan
where s.routecontrol_id = rc.routecontrol_id
      and scan.batchnumber = 'ONSITE' || to_char(s.stop_id)
      and scan.transactiontype_id in (1, 75, 546)
      and s.customer_link_id = cl.customer_link_id
      and scan.customer_link_id = cl.customer_link_id
/

  CREATE OR REPLACE VIEW "V_ONSITESOILSCANDETAIL" ("DRIVINGDATE", "STOP_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "SIZEDESCRIPTION", "PRIMARYID", "DELPOINTCODEDESC", "DELPOINTCODE", "DELPOINTDESC", "LANGUAGECODE", "WEARERNAME", "WEARERNUMBER", "TRANSACTIONTYPE") AS 
  select rc.drivingdate, s.stop_id,
       cl.customernumber, cl.name customername,
       (select prl.code from product_link prl where prl.product_link_id = scan.product_link_id) productcode,
       (select prd.description from product_link_desc prd where prd.product_link_id = scan.product_link_id and prd.language_id = lan.language_id) productdesc,
       (select sd.code from sizedefinition sd where sd.sizedefinition_id = scan.sizedefinition_link_id) sizecode,
       (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = scan.sizedefinition_link_id
       and sdd.language_id = lan.language_id) sizedescription,
       scan.primaryid,
       case
         when ((s.routestop_id is null or
                (select rs.deliverypoint_id from routestop rs where s.routestop_id = rs.routestop_id) is null)
                and
                ((select count(dl.deliverypoint_id)
                  from deliverypoint dl
                  where dl.customer_id = s.customer_link_id) = 1))
          then ((select dl.code || ', ' || dl.description
                  from deliverypoint dl
                  where dl.customer_id = s.customer_link_id))
         else null
       end delpointcodedesc,
       dlp.code delpointcode,
       dlp.description delpointdesc,
       lan.code languagecode,
       wel.wearername, wel.wearernumber, scan.transactiontype_id TransactionType
from routecontrol rc,
     stop s left outer join deliverypoint dlp on s.deliverypoint_id = dlp.deliverypoint_id
            left outer join routestop rs on s.routestop_id = rs.routestop_id,
     scan, customer_link cl, languages lan, weareremployment_link wel
where s.routecontrol_id = rc.routecontrol_id
      and scan.batchnumber = 'ONSITE' || to_char(s.stop_id)
      and scan.transactiontype_id in (1, 75, 546)
      and s.customer_link_id = cl.customer_link_id
      and scan.customer_link_id = cl.customer_link_id
      and scan.weareremployment_link_id = wel.weareremployment_link_id
/

  CREATE OR REPLACE VIEW "V_OPTIMIZEDLOADPACKING" ("PACKINGNOTEID", "NOTENUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINTDESCRIPTION", "DELIVERYDATE", "ROUTEDESCRIPTION", "LANGUAGECODE", "BULKPUTUPONPACKINGNOTE", "PACKINGNOTECOLUMNS", "STOPNUMBER", "PUTUPREPORTPERCUSTOMER", "ROUTENUMBER", "CUSTOMERLANGUAGECODE") AS 
  select /*version 2.0*/
 pn.packingnote_id packingnoteid,
 pn.notenumber, c.customernumber, c.name customername,
 dep.description departmentdescription,
 dp.description distributionpointdescription,
 pn.deliverydate,
 r.description routedescription,
 lan.code languagecode,
 case when c.delnoteforbulkputupitems = 0 then  'N' else 'Y' end bulkputuponpackingnote,
 (select ss.value
  from systemsetting ss
  where ss.plant_id = processbu.plant_id and ss.name = 'PACKINGNOTECOLUMNS') packingnotecolumns,
 pn.stopnumber, r.putupreportpercustomer, r.routenumber,
 cula.code customerlanguagecode
from packingnote pn
     join distributionpoint dp on pn.distributionpoint_id = dp.distributionpoint_id
          join department dep on dp.department_id = dep.department_id
               join customer c on dep.customer_id = c.customer_id
                    join languages cula on c.language_id = cula.language_id
     left join routecontrol rc on pn.routecontrol_id = rc.routecontrol_id
     left join route r on pn.route_id = r.route_id
     join plantdepartment pd on pn.plantdepartment_id = pd.plantdepartment_id
     join businessunit processbu on pn.processbusinessunit_id = processbu.businessunit_id
     join status st on pn.status_id = st.status_id
     cross join languages lan
where st.statustype = 'PN' and cast(st.code as numeric) <= 20
/

  CREATE OR REPLACE VIEW "V_OPTIMIZEDLOADPACKINGLINE" ("PACKINGNOTEID", "PRODUCTCODE", "SIZECODE", "FINISHINGMETHODCODE", "PACKINGSEQUENCE", "TOBEDELIVEREDAMOUNT", "LANGUAGECODE", "PUTUPTYPE", "PACKINGNOTELINE_ID", "BUNDLEQTY", "SEQUENCENUMBER", "DELIVEREDAMOUNT", "PRODUCTDESCRIPTION") AS 
  select /*version 3.0*/
       pnl.packingnote_id packingnoteid, prod.code productcode, sd.code sizecode, fm.code finishingmethodcode,
       pnl.packingsequence, pnl.tobedeliveredamount, lan.code languagecode, pnl.putuptype, pnl.packingnoteline_id,
       pnl.bundleqty, psz.sequencenumber, pnl.deliveredamount,
       (select pd.description
          from product_desc pd
         where pd.product_id = pnl.product_id
           and pd.language_id = lan.language_id)  productdescription
  from packingnoteline pnl
       join product prod on pnl.product_id = prod.product_id
       join sizedefinition sd on pnl.sizedefinition_id = sd.sizedefinition_id
       join finishingmethod fm on pnl.finishingmethod_id = fm.finishingmethod_id
       join productsize psz on prod.product_id = psz.product_id and psz.sizedefinition_id = sd.sizedefinition_id
       cross join languages lan
/

  CREATE OR REPLACE VIEW "V_OPTIMIZEDPICKLISTORIGIN" ("PICKLIST_ID", "PICKLISTNUMBER", "WORKORDER_ID", "WORKORDERNUMBER", "REQUESTEDDELIVERYDATE", "WEAREREMPLOYMENT_LINK_ID", "CUSTOMER_LINK_ID", "CUSTOMERNUMBER", "NAME", "DISTRIBUTIONPOINT_LINK_ID", "DISTRIBUTIONPOINTNUMBER", "DESCRIPTION", "WEARERNUMBER", "SEARCHNAME", "ORIGIN", "SUBTYPE", "ORDERPRIORITY_ID", "ORDERPRIO", "PRIORITYCODE", "CUSTOMERPRIO", "RANKING") AS 
  select x.picklist_id, pl.picklistnumber,
       wo.workorder_id, wo.workordernumber, wo.neededdate requesteddeliverydate,
       wo.weareremployment_link_id, wo.customer_link_id, cu.customernumber, cu.name,
       wo.distributionpoint_link_id, dp.distributionpointnumber, dp.description,
       wr.wearernumber, wr.searchname,
       wo.origin, wo.subtype, wo.orderpriority_id,
       op.sequencenumber orderprio, op.prioritycode,
       nvl(cr.priority,999) customerprio, nvl(cr.ranking,'ZZZZZZZZZZ') ranking
from   workorder wo
       left outer join customer cu
            left outer join customerranking cr on cu.customerranking_id = cr.customerranking_id
       on wo.customer_link_id = cu.customer_id
       left outer join distributionpoint dp on wo.distributionpoint_link_id = dp.distributionpoint_id
       left outer join weareremployment we
            inner join wearer wr on we.wearer_id = wr.wearer_id
       on wo.weareremployment_link_id = we.weareremployment_id,
       orderpriority op, picklist pl,
       (select pll.picklist_id, wo.workorder_id
          from picklistline pll, picklistlineorigin plo, workorderline wol, workorder wo
         where plo.picklistline_id = pll.picklistline_id
           and wol.workorderline_id = plo.baselinetable_link_id
           and upper(plo.baselinetable) = 'WORKORDERLINE'
           and plo.baselinetable_link_id = wol.workorderline_id
           and wo.workorder_id = wol.workorder_id
           and plo.baselinetype = wo.origin
         group by pll.picklist_id, wo.workorder_id) x
where  op.orderpriority_id = wo.orderpriority_id
  and  pl.picklist_id = x.picklist_id
  and  wo.workorder_id = x.workorder_id
/

  CREATE OR REPLACE VIEW "V_OPTIMIZEDSTOCKITEMPICKLIST" ("STOCKCODE", "STOCKNAME", "AREACODE", "ROWCODE", "LOCATIONCODE", "MOBILEDEVICECODE", "MOBILEDEVICEDESC", "PICKLISTNUMBER", "PICKLIST_ID", "LINENUMBER", "PRODUCTID", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "QUALITYGRADECODE", "UNIQUEI", "PICKINGSEQ", "QTYONSTOCK", "QTYUNIQUE", "QTYNONUNIQUE", "QTYREQUIREDPRODUCT", "QTYREQUIREDLOCATION", "QTYTOPICKPRODUCT", "QTYTOPICKLOCATION", "QTYPICKEDPRODUCT", "QTYPICKEDLOCATION", "STATUS", "LANGUAGECODE") AS 
  select s.code stockcode, s.name stockname, sl.areacode, sl.rowcode, sl.locationcode,
       (select md.code from mobiledevice md where pl.mobiledevice_id = md.mobiledevice_id) mobiledevicecode,
       (select md.description from mobiledevice md where pl.mobiledevice_id = md.mobiledevice_id) mobiledevicedesc,
       pl.picklistnumber, pl.picklist_id, pll.linenumber, sdi.product_id productid,
       (select prd.code from product prd where prd.product_id = sdi.product_id) productcode,
       (select prddesc.description from product_desc prddesc where prddesc.product_id = sdi.product_id and prddesc.language_id = lan.language_id) productdesc,
       (select sd.code from sizedefinition sd where sd.sizedefinition_id = sdi.sizedefinition_id) sizecode,
       qg.code qualitygradecode, pll.stocktype uniquei, --1 = non unique 2 = unique 3 = unique with modifications
       nvl(plps.pickinglinenumber, -1) pickingseq,
       case --when pll.stocktype <> 1 then (sq.qtyunique + sq.qtynonunique)
         when pll.stocktype = 1 then sq.qtynonunique
         when pll.stocktype = 2 then sq.qtyunique
         when pll.stocktype = 3 then sq.qtyuniquewithmodifications
         else sq.qtynonunique
       end qtyonstock,
       sq.qtyunique, sq.qtynonunique, pll.qtytopick qtyrequiredproduct,
       nvl(plps.qtytopick,0) qtyrequiredlocation, --per location (from picklistpickingsequence)
       (pll.qtytopick-pll.qtypicked) qtytopickproduct, --per product
       (nvl(plps.qtytopick,0)-nvl(plps.qtypicked,0)) qtytopicklocation, --per location (from picklistpickingsequence)
       pll.qtypicked qtypickedproduct, nvl(plps.qtypicked,0) qtypickedlocation, --per location (from picklistpickingsequence)
       (select st.code from status st where st.status_id = pl.status_id) status,
       lan.code languagecode
from picklist pl, picklistline pll
     left outer join picklistpickingsequence plps on pll.picklistline_id = plps.picklistline_id,
     picklistlinelocation pllo, stockroomlocation sl, stockroom s,
     stockquantity sq, stockreservationpergrade srg, stockdefinitionperitem sdi,
     qualitygrade qg, languages lan
where pll.picklist_id = pl.picklist_id
and pllo.picklistline_id = pll.picklistline_id
and pll.picklist_id = pl.picklist_id
and pllo.picklistline_id = pll.picklistline_id
and sl.stockroomlocation_id = pllo.stockroomlocation_id
and sl.stockroom_id = s.stockroom_id
and sq.stockreservationpergrade_id = srg.stockreservationpergrade_id
and sq.stockroomlocation_id = pllo.stockroomlocation_id
and srg.stockreservationpergrade_id = pll.stockreservationpergrade_id
and srg.stockdefinitionperitem_id = sdi.stockdefinitionperitem_id
and srg.qualitygrade_id = qg.qualitygrade_id
and sdi.stockroom_id = s.stockroom_id
/

  CREATE OR REPLACE VIEW "V_ORDEREXCEPTION" ("CUSTOMER_ID", "BUSINESSUNIT_ID", "DELIVERYDATE", "BUSINESSUNITCODE", "BUSINESSUNITDESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "PRODUCTGROUPCODE", "PRODUCTCODE", "SIZECODE", "FINMETHODCODE", "PRODUCTDESC", "AMOUNTORDERED", "AMOUNTDELIVERED", "DIFF", "CUSTOMERLANGUAGECODE", "LANGUAGECODE", "SIZEDESC", "CUSTDATEACTIVE", "CUSTDATEINACTIVE") AS 
  select culk.customer_id, bu.businessunit_id,
  dh.deliverydate, bu.code businessunitCode, bu.description businessunitDesc, culk.customernumber, culk.name customerName
, delk.departmentnumber, delk.description departmentDesc, dilk.distributionpointnumber, dilk.description distributionpointDesc
, prdlk.Productgroupcode, prdlk.code productCode, szlk.code sizeCode, fm.code finmethodCode
, ( select product_link_desc.description from product_link_desc where product_link_desc.product_link_id = prdlk.product_link_id
  and product_link_desc.language_id = languages.language_id ) productDesc
, dh.amountordered, dh.amountdelivered
, ( dh.amountdelivered - dh.amountordered ) diff
--, culk.languagecode CUSTOMERLANGUAGECODE
, (select l.code from languages l where l.language_id = culk.language_id) CUSTOMERLANGUAGECODE
, languages.code languageCode
, ( select sizedefinition_link_desc.description from sizedefinition_link_desc where sizedefinition_link_desc.sizedefinition_link_id = szlk.sizedefinition_link_id
  and sizedefinition_link_desc.language_id = languages.language_id ) sizeDesc
, culk.dateactive custdateactive
, culk.dateinactive custdateinactive
--, default_bu.businessunit_id DefaultBusinessunit_id
from
  deliveryhistory dh, businessunit bu, customer culk, department_link delk, distributionpoint_link dilk
, product_link prdlk, sizedefinition_link szlk, finishingmethod fm
, languages
--, businessunit default_bu
where
    dh.processbusinessunit_id = bu.businessunit_id
and dh.customer_link_id = culk.customer_id
and dh.department_link_id = delk.department_link_id
and dh.distributionpoint_link_id = dilk.distributionpoint_link_id
and dh.product_link_id = prdlk.product_link_id
and dh.sizedefinition_link_id = szlk.sizedefinition_link_id
and dh.finishingmethod_id = fm.finishingmethod_id
--  and exists (select v.customer_id from v_customersperbusinessunitdp v
--              where v.customer_id=culk.customer_link_id and v.businessunit_id=default_bu.businessunit_id)
/

  CREATE OR REPLACE VIEW "V_ORDERSPECIFICATION" ("CUSTOMER_ID", "DELIVERYDATE", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "PRODUCTGROUPCODE", "PRODUCTCODE", "SIZECODE", "PRODUCTDESC", "STANDARDAMOUNT", "NORMSTOCKLEVEL", "VARIATIONAMOUNT", "STOCKCOUNTQTY", "PREVSTANDARDQTY", "PREVDELIVEREDQTY", "TOBEDELIVEREDAMOUNT", "AMOUNT", "DELIVEREDAMOUNT", "LANGUAGECODE", "SIZEDESC", "ACTIVITYCODE", "STATUSCODE", "AUTOLOADPACKING", "NOTENUMBER") AS 
  select /*+rule*/
  cu.customer_id, pn.deliverydate, cu.customernumber, cu.name customerName
, dep.departmentnumber, dep.description departmentDesc, dp.distributionpointnumber, dp.description distributionpointDesc
, prdlk.Productgroupcode, coalesce(pnl.customcode, prdlk.code) productCode, sz.code sizeCode
, coalesce(pnl.customdescription, (select product_link_desc.description from product_link_desc where product_link_desc.product_link_id = prdlk.product_link_id
  and product_link_desc.language_id = languages.language_id)) productDesc
, pnl.standardamount, pnl.normstocklevel, pnl.variationamount, pnl.stockcountqty, pnl.prevstandardqty, pnl.prevdeliveredqty
, pnl.tobedeliveredamount, pnl.amount, pnl.deliveredamount
, languages.code languageCode
, (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sz.sizedefinition_id
  and sdd.language_id = languages.language_id ) sizeDesc
, (select ac.code from activity ac, productgroup pg
where ac.activity_id = pg.activity_id and pg.code = prdlk.productgroupcode ) ActivityCode
, (select st.code from status st where pn.status_id = st.status_id and st.statustype = 'PN') StatusCode
, cu.autoloadpacking, pn.notenumber
from
packingnote pn, distributionpoint dp, department dep, customer cu
, packingnoteline pnl, product_link prdlk, sizedefinition sz
, languages
where pn.packingnote_id = pnl.packingnote_id
and pn.distributionpoint_id = dp.distributionpoint_id
and dp.department_id = dep.department_id
and dep.customer_id = cu.customer_id
and pnl.product_id = prdlk.product_id
and pnl.sizedefinition_id = sz.sizedefinition_id
/

  CREATE OR REPLACE VIEW "V_ORDERSTATUS" ("CUSTOMERNUMBER", "NAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINTNUMBER", "SCALEOPERATOR", "TIMESTAMP", "CONTAINERID", "NETWEIGHT") AS 
  select cl.customernumber, cl.name,
       d.departmentnumber, d.description departmentdesc,
       dp.distributionpointnumber,
       (select s.username from systemuser s where s.systemuser_id = pn.systemuser_id) scaleoperator,
       pn.timestamp,
       ct.primaryid containerid,
       (pnc.grossweight - pnc.tareweight) netweight
from packingnote pn, packingnotecontainer pnc, container ct
     , department_link d, distributionpoint_link dp, customer_link cl
where pn.packingnote_id = pnc.packingnote_id
      and pnc.container_id = ct.container_id
      and pn.distributionpoint_id = dp.distributionpoint_id
      and dp.department_link_id = d.department_link_id
      and d.customer_link_id = cl.customer_link_id
/

  CREATE OR REPLACE VIEW "V_ORDERSTOBESORTED" ("ORDERNUMBER", "ROUTEDAY", "ROUTENUMBER", "STOPNUMBER", "CUSTOMERNUMBER", "PACKINGDATETIME", "PRODUCTCODE", "SIZECODE", "QUANTITYORDERED") AS 
  select
 ph.notenumber ordernumber,
 r.drivingday_id routeday,
 case
   when dx.code = 'RFL' then
    dp.sortaddress
   else
    to_char(r.routenumber)
 end routenumber,
 case
   when dx.code = 'RFL' then
    0
   else
    ph.stopnumber
 end stopnumber,
 c.customernumber,
 (to_char(ph.productiondate, 'yyyymmdd') ||
 to_char(rc.packingdeadline, 'hh24mi')) packingdatetime,
 nvl(x.ppcode, p.code) productcode,
 nvl(x.spcode, s.code) sizecode,
 trunc(nvl(pl.tobedeliveredamount * x.quantity, pl.tobedeliveredamount)) quantityordered
  from packingnote ph
  join packingnoteline pl
    on pl.packingnote_id = ph.packingnote_id
  left outer join (select pc.packingnoteline_id,
                          pp.code               ppcode,
                          sp.code               spcode,
                          pc.quantity
                     from packingnotelinecontent pc
                     join product pp
                       on pp.product_id = pc.product_id
                     join sizedefinition sp
                       on sp.sizedefinition_id = pc.sizedefinition_id) x
    on x.packingnoteline_id = pl.packingnoteline_id
  join product p
    on p.product_id = pl.product_id
  join distributionpoint d
    on d.distributionpoint_id = ph.distributionpoint_id
  join department e
    on e.department_id = d.department_id
  join customer_link c
    on c.customer_id = e.customer_id
  left outer join route r
    on r.route_id = ph.route_id
  left outer join routecontrol rc
    on rc.routecontrol_id = ph.routecontrol_id
  join sizedefinition s
    on s.sizedefinition_id = pl.sizedefinition_id
  join status
    on status.status_id = ph.status_id
  join plantdepartment pd
    on pd.plantdepartment_id = ph.plantdepartment_id
  join deliverypoint dp
    on dp.deliverypoint_id = ph.deliverypoint_id
 cross join (select max(ds.code) code from databasesettings ds) dx
 where status.statustype = 'PN'
   and status.code in ('10', '20')
   and pl.origin = 0
   and p.typeofmerchandise = 2
   and pl.tobedeliveredamount > 0
   and pd.code = 'METRIC'
   and ph.deliverydate >= trunc(sysdate - 1)
/

  CREATE OR REPLACE VIEW "V_ORDERSTOBESORTED_NOROUTE" ("ORDERNUMBER", "CUSTOMERNUMBER", "PRODUCTCODE", "SIZECODE", "QUANTITYORDERED") AS 
  select ph.notenumber ordernumber, c.customernumber,
p.code productcode, s.code sizecode, trunc(pl.tobedeliveredamount) quantityordered
 from packingnote ph, packingnoteline pl, product p, customer_link c, distributionpoint d,
 department e, sizedefinition s, status, plantdepartment pd
where ph.packingnote_id = pl.packingnote_id
and pl.product_id = p.product_id
and ph.distributionpoint_id = d.distributionpoint_id
and d.department_id = e.department_id
and e.customer_id = c.customer_id
and pl.sizedefinition_id = s.sizedefinition_id
and ph.status_id = status.status_id
and status.statustype= 'PN'
and status.code in ('10','20')
and pl.origin=0
and p.typeofmerchandise=2
and pl.tobedeliveredamount>0
and pd.plantdepartment_id = ph.plantdepartment_id
and pd.code = 'METRIC'
/

  CREATE OR REPLACE VIEW "V_ORPRODUCTSPERSTAY" ("LINETYPE", "STAY_ID", "STAYTYPE", "STAYNR", "STAYDESC", "PRODUCTCODE", "PRODUCTDESC", "PGCODE", "PGDESC", "PRIMARYID", "STAYCHANGEDATE", "CUSTOMERNUMBER", "CUSTOMERNAME", "PNLCQTY", "BUSINESSUNIT_ID", "LANGUAGE_CODE", "PACKINGNOTELINE_ID", "PREVSTAY_ID") AS 
  select /*version 2.0*/
       1 linetype, st.stay_id, st.staytype, st.staynr,
        --ui products NOT on a pack
       (select sd.description
          from stay_desc sd
         where st.stay_id = sd.stay_id
           and sd.language_id = languages.language_id) staydesc, pr.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = pr.product_id
           and pd.language_id = languages.language_id) productdesc,
       (select pg.code from productgroup pg where pg.productgroup_id = pr.productgroup_id) pgcode,
       (select pgd.description
          from productgroup_desc pgd
         where pgd.productgroup_id = pr.productgroup_id
           and pgd.language_id = languages.language_id) pgdesc, ui.primaryid, ui.staychangedate, c.customernumber customernumber, c.name customername,
       pnl.deliveredamount pnlcqty, ui.businessunit_id, languages.code language_code, pnl.packingnoteline_id, ui.prevstay_id
from uniqueitem ui
     left join packingnoteline pnl
               join packingnote pn
                    join distributionpoint dp
                         join department dep
                              join customer c on dep.customer_id = c.customer_id
                         on dp.department_id = dep.department_id
                    on pn.distributionpoint_id = dp.distributionpoint_id
               on pnl.packingnote_id = pn.packingnote_id
               and pn.status_id in (select s1.status_id from status s1 where s1.statustype = 'PN' and s1.code in ('10', '20'))
     on ui.product_id = pnl.product_id
        and ui.sizedefinition_id = pnl.sizedefinition_id
        and ui.finishingmethod_id = pnl.finishingmethod_id
        and ui.distributionpoint_id = pn.distributionpoint_id
     join product pr on ui.product_id = pr.product_id
     join stay st on ui.stay_id = st.stay_id
, languages
 where st.staytype = 1
   and (st.staynr in (10, 30, 31, 32, 33, 38) or
       (st.staynr = 20 and ui.prevstay_id <> (select s.stay_id from stay s where s.staytype = 1 and s.staynr = 35)))
   and pr.orpackcontentsallowed <> 0
   and ui.businessunit_id in (select ordbu.delivertobusinessunit_id from ordeliverbusinessunit ordbu)
union
select 2 linetype, s2.stay_id, s2.staytype, s2.staynr,
        -- ui products on a pack on a packingnotelinecontent
       (select sd.description
          from stay_desc sd
         where s2.stay_id = sd.stay_id
           and sd.language_id = languages.language_id) staydesc, pr.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = pr.product_id
           and pd.language_id = languages.language_id) productdesc,
       (select pg.code from productgroup pg where pg.productgroup_id = pr.productgroup_id) pgcode,
       (select pgd.description
          from productgroup_desc pgd
         where pgd.productgroup_id = pr.productgroup_id
           and pgd.language_id = languages.language_id) pgdesc, ui1.primaryid, ui1.staychangedate, c.customernumber, c.name customername, pnlc.quantity,
       ui1.businessunit_id, languages.code language_code, pnl.packingnoteline_id, ui1.prevstay_id
from uniqueitem ui1
     left join packingnotelinecontent pnlc
                     join packingnoteline pnl
                               join packingnote pn
                                    join distributionpoint dp
                                         join department dep
                                         join customer c on dep.customer_id = c.customer_id
                                    on dp.department_id = dep.department_id
                               on pn.distributionpoint_id = dp.distributionpoint_id
                          on pnl.packingnote_id = pn.packingnote_id
                     and pn.status_id in (select s1.status_id from status s1 where s1.statustype = 'PN' and s1.code in ('10', '20'))
                    on pnlc.packingnoteline_id = pnl.packingnoteline_id
     on ui1.product_id = pnlc.product_id
        and ui1.sizedefinition_id = pnlc.sizedefinition_id
        and ui1.finishingmethod_id = pnlc.finishingmethod_id
        and ui1.stay_id = (select s.stay_id from stay s where s.staytype = 1 and s.staynr = 20)
     join product pr on ui1.product_id = pr.product_id
     join stay s1 on ui1.stay_id = s1.stay_id
     join uniqueorpackcontents uorpc on ui1.uniqueitem_id = uorpc.uniqueitem_id
     join uniqueorpack uorp on uorp.uniqueitem_id = uorpc.uniqueitem_id
     join uniqueitem ui2 on uorp.uniqueitem_id = ui2.uniqueitem_id
     join stay s2 on ui2.stay_id = s2.stay_id
     join uniqueorpackuniquecontents uorpuc on uorpc.uniqueorpackcontents_id = uorpuc.uniqueorpackcontents_id
, languages
 where ((s1.staytype = 1 and s1.staynr = 35) or (s1.staytype = 1 and s1.staynr = 20))
   and s2.staytype = 3
   and s2.staynr in (20, 30, 35, 40, 45, 46)
   and pr.orpackcontentsallowed <> 0
   and ui1.businessunit_id in (select ordbu.delivertobusinessunit_id from ordeliverbusinessunit ordbu)
/

  CREATE OR REPLACE VIEW "V_OUTOFCIRCCHARGES" ("OUTOFCIRCYEAR", "OUTOFCIRCWEEK", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "WEARERNUMBER", "WEARERNAME", "PRODUCTCODE", "PRODUCTDESC", "REASONCODE", "REASONDESC", "RAGREASONCODE", "RAGREASONDESC", "INCIRCDATE", "OUTOFCIRCDATE", "TOBECHARGEDPERCENTAGE", "AMOUNT", "QUANTITY", "RESIDUALVALUE", "INVOICEHEADER_ID", "CHARGETYPE", "STATUS", "INVOICECATEGORY", "LANGUAGECODE", "BU_CODE", "BU_DESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "PRIMARYID", "SIZECODE", "SIZEDESC", "CHARGERESIDUALVALUE", "HISTORYPRIMARYID", "CHAIN_CODE") AS 
  select
 a.outofcircyear, a.outofcircweek,
 e.departmentnumber, e.description departmentdesc,
 w.wearernumber, w.wearername,
 p.code productcode,
 (select z.description from product_link_desc z where z.product_link_id = a.product_link_id
  and z.language_id = languages.language_id) productdesc,
 b.code reasoncode,
 (select x.description from reasoncode_desc x where x.reasoncode_id = a.reasoncode_id
  and x.language_id = languages.language_id) reasondesc,
 (select c.code from ragreason c where a.ragreason_id = c.ragreason_id) RAGreasoncode,
 (select y.description from ragreason_desc y where y.ragreason_id = a.ragreason_id
  and y.language_id = languages.language_id) RAGreasondesc,
 a.outofcircdate incircdate, a.outofcircdate, a.tobechargedpercentage, a.amount, a.quantity, a.amount residualvalue,
 a.invoiceheader_id, a.chargetype, a.status, b.invoicecategory, languages.code languagecode,
 bu.code bu_code, bu.description bu_desc, cu.customernumber, cu.name customername,
 (select ui.primaryid from uniqueitem ui where a.uniqueitem_link_id = ui.uniqueitem_id) primaryid,
 (select w.code from sizedefinition_link w where w.sizedefinition_link_id = a.sizedefinition_link_id) sizecode,
 (select q.description from sizedefinition_link_desc q where q.sizedefinition_link_id = a.sizedefinition_link_id
  and q.language_id = languages.language_id) sizedesc
, b.chargeresidualvalue, a.primaryid historyprimaryid,
(SELECT ch.code FROM chain ch, customer c WHERE c.customer_id = cu.customer_id AND ch.chain_id = c.chain_id) chain_code
from outofcirculationhistory a
 left outer join weareremployment_link w on (a.weareremployment_link_id = w.weareremployment_link_id),
 reasoncode b, distributionpoint_link d, department_link e, product_link p, languages,
 businessunit bu, customer_link cu
where a.reasoncode_id = b.reasoncode_id
 and a.distributionpoint_link_id = d.distributionpoint_link_id
 and d.department_link_id = e.department_link_id
 and a.product_link_id = p.product_link_id
 and a.processbusinessunit_id = bu.businessunit_id
 and a.customer_link_id = cu.customer_link_id
/

  CREATE OR REPLACE VIEW "V_OUTOFCIRCULATIONHISTORY" ("OUTOFCIRCYEAR", "OUTOFCIRCWEEK", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "WEARERNUMBER", "WEARERNAME", "PRODUCTCODE", "PRODUCTDESC", "REASONCODE", "REASONDESC", "RAGREASONCODE", "RAGREASONDESC", "INCIRCDATE", "OUTOFCIRCDATE", "TOBECHARGEDPERCENTAGE", "RESIDUALVALUE", "INVOICEHEADER_ID", "CHARGETYPE", "STATUS", "INVOICECATEGORY", "LANGUAGECODE", "LANGUAGE_ID", "PRIMARYID", "SIZECODE", "SIZEDESC", "TIMESTAMP", "TIMESTAMP_TRUNC", "LASTOUTSCANDATE") AS 
  select
 a.outofcircyear, a.outofcircweek,
 e.departmentnumber, e.description departmentdesc,
 w.wearernumber, w.wearername,
 p.code productcode,
 (select z.description from product_link_desc z where z.product_link_id = a.product_link_id
  and z.language_id = languages.language_id) productdesc,
 b.code reasoncode,
 (select x.description from reasoncode_desc x where x.reasoncode_id = a.reasoncode_id
  and x.language_id = languages.language_id) reasondesc,
 c.code ragreasoncode,
 (select y.description from ragreason_desc y where y.ragreason_id = c.ragreason_id
  and y.language_id = languages.language_id) ragreasondesc,
 a.incircdate, a.outofcircdate, a.tobechargedpercentage, a.amount residualvalue,--coalesce(a.residualvalue,0) residualvalue,
 a.invoiceheader_id, a.chargetype, a.status, b.invoicecategory, languages.code languagecode,languages.language_id,
 nvl((select ui.primaryid from uniqueitem ui, uniqueitem_link uil where ui.uniqueitem_id = uil.uniqueitem_id
  and uil.uniqueitem_link_id = a.uniqueitem_link_id),
  (select ri.primaryid from raggeditem ri, uniqueitem_link uil where ri.raggeditem_id = uil.raggeditem_id
  and uil.uniqueitem_link_id = a.uniqueitem_link_id)) primaryid,
 (select sz.code from sizedefinition sz where sz.sizedefinition_id = a.sizedefinition_link_id) sizecode,
 (select szd.description from sizedefinition_desc szd where szd.sizedefinition_id = a.sizedefinition_link_id
  and szd.language_id = languages.language_id) sizedesc, a.timestamp, trunc(a.timestamp) timestamp_trunc,
 coalesce((select ui.lastoutscandate from uniqueitem ui, uniqueitem_link uil where ui.uniqueitem_id = uil.uniqueitem_id
  and uil.uniqueitem_link_id = a.uniqueitem_link_id), getabsmaxdate()) lastoutscandate
from outofcirculationhistory a
 left outer join ragreason c on (a.ragreason_id = c.ragreason_id)
 left outer join weareremployment_link w on (a.weareremployment_link_id = w.weareremployment_link_id),
 reasoncode b, distributionpoint_link d, department_link e, product_link p, languages
where a.reasoncode_id = b.reasoncode_id
 and a.distributionpoint_link_id = d.distributionpoint_link_id
 and d.department_link_id = e.department_link_id
 and a.product_link_id = p.product_link_id
/

  CREATE OR REPLACE VIEW "V_OUTOFSTOCKHISTORY" ("STOCKROOMCODE", "STOCKROOMNAME", "OUTOFCIRCDATE", "OUTOFCIRCDATETRUNC", "CUSTOMERRELATED", "CUSTOMER_ID", "CUSTOMERNUMBER", "PRODUCTCODE", "SIZECODE", "PRODUCTDESC", "QUALITYGRADEDESC", "QUALITYGRADECODE", "PRIORITY", "RAGREASONCODE", "REASONCODE", "QUANTITY", "LANGUAGECODE", "PROCESSBUSINESSUNIT_ID") AS 
  select
  stockroom.code stockroomCode, stockroom.name stockroomName, ochy.outofstockdate outofcircdate
, trunc(ochy.outofstockdate) outofcircdateTrunc
, (case ochy.relatedcustomer_link_id when cu.customer_id  then 'Y' else 'N' end) customerrelated
, cu.customer_id, cu.customernumber, prd.code ProductCode, sz.code sizeCode
, (select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) ProductDesc
, (select qualitygrade_desc.description from qualitygrade_desc where qualitygrade_desc.qualitygrade_id = qualitygrade.qualitygrade_id
  and qualitygrade_desc.language_id = languages.language_id) qualitygradeDesc
, qualitygrade.code qualitygradeCode, qualitygrade.priority
, ragreason.code ragreasonCode, reasoncode.code  reasonCode
, ochy.quantity, languages.code languageCode
, ochy.processbusinessunit_id
from outofstockhistory ochy
     left outer join customer cu on ochy.relatedcustomer_link_id = cu.customer_id
     left outer join reasoncode on ochy.reasoncode_id = reasoncode.reasoncode_id
, qualitygrade
, stockroom , ragreason, product prd, sizedefinition sz, languages
where ochy.ragreason_id is not null
and ochy.qualitygrade_id = qualitygrade.qualitygrade_id
and ochy.stockroom_id = stockroom.stockroom_id
and ochy.ragreason_id = ragreason.ragreason_id
and ochy.product_link_id = prd.product_id
and ochy.sizedefinition_link_id = sz.sizedefinition_id
/

  CREATE OR REPLACE VIEW "V_OUTSCANPERROUTE" ("ROUTECONTROL_ID", "ACTIVESTOCKDELIVERY_ID", "DRIVINGDATE", "ROUTENUMBER", "ROUTEDESC", "SUBSTITUTE", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "QUANTITYREQUESTED", "QUANTITYDELIVERED", "QUANTITYSUBSTITUTED", "LANGUAGECODE") AS 
  select rc.routecontrol_id, asd.activestockdelivery_id,
  rc.drivingdate, rt.routenumber, rt.description routedesc,
  (select count(*) from activestockdeliverydetail asdd where asdd.activestockdelivery_id = asd.activestockdelivery_id
     and asdd.detailinfo = 3) substitute,
  pl.code productcode,
  (select pld.description from product_link_desc pld where pl.product_link_id = pld.product_link_id
     and pld.language_id = lg.language_id) productdesc,
  sl.code sizecode,
--  (select sld.description from sizedefinition_link_desc sld where sld.sizedefinition_link_id = sl.sizedefinition_link_id
--     and sld.language_id = lg.language_id) sizedesc,
  asd.quantityrequested, asd.quantitydelivered, asd.quantitysubstituted,
  lg.code languagecode
from route rt, routecontrol rc, activestockdelivery asd, product_link pl, sizedefinition_link sl,
  languages lg
where rt.route_id = rc.route_id
  and rc.routecontrol_id = asd.routecontrol_id
  and asd.product_link_id = pl.product_link_id
  and asd.sizedefinition_link_id = sl.sizedefinition_link_id
  and asd.deliverfrom = 2
/

  CREATE OR REPLACE VIEW "V_OUTSCANPERROUTESUBSTITUTE" ("ACTIVESTOCKDELIVERY_ID", "QUANTITY", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "LANGUAGECODE") AS 
  select asdd.activestockdelivery_id, count(*) quantity,
  pl.code productcode,
  (select pld.description from product_link_desc pld where pld.product_link_id = pl.product_link_id
     and pld.language_id = lg.language_id) productdesc,
  sl.code sizecode, lg.code languagecode
from activestockdeliverydetail asdd, product_link pl, sizedefinition_link sl,
  languages lg
where asdd.substrproduct_id = pl.product_link_id
  and asdd.substrsizedefintion_id = sl.sizedefinition_link_id
  and asdd.detailinfo = 3
group by asdd.activestockdelivery_id, pl.code, sl.code, pl.product_link_id, lg.code, lg.language_id
/

  CREATE OR REPLACE VIEW "V_OUTSTANDINGSAMPLES" ("CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DISTRIBUTIONPOINTNUMBER", "DPDESCRIPTION", "DEPARTMENTNUMBER", "DEPDESCRIPTION", "PRODCODE", "PRODDESC", "SIZECODE", "SIZEDESC", "FINMCODE", "FINMDESC", "QUALITY", "QUANTITY", "ADJUSTMENTDATE", "EXPIRATIONDATE", "AUTOBILL", "BUSINESSUNIT_ID", "LANGUAGE") AS 
  select c.customer_id,c.customernumber,c.name customername,
dp.distributionpointnumber , dp.description dpdescription,
dep.departmentnumber , dep.description depdescription,
p.code prodcode,
 (select a.description from product_desc a where a.product_id = p.product_id
  and a.language_id = lang.language_id) proddesc,
sd.code sizecode,
(select sdd.description  from sizedefinition_desc sdd where sdd.sizedefinition_id=sd.sizedefinition_id
 and sdd.language_id=lang.language_id) sizedesc,
fm.code finmcode,
(select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id=fm.finishingmethod_id
 and fmd.language_id=lang.language_id) finmdesc,
qq.code quality, rqa.quantity ,
rqa.adjustmentdate, rqa.expirationdate , rqa.autobillonexpirationdate autobill,
bu.businessunit_id,lang.code language
from rentalqtyadjustment rqa, productlistperdistribpoint plpd,distributionpoint dp, department dep ,customer c,
product p, sizedefinition sd, finishingmethod fm,  qualitygrade qq, businessunit bu, languages lang
where rqa.productlistperdistribpoint_id=plpd.productlistperdistribpoint_id
and plpd.distributionpoint_id=dp.distributionpoint_id
and dp.department_id=dep.department_id
and dep.customer_id=c.customer_id
and plpd.product_id=p.product_id
and plpd.sizedefinition_id=sd.sizedefinition_id
and plpd.finishingmethod_id=fm.finishingmethod_id
and rqa.qualitygrade_id=qq.qualitygrade_id
and rqa.sampleitem='Y'
and rqa.autoprocessed='N' and rqa.quantity> 0--only  samples not processed
and (exists (select processbusinessunit_id
                from customeractivities ca
                where ca.customer_id = c.customer_id
                and ca.processbusinessunit_id = bu.businessunit_id)
        or bu.businessunit_id = c.defaultbusinessunit_id)
/

  CREATE OR REPLACE VIEW "V_OUTSTANDINGWORKORDERS" ("LINETYPE", "BUSINESSUNIT_ID", "DELIVERFROM", "WEAREREMPLOYMENT_LINK_ID", "ORIGIN", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEP_DESC", "DISTRIBUTIONPOINTNUMBER", "DISTRIBPOINT_DESC", "WEARERNUMBER", "FULLNAME", "FIRSTNAME", "SEARCHNAME", "WORKORDERNUMBER", "REQUESTDATE", "NEEDEDDATE", "QUANTITYORDERED", "QUANTITYCANCELLED", "QUANTITYFILLED", "OUTSTANDING", "STATUS_DESC", "STATUS_CODE", "PROD_CODE", "SIZE_CODE", "PRODGROUP_CODE", "PRODGROUP_DESC", "PROD_DESC", "SIZE_DESC", "REASON_CODE", "REFERENCENUMBER", "REASON_DESC", "LAN_CODE", "REMARK", "WOREFERENCENR", "WOREFNR_DESC", "NEEDFORBUID", "NEEDFORBUCODE", "INTPROCESSBUID", "INTPROCESSBUCODE") AS 
  select /*version 1.0*/
       1 linetype, parambu.businessunit_id, wo.deliverfrom, wo.weareremployment_link_id, wo.origin,
       cu.customernumber, cu.name customername, de.departmentnumber, de.description dep_desc,
       dp.distributionpointnumber, dp.description distribpoint_desc, w.wearernumber, w.fullname,
       w.firstname, w.searchname, wo.workordernumber, wo.requestdate, wo.neededdate,
       wol.quantityordered, wol.quantitycancelled, wol.quantityfilled,
       greatest((wol.quantityordered - wol.quantitycancelled - wol.quantityfilled), 0) outstanding,
       (select std.description
          from status_desc std
         where st.status_id = std.status_id
           and std.language_id = lan.language_id) status_desc,
       st.code status_code, pr.code prod_code, sd.code size_code,
       (select pg.code from productgroup pg where pg.productgroup_id = pr.productgroup_id) prodgroup_code,
       (select pgd.description
          from productgroup_desc pgd
         where pgd.productgroup_id = pr.productgroup_id
           and pgd.language_id = lan.language_id) prodgroup_desc,
       (select prd.description
          from product_desc prd
         where pr.product_id = prd.product_id
           and prd.language_id = lan.language_id) prod_desc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) size_desc, rc.code reason_code,
       wo.referencenumber referencenumber,
       (select rcd.description
          from reasoncode_desc rcd
         where rc.reasoncode_id = rcd.reasoncode_id
           and rcd.language_id = lan.language_id) reason_desc, lan.code lan_code, wo.remark,
       worefnr.referencenumber woreferencenr, worefnr.description worefnr_desc,
       f_getprocbuid(wo.workorder_id) needforbuid,
       (select b.code from businessunit b where b.businessunit_id = f_getprocbuid(wo.workorder_id)) needforbucode,
       coalesce(wo.internalprocessingbu_id, f_getintprocbuid(wo.workorder_id)) intprocessbuid,
       (select b.code
          from businessunit b
         where b.businessunit_id = coalesce(wo.internalprocessingbu_id, f_getintprocbuid(wo.workorder_id))) intprocessbucode
  from workorderline wol
       left join product pr on wol.product_link_id = pr.product_id
       left join sizedefinition sd on wol.sizedefinition_link_id = sd.sizedefinition_id
       join workorder wo
            left join woreferencenumber worefnr on wo.woreferencenumber_id = worefnr.woreferencenumber_id
            join status st on wo.status_id = st.status_id and st.statustype = 'WO'
            join reasoncode rc on wo.reasoncode_id = rc.reasoncode_id
            join weareremployment we
                 join wearer w
                      join customer cu on w.customer_id = cu.customer_id
                 on we.wearer_id = w.wearer_id
                 join distributionpoint dp
                      join department de on dp.department_id = de.department_id
                 on we.distributionpoint_id = dp.distributionpoint_id
            on wo.weareremployment_link_id = we.weareremployment_id
       on wol.workorder_id = wo.workorder_id
       cross join languages lan
       cross join businessunit parambu
 where de.customer_id = cu.customer_id
   and (parambu.businessunit_id = wo.businessunit_id
        or
        parambu.businessunit_id = (select st.managedbybu_id
                                     from stockroom st
                                    where wo.processingstockroom_id = st.stockroom_id)
       )
 union all
select 2 linetype, parambu.businessunit_id, wo.deliverfrom, wo.weareremployment_link_id, wo.origin,
       cu.customernumber, cu.name customername, de.departmentnumber, de.description dep_desc,
       dp.distributionpointnumber, dp.description distribpoint_desc, -1 wearernumber, '' fullname,
       '' firstname, '' searchname, wo.workordernumber, wo.requestdate, wo.neededdate,
       wol.quantityordered, wol.quantitycancelled, wol.quantityfilled,
       greatest((wol.quantityordered - wol.quantitycancelled - wol.quantityfilled), 0) outstanding,
       (select std.description
          from status_desc std
         where st.status_id = std.status_id
           and std.language_id = lan.language_id) status_desc, st.code status_code,
       pr.code prod_code, sd.code size_code,
       (select pg.code from productgroup pg where pg.productgroup_id = pr.productgroup_id) prodgroup_code,
       (select pgd.description
          from productgroup_desc pgd
         where pgd.productgroup_id = pr.productgroup_id
           and pgd.language_id = lan.language_id) prodgroup_desc,
       (select prd.description
          from product_desc prd
         where pr.product_id = prd.product_id
           and prd.language_id = lan.language_id) prod_desc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) size_desc,
       rc.code reason_code, wo.referencenumber referencenumber,
       (select rcd.description
          from reasoncode_desc rcd
         where rc.reasoncode_id = rcd.reasoncode_id
           and rcd.language_id = lan.language_id) reason_desc,
       lan.code lan_code, wo.remark, worefnr.referencenumber woreferencenr,
       worefnr.description worefnr_desc, f_getprocbuid(wo.workorder_id) needforbuid,
       (select b.code from businessunit b where b.businessunit_id = f_getprocbuid(wo.workorder_id)) needforbucode,
       coalesce(wo.internalprocessingbu_id, f_getintprocbuid(wo.workorder_id)) intprocessbuid,
       (select b.code
          from businessunit b
         where b.businessunit_id = coalesce(wo.internalprocessingbu_id, f_getintprocbuid(wo.workorder_id))) intprocessbucode
  from workorderline wol
       left join product pr on wol.product_link_id = pr.product_id
       left join sizedefinition sd on wol.sizedefinition_link_id = sd.sizedefinition_id
       join workorder wo
            left join woreferencenumber worefnr on wo.woreferencenumber_id = worefnr.woreferencenumber_id
            join status st on wo.status_id = st.status_id and st.statustype = 'WO'
            join reasoncode rc on wo.reasoncode_id = rc.reasoncode_id
            join distributionpoint dp
                 join department de
                      join customer cu on de.customer_id = cu.customer_id
                 on dp.department_id = de.department_id
            on wo.distributionpoint_link_id = dp.distributionpoint_id
       on wol.workorder_id = wo.workorder_id
       cross join languages lan
       cross join businessunit parambu
 where wo.weareremployment_link_id is null
   and wo.distributionpoint_link_id is not null
   and (parambu.businessunit_id = wo.businessunit_id
        or
        parambu.businessunit_id = (select st.managedbybu_id
                                     from stockroom st
                                    where wo.processingstockroom_id = st.stockroom_id)
       )
 union all
select 3 linetype, parambu.businessunit_id, wo.deliverfrom, wo.weareremployment_link_id, wo.origin,
       cu.customernumber, cu.name customername, -1 departmentnumber, '' dep_desc,
       -1 distributionpointnumber, '' distribpoint_desc, -1 wearernumber, '' fullname, '' firstname,
       '' searchname, wo.workordernumber, wo.requestdate, wo.neededdate, wol.quantityordered,
       wol.quantitycancelled, wol.quantityfilled,
       greatest((wol.quantityordered - wol.quantitycancelled - wol.quantityfilled), 0) outstanding,
       (select std.description
          from status_desc std
         where st.status_id = std.status_id
           and std.language_id = lan.language_id) status_desc,
       st.code status_code, pr.code prod_code, sd.code size_code,
       (select pg.code from productgroup pg where pg.productgroup_id = pr.productgroup_id) prodgroup_code,
       (select pgd.description
          from productgroup_desc pgd
         where pgd.productgroup_id = pr.productgroup_id
           and pgd.language_id = lan.language_id) prodgroup_desc,
       (select prd.description
          from product_desc prd
         where pr.product_id = prd.product_id
           and prd.language_id = lan.language_id) prod_desc,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) size_desc, rc.code reason_code,
       wo.referencenumber referencenumber,
       (select rcd.description
          from reasoncode_desc rcd
         where rc.reasoncode_id = rcd.reasoncode_id
           and rcd.language_id = lan.language_id) reason_desc, lan.code lan_code, wo.remark,
       worefnr.referencenumber woreferencenr, worefnr.description worefnr_desc,
       f_getprocbuid(wo.workorder_id) needforbuid,
       (select b.code from businessunit b where b.businessunit_id = f_getprocbuid(wo.workorder_id)) needforbucode,
       coalesce(wo.internalprocessingbu_id, f_getintprocbuid(wo.workorder_id)) intprocessbuid,
       (select b.code
          from businessunit b
         where b.businessunit_id = coalesce(wo.internalprocessingbu_id, f_getintprocbuid(wo.workorder_id))) intprocessbucode
  from workorderline wol
       left join product pr on wol.product_link_id = pr.product_id
       left join sizedefinition sd on wol.sizedefinition_link_id = sd.sizedefinition_id
       join workorder wo
            left join woreferencenumber worefnr on wo.woreferencenumber_id = worefnr.woreferencenumber_id
            left join customer cu on wo.customer_link_id = cu.customer_id
            join status st on wo.status_id = st.status_id and st.statustype = 'WO'
            join reasoncode rc on wo.reasoncode_id = rc.reasoncode_id
       on wol.workorder_id = wo.workorder_id
       cross join languages lan
       cross join businessunit parambu
 where wo.weareremployment_link_id is null
   and wo.distributionpoint_link_id is null
   and (parambu.businessunit_id = wo.businessunit_id
        or
        parambu.businessunit_id = (select st.managedbybu_id
                                     from stockroom st
                                    where wo.processingstockroom_id = st.stockroom_id)
       )
/

  CREATE OR REPLACE VIEW "V_OVERSFROMTERMINATIONS" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DATEINACTIVE", "TIMESTAMP", "DELIVERYDATE", "PRODUCTGROUPCODE", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "AMOUNT", "LANGUAGECODE", "BUCODE") AS 
  select c.customernumber,
c.name customername,
c.dateinactive,
dv.timestamp,
dv.deliverydate,
(select pg.code from productgroup pg where pg.productgroup_id = p.productgroup_id) productgroupcode,
p.code productcode,
(select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = l.language_id) productdesc,
sd.code sizecode,
dv.amount,
l.code languagecode,
(select bu.code from businessunit bu where bu.businessunit_id = c.defaultbusinessunit_id) bucode
from deliveryvariations dv
inner join distributionpoint dp on dv.distributionpoint_id = dp.distributionpoint_id
inner join department d on dp.department_id = d.department_id
inner join customer c on d.customer_id = c.customer_id
inner join product p on dv.product_id = p.product_id
inner join sizedefinition sd on dv.sizedefinition_id = sd.sizedefinition_id,
languages l
where dv.reasoncode_id = (select rc.reasoncode_id from reasoncode rc where rc.code = 'TER-ES')
and dv.amount > 0
/

  CREATE OR REPLACE VIEW "V_OVERUSE" ("CUSTOMERNUMBER", "NAME", "CUSTOMERLANGUAGECODE", "DEPARTMENTNUMBER", "DESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "DELIVERYPOINTCODE", "DELIVERYPOINTDESC", "PRODUCTCODE", "PRODUCTGROUPCODE", "PRODUCTDESC", "SIZECODE", "FINISHINGMETHODCODE", "DELIVERYSCHEMECODE", "SEASONCODE", "SEASONDESC", "ORDERINGMETHOD", "GENERATEZEROLINES", "CLEANRETURN", "DELIVERSTERILE", "CORRECTSHORTAGES", "CORRECTOVERDELIVERIES", "NUMBEROFTRANSPORTARTICLES", "OCCUPANCY", "STANDARDQTYDEFINITION", "TRANSPORTARTICLE_DESC", "DATEACTIVE", "DATEINACTIVE", "SYSTEMUSER_ID", "TIMESTAMP", "STANDARDDELIVERY_ID", "LANGUAGECODE", "ISTEMPDELSTOP", "BUSINESSUNIT_ID", "REPORTPARAM_ID", "FIXEDRENTQUANTITY", "STANDARDDELIVERYLINE_ID", "INCLUDEDQTY", "DELIVEREDQTY") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, W.CODE CUSTOMERLANGUAGECODE, DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION,
  DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION distributionpointdesc,
  DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESC, PR.CODE productcode,
  Z.CODE productgroupcode,
  (select a.DESCRIPTION from PRODUCT_DESC a where a.product_id = PR.PRODUCT_ID and a.language_id = LG.language_id) productdesc,
  SD.CODE sizecode,
  FM.CODE finishingmethodcode,
  Y.CODE deliveryschemecode,
  X.code SEASONCODE,
  (select STD.DESCRIPTION from SEASONTYPE_DESC STD where X.SEASONTYPE_ID=STD.SEASONTYPE_ID and STD.language_id = LG.language_id) SEASONDESC,
  PLPD.ORDERINGMETHOD, STANDARDDELIVERY.GENERATEZEROLINES, STANDARDDELIVERY.CLEANRETURN,
  STANDARDDELIVERY.DELIVERSTERILE, STANDARDDELIVERY.CORRECTSHORTAGES, STANDARDDELIVERY.CORRECTOVERDELIVERIES,
  STANDARDDELIVERY.NUMBEROFTRANSPORTARTICLES,
  DEPARTMENT.OCCUPANCY, CUSTOMER.STANDARDQTYDEFINITION,
  (select d.DESCRIPTION from TRANSPORTARTICLE_DESC D where D.TRANSPORTARTICLE_ID= STANDARDDELIVERY.TRANSPORTARTICLE_ID and D.language_id = LG.language_id) TRANSPORTARTICLE_DESC,
  trunc(STANDARDDELIVERYLINE.DATEACTIVE) DATEACTIVE, trunc(STANDARDDELIVERYLINE.DATEINACTIVE) DATEINACTIVE,
  STANDARDDELIVERYLINE.SYSTEMUSER_ID,
  STANDARDDELIVERYLINE.TIMESTAMP, standarddeliveryline.standarddelivery_id, LG.CODE languagecode,
  ISTEMPORARYDELIVERYSTOP(rp.number_value1, rp.number_value2, STANDARDDELIVERYLINE.Standarddeliveryline_Id)
  + ISTEMPORARYDELIVERYSTOP_DATE(rp.date_value1, STANDARDDELIVERYLINE.Standarddeliveryline_Id) istempdelstop,
   bu.businessunit_id, rp.reportparam_id, STANDARDDELIVERYLINE.Fixedrentquantity, STANDARDDELIVERYLINE.STANDARDDELIVERYLINE_ID
, (select sum(foca.quantity) from Freeofchargeadjustment FOCA where FOCA.Productlistperdistribpoint_Id = PLPD.Productlistperdistribpoint_Id
  and foca.adjustmenttype in (1, 4) and foca.adjustmentdate <= rp.date_value1
  and FOCA.AdjustmentDate >= F_GetMostRecentFreeOfChargeAdj(RP.DATE_VALUE1, PLPD.Productlistperdistribpoint_Id) and FOCA.AdjustmentDate <= RP.Date_Value1
  ) IncludedQty
, (select sum(DNL.Deliveredamount-DNL.Nochargeactiveseason-DNL.NOChargeFirstIssue-DNL.NoChargeFirstIssueCOG-DNL.Nochargegddeliveryforpool-DNL.Nochargegddeliveryforpoolcog-DNL.NoChargePrevRejected-DNL.NoChargePrevShortage-DNL.QtyFreeCleanChange)
   from PackingNoteLine dnl, packingnote DN, Status ST where DNL.Packingnote_Id = DN.Packingnote_Id and DN.Status_Id =	ST.Status_ID
  and (DN.DeliveryDate >= F_GetMostRecentFreeOfChargeAdj(RP.DATE_VALUE1, PLPD.Productlistperdistribpoint_Id) and DN.DeliveryDate <= RP.DATE_VALUE1)
   and nvl(dnl.freeofchargereason_id, 0) = 0 and nvl(DN.Freeofchargereason_Id, 0) = 0
   and st.Statustype = 'PN' And ST.Code = '30' and DN.Origin not in (5, 6, 11, 12, 13)
   and dn.distributionpoint_id = plpd.distributionpoint_id and dnl.product_id = pr.product_id
   and dnl.sizedefinition_id = sd.sizedefinition_id and dnl.finishingmethod_id = fm.finishingmethod_id
   ) DeliveredQty
FROM
  STANDARDDELIVERY
  inner join STANDARDDELIVERYLINE
         left outer join season X ON standarddeliveryline.season_id = X.season_id
         left outer join deliveryscheme Y ON standarddeliveryline.deliveryscheme_id = Y.deliveryscheme_id
         inner join PRODUCTLISTPERDISTRIBPOINT PLPD
             inner join DISTRIBUTIONPOINT
                   inner join DELIVERYPOINT on DISTRIBUTIONPOINT.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
                   inner join DEPARTMENT
                        inner join CUSTOMER
                              inner join LANGUAGES W on CUSTOMER.LANGUAGE_ID = W.LANGUAGE_ID
                        on DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
                   on DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
             on PLPD.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
             inner join PRODUCT PR
                   left outer join PRODUCTGROUP Z ON PR.PRODUCTGROUP_ID = Z.PRODUCTGROUP_ID
             on PLPD.PRODUCT_ID = PR.PRODUCT_ID
             inner join SIZEDEFINITION SD on PLPD.SIZEDEFINITION_ID = SD.SIZEDEFINITION_ID
             inner join FINISHINGMETHOD FM on PLPD.FINISHINGMETHOD_ID = FM.FINISHINGMETHOD_ID
          ON STANDARDDELIVERYLINE.PRODUCTLISTPERDISTRIBPOINT_ID = PLPD.PRODUCTLISTPERDISTRIBPOINT_ID
  on STANDARDDELIVERY.STANDARDDELIVERY_ID = STANDARDDELIVERYLINE.STANDARDDELIVERY_ID,
  LANGUAGES LG, reportparam rp, businessunit bu
WHERE DEPARTMENT.ACTIVE = 'Y' and plpd.freeqtyperiod = 1 and PLPD.Freeqtyfrequency = 2
  and exists (select ca.customer_id
        from   customeractivities ca
        where  ca.activity_id = z.activity_id and ca.customer_id = customer.customer_id and
               ca.processbusinessunit_id = bu.businessunit_id) --Overuse.rpt
/

  CREATE OR REPLACE VIEW "V_OVERUSEAPPENDIX" ("INVOICEHEADER_ID", "INVOICEDATE", "INVOICENUMBER", "STARTDATE", "ENDDATE", "STARTWEEK", "STARTMONTH", "STARTYEAR", "ENDWEEK", "ENDMONTH", "ENDYEAR", "YEAR", "WEEK", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINT_DESC", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "COSTCENTER_CODE", "COSTCENTER_DESC", "CUSTOMERNUMBER", "CUSTOMER_NAME", "WEARERNUMBER", "FULLNAME", "STREET", "STREET2", "ZIPCODE", "CITY", "PRODUCTCODE", "TYPEOFMERCHANDISE", "SIZECODE", "CHANGESPERWEEK", "DELIVEREDQUANTITY", "SIZEDEF_DESC", "PRODUCT_DESC", "LANGUAGE_CODE") AS 
  select /*v_bdm_overuse_wearer version 0.9*/
 ih.invoiceheader_id, ih.invoicedate, ih.invoicenumber, ih.startdate, ih.enddate,
 ih.startweek, ih.startmonth, ih.startyear, ih.endweek, ih.endmonth, ih.endyear,
 sqh.year, sqh.week, dp.distributionpointnumber, dp.description distributionpoint_desc,
 de.departmentnumber, de.description departmentdesc, cc.code costcenter_code, cc.description costcenter_desc,
 c.customernumber, c.name customer_name, w.wearernumber, w.fullname, a.street, a.street2, a.zipcode, a.city,
 p.code productcode, p.typeofmerchandise, s.code sizecode, sqset.changesperweek,
 coalesce((select count(1)
   from   deliveryscan ds
   join   packingnote pn on ds.packingnote_id = pn.packingnote_id
   where  ds.customer_link_id = w.customer_id
   and    ds.weareremployment_link_id = sqset.weareremployment_link_id
   and    ds.distributionpoint_link_id = sqset.distributionpoint_link_id
   and    ds.product_link_id = sqset.product_link_id
   and    ds.sizedefinition_link_id = sqset.sizedefinition_link_id
   and    pn.deliverydate between getdateforweekyear(1, sqh.week, sqh.year) and
          getdateforweekyear(7, sqh.week, sqh.year)
   and    ds.fromstock <> 'Y'), 0) deliveredquantity,
 (select sd.description from sizedefinition_desc sd where sd.sizedefinition_id = s.sizedefinition_id and sd.language_id = l.language_id) sizedef_desc,
 (select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = l.language_id) product_desc,
  l.code language_code
from  invoiceheader ih,
      statusquoheader sqh
      join sqsetincirculation sqset
            join weareremployment we
                join wearer w
                     join customer c
                            join address a on c.visitaddress_id = a.address_id
                     on w.customer_id = c.customer_id
                on we.wearer_id = w.wearer_id
                join distributionpoint dp
                       join costcenter cc on dp.costcenter_id = cc.costcenter_id
                       join department de on dp.department_id = de.department_id
                on we.distributionpoint_id = dp.distributionpoint_id
            on sqset.weareremployment_link_id = we.weareremployment_id
            join product p on sqset.product_link_id = p.product_id
            join sizedefinition s on sqset.sizedefinition_link_id = s.sizedefinition_id
      on sqh.statusquoheader_id = sqset.statusquoheader_id
      cross join languages l
where  sqh.statusquotype = 2 and sqset.totalcircinv > 0
       and exists (select 1 from productlistpercustomer plpc
                   where  plpc.customer_id = w.customer_id
                   and    plpc.product_id = sqset.product_link_id
                   and    ih.invoicedate between plpc.dateactive and plpc.dateinactive
                   and    plpc.finishingmethod_id = (select f.finishingmethod_id from finishingmethod f where f.code = 'OVRUSE'))
        and ih.deltocustomer_link_id = c.customer_id
        and (sqh.year*100+sqh.week) >= (case when getisoweek(ih.startdate) in (52, 53) then
                                             year(trunc(ih.startdate, 'iw'))*100+coalesce(getisoweek(ih.startdate), ih.startweek)
                                             else
                                               ih.startyear*100+coalesce(getISOweek(ih.startdate), ih.startweek)
                                        end)
        and (sqh.year*100+sqh.week) <= ih.endyear*100+coalesce(getisoweek(next_day(ih.enddate - 7, 1)), ih.endweek)
union all
select /*v_bdm_overuse_cpl version 0.5*/
 ih.invoiceheader_id, ih.invoicedate, ih.invoicenumber, ih.startdate, ih.enddate,
 ih.startweek, ih.startmonth, ih.startyear, ih.endweek, ih.endmonth, ih.endyear,
 pn.year, pn.week, x.distributionpointnumber, x.distributionpoint_desc,
 x.departmentnumber, x.departmentdesc, x.costcenter_code, x.costcenter_desc,
 x.customernumber, x.customer_name, -1 wearernumber, '' fullname,
 x.street, x.street2, x.zipcode, x.city,
 x.productcode, x.typeofmerchandise, x.sizecode, x.fixedrentquantity changesperweek,
 sum(pnl.deliveredamount) deliveredquantity,
 (select sd.description from sizedefinition_desc sd where sd.sizedefinition_id = pnl.sizedefinition_id and sd.language_id = l.language_id) sizedef_desc,
 (select pd.description from product_desc pd where pd.product_id = pnl.product_id and pd.language_id = l.language_id) product_desc,
 l.code language_code
from invoiceheader ih,
packingnote pn
join packingnoteline pnl on pn.packingnote_id = pnl.packingnote_id
join (select c.customernumber, t.departmentnumber, dp.distributionpointnumber, p.code productcode, p.typeofmerchandise,
               s.code sizecode, stl.fixedrentquantity, plpd.distributionpoint_id, plpd.product_id,
               plpd.sizedefinition_id, plpd.finishingmethod_id, stl.dateactive, stl.dateinactive,
               t.customer_id, dp.description distributionpoint_desc, t.description departmentdesc, c.name customer_name,
               a.street, a.street2, a.zipcode, a.city, cc.code costcenter_code, cc.description costcenter_desc
        from   standarddeliveryline stl
         join productlistperdistribpoint plpd
               join distributionpoint dp
                       join costcenter cc on dp.costcenter_id = cc.costcenter_id
                       join department t
                             join customer c
                                   join address a on c.visitaddress_id = a.address_id
                            on t.customer_id = c.customer_id
                      on dp.department_id = t.department_id
              on plpd.distributionpoint_id = dp.distributionpoint_id
              join product p on plpd.product_id = p.product_id
              join sizedefinition s on plpd.sizedefinition_id = s.sizedefinition_id
        on stl.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
        where  stl.fixedrentquantity > 0) x
     on (x.distributionpoint_id = pn.distributionpoint_id and x.product_id = pnl.product_id and
         x.sizedefinition_id = pnl.sizedefinition_id and
         x.finishingmethod_id = pnl.finishingmethod_id and pn.deliverydate between x.dateactive and x.dateinactive)
cross join languages l
where  pn.status_id = (select st.status_id from status st where st.statustype = 'PN' and st.code = '30')
and exists (select 1 from productlistpercustomer plpc
            where  plpc.customer_id = x.customer_id
              and  plpc.product_id = pnl.product_id
              and  plpc.sizedefinition_id = pnl.sizedefinition_id
              and  ih.invoicedate between plpc.dateactive and plpc.dateinactive
              and  plpc.finishingmethod_id = (select f.finishingmethod_id from finishingmethod f where f.code = 'OVRUSE'))
and ih.deltocustomer_link_id = x.customer_id
and (pn.year*100+pn.week) >= ih.startyear*100+coalesce(getisoweek(ih.startdate), ih.startweek)
and (pn.year*100+pn.week) <= ih.endyear*100+coalesce(getisoweek(getdateforyearmonthday(ih.endyear, ih.endmonth, extract(day from getlastday(getdateforyearmonthday(ih.endyear, ih.endmonth, 20))))), ih.endweek)--(ih.endyear*100+ih.endweek)
group by ih.invoiceheader_id, ih.invoicedate, ih.invoicenumber, ih.startdate, ih.enddate,
         ih.startweek, ih.startmonth, ih.startyear, ih.endweek, ih.endmonth, ih.endyear,
         pn.year, pn.week, pnl.product_id, pnl.sizedefinition_id, x.costcenter_code, x.costcenter_desc,
         x.distributionpointnumber, x.distributionpoint_desc, x.departmentnumber, x.departmentdesc,
         x.customernumber, x.customer_name, x.street, x.street2, x.zipcode, x.city,
         x.productcode, x.typeofmerchandise, x.sizecode, x.fixedrentquantity, l.language_id, l.code
/

  CREATE OR REPLACE VIEW "V_PACKCONTENTS" ("PACK_ID", "PACKPRODUCTCODE", "PACKPRODUCTDESCRIPTION", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZECODE", "SIZEDESCRIPTION", "AMOUNT", "PACKSEQUENCE", "REMARK", "LOCATION", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  select /*version 2.0*/
 pc.pack_id, packprod.code packproductcode,
 (select description from product_desc a where a.product_id = pc.pack_id
  and a.language_id = languages.language_id) packproductdescription,
 prod.code productcode,
 (select description from product_desc b where b.product_id = pc.product_id
  and b.language_id = languages.language_id) productdescription,
 sd.code sizecode,
 (select description from sizedefinition_desc c where c.sizedefinition_id = pc.sizedefinition_id
  and c.language_id = languages.language_id) sizedescription,
 pc.amount, pc.packsequence, pc.remark, pc.location,
 pc.systemuser_id, pc.timestamp, languages.code languagecode
from packcontents pc
     join product packprod on pc.pack_id = packprod.product_id
     join product prod on pc.product_id = prod.product_id
     join sizedefinition sd on pc.sizedefinition_id = sd.sizedefinition_id
     cross join languages
/

  CREATE OR REPLACE VIEW "V_PACKER_LINEN" ("ROUTECONTROL_ID", "PLANT_ID", "CUSTOMERNUMBER", "NAME", "STREET", "CITY", "ZIPCODE", "ROUTENUMBER", "DAYCODE", "STOPNUMBER", "DRIVINGDATE", "PLANTDEPARTMENTCODE", "PRODUCTCODE", "PRODUCTDESC", "DELIVERYSCHEMECODE", "BUNDLEQTY", "TOBEDELIVEREDAMOUNT", "TOTALSOILCOUNT", "CURRENTBUNDLE", "NOOFBUNDLES", "PACKINGNOTE_ID", "LANGUAGE_CODE") AS 
  select rc.routecontrol_id, rc.plant_id, cu.customernumber, cu.name, ad.street, ad.city, ad.zipcode, ro.routenumber,
       (select dd.code
          from day_desc dd
         where dd.day_id = ro.drivingday_id
           and dd.language_id = pl.language_id) daycode, stop.stopnumber, rc.drivingdate,
       (select pld.code
          from plantdepartment pld
         where pn.plantdepartment_id = pld.plantdepartment_id) plantdepartmentcode,
       pr.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = pnl.product_id
           and pd.language_id = pl.language_id) productdesc,
       (select ds.code
          from packingnotelineperdelscheme pnlds, deliveryscheme ds
         where pnlds.packingnoteline_id = pnl.packingnoteline_id
           and pnlds.deliveryscheme_id = ds.deliveryscheme_id
           and ds.frequency in (select min(ds.frequency)
                                  from packingnotelineperdelscheme pnlds, deliveryscheme ds
                                 where pnlds.packingnoteline_id = pnl.packingnoteline_id
                                   and pnlds.deliveryscheme_id = ds.deliveryscheme_id)) deliveryschemecode,
       pnl.bundleqty, pnl.tobedeliveredamount,
       (select sum(dv.amount)
          from deliveryvariations dv
         where dv.packingnote_id = pn.packingnote_id
           and dv.product_id = pnl.product_id
           and dv.origin = 1) totalsoilcount,
       c.nr currentbundle, f_packernoofbundles(pnl.tobedeliveredamount, pnl.bundleqty) noofbundles, pn.packingnote_id,
       (select lan.code
          from languages lan
         where lan.language_id = cu.language_id) language_code
  from packingnoteline pnl
  join packingnote pn
       join stop
            left join customer cu on stop.customer_link_id = cu.customer_id
            join routecontrol rc on stop.routecontrol_id = rc.routecontrol_id
            join plant pl on rc.plant_id = pl.plant_id
            join route ro on rc.route_id = ro.route_id
         on pn.stop_id = stop.stop_id
       join distributionpoint dp
            join deliverypoint delp
                 join address ad on delp.deliveryaddress_id = ad.address_id
              on dp.deliverypoint_id = delp.deliverypoint_id
         on pn.distributionpoint_id = dp.distributionpoint_id
    on pnl.packingnote_id = pn.packingnote_id
  join product pr on pnl.product_id = pr.product_id
     , (select rownum nr from (select 1 just_a_column from dual connect by level <= 99)) c
 where pnl.putuptype = 3 --packer / bundle tag
   and c.nr <= f_packernoofbundles(pnl.tobedeliveredamount, pnl.bundleqty)
   and not exists (select 1
                     from productlistpercustomer plpc
                    where plpc.customer_id = cu.customer_id
                      and plpc.product_id = pnl.product_id
                      and plpc.sizedefinition_id = pnl.sizedefinition_id
                      and plpc.finishingmethod_id = pnl.finishingmethod_id
                      and plpc.suppressonpackingreports = 2)
   and not exists (select 1
                     from plantproductsettings pps
                    where pps.plant_id = pl.plant_id
                      and pps.product_id = pnl.product_id
                      and pps.suppressonpackingreports = 2)
   and pr.suppressonpackingreports <> 2
/

  CREATE OR REPLACE VIEW "V_PACKER_LOOSELINEN" ("ROUTECONTROL_ID", "PLANT_ID", "DRIVINGDATE", "ROUTENUMBER", "DAYCODE", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "BUNDLEQTY", "REPORTPARAM_ID", "TOBEDELIVEREDAMOUNT", "PLANTDEPARTMENTCODE", "CURRENTBUNDLE", "NOOFBUNDLES", "LANGUAGE_CODE") AS 
  select x.routecontrol_id, x.plant_id, x.drivingdate, (select r.routenumber from route r where r.route_id = x.route_id) routenumber,
       (select dd.code
          from route r, day_desc dd, plant pl
         where r.route_id = x.route_id
           and pl.plant_id = x.plant_id
           and r.drivingday_id = dd.day_id
           and dd.language_id = pl.language_id) daycode, (select p.code from product p where x.product_id = p.product_id) productcode,
       (select pd.description
          from product_desc pd, plant pl
         where pd.product_id = x.product_id
           and pl.plant_id = x.plant_id
           and pl.language_id = pd.language_id) productdesc,
       (select s.code from sizedefinition s where s.sizedefinition_id = x.sizedefinition_id) sizecode,
       x.bundleqty, x.reportparam_id, x.tobedeliveredamount,
       (select pld.code
          from plantdepartment pld
         where x.plantdepartment_id = pld.plantdepartment_id) plantdepartmentcode,
       c.nr currentbundle, f_packernoofbundles(x.tobedeliveredamount, x.bundleqty) noofbundles, x.language_code
  from (select rc.plant_id, rc.routecontrol_id, rc.drivingdate, rc.route_id, pn.plantdepartment_id, pnl.product_id,
               pnl.sizedefinition_id, pnl.bundleqty, rp.reportparam_id, sum(pnl.tobedeliveredamount) tobedeliveredamount,
               (select lan.code
                  from languages lan
                 where lan.language_id = cu.language_id) language_code
          from reportparam rp
          join packingnoteline pnl
               join packingnote pn
                    join stop st
                         join customer cu on st.customer_link_id = cu.customer_id
                         join routecontrol rc
                              join plant p on rc.plant_id = p.plant_id
                         on st.routecontrol_id = rc.routecontrol_id
                      on pn.stop_id = st.stop_id
                 on pnl.packingnote_id = pn.packingnote_id
               join product pr on pnl.product_id = pr.product_id
            on rp.number_value = pnl.packingnote_id
         where pnl.putuptype = 5 --packer loose linen
           and not exists (select 1
                             from productlistpercustomer plpc
                            where plpc.customer_id = cu.customer_id
                              and plpc.product_id = pnl.product_id
                              and plpc.sizedefinition_id = pnl.sizedefinition_id
                              and plpc.finishingmethod_id = pnl.finishingmethod_id
                              and plpc.suppressonpackingreports = 2)
           and not exists (select 1
                             from plantproductsettings pps
                            where pps.plant_id = p.plant_id
                              and pps.product_id = pnl.product_id
                              and pps.suppressonpackingreports = 2)
           and pr.suppressonpackingreports <> 2
      group by rc.plant_id, rc.routecontrol_id, rc.drivingdate, rc.route_id, pn.plantdepartment_id,
               pnl.product_id, pnl.sizedefinition_id, rp.reportparam_id, pnl.bundleqty, st.customer_link_id, cu.language_id) x
     , (select rownum nr from (select 1 just_a_column from dual connect by level <= 999)) c
 where c.nr <= f_packernoofbundles(x.tobedeliveredamount, x.bundleqty)
/

  CREATE OR REPLACE VIEW "V_PACKINGNOTE" ("PACKINGNOTEID", "STATUSTYPE", "DRIVINGDATE", "DEPOTCODE", "DEPOTDESCRIPTION", "NOTENUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMERLEGALNAME", "STREET", "STREET2", "CITY", "STATE", "ZIPCODE", "COUNTY", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "SORTADDRESS", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "DELIVERYPOINTCODE", "DELIVERYPOINTDESCRIPTION", "SEQUENCENUMBER", "PACKINGDEPARTMENTCODE", "PACKINGDEPARTMENTDESCRIPTION", "TRANSPORTARTICLECODE", "OCCUPANCY", "EMPLOYEENUMBER", "EMPLOYEENAME", "PRODUCTIONDATE", "DELIVERYDATE", "STATUSCODE", "REMARK", "PROCESSBUCODE", "PROCESSBUDESCRIPTION", "INVOICEBUCODE", "INVOICEBUDESCRIPTION", "ROUTENUMBER", "ROUTEDESCRIPTION", "LOADINGDOCK", "PACKINGDAY", "PACKINGDEADLINE", "CLEANRETURN", "DEADLINE", "DEADLINEASNUMERIC", "CONSIGNMENTNOTENUMBER", "SYSTEMUSER_ID", "TIMESTAMP", "CREATIONTIMESTAMP", "ENDDATEFORUSE", "WEEK", "LANGUAGECODE", "DRIVERNAME", "DRIVERNUMBER", "STOPNUMBER", "PUTUPREPORTPERCUSTOMER", "EXTRANAME1", "CUSTOMERSEARCHNAME", "ORIGIN", "YEAR", "REMARKONPACKINGNOTE", "REMARKONDELIVERYNOTE", "DISTRICTDESC", "DISTRICTCODE", "PNREMARK", "REFERENCENUMBER", "BULKPUTUPONPACKINGNOTE", "PACKINGNOTECOLUMNS", "BULKPUTUPSORTING", "DELIVERGARMENTS", "LAYOUTCODE", "DAYDESCRIPTION", "STATUSDESCRIPTION", "TRANSPORTARTICLEDESCRIPTION", "MARKET_SEGMENT") AS 
  select /*version 3.0*/
       pn.packingnote_id packingnoteid, st.statustype,  rc.drivingdate, dt.code depotcode, dt.description depotdescription, pn.notenumber, cu.customernumber,
       cu.name customername, cu.legalname customerlegalname, ads.street, ads.street2, ads.city, ads.state, ads.zipcode, ads.county, dep.departmentnumber,
       dep.description departmentdescription, dep.sortaddress, distp.distributionpointnumber, distp.description distributionpointdescription, delp.code deliverypointcode,
       delp.description deliverypointdescription, pn.sequencenumber, pd.code packingdepartmentcode, pd.description packingdepartmentdescription, tar.code transportarticlecode,
       pn.occupancy, emp.employeenumber, emp.name employeename, pn.productiondate, pn.deliverydate, st.code statuscode, pn.remark, procbu.code processbucode,
       procbu.description processbudescription, invbu.code invoicebucode, invbu.description invoicebudescription, ro.routenumber, ro.description routedescription,
       ro.loadingdock, packday.daynumber packingday, ro.packingdeadline, pn.cleanreturn, pn.deadline, gettimeasnumeric(pn.deadline) deadlineasnumeric, cn.consignmentnotenumber,
       pn.systemuser_id, pn.timestamp, pn.creationtimestamp, pn.enddateforuse, cast(pn.week as varchar2(2)) week, lan.code languagecode, driver.name drivername,
       driver.employeenumber drivernumber, pn.stopnumber, ro.putupreportpercustomer, cu.extraname1, cu.searchname customersearchname, pn.origin, pn.year year,
       distp.remarkonpackingnote, distp.remarkondeliverynote, di.code districtdesc, di.description districtcode, pn.pnremark, pn.referencenumber,
       case when cu.delnoteforbulkputupitems = 0 then 'N'
            else 'Y'
        end bulkputuponpackingnote,
       (select ss.value
          from systemsetting ss
         where ss.plant_id = procbu.plant_id
           and ss.name = 'PACKINGNOTECOLUMNS') packingnotecolumns,
       (select ss1.value
          from systemsetting ss1
         where ss1.plant_id = procbu.plant_id
           and ss1.name = 'BULKPUTUPSORTING') bulkputupsorting,
       (select count(1)
          from customerdeliveryday cdd
         where cu.customer_id = cdd.customer_id
           and cdd.day_id = pn.daynumber
           and cdd.typeofmerchadise = 2) delivergarments,
       (select fly.code
          from formlayout fly
         where fly.formlayout_id = cu.deliverynotelayout_id) layoutcode,
       (select dds.description
          from day_desc dds
         where dds.language_id = lan.language_id
           and dds.day_id = pn.daynumber) daydescription,
       (select sds.description
          from status_desc sds
         where sds.status_id = pn.status_id
           and sds.language_id = lan.language_id ) statusdescription,
       (select tas.description
          from transportarticle_desc  tas
         where tas.transportarticle_id = pn.transportarticle_id
           and tas.language_id = lan.language_id ) transportarticledescription,
       (select ms.code
          from marketsegment ms
         where ms.marketsegment_id = cu.marketsegment_id) market_segment
  from packingnote pn
       left join employee emp on pn.employee_id = emp.employee_id
       left join routecontrol rc on pn.routecontrol_id = rc.routecontrol_id
       left join consignmentnote cn on pn.consignmentnote_id = cn.consignmentnote_id
       left join route ro
            left join depot dt on ro.depot_id = dt.depot_id
            left join employee driver on ro.driver_id = driver.employee_id
            left join day packday on ro.packingday_id = packday.day_id
            join district di on ro.district_id = di.district_id
       on pn.route_id = ro.route_id
       join deliverypoint delp
            join address ads on delp.deliveryaddress_id = ads.address_id
       on pn.deliverypoint_id = delp.deliverypoint_id
       join plantdepartment pd on pn.plantdepartment_id = pd.plantdepartment_id
       join businessunit procbu on pn.processbusinessunit_id = procbu.businessunit_id
       join businessunit invbu on pn.invoicebusinessunit_id = invbu.businessunit_id
       join distributionpoint distp
            join department dep
                 join customer cu on dep.customer_id = cu.customer_id
            on distp.department_id = dep.department_id
       on pn.distributionpoint_id = distp.distributionpoint_id
       join transportarticle tar on pn.transportarticle_id = tar.transportarticle_id
       join status st on pn.status_id = st.status_id,
       languages lan
 where st.statustype = 'PN'
   and cast(st.code as numeric) <= 20
/

  CREATE OR REPLACE VIEW "V_PACKINGNOTELINE" ("PACKINGNOTEID", "PRODUCTGROUPCODE", "PRODUCTCODE", "PACKINGSEQUENCE", "PACKINGAMOUNT", "PRODUCTCUSTOMCODE", "PRODUCTCUSTOMDESCRIPTION", "SIZECODE", "STANDARDAMOUNT", "VARIATIONAMOUNT", "DELIVEREDAMOUNT", "TOBEDELIVEREDAMOUNT", "NODELIVERYAMOUNT", "PRICE", "DISCOUNT", "LOCATION", "REMARKFORPACKINGINSTRUCTIONS", "SYSTEMUSER_ID", "TIMESTAMP", "PUTUPTYPE", "PACKINGNOTELINE_ID", "PACKINGAMOUNTPSZ", "BUNDLEQTY", "PRODUCT_ID", "ISPACK", "PRICECOG", "CLEANLOADQTY", "SEQUENCENUMBER", "NOCHARGEPREVSHORTAGE", "NOCHARGEPREVREJECTED", "LANGUAGECODE", "REPLACEMENTQTY", "REPLACEMENTLOSSQTY", "PROD_PACKINGSEQUENCE", "PRODUCTDESCRIPTION", "PRODUCTLONGDESCRIPTION", "ACTIVITYCODE", "ACTIVITYDESCRIPTION", "SIZEDESCRIPTION", "FINISHINGMETHODDESCRIPTION", "FINISHINGMETHODCODE", "THEORETICALWEIGHT", "BULKPUTUP", "PACKINGGROUP") AS 
  select /*version 2.1*/
       pnl.packingnote_id packingnoteid, pg.code productgroupcode, pr.code productcode, pnl.packingsequence, pr.packingamount, pnl.customcode productcustomcode,
       pnl.customdescription productcustomdescription, sd.code sizecode, pnl.standardamount, pnl.variationamount, pnl.deliveredamount, pnl.tobedeliveredamount, pnl.nodeliveryamount,
       coalesce(pnl.price, 0) price, pnl.discount, pnl.location, pnl.remarkforpackinginstructions, pnl.systemuser_id, pnl.timestamp, pnl.putuptype, pnl.packingnoteline_id,
       psz.packingamount packingamountpsz, pnl.bundleqty, pr.product_id, pr.pack ispack, coalesce(pnl.pricecog, 0) pricecog, pnl.cleanloadqty, psz.sequencenumber, pnl.nochargeprevshortage,
       pnl.nochargeprevrejected, lan.code languagecode, pnl.replacementqty, pnl.replacementlossqty, pr.packingsequence prod_packingsequence,
       (select prd.description
          from product_desc prd
         where prd.product_id = pnl.product_id
           and prd.language_id = lan.language_id) productdescription,
       (select prd.longdescription
          from product_desc prd
         where prd.product_id = pnl.product_id
           and prd.language_id = lan.language_id) productlongdescription, act.code activitycode,
       (select actd.description
          from activity_desc actd
         where actd.activity_id = act.activity_id
           and actd.language_id = lan.language_id) activitydescription,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = pnl.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedescription,
       (select fmd.description
          from finishingmethod_desc fmd
         where fmd.finishingmethod_id = pnl.finishingmethod_id
           and fmd.language_id = lan.language_id) finishingmethoddescription, fm.code finishingmethodcode,
       case when psz.theoreticalweight = 0 then pr.theoreticalweight
            else psz.theoreticalweight
        end theoreticalweight,
       case when pnl.putuptype = 2 then 'Y'
            else 'N'
        end bulkputup,
       coalesce((select pps.packinggroup
                   from plantproductsettings pps
                  where pps.plant_id = pbu.plant_id
                    and pps.product_id = pr.product_id), pr.packinggroup) packinggroup
  from packingnoteline pnl
       join productsize psz on pnl.product_id = psz.product_id and pnl.sizedefinition_id = psz.sizedefinition_id
       join product pr
            join productgroup pg
                 join activity act on pg.activity_id = act.activity_id
            on pr.productgroup_id = pg.productgroup_id
       on pnl.product_id = pr.product_id
       join sizedefinition sd on pnl.sizedefinition_id = sd.sizedefinition_id
       join finishingmethod fm on pnl.finishingmethod_id = fm.finishingmethod_id
       join packingnote pn
            join businessunit pbu on pn.processbusinessunit_id = pbu.businessunit_id
            join distributionpoint dp
                 join department de on dp.department_id = de.department_id
            on pn.distributionpoint_id = dp.distributionpoint_id
       on pnl.packingnote_id = pn.packingnote_id
       cross join languages lan
 where not exists (select 1
                     from productlistpercustomer plpc
                    where plpc.customer_id = de.customer_id
                      and plpc.product_id = pr.product_id
                      and plpc.sizedefinition_id = sd.sizedefinition_id
                      and plpc.finishingmethod_id = fm.finishingmethod_id
                      and plpc.suppressonpackingreports = 2)
   and not exists (select 1
                     from plantproductsettings pps
                    where pps.plant_id = pbu.plant_id
                      and pps.product_id = pr.product_id
                      and pps.suppressonpackingreports = 2)
   and pr.suppressonpackingreports <> 2
/

  CREATE OR REPLACE VIEW "V_PACKINGNOTELINEPERDELSCH" ("PACKINGNOTELINE_ID", "STARTDATE", "TOBEDELIVEREDQTY", "DELIVEREDQTY", "CODE", "DEFAULTDELIVERYSCHEME", "FREQUENCY", "OFFSETWEEK", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  select /*version 2.0*/
       pd.packingnoteline_id, pd.startdate, pd.tobedeliveredqty, pd.deliveredqty, sc.code,
       sc.defaultdeliveryscheme, sc.frequency, sc.offsetweek, pd.systemuser_id, pd.timestamp
from packingnotelineperdelscheme pd
     join deliveryscheme sc on pd.deliveryscheme_id = sc.deliveryscheme_id
/

  CREATE OR REPLACE VIEW "V_PACKINGNOTELINE_PRE" ("PACKINGNOTEID", "PRODUCTGROUPCODE", "PRODUCTCODE", "PRODUCTDESCRIPTION", "ACTIVITYCODE", "ACTIVITYDESCRIPTION", "PRODUCTCUSTOMCODE", "PRODUCTCUSTOMDESCRIPTION", "SIZECODE", "SIZEDESCRIPTION", "FINISHINGMETHODDESCRIPTION", "FINISHINGMETHODCODE", "PACKINGSEQUENCE", "PACKINGAMOUNT", "THEORETICALWEIGHT", "STANDARDAMOUNT", "VARIATIONAMOUNT", "DELIVEREDAMOUNT", "TOBEDELIVEREDAMOUNT", "PRICE", "DISCOUNT", "LOCATION", "REMARKFORPACKINGINSTRUCTIONS", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE", "BULKPUTUP", "PUTUPTYPE", "PACKINGNOTELINE_ID", "PACKINGAMOUNTPSZ", "BUNDLEQTY", "PRODUCT_ID", "ISPACK", "PRICECOG", "SEQUENCENUMBER", "DV_AMOUNT", "DV_AMOUNT2") AS 
  SELECT PNL.Packingnote_Id,--PACKINGNOTE.PACKINGNOTE_ID,
  PG.code, --PACKINGNOTE.NOTENUMBER,
  P.code productcode,
  (select description from product_desc p where p.product_id = pnl.product_id
     and p.language_id = l.language_id)  productdescription, -- productdescription
  A.code activitycode,
  (select description from activity_desc ad where ad.activity_id = a.activity_id
     and ad.language_id = l.language_id)  activitydescription,
  PNL.customcode,
  PNL.customdescription, -- productcustomdescription
  Sd.code sizecode,
  (select description from sizedefinition_desc s where s.sizedefinition_id = pnl.sizedefinition_id
     and s.language_id = l.language_id)  SIZEdescription,
  (select description from finishingmethod_desc f where f.finishingmethod_id = pnl.finishingmethod_id
     and f.language_id = l.language_id)  FINISHINGMETHODdescription,
  FM.code FINISHINGMETHODcode,
  PNL.packingsequence,
  P.packingamount,
  Case
   when PSZ.theoreticalweight = 0 then P.theoreticalweight
	 else PSZ.theoreticalweight
   end  theoreticalweight,--  product.theoreticalweight
  PNL.standardamount,
  PNL.variationamount,
  PNL.deliveredamount,
  PNL.tobedeliveredamount,
  (case when PNL.PRICE is null then 0 else PNL.PRICE end) price,
  PNL.discount,
  PNL.location,
  PNL.remarkforpackinginstructions,
  PNL.SYSTEMUSER_ID,
  PNL.TIMESTAMP,
  L.code languagecode,
  case when PNL.putuptype = 2 then 'Y' else 'N' end bulkputup,
  PNL.putuptype,
  PNL.packingnoteline_id,
  PSZ.packingamount packingamountPSZ,
  PNL.Bundleqty,
  P.product_id,
  P.pack isPack,
  (case when PNL.PRICECOG is null then 0 else PNL.PRICECOG end) pricecog
  , psz.sequencenumber
  ,(select sum(dv.amount)    --> CNE
    from deliveryvariations dv--, packingnote pn
    where dv.product_id = PNL.product_id
    and dv.sizedefinition_id = PNL.sizedefinition_id
    and dv.finishingmethod_id = PNL.finishingmethod_id
    and PNL.packingnote_id=PN.packingnote_id
    and dv.distributionpoint_id = PN.distributionpoint_id
   -- and dv.deliverydate <= pn.deliverydate ----?
    and dv.packingnote_id = pn.packingnote_id
    ---and dv.processed = 'N' ---????????
    and dv.amount > 0) dv_amount,
    (select sum(dv.amount)
    from deliveryvariations dv
    where dv.product_id = P.product_id
    and dv.sizedefinition_id = SD.sizedefinition_id
    and dv.finishingmethod_id = FM.finishingmethod_id
    and dv.distributionpoint_id = PN.distributionpoint_id
    and dv.packingnote_id is null
    --and dv.processed = 'N'
    and dv.amount > 0
    ) dv_amount2          --< CNE
FROM PACKINGNOTELINE PNL, FINISHINGMETHOD FM,
      PACKINGNOTE PN,
      DISTRIBUTIONPOINT DP,DEPARTMENT D,CUSTOMER C,
      PRODUCT P,PRODUCTGROUP PG, ACTIVITY A,
      SIZEDEFINITION SD, LANGUAGES L, PRODUCTSIZE PSZ
WHERE PNL.PACKINGNOTE_ID = PN.PACKINGNOTE_ID
	    AND PNL.PRODUCT_ID = P.PRODUCT_ID
      AND PNL.SIZEDEFINITION_ID = SD.SIZEDEFINITION_ID
      AND PG.PRODUCTGROUP_ID = P.PRODUCTGROUP_ID
      AND FM.FINISHINGMETHOD_ID = PNL.FINISHINGMETHOD_ID
      AND P.PRODUCT_ID = PSZ.PRODUCT_ID
      AND PSZ.SIZEDEFINITION_ID = SD.SIZEDEFINITION_ID
      AND PG.ACTIVITY_ID = A.ACTIVITY_ID
--      AND PN.PACKINGNOTE_ID = PNL.PACKINGNOTE_ID
      AND PN.DISTRIBUTIONPOINT_ID = DP.DISTRIBUTIONPOINT_ID
      AND DP.DEPARTMENT_ID = D.DEPARTMENT_ID
      AND D.CUSTOMER_ID = C.CUSTOMER_ID
      AND C.LANGUAGE_ID = L.LANGUAGE_ID
--CNE
/*UNION ALL
SELECT PN.packingnote_id packingnoteid,
 PG.code productgroupcode,
 P.code productcode,
(select description from product_desc p where P.product_id = DV.product_id and
 P.language_id = C.language_id)  productdescription ,
 A.code activitycode,
 (select activity_desc.description from activity_desc where activity_desc.activity_id = A.activity_id and
   activity_desc.language_id = C.language_id) activitydescription,
 PLPC.customcode ,
 PLPC.customdescription ,
 SD.code sizecode ,
 (select description from sizedefinition_desc  where sizedefinition_desc.sizedefinition_id = SD.sizedefinition_id and
   sizedefinition_desc.language_id = C.language_id) sizedescription ,
 (select finishingmethod_desc.description from finishingmethod_desc where finishingmethod_desc.finishingmethod_id = FM.finishingmethod_id and
   finishingmethod_desc.language_id = C.language_id) finishingmethoddescription ,
 FM.code finishingmethodcode ,
 P.packingsequence,
 PSZ.packingamount,
 PSZ.theoreticalweight ,
 0,
 0,
 0,
 0,
 null,
 null,
 null,
 null,
 null,
 null,
 (select code from languages l where l.language_id = C.language_id) languagecode ,
 null,
 null,
 null,
 null,
 null,
 P.product_id,
 P.pack isPack,
 0,
 PSZ.sequencenumber,
 (select sum(dv.amount)
    from deliveryvariations dv
    where dv.product_id = P.product_id
    and dv.sizedefinition_id = SD.sizedefinition_id
    and dv.finishingmethod_id = FM.finishingmethod_id
    and dv.distributionpoint_id = PN.distributionpoint_id
    and dv.packingnote_id is null
    and dv.processed = 'N'
    and dv.amount > 0
    ) dv_amount
FROM PACKINGNOTE PN, DISTRIBUTIONPOINT DP,DEPARTMENT D,
DELIVERYVARIATIONS DV,PRODUCT P,PRODUCTGROUP PG
,CUSTOMER C,PACKINGNOTELINE PNL,ACTIVITY A,PRODUCTSIZE PSZ,
PRODUCTLISTPERCUSTOMER PLPC,SIZEDEFINITION SD,FINISHINGMETHOD FM
WHERE
DV.DISTRIBUTIONPOINT_ID = PN.DISTRIBUTIONPOINT_ID
AND DV.DELIVERYDATE <= PN.DELIVERYDATE
AND DV.PRODUCT_ID = P.PRODUCT_ID
AND P.PRODUCTGROUP_ID = PG.PRODUCTGROUP_ID
AND P.PRODUCT_ID = PSZ.PRODUCT_ID
AND PSZ.SIZEDEFINITION_ID = SD.SIZEDEFINITION_ID
AND A.ACTIVITY_ID = PG.ACTIVITY_ID
AND PLPC.PRODUCT_ID = P.PRODUCT_ID
AND PLPC.SIZEDEFINITION_ID = SD.SIZEDEFINITION_ID
AND PLPC.FINISHINGMETHOD_ID = FM.FINISHINGMETHOD_ID
AND PLPC.CUSTOMER_ID = C.CUSTOMER_ID
AND PLPC.DATEACTIVE <= DV.DELIVERYDATE
AND DV.DELIVERYDATE < PLPC.DATEINACTIVE
AND DV.PACKINGNOTE_ID IS NULL
AND PN.DISTRIBUTIONPOINT_ID = DP.DISTRIBUTIONPOINT_ID
AND DP.DEPARTMENT_ID = D.DEPARTMENT_ID
AND D.CUSTOMER_ID = C.CUSTOMER_ID*/
--CNE
/

  CREATE OR REPLACE VIEW "V_PACKINGNOTELNPERDELSCH" ("PACKINGNOTELINE_ID", "STARTDATE", "TOBEDELIVEREDQTY", "DELIVEREDQTY", "CODE", "DEFAULTDELIVERYSCHEME", "FREQUENCY", "OFFSETWEEK", "DELIVERYSCHEME_DESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGE_CODE") AS 
  SELECT PD.PACKINGNOTELINE_ID, PD.STARTDATE, PD.TOBEDELIVEREDQTY, PD.DELIVEREDQTY,
       SC.CODE, SC.DEFAULTDELIVERYSCHEME, SC.FREQUENCY, SC.OFFSETWEEK,
       (SELECT SCD.DESCRIPTION
              FROM deliveryscheme_desc SCD
              WHERE SCD.DELIVERYSCHEME_ID = SC.DELIVERYSCHEME_ID
                    AND SCD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) DELIVERYSCHEME_DESCRIPTION,
       pd.systemuser_id, pd.timestamp,
       LANGUAGES.CODE LANGUAGE_CODE
FROM packingnotelineperdelscheme PD, DELIVERYSCHEME SC, LANGUAGES
WHERE PD.DELIVERYSCHEME_ID = SC.DELIVERYSCHEME_ID
/

  CREATE OR REPLACE VIEW "V_PACKINGNOTEVARIATION" ("SELECT_NR", "PACKINGNOTE_ID", "PACKINGNOTELINE_ID", "REFERENCE", "REASONCODE", "REASONCODEDESC", "ORIGIN", "AMOUNT", "DVDELDATE", "DELIVERYDATE", "LANGUAGE_CODE", "PN_PSF", "DVOTHERSOIL", "PRODUCT_ID", "SIZEDEFINITION_ID", "FINISHINGMETHOD_ID") AS 
  select -- + INDEX (dv XSPEED2DELIVERYVARIATIONS)
1 select_nr, pn.packingnote_id, pnl.packingnoteline_id, dv.reference
,(select rc.code from reasoncode rc where dv.adjustmentreason_id = rc.reasoncode_id) reasoncode
,(select rc.description from reasoncode_desc rc where dv.adjustmentreason_id = rc.reasoncode_id and rc.language_id = lan.language_id) reasoncodedesc
, dv.origin, dv.amount, to_char(dv.deliverydate,'DD-MON-YYYY') dvdeldate, dv.deliverydate
, lan.code Language_code
, (pn.packingnote_id || pnl.product_id || pnl.sizedefinition_id || pnl.finishingmethod_id) pn_psf,
 (case when ((select -- + INDEX (dvc XSPEED2DELIVERYVARIATIONS)
                    min(dvc.deliveryvariations_id) from deliveryvariations dvc
              where dvc.packingnote_id = pn.packingnote_id and dvc.product_id = pnl.product_id
              and dvc.sizedefinition_id = pnl.sizedefinition_id and dvc.finishingmethod_id = pnl.finishingmethod_id
              and dvc.deliveryvariations_id <> dv.deliveryvariations_id and dvc.origin > 1) > 0)
       then 1 else 0 END) dvothersoil
, pnl.product_id, pnl.sizedefinition_id, pnl.finishingmethod_id
from packingnote pn, packingnoteline pnl, deliveryvariations dv, languages lan
where dv.packingnote_id = pn.packingnote_id
and pnl.packingnote_id = pn.packingnote_id
and dv.product_id = pnl.product_id
and dv.sizedefinition_id = pnl.sizedefinition_id
and dv.finishingmethod_id = pnl.finishingmethod_id
and (dv.productconversioncpl_id is null or (dv.productconversioncpl_id is not null and dv.updaterentqty = 'Y' and dv.amount > 0))
union all
select -- + INDEX (dv XSPEED2DELIVERYVARIATIONS)
2 select_nr, pn.packingnote_id, -1 packingnoteline_id, dv.reference
,(select rc.code from reasoncode rc where dv.adjustmentreason_id = rc.reasoncode_id) reasoncode
,(select rc.description from reasoncode_desc rc where dv.adjustmentreason_id=rc.reasoncode_id and rc.language_id = lan.language_id) reasoncodedesc
, dv.origin, dv.amount, to_char(dv.deliverydate,'DD-MON-YYYY') dvdeldate, dv.deliverydate
, lan.code Language_code
, (pn.packingnote_id || dv.product_id || dv.sizedefinition_id || dv.finishingmethod_id) pn_psf,
1 dvothersoil, dv.product_id, dv.sizedefinition_id, dv.finishingmethod_id
from packingnote pn, deliveryvariations dv, languages lan, product p, sizedefinition sd, finishingmethod fm
where dv.packingnote_id = pn.packingnote_id
and dv.product_id = p.product_id
and dv.sizedefinition_id = sd.sizedefinition_id
and dv.finishingmethod_id = fm.finishingmethod_id
and not exists (select pnl1.packingnoteline_id from packingnoteline pnl1
                where pn.packingnote_id = dv.packingnote_id
                and pn.packingnote_id = pnl1.packingnote_id
                and pnl1.product_id = dv.product_id
                and pnl1.sizedefinition_id = dv.sizedefinition_id
                and pnl1.finishingmethod_id = dv.finishingmethod_id)
and (dv.productconversioncpl_id is null or (dv.productconversioncpl_id is not null and dv.updaterentqty = 'Y' and dv.amount > 0))
union all
select -- + INDEX (dv XSPEED3DELIVERYVARIATIONS)
3 select_nr, pn.packingnote_id, coalesce((select pnl1.packingnoteline_id from packingnoteline pnl1
    where pn.packingnote_id = dv.causenote_id and pn.packingnote_id = pnl1.packingnote_id
    and pnl1.product_id = dv.product_id and pnl1.sizedefinition_id = dv.sizedefinition_id
    and pnl1.finishingmethod_id = dv.finishingmethod_id),-1) packingnoteline_id , dv.reference
,(select rc.code from reasoncode rc where dv.adjustmentreason_id = rc.reasoncode_id) reasoncode
,(select rc.description from reasoncode_desc rc where dv.adjustmentreason_id=rc.reasoncode_id and rc.language_id = lan.language_id) reasoncodedesc
, dv.origin, dv.amount, to_char(dv.deliverydate,'DD-MON-YYYY') dvdeldate, dv.deliverydate
, lan.code Language_code
, (pn.packingnote_id || dv.product_id || dv.sizedefinition_id || dv.finishingmethod_id) pn_psf,
1 dvothersoil, dv.product_id, dv.sizedefinition_id, dv.finishingmethod_id
from packingnote pn, deliveryvariations dv, languages lan, product p, sizedefinition sd, finishingmethod fm
where dv.causenote_id = pn.packingnote_id
and dv.product_id = p.product_id
and dv.sizedefinition_id = sd.sizedefinition_id
and dv.finishingmethod_id = fm.finishingmethod_id
and dv.amount < 0 and dv.adjustmentreason_id is not null and dv.origin in (4,5)
and exists ( select 1 from deliveryvariations soildv where soildv.packingnote_id = pn.packingnote_id and soildv.origin = 1-- soil
              and soildv.product_id = dv.product_id and soildv.sizedefinition_id = dv.sizedefinition_id
              and soildv.finishingmethod_id = dv.finishingmethod_id)
/

  CREATE OR REPLACE VIEW "V_PACKINGNOTE_PACKCONTENTS" ("PACK_ID", "PACKCONTENTS_ID", "PACKSEQUENCE", "PRODUCT_ID", "PRODUCT_CODE", "SIZEDEFINITION_ID", "SIZE_CODE", "FINISHINGMETHOD_ID", "FINMETH_CODE", "REMARK", "LOCATION", "AMOUNT", "LANGUAGE_CODE", "PRODUCT_DESC", "SIZE_DESC", "FINMETH_DESC") AS 
  select /*version 2.0*/
       pc.pack_id, pc.packcontents_id, pc.packsequence, pc.product_id, p.code product_code, pc.sizedefinition_id, s.code size_code,
       pc.finishingmethod_id, f.code finmeth_code, pc.remark, pc.location, pc.amount, l.code language_code,
       (select pd.description
          from product_desc pd
         where pd.product_id = p.product_id
           and pd.language_id = l.language_id) product_desc,
       (select sd.description
          from sizedefinition_desc sd
         where sd.sizedefinition_id = s.sizedefinition_id
           and sd.language_id = l.language_id) size_desc,
       (select fd.description
          from finishingmethod_desc fd
         where fd.finishingmethod_id = f.finishingmethod_id
           and fd.language_id = l.language_id) finmeth_desc
 from packcontents pc
      join product p on pc.product_id = p.product_id
      join sizedefinition s on pc.sizedefinition_id = s.sizedefinition_id
      join finishingmethod f on pc.finishingmethod_id = f.finishingmethod_id
      cross join languages l
/

  CREATE OR REPLACE VIEW "V_PATIENTDAY" ("DISTRIBUTIONPOINT_LINK_ID", "YEAR", "MONTH", "PATIENTDAYS", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  select "DISTRIBUTIONPOINT_LINK_ID","YEAR","MONTH","PATIENTDAYS","SYSTEMUSER_ID","TIMESTAMP" from patientday
/

  CREATE OR REPLACE VIEW "V_PATIENTDAYS_CC" ("PATIENTDAYSCC", "COSTCENTER_ID", "REPORTPARAM_ID") AS 
  select f_getpatientdays(cc.costcenter_id, rp.reportparam_id, 'CC') patientdaysCC,cc.costcenter_id, rp.reportparam_id
from costcenter cc, reportparam rp
group by cc.costcenter_id, rp.reportparam_id
/

  CREATE OR REPLACE VIEW "V_PATIENTDAYS_CUST" ("PATIENTDAYSCUST", "CUSTOMER_ID", "REPORTPARAM_ID") AS 
  select f_getpatientdays(cu.customer_id, rp.reportparam_id, 'CUST') patientdaysCust, cu.customer_id, rp.reportparam_id
from customer cu, reportparam rp
group by cu.customer_id, rp.reportparam_id
/

  CREATE OR REPLACE VIEW "V_PATIENTDAYS_DEP" ("PATIENTDAYSDEP", "DEPARTMENT_ID", "REPORTPARAM_ID") AS 
  select  f_getpatientdays(dpl.department_id, rp.reportparam_id, 'DEP') patientdaysDep,dpl.department_id, rp.reportparam_id
from department dpl, reportparam rp
group by dpl.department_id, rp.reportparam_id
/

  CREATE OR REPLACE VIEW "V_PATIENTDAYS_DSP" ("PATIENTDAYSDSP", "DISTRIBUTIONPOINT_ID", "REPORTPARAM_ID") AS 
  select f_getpatientdays(dsp.distributionpoint_id,rp.reportparam_id, 'DSP') patientdaysDsp, dsp.distributionpoint_id, rp.reportparam_id
from distributionpoint dsp, reportparam rp
group by dsp.distributionpoint_id, rp.reportparam_id
/

  CREATE OR REPLACE VIEW "V_PATIENTDAY_BENCHMARKINVOICE" ("PATIENTDAYS", "PATIENTS", "AVERAGE_STAY", "PD_CUNUMBER", "PD_COSTCENTERCODE", "BUDGETRELEVANT", "REPORTPARAM_ID", "INVOICEAMOUNTDECIMALS") AS 
  select
  case when cc.budgetrelevant = 'Y' then sum(pday.patientdays) else 0 end  patientdays
, case when cc.budgetrelevant = 'Y' then sum(pday.patients) else 0 end patients
, case when SUM(pday.patients) <> 0 then sum(pday.patientdays) / SUM(pday.patients)
         else 0 end Average_stay
, cu.customernumber pd_cuNumber
, cc.code pd_costcentercode, cc.budgetrelevant
, rp.reportparam_id
, currency.invoiceamountdecimals
from
  patientday pday, customer cu, costcenter cc, distributionpoint dip
, reportparam rp, currency
where
    cu.customer_id = cc.customer_id
and cc.costcenter_id = dip.costcenter_id
and dip.distributionpoint_id = pday.distributionpoint_link_id
and cu.currency_id = currency.currency_id
and pday.year = rp.number_value1
and
    (
     ( rp.number_value2 = 0 and rp.number_value3 = 0
         and pday.month between rp.number_value4 and rp.number_value5 )
     or
     ( rp.number_value4 = 0 and rp.number_value5 = 0
         and pday.week between rp.number_value2 and rp.number_value3 )
    )
group by
  cu.customernumber, cc.code, rp.reportparam_id, currency.invoiceamountdecimals, cc.budgetrelevant
/

  CREATE OR REPLACE VIEW "V_PENDINGDELIVERIES" ("COUNTPACKINGNOTELINE", "COUNTPLANTDEP", "PDCODE", "PDDESC", "COUNTROUTE", "ROUTENUMBER", "PRODUCTCODE", "SIZECODE", "FINCODE", "PRODUCT_ID", "SIZEDEFINITION_ID", "FINISHINGMETHOD_ID", "FINISHINGMETHOD_DESC", "SIZEDEFINITION_DESC", "VARIATIONAMOUNT", "STANDARDAMOUNT", "TOBEDELIVEREDAMOUNT", "DELIVEREDAMOUNT") AS 
  select 0 countpackingnoteline,
       count(distinct std.plantdepartment_id) countplantdep,
       min(pd.code) pdcode,
       min(pd.description) pddesc,
       0 countroute,
       null routenumber,
       p.code productcode,
       s.code sizecode,
       f.code fincode,
       p.product_id,
       s.sizedefinition_id,
       f.finishingmethod_id,
       (select description
          from finishingmethod_desc
         where finishingmethod_desc.finishingmethod_id =
               f.finishingmethod_id
           and language_id = 62) finishingmethod_desc,
       (select description
          from sizedefinition_desc
         where sizedefinition_desc.sizedefinition_id = s.sizedefinition_id
           and language_id = 62) sizedefinition_desc,
       0 variationamount,
       0 standardamount,
       0 tobedeliveredamount,
       0 deliveredamount
  from product                    p,
       sizedefinition             s,
       finishingmethod            f,
       productlistperdistribpoint plpd,
       standarddeliveryline       stdl,
       standarddelivery           std
  left outer join plantdepartment pd on pd.plantdepartment_id =
                                        std.plantdepartment_id
 where plpd.distributionpoint_id = 19748 --12783
   and plpd.productlistperdistribpoint_id =
       stdl.productlistperdistribpoint_id
   and stdl.dateactive <= trunc(sysdate) - 2
   and stdl.dateinactive > trunc(sysdate) - 2
   and std.standarddelivery_id = stdl.standarddelivery_id
   and plpd.product_id = p.product_id
   and plpd.sizedefinition_id = s.sizedefinition_id
   and plpd.finishingmethod_id = f.finishingmethod_id
 group by p.code,
          s.code,
          f.code,
          p.product_id,
          s.sizedefinition_id,
          f.finishingmethod_id --,
--plpc.productlistpercustomer_id,*/
union all
select count(1) countpackingnoteline,
       count(distinct pn.plantdepartment_id) countplantdep,
       min(pd.code) pdcode,
       min(pd.description) pddesc,
       count(distinct rc.route_id) countroute,
       min(route.routenumber) routenumber,
       p.code productcode,
       s.code sizecode,
       f.code fincode,
       p.product_id,
       s.sizedefinition_id,
       f.finishingmethod_id,
       --plpc.productlistpercustomer_id,
       (select description
          from finishingmethod_desc
         where finishingmethod_desc.finishingmethod_id =
               f.finishingmethod_id
           and language_id = 62) finishingmethod_desc,
       (select description
          from sizedefinition_desc
         where sizedefinition_desc.sizedefinition_id = s.sizedefinition_id
           and language_id = 62) sizedefinition_desc,
       sum(pnl.variationamount) variationamount,
       sum(pnl.standardamount) standardamount,
       sum(pnl.tobedeliveredamount) tobedeliveredamount,
       sum(pnl.deliveredamount) deliveredamount
  from --productlistpercustomer plpc,
       plantdepartment pd,
       packingnote     pn
  left outer join(routecontrol rc
  left outer join route on route.route_id = rc.route_id) on pn.routecontrol_id = rc.routecontrol_id, packingnoteline pnl, product p, sizedefinition s, finishingmethod f
 where /*plpc.customer_id = 1901
    and plpc.dateactive < trunc(sysdate)-2
    and plpc.dateinactive > trunc(sysdate)-2*/
 pn.distributionpoint_id = 19748
 and ((pn.routecontrol_id is null and pn.deliverydate = trunc(sysdate) - 2) or
 (pn.routecontrol_id is not null and rc.drivingdate = trunc(sysdate) - 2))
 and pn.plantdepartment_id = pd.plantdepartment_id
--and pnl.product_id = plpc.product_id
/*and (plpc.sizedefinition_id = 541 or
        pnl.sizedefinition_id = plpc.sizedefinition_id )
    and pnl.finishingmethod_id = plpc.finishingmethod_id */
 and pn.packingnote_id = pnl.packingnote_id
 and pn.status_id not in (select s.status_id
                          from status s
                          where s.statustype = 'PN'
                          and s.code in (40, 60))
 and p.product_id = pnl.product_id
 and pnl.sizedefinition_id = s.sizedefinition_id
 and pnl.finishingmethod_id = f.finishingmethod_id
 group by p.code,
          s.code,
          f.code,
          p.product_id,
          s.sizedefinition_id,
          f.finishingmethod_id --,
--plpc.productlistpercustomer_id,**/
/

  CREATE OR REPLACE VIEW "V_PERIODACTUALBUDGET" ("CUSTOMERNUMBER", "CUSTOMER_ID", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "WEBSESSION_ID", "WEBUSER_ID", "WEB_DEPARTMENT_ID", "DEPARTMENT_LINK_ID", "REPORTPARAM_ID", "PATIENTDAYSDEP", "WEIGHT", "BUDGET", "ACTUAL", "INVOICEAMOUNTDECIMALS", "DECIMALS", "CURRENCYCODE", "LANGUAGECODE") AS 
  select
  cu.customernumber, cu.customer_id , cu.name customerName, delk.departmentnumber, delk.description departmentDesc
, websession.websession_id, wcu.webuser_id, wde.department_id web_department_id, delk.department_link_id, rp.reportparam_id
, coalesce(( select sum(pdy.patientdays) from patientday pdy, distributionpoint_link
             where distributionpoint_link.department_link_id = delk.department_link_id
             and distributionpoint_link.distributionpoint_link_id = pdy.distributionpoint_link_id
--             and pdy.year = rp.number_value
--             and pdy.month between rp.number_value1 and rp.number_value2
               AND pdy.year*100+pdy.month between (rp.number_value*100+rp.number_value1) and (rp.number_value3*100+rp.number_value2)
             group by distributionpoint_link.department_link_id),0) patientdaysDep
, coalesce(sum(dh.amountdelivered * coalesce(psz.theoreticalweight, prd.theoreticalweight)
                          ),0) weight
, coalesce(( select sum(budget.amount) from budget
                    where budget.department_link_id = delk.department_link_id
--                          and RP.NUMBER_VALUE = budget.YEAR
--                              and budget.MONTH BETWEEN RP.NUMBER_VALUE1 AND RP.NUMBER_VALUE2 ),0) Budget
                      AND budget.year*100+budget.month between (rp.number_value*100+rp.number_value1) and (rp.number_value3*100+rp.number_value2)),0) Budget
, coalesce(sum(dh.amountdelivered *
  F_RESTOCKINGPRICE(dh.customer_link_id, dh.product_link_id, dh.sizedefinition_link_id
                                         , dh.finishingmethod_id, dh.deliverydate, prd.typeofmerchandise)),0) Actual
, currency.invoiceamountdecimals, currency.decimals, currency.code currencyCode
, languages.code languageCode
from
  deliveryhistory dh
, webusercustomer wcu left outer join webuserdepartment wde on wcu.webusercustomer_id = wde.webusercustomer_id
, websession, customer cu, department_link delk
, product prd, productsize psz, sizedefinition sz, customermonth cm
, currency, reportparam rp , languages
where
    dh.packindication <> 2
and dh.customer_link_id = cu.customer_id
and dh.customer_link_id= wcu.customer_id
and dh.customer_link_id = websession.customer_id
and dh.department_link_id = delk.department_link_id
and dh.product_link_id = prd.product_id
    and prd.product_id = psz.product_id
        and psz.sizedefinition_id = sz.sizedefinition_id
and dh.sizedefinition_link_id = sz.sizedefinition_id
and dh.customer_link_id = cm.customer_id
--    AND CM.YEAR = RP.NUMBER_VALUE
--        AND CM.MONTH BETWEEN RP.NUMBER_VALUE1 AND RP.NUMBER_VALUE2
    and CM.YEAR*100+CM.MONTH BETWEEN (RP.NUMBER_VALUE*100+RP.NUMBER_VALUE1) AND (RP.NUMBER_VALUE3*100+RP.NUMBER_VALUE2)
            and dh.deliverydate between cm.startdate and cm.enddate
and cu.currency_id = currency.currency_id
group by
  cu.customernumber, cu.customer_id, cu.name , delk.departmentnumber, delk.description
, websession.websession_id, wcu.webuser_id, wde.department_id, delk.department_link_id
, currency.invoiceamountdecimals, currency.decimals, currency.code
, languages.language_id, languages.code
, rp.reportparam_id, rp.number_value, rp.number_value1, rp.number_value2, rp.number_value3
/

  CREATE OR REPLACE VIEW "V_PERIODACTUALBUDGETNEW" ("YEAR", "MONTH", "CUSTOMERNUMBER", "CUSTOMER_ID", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "WEBSESSION_ID", "WEBUSER_ID", "WEB_DEPARTMENT_ID", "DEPARTMENT_LINK_ID", "PATIENTDAYSDEP", "WEIGHT", "BUDGET", "ACTUAL", "INVOICEAMOUNTDECIMALS", "DECIMALS", "CURRENCYCODE", "BUDGETRELEVANT") AS 
  select /*view v_periodactualbudgetnew version 0.2*/
 x.year year, x.month month, max(c.customernumber) customernumber, c.customer_id,
 max(c.name) customername, max(delk.departmentnumber) departmentnumber,
 max(delk.description) departmentdesc, wus.websession_id, wcu.webuser_id,
 x.department_link_id web_department_id, x.department_link_id,
 coalesce((select sum(pdy.patientdays)
           from   patientday pdy, distributionpoint_link
           where  distributionpoint_link.department_link_id = x.department_link_id
           and    distributionpoint_link.distributionpoint_link_id = pdy.distributionpoint_link_id
           and    pdy.year = x.year
           and    pdy.month = x.month
           group  by distributionpoint_link.department_link_id), 0) patientdaysdep,
 sum(x.weight) weight,
 coalesce((select sum(budget.amount)
           from   budget
           where  budget.department_link_id = x.department_link_id
           and    budget.year = x.year
           and    budget.month = x.month
           and    budget.week = 0), 0) budget,
 coalesce(sum(x.amountdelivered *
               (select f_getcostreportprice(x.customer_link_id, x.product_link_id,
                                             x.sizedefinition_link_id, x.finishingmethod_id,
                                             x.deliverydate, x.typeofmerchandise, x.weighingcategory_id,
                                             max(cr.decimals))
                from   dual)), 0) actual, max(cr.invoiceamountdecimals) invoiceamountdecimals,
 max(cr.decimals) decimals, cr.code currencycode,
 coalesce(max((select max(plpc.budgetrelevant)
               from   productlistpercustomer plpc
               where  plpc.customer_id = x.customer_link_id
               and    plpc.product_id = x.product_link_id
               and    (plpc.sizedefinition_id = x.sizedefinition_link_id or
                     plpc.sizedefinition_id in
                     (select szdef.sizedefinition_id
                        from   sizedefinition szdef
                        where  szdef.code = '*'))
               and    plpc.finishingmethod_id = x.finishingmethod_id
               and    plpc.dateactive <= x.deliverydate
               and    plpc.dateinactive >= x.deliverydate)), 'N') budgetrelevant
from   (select cm.year, cm.month, dh.deliverydate, dh.customer_link_id, dh.department_link_id,
                dh.product_link_id, dh.sizedefinition_link_id, dh.finishingmethod_id,
                coalesce(sum(dh.amountdelivered * case
                               when dh.pieceweight <> 0 then
                                dh.pieceweight
                               else
                                nvl(ps.theoreticalweight, 0)
                             end), 0) weight, sum(dh.amountdelivered) amountdelivered,
                max(px.weighingcategory_id) weighingcategory_id,
                max(px.typeofmerchandise) typeofmerchandise
         from   customermonth cm
         join   deliveryhistory dh
         on     (dh.customer_link_id = cm.customer_id and dh.deliverydate between cm.startdate and
                cm.enddate)
         join   product px
         on     px.product_id = dh.product_link_id
         join   productsize ps
         on     ps.product_id = dh.product_link_id
         and    ps.sizedefinition_id = dh.sizedefinition_link_id
         where  dh.packindication <> 2
         group  by cm.year, cm.month, dh.deliverydate, dh.customer_link_id, dh.department_link_id,
                   dh.product_link_id, dh.sizedefinition_link_id, dh.finishingmethod_id) x
join   customer c
on     c.customer_id = x.customer_link_id
join   webusercustomer wcu
on     wcu.customer_id = x.customer_link_id
left   outer join webuserdepartment wde
on     wde.webusercustomer_id = wcu.webusercustomer_id
and    wde.department_id = x.department_link_id
join   webusersession wus
on     wus.customer_id = x.customer_link_id
join   department_link delk
on     delk.department_link_id = x.department_link_id
join   currency cr
on     cr.currency_id = c.currency_id
group  by x.year, x.month, c.customer_id, wus.websession_id, wcu.webuser_id, x.department_link_id,
          cr.code, x.customer_link_id, x.product_link_id, x.sizedefinition_link_id,
          x.finishingmethod_id
/

  CREATE OR REPLACE VIEW "V_PICKLIST" ("CUSTOMER_ID", "CUSTOMERNUMBER", "NAME", "ROUTENUMBER", "DELIVERYDATE", "ROUTEDESC", "PLANTDEPARTMENT_CODE", "PLANTDEPARTMENT_DESC", "PACKINGDEADLINE", "PRODUCT_CODE", "PRODUCT_DESCRIPTION", "SIZEDEFINITION_CODE", "FINISHINGMETHOD_CODE", "SIZEDEFINITION_DESC", "FINISHINGMETHOD_DESC", "TOTAL_QTY", "BUNDLES", "THEORETICALWEIGHT", "TOBEDELIVEREDAMOUNT", "CONNECTEDPACKINGNOTES", "PACKINGSEQUENCE", "CURRENTDATE", "LANGUAGECODE") AS 
  select cu.customer_id,
  cu.customernumber, cu.Name, Route.routenumber, pn.deliverydate deliverydate, Route.Description RouteDesc
, plantdepartment.code plantdepartment_code, plantdepartment.description plantdepartment_desc
, route.packingdeadline, prd.code product_code
,( select description from product_desc where product_desc. product_id = prd.product_id
  and product_desc.language_id = languages.language_id) product_description
, sz.code sizedefinition_code, fm.code finishingmethod_code
,( select szd.description from sizedefinition_desc szd where szd.sizedefinition_id = sz.sizedefinition_id
  and szd.language_id = languages.language_id) sizedefinition_desc
,( select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
  and fmd.language_id = languages.language_id) finishingmethod_desc
, pnl.tobedeliveredamount total_Qty, psz.packingamount Bundles, psz.theoreticalweight
, pnl.tobedeliveredamount, pn.notenumber ConnectedPackingNotes, prd.packingsequence
, trunc(sysdate) CurrentDate
, languages.code languageCode
from
  packingnote pn
    left outer join route on pn.Route_ID = Route.Route_ID
, status, distributionpoint dip, department de, customer cu
, plantdepartment
, packingnoteline pnl, product prd, sizedefinition sz, finishingmethod fm
, productsize psz
, languages
where
    pn.status_id = status.status_id
    and status.statustype = 'PN'
        and status.code IN ('10','20')
and pn.Distributionpoint_ID = dip.Distributionpoint_ID
    and dip.Department_ID = de.Department_ID
        and de.Customer_ID = cu.Customer_ID
and pn.plantdepartment_id = plantdepartment.plantdepartment_id
and pn.packingnote_id = pnl.packingnote_id
    and pnl.product_id = prd.product_id
        and pnl.sizedefinition_id = sz.sizedefinition_id
            and pnl.finishingmethod_id = fm.finishingmethod_id
and psz.product_id = prd.product_id
and psz.sizedefinition_id = sz.sizedefinition_id
/

  CREATE OR REPLACE VIEW "V_PICKORDEREMBLEM" ("WORKORDERLINEEMBLEM_ID", "EMBLEMTEMPLATELINE_ID", "WORKORDERLINE_ID", "WORKORDER_ID", "EMBLEMTEMPLATE_ID", "EMBLEMTEMPLATEDESCRIPTION", "QUANTITY", "EMBLEMTEMPLATELINEDESC", "LANGUAGECODE", "PRODUCTCODE", "PRODUCTDESCRIPTION", "PLACEMENTCODE", "PLACEMENTDESCRIPTION") AS 
  select wole.workorderlineemblem_id,
       wole.emblemtemplateline_id,
       wol.workorderline_id,
       wol.workorder_id,
       et.emblemtemplate_id,
       et.description emblemtemplatedescription,
       wole.qtyrequested quantity,
       etl.description emblemtemplatelinedesc,
       l.code languagecode,
       emblemtemplateproduct.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = emblemtemplateproduct.product_id
           and l.language_id = pd.language_id) productdescription,
       pc.code placementcode,
       (select pcd.description
          from placement_desc pcd
         where pcd.placement_id = pc.placement_id
           and pcd.language_id = l.language_id) placementdescription
  from workorderlineemblem wole
       left outer join placement pc on wole.placement_id = pc.placement_id
  , workorderline wol
  , workorder wo
  , languages l
  , emblemtemplateline etl
  , product emblemtemplateproduct
  , emblemtemplate et
 where wole.emblemtemplateline_id = etl.emblemtemplateline_id
   and et.emblemtemplate_id = etl.emblemtemplate_id
   and wole.workorderline_id = wol.workorderline_id
   and wol.workorder_id = wo.workorder_id
   and wole.product_id is null
   and etl.product_id = emblemtemplateproduct.product_id
   and wole.emblemtemplateline_id is not null
union
select wole.workorderlineemblem_id,
       wole.emblemtemplateline_id,
       wol.workorderline_id,
       wol.workorder_id,
       null emblemtemplate_id,
       null emblemtemplatedescription,
       wole.qtyrequested quantity,
       '' emblemtemplatelinedescription,
       l.code languagecode,
       p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = p.product_id
           and l.language_id = pd.language_id) productdescription,
       pc.code placementcode,
       (select pcd.description
          from placement_desc pcd
         where pcd.placement_id = pc.placement_id
           and pcd.language_id = l.language_id) placementdescription
  from workorderlineemblem wole
       left outer join placement pc on wole.placement_id = pc.placement_id
  , workorderline wol
  , workorder wo
  , languages l
  , product p
 where wole.workorderline_id = wol.workorderline_id
   and wole.product_id = p.product_id
   and wol.workorder_id = wo.workorder_id
   and wole.product_id is not null
   and wole.emblemtemplateline_id is null
union
select wole.workorderlineemblem_id,
       wole.emblemtemplateline_id,
       wol.workorderline_id,
       wol.workorder_id,
       et.emblemtemplate_id,
       et.description emblemtemplatedescription,
       wole.qtyrequested quantity,
       etl.description emblemtemplatelinedesc,
       l.code languagecode,
       '' productcode,
       '' productdescription,
       pc.code placementcode,
       (select pcd.description
          from placement_desc pcd
         where pcd.placement_id = pc.placement_id
           and pcd.language_id = l.language_id) placementdescription
  from workorderlineemblem wole
       left outer join placement pc on wole.placement_id = pc.placement_id
  , workorderline wol
  , workorder wo
  , languages l
  , emblemtemplateline etl
  , emblemtemplate et
 where wole.emblemtemplateline_id = etl.emblemtemplateline_id
   and et.emblemtemplate_id = etl.emblemtemplate_id
   and wole.workorderline_id = wol.workorderline_id
   and wol.workorder_id = wo.workorder_id
   and wole.product_id is null
   and etl.product_id is null
   and wole.emblemtemplateline_id is not null
/

  CREATE OR REPLACE VIEW "V_PICKUPCONTAINERS" ("STOP_ID", "TIMECH24", "CONTAINERID", "CODE", "CTYPEDESC") AS 
  SELECT st.stop_id,
(to_char(rt.timestamp,'DD.MM.YYYY')|| '-' ||to_char(rt.timestamp,'fmhh24fm:MI'))TIMECH24,
nvl(cnt.primaryid, rt.stringvalue1) CONTAINERID, NVL(ct.code, 'Standard Container') code,
(select ct_desc.description from containertype_desc ct_desc where ct_desc.containertype_id=ct.containertype_id
and ct_desc.language_id=c.language_id) ctypedesc
from  stop st,routetransaction rt,  container cnt, containertype ct, customer c
where st.routecontrol_id=rt.routecontrol_id
and st.stop_id=rt.stop_id
and st.customer_link_id=c.customer_id
and rt.routetransactiontype_id=213--pickup containers
and rt.stringvalue1=cnt.primaryid (+)
and cnt.containertype_id=ct.containertype_id (+)
/

  CREATE OR REPLACE VIEW "V_PIECESPERBENCHMARKCATEGORY" ("BENCHMARKCODE", "BENCHMARKDESC", "BILLNUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEFAULTBUSINESSUNIT_ID", "MARKETSEGMENTCODE", "PRODUCTCODE", "SIZECODE", "FINISHINGCODE", "PRODUCTDESC", "COSTCENTERCODE", "COSTCENTERDESC", "PIECES", "REPORTPARAM_ID", "LANGUAGECODE") AS 
  select distinct -- selection on WEEK based on costreportinfo CCIF
  bkc.code benchmarkCode, bkc.description benchmarkDesc
, bill.customernumber billNumber, cu.customernumber, cu.name customerName
, cu.defaultbusinessunit_id, marketsegment.code marketsegmentCode
, prd.code productCode, sz.code sizeCode, fm.code finishingCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, cc.code costcenterCode, cc.description costcenterDesc
, sum(ccif.quantity) Pieces
, RP.REPORTPARAM_ID, languages.code languageCode
from
  customer cu, customer bill, marketsegment
, costcenter cc
, costreportinfo ccif, invoiceline il, invoicelineproduct ilp, invoicelinetype ilty, invoiceheader ih
, benchmarkcategory bkc
, product prd, sizedefinition sz, finishingmethod fm
, reportparam rp, languages
where
    cu.debtor_id = bill.customer_id
and cu.marketsegment_id = marketsegment.marketsegment_id
and cu.customer_id = cc.customer_id --
    and cc.benchmarkcategory_id = bkc.benchmarkcategory_id --
    and cc.costcenter_id = ccif.costcenter_link_id --
        and ccif.invoiceline_id = ilp.invoiceline_id --
            and ilp.product_link_id = prd.product_id
                and prd.benchmarkrelevant = 'Y'
            and ilp.sizedefinition_link_id = sz.sizedefinition_id
            and ilp.finishingmethod_id = fm.finishingmethod_id
        and ccif.invoiceline_id = il.invoiceline_id
            and il.invoicelinetype_id = ilty.invoicelinetype_id
                and ilty.type in (2, 5) -- 2: wash, 5: sales
            and il.invoiceheader_id = ih.invoiceheader_id
            and ih.status_id = (select status_id from status where statustype='IN' and code='2')
and ih.deltocustomer_link_id = cu.customer_id
and ccif.year = rp.number_value1
and
    ( rp.number_value4 = 0 and rp.number_value5 = 0
          and ccif.week between rp.number_value2 and rp.number_value3 )
group by
  bkc.code , bkc.description
, bill.customernumber , cu.customernumber, cu.name
, cu.defaultbusinessunit_id, marketsegment.code
, prd.code , sz.code , fm.code
, prd.product_id, languages.language_id
, cc.code , cc.description
, RP.REPORTPARAM_ID, languages.code
union
select distinct -- selection on MONTH based on costcenterinvoiceline CCIL
  bkc.code benchmarkCode, bkc.description benchmarkDesc
, bill.customernumber billNumber, cu.customernumber, cu.name customerName
, cu.defaultbusinessunit_id, marketsegment.code marketsegmentCode
, prd.code productCode, sz.code sizeCode, fm.code finishingCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, cc.code costcenterCode, cc.description costcenterDesc
, sum(ccil.quantity) Pieces
, RP.REPORTPARAM_ID, languages.code languageCode
from
  customer cu, customer bill, marketsegment
, costcenter cc
, costcenterinvoiceline ccil, invoiceline il, invoicelineproduct ilp, invoicelinetype ilty, invoiceheader ih
, benchmarkcategory bkc
, product prd, sizedefinition sz, finishingmethod fm
, reportparam rp, languages
where
    cu.debtor_id = bill.customer_id
and cu.marketsegment_id = marketsegment.marketsegment_id
and cu.customer_id = cc.customer_id
    and cc.benchmarkcategory_id = bkc.benchmarkcategory_id
    and cc.costcenter_id = ccil.costcenter_link_id
        and ccil.invoiceline_id = ilp.invoiceline_id
            and ilp.product_link_id = prd.product_id
                and prd.benchmarkrelevant = 'Y'
            and ilp.sizedefinition_link_id = sz.sizedefinition_id
            and ilp.finishingmethod_id = fm.finishingmethod_id
        and ccil.invoiceline_id = il.invoiceline_id
            and il.invoicelinetype_id = ilty.invoicelinetype_id
                and ilty.type in (2, 5) -- 2: wash, 5: sales
            and il.invoiceheader_id = ih.invoiceheader_id
            and ih.status_id = (select status_id from status where statustype='IN' and code='2')
and ih.deltocustomer_link_id = cu.customer_id
and ih.endyear = rp.number_value1
and
    ( rp.number_value2 = 0 and rp.number_value3 = 0
          and ih.endmonth between rp.number_value4 and rp.number_value5 )
group by
  bkc.code , bkc.description
, bill.customernumber , cu.customernumber, cu.name
, cu.defaultbusinessunit_id, marketsegment.code
, prd.code , sz.code , fm.code
, prd.product_id, languages.language_id
, cc.code , cc.description
, RP.REPORTPARAM_ID, languages.code
/

  CREATE OR REPLACE VIEW "V_PLANT" ("CODE", "NAME", "STREET", "ZIPCODE", "CITY", "COUNTY", "STATE", "COUNTRYCODE", "COUNTRYNAME", "ACTIVE", "HEADOFFICECODE", "HEADOFFICENAME", "PHONENO", "FAXNO", "EMAIL", "SYSTEMUSER_ID", "TIMESTAMP", "PLANT_ID", "WEIGHTUNIT") AS 
  select /*version 2.0 */
       plt.code, plt.name, ads.street, ads.zipcode, ads.city, ads.county,
       ads.state, co.code countrycode, co.description countryname, plt.active,
       headoffice.code headofficecode, headoffice.name headofficename, plt.phoneno, plt.faxno,
       plt.email, plt.systemuser_id, plt.timestamp, plt.plant_id, z.value weightunit
  from plant plt
       join address ads on plt.address_id = ads.address_id
       join country co on plt.country_id = co.country_id
       join plant headoffice
            left join systemsetting z on headoffice.plant_id = z.plant_id and z.name = 'WEIGHTUNIT'
       on plt.headoffice_id = headoffice.plant_id
/

  CREATE OR REPLACE VIEW "V_PLANTDELIVERYHISTORY" ("PLANTCODE", "PLANTNAME", "BUSINESSUNIT_ID", "PROCESSBUCODE", "PROCESSBUDESC", "MARKETSEGMENTCODE", "MARKETSEGMENTDESC", "PRODUCTGROUPCODE", "PRODUCTGROUPDESC", "PRODUCTCODE", "PRODUCTDESC", "PARENTPRODUCTCODE", "PARENTPRODUCTDESC", "PACKINDICATION", "PACKCODE", "PACKDESC", "ACTIVITYCODE", "THEORETICALWEIGHT", "TYPEOFMERCHANDISE", "MODEL", "PRODSIZE_THEORETICALWEIGHT", "SIZECODE", "SIZEDESC", "FINISHINGMETHODCODE", "FINISHINGMETHODDESC", "DELIVERYDATE", "YEARWEEK", "WEEK", "YEAR", "DAYNUMBER", "REALMONTH", "REALYEAR", "AMOUNTORDERED", "AMOUNTDELIVERED", "AMOUNTSHORTAGE", "PRICE", "INTERNALPRICE", "DISCOUNT", "PARENTPACKPRODUCT_LINK_ID", "PARENTPRODUCT_LINK_ID", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE", "WIDTH_S", "LENGTH_S") AS 
  select
  plant.code plantCode, plant.name plantName, processBU.Businessunit_Id
, processBU.Code processbuCode, processBU.description processbuDesc, marketsegment.code marketsegmentCode
, ( select marketsegment_desc.description from marketsegment_desc where marketsegment_desc.marketsegment_id = marketsegment.marketsegment_id
  and marketsegment_desc.language_id = languages.language_id ) marketsegmentDesc
, ProductGroup.Code ProductGroupCode
, ( select ProductGroup_Desc.description from ProductGroup_Desc where ProductGroup_Desc.ProductGroup_id = ProductGroup.ProductGroup_id
  and ProductGroup_Desc.language_id = languages.language_id ) ProductGroupDesc
, product_link.code productcode
, ( select product_link_desc.description from product_link_desc where product_link_desc.product_link_id = deliveryHistory.Product_Link_Id
  and product_link_desc.language_id = languages.language_id ) productDesc
, parentproduct.CODE parentproductcode
, ( select product_link_desc.description from product_link_desc where product_link_desc.product_link_id = deliveryHistory.Parentpackproduct_Link_Id
  and product_link_desc.language_id = languages.language_id ) parentproductDesc
, deliveryHistory.Packindication, pack.code packcode
, ( select product_link_desc.description from product_link_desc where product_link_desc.product_link_id = deliveryHistory.Parentpackproduct_Link_Id
  and product_link_desc.language_id = languages.language_id ) packDesc
, ( select activity.code from activity where activity.activity_id = ProductGroup.Activity_Id) ActivityCode
, product.theoreticalweight , product.typeofmerchandise, product.model, productsize.theoreticalweight prodsize_theoreticalweight
, sizedefinition_link.code sizeCode
, ( select sizedefinition_link_desc.description from sizedefinition_link_desc where sizedefinition_link_desc.sizedefinition_link_id = deliveryHistory.sizedefinition_link_id
  and sizedefinition_link_desc.language_id = languages.language_id ) sizeDesc
, finishingmethod.code finishingmethodcode
, ( select finishingmethod_desc.description from finishingmethod_desc where finishingmethod_desc.finishingmethod_id = deliveryHistory.finishingmethod_id
  and finishingmethod_desc.language_id = languages.language_id ) finishingmethodDesc
, deliveryHistory.Deliverydate
, ( deliveryHistory.year*100 + deliveryHistory.week ) YearWeek, deliveryHistory.Week, deliveryHistory.Year, deliveryHistory.Daynumber
, month(deliveryHistory.deliverydate) realmonth
, year(deliveryHistory.deliverydate) realyear
, deliveryHistory.Amountordered, deliveryHistory.Amountdelivered, deliveryHistory.Amountshortage
, deliveryHistory.Price, deliveryHistory.Internalprice, deliveryHistory.DISCOUNT
, deliveryHistory.Parentpackproduct_Link_Id, deliveryHistory.Parentproduct_Link_Id, deliveryHistory.Systemuser_Id, deliveryHistory.Timestamp
, languages.code languageCode,
SIZEDEFINITION.WIDTH WIDTH_S,SIZEDEFINITION.LENGTH LENGTH_S--CSW
from
  deliveryHistory
      left outer join  product on deliveryHistory.Product_Link_Id = product.product_id
      left outer join sizedefinition on deliveryHistory.Sizedefinition_Link_Id = sizedefinition.sizedefinition_id
, businessunit processBu, plant, distributionpoint_link, department_link, customer, marketsegment
, productsize
, sizedefinition_link, finishingmethod
, product_link parentproduct, product_link pack
, product_link
      left outer join ProductGroup on product_link.ProductGroupCode = ProductGroup.Code
, languages
where
    deliveryHistory.Processbusinessunit_Id = processBu.Businessunit_Id
    and processBu.Plant_Id = plant.plant_id
and deliveryHistory.Product_Link_Id = product_link.product_link_id
and deliveryHistory.Parentproduct_Link_Id = parentproduct.product_link_id
and deliveryHistory.Parentpackproduct_Link_Id = pack.product_link_id
and deliveryHistory.Sizedefinition_Link_Id = sizedefinition_link.sizedefinition_link_id
and deliveryHistory.Finishingmethod_Id = finishingmethod.finishingmethod_id
and product.product_id = productsize.product_id
    and productsize.sizedefinition_id = sizedefinition.sizedefinition_id
and deliveryHistory.Distributionpoint_Link_Id = distributionpoint_link.distributionpoint_link_id
    and distributionpoint_link.department_link_id = department_link.department_link_id
        and department_link.customer_link_id = customer.customer_id
            and customer.marketsegment_id = marketsegment.marketsegment_id
/

  CREATE OR REPLACE VIEW "V_PLANTDEPARTMENT" ("PLANTCODE", "PLANTNAME", "CODE", "DESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  SELECT PLANT.CODE, PLANT.NAME, PLANTDEPARTMENT.CODE, PLANTDEPARTMENT.DESCRIPTION,
PLANTDEPARTMENT.SYSTEMUSER_ID, PLANTDEPARTMENT.TIMESTAMP
       FROM PLANTDEPARTMENT, PLANT
       WHERE PLANTDEPARTMENT.PLANT_ID = PLANT.PLANT_ID
/

  CREATE OR REPLACE VIEW "V_PLANTMERCHANDISEREQUIREMENT" ("LINETYPE", "PACKPRODUCT", "DEPOT", "ROUTENUMBER", "ACTIVITYCODE", "ACTIVITYDESCRIPTION", "PRODUCTCODE", "DELIVERYDATE", "DAYDESCRIPTION", "PLANTDEPARTMENTCODE", "PLANTDEPARTMENTDESCRIPTION", "PRODUCTDESCRIPTION", "SIZECODE", "FINISHINGMETHODCODE", "SIZEDESC", "FINISHINGMETHODDESC", "TOTALQTY", "BUNDLESIZE", "THEORETICALWEIGHT", "PACKINGSEQUENCE", "PRODUCTGROUPCODE", "PRODUCTGROUPDESCRIPTION", "ROUTE_ID", "PLANT_ID", "PACKINGDEADLINE", "LANGUAGECODE", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_ID", "DEFAULTBUSINESSUNIT_ID", "NOTENUMBER", "INTERNALBU_ID", "INTERNALBU_CODE", "INTERNALBU_DESC", "PROCESSBUSINESSUNIT_ID", "PROCESSBU_CODE", "PROCESSBU_DESC", "PRODUCTIONDATE", "DN_TOBEDELIVEREDAMOUNT", "DELIVEREDAMOUNT", "ORDEREDAMOUNT", "DN_BALANCE") AS 
  select /*version 2.0*/
       1 linetype, 'Y' packproduct, dep.code depot, ro.routenumber, upper(act.code) activitycode,
       (select actd.description
          from activity_desc actd
         where actd.activity_id = act.activity_id
           and actd.language_id = lan.language_id) activitydescription,
       prd.code productcode, pk.deliverydate,
       (select dd.description
          from day_desc dd
               join day on dd.day_id = day.day_id
         where pk.daynumber = day.daynumber
           and dd.language_id = lan.language_id) daydescription,
       pd.code plantdepartmentcode, pd.description plantdepartmentdescription,
       (select prde.description
          from product_desc prde
         where prde.product_id = prd.product_id
           and prde.language_id = lan.language_id) productdescription,
       sd.code sizecode, fm.code finishingmethodcode,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc,
       (select fmd.description
          from finishingmethod_desc fmd
         where fmd.finishingmethod_id = fm.finishingmethod_id
           and fmd.language_id = lan.language_id) finishingmethoddesc,
       case when pk.origin = 7 then pkli.deliveredamount
         else pkli.tobedeliveredamount
       end totalqty,
       coalesce((select ppss.packingamount
                   from plantproductsizesettings ppss
                  where ppss.product_id = pkli.product_id
                    and ppss.sizedefinition_id = pkli.sizedefinition_id
                    and ppss.plant_id = pd.plant_id), psz.packingamount) bundlesize,
       psz.theoreticalweight, prd.packingsequence, pg.code productgroupcode,
       (select pgd.description
          from productgroup_desc pgd
         where pgd.productgroup_id = pg.productgroup_id
           and pgd.language_id = lan.language_id) productgroupdescription,
       ro.route_id, ro.plant_id, ro.packingdeadline, lan.code languagecode,
       cu.customernumber customernumber, cu.name customername, cu.customer_id,
       cu.defaultbusinessunit_id, pk.notenumber, pk.internalprocessingbu_id internalbu_id,
       ibu.code internalbu_code, ibu.description internalbu_desc, pk.processbusinessunit_id,
       pbu.code processbu_code, pbu.description processbu_desc, pk.productiondate,
       pkli.tobedeliveredamount dn_tobedeliveredamount, pkli.deliveredamount,
       (pkli.standardamount + pkli.variationamount) orderedamount,
       case when pkli.origin <> 1
            then (pkli.standardamount + pkli.variationamount - pkli.deliveredamount)
         when pkli.origin = 1 and prd.packtype >= 2 and (pkli.standardamount + pkli.variationamount <> 0)
         then (pkli.standardamount + pkli.variationamount - pkli.deliveredamount)
       else 0 end dn_balance
  from packingnoteline pkli
       join packingnote pk
            left join route ro
                 left join depot dep on ro.depot_id = dep.depot_id
            on pk.route_id = ro.route_id and ro.active = 'Y'
            left join businessunit ibu on pk.internalprocessingbu_id = ibu.businessunit_id
            join plantdepartment pd on pk.plantdepartment_id = pd.plantdepartment_id
            join businessunit pbu on pk.processbusinessunit_id = pbu.businessunit_id
            join status st on pk.status_id = st.status_id and st.statustype = 'PN'
            join distributionpoint dp
                 join department de
                      join customer cu on de.customer_id = cu.customer_id
                 on dp.department_id = de.department_id
            on pk.distributionpoint_id = dp.distributionpoint_id
       on pkli.packingnote_id = pk.packingnote_id
       join productsize psz on pkli.product_id = psz.product_id and pkli.sizedefinition_id = psz.sizedefinition_id
       join product prd
            join productgroup pg
                 join activity act on pg.activity_id = act.activity_id
            on prd.productgroup_id = pg.productgroup_id
       on pkli.product_id = prd.product_id
       join sizedefinition sd on pkli.sizedefinition_id = sd.sizedefinition_id
       join finishingmethod fm on pkli.finishingmethod_id = fm.finishingmethod_id
       cross join languages lan
 where st.code in ('10', '20')
 union all -- 2 : content
select 2 linetype, 'N' packproduct, dep.code depot, ro.routenumber, upper(act.code) activitycode,
       (select actd.description
          from activity_desc actd
         where actd.activity_id = act.activity_id
           and actd.language_id = lan.language_id) activitydescription,
       prd.code productcode, pk.deliverydate,
       (select dd.description
          from day_desc dd, day
         where pk.daynumber = day.daynumber
           and dd.day_id = day.day_id
           and dd.language_id = lan.language_id) daydescription,
       pd.code plantdepartmentcode, pd.description plantdepartmentdescription,
       (select prde.description
          from product_desc prde
         where prde.product_id = prd.product_id
           and prde.language_id = lan.language_id) productdescription,
       sd.code sizecode, fm.code finishingmethodcode,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc,
       (select fmd.description
          from finishingmethod_desc fmd
         where fmd.finishingmethod_id = fm.finishingmethod_id
           and fmd.language_id = lan.language_id) finishingmethoddesc,
       case when pk.origin = 7 then pkli.deliveredamount * pkc.quantity
          else pkli.tobedeliveredamount * pkc.quantity
       end totalqty,
       coalesce((select ppss.packingamount
                   from plantproductsizesettings ppss
                  where ppss.product_id = pkc.product_id
                    and ppss.sizedefinition_id = pkc.sizedefinition_id
                    and ppss.plant_id = pd.plant_id), psz.packingamount) bundlesize,
       psz.theoreticalweight, prd.packingsequence, pg.code productgroupcode,
       (select pgd.description
          from productgroup_desc pgd
         where pgd.productgroup_id = pg.productgroup_id
           and pgd.language_id = lan.language_id) productgroupdescription,
       ro.route_id, ro.plant_id, ro.packingdeadline, lan.code languagecode,
       cu.customernumber customernumber, cu.name customername, cu.customer_id,
       cu.defaultbusinessunit_id, pk.notenumber, pk.internalprocessingbu_id internalbu_id,
       ibu.code internalbu_code, ibu.description internalbu_desc, pk.processbusinessunit_id,
       pbu.code processbu_code, pbu.description processbu_desc, pk.productiondate,
       pkli.tobedeliveredamount dn_tobedeliveredamount, pkli.deliveredamount,
       (pkli.standardamount + pkli.variationamount) orderedamount,
       case when pkli.origin <> 1
            then (pkli.standardamount + pkli.variationamount - pkli.deliveredamount)
         when pkli.origin = 1 and prd.packtype >= 2 and (pkli.standardamount + pkli.variationamount <> 0)
         then (pkli.standardamount + pkli.variationamount - pkli.deliveredamount)
       else 0 end dn_balance
  from packingnotelinecontent pkc
       join packingnoteline pkli
            join packingnote pk
                 left join route ro
                      left join depot dep on ro.depot_id = dep.depot_id
                 on pk.route_id = ro.route_id and ro.active = 'Y'
                 left join businessunit ibu on pk.internalprocessingbu_id = ibu.businessunit_id
                 join plantdepartment pd on pk.plantdepartment_id = pd.plantdepartment_id
                 join businessunit pbu on pk.processbusinessunit_id = pbu.businessunit_id
                 join status st on pk.status_id = st.status_id and st.statustype = 'PN'
                 join distributionpoint dp
                      join department de
                           join customer cu on de.customer_id = cu.customer_id
                      on dp.department_id = de.department_id
                 on pk.distributionpoint_id = dp.distributionpoint_id
            on pkli.packingnote_id = pk.packingnote_id
       on pkc.packingnoteline_id = pkli.packingnoteline_id
       join productsize psz on pkc.product_id = psz.product_id and pkc.sizedefinition_id = psz.sizedefinition_id
       join product prd
            join productgroup pg
                 join activity act on pg.activity_id = act.activity_id
            on prd.productgroup_id = pg.productgroup_id
       on pkc.product_id = prd.product_id
       join sizedefinition sd on pkc.sizedefinition_id = sd.sizedefinition_id
       join finishingmethod fm on pkc.finishingmethod_id = fm.finishingmethod_id
       cross join languages lan
 where st.code in ('10', '20')
/

  CREATE OR REPLACE VIEW "V_PLANTTAXAREAID" ("PLANT_CODE", "PLANT_NAME", "CUST_USERNAME", "CUST_FULLNAME", "CUST_ACTIVE", "PTAXAREAID", "PTIMESTAMP", "PCONFIDENCEINDICATOR", "PUSERNAME", "PFULLNAME", "PACTIVE", "PMSETUSERNAME", "PMSETFULLNAME", "PMSETACTIVE", "PSTREET", "PSTREET2", "PCITY", "PCOUNTY", "PSTATE", "PZIPCODE", "PATIMESTAMP", "COUNTRY_CODE", "COUNTRY_DESC") AS 
  select pl.code plant_code, pl.name plant_name,
       null cust_username, null cust_fullname, sysdate cust_active,
       pata.taxareaid ptaxareaid, trunc(pata.timestamp) ptimestamp, pata.confidenceindicator pconfidenceindicator,
       psu.username pusername, psu.fullname pfullname, psu.active pactive,
       pmsu.username pmsetusername, pmsu.fullname pmsetfullname, pmsu.active pmsetactive,
       pad.street pstreet, pad.street2 pstreet2, pad.city pcity,
       pad.county pcounty, pad.state pstate, pad.zipcode pzipcode,
       trunc(pad.timestamp) patimestamp,
       co.code country_code, co.description country_desc
from plant pl
     join country co on pl.country_id = co.country_id
     join address pad on pl.address_id = pad.address_id
     join AddressTaxAreaID pata on pad.address_id = pata.address_id
     join systemuser psu on pata.systemuser_id = psu.systemuser_id
     left outer join systemuser pmsu on pata.manuallysetsystemuser_id = pmsu.systemuser_id
/

  CREATE OR REPLACE VIEW "V_PLANTTURNOVERGROUP" ("PLANTCODE", "PLANTNAME", "TURNOVERGROUPCODE", "TURNOVERGROUPDESCRIPTION", "ACTIVE", "SALESJOURNALGROUPCODE", "SALESJOURNALGROUPDESCRIPTION", "COMMISSIONPERCENTAGE", "TIMESTAMP", "SYSTEMUSER_ID", "LANGUAGECODE") AS 
  select a.code plantcode, a.name plantname,
 b.code turnovergroupcode,
 (SELECT description FROM turnovergroup_DESC e WHERE e.turnovergroup_id = c.turnovergroup_id
  AND e.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) turnovergroupdescription,
 b.active,
 d.code salesjournalgroupcode,
 (SELECT description FROM salesjournalgroup_DESC f WHERE f.salesjournalgroup_id = b.salesjournalgroup_id
  AND f.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) salesjournalgroupdescription,
 c.commissionpercentage, c.timestamp, c.systemuser_id, languages.code languagecode
from plant a, turnovergroup b, plantturnovergroup c, salesjournalgroup d, languages
where c.plant_id = a.plant_id
 and c.turnovergroup_id = b.turnovergroup_id
 and b.salesjournalgroup_id = d.salesjournalgroup_id
/

  CREATE OR REPLACE VIEW "V_PLANTWEIGHINGHISTORY" ("PLANTCODE", "PLANTNAME", "BUSINESSUNIT_ID", "PROCESSBUCODE", "PROCESSBUDESC", "MARKETSEGMENTCODE", "MARKETSEGMENTDESC", "WEIGHINGCATCODE", "WEIGHINGCATEGORYDESCRIPTION", "WEIGHINGDATE", "YEAR", "WEEK", "DAYNUMBER", "YEARWEEK", "REALMONTH", "REALYEAR", "SOILWEIGHT", "CLEANWEIGHT", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE", "WEIGHTDECIMALSMANUALINPUT", "WEIGHINGUSE", "WEIGHTUNIT") AS 
  select /*version 1.0*/
       pl.code plantcode, pl.name plantname, pbu.businessunit_id,
       pbu.code processbucode, pbu.description processbudesc,
       ms.code marketsegmentcode,
       (select msd.description
          from marketsegment_desc msd
         where msd.marketsegment_id = ms.marketsegment_id
           and msd.language_id = lan.language_id) marketsegmentdesc,
       wcl.code weighingcatcode,
       (select wcld.description
          from weighingcategory_link_desc wcld
         where wcld.weighingcategory_link_id = wh.weighingcategory_link_id
           and wcld.language_id = lan.language_id) weighingcategorydescription,
       wh.weighingdate, wh.year, wh.week,
       wh.daynumber, wh.year * 100 + wh.week yearweek,
       month(wh.weighingdate) realmonth, year(wh.weighingdate) realyear,
       wh.soilweight, wh.cleanweight, wh.systemuser_id,
       wh.timestamp, lan.code languagecode,
       (case
         when (select a.weighinguse
                 from weighingcategory a
                where a.weighingcategory_id = wcl.weighingcategory_id) = 1 then
          ((select rg.decimals
              from weighingcategory a, registrationunit rg
             where a.weighingcategory_id = wcl.weighingcategory_id
               and a.registrationunit_id = rg.registrationunit_id))
         else
          castvarcharasnumber(ss.value)
       end) weightdecimalsmanualinput,
       (select a.weighinguse
           from weighingcategory a
          where a.weighingcategory_id = wcl.weighingcategory_id) weighinguse,
       (case
         when (select a.weighinguse
                 from weighingcategory a
                where a.weighingcategory_id = wcl.weighingcategory_id) = 1 then
          ((select rg.code
              from weighingcategory a, registrationunit rg
             where a.weighingcategory_id = wcl.weighingcategory_id
               and a.registrationunit_id = rg.registrationunit_id))
         else
          ''
       end) weightunit
  from weighinghistory wh
       join weighingcategory_link wcl on wh.weighingcategory_link_id = wcl.weighingcategory_link_id
       join businessunit pbu
            join plant pl on pbu.plant_id = pl.plant_id
            join systemsetting ss on pbu.plant_id = ss.plant_id and ss.name = 'WEIGHTDECIMALSMANUALINPUT'
       on wh.processbusinessunit_id = pbu.businessunit_id
       join customer cu
            join marketsegment ms on cu.marketsegment_id = ms.marketsegment_id
       on wh.customer_link_id = cu.customer_id
       cross join languages lan
/

  CREATE OR REPLACE VIEW "V_PLPC" ("CUSTOMERNUMBER", "NAME", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "SIZEDEFINITION_DESC", "FINISHINGMETHODCODE", "FINISHINGMETHOD_DESC", "DATEACTIVE", "DATEINACTIVE", "CODEUNIQUELY", "SOILWEIGHT", "ONSITEINVENTORYCOUNT", "PERCENTAGEAFTERDEPRECIATION", "CLEANCOUNT", "BILLINGMETHOD", "SOILCOUNTMETHOD", "SRCMETHOD", "SRCPERCENTAGESOILCOUNT", "SRCPERCENTAGEINVENTORY", "SRCQUANTITY", "SRCFREQUENCY", "MINIMUMTURNAROUND", "MINIMUMQUANTITY", "QTYFREEOFCHARGE", "CHARGESTOCKROOMINVENTORY", "CUSTOMCODE", "CUSTOMDESCRIPTION", "CUSTOMBUNDLESIZE", "GAINREASONCODE", "GAINREASON_DESC", "GAINCOMPETITORCODE", "GAINCOMPETITORNAME", "LOSTREASONCODE", "LOSTREASON_DESC", "LOSTCOMPETITORCODE", "LOSTCOMPETITORNAME", "RESIDUALVALUESCHEMECODE", "RESIDUALVALUESCHEME_DESC", "DELAYEDEVENEXCHANGE", "REALQUANTITY", "CHARGEOVERUSE", "CHANGESPERWEEK", "DELIVERREPLACEMENTQTY", "MINIMUMFREQUENCY", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, PRODUCT.CODE productcode,
(SELECT description FROM PRODUCT_DESC A WHERE A.PRODUCT_ID = PRODUCTLISTPERCUSTOMER.PRODUCT_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
SIZEDEFINITION.CODE sizedefinitioncode,
(SELECT description FROM SIZEDEFINITION_DESC B WHERE B.SIZEDEFINITION_ID = PRODUCTLISTPERCUSTOMER.SIZEDEFINITION_ID
  AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEDEFINITION_DESC,
FINISHINGMETHOD.CODE finishingmethodcode,
(SELECT description FROM FINISHINGMETHOD_DESC C WHERE C.FINISHINGMETHOD_ID = PRODUCTLISTPERCUSTOMER.FINISHINGMETHOD_ID
  AND C.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHOD_DESC,
PRODUCTLISTPERCUSTOMER.DATEACTIVE, PRODUCTLISTPERCUSTOMER.DATEINACTIVE, PRODUCTLISTPERCUSTOMER.CODEUNIQUELY,
PRODUCTLISTPERCUSTOMER.SOILWEIGHT, PRODUCTLISTPERCUSTOMER.ONSITEINVENTORYCOUNT,
PRODUCTLISTPERCUSTOMER.PERCENTAGEAFTERDEPRECIATION, PRODUCTLISTPERCUSTOMER.CLEANCOUNT,
PRODUCTLISTPERCUSTOMER.BILLINGMETHOD,
PRODUCTLISTPERCUSTOMER.SOILCOUNTMETHOD, PRODUCTLISTPERCUSTOMER.SRCMETHOD,
PRODUCTLISTPERCUSTOMER.SRCPERCENTAGESOILCOUNT,
PRODUCTLISTPERCUSTOMER.SRCPERCENTAGEINVENTORY, PRODUCTLISTPERCUSTOMER.SRCQUANTITY,
PRODUCTLISTPERCUSTOMER.SRCFREQUENCY,
PRODUCTLISTPERCUSTOMER.MINIMUMTURNAROUND, PRODUCTLISTPERCUSTOMER.MINIMUMQUANTITY,
PRODUCTLISTPERCUSTOMER.QTYFREEOFCHARGE, PRODUCTLISTPERCUSTOMER.CHARGESTOCKROOMINVENTORY,
PRODUCTLISTPERCUSTOMER.CUSTOMCODE, PRODUCTLISTPERCUSTOMER.CUSTOMDESCRIPTION,
PRODUCTLISTPERCUSTOMER.CUSTOMBUNDLESIZE,
GAINREASON.CODE gainreasoncode,
(SELECT description FROM GAINLOSTREASON_DESC D WHERE D.GAINLOSTREASON_ID = PRODUCTLISTPERCUSTOMER.GAINREASON_ID
  AND D.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) GAINREASON_DESC,
GAINCOMPETITOR.CODE gaincompetitorcode, GAINCOMPETITOR.NAME gaincompetitorname,
LOSTREASON.CODE lostreasoncode,
(SELECT description FROM GAINLOSTREASON_DESC E WHERE E.GAINLOSTREASON_ID = PRODUCTLISTPERCUSTOMER.LOSTREASON_ID
  AND E.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) LOSTREASON_DESC,
LOSTCOMPETITOR.CODE lostcompetitorcode, LOSTCOMPETITOR.NAME lostcompetitorname,
RESIDUALVALUESCHEME.CODE residualvalueschemecode,
(SELECT description FROM RESIDUALVALUESCHEME_DESC F WHERE F.RESIDUALVALUESCHEME_ID = PRODUCTLISTPERCUSTOMER.RESIDUALVALUESCHEME_ID
  AND F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) RESIDUALVALUESCHEME_DESC,
PRODUCTLISTPERCUSTOMER.DELAYEDEVENEXCHANGE,
--PRODUCTLISTPERCUSTOMER.REALQUANTITY,
 case when PRODUCTLISTPERCUSTOMER.Inventorybillingtype = 1 then 'Y' else 'N' end REALQUANTITY , -- ! --
--PRODUCTLISTPERCUSTOMER.DELIVERMINIMUM,
 PRODUCTLISTPERCUSTOMER.CHARGEOVERUSE,
PRODUCTLISTPERCUSTOMER.CHANGESPERWEEK,
--PRODUCTLISTPERCUSTOMER.FIXEDQUANTITY,
PRODUCTLISTPERCUSTOMER.DELIVERREPLACEMENTQTY,
PRODUCTLISTPERCUSTOMER.MINIMUMFREQUENCY,
PRODUCTLISTPERCUSTOMER.SYSTEMUSER_ID, PRODUCTLISTPERCUSTOMER.TIMESTAMP, LANGUAGES.CODE languagecode
FROM PRODUCTLISTPERCUSTOMER
LEFT OUTER JOIN GAINLOSTREASON GAINREASON ON (PRODUCTLISTPERCUSTOMER.GAINREASON_ID = GAINREASON.GAINLOSTREASON_ID)
LEFT OUTER JOIN GAINLOSTREASON LOSTREASON ON(PRODUCTLISTPERCUSTOMER.LOSTREASON_ID = LOSTREASON.GAINLOSTREASON_ID)
LEFT OUTER JOIN COMPETITOR GAINCOMPETITOR ON(PRODUCTLISTPERCUSTOMER.GAINCOMPETITOR_ID = GAINCOMPETITOR.COMPETITOR_ID)
LEFT OUTER JOIN COMPETITOR LOSTCOMPETITOR ON(PRODUCTLISTPERCUSTOMER.LOSTCOMPETITOR_ID = LOSTCOMPETITOR.COMPETITOR_ID),
CUSTOMER, PRODUCT, SIZEDEFINITION, FINISHINGMETHOD, RESIDUALVALUESCHEME, LANGUAGES
WHERE PRODUCTLISTPERCUSTOMER.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
and PRODUCTLISTPERCUSTOMER.PRODUCT_ID  = PRODUCT.PRODUCT_ID
and PRODUCTLISTPERCUSTOMER.SIZEDEFINITION_ID  = SIZEDEFINITION.SIZEDEFINITION_ID
and PRODUCTLISTPERCUSTOMER.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
and PRODUCTLISTPERCUSTOMER.RESIDUALVALUESCHEME_ID = RESIDUALVALUESCHEME.RESIDUALVALUESCHEME_ID
/

  CREATE OR REPLACE VIEW "V_PLPCLOCATION" ("PRODUCTLISTPERCUSTOMER_ID", "LOCATION", "UNIQUELOCATION", "PROCESSBUSINESSUNIT_ID", "DATEACTIVE", "DATEINACTIVE") AS 
  select plpc.Productlistpercustomer_Id, plpc.Location,
       plpc.UniqueLocation,
       ca.Processbusinessunit_Id
       , plpc.dateactive, plpc.dateinactive
-- this view is used in PDProductListPerCustomer.java
from ProductListPerCustomer plpc, CustomerActivities ca,
     product p, productgroup pg
where plpc.customer_id = ca.customer_id
      and plpc.product_id = p.product_id
      and p.productgroup_id = pg.productgroup_id
      and pg.activity_id = ca.activity_id
      and plpc.location is not null
/

  CREATE OR REPLACE VIEW "V_PLPC_DELIVERYHISTORY" ("PRODUCT_CODE", "PRODUCT_ID", "SIZEDEFINITION_CODE", "FINISHINGMETHOD_CODE", "PERMANENT_CIRC", "CHARGEABLE_CIRC", "LOAN_QTY", "MIN_TURN_AROUND_PERC", "MIN_QTY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY", "TOTAL_LAST_4_WEEKS", "WEEKS_ACTIVE", "WEEKS_INACTIVE", "TOTAL_LAST_WEEK", "OUTSTANDING_ORDERS", "CUSTOMER_ID", "DATEACTIVE", "DATEINACTIVE") AS 
  (select p.code product_code,
p.product_id,
sd.code sizeDefinition_code,
fm.code finishingMethod_code,
nvl((select sum(rqa.quantity)
  from rentalqtyadjustment rqa, productlistperdistribpoint plpd, distributionpoint dp, department d
 where rqa.adjustmentDate <= trunc(sysdate)
   and rqa.origin <> 2 /*not Loan*/
   and rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
   and dp.distributionpoint_id = plpd.distributionpoint_id
   and d.department_id = dp.department_id
   and d.customer_id = plpc.customer_id
   and plpd.product_id = plpc.product_id
   and plpd.sizedefinition_id = plpc.sizedefinition_id
   and plpd.finishingmethod_id = plpc.finishingmethod_id
),0) permanent_circ,
nvl((select sum(rqa.quantity)
  from rentalqtyadjustment rqa, productlistperdistribpoint plpd, distributionpoint dp, department d--, reasoncode r
 where rqa.adjustmentDate <= trunc(sysdate)
   and rqa.origin <> 2 /*not Loan*/
   and rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
   and dp.distributionpoint_id = plpd.distributionpoint_id
   and d.department_id = dp.department_id
   and d.customer_id = plpc.customer_id
   and plpd.product_id = plpc.product_id
   and plpd.sizedefinition_id = plpc.sizedefinition_id
   and plpd.finishingmethod_id = plpc.finishingmethod_id
   --and r.reasoncode_id = rqa.reasoncode_id
   and rqa.sampleitem = 'N'
),0) chargeable_circ,
nvl((select sum(rqa.quantity)
  from rentalqtyadjustment rqa, productlistperdistribpoint plpd, distributionpoint dp, department d
 where rqa.adjustmentDate <= trunc(sysdate)
   and rqa.origin = 2 /*Loan*/
   and rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
   and dp.distributionpoint_id = plpd.distributionpoint_id
   and d.department_id = dp.department_id
   and d.customer_id = plpc.customer_id
   and plpd.product_id = plpc.product_id
   and plpd.sizedefinition_id = plpc.sizedefinition_id
   and plpd.finishingmethod_id = plpc.finishingmethod_id
),0) loan_qty,
plpc.minimumturnaround min_turn_around_perc,
plpc.minimumquantity min_qty,
(select sum(pnl.deliveredamount)
from packingnote pn, packingnoteline pnl, distributionpoint dp, department d, status s
where pn.packingnote_id = pnl.packingnote_id
and pn.distributionpoint_id = dp.distributionpoint_id
and dp.department_id = d.department_id
and d.customer_id = plpc.customer_id
and pnl.product_id = plpc.product_id
and pnl.sizedefinition_id = plpc.sizedefinition_id
and pnl.finishingmethod_id = plpc.finishingmethod_id
and pn.status_id = s.status_id
and pn.deliverydate = getFirstDayofWeek(trunc(sysdate))
and s.code = '30'
and s.statustype = 'PN'
) monday,
(select sum(pnl.deliveredamount)
from packingnote pn, packingnoteline pnl, distributionpoint dp, department d, status s
where pn.packingnote_id = pnl.packingnote_id
and pn.distributionpoint_id = dp.distributionpoint_id
and dp.department_id = d.department_id
and d.customer_id = plpc.customer_id
and pnl.product_id = plpc.product_id
and pnl.sizedefinition_id = plpc.sizedefinition_id
and pnl.finishingmethod_id = plpc.finishingmethod_id
and pn.status_id = s.status_id
and pn.deliverydate = getFirstDayofWeek(trunc(sysdate))+1
and s.code = '30'
and s.statustype = 'PN'
) tuesday,
(select sum(pnl.deliveredamount)
from packingnote pn, packingnoteline pnl, distributionpoint dp, department d, status s
where pn.packingnote_id = pnl.packingnote_id
and pn.distributionpoint_id = dp.distributionpoint_id
and dp.department_id = d.department_id
and d.customer_id = plpc.customer_id
and pnl.product_id = plpc.product_id
and pnl.sizedefinition_id = plpc.sizedefinition_id
and pnl.finishingmethod_id = plpc.finishingmethod_id
and pn.status_id = s.status_id
and pn.deliverydate = getFirstDayofWeek(trunc(sysdate))+2
and s.code = '30'
and s.statustype = 'PN'
) wednesday,
(select sum(pnl.deliveredamount)
from packingnote pn, packingnoteline pnl, distributionpoint dp, department d, status s
where pn.packingnote_id = pnl.packingnote_id
and pn.distributionpoint_id = dp.distributionpoint_id
and dp.department_id = d.department_id
and d.customer_id = plpc.customer_id
and pnl.product_id = plpc.product_id
and pnl.sizedefinition_id = plpc.sizedefinition_id
and pnl.finishingmethod_id = plpc.finishingmethod_id
and pn.status_id = s.status_id
and pn.deliverydate = getFirstDayofWeek(trunc(sysdate))+3
and s.code = '30'
and s.statustype = 'PN'
) thursday,
(select sum(pnl.deliveredamount)
from packingnote pn, packingnoteline pnl, distributionpoint dp, department d, status s
where pn.packingnote_id = pnl.packingnote_id
and pn.distributionpoint_id = dp.distributionpoint_id
and dp.department_id = d.department_id
and d.customer_id = plpc.customer_id
and pnl.product_id = plpc.product_id
and pnl.sizedefinition_id = plpc.sizedefinition_id
and pnl.finishingmethod_id = plpc.finishingmethod_id
and pn.status_id = s.status_id
and pn.deliverydate = getFirstDayofWeek(trunc(sysdate))+4
and s.code = '30'
and s.statustype = 'PN'
) friday,
(select sum(pnl.deliveredamount)
from packingnote pn, packingnoteline pnl, distributionpoint dp, department d, status s
where pn.packingnote_id = pnl.packingnote_id
and pn.distributionpoint_id = dp.distributionpoint_id
and dp.department_id = d.department_id
and d.customer_id = plpc.customer_id
and pnl.product_id = plpc.product_id
and pnl.sizedefinition_id = plpc.sizedefinition_id
and pnl.finishingmethod_id = plpc.finishingmethod_id
and pn.status_id = s.status_id
and pn.deliverydate = getFirstDayofWeek(trunc(sysdate))+5
and s.code = '30'
and s.statustype = 'PN'
) saturday,
(select sum(pnl.deliveredamount)
from packingnote pn, packingnoteline pnl, distributionpoint dp, department d, status s
where pn.packingnote_id = pnl.packingnote_id
and pn.distributionpoint_id = dp.distributionpoint_id
and dp.department_id = d.department_id
and d.customer_id = plpc.customer_id
and pnl.product_id = plpc.product_id
and pnl.sizedefinition_id = plpc.sizedefinition_id
and pnl.finishingmethod_id = plpc.finishingmethod_id
and pn.status_id = s.status_id
and pn.deliverydate = getLastDayofWeek(trunc(sysdate))
and s.code = '30'
and s.statustype = 'PN'
) sunday,
(select sum(pnl.deliveredamount)
from packingnote pn, packingnoteline pnl, distributionpoint dp, department d, status s
where pn.packingnote_id = pnl.packingnote_id
and pn.distributionpoint_id = dp.distributionpoint_id
and dp.department_id = d.department_id
and d.customer_id = plpc.customer_id
and pnl.product_id = plpc.product_id
and pnl.sizedefinition_id = plpc.sizedefinition_id
and pnl.finishingmethod_id = plpc.finishingmethod_id
and pn.status_id = s.status_id
and pn.deliverydate between getFirstDayofWeek(trunc(sysdate))-28 and getFirstDayofWeek(trunc(sysdate))-1
and s.code = '30'
and s.statustype = 'PN'
) total_last_4_weeks, --original select used only plpc active this week plpc.dateactive <= getFirstDayofWeek(trunc(sysdate)) and plpc.dateinactive >= getLastDayofWeek(trunc(sysdate))
case when plpc.dateactive >= sysdate then 0
  else
(getFirstDayofWeek(trunc(sysdate)) - greatest(
      case when getabsdayNumber(plpc.dateactive) <= 3
        then getFirstDayofWeek(plpc.dateactive)    -- count the week for mo/tu/we
        else getLastDayofWeek(plpc.dateactive) + 1 -- don't count the week for th/fr
      end,getFirstDayofWeek(trunc(sysdate))-28))/7
end weeks_active, /*Needed for average last 4 weeks*/
case when plpc.dateinactive >= sysdate then 0
  else
(getFirstDayofWeek(trunc(sysdate)) - greatest(
      case when getabsdayNumber(plpc.dateinactive) <= 3
        then getFirstDayofWeek(plpc.dateinactive)    -- count the week for mo/tu/we
        else getLastDayofWeek(plpc.dateinactive) + 1 -- don't count the week for th/fr
      end,getFirstDayofWeek(trunc(sysdate))-28))/7
end weeks_inactive, /*Needed for average last 4 weeks*/
(select sum(pnl.deliveredamount)
from packingnote pn, packingnoteline pnl, distributionpoint dp, department d, status s
where pn.packingnote_id = pnl.packingnote_id
and pn.distributionpoint_id = dp.distributionpoint_id
and dp.department_id = d.department_id
and d.customer_id = plpc.customer_id
and pnl.product_id = plpc.product_id
and pnl.sizedefinition_id = plpc.sizedefinition_id
and pnl.finishingmethod_id = plpc.finishingmethod_id
and pn.status_id = s.status_id
and pn.deliverydate between getFirstDayofWeek(trunc(sysdate))-7 and getLastDayofWeek(trunc(sysdate))-7
and s.code = '30'
and s.statustype = 'PN'
) total_last_week,
(select sum(dv.amount)
  from deliveryvariations dv, distributionpoint dp, department d
 where dp.distributionpoint_id = dv.distributionpoint_id
   and d.department_id = dp.department_id
   and d.customer_id = plpc.customer_id
   and dv.product_id = plpc.product_id
   and dv.sizedefinition_id = plpc.sizedefinition_id
   and dv.finishingmethod_id = plpc.finishingmethod_id
   and (dv.processed = 'N' or (dv.processed = 'Y' and exists (select pn.packingnote_id from packingnote pn, status s where pn.packingnote_id = dv.packingnote_id and pn.status_id = s.status_id and s.code = 10)))) outstanding_orders,
plpc.customer_id,
plpc.dateactive,
plpc.dateinactive
from productlistpercustomer plpc,
product p,
sizedefinition sd,
finishingmethod fm
where plpc.product_id = p.product_id
and plpc.sizedefinition_id = sd.sizedefinition_id
and plpc.finishingmethod_id = fm.finishingmethod_id
and p.typeofmerchandise <> 5
)
/

  CREATE OR REPLACE VIEW "V_PNL_DELIVERYFROMSTOCK" ("AMOUNT", "PACKINGNOTE_ID", "PACKINGNOTELINE_ID", "REASONCODE", "REASON_CODE", "LANGUAGECODE") AS 
  SELECT count(ds.uniqueitem_link_id) amount,
      pn.packingnote_id,
      pnl.packingnoteline_id,
      r.code reasoncode,
       (select rd.description from reasoncode_desc rd where rd.reasoncode_id = r.reasoncode_id
        and rd.language_id = l.language_id) reason_code,
      l.code languagecode
  FROM deliveryscan ds, packingnote pn, packingnoteline pnl,reasoncode r, languages l
 WHERE pn.packingnote_id = ds.packingnote_id
and pn.packingnote_id = pnl.packingnote_id
and pnl.product_id = ds.product_link_id
and pnl.sizedefinition_id = ds.sizedefinition_link_id
and pnl.finishingmethod_id = ds.finishingmethod_id
and r.reasoncode_id = ds.reasoncode_id
and ds.fromstock = 'Y'
and r.code in ('ERST', 'STAND', 'UMT','STDVM')
group by pn.packingnote_id, pnl.packingnoteline_id, r.code, r.reasoncode_id, l.language_id, l.code
/

  CREATE OR REPLACE VIEW "V_POOLITEMRAGSTATISTICS" ("REPORTPARAM_ID", "PRODUCTGROUP_ID", "PRODUCTGROUPCODE", "PRODUCTGROUP_DESC", "PRODUCT_ID", "PRODUCTCODE", "PRODUCT_DESC", "SUPPLIERNUMBER", "SUPPLIERNAME", "RAGREASON1_DESC", "PIECES1", "WASHES1", "RAGREASON2_DESC", "PIECES2", "WASHES2", "RAGREASON3_DESC", "PIECES3", "WASHES3", "RAGREASON4_DESC", "PIECES4", "WASHES4", "RAGREASON5_DESC", "PIECES5", "WASHES5") AS 
  select /*+index(ri XIE6RAGGEDITEM) */
       rp.reportparam_id,
       pg.productgroup_id, pg.code productgroupcode,
       (select pgd.description
          from productgroup_desc pgd
         where pgd.productgroup_id = pg.productgroup_id and pgd.language_id=l.language_id) productgroup_desc,
       p.product_id, p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = p.product_id and pd.language_id=l.language_id) product_desc,
       case when rp.number_value = 0 then 0 else s.suppliernumber end suppliernumber,
       case when rp.number_value = 0 then ' ' else s.name end suppliername,
        rr1.description ragreason1_desc,
       sum(case when rr1.ragreason_id = ri.ragreason_id then 1 else 0 end) pieces1,
       sum(case when rr1.ragreason_id = ri.ragreason_id then ri.washestotal else 0 end) washes1,
        rr2.description ragreason2_desc,
       sum(case when rr2.ragreason_id = ri.ragreason_id then 1 else 0 end) pieces2,
       sum(case when rr2.ragreason_id = ri.ragreason_id then ri.washestotal else 0 end) washes2,
        rr3.description ragreason3_desc,
       sum(case when rr3.ragreason_id = ri.ragreason_id then 1 else 0 end) pieces3,
       sum(case when rr3.ragreason_id = ri.ragreason_id then ri.washestotal else 0 end) washes3,
        rr4.description ragreason4_desc,
       sum(case when rr4.ragreason_id = ri.ragreason_id then 1 else 0 end) pieces4,
       sum(case when rr4.ragreason_id = ri.ragreason_id then ri.washestotal else 0 end) washes4,
        rr5.description ragreason5_desc,
       sum(case when rr5.ragreason_id = ri.ragreason_id then 1 else 0 end) pieces5,
       sum(case when rr5.ragreason_id = ri.ragreason_id then ri.washestotal else 0 end) washes5
from raggeditem ri
     left outer join reasoncode rc on rc.reasoncode_id = ri.reasoncode_id,
     product p, productgroup pg, supplier s, businessunit b, languages l,
     reportparam rp
             left outer join ragreason_desc rr1 on rr1.ragreason_id = rp.number_value1 and rr1.language_id = rp.number_value9
             left outer join ragreason_desc rr2 on rr2.ragreason_id = rp.number_value2 and rr2.language_id = rp.number_value9
             left outer join ragreason_desc rr3 on rr3.ragreason_id = rp.number_value3 and rr3.language_id = rp.number_value9
             left outer join ragreason_desc rr4 on rr4.ragreason_id = rp.number_value4 and rr4.language_id = rp.number_value9
             left outer join ragreason_desc rr5 on rr5.ragreason_id = rp.number_value5 and rr5.language_id = rp.number_value9
where p.product_id = ri.product_link_id
      and pg.productgroup_id = p.productgroup_id
      and s.supplier_id = ri.supplier_id
      and b.businessunit_id = ri.businessunit_id
      and ri.poolitem = 1 -- pool items
      and trunc(ri.ragtimestamp) >= rp.date_value1
      and trunc(ri.ragtimestamp) <= rp.date_value2
      and b.code >= rp.string_value1
      and b.code <= rp.string_value2
      and pg.code >= rp.string_value3
      and pg.code <= rp.string_value4
      and p.code >= rp.string_value5
      and p.code <= rp.string_value6
      and ((rp.string_value7 = ' ' and rp.string_value8 = 'ZZZZZZ') --no filter on Reason Code
            or (rc.code >= rp.string_value7 and rc.code <= rp.string_value8))
      and l.code = rp.string_value
group by rp.reportparam_id, l.language_id,
         pg.code, pg.productgroup_id, p.code, p.product_id,
         case when rp.number_value = 0 then 0 else s.suppliernumber end,
         case when rp.number_value = 0 then ' ' else s.name end,
         rr1.description, rr2.description, rr3.description, rr4.description, rr5.description
/

  CREATE OR REPLACE VIEW "V_POOLITEMSATCUSTOMER" ("GRP", "UNIQUEITEM_ID", "BUSINESSUNITCODE", "BUSINESSUNITDESC", "STAYNR", "PRODUCTCODE", "SIZECODE", "PRIMARYID", "STAYCHANGEDATE", "LASTSCANDATE", "CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "LANGUAGECODE", "DAYS", "STAYDESC", "PRODUCTDESC", "ONSITE_SCAN", "SIZEDESC", "ISINVOICED") AS 
  select /*version 1.0*/
       0 grp, ui.uniqueitem_id, bu.code businessunitcode,
       bu.description businessunitdesc, s.staynr, pr.code productcode,
       sz.code sizecode, ui.primaryid, ui.staychangedate, ui.lastscandate,
       cs.customernumber, cs.name customername, ad.city, dp.departmentnumber,
       dp.description departmentdesc, di.distributionpointnumber,
       di.description distributionpointdesc, lan.code languagecode,
       trunc(sysdate) - trunc(ui.staychangedate) days,
       (select sd.description
          from stay_desc sd
         where s.stay_id = sd.stay_id
           and sd.language_id = lan.language_id) staydesc,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdesc,
       nvl((select max(sc.scantimestamp) from scan sc
             where sc.uniqueitem_link_id = ui.uniqueitem_id
               and sc.transactiontype_id = 76),
           ui.staychangedate) onsite_scan,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sz.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc,
       nvl((select max(1)
              from uniqueitemloss uil
                   join invoiceheader ih on uil.lossinvoiceheader_id = ih.invoiceheader_id
             where uil.uniqueitem_link_id = ui.uniqueitem_id and uil.lossstatus = 1
               and ih.invoicenumber <> 0), 0) isInvoiced
  from uniqueitem ui
       join status st on ui.status_id = st.status_id
       join stay s on ui.stay_id = s.stay_id
       join businessunit bu on ui.businessunit_id = bu.businessunit_id
       join product pr on ui.product_id = pr.product_id
       join sizedefinition sz on ui.sizedefinition_id = sz.sizedefinition_id
       join distributionpoint di
            join department dp
                 join customer cs
                      join address ad on cs.visitaddress_id = ad.address_id
                 on dp.customer_id = cs.customer_id
            on di.department_id = dp.department_id
       on ui.distributionpoint_id = di.distributionpoint_id
       cross join languages lan
 where ui.poolitem = 1--pool
   and st.code = 20--in circulation
   and s.staytype = 1
   and s.staynr >= 20
   and s.staynr < 30
/

  CREATE OR REPLACE VIEW "V_POOLITEMSCANS" ("SCANTIMESTAMP", "SCANSTATION", "STAYNR", "STAYDESC", "BUSINESSUNIT_ID", "SYSTEMUSER_ID", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "SIZECODE", "SIZEDESC", "PRODUCTCODE", "PRODUCTDESC", "PRIMARYID", "LANGUAGECODE", "WASHESTOTAL") AS 
  select sc.scantimestamp, sc.scanstation,
  st.staynr,
  (select std.description from stay_desc std where std.stay_id = st.stay_id and std.language_id = l.language_id) staydesc,
  sc.businessunit_id, sc.systemuser_id,
  dpl.distributionpointnumber, dpl.description distributionpointdesc,
  del.departmentnumber, del.description departmentdesc,
  cul.customernumber, cul.name customername,
  szl.code sizecode,
  (select szld.description from sizedefinition_link_desc szld
   where szld.language_id = l.language_id and szld.sizedefinition_link_id = szl.sizedefinition_link_id) sizedesc,
  prl.code productcode,
  (select prld.description from product_link_desc prld
   where prld.language_id = l.language_id and prld.product_link_id = prl.product_link_id) productdesc,
  sc.primaryid, l.code languagecode,
   (select ui.washestotal from uniqueitem ui where ui.uniqueitem_id = sc.uniqueitem_link_id) washestotal
from scan sc, product_link prl, product pr, stay st, distributionpoint_link dpl, department_link del, customer_link cul,
  sizedefinition_link szl, languages l
where sc.weareremployment_link_id is null --Pool item scan
  and sc.product_link_id = prl.product_link_id
  and prl.product_id = pr.product_id
  and pr.uniquepoolitem = 'Y'
  and sc.stay_id = st.stay_id
  and sc.distributionpoint_link_id = dpl.distributionpoint_link_id
  and dpl.department_link_id = del.department_link_id
  and del.customer_link_id = cul.customer_link_id
  and sc.sizedefinition_link_id = szl.sizedefinition_link_id
/

  CREATE OR REPLACE VIEW "V_POOLITEMSINLAUNDRY" ("UNIQUEITEM_ID", "BUSINESSUNITCODE", "BUSINESSUNITDESC", "STAYNR", "STAYDESC", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "PRIMARYID", "STAYCHANGEDATE", "DAYS", "SIZEDESC", "LANGUAGECODE", "ISINVOICED") AS 
  select ui.uniqueitem_id, bu.code businessunitcode, bu.description businessunitdesc, s.staynr,
       (select sd.description
          from stay_desc sd
         where s.stay_id = sd.stay_id
           and sd.language_id = lan.language_id) staydesc, pr.code productcode,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdesc, sz.code sizecode, ui.primaryid, ui.staychangedate,
       trunc(sysdate) - trunc(ui.staychangedate) days,
       (select szd.description
          from sizedefinition_desc szd
         where szd.sizedefinition_id = sz.sizedefinition_id
           and szd.language_id = lan.language_id) sizedesc, lan.code languagecode,
       coalesce((select max(1)
                   from uniqueitemloss uil, invoiceheader ih
                  where uil.uniqueitem_link_id = ui.uniqueitem_id and uil.lossstatus = 1
                    and uil.lossinvoiceheader_id = ih.invoiceheader_id and ih.invoicenumber <> 0), 0) isInvoiced
  from uniqueitem ui
       join businessunit bu on ui.businessunit_id = bu.businessunit_id
       join product pr on ui.product_id = pr.product_id
       join sizedefinition sz on ui.sizedefinition_id = sz.sizedefinition_id
       join stay s on ui.stay_id = s.stay_id
       join status st on ui.status_id = st.status_id, --  and st.statustype = 'UI'  -- unique item
       languages lan
 where ui.poolitem = 1 -- pool
   and st.code = 20 -- in circulation
   and s.staytype = 1
/

  CREATE OR REPLACE VIEW "V_PRICECUSTOMER_EMBLEMTEMPLATE" ("PRICETYPE", "CUSTOMER_ID", "REPORTPARAM_ID", "TIMESTAMP", "DATE_VALUE1", "PRODUCTCODE", "SIZECODE", "PRODUCTDESC", "STARTDATE", "PRICE", "LANGUAGECODE", "REASONCODE", "REASONCODE_DESC", "DECIMALS") AS 
  select /*version 2.0*/
       -- 5 a -- emblem_template
  '7' pricetype, etp.customer_id, rp.reportparam_id, rp.timestamp, rp.date_value1 -- emblem and emblem template , type 7 and 8
, coalesce(prd.code, etp.code) productCode, sz.code sizeCode
, coalesce(( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ), etp.description) productDesc
, etplip.startdate, etplip.price
, languages.code languageCode
, '' reasoncode, '' reasoncode_desc
, (select cu.decimals from currency cu
    where cu.currency_id = (select c.currency_id from customer c where c.customer_id = etp.customer_id)) decimals
from
  emblemtemplate etp
, emblemtemplateline etpli
    left outer join product prd on etpli.product_id = prd.product_id
    left outer join sizedefinition sz on etpli.sizedefinition_id = sz.sizedefinition_id
, emblemtemplatelineprice etplip
, reportparam rp, languages
where
    etp.emblemtemplate_id = etpli.emblemtemplate_id
and etpli.emblemtemplateline_id = etplip.emblemtemplateline_id
    and etplip.startdate = (select max(emblemtemplatelineprice.startdate) from emblemtemplatelineprice
                                       where emblemtemplatelineprice.startdate <= rp.date_value1
                                           and emblemtemplatelineprice.emblemtemplateline_id = etpli.emblemtemplateline_id)
UNION ALL
select    -- 5 b -- emblem_template / prep_charges
  '7' pricetype, cpp.customer_id, rp.reportparam_id, rp.timestamp, rp.date_value1
, '1' productCode, '' sizeCode, '' productDesc
, cpp.startdate, cpp.price
, languages.code languageCode
, (select rc.code from reasoncode rc where cpp.reasoncode_id = rc.reasoncode_id) reasoncode
, (select rcd.description from reasoncode_desc rcd where cpp.reasoncode_id = rcd.reasoncode_id and rcd.language_id = languages.language_id) reasoncode_desc
, (select cu.decimals from currency cu
    where cu.currency_id = (select c.currency_id from customer c where c.customer_id = cpp.customer_id)) decimals
from
  customerprepcharge cpp
, reportparam rp, languages
where
    cpp.startdate = ( select max(customerprepcharge.startdate) from customerprepcharge
                             where customerprepcharge.customer_id = cpp.customer_id
                                   and customerprepcharge.startdate <= rp.date_value1
                                   and ((customerprepcharge.reasoncode_id = cpp.reasoncode_id)
                                   or(cpp.reasoncode_id is null and customerprepcharge.reasoncode_id is null )))
/

  CREATE OR REPLACE VIEW "V_PRICECUSTOMER_INSURANCE" ("PRICETYPE", "CUSTOMER_ID", "REPORTPARAM_ID", "TIMESTAMP", "DATE_VALUE1", "PRODUCTCODE", "SIZECODE", "FINISHINGMETCODE", "PRODUCTDESC", "PRICE_DETAILS", "LANGUAGECODE", "DECIMALS", "STARTDATE") AS 
  select /*version 2.0*/
       -- 6 -- insurance
  '9' pricetype, pripc.customer_id, rp.reportparam_id, rp.timestamp, rp.date_value1 -- insurance , type 9
, prd.code productcode, sz.code sizecode, fm.code finishingmetcode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productdesc
, cast(f_priceinsurance_details(pripc.customer_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, rp.date_value1) as varchar2(30)) price_details
, languages.code languagecode
, (select cu.decimals from currency cu
    where cu.currency_id = (select c.currency_id from customer c where c.customer_id = pripc.customer_id)) decimals
, getdateforyearmonthday(
   castvarcharasnumber(substr(f_priceinsurance_details(pripc.customer_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, rp.date_value1), 1, 4)),
   castvarcharasnumber(substr(f_priceinsurance_details(pripc.customer_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, rp.date_value1), 5, 2)),
   castvarcharasnumber(substr(f_priceinsurance_details(pripc.customer_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, rp.date_value1), 7, 2))) startdate
from
  productlistpercustomer plpc, pricelistpercustomer pripc
, product prd, sizedefinition sz, finishingmethod fm
, reportparam rp, languages
where
    plpc.customer_id = pripc.customer_id
and rp.date_value1 between plpc.dateactive and plpc.dateinactive
    and rp.date_value1 between pripc.dateactive and pripc.dateinactive
        and pripc.pricetype = 9
            and f_priceinsurance_details(pripc.customer_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, rp.date_value1) is not null
and plpc.product_id = prd.product_id
and plpc.sizedefinition_id = sz.sizedefinition_id
and plpc.finishingmethod_id = fm.finishingmethod_id
/

  CREATE OR REPLACE VIEW "V_PRICECUSTOMER_INVOICE" ("PRICETYPE", "CUSTOMER_ID", "PRICE", "DECIMALS") AS 
  select /*version 2.0*/
  50 pricetype -- assign pricetype 50 TO 'minimuminvoiceamount' group
, cu.customer_id, cu.minimuminvoiceamount price
, (select c.decimals from currency c
    where c.currency_id = cu.currency_id) decimals
from
  customer cu
union
select
  60 pricetype -- assign pricetype 60 TO 'creditsqueezeperc' group
, cu.customer_id, cubi.creditsqueezeperc price
, (select c.decimals from currency c
    where c.currency_id = cu.currency_id) decimals
from
  customer cu, customerbillinginfo cubi
where
    ( cubi.customer_id = cu.customer_id or  cubi.customer_id = cu.debtor_id )
and cubi.creditsqueezeperc <> 0
/

  CREATE OR REPLACE VIEW "V_PRICECUSTOMER_LABEL" ("PRICETYPE", "CUSTOMER_ID", "REPORTPARAM_ID", "TIMESTAMP", "DATE_VALUE1", "LABELTYPE", "STARTDATE", "PRICE", "DECIMALS") AS 
  select /*version 2.0*/
       -- 7 --  label
  '92' pricetype, cullyp.customer_id, rp.reportparam_id, rp.timestamp, rp.date_value1
, cullyp.labeltype -- labeltype = 1 : 'code label'  2 : 'name label'
, cullyp.startdate, cullyp.price
, (select cu.decimals from currency cu
    where cu.currency_id = (select c.currency_id from customer c where c.customer_id = cullyp.customer_id)) decimals
from
  customerlabellayoutprice cullyp, reportparam rp
where
  cullyp.startdate = (select max(customerlabellayoutprice.startdate)
                                  from customerlabellayoutprice
                                       where customerlabellayoutprice.customer_id = cullyp.customer_id
                                       and customerlabellayoutprice.labeltype = cullyp.labeltype
                                       and customerlabellayoutprice.startdate <= rp.date_value1
                                       )
UNION ALL
select    -- 8 --  finance charge
  '93' pricetype, financecharge.customer_link_id, rp.reportparam_id, rp.timestamp, rp.date_value1
, null labeltype, financecharge.cutoffdate, financecharge.amountdue
, (select cu.decimals from currency cu
    where cu.currency_id = (select c.currency_id from customer c where c.customer_id = financecharge.customer_link_id)) decimals
from
  financecharge, reportparam rp
where
    financecharge.cutoffdate = (select max(fc.cutoffdate) from financecharge fc
                                   where financecharge.customer_link_id = fc.customer_link_id
                                     and fc.cutoffdate <= rp.date_value1
                                     )
/

  CREATE OR REPLACE VIEW "V_PRICECUSTOMER_REPAIR" ("PRICETYPE", "CUSTOMER_ID", "REPORTPARAM_ID", "TIMESTAMP", "DATE_VALUE1", "PRODUCTCODE", "PRODUCTDESC", "PRICE_DETAILS", "LANGUAGECODE", "DECIMALS", "STARTDATE") AS 
  select /*version 2.0*/
       -- 4 a -- repair / price per pieces
  '6a' pricetype, pripc.customer_id, rp.reportparam_id, rp.timestamp, rp.date_value1
, rty.code productcode
, ( select repairtype_desc.description from repairtype_desc where repairtype_desc.repairtype_id = rty.repairtype_id
  and repairtype_desc.language_id = languages.language_id ) productdesc
, cast(f_pricerepair_details(pripc.customer_id, rty.repairtype_id, rp.date_value1, 1) as varchar2(30)) price_details
, languages.code languagecode
, (select cu.decimals from currency cu
    where cu.currency_id = (select c.currency_id from customer c where c.customer_id = pripc.customer_id)) decimals
, getdateforyearmonthday(
    castvarcharasnumber(substr(f_pricerepair_details(pripc.customer_id, rty.repairtype_id, rp.date_value1, 1), 1, 4)),
    castvarcharasnumber(substr(f_pricerepair_details(pripc.customer_id, rty.repairtype_id, rp.date_value1, 1), 5, 2)),
    castvarcharasnumber(substr(f_pricerepair_details(pripc.customer_id, rty.repairtype_id, rp.date_value1, 1), 7, 2))) startdate
from
  pricelistpercustomer pripc
, repairtype rty -- ! -- cross join
, reportparam rp, languages
where
    pripc.customer_id = pripc.customer_id
and rp.date_value1 between pripc.dateactive and pripc.dateinactive
    and pripc.pricetype = 6
        and f_pricerepair_details(pripc.customer_id, rty.repairtype_id, rp.date_value1, 1) is not null
union
select    -- 4 b -- repair / price per minute
  '6b' pricetype, pripc.customer_id, rp.reportparam_id, rp.timestamp, rp.date_value1
, rty.code productcode
, ( select repairtype_desc.description from repairtype_desc where repairtype_desc.repairtype_id = rty.repairtype_id
  and repairtype_desc.language_id = languages.language_id ) productdesc
, cast(f_pricerepair_details(pripc.customer_id, rty.repairtype_id, rp.date_value1, 2) as varchar2(30)) price_details
, languages.code languagecode
, (select cu.decimals from currency cu
    where cu.currency_id = (select c.currency_id from customer c where c.customer_id = pripc.customer_id)) decimals
, getdateforyearmonthday(
    castvarcharasnumber(substr(f_pricerepair_details(pripc.customer_id, rty.repairtype_id, rp.date_value1, 2), 1, 4)),
    castvarcharasnumber(substr(f_pricerepair_details(pripc.customer_id, rty.repairtype_id, rp.date_value1, 2), 5, 2)),
    castvarcharasnumber(substr(f_pricerepair_details(pripc.customer_id, rty.repairtype_id, rp.date_value1, 2), 7, 2))) startdate
from
  repairtype rty -- ! -- cross join
, pricelistpercustomer pripc
, reportparam rp, languages
where
    pripc.customer_id = pripc.customer_id
and rp.date_value1 between pripc.dateactive and pripc.dateinactive
    and pripc.pricetype = 6
        and f_pricerepair_details(pripc.customer_id, rty.repairtype_id, rp.date_value1, 2) is not null
/

  CREATE OR REPLACE VIEW "V_PRICECUSTOMER_SPECIALCHARGE" ("PRICETYPE", "SUBTYPE", "CUSTOMER_ID", "REPORTPARAM_ID", "TIMESTAMP", "DATE_VALUE1", "PRODUCTCODE", "PRODUCTDESC", "STARTDATE", "PRICE", "FREQUENCY", "PRICE_TYPE", "LANGUAGECODE", "DECIMALS") AS 
  select /*version 3.0*/
       -- 9 --  special charge
       '94' pricetype, 1 subtype, cuscg.customer_id,
       rp.reportparam_id, rp.timestamp, rp.date_value1, scg.code productcode,
       (select scg_d.description
          from specialcharge_desc scg_d
         where scg_d.specialcharge_id = scg.specialcharge_id
           and scg_d.language_id = lan.language_id) productdesc, scg.startdate,
       case scg.fixedamount
          when 'N' then
           pack_price.specialcharge_percentage(cuscg.customer_id, scg.specialcharge_id, rp.date_value1)
          else
           pack_price.specialcharge_price(cuscg.customer_id, scg.specialcharge_id, rp.date_value1)
        end price, scg.frequency,
       case scg.fixedamount
          when 'N' then 2
          else 1 end price_type, lan.code languagecode,
       (select cu.decimals
          from customer c
          join currency cu on c.currency_id = cu.currency_id
         where c.customer_id = cuscg.customer_id) decimals
  from customerspecialcharge cuscg
       join specialcharge scg on cuscg.specialcharge_id = scg.specialcharge_id
       cross join reportparam rp
       cross join languages lan
 union all -- 10 -- locker
select cast(950 + culop.pricetype as varchar2(3)) pricetype, 0 subtype, culop.customer_id,
       rp.reportparam_id, rp.timestamp, rp.date_value1,
       cast((case culop.pricetype
                when 1 then culom.chargerent
                when 2 then culom.chargeservice
             end) as varchar2(12)) productcode,
       '' productdesc, culop.startdate, culop.price, null frequency,
       culom.fixednumberbank price_details, lan.code languagecode,
       (select cu.decimals
          from customer c
          join currency cu on c.currency_id = cu.currency_id
         where c.customer_id = culop.customer_id) decimals
  from customerlockermanagement culom
       join customerlockerprice culop on culom.customer_id = culop.customer_id
       cross join reportparam rp
       cross join languages lan
 where culop.startdate = (select customerlockerprice.startdate
                            from customerlockerprice
                           where culop.customer_id = customerlockerprice.customer_id
                             and customerlockerprice.pricetype = culop.pricetype
                             and customerlockerprice.startdate <= rp.date_value1)
 union all
select '94' pricetype, 2 subtype, ci.customer_id,
       rp.reportparam_id, rp.timestamp, rp.date_value1, scg.code productcode,
       (select scg_d.description
          from specialcharge_desc scg_d
         where scg_d.specialcharge_id = scg.specialcharge_id
           and scg_d.language_id = lan.language_id) productdesc,
       cl.startdate, cl.newamount price, scg.frequency,
       case cl.newamount
          when 0 then 2
          else 1 end price_type, lan.code languagecode,
       (select cu.decimals
          from currency cu
         where cu.currency_id = c.currency_id) decimals
  from clientinvoicecategorycharge cl
       join specialcharge scg on cl.specialcharge_id = scg.specialcharge_id
       join clientinvoicecategory ci
            join customer c on ci.customer_id = c.customer_id
       on cl.clientinvoicecategory_id = ci.clientinvoicecategory_id
       cross join reportparam rp
       cross join languages lan
 union all
select '97' pricetype, 0 subtype, csc.customer_id, rp.reportparam_id, rp.timestamp, rp.date_value1,
       'Stock charge' productcode, '' productdesc, csc.startdate, csc.price, null frequency,
       null price_type, lan.code languagecode,
       (select cu.decimals
          from customer c
          join currency cu on c.currency_id = cu.currency_id
         where c.customer_id = csc.customer_id) decimals
  from customerstockcharge csc
       cross join reportparam rp
       cross join languages lan
 where csc.startdate = (select max(csc2.startdate)
                          from customerstockcharge csc2
                         where csc2.customer_id = csc.customer_id
                           and csc2.startdate <= rp.date_value1)
 union all
select '98' pricetype, 0 subtype, csc.customer_id, rp.reportparam_id, rp.timestamp, rp.date_value1,
       'Service Costs' productcode, '' productdesc, csc.startdate, csc.price, null frequency,
       csc.pricetype, lan.code languagecode,
       (select cu.decimals
          from customer c
          join currency cu on c.currency_id = cu.currency_id
         where c.customer_id = csc.customer_id) decimals
  from customerservicecostsprice csc
       cross join reportparam rp
       cross join languages lan
 where csc.startdate = (select max(csc2.startdate)
                          from customerservicecostsprice csc2
                         where csc2.customer_id = csc.customer_id
                           and csc2.pricetype = csc.pricetype
                           and csc2.startdate <= rp.date_value1)
/

  CREATE OR REPLACE VIEW "V_PRICECUSTOMER_WASH" ("PRICETYPE", "CUSTOMER_ID", "REPORTPARAM_ID", "TIMESTAMP", "DATE_VALUE1", "PRODUCTCODE", "SIZECODE", "FINISHINGMETCODE", "PRODUCTDESC", "PRICE_DETAILS", "DISCOUNT", "LANGUAGECODE", "RPPRICESID", "CHANGESPERWEEK", "STARTDATE", "DECIMALS") AS 
  select /*version 2.0*/
       distinct   -- 1 -- wash only piece price, rent, replacement, sales
  rpprices.copy_number pricetype,
  plpc.customer_id, rp.reportparam_id, rp.timestamp, rp.date_value1
, prd.code productcode, sz.code sizecode, fm.code finishingmetcode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productdesc
, rpprices.string_value2 price_details
, case rpprices.copy_number--pripc.pricetype
       when 1 then rpprices.number_value5
       when 2 then rpprices.number_value5
          end
         discount
, languages.code languagecode, rpprices.reportparam_id rppricesid, plpc.changesperweek
, getdateforyearmonthday(castvarcharasnumber(substr(rpprices.string_value2, 1, 4)),
castvarcharasnumber(substr(rpprices.string_value2, 5, 2)),
castvarcharasnumber(substr(rpprices.string_value2, 7, 2))) startdate
, (select cu.decimals from currency cu
    where cu.currency_id = (select c.currency_id from customer c where c.customer_id = plpc.customer_id)) decimals
from
  productlistpercustomer plpc
, product prd, sizedefinition sz, finishingmethod fm
, reportparam rp, languages
, reportparam rpprices
where
    rpprices.number_value = plpc.productlistpercustomer_id
and rp.date_value1 between plpc.dateactive and plpc.dateinactive
and plpc.product_id = prd.product_id
and plpc.sizedefinition_id = sz.sizedefinition_id
and plpc.finishingmethod_id = fm.finishingmethod_id
/

  CREATE OR REPLACE VIEW "V_PRICECUSTOMER_WEARER" ("CUSTOMER_ID", "REPORTPARAM_ID", "WEARERNUMBER", "FULLNAME", "ADMINNUMBER", "PRODUCTCODE", "SIZECODE", "FINISHINGMETCODE", "PRODUCTDESC", "STARTDATE", "PRICE", "LANGUAGECODE", "DECIMALS") AS 
  select /*version 2.0*/
  we.customer_id, rp.reportparam_id
, we.wearernumber, we.fullname, we.customeremployeenumber adminnumber
, prd.code productCode, sz.code sizeCode, fm.code finishingmetCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, wip.startdate, wip.price
, languages.code languageCode
, (select cu.decimals from currency cu
    where cu.currency_id = (select c.currency_id from customer c where c.customer_id = we.customer_id)) decimals
from
  wearer we, weareremployment wemp, wearerinventory weinv
, product prd, sizedefinition sz, finishingmethod fm
, wearerinvprice wip
, reportparam rp, languages
where
    we.wearer_id = wemp.wearer_id
and wemp.weareremployment_id = weinv.weareremployment_id
    and weinv.product_id = prd.product_id
        and weinv.sizedefinition_id = sz.sizedefinition_id
            and weinv.finishingmethod_id = fm.finishingmethod_id
and weinv.wearerinventory_id = wip.wearerinventory_id
    and wip.startdate = (select max(wearerinvprice.startdate) from wearerinvprice
                         where wearerinvprice.wearerinventory_id = wip.wearerinventory_id
                         and wearerinvprice.startdate <= RP.DATE_VALUE1)
    and weinv.dateinactive >= rp.date_value1
/

  CREATE OR REPLACE VIEW "V_PRICECUSTOMER_WEIGHT" ("PRICETYPE", "CUSTOMER_ID", "REPORTPARAM_ID", "TIMESTAMP", "DATE_VALUE1", "PRODUCTCODE", "SIZECODE", "FINISHINGMETCODE", "PRODUCTDESC", "PRICE", "PRICE_DETAILS", "DISCOUNT", "LANGUAGECODE", "WEIGHINGCATEGORY_ID", "DECIMALS") AS 
  select /*version 2.0*/
       distinct  -- 2 -- weight soil (distinct : priority multiply lines)
  '5a' pricetype, pripc.customer_id, rp.reportparam_id, rp.timestamp, rp.date_value1
, wgh.code productcode, '' sizecode, '' finishingmetcode
, ( select weighingcategory_desc.description from weighingcategory_desc where weighingcategory_desc.weighingcategory_id = wgh.weighingcategory_id
  and weighingcategory_desc.language_id = languages.language_id ) productdesc
, pack_price.weight_price(pripc.customer_id, wgh.weighingcategory_id, 'Y', rp.date_value1) price
, pack_price.weight_price_details(pripc.customer_id, wgh.weighingcategory_id, 'Y', rp.date_value1)price_details
, pack_price.weight_discount_display(pripc.customer_id, wgh.weighingcategory_id, 'Y', rp.date_value1) discount
, languages.code languagecode, wgh.weighingcategory_id
, (select cu.decimals from currency cu
    where cu.currency_id = (select c.currency_id from customer c where c.customer_id = pripc.customer_id)) decimals
from
  weighingcategpercustomer whgcu, weighingcategory wgh
, pricelistpercustomer pripc
, reportparam rp, languages
where
    whgcu.customer_id = pripc.customer_id
and whgcu.weightsoiled = 'Y'
    and whgcu.invoicemethod = 2
and wgh.weighingcategory_id = whgcu.weighingcategory_id
    and rp.date_value1 between whgcu.dateactive and whgcu.dateinactive
    and rp.date_value1 between pripc.dateactive and pripc.dateinactive
        and pripc.pricetype = 5
            and pack_price.weight_price_details(pripc.customer_id, wgh.weighingcategory_id, 'Y', rp.date_value1) is not null
union all
select distinct  -- 3 -- weight clean ( distinct : priority multiply lines)
  '5b' pricetype, pripc.customer_id, rp.reportparam_id, rp.timestamp, rp.date_value1
, wgh.code productcode, '' sizecode, '' finishingmetcode
, ( select weighingcategory_desc.description from weighingcategory_desc where weighingcategory_desc.weighingcategory_id = wgh.weighingcategory_id
  and weighingcategory_desc.language_id = languages.language_id ) productdesc
, pack_price.weight_price(pripc.customer_id, wgh.weighingcategory_id, 'N', rp.date_value1) price
, pack_price.weight_price_details(pripc.customer_id, wgh.weighingcategory_id, 'Y', rp.date_value1)price_details
, pack_price.weight_discount_display(pripc.customer_id, wgh.weighingcategory_id, 'N', rp.date_value1) discount
, languages.code languagecode, wgh.weighingcategory_id
, (select cu.decimals from currency cu
    where cu.currency_id = (select c.currency_id from customer c where c.customer_id = pripc.customer_id)) decimals
from
  weighingcategpercustomer whgcu, weighingcategory wgh
, pricelistpercustomer pripc
, reportparam rp, languages
where
    whgcu.customer_id = pripc.customer_id
and whgcu.weightclean = 'Y'
                and whgcu.invoicemethod = 3
and rp.date_value1 between whgcu.dateactive and whgcu.dateinactive
    and whgcu.weighingcategory_id = wgh.weighingcategory_id
    and rp.date_value1 between pripc.dateactive and pripc.dateinactive
        and pripc.pricetype = 5
            and pack_price.weight_price_details(pripc.customer_id, wgh.weighingcategory_id, 'N', rp.date_value1) is not null
/

  CREATE OR REPLACE VIEW "V_PRICEUPDATE" ("CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "NEXTANNIVERSARYDATE", "ANNIVERSARYPRICEADJ", "FIXEDRENTPERC", "FIXEDWASHPERC", "FIXEDREPLACEPERC", "FIXEDSALESPERC", "FIXEDWEIGHTPERC", "PRODUCTCODE", "SIZECODE", "PRODUCTDESC", "RQAQTY", "MAXINVENTORY", "PLANT_ID", "BUCODE", "CPIBASED", "CPI_INCRPERC", "RENTPRICE", "RENTPRICE_CHPERWEEK", "WASHPRICE", "REPLACEPRICE", "SALESPRICE", "WEIGHTPRICE", "BILLINGMETHOD", "CHANGESPERWEEK", "STARTDATE", "TYPEOFRENT", "TYPEOFMERCHANDISE", "LANGUAGECODE", "COUNTWEARERS", "DATEACTIVE", "DATEINACTIVE", "CUST_DATEACTIVE", "CUST_DATEINACTIVE") AS 
  select c.customer_id, c.customernumber, c.name customername, cpc.nextanniversarydate, cpc.anniversarypriceadj, cpc.fixedrentperc,
       cpc.fixedwashperc, cpc.fixedreplaceperc, cpc.fixedsalesperc, cpc.fixedweightperc, p.code productcode, sd.code sizecode,
       (select pd.description
          from product_desc pd
         where pd.product_id = p.product_id
           and pd.language_id = lan.language_id) productdesc,
       nvl((select sum(rqa.quantity)
              from rentalqtyadjustment rqa
              join productlistperdistribpoint plpd on rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
              join distributionpoint dp on plpd.distributionpoint_id = dp.distributionpoint_id
              join department d on dp.department_id = d.department_id
             where plpd.product_id = plpc.product_id
               and plpd.sizedefinition_id = plpc.sizedefinition_id
               and plpd.finishingmethod_id = plpc.finishingmethod_id
               and d.customer_id = c.customer_id
               and rqa.sampleitem = 'N' --only chargeable
               and rqa.adjustmentdate <= sysdate), 0) rqaqty,
       nvl((select sum(wi.maxinventory)
              from wearerinventory wi
              join weareremployment we on wi.weareremployment_id = we.weareremployment_id
              join wearer w on we.wearer_id = w.wearer_id
             where w.customer_id = c.customer_id
               and wi.product_id = plpc.product_id
               and (wi.sizedefinition_id = plpc.sizedefinition_id or
                   plpc.sizedefinition_id in (select siz.sizedefinition_id from sizedefinition siz where siz.code = '*'))
               and wi.finishingmethod_id = plpc.finishingmethod_id), 0) maxinventory,
       bu.plant_id, bu.code bucode, cpc.cpibased,
       (select ss.value
          from systemsetting ss
         where ss.name = 'CPI_INCREASEPERCENTAGE'
           and ss.plant_id = bu.plant_id) cpi_incrperc,
       pack_price.rent_price(plpc.customer_id, plpc.product_id, plpc.sizedefinition_id, plpc.finishingmethod_id, cpc.nextanniversarydate) rentprice,
       pack_price.rent_price(plpc.customer_id, plpc.product_id, plpc.sizedefinition_id, plpc.finishingmethod_id, cpc.nextanniversarydate, crp.changesperweek) rentprice_chperweek,
       pack_price.wash_price(plpc.customer_id, plpc.product_id, plpc.sizedefinition_id, plpc.finishingmethod_id, cpc.nextanniversarydate) washprice,
       pack_price.replacement_price(plpc.customer_id, plpc.product_id, plpc.sizedefinition_id, plpc.finishingmethod_id, cpc.nextanniversarydate) replaceprice,
       pack_price.sales_price(plpc.customer_id, plpc.product_id, plpc.sizedefinition_id, cpc.nextanniversarydate) salesprice,
       pack_price.weight_price(plpc.customer_id, (select min(wcc.weighingcategory_id) from weighingcategpercustomer wcc
                                                   where wcc.customer_id = c.customer_id), cpc.nextanniversarydate) weightprice,
       plpc.billingmethod, crp.changesperweek, crp.startdate, crp.typeofrent, p.typeofmerchandise, lan.code languagecode,
       nvl((select count(w.wearernumber)
              from wearerinventory wi
              join weareremployment we on wi.weareremployment_id = we.weareremployment_id
              join wearer w on we.wearer_id = w.wearer_id
             where w.customer_id = c.customer_id
               and wi.product_id = plpc.product_id
               and (wi.sizedefinition_id = plpc.sizedefinition_id or
                   plpc.sizedefinition_id in (select siz.sizedefinition_id from sizedefinition siz where siz.code = '*'))
               and wi.finishingmethod_id = plpc.finishingmethod_id
               and wi.changesperweek = nvl(crp.changesperweek, wi.changesperweek)), 0) countwearers,
       plpc.dateactive, plpc.dateinactive, c.dateactive cust_dateactive, c.dateinactive cust_dateinactive
  from contractspercustomer cpc
  join customer c on cpc.customer_id = c.customer_id
  join businessunit bu on c.defaultbusinessunit_id = bu.businessunit_id
  join productlistpercustomer plpc
       left join customerrentprice crp on plpc.productlistpercustomer_id = crp.productlistpercustomer_id and crp.typeofrent = 2
    on c.customer_id = plpc.customer_id
  join product p on plpc.product_id = p.product_id
  join sizedefinition sd on plpc.sizedefinition_id = sd.sizedefinition_id
  join finishingmethod fm on plpc.finishingmethod_id = fm.finishingmethod_id
     , languages lan
 where cpc.nextanniversarydate <> getABSMaxDate and c.dateactive <> getABSMaxDate --and c.dateinactive > cpc.nextanniversarydate
   and coalesce(crp.startdate, sysdate) = coalesce((select max(crp2.startdate)
                                                      from customerrentprice crp2
                                                     where crp2.productlistpercustomer_id = plpc.productlistpercustomer_id
                                                       and crp2.typeofrent = 2)
                                                 , sysdate)
/

  CREATE OR REPLACE VIEW "V_PRODUCT" ("CODE", "DESCRIPTION", "LONGDESCRIPTION", "PRODUCTGROUPCODE", "PRODUCTGROUPDESCRIPTION", "WEIGHINGCATEGORYCODE", "WEIGHINGCATEGORYDESCRIPTION", "SIZETYPECODE", "SIZETYPEDESCRIPTION", "PACKINGSEQUENCE", "PACKINGAMOUNT", "MODEL", "PARENTPRODUCTCODE", "PARENTPRODUCTDESCRIPTION", "GARMENTSET", "OCCUPANCYRELATED", "SPECIALSIZE", "ACTIVE", "VOLUMEUNITS", "THEORETICALWEIGHT", "SUPPLIERNUMBER", "SUPPLIERNAME", "COLORCODE", "COLORDESCRIPTION", "FABRICCODE", "FABRICDESCRIPTION", "WASHINGPROCESSCODE", "WASHINGPROCESSDESCRIPTION", "PACK", "REGISTRATIONUNITCODE", "REGISTRATIONUNITDESCRIPTION", "LEGACYPRODUCTCODE", "SOILCOUNTMETHOD", "RECORDPASSIVESTOCK", "TYPEOFMERCHANDISE", "MINIMUMTURNAROUND", "AUTOREPLACEMENT", "SHORTDESCRIPTION", "RENTTURNOVERGROUPCODE", "RENTTURNOVERGROUPDESCRIPTION", "WASHURNOVERGROUPCODE", "WASHTURNOVERGROUPDESCRIPTION", "REPLACEMENTTURNOVERGROUPCODE", "REPLACEMENTTURNOVERGROUPDESC", "SALESTURNOVERGROUPCODE", "SALESTURNOVERGROUPDESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT PRODUCT.CODE,
 (SELECT description FROM PRODUCT_DESC A WHERE A.PRODUCT_ID = PRODUCT.PRODUCT_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) DESCRIPTION,
 (SELECT LONGDESCRIPTION FROM PRODUCT_DESC B WHERE B.PRODUCT_ID = PRODUCT.PRODUCT_ID
  AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) LONGDESCRIPTION,
  PRODUCTGROUP.CODE PRODUCTGROUPCODE,
 (SELECT DESCRIPTION FROM PRODUCTGROUP_DESC C WHERE C.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID
  AND C.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTGROUPDESCRIPTION,
  WEIGHINGCATEGORY.CODE WEIGHINGCATEGORYCODE,
 (SELECT DESCRIPTION FROM WEIGHINGCATEGORY_DESC D WHERE D.WEIGHINGCATEGORY_ID = PRODUCT.WEIGHINGCATEGORY_ID
  AND D.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) WEIGHINGCATEGORYDESCRIPTION,
  SIZETYPE.CODE SIZETYPECODE,
 (SELECT DESCRIPTION FROM SIZETYPE_DESC E WHERE E.SIZETYPE_ID = PRODUCT.SIZETYPE_ID
  AND E.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZETYPEDESCRIPTION,
  PRODUCT.PACKINGSEQUENCE,
  PRODUCT.PACKINGAMOUNT, PRODUCT.MODEL, PARENTPRODUCT.CODE PARENTPRODUCTCODE,
 (SELECT description FROM PRODUCT_DESC F WHERE F.PRODUCT_ID = PRODUCT.PARENTPRODUCT_ID
  AND F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PARENTPRODUCTDESCRIPTION,
  PRODUCT.GARMENTSET, PRODUCT.OCCUPANCYRELATED,
    PRODUCT.SPECIALSIZE, PRODUCT.ACTIVE, PRODUCT.VOLUMEUNITS, PRODUCT.THEORETICALWEIGHT,
  SUPPLIER.SUPPLIERNUMBER, SUPPLIER.NAME SUPPLIERNAME,
  COLOR.CODE COLORCODE,
 (SELECT description FROM COLOR_DESC G WHERE G.COLOR_ID = PRODUCT.COLOR_ID
  AND G.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) COLORDESCRIPTION,
  FABRIC.CODE FABRICCODE,
 (SELECT description FROM FABRIC_DESC H WHERE H.FABRIC_ID = PRODUCT.FABRIC_ID
  AND H.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FABRICDESCRIPTION,
  WASHINGPROCESS.CODE WASHINGPROCESSCODE,
 (SELECT description FROM WASHINGPROCESS_DESC I WHERE I.WASHINGPROCESS_ID = PRODUCT.WASHINGPROCESS_ID
  AND I.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) WASHINGPROCESSDESCRIPTION,
  PRODUCT.PACK, REGISTRATIONUNIT.CODE REGISTRATIONUNITCODE,
 (SELECT description FROM REGISTRATIONUNIT_DESC J WHERE J.REGISTRATIONUNIT_ID = PRODUCT.REGISTRATIONUNIT_ID
  AND J.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) REGISTRATIONUNITDESCRIPTION,
  PRODUCT.LEGACYPRODUCTCODE, PRODUCT.SOILCOUNTMETHOD, PRODUCT.RECORDPASSIVESTOCK,
  PRODUCT.TYPEOFMERCHANDISE, PRODUCT.MINIMUMTURNAROUND, PRODUCT.AUTOREPLACEMENT, PRODUCT.SHORTDESCRIPTION,
  rentturnovergroup.code rentturnovergroupcode,
 (SELECT description FROM turnovergroup_DESC K WHERE K.turnovergroup_id = PRODUCT.rentturnovergroup_id
  AND K.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) rentturnovergroupdescription,
  washturnovergroup.code washurnovergroupcode,
 (SELECT description FROM turnovergroup_DESC L WHERE L.turnovergroup_id = PRODUCT.washturnovergroup_id
  AND L.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) washturnovergroupdescription,
  replacementturnovergroup.code replacementturnovergroupcode,
 (SELECT description FROM turnovergroup_DESC M WHERE M.turnovergroup_id = PRODUCT.replacementturnovergroup_id
  AND M.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) replacementturnovergroupdesc,
  salesturnovergroup.code salesturnovergroupcode,
 (SELECT description FROM turnovergroup_DESC N WHERE N.turnovergroup_id = PRODUCT.salesturnovergroup_id
  AND N.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) salesturnovergroupdescription,
  PRODUCT.SYSTEMUSER_ID, PRODUCT.TIMESTAMP, LANGUAGES.CODE LANGUAGECODE
FROM PRODUCT
 left outer join PRODUCTGROUP on(PRODUCT.PRODUCTGROUP_ID = PRODUCTGROUP.PRODUCTGROUP_ID)
 left outer join WEIGHINGCATEGORY on(PRODUCT.WEIGHINGCATEGORY_ID = WEIGHINGCATEGORY.WEIGHINGCATEGORY_ID)
 left outer join turnovergroup rentturnovergroup ON (product.rentturnovergroup_id = rentturnovergroup.turnovergroup_id)
 left outer join turnovergroup washturnovergroup ON (product.washturnovergroup_id = washturnovergroup.turnovergroup_id)
 left outer join turnovergroup replacementturnovergroup ON (product.replacementturnovergroup_id = replacementturnovergroup.turnovergroup_id)
 left outer join turnovergroup salesturnovergroup ON (product.salesturnovergroup_id = salesturnovergroup.turnovergroup_id),
 PRODUCT PARENTPRODUCT, SUPPLIER, COLOR, FABRIC, WASHINGPROCESS, SIZETYPE, REGISTRATIONUNIT, LANGUAGES
WHERE PRODUCT.SIZETYPE_ID = SIZETYPE.SIZETYPE_ID
 AND PRODUCT.PARENTPRODUCT_ID = PARENTPRODUCT.PRODUCT_ID
 AND PRODUCT.SUPPLIER_ID = SUPPLIER.SUPPLIER_ID
 and PRODUCT.COLOR_ID = COLOR.COLOR_ID
 and PRODUCT.FABRIC_ID = FABRIC.FABRIC_ID
 and PRODUCT.REGISTRATIONUNIT_ID = REGISTRATIONUNIT.REGISTRATIONUNIT_ID
 and PRODUCT.WASHINGPROCESS_ID = WASHINGPROCESS.WASHINGPROCESS_ID
/

  CREATE OR REPLACE VIEW "V_PRODUCTFINISHINGMETHOD" ("PRODUCTCODE", "PRODUCTDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT PRODUCT.CODE,
 (SELECT description FROM PRODUCT_DESC A WHERE A.PRODUCT_ID = PRODUCTFINISHINGMETHOD.PRODUCT_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
 FINISHINGMETHOD.CODE,
 (SELECT description FROM FINISHINGMETHOD_DESC B WHERE B.FINISHINGMETHOD_ID = PRODUCTFINISHINGMETHOD.FINISHINGMETHOD_ID
  AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddescription,
 PRODUCTFINISHINGMETHOD.SYSTEMUSER_ID, PRODUCTFINISHINGMETHOD.TIMESTAMP, LANGUAGES.CODE
FROM PRODUCTFINISHINGMETHOD, PRODUCT, FINISHINGMETHOD, LANGUAGES
WHERE PRODUCTFINISHINGMETHOD.PRODUCT_ID = PRODUCT.PRODUCT_ID
 and PRODUCTFINISHINGMETHOD.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
/

  CREATE OR REPLACE VIEW "V_PRODUCTFINISHINGMETHODCH" ("PRODUCTCODE", "PRODUCTDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESC", "SPECIALCHARGECODE", "SPECIALCHARGEDESCRIPTION", "TIMESTAMP", "SYSTEMUSER_ID", "LANGUAGECODE") AS 
  select b.code productcode,
( select description from  product_desc y where y.product_id = a.product_id and y.language_id = languages.language_id) productdescription,
d.code finishingmethodcode,
( select description from  finishingmethod_desc x where x.finishingmethod_id = a.finishingmethod_id and x.language_id = languages.language_id) finishingmethoddesc,
c.code specialchargecode,
( select description from  specialcharge_desc z where z.specialcharge_id = a.specialcharge_id and z.language_id = languages.language_id) specialchargedescription,
a.timestamp, a.systemuser_id, languages.code languagecode
from productfinishingmethodcharge a, product b, specialcharge c, finishingmethod d, languages
where a.product_id = b.product_id
and a.specialcharge_id = c.specialcharge_id
and a.finishingmethod_id = d.finishingmethod_id
/

  CREATE OR REPLACE VIEW "V_PRODUCTGROUP" ("CODE", "DESCRIPTION", "ACTIVE", "ACTIVITYCODE", "ACTIVITYDESCRIPTION", "LEGACYPRODUCTGROUPCODE", "RENTTURNOVERGROUPCODE", "RENTTURNOVERGROUPDESCRIPTION", "WASHURNOVERGROUPCODE", "WASHTURNOVERGROUPDESCRIPTION", "REPLACEMENTTURNOVERGROUPCODE", "REPLACEMENTTURNOVERGROUPDESC", "SALESTURNOVERGROUPCODE", "SALESTURNOVERGROUPDESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP", "PRODUCTGROUP_ID", "LANGUAGECODE") AS 
  SELECT PRODUCTGROUP.CODE,
 (SELECT description FROM PRODUCTGROUP_DESC A WHERE A.PRODUCTGROUP_ID = PRODUCTGROUP.PRODUCTGROUP_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTGROUP_DESC,
 PRODUCTGROUP.ACTIVE, ACTIVITY.CODE,
 (SELECT description FROM ACTIVITY_DESC B WHERE B.ACTIVITY_ID = ACTIVITY.ACTIVITY_ID
  AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) ACTIVITY_DESC,
 PRODUCTGROUP.LEGACYPRODUCTGROUPCODE, rentturnovergroup.CODE rentturnovergroupcode,
 (SELECT description FROM turnovergroup_DESC C WHERE C.turnovergroup_id = PRODUCTGROUP.rentturnovergroup_id
  AND C.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) rentturnovergroupdescription,
 washturnovergroup.CODE washurnovergroupcode,
 (SELECT description FROM turnovergroup_DESC D WHERE D.turnovergroup_id = PRODUCTGROUP.washturnovergroup_id
  AND D.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) washturnovergroupdescription,
 replacementturnovergroup.CODE replacementturnovergroupcode,
 (SELECT description FROM turnovergroup_DESC E WHERE E.turnovergroup_id = PRODUCTGROUP.replacementturnovergroup_id
  AND E.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) replacementturnovergroupdesc,
 salesturnovergroup.CODE salesturnovergroupcode,
 (SELECT description FROM turnovergroup_DESC F WHERE F.turnovergroup_id = PRODUCTGROUP.salesturnovergroup_id
  AND F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) salesturnovergroupdescription,
 PRODUCTGROUP.SYSTEMUSER_ID, PRODUCTGROUP.TIMESTAMP, PRODUCTGROUP.PRODUCTGROUP_ID, LANGUAGES.CODE
FROM PRODUCTGROUP
 left outer join turnovergroup rentturnovergroup on(PRODUCTGROUP.rentturnovergroup_id = rentturnovergroup.turnovergroup_id)
 left outer join turnovergroup washturnovergroup on(PRODUCTGROUP.washturnovergroup_id = washturnovergroup.turnovergroup_id)
 left outer join turnovergroup replacementturnovergroup on(PRODUCTGROUP.replacementturnovergroup_id = replacementturnovergroup.turnovergroup_id)
 left outer join turnovergroup salesturnovergroup on(PRODUCTGROUP.salesturnovergroup_id = salesturnovergroup.turnovergroup_id),
 ACTIVITY, LANGUAGES
WHERE
 PRODUCTGROUP.ACTIVITY_ID = ACTIVITY.ACTIVITY_ID
/

  CREATE OR REPLACE VIEW "V_PRODUCTGROUPCHARGE" ("PRODUCTGROUPCODE", "PRODUCTGROUPDESCRIPTION", "SPECIALCHARGECODE", "SPECIALCHARGEDESCRIPTION", "TIMESTAMP", "SYSTEMUSER_ID", "LANGUAGECODE") AS 
  select b.code productgroupcode,
( SELECT description FROM PRODUCTGROUP_DESC X WHERE X.PRODUCTGROUP_ID = A.PRODUCTGROUP_ID AND X.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productgroupdescription,
c.code specialchargecode,
( SELECT DESCRIPTION FROM SPECIALCHARGE_DESC Y WHERE Y.SPECIALCHARGE_ID = A.SPECIALCHARGE_ID AND Y.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) specialchargedescription,
 a.timestamp, a.systemuser_id, LANGUAGES.CODE LANGUAGECODE
from productgroupcharge a, specialcharge c, productgroup b, LANGUAGES
where a.productgroup_id = b.productgroup_id
and a.specialcharge_id = c.specialcharge_id
/

  CREATE OR REPLACE VIEW "V_PRODUCTGROUPPERCUSTOMER" ("CUSTOMERNUMBER", "NAME", "CODE", "PRODUCTGROUP_DESC", "INVOICEGROUPINGCODE", "CUSTOMCODE", "CUSTOMDESCRITPION", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, PRODUCTGROUP.CODE,
(SELECT A.DESCRIPTION FROM PRODUCTGROUP_DESC A WHERE A.PRODUCTGROUP_ID = PRODUCTGROUPPERCUSTOMER.PRODUCTGROUP_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTGROUP_DESC,
 PRODUCTGROUPPERCUSTOMER.INVOICEGROUPINGCODE,
 PRODUCTGROUPPERCUSTOMER.CUSTOMCODE, PRODUCTGROUPPERCUSTOMER.CUSTOMDESCRITPION,
 PRODUCTGROUPPERCUSTOMER.SYSTEMUSER_ID, PRODUCTGROUPPERCUSTOMER.TIMESTAMP, LANGUAGES.CODE LANGUAGECODE
FROM PRODUCTGROUPPERCUSTOMER, CUSTOMER,  PRODUCTGROUP, LANGUAGES
WHERE PRODUCTGROUPPERCUSTOMER.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
and PRODUCTGROUPPERCUSTOMER.PRODUCTGROUP_ID = PRODUCTGROUP.PRODUCTGROUP_ID
/

  CREATE OR REPLACE VIEW "V_PRODUCTGROUPTAX" ("CODE", "PRODUCTGROUPDESC", "COUNTRYCODE", "COUNTRYDESCRIPTION", "TAXGROUPCODE", "TAXGROUPDESCRIPTION", "TIMESTAMP", "SYSTEMUSER_ID", "LANGUAGECODE") AS 
  select b.code,
(SELECT description FROM PRODUCTGROUP_DESC X WHERE X.PRODUCTGROUP_ID = A.PRODUCTGROUP_ID AND X.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTGROUPDESC,
 d.code countrycode, d.description countrydescription,
c.code taxgroupcode, c.description taxgroupdescription, a.timestamp, a.systemuser_id, LANGUAGES.CODE LANGUAGECODE
from productgrouptax a
LEFT OUTER JOIN taxgroup c ON (a.taxgroup_id = c.taxgroup_id),
 productgroup b, country d, LANGUAGES
where a.productgroup_id = b.productgroup_id
and a.country_id = d.country_id
/

  CREATE OR REPLACE VIEW "V_PRODUCTIONPLANNINGPOOL" ("REPORTPARAM_ID", "BUSINESSUNIT", "PRODUCTGROUPCODE", "PRODUCTGROUP_DESC", "PRODUCTCODE", "PRODUCT_DESC", "SIZE_DESC", "SOILRETURNS", "DELIVERIESLASTWEEK", "TODAYSREQUIREMENT", "INLAUNDRY", "INSTOCK") AS 
  select rp.reportparam_id,
       b.description businessunit,
       pg.code productgroupcode,
       (select pgd.description
          from productgroup_desc pgd
         where pgd.productgroup_id = p.productgroup_id and pgd.language_id=l.language_id) productgroup_desc,
       p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = x.product_link_id and pd.language_id=l.language_id) product_desc,
       (select sd.description
          from sizedefinition_desc sd
         where sd.sizedefinition_id = x.sizedefinition_link_id and sd.language_id=l.language_id) size_desc,
       x.soilreturns,
       x.deliverieslastweek,
       x.todaysrequirement,
       x.inlaundry,
       x.instock
  from
     (select y.businessunit_id,
             y.product_link_id,
             y.sizedefinition_link_id,
             sum(y.soilreturns) soilreturns,
             sum(y.deliverieslastweek) deliverieslastweek,
             sum(y.todaysrequirement) todaysrequirement,
             sum(y.inlaundry) inlaundry,
             sum(y.instock) instock
      from
      (
      -- part 1: soil returns same day last week
      select sc.businessunit_id,
             sc.product_link_id,
             sc.sizedefinition_link_id,
             count(*) soilreturns,
             0 deliverieslastweek,
             0 todaysrequirement,
             0 inlaundry,
             0 instock
        from scan sc,
             product p
       where sc.transactiontype_id = 1 -- inscan
         and trunc(sc.scantimestamp) = trunc(sysdate) - 7 -- same day last week
         and p.product_id = sc.product_link_id
         and p.uniquepoolitem = 'Y'
      group by sc.businessunit_id,
               sc.product_link_id,
               sc.sizedefinition_link_id
      -- part 2: deliveries same day last week
      union all
      select pn.processbusinessunit_id businessunit_id,
             pl.product_id,
             pl.sizedefinition_id,
             0 soilreturns,
             pl.deliveredamount deliverieslastweek,
             0 todaysrequirement,
             0 inlaundry,
             0 instock
        from packingnote pn,
             status s,
             packingnoteline pl,
             product p
       where pl.packingnote_id = pn.packingnote_id
         and pn.productiondate = trunc(sysdate) - 7 -- same day last week
         and p.product_id = pl.product_id
         and p.uniquepoolitem = 'Y'
         and s.status_id = pn.status_id
         and s.code = '30' -- processed
      -- part 3: today's requirement
      union all
      select pn.processbusinessunit_id businessunit_id,
             pl.product_id,
             pl.sizedefinition_id,
             0 soilreturns,
             0 deliverieslastweek,
             pl.tobedeliveredamount todaysrequirement,
             0 inlaundry,
             0 instock
        from packingnote pn,
             status s,
             packingnoteline pl,
             product p
       where pl.packingnote_id = pn.packingnote_id
         and pn.productiondate = trunc(sysdate)
         and p.product_id = pl.product_id
         and p.uniquepoolitem = 'Y'
         and s.status_id = pn.status_id
         and s.code not in ('30','40','60') -- not processed or cancelled or prepackingnote
      -- part 4: in laundry process
      union all
      select u.businessunit_id,
             u.product_id,
             u.sizedefinition_id,
             0 soilreturns,
             0 deliverieslastweek,
             0 todaysrequirement,
             count(*) inlaundry,
             0 instock
        from uniqueitem u,
             stay st,
             product p
       where st.stay_id = u.stay_id
         and st.staynr between 30 and 39  -- somewhere in laundry process
         and p.product_id = u.product_id
         and p.uniquepoolitem = 'Y'
      group by u.businessunit_id,
               u.product_id,
               u.sizedefinition_id
      -- part 5: in stock
      union all
      select u.businessunit_id,
             u.product_id,
             u.sizedefinition_id,
             0 soilreturns,
             0 deliverieslastweek,
             0 todaysrequirement,
             0 inlaundry,
             count(*) instock
        from uniqueitem u,
             stay st,
             product p
       where st.stay_id = u.stay_id
         and st.staynr = 10 -- in stock
         and p.product_id = u.product_id
         and p.uniquepoolitem = 'Y'
      group by u.businessunit_id,
               u.product_id,
               u.sizedefinition_id) y
      group by y.businessunit_id,
               y.product_link_id,
               y.sizedefinition_link_id
      having sum(y.todaysrequirement) > 0
      ) x,
      businessunit b,
      product p,
      productgroup pg,
      reportparam rp,
      languages l
where x.businessunit_id = rp.number_value
  and b.businessunit_id = x.businessunit_id
  and p.product_id = x.product_link_id
  and pg.productgroup_id = p.productgroup_id
  and pg.code >= rp.string_value1
  and pg.code <= rp.string_value2
  and p.code >= rp.string_value3
  and p.code <= rp.string_value4
  and l.code = rp.string_value
/

  CREATE OR REPLACE VIEW "V_PRODUCTIONPLANNINGPOOLITEMA" ("REPORTPARAM_ID", "BUSINESSUNIT_ID", "PRODUCT_ID", "SIZEDEFINITION_ID", "LESS_THAN_DAYS", "NR_OF_WEEKS", "BUSINESSUNIT", "PRODUCTCODE", "PRODUCT_DESC", "SIZE_DESC", "TODAYSREQUIREMENT", "INLAUNDRY", "INSTOCK") AS 
  select rp.reportparam_id,
       x.businessunit_id,
       x.product_id,
       x.sizedefinition_id,
       rp.number_value2 less_than_days,
       rp.number_value3 nr_of_weeks,
       b.description businessunit,
       p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = x.product_id and pd.language_id=l.language_id) product_desc,
       (select sd.description
          from sizedefinition_desc sd
         where sd.sizedefinition_id = x.sizedefinition_id and sd.language_id=l.language_id) size_desc,
       x.todaysrequirement,
       x.inlaundry,  -- active stock
       x.instock     -- passive stock
  from
     (select y.businessunit_id,
             y.product_id,
             y.sizedefinition_id,
             sum(y.todaysrequirement) todaysrequirement,
             sum(y.inlaundry) inlaundry,
             sum(y.instock) instock
      from
      (
      -- part 1: today's requirement
      select pn.processbusinessunit_id businessunit_id,
             pl.product_id,
             pl.sizedefinition_id,
             0 soilreturns,
             0 deliverieslastweek,
             pl.tobedeliveredamount todaysrequirement,
             0 inlaundry,
             0 instock
        from packingnote pn,
             status s,
             packingnoteline pl,
             product p
       where pl.packingnote_id = pn.packingnote_id
         and pn.productiondate = trunc(sysdate)
         and p.product_id = pl.product_id
         and p.uniquepoolitem = 'Y'
         and s.status_id = pn.status_id
         and s.code not in ('30','40','60') -- not processed or cancelled or prepackingnote
      -- part 2: in laundry process
      union all
      select /*+ index (u XIF8UNIQUEITEM) */
             u.businessunit_id,
             u.product_id,
             u.sizedefinition_id,
             0 soilreturns,
             0 deliverieslastweek,
             0 todaysrequirement,
             count(*) inlaundry,
             0 instock
        from uniqueitem u,
             stay st,
             product p
       where st.stay_id = u.stay_id
         and st.staynr between 30 and 39  -- somewhere in laundry process
         and p.product_id = u.product_id
         and p.uniquepoolitem = 'Y'
      group by u.businessunit_id,
               u.product_id,
               u.sizedefinition_id
      -- part 3: in stock
      union all
      select /*+ index (u XIF8UNIQUEITEM) */
             u.businessunit_id,
             u.product_id,
             u.sizedefinition_id,
             0 soilreturns,
             0 deliverieslastweek,
             0 todaysrequirement,
             0 inlaundry,
             count(*) instock
        from uniqueitem u,
             stay st,
             product p
       where st.stay_id = u.stay_id
         and st.staynr = 10 -- in stock
         and p.product_id = u.product_id
         and p.uniquepoolitem = 'Y'
      group by u.businessunit_id,
               u.product_id,
               u.sizedefinition_id) y
      group by y.businessunit_id,
               y.product_id,
               y.sizedefinition_id
      ) x,
      businessunit b,
      product p,
      sizedefinition s,
      reportparam rp,
      languages l
where x.businessunit_id = rp.number_value
  and x.product_id = rp.number_value1
  and s.code >= rp.string_value1
  and s.code <= rp.string_value2
  and b.businessunit_id = x.businessunit_id
  and p.product_id = x.product_id
  and s.sizedefinition_id = x.sizedefinition_id
  and l.code = rp.string_value
/

  CREATE OR REPLACE VIEW "V_PRODUCTIONPLANNINGPOOLITEMB" ("REPORTPARAM_ID", "BUSINESSUNIT_ID", "PRODUCT_ID", "SIZEDEFINITION_ID", "BUSINESSUNIT", "PRODUCTCODE", "PRODUCT_DESC", "SIZE_DESC", "CUSTOMERNUMBER", "NAME", "TODAYSREQUIREMENT", "DELIVERIESLASTWEEK", "SOILRETURNS", "ATCUSTOMER", "AVG_DAILY_SHIPMENTS", "USAGE_DAYS_ON_HAND") AS 
  select x.reportparam_id,
      x.businessunit_id,
      x.product_id,
      x.sizedefinition_id,
      b.description businessunit,
      p.code productcode,
      (select pd.description
         from product_desc pd
        where pd.product_id = x.product_id and pd.language_id=l.language_id) product_desc,
      (select sd.description
         from sizedefinition_desc sd
        where sd.sizedefinition_id = x.sizedefinition_id and sd.language_id=l.language_id) size_desc,
      c.customernumber,
      c.name,
      x.todaysrequirement,
      x.deliverieslastweek,
      x.soilreturns,
      x.atcustomer,
      round(x.totalshipped / (rp.date_value2 - rp.date_value1 + 1),1) avg_daily_shipments,
      case when round(x.totalshipped / (rp.date_value2 - rp.date_value1 + 1)) = 0
        then 0
        else x.atcustomer / round(x.totalshipped / (rp.date_value2 - rp.date_value1 + 1),1)
      end usage_days_on_hand
 from
    (select y.reportparam_id,
            y.businessunit_id,
            y.product_id,
            y.sizedefinition_id,
            y.customer_id,
            sum(soilreturns) soilreturns,
            sum(deliverieslastweek) deliverieslastweek,
            sum(y.todaysrequirement) todaysrequirement,
            sum(y.atcustomer) atcustomer,
            sum(y.totalshipped) totalshipped
     from
     (
     -- part 1: today's requirement
     select rp1.reportparam_id,
            pn.processbusinessunit_id businessunit_id,
            pl.product_id,
            pl.sizedefinition_id,
            d.customer_id,
            0 soilreturns,
            0 deliverieslastweek,
            pl.tobedeliveredamount todaysrequirement,
            0 atcustomer,
            0 totalshipped
       from packingnote pn,
            distributionpoint dp,
            department d,
            status s,
            packingnoteline pl,
            reportparam rp1
      where pl.packingnote_id = pn.packingnote_id
        and pn.productiondate = trunc(sysdate)
        and dp.distributionpoint_id = pn.distributionpoint_id
        and d.department_id = dp.department_id
        and s.status_id = pn.status_id
        and s.code not in ('30','40','60') -- not processed or cancelled or prepackingnote
     -- part 2: in deliveries same day last week
     union all
     select rp2.reportparam_id,
            pn.processbusinessunit_id businessunit_id,
            pl.product_id,
            pl.sizedefinition_id,
            d.customer_id,
            0 soilreturns,
            pl.deliveredamount deliverieslastweek,
            0 todaysrequirement,
            0 atcustomer,
            0 totalshipped
       from packingnote pn,
            distributionpoint dp,
            department d,
            status s,
            packingnoteline pl,
            reportparam rp2
      where pl.packingnote_id = pn.packingnote_id
        and pn.productiondate = trunc(sysdate) - 7 -- same day last week
        and dp.distributionpoint_id = pn.distributionpoint_id
        and d.department_id = dp.department_id
        and s.status_id = pn.status_id
        and s.code = '30' -- processed
     -- part 3: in soil returns same day last week
     union all
     select rp3.reportparam_id,
            sc.businessunit_id,
            sc.product_link_id,
            sc.sizedefinition_link_id,
            sc.customer_link_id customer_id,
            count(*) soilreturns,
            0 deliverieslastweek,
            0 todaysrequirement,
            0 atcustomer,
            0 totalshipped
       from scan sc,
            reportparam rp3
      where sc.transactiontype_id = 1 -- inscan
        and trunc(sc.scantimestamp) = trunc(sysdate) - 7 -- same day last week
     group by rp3.reportparam_id,
              sc.businessunit_id,
              sc.product_link_id,
              sc.sizedefinition_link_id,
              sc.customer_link_id
     -- part 4: at customer less than X days
     union all
     select /*+ index (uq XIF8UNIQUEITEM) */
            rp4.reportparam_id,
            rp4.number_value businessunit_id,
            uq.product_id,
            uq.sizedefinition_id,
            dp.customer_id,
            0 soilreturns,
            0 deliverieslastweek,
            0 todaysrequirement,
            count(*) atcustomer,
            0 totalshipped
       from uniqueitem        uq,
            department        dp,
            distributionpoint cp,
            reportparam       rp4
      where dp.department_id = cp.department_id
        and cp.distributionpoint_id = uq.distributionpoint_id
        and uq.poolitem = 1
        and uq.status_id in
            (select s1.status_id
               from status s1
              where s1.statustype = 'UI'
                and s1.code in ('20', '30'))
        and uq.stay_id in
            (select s2.stay_id
               from stay s2
              where s2.staytype = 1
                and s2.staynr between 20 and 27)
        and (trunc(sysdate) - trunc(uq.lastoutscandate)) <= rp4.number_value2
      group by rp4.reportparam_id,
               rp4.number_value,
               uq.product_id,
               uq.sizedefinition_id,
               dp.customer_id
     -- part 5: Avg daily shipments.
     union all
     select rp5.reportparam_id,
            dh.processbusinessunit_id businessunit_id,
            dh.product_link_id product_id,
            dh.sizedefinition_link_id sizedefinition_id,
            dh.customer_link_id customer_id,
            0 soilreturns,
            0 deliverieslastweek,
            0 todaysrequirement,
            0 atcustomer,
            sum(dh.amountdelivered) totalshipped
       from deliveryhistory dh,
            product p,
            reportparam rp5
      where p.product_id = dh.product_link_id
        and p.uniquepoolitem = 'Y'
        and dh.deliverydate >= rp5.date_value1
        and dh.deliverydate <= rp5.date_value2
   group by rp5.reportparam_id,
            dh.processbusinessunit_id,
            dh.product_link_id,
            dh.sizedefinition_link_id,
            dh.customer_link_id
              ) y
     group by y.reportparam_id,
              y.businessunit_id,
              y.product_id,
              y.sizedefinition_id,
              y.customer_id
     having sum(y.todaysrequirement) > 0
     ) x,
     businessunit b,
     customer c,
     product p,
     sizedefinition s,
     reportparam rp,
     languages l
where x.reportparam_id = rp.reportparam_id
 and x.businessunit_id = rp.number_value
 and p.product_id = rp.number_value1
 and s.code >= rp.string_value1
 and s.code <= rp.string_value2
 and b.businessunit_id = x.businessunit_id
 and x.product_id = p.product_id
 and s.sizedefinition_id = x.sizedefinition_id
 and c.customer_id = x.customer_id
 and l.code = rp.string_value
 and x.customer_id in (select dep.customer_id
                         from packingnote pn,
                              distributionpoint dp,
                              department dep,
                              status st,
                              packingnoteline pnl
                        where pnl.packingnote_id = pn.packingnote_id
                          and pn.productiondate = trunc(sysdate)
                          and pn.processbusinessunit_id = x.businessunit_id
                          and dp.distributionpoint_id = pn.distributionpoint_id
                          and dep.department_id = dp.department_id
                          and pnl.product_id = p.product_id
                          and st.status_id = pn.status_id
                          and pnl.tobedeliveredamount > 0
                          and st.code not in ('30','40','60'))
/

  CREATE OR REPLACE VIEW "V_PRODUCTLISTPERCUSTOMER" ("CUSTOMERNUMBER", "NAME", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "SIZEDEFINITION_DESC", "FINISHINGMETHODCODE", "FINISHINGMETHOD_DESC", "DATEACTIVE", "DATEINACTIVE", "CODEUNIQUELY", "SOILWEIGHT", "ONSITEINVENTORYCOUNT", "PERCENTAGEAFTERDEPRECIATION", "CLEANCOUNT", "BILLINGMETHOD", "SOILCOUNTMETHOD", "SRCMETHOD", "SRCPERCENTAGESOILCOUNT", "SRCPERCENTAGEINVENTORY", "SRCQUANTITY", "SRCFREQUENCY", "MINIMUMTURNAROUND", "MINIMUMQUANTITY", "QTYFREEOFCHARGE", "CHARGESTOCKROOMINVENTORY", "CUSTOMCODE", "CUSTOMDESCRIPTION", "CUSTOMBUNDLESIZE", "GAINREASONCODE", "GAINREASON_DESC", "GAINCOMPETITORCODE", "GAINCOMPETITORNAME", "LOSTREASONCODE", "LOSTREASON_DESC", "LOSTCOMPETITORCODE", "LOSTCOMPETITORNAME", "RESIDUALVALUESCHEMECODE", "RESIDUALVALUESCHEME_DESC", "DELAYEDEVENEXCHANGE", "REALQUANTITY", "CHARGEOVERUSE", "CHANGESPERWEEK", "DELIVERREPLACEMENTQTY", "MINIMUMFREQUENCY", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, PRODUCT.CODE productcode,
(SELECT description FROM PRODUCT_DESC A WHERE A.PRODUCT_ID = PRODUCTLISTPERCUSTOMER.PRODUCT_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
SIZEDEFINITION.CODE sizedefinitioncode,
(SELECT description FROM SIZEDEFINITION_DESC B WHERE B.SIZEDEFINITION_ID = PRODUCTLISTPERCUSTOMER.SIZEDEFINITION_ID
  AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEDEFINITION_DESC,
FINISHINGMETHOD.CODE finishingmethodcode,
(SELECT description FROM FINISHINGMETHOD_DESC C WHERE C.FINISHINGMETHOD_ID = PRODUCTLISTPERCUSTOMER.FINISHINGMETHOD_ID
  AND C.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHOD_DESC,
PRODUCTLISTPERCUSTOMER.DATEACTIVE, PRODUCTLISTPERCUSTOMER.DATEINACTIVE, PRODUCTLISTPERCUSTOMER.CODEUNIQUELY,
PRODUCTLISTPERCUSTOMER.SOILWEIGHT, PRODUCTLISTPERCUSTOMER.ONSITEINVENTORYCOUNT,
PRODUCTLISTPERCUSTOMER.PERCENTAGEAFTERDEPRECIATION, PRODUCTLISTPERCUSTOMER.CLEANCOUNT,
PRODUCTLISTPERCUSTOMER.BILLINGMETHOD,
PRODUCTLISTPERCUSTOMER.SOILCOUNTMETHOD, PRODUCTLISTPERCUSTOMER.SRCMETHOD,
PRODUCTLISTPERCUSTOMER.SRCPERCENTAGESOILCOUNT,
PRODUCTLISTPERCUSTOMER.SRCPERCENTAGEINVENTORY, PRODUCTLISTPERCUSTOMER.SRCQUANTITY,
PRODUCTLISTPERCUSTOMER.SRCFREQUENCY,
PRODUCTLISTPERCUSTOMER.MINIMUMTURNAROUND, PRODUCTLISTPERCUSTOMER.MINIMUMQUANTITY,
PRODUCTLISTPERCUSTOMER.QTYFREEOFCHARGE, PRODUCTLISTPERCUSTOMER.CHARGESTOCKROOMINVENTORY,
PRODUCTLISTPERCUSTOMER.CUSTOMCODE, PRODUCTLISTPERCUSTOMER.CUSTOMDESCRIPTION,
PRODUCTLISTPERCUSTOMER.CUSTOMBUNDLESIZE,
GAINREASON.CODE gainreasoncode,
(SELECT description FROM GAINLOSTREASON_DESC D WHERE D.GAINLOSTREASON_ID = PRODUCTLISTPERCUSTOMER.GAINREASON_ID
  AND D.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) GAINREASON_DESC,
GAINCOMPETITOR.CODE gaincompetitorcode, GAINCOMPETITOR.NAME gaincompetitorname,
LOSTREASON.CODE lostreasoncode,
(SELECT description FROM GAINLOSTREASON_DESC E WHERE E.GAINLOSTREASON_ID = PRODUCTLISTPERCUSTOMER.LOSTREASON_ID
  AND E.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) LOSTREASON_DESC,
LOSTCOMPETITOR.CODE lostcompetitorcode, LOSTCOMPETITOR.NAME lostcompetitorname,
RESIDUALVALUESCHEME.CODE residualvalueschemecode,
(SELECT description FROM RESIDUALVALUESCHEME_DESC F WHERE F.RESIDUALVALUESCHEME_ID = PRODUCTLISTPERCUSTOMER.RESIDUALVALUESCHEME_ID
  AND F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) RESIDUALVALUESCHEME_DESC,
PRODUCTLISTPERCUSTOMER.DELAYEDEVENEXCHANGE,
 case when PRODUCTLISTPERCUSTOMER.Inventorybillingtype = 1 then 'Y' else 'N' end REALQUANTITY , -- ! --
--PRODUCTLISTPERCUSTOMER.DELIVERMINIMUM,
 PRODUCTLISTPERCUSTOMER.CHARGEOVERUSE,
PRODUCTLISTPERCUSTOMER.CHANGESPERWEEK,
--PRODUCTLISTPERCUSTOMER.FIXEDQUANTITY,
PRODUCTLISTPERCUSTOMER.DELIVERREPLACEMENTQTY,
PRODUCTLISTPERCUSTOMER.MINIMUMFREQUENCY,
PRODUCTLISTPERCUSTOMER.SYSTEMUSER_ID, PRODUCTLISTPERCUSTOMER.TIMESTAMP, LANGUAGES.CODE languagecode
FROM PRODUCTLISTPERCUSTOMER
LEFT OUTER JOIN GAINLOSTREASON GAINREASON ON (PRODUCTLISTPERCUSTOMER.GAINREASON_ID = GAINREASON.GAINLOSTREASON_ID)
LEFT OUTER JOIN GAINLOSTREASON LOSTREASON ON(PRODUCTLISTPERCUSTOMER.LOSTREASON_ID = LOSTREASON.GAINLOSTREASON_ID)
LEFT OUTER JOIN COMPETITOR GAINCOMPETITOR ON(PRODUCTLISTPERCUSTOMER.GAINCOMPETITOR_ID = GAINCOMPETITOR.COMPETITOR_ID)
LEFT OUTER JOIN COMPETITOR LOSTCOMPETITOR ON(PRODUCTLISTPERCUSTOMER.LOSTCOMPETITOR_ID = LOSTCOMPETITOR.COMPETITOR_ID),
CUSTOMER, PRODUCT, SIZEDEFINITION, FINISHINGMETHOD, RESIDUALVALUESCHEME, LANGUAGES
WHERE PRODUCTLISTPERCUSTOMER.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
and PRODUCTLISTPERCUSTOMER.PRODUCT_ID  = PRODUCT.PRODUCT_ID
and PRODUCTLISTPERCUSTOMER.SIZEDEFINITION_ID  = SIZEDEFINITION.SIZEDEFINITION_ID
and PRODUCTLISTPERCUSTOMER.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
and PRODUCTLISTPERCUSTOMER.RESIDUALVALUESCHEME_ID = RESIDUALVALUESCHEME.RESIDUALVALUESCHEME_ID
/

  CREATE OR REPLACE VIEW "V_PRODUCTMODIFICATIONGROUP" ("MODIFICATIONGROUPCODE", "MODIFICATIONGROUPDESCRIPTION", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT  C.CODE MODIFICATIONGROUPCODE,
 (SELECT description FROM MODIFICATIONGROUP_DESC E WHERE E.MODIFICATIONGROUP_ID = A.MODIFICATIONGROUP_ID
  AND E.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) MODIFICATIONGROUPDESCRIPTION,
 B.CODE PRODUCTCODE,
 (SELECT description FROM PRODUCT_DESC F WHERE F.PRODUCT_ID = A.PRODUCT_ID
  AND F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
 A.SYSTEMUSER_ID, A.TIMESTAMP, LANGUAGES.CODE languagecode
FROM PRODUCTMODIFICATIONGROUP A, PRODUCT B, MODIFICATIONGROUP C, LANGUAGES
WHERE A.PRODUCT_ID = B.PRODUCT_ID
 AND A.MODIFICATIONGROUP_ID = C.MODIFICATIONGROUP_ID
/

  CREATE OR REPLACE VIEW "V_PRODUCTREVENUE" ("DELTOCUSTOMER_LINK_ID", "BILLTOCUSTOMER_LINK_ID", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "DELTOCITY", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "MASTERACCOUNTNUMBER", "MASTERACCOUNTNAME", "MASTERACCOUNT_ID", "INVOICEDATE", "INVOICELINETYPE", "INVOICELINETYPEDESC", "TURNOVERGROUPCODE", "TURNOVERGROUPDESC", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "SIZEDESC", "FINISHINGMETHODCODE", "FINISHINGMETHODDESC", "THEORETICALWEIGHT", "BILLEDAMOUNT", "BILLEDQTY", "DELIVEREDQTY", "SETTLEMENTACTIVE", "WEIGHTUNIT", "PRICEDECIMALS", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE", "SALESAREA_ID", "SALESAREA_CODE", "SALESAREA_DESC") AS 
  select ih.deltocustomer_link_id, ih.billtocustomer_link_id,
  coalesce(ih.deltocustomernumber, -1) deltocustomernumber, ih.deltocustomername, ih.deltocity
, ih.billtocustomernumber, ih.billtocustomername
, coalesce(macc.customernumber, -1) masteraccountnumber, macc.name masteraccountname
, coalesce(macc.customer_id, -1) masteraccount_id
, ih.invoicedate invoicedate
, ilt.type invoicelinetype
, (select invoicelinetype_desc.description from invoicelinetype_desc
  where invoicelinetype_desc.invoicelinetype_id = ilt.invoicelinetype_id
  and invoicelinetype_desc.language_id = languages.language_id) invoicelinetypedesc
, tg.code turnovergroupcode
, (select description from turnovergroup_desc where turnovergroup_desc.turnovergroup_id = tg.turnovergroup_id
  and turnovergroup_desc.language_id = languages.language_id) turnovergroupdesc
, prd.code productcode
, (select description from product_desc where product_desc.product_id = prd.product_id
    and product_desc.language_id = languages.language_id) productdesc
, sz.code sizecode
, (select szd.description from sizedefinition_desc szd where szd.sizedefinition_id = sz.sizedefinition_id
    and szd.language_id = languages.language_id) sizedesc
, fm.code finishingmethodcode
, (select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
    and fmd.language_id = languages.language_id) finishingmethoddesc
, max(prdsz.theoreticalweight) theoreticalweight
, sum(case when il.adjustmentreason_id is null
      then il.amount
      else il.adjustedamount
      end) billedamount
, sum(case when il.adjustmentreason_id is null
      then il.billedqty
      else il.billedqty+il.adjustmentbilledqty
      end) billedqty
, sum(case when il.adjustmentreason_id is null
      then ilp.deliveredqty
      else ilp.deliveredqty+ilp.adjustmentdeliveredqty
      end) deliveredqty
, (select ss.value from systemsetting ss where ss.plant_id = plant.plant_id and ss.name = 'SETTLEMENTACTIVE') settlementactive
, (select sy.value from systemsetting sy where sy.plant_id = plant.plant_id and sy.name = 'WEIGHTUNIT') weightunit
, cur.decimals pricedecimals, cur.invoiceamountdecimals
, languages.code languagecode
, sa.salesarea_id, sa.code salesarea_code
, (select sad.description from salesarea_desc sad where sa.salesarea_id=sad.salesarea_id and sad.language_id=languages.language_id) salesarea_desc
from
  invoiceheader ih
    left join customer cu
                             join customer macc on cu.masteraccount_id = macc.customer_id
                             join salesarea sa on cu.salesarea_id = sa.salesarea_id
       on ih.deltocustomer_link_id = cu.customer_id
    join status on ih.status_id = status.status_id
    join currency cur on ih.currency_id=cur.currency_id
    join businessunit inbu on ih.invoicebusinessunit_id = inbu.businessunit_id
    join plant on inbu.plant_id = plant.plant_id
    join invoiceline il on ih.invoiceheader_id = il.invoiceheader_id
    join invoicelinetype ilt on il.invoicelinetype_id = ilt.invoicelinetype_id
    join turnovergroup tg on il.turnovergroup_id=tg.turnovergroup_id
    join (invoicelineproduct ilp
                            left join productsize prdsz on ilp.product_link_id = prdsz.product_id
                                                           and ilp.sizedefinition_link_id = prdsz.sizedefinition_id
                            join product prd on ilp.product_link_id = prd.product_id
                            left join sizedefinition sz on ilp.sizedefinition_link_id = sz.sizedefinition_id
                            left join finishingmethod fm on ilp.finishingmethod_id = fm.finishingmethod_id)
         on il.invoiceline_id = ilp.invoiceline_id
, languages
where status.statustype = 'IN'
      and status.code = 2
      and il.extend='Y'
group by ih.deltocustomer_link_id, ih.billtocustomer_link_id,
  ih.deltocustomernumber, ih.deltocustomername, ih.deltocity
, ih.billtocustomernumber, ih.billtocustomername
, macc.customernumber, macc.name, macc.customer_id
, ih.invoicedate, ilt.type, ilt.invoicelinetype_id, tg.code, tg.turnovergroup_id
, prd.code, prd.product_id, sz.code, sz.sizedefinition_id, fm.code, fm.finishingmethod_id, languages.language_id, languages.code
, cur.decimals, cur.invoiceamountdecimals
, sa.salesarea_id, sa.code, plant.plant_id
having
  sum(case when il.adjustmentreason_id is null
      then il.billedqty
      else il.billedqty+il.adjustmentbilledqty
      end) <> 0 or
  sum(case when il.adjustmentreason_id is null
      then il.amount
      else il.adjustedamount
      end) <> 0
/

  CREATE OR REPLACE VIEW "V_PRODUCTSIZE" ("PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZECODE", "SIZEDESCRIPTION", "SEQUENCENUMBER", "SPECIALSIZE", "PACKINGAMOUNT", "THEORETICALWEIGHT", "SYSTEMUSER_ID", "TIMESTAMP", "CODE") AS 
  SELECT PRODUCT.CODE productcode,
 (SELECT description FROM PRODUCT_DESC A WHERE A.PRODUCT_ID = PRODUCTSIZE.PRODUCT_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
 SIZEDEFINITION.CODE sizecode,
 (SELECT description FROM SIZEDEFINITION_DESC B WHERE B.SIZEDEFINITION_ID = PRODUCTSIZE.SIZEDEFINITION_ID
  AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) sizedescription,
 PRODUCTSIZE.SEQUENCENUMBER, PRODUCTSIZE.SPECIALSIZE, PRODUCTSIZE.PACKINGAMOUNT,
 PRODUCTSIZE.THEORETICALWEIGHT, PRODUCTSIZE.SYSTEMUSER_ID, PRODUCTSIZE.TIMESTAMP, LANGUAGES.CODE
FROM PRODUCTSIZE, PRODUCT, SIZEDEFINITION, LANGUAGES
WHERE PRODUCTSIZE.PRODUCT_ID = PRODUCT.PRODUCT_ID
 and PRODUCTSIZE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
/

  CREATE OR REPLACE VIEW "V_PRODUCTSPERBUSINESSUNIT" ("BUSINESSUNIT_ID", "PRODUCT_ID") AS 
  select c.businessunit_id, a.product_id
	from product a, productgroup b, businessunitactivities c
	where a.productgroup_id = b.productgroup_id
		and b.activity_id = c.activity_id
/

  CREATE OR REPLACE VIEW "V_PRODUCTSTATISTIC" ("PLANTCODE", "PLANTNAME", "BUSINESSUNITCODE", "BUSINESSUNITDESC", "INVOICEDATE", "ROUTENUMBER", "ROUTEDESC", "INVOICELINETYPE", "INVOICELINETYPEDESC", "TURNOVERGROUPCODE", "PRODUCTCODE", "PRODUCTDESC", "TURNOVERGROUPDESC", "SIZECODE", "SIZEDESCRIPTION", "THEORETICALWEIGHT", "BILLEDAMOUNT", "BILLEDQTY", "DELIVEREDQTY", "SETTLEMENTACTIVE", "WEIGHTUNIT", "LANGUAGECODE", "PRODUCTSIZE_WEIGHT", "PRODUCTGROUP_CODE") AS 
  SELECT h.code plantcode, h.name plantname, i.code businessunitcode, i.description businessunitdesc,
  a.invoicedate, g.routenumber, g.description routedesc, c.type invoicelinetype
, ( select invoicelinetype_desc.description from invoicelinetype_desc where invoicelinetype_desc.invoicelinetype_id = c.invoicelinetype_id
  and invoicelinetype_desc.language_id = LANGUAGES.Language_Id ) invoicelinetypedesc
, f.code turnovergroupcode,
  m.code productcode,
  (SELECT description FROM product_DESC k WHERE k.product_id = m.product_id
    AND k.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
  (SELECT description FROM turnovergroup_DESC j WHERE j.turnovergroup_id =f.turnovergroup_id
    AND j.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) turnovergroupDESC
 , d.sizecode, d.sizedescription,
  MAX(m.theoreticalweight) theoreticalweight--, SUM(b.amount) billedamount,  SUM(b.billedqty) billedqty, SUM(d.deliveredqty + d.adjustmentdeliveredqty) deliveredqty
, case
         when b.adjustmentreason_id is null then
          sum(b.amount)
         else
          sum(b.adjustedamount)
       end billedamount
, case
         when b.adjustmentreason_id is null then
          sum(b.billedqty)
         else
          sum(b.adjustmentbilledqty + b.billedqty)
       end billedqty
, case
         when b.adjustmentreason_id is null then
           sum(d.deliveredqty)
         else
           sum(d.deliveredqty + d.adjustmentdeliveredqty)
       end deliveredqty
, ss.value SETTLEMENTACTIVE, sy.value WEIGHTUNIT, LANGUAGES.Code LANGUAGECode
, (select max(ps.theoreticalweight) from productsize ps where ps.product_id=m.product_id and ps.sizedefinition_id=d.sizedefinition_link_id) ProductSize_Weight
, (select pg.code from Productgroup pg where pg.productgroup_id=m.productgroup_id) Productgroup_code
FROM invoiceheader a
    left outer join route g on (a.route_id=g.route_id),
  invoiceline b, turnovergroup f, invoicelineproduct d, product m,
  invoicelinetype c, plant h, businessunit i, status n
, businessunit inBu, plant, systemsetting ss, systemsetting sy, LANGUAGES
WHERE a.invoiceheader_id = b.invoiceheader_id
  and b.invoicelinetype_id = c.invoicelinetype_id
  and b.turnovergroup_id=f.turnovergroup_id
  and b.invoiceline_id = d.invoiceline_id
  and m.product_id = d.product_link_id
  and a.invoicebusinessunit_id = i.businessunit_id
  and i.plant_id = h.plant_id
  and a.status_id = n.status_id
  and n.statustype = 'IN'
  and n.code = 2
  and b.extend = 'Y' --SSB for todo 8254
and a.invoicebusinessunit_id = inBu.Businessunit_Id
    and inBu.Plant_Id = plant.plant_id
        and plant.plant_id = ss.plant_id
            and ss.name = 'SETTLEMENTACTIVE'
        and plant.plant_id = sy.plant_id
            and sy.name = 'WEIGHTUNIT'
GROUP BY h.code, h.name, i.code, i.description, a.invoicedate, g.routenumber, g.description, c.type
, c.invoicelinetype_id, f.code, f.turnovergroup_id, m.code, m.product_id, m.productgroup_id, d.sizecode, d.sizedescription, d.sizedefinition_link_id
, ss.value, sy.value,LANGUAGES.LANGUAGE_ID,  LANGUAGES.Code
, b.adjustmentreason_id--having SUM(b.amount) <> 0 or SUM(b.billedqty) <> 0
/

  CREATE OR REPLACE VIEW "V_PRODUCTSUPPLIERS" ("PRODUCTLAUNDRYCODE", "SIZELAUNDRYCODE", "PRODUCTLAUNDRYDESC", "SUPPLIERNUMBER", "SUPPLIERNAME", "SUPPLIERPRODUCTCODE", "SUPPLIERSIZECODE", "SUPPLIERPRODUCTDESC", "PURCHASEPRICE", "DELIVERYDAYS", "MINORDERQTY", "BOXQUANTITY", "PREFERREDSUPPLIER", "PRODUCTGROUPCODE", "LANGUAGECODE") AS 
  select -- count(*)
  prd.code productLaundryCode
, ( case sz.code when '*' then ' ' else sz.code end ) sizeLaundryCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productLaundryDesc
, supplier.supplierNumber, supplier.name supplierName
, spp.supplierproductcode, spp.suppliersizecode, spp.supplierproductdescription supplierproductDesc
, ( select spprice.purchaseprice from supplierproductprice spprice
           where spprice.supplierproduct_id = spp.supplierproduct_id
                 and spprice.startdate = ( select max(supplierproductprice.startdate) from supplierproductprice
                                                  where supplierproductprice.supplierproduct_id = spprice.supplierproduct_id
                                                        and supplierproductprice.startdate <= sysdate)) purchaseprice
, spp.deliverydays, spp.minorderqty, spp.boxquantity
, ( case prd.supplier_id
       when spp.supplier_id then 'Y'
            else
                'N'
                   end
                      ) preferredSupplier
, productgroup.code productgroupCode, languages.code languageCode
from
  productsize psz
          left outer join
           ( productsizepersupproduct pszspp
                 join    ( supplierproduct spp join supplier
                                            on spp.supplier_id = supplier.supplier_id )
                          on pszspp.supplierproduct_id = spp.supplierproduct_id )
               on pszspp.product_id = psz.product_id
                  and pszspp.sizedefinition_id = psz.sizedefinition_id
, product prd , sizedefinition sz, productgroup, languages
where
    prd.product_id = psz.product_id
and psz.sizedefinition_id = sz.sizedefinition_id
and prd.productgroup_id = productgroup.productgroup_id
/

  CREATE OR REPLACE VIEW "V_PRODUCTTAX" ("PRODUCTCODE", "PRODUCTDESCRIPTION", "COUNTRYCODE", "COUNTRYDESCRIPTION", "TAXGROUPCODE", "TAXGROUPDESCRIPTION", "TIMESTAMP", "SYSTEMUSER_ID", "LANGUAGECODE") AS 
  select b.code productcode,
(select description from product_desc x where x.product_id = a.product_id and x.language_id = languages.language_id) productdescription,
c.code countrycode, c.description countrydescription,
d.code taxgroupcode, d.description taxgroupdescription,
a.timestamp, a.systemuser_id, languages.code languagecode
from producttax a
left outer join taxgroup d on (a.taxgroup_id = d.taxgroup_id), product b, country c, languages
where a.product_id = b.product_id
and a.country_id =c.country_id
/

  CREATE OR REPLACE VIEW "V_PROFITABILITYDASHBOARD_SC" ("CUSTOMER_ID", "SPECIALCHARGECODE", "FIXEDAMOUNT", "OLDAMOUNT", "OLDPERCENTAGE", "STARTDATE", "NEWAMOUNT", "NEWPERCENTAGE", "OVERRULED", "NEWSPECIFICAMOUNT", "OLDSPECIFICAMOUNT", "NEWSPECIFICPERCENTAGE", "OLDSPECIFICPERCENTAGE") AS 
  SELECT csc.customer_id, sc.code SpecialChargeCode--used in report CustomerDetailsWithYield !!
       , sc.fixedamount, sc.oldamount, sc.oldpercentage, sc.startdate
			 , case sc.fixedamount when 'Y' then pack_price.SpecialCharge_Price(csc.customer_id, sc.specialcharge_id, sysdate) else 0 end newamount
			 , case sc.fixedamount when 'N' then pack_price.SpecialCharge_Percentage(csc.customer_id, sc.specialcharge_id, sysdate) else 0 end newpercentage
			 , 'N' overruled, 0 newspecificamount, 0 oldspecificamount
			 , 0 newspecificpercentage, 0 oldspecificpercentage
FROM customerspecialcharge csc, specialcharge sc
WHERE csc.specialcharge_id = sc.specialcharge_id
/

  CREATE OR REPLACE VIEW "V_PROGRESS" ("LINETYPE", "DATEINACTIVE", "CUSTOMERNUMBER", "CUSTOMERNAME", "STREET", "CITY", "COUNTY", "REASONCODE", "REASONGROUP", "WEARERNUMBER", "PRODUCTCODE", "PRODUCTDESCRIPTION", "PRODUCTGROUPCODE", "TYPEOFMERCHANDISE", "SIZECODE", "CHANGEDATE", "CONTRACT", "SAMPLEITEM", "ISSUED", "BUSINESSTYPE", "LANGUAGECODE", "REASONCODEDESC", "RENTPRICE", "SERVICEEMPLOYEENAME", "SERVICEEMPLOYEENUMBER", "BUCODE", "PLANTCODE") AS 
  select 1 linetype, c.dateinactive,
       c.customernumber CustomerNumber,
       c.name CustomerName,
       a.street Street,
       a.city City,
       a.county County,
       case when c.dateinactive < sysdate
         then case when (select max(glr.code) from CONTRACTSPERCUSTOMER cpc, gainlostreason glr
                        where cpc.customer_id = c.customer_id and cpc.lostreason_id = glr.gainlostreason_id) = '6'
                   then 'RN- CH'
            else 'CAN CH' end
         else rc.code end Reasoncode,
       rc.reasongroup ReasonGroup,
       0 WearerNumber,
       prd.code ProductCode,
       (select description
          from product_desc
         where l.language_id = product_desc.language_id
           and product_desc.product_id = prd.product_id) ProductDescription,
       (select pg.code
          from Productgroup pg
         where prd.productgroup_id = pg.productgroup_id) ProductgroupCode,
       prd.typeofmerchandise TypeofMerchandise,
       s.code SizeCode,
       case when c.dateinactive < sysdate then c.dateinactive
         else rqa.adjustmentdate end ChangeDate,
       rqa.quantity Contract,
       rqa.sampleitem SampleItem,
       rqa.quantity Issued,
       (select max(plpc.billingmethod)
          from productlistpercustomer plpc
         where plpc.product_id = plpd.product_id
           and (plpc.sizedefinition_id = plpd.sizedefinition_id or
               plpc.sizedefinition_id =
               (select szd.sizedefinition_id
                   from sizedefinition szd
                  where szd.code = '*'))
           and plpc.finishingmethod_id = plpd.finishingmethod_id
           and plpc.customer_id = c.customer_id
           and plpc.dateactive <= rqa.adjustmentdate
           and plpc.dateinactive >= rqa.adjustmentdate) BusinessType,
       l.code LanguageCode,
       (select rcd.description
          from reasoncode_desc rcd
         where rc.reasoncode_id = rcd.reasoncode_id
           and l.language_id = rcd.language_id) ReasonCodeDesc,
       pack_price.Rent_Price(c.customer_id,
                             prd.product_id,
                             s.sizedefinition_id,
                             fm.FINISHINGMETHOD_ID,
                             case when c.dateinactive < sysdate then c.dateinactive
                             else rqa.adjustmentdate end) RentPrice,
       (select em.name
          from employee em
         where c.serviceemployee_id = em.employee_id) serviceemployeename,       --cast(
         (select em.employeenumber
          from employee em
         where c.serviceemployee_id = em.employee_id) --as varchar(8))
         serviceemployeenumber,
       (select bu.code
          from businessunit bu
         where c.defaultbusinessunit_id = bu.businessunit_id) BuCode,
        (select p.code from plant p, businessunit b
        where p.plant_id=b.plant_id and b.businessunit_id=c.defaultbusinessunit_id) PlantCode
  from customer                   c,
       address                    a,
       reasoncode                 rc,
       product                    prd,
       sizedefinition             s,
       finishingmethod            fm,
       productlistperdistribpoint plpd,
       distributionpoint          dp,
       department                 d,
       rentalqtyadjustment        rqa,
       languages                  l
 where c.visitaddress_id = a.address_id
   and plpd.distributionpoint_id = dp.distributionpoint_id
   and dp.department_id = d.department_id
   and d.customer_id = c.customer_id
   and rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
   and plpd.product_id = prd.product_id
   and plpd.sizedefinition_id = s.sizedefinition_id
   and plpd.finishingmethod_id = fm.finishingmethod_id
   and rc.reasoncode_id = rqa.reasoncode_id
   and (c.dateinactive < sysdate or rc.code not in ('-',
                       'ABUSE',
                       'ACC.CA',
                       'ACCSUP',
                       'BM1',
                       'BROKEN',
                       'CLOSED',
                       'CLR',
                       'CLR EX',
                       'CONVER',
                       'COR',
                       'CSRING',
                       'CS_N',
                       'DELNRQ',
                       'FAIR',
                       'FLOAT',
                       'FREE',
                       'INCR',
                       'LABERR',
                       'LOAN',
                       'LOSTCU',
                       'LOSTSG',
                       'LOT',
                       'NOSTVA',
                       'PACK',
                       'POOL',
                       'SAMPLE',
                       'SIZ EX',
                       'SO_U',
                       'STYCH',
                       'VIS'))
   and prd.typeofmerchandise = 1
   and rqa.sampleitem = 'N'
   and rqa.quantity <> 0
union all
select 2 linetype, c.dateinactive,
       c.customernumber CustomerNumber,
       c.name CustomerName,
       a.street Street,
       a.city City,
       a.county County,
       rc.code Reasoncode,
       rc.reasongroup ReasonGroup,
       w.wearernumber WearerNumber,
       prd.code ProductCode,
       (select description
          from product_desc
         where l.language_id = product_desc.language_id
           and product_desc.product_id = prd.product_id) ProductDescription,
       (select pg.code
          from Productgroup pg
         where prd.productgroup_id = pg.productgroup_id) ProductgroupCode,
       prd.typeofmerchandise TypeofMerchandise,
       s.code SizeCode,
       trunc(ih.incircdate) ChangeDate,
       1 Contract,
       null SampleItem,
       nvl(count(distinct(ih.uniqueitem_link_id)),0)
           Issued,
       plpc.billingmethod BusinessType,
       l.code LanguageCode,
       (select rcd.description
          from reasoncode_desc rcd
         where rc.reasoncode_id = rcd.reasoncode_id
           and l.language_id = rcd.language_id) ReasonCodeDesc,
       pack_price.Rent_Price(c.customer_id,
                             prd.product_id,
                             s.sizedefinition_id,
                             fm.FINISHINGMETHOD_ID,
                             trunc(ih.incircdate),
                             case plpc.billingmethod
                               when 1 then
                                WI.CHANGESPERWEEK
                               else
                                null
                             end) RentPrice,
       (select em.name
          from employee em
         where c.serviceemployee_id = em.employee_id) serviceemployeename,       --cast(
         (select em.employeenumber
          from employee em
         where c.serviceemployee_id = em.employee_id) --as varchar(8))
         serviceemployeenumber,
       (select bu.code
          from businessunit bu
         where c.defaultbusinessunit_id = bu.businessunit_id) BuCode,
       (select p.code from plant p, businessunit b
        where p.plant_id=b.plant_id and b.businessunit_id=c.defaultbusinessunit_id) PlantCode
  from customer               c,
       address                a,
       wearer                 w,
       weareremployment       wemp,
       wearerinventory        wi,
       product                prd,
       sizedefinition         s,
       issuehistory           ih,
       reasoncode             rc,
       productlistpercustomer plpc,
       languages              l,
       finishingmethod        fm
 where ih.processbusinessunit_id = c.defaultbusinessunit_id
   and ih.weareremployment_link_id = wi.weareremployment_id
   and (ih.product_link_id = wi.product_id or
       ih.substituteforproduct_id = wi.product_id)
   and (ih.sizedefinition_link_id = wi.sizedefinition_id or
       ih.substituteforsizedefinition_id = wi.sizedefinition_id)
   and wi.weareremployment_id = wemp.weareremployment_id
   and wemp.wearer_id = w.wearer_id
   and w.customer_id = c.customer_id
   and c.visitaddress_id = a.address_id
   and wi.product_id = prd.product_id
   and wi.sizedefinition_id = s.sizedefinition_id
   and wi.finishingmethod_id = fm.finishingmethod_id
   and plpc.customer_id = c.customer_id
   and plpc.product_id = wi.product_id
   and (plpc.sizedefinition_id = wi.sizedefinition_id or
       plpc.sizedefinition_id =
       (select szd.sizedefinition_id
           from sizedefinition szd
          where szd.code = '*'))
   and plpc.finishingmethod_id = wi.finishingmethod_id
   and ih.reasoncode_id = rc.reasoncode_id
   and rc.code not in ('-',
                       'ABUSE',
                       'ACC.CA',
                       'ACCSUP',
                       'BM1',
                       'BROKEN',
                       'CLOSED',
                       'CLR',
                       'CLR EX',
                       'CONVER',
                       'COR',
                       'CSRING',
                       'CS_N',
                       'DELNRQ',
                       'FAIR',
                       'FLOAT',
                       'FREE',
                       'INCR',
                       'LABERR',
                       'LOAN',
                       'LOSTCU',
                       'LOSTSG',
                       'LOT',
                       'NOSTVA',
                       'PACK',
                       'POOL',
                       'SAMPLE',
                       'SIZ EX',
                       'SO_U',
                       'STYCH',
                       'VIS')
   and prd.typeofmerchandise = 2
   and plpc.billingmethod in (1, 3)
   and ih.quantity <> 0
group by c.dateinactive, c.customernumber, c.name, a.street ,
       a.city , a.county, rc.code, rc.reasongroup, w.wearernumber,
       prd.code, l.language_id, prd.product_id, prd.productgroup_id,  prd.typeofmerchandise,
       s.code, trunc(ih.incircdate), plpc.billingmethod, l.code, rc.reasoncode_id, c.customer_id,
       s.sizedefinition_id, fm.FINISHINGMETHOD_ID,
       case plpc.billingmethod when 1 then WI.CHANGESPERWEEK else null end,
       c.serviceemployee_id, c.defaultbusinessunit_id
union all
select 3 linetype, c.dateinactive,
       c.customernumber CustomerNumber,
       c.name CustomerName,
       a.street Street,
       a.city City,
       a.county County,
       rc.code Reasoncode,
       rc.reasongroup ReasonGroup,
       w.wearernumber WearerNumber,
       prd.code ProductCode,
       (select description
          from product_desc
         where l.language_id = product_desc.language_id
           and product_desc.product_id = prd.product_id) ProductDescription,
       (select pg.code
          from Productgroup pg
         where prd.productgroup_id = pg.productgroup_id) ProductgroupCode,
       prd.typeofmerchandise TypeofMerchandise,
       s.code SizeCode,
       trunc(oh.outofcircdate) ChangeDate,
       1 Contract,
       null SampleItem,
      nvl(sum(oh.quantity),0) Issued,
       plpc.billingmethod BusinessType,
       l.code LanguageCode,
       (select rcd.description
          from reasoncode_desc rcd
         where rc.reasoncode_id = rcd.reasoncode_id
           and l.language_id = rcd.language_id) ReasonCodeDesc,
       pack_price.Rent_Price(c.customer_id,
                             prd.product_id,
                             s.sizedefinition_id,
                             fm.FINISHINGMETHOD_ID,
                             trunc(oh.outofcircdate),
                             case plpc.billingmethod
                               when 1 then
                                WI.CHANGESPERWEEK
                               else
                                null
                             end) RentPrice,
       (select em.name
          from employee em
         where c.serviceemployee_id = em.employee_id) serviceemployeename,       --cast(
         (select em.employeenumber
          from employee em
         where c.serviceemployee_id = em.employee_id) --as varchar(8))
         serviceemployeenumber,
       (select bu.code
          from businessunit bu
         where c.defaultbusinessunit_id = bu.businessunit_id) BuCode,
       (select p.code from plant p, businessunit b
        where p.plant_id=b.plant_id and b.businessunit_id=c.defaultbusinessunit_id) PlantCode
  from customer                c,
       address                 a,
       wearer                  w,
       weareremployment        wemp,
       wearerinventory         wi,
       product                 prd,
       sizedefinition          s,
       outofcirculationhistory oh,
       reasoncode              rc,
       productlistpercustomer  plpc,
       languages               l,
       finishingmethod         fm
 where oh.processbusinessunit_id = c.defaultbusinessunit_id
   and oh.weareremployment_link_id = wi.weareremployment_id
   and oh.product_link_id = wi.product_id
   and oh.sizedefinition_link_id = wi.sizedefinition_id
   and wi.weareremployment_id = wemp.weareremployment_id
   and wemp.wearer_id = w.wearer_id
   and w.customer_id = c.customer_id
   and c.visitaddress_id = a.address_id
   and wi.product_id = prd.product_id
   and wi.sizedefinition_id = s.sizedefinition_id
   and wi.finishingmethod_id = fm.finishingmethod_id
   and plpc.customer_id = c.customer_id
   and plpc.product_id = wi.product_id
   and (plpc.sizedefinition_id = wi.sizedefinition_id or
       plpc.sizedefinition_id =
       (select szd.sizedefinition_id
           from sizedefinition szd
          where szd.code = '*'))
   and plpc.finishingmethod_id = wi.finishingmethod_id
   and oh.reasoncode_id = rc.reasoncode_id
   and rc.code not in ('-',
                       'ABUSE',
                       'ACC.CA',
                       'ACCSUP',
                       'BM1',
                       'BROKEN',
                       'CLOSED',
                       'CLR',
                       'CLR EX',
                       'CONVER',
                       'COR',
                       'CSRING',
                       'CS_N',
                       'DELNRQ',
                       'FAIR',
                       'FLOAT',
                       'FREE',
                       'INCR',
                       'LABERR',
                       'LOAN',
                       'LOSTCU',
                       'LOSTSG',
                       'LOT',
                       'NOSTVA',
                       'PACK',
                       'POOL',
                       'SAMPLE',
                       'SIZ EX',
                       'SO_U',
                       'STYCH',
                       'VIS')
   and prd.typeofmerchandise = 2
   and plpc.billingmethod in (1, 3)
   and oh.quantity <> 0
group by c.dateinactive, c.customernumber, c.name, a.street,
       a.city, a.county, rc.code, rc.reasongroup, w.wearernumber,
       prd.code,l.language_id, prd.product_id,prd.productgroup_id, prd.typeofmerchandise,
       s.code, trunc(oh.outofcircdate), plpc.billingmethod, l.code,rc.reasoncode_id, c.customer_id,
       s.sizedefinition_id, fm.FINISHINGMETHOD_ID, --oh.outofcircdate,
       case plpc.billingmethod when 1 then WI.CHANGESPERWEEK else null end,
       c.serviceemployee_id, c.defaultbusinessunit_id
union all --next there will be the price changes via CustomerRentPrice
select 1 linetype, c.dateinactive,
       c.customernumber CustomerNumber,
       c.name CustomerName,
       a.street Street,
       a.city City,
       a.county County,
       case when NewP.Price >= OldP.Price then 'PR INC'
          when NewP.Price < OldP.Price then 'PR DEC'
         else rc.code end Reasoncode,
       rc.reasongroup ReasonGroup,
       0 WearerNumber,
       prd.code ProductCode,
       (select description
          from product_desc
         where l.language_id = product_desc.language_id
           and product_desc.product_id = prd.product_id) ProductDescription,
       (select pg.code
          from Productgroup pg
         where prd.productgroup_id = pg.productgroup_id) ProductgroupCode,
       prd.typeofmerchandise TypeofMerchandise,
       s.code SizeCode,
      Newp.Startdate ChangeDate,
       rqa.quantity Contract,
       rqa.sampleitem SampleItem,
       rqa.quantity Issued,
       plpc.billingmethod BusinessType,
       l.code LanguageCode,
       (select rcd.description
          from reasoncode_desc rcd
         where rc.reasoncode_id = rcd.reasoncode_id
           and l.language_id = rcd.language_id) ReasonCodeDesc,
       (NewP.Price-OldP.Price) RentPrice,
       (select em.name
          from employee em
         where c.serviceemployee_id = em.employee_id) serviceemployeename,       --cast(
         (select em.employeenumber
          from employee em
         where c.serviceemployee_id = em.employee_id) --as varchar(8))
         serviceemployeenumber,
       (select bu.code
          from businessunit bu
         where c.defaultbusinessunit_id = bu.businessunit_id) BuCode,
       (select p.code from plant p, businessunit b
        where p.plant_id=b.plant_id and b.businessunit_id=c.defaultbusinessunit_id) PlantCode
  from customer                   c,
       address                    a,
       reasoncode                 rc,
       product                    prd,
       sizedefinition             s,
       finishingmethod            fm,
       productlistperdistribpoint plpd,
       distributionpoint          dp,
       department                 d,
       rentalqtyadjustment        rqa,
       languages                  l,
       productlistpercustomer     plpc,
       customerrentprice          NewP,
       customerrentprice          OldP
 where c.visitaddress_id = a.address_id
   and plpd.distributionpoint_id = dp.distributionpoint_id
   and dp.department_id = d.department_id
   and d.customer_id = c.customer_id
   and rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
   and plpd.product_id = prd.product_id
   and plpd.sizedefinition_id = s.sizedefinition_id
   and plpd.finishingmethod_id = fm.finishingmethod_id
   and rc.reasoncode_id = rqa.reasoncode_id
   and prd.typeofmerchandise = 1
   and rqa.sampleitem = 'N'
   and plpc.customer_id = c.customer_id
   and plpc.product_id = prd.product_id
   and (plpc.sizedefinition_id = s.sizedefinition_id or
       plpc.sizedefinition_id =
       (select szd.sizedefinition_id
           from sizedefinition szd
          where szd.code = '*'))
   and plpc.finishingmethod_id = fm.finishingmethod_id
   and Newp.Productlistpercustomer_ID = plpc.productlistpercustomer_id
   and OldP.Productlistpercustomer_Id = plpc.productlistpercustomer_id
   and Newp.Startdate in (select max(crp.startdate) from customerrentprice crp where crp.productlistpercustomer_id = plpc.productlistpercustomer_id
                         and crp.startdate <= sysdate)
   and OldP.Startdate in (select max(crp2.startdate) from customerrentprice crp2 where crp2.productlistpercustomer_id = plpc.productlistpercustomer_id
                         and crp2.startdate < Newp.Startdate)
   and c.dateinactive >= sysdate
   and ((plpc.priceusage = 1 and Newp.Typeofrent = 7) or (plpc.priceusage <> 1 and Newp.Typeofrent <> 7)) -- split price
union all
select 2 linetype, c.dateinactive,
       c.customernumber CustomerNumber,
       c.name CustomerName,
       a.street Street,
       a.city City,
       a.county County,
       case when NewP.Price >= OldP.Price then 'PR INC'
          when NewP.Price < OldP.Price then 'PR DEC'
       else ' ' end Reasoncode,
       ' ' ReasonGroup,
       w.wearernumber WearerNumber,
       prd.code ProductCode,
       (select description
          from product_desc
         where l.language_id = product_desc.language_id
           and product_desc.product_id = prd.product_id) ProductDescription,
       (select pg.code
          from Productgroup pg
         where prd.productgroup_id = pg.productgroup_id) ProductgroupCode,
       prd.typeofmerchandise TypeofMerchandise,
       s.code SizeCode,
       Newp.Startdate ChangeDate,
       0 Contract,
       null SampleItem,
     nvl((select sum(wi1.changesperweek)
             from wearerinventory wi1
            where wi1.product_id = plpc.product_id
            and (wi1.sizedefinition_id = plpc.sizedefinition_id
            or plpc.sizedefinition_id =
       (select szd.sizedefinition_id
           from sizedefinition szd
          where szd.code = '*'))
            and wi1.finishingmethod_id = plpc.finishingmethod_id
            and plpc.changesperweek = 'Y'
            and wi1.wearerinventory_id= wi.wearerinventory_id
           ),
           0)
           Issued,
       plpc.billingmethod BusinessType,
       l.code LanguageCode,
        case when NewP.Price >= OldP.Price then 'Price Increase'
          when NewP.Price < OldP.Price then 'Price Decrease'
       else ' ' end ReasonCodeDesc,
       (NewP.Price-OldP.Price) RentPrice,
       (select em.name
          from employee em
         where c.serviceemployee_id = em.employee_id) serviceemployeename,         --cast(
         (select em.employeenumber
          from employee em
         where c.serviceemployee_id = em.employee_id) --as varchar(8))
         serviceemployeenumber,
       (select bu.code
          from businessunit bu
         where c.defaultbusinessunit_id = bu.businessunit_id) BuCode,
       (select p.code from plant p, businessunit b
        where p.plant_id=b.plant_id and b.businessunit_id=c.defaultbusinessunit_id) PlantCode
  from customer               c,
       address                a,
       wearer                 w,
       weareremployment       wemp,
       wearerinventory        wi,
       product                prd,
       sizedefinition         s,
       productlistpercustomer plpc,
       languages              l,
       finishingmethod        fm,
       customerrentprice      NewP,
       customerrentprice      OldP
 where
    wi.weareremployment_id = wemp.weareremployment_id
   and wemp.wearer_id = w.wearer_id
   and w.customer_id = c.customer_id
   and c.visitaddress_id = a.address_id
   and wi.product_id = prd.product_id
   and wi.sizedefinition_id = s.sizedefinition_id
   and wi.finishingmethod_id = fm.finishingmethod_id
   and plpc.customer_id = c.customer_id
   and plpc.product_id = wi.product_id
   and (plpc.sizedefinition_id = wi.sizedefinition_id or
       plpc.sizedefinition_id =
       (select szd.sizedefinition_id
           from sizedefinition szd
          where szd.code = '*'))
   and plpc.finishingmethod_id = wi.finishingmethod_id
   and prd.typeofmerchandise = 2
   and plpc.billingmethod = 1
   and plpc.changesperweek = 'Y'
   and NewP.Changesperweek = wi.changesperweek
   and OldP.Changesperweek =  wi.changesperweek
   and Newp.Productlistpercustomer_ID = plpc.productlistpercustomer_id
   and OldP.Productlistpercustomer_Id = plpc.productlistpercustomer_id
   and Newp.Startdate in (select max(crp.startdate) from customerrentprice crp where crp.productlistpercustomer_id = plpc.productlistpercustomer_id
                         and crp.startdate <= sysdate)
   and OldP.Startdate in (select max(crp2.startdate) from customerrentprice crp2 where crp2.productlistpercustomer_id = plpc.productlistpercustomer_id
                         and crp2.startdate < Newp.Startdate)
   and wi.dateinactive >= sysdate
union all
select 3 linetype, c.dateinactive,
       c.customernumber CustomerNumber,
       c.name CustomerName,
       a.street Street,
       a.city City,
       a.county County,
       case when NewP.Price >= OldP.Price then 'PR INC'
          when NewP.Price < OldP.Price then 'PR DEC'
       else ' ' end Reasoncode,
       ' ' ReasonGroup,
       w.wearernumber WearerNumber,
       prd.code ProductCode,
       (select description
          from product_desc
         where l.language_id = product_desc.language_id
           and product_desc.product_id = prd.product_id) ProductDescription,
       (select pg.code
          from Productgroup pg
         where prd.productgroup_id = pg.productgroup_id) ProductgroupCode,
       prd.typeofmerchandise TypeofMerchandise,
       s.code SizeCode,
       Newp.Startdate ChangeDate,
       1 Contract,
       null SampleItem,
       nvl((select sum(wi2.circinventory)
                   from wearerinventory wi2
            where wi2.product_id = plpc.product_id
            and (wi2.sizedefinition_id = plpc.sizedefinition_id
            or plpc.sizedefinition_id =
       (select szd.sizedefinition_id
           from sizedefinition szd
          where szd.code = '*'))
            and wi2.finishingmethod_id = plpc.finishingmethod_id
            and wi2.wearerinventory_id= wi.wearerinventory_id
           ),
           0)
           Issued,
       plpc.billingmethod BusinessType,
       l.code LanguageCode,
       case when NewP.Price >= OldP.Price then 'Price Increase'
          when NewP.Price < OldP.Price then 'Price Decrease'
       else ' ' end ReasonCodeDesc,
       (NewP.Price-OldP.Price) RentPrice,
       (select em.name
          from employee em
         where c.serviceemployee_id = em.employee_id) serviceemployeename,         --cast(
         (select em.employeenumber
          from employee em
         where c.serviceemployee_id = em.employee_id) --as varchar(8))
         serviceemployeenumber,
       (select bu.code
          from businessunit bu
         where c.defaultbusinessunit_id = bu.businessunit_id) BuCode,
       (select p.code from plant p, businessunit b
        where p.plant_id=b.plant_id and b.businessunit_id=c.defaultbusinessunit_id) PlantCode
  from customer                c,
       address                 a,
       wearer                  w,
       weareremployment        wemp,
       wearerinventory         wi,
       product                 prd,
       sizedefinition          s,
       productlistpercustomer  plpc,
       languages               l,
       finishingmethod         fm,
       customerrentprice       NewP,
       customerrentprice       OldP
 where
    wi.weareremployment_id = wemp.weareremployment_id
   and wemp.wearer_id = w.wearer_id
   and w.customer_id = c.customer_id
   and c.visitaddress_id = a.address_id
   and wi.product_id = prd.product_id
   and wi.sizedefinition_id = s.sizedefinition_id
   and wi.finishingmethod_id = fm.finishingmethod_id
   and plpc.customer_id = c.customer_id
   and plpc.product_id = wi.product_id
   and (plpc.sizedefinition_id = wi.sizedefinition_id or
       plpc.sizedefinition_id =
       (select szd.sizedefinition_id
           from sizedefinition szd
          where szd.code = '*'))
   and plpc.finishingmethod_id = wi.finishingmethod_id
   and prd.typeofmerchandise = 2
   and plpc.billingmethod= 3
   and Newp.Productlistpercustomer_ID = plpc.productlistpercustomer_id
   and OldP.Productlistpercustomer_Id = plpc.productlistpercustomer_id
   and Newp.Startdate in (select max(crp.startdate) from customerrentprice crp where crp.productlistpercustomer_id = plpc.productlistpercustomer_id
                         and crp.startdate <= sysdate)
   and OldP.Startdate in (select max(crp2.startdate) from customerrentprice crp2 where crp2.productlistpercustomer_id = plpc.productlistpercustomer_id
                         and crp2.startdate < Newp.Startdate)
   and wi.dateinactive >= sysdate
union all -- General Price list price changes
select 3 linetype, c.dateinactive,
       c.customernumber CustomerNumber,
       c.name CustomerName,
       a.street Street,
       a.city City,
       a.county County,
       case when NewP.Price >= OldP.Price then 'PR INC'
          when NewP.Price < OldP.Price then 'PR DEC'
       else ' ' end Reasoncode,
       ' ' ReasonGroup,
       0 WearerNumber,
       prd.code ProductCode,
       (select description
          from product_desc
         where l.language_id = product_desc.language_id
           and product_desc.product_id = prd.product_id) ProductDescription,
       (select pg.code
          from Productgroup pg
         where prd.productgroup_id = pg.productgroup_id) ProductgroupCode,
       prd.typeofmerchandise TypeofMerchandise,
       s.code SizeCode,
       Newp.Startdate ChangeDate,
       1 Contract,
       null SampleItem,
       nvl(
           (select sum(rqa.quantity) from rentalqtyadjustment rqa, productlistperdistribpoint plpd, distributionpoint dp, department de
           where rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id and
                 plpd.distributionpoint_id = dp.distributionpoint_id and dp.department_id = de.department_id
                 and de.customer_id = c.customer_id and plpd.product_id = prd.product_id
                 and plpd.sizedefinition_id = s.sizedefinition_id and plpd.finishingmethod_id = newp.finishingmethod_id),
           1)
           Issued,
       NewP.Typeofrent BusinessType,
       l.code LanguageCode,
       case when NewP.Price >= OldP.Price then 'Price Increase'
          when NewP.Price < OldP.Price then 'Price Decrease'
       else ' ' end ReasonCodeDesc,
       (NewP.Price-OldP.Price) RentPrice,
       (select em.name
          from employee em
         where c.serviceemployee_id = em.employee_id) serviceemployeename,         --cast(
         (select em.employeenumber
          from employee em
         where c.serviceemployee_id = em.employee_id) --as varchar(8))
         serviceemployeenumber,
       (select bu.code
          from businessunit bu
         where c.defaultbusinessunit_id = bu.businessunit_id) BuCode,
       (select p.code from plant p, businessunit b
        where p.plant_id=b.plant_id and b.businessunit_id=c.defaultbusinessunit_id) PlantCode
  from customer                c,
       address                 a,
       product                 prd,
       sizedefinition          s,
       generalpricelist        gpl,
       pricelistpercustomer    plpc,
       languages               l,
       finishingmethod         fm,
       generalrentprice        NewP,
       generalrentprice        OldP, productlistpercustomer prdpc
 where  c.visitaddress_id = a.address_id
   and plpc.customer_id = c.customer_id
   and plpc.generalpricelist_id = gpl.generalpricelist_id
   and NewP.generalpricelist_id = gpl.generalpricelist_id
   and OldP.generalpricelist_id = gpl.generalpricelist_id
   and NewP.product_id = prd.product_id
   and (NewP.sizedefinition_id = s.sizedefinition_id )
   and NewP.finishingmethod_id = fm.finishingmethod_id
   and NewP.product_id = OldP.product_id
   and NewP.sizedefinition_id = OldP.sizedefinition_id
   and NewP.finishingmethod_id = OldP.finishingmethod_id
   and prdpc.customer_id = c.customer_id
   and prdpc.product_id = prd.product_id
   and (prdpc.sizedefinition_id = s.sizedefinition_id or prdpc.sizedefinition_id =
       (select szd.sizedefinition_id
           from sizedefinition szd
          where szd.code = '*'))
   and prdpc.finishingmethod_id = fm.finishingmethod_id
   and Newp.Startdate in (select max(grp.startdate) from generalrentprice grp where grp.generalpricelist_id = gpl.generalpricelist_id
                         and grp.product_id = NewP.product_id
                         and grp.sizedefinition_id = NewP.sizedefinition_id
                         and grp.finishingmethod_id = NewP.finishingmethod_id
                         and grp.startdate <= sysdate)
   and OldP.Startdate in (select max(grp2.startdate) from generalrentprice grp2 where grp2.generalpricelist_id = gpl.generalpricelist_id
                         and grp2.product_id = OldP.product_id
                         and grp2.sizedefinition_id = OldP.sizedefinition_id
                         and grp2.finishingmethod_id = OldP.finishingmethod_id
                         and grp2.startdate < Newp.Startdate)
/

  CREATE OR REPLACE VIEW "V_PURCHASEAMOUNTPERPROD" ("BUSINESSUNITCODE", "STOCKCODE", "SUPPLIERNUMBER", "SUPPLIERNAME", "BUYERCODE", "YEAR", "MONTH", "YEARMONTH", "PRODUCTGROUPCODE", "PRODUCTGROUPDESC", "PRODUCTCODE", "TYPEOFMERCHANDISE", "PRODUCTDESC", "QUANTITYRECEIVED", "AMOUNT", "CURRENCYCODE", "LANGUAGECODE") AS 
  select
  bu.code businessUnitCode
, max(( select sk.code from stockroom sk where sk.managedbybu_id = bu.businessunit_id
  and ph.stockroom_id = sk.stockroom_id )) stockCode
, spp.suppliernumber, max(spp.name) supplierName,
max((select sksp.buyercode
from stockroomsupplier sksp
where ph.stockroom_id = sksp.stockroom_id and ph.supplier_id = sksp.supplier_id)) buyercode
, year(ph.firstreceivingdate) year
, month(ph.firstreceivingdate) month
, (year(ph.firstreceivingdate)*100 + month(ph.firstreceivingdate)) YearMonth
, prdgr.code productGroupCode
, max(( select pgd.description from productgroup_desc pgd where prdgr.productgroup_id = pgd.productgroup_id
  and pgd.language_id = languages.language_id )) productgroupDesc
, prd.code productCode, prd.typeofmerchandise
, max(( select product_desc.description from product_desc where prd.product_id = product_desc.product_id
  and product_desc.language_id = languages.language_id )) productDesc
, sum(phli.quantityreceived) quantityreceived
, sum(phli.quantityreceived * phli.purchaseprice) Amount
, currency.code currencyCode
, languages.code languageCode
from  purchaseorderheader ph
, purchaseorderline phli
, product prd
join productgroup prdgr on prd.productgroup_id = prdgr.productgroup_id
, businessunit bu, supplier spp
, currency, languages
where ph.purchaseorderheader_id = phli.purchaseorderheader_id
and phli.quantityreceived <> 0
and phli.product_link_id  = prd.product_id
and ph.businessunit_id = bu.businessunit_id
and ph.supplier_id = spp.supplier_id
and ph.currency_id = currency.currency_id
group by
  bu.code,bu.businessunit_id
, ph.stockroom_id
, spp.suppliernumber
, ph.firstreceivingdate
, prdgr.code
, prdgr.productgroup_id
, languages.language_id
, prd.code
, prd.typeofmerchandise
, prd.product_id
, currency.code
, languages.code
/

  CREATE OR REPLACE VIEW "V_PURCHASEAMOUNTPERPRODSUPP" ("USERGROUP_ID", "BUSSINESSUNITCODE", "ORDERDATE", "SUPPLIERNUMBER", "SUPPLIERNAME", "STOCKROOMCODE", "PRODUCTGROUPCODE", "PRODUCTCODE", "PRODUCTDESC", "TYPEOFMERCHANDISE", "SIZECODE", "PIECES", "AMOUNT", "LANGUAGECODE") AS 
  select bug.usergroup_id, bu.code bussinessunitcode, poh.orderdate,
  sp.suppliernumber, sp.name suppliername, sr.code stockroomcode,
  pg.code productgroupcode,
  pr.code productcode,
  (select prd.description from product_desc prd where prd.product_id = pr.product_id
    and prd.language_id = languages.language_id) productdesc,
  pr.typeofmerchandise,
  sz.code sizecode,
  (pol.quantityordered - pol.quantitycancelled) pieces,
  (pol.quantityordered - pol.quantitycancelled)*pol.purchaseprice amount,
  languages.code languagecode
from purchaseorderheader poh
    left outer join stockroom sr on sr.stockroom_id = poh.stockroom_id,
  status st, purchaseorderline pol,
  businessunitsperusergroup bug, businessunit bu, supplier sp, product pr, sizedefinition sz,
  productgroup pg,
  languages
where poh.purchaseorderheader_id = pol.purchaseorderheader_id
  and poh.status_id = st.status_id
  and st.code <> '05' and st.code <> '40'
  and bug.businessunit_id = bu.businessunit_id
  and bu.businessunit_id = poh.businessunit_id
  and poh.supplier_id = sp.supplier_id
  and pol.product_link_id = pr.product_id
  and pr.productgroup_id = pg.productgroup_id
/

  CREATE OR REPLACE VIEW "V_PURCHASEAMOUNTPERPRODSUPPOR" ("USERGROUP_ID", "BUSSINESSUNITCODE", "ORDERDATE", "SUPPLIERNUMBER", "SUPPLIERNAME", "STOCKROOMCODE", "PRODUCTGROUPCODE", "PRODUCTCODE", "PRODUCTDESC", "TYPEOFMERCHANDISE", "SIZECODE", "PIECES", "AMOUNT", "PRICEDECIMALS", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE") AS 
  select bug.usergroup_id, bu.code bussinessunitcode, poh.orderdate,
  sp.suppliernumber, sp.name suppliername, sr.code stockroomcode,
  pg.code productgroupcode,
  pr.code productcode,
  (select prd.description from product_desc prd where prd.product_id = pr.product_id
    and prd.language_id = languages.language_id) productdesc,
  pr.typeofmerchandise,
  sz.code sizecode,
  (pol.quantityordered - pol.quantitycancelled) pieces,
  (pol.quantityordered - pol.quantitycancelled)*pol.purchaseprice amount,
  cr.decimals pricedecimals, cr.invoiceamountdecimals,
  languages.code languagecode
from purchaseorderheader poh
    left outer join stockroom sr on sr.stockroom_id = poh.stockroom_id,
  status st, purchaseorderline pol,
  businessunitsperusergroup bug, businessunit bu, supplier sp, product pr, sizedefinition sz,
  productgroup pg, currency cr,
  languages
where poh.purchaseorderheader_id = pol.purchaseorderheader_id
  and poh.status_id = st.status_id
  and st.code <> '05' and st.code <> '50'
  and bug.businessunit_id = bu.businessunit_id
  and bu.businessunit_id = poh.businessunit_id
  and poh.supplier_id = sp.supplier_id
  and pol.product_link_id = pr.product_id
  and pol.sizedefinition_link_id = sz.sizedefinition_id
  and pr.productgroup_id = pg.productgroup_id
  and sp.currency_id = cr.currency_id
/

  CREATE OR REPLACE VIEW "V_PURCHASEAMOUNTPERPRODSUPPREC" ("USERGROUP_ID", "BUSSINESSUNITCODE", "TRANSACTIONDATE", "SUPPLIERNUMBER", "SUPPLIERNAME", "STOCKROOMCODE", "PRODUCTGROUPCODE", "PRODUCTCODE", "PRODUCTDESC", "TYPEOFMERCHANDISE", "SIZECODE", "PIECES", "AMOUNT", "PRICEDECIMALS", "INVOICEAMOUNTDECIMALS", "REASONCODE", "REASONDESC", "LANGUAGECODE") AS 
  select bug.usergroup_id, bu.code bussinessunitcode, stt.transactiondate, --poh.orderdate,
  sp.suppliernumber, sp.name suppliername, sr.code stockroomcode,
  pg.code productgroupcode,
  pr.code productcode,
  (select prd.description from product_desc prd where prd.product_id = pr.product_id
    and prd.language_id = languages.language_id) productdesc,
  pr.typeofmerchandise,
  sz.code sizecode,
  pot.quantity pieces,
  pot.quantity*pol.purchaseprice amount,
  cr.decimals pricedecimals, cr.invoiceamountdecimals,
  rc.code reasoncode,
  (select rcd.description from reasoncode_desc rcd where rc.reasoncode_id = rcd.reasoncode_id
    and rcd.language_id = languages.language_id) reasondesc,
  languages.code languagecode
from purchaseorderheader poh
    left outer join stockroom sr on sr.stockroom_id = poh.stockroom_id,
  purchaseorderline pol, purchaseorderstocktransaction pot, --status st,
  stocktransaction stt, stockreservationpergrade srpg, stockdefinitionperitem sdpi,
  reasoncode rc,
  businessunitsperusergroup bug, businessunit bu, supplier sp, product pr, sizedefinition sz,
  productgroup pg, currency cr,
  languages
where poh.purchaseorderheader_id = pol.purchaseorderheader_id
  and pol.purchaseorderline_id = pot.purchaseorderline_id
  and pot.stocktransaction_id = stt.stocktransaction_id
  and stt.stockreservationpergrade_id = srpg.stockreservationpergrade_id
  and srpg.stockdefinitionperitem_id = sdpi.stockdefinitionperitem_id
  and stt.reasoncode_id = rc.reasoncode_id
--  and poh.status_id = st.status_id
--  and st.code <> '05' and st.code <> '40'
  and bug.businessunit_id = bu.businessunit_id
  and bu.businessunit_id = poh.businessunit_id
  and poh.supplier_id = sp.supplier_id
  and sdpi.product_id = pr.product_id
  and sdpi.sizedefinition_id = sz.sizedefinition_id
  and pr.productgroup_id = pg.productgroup_id
  and sp.currency_id = cr.currency_id
/

  CREATE OR REPLACE VIEW "V_PURCHASEORDEREMBL" ("PURCHASEORDERHEADER_ID", "PURCHASEORDERLINE_ID", "CUSTOMERNUMBER", "NAME", "WORKORDERLINE_ID", "WEARERNUMBER", "FULLNAME", "EMBLEMNAME", "QTYREQUESTED") AS 
  select poh.purchaseorderheader_id, pol.purchaseorderline_id,c.customernumber, c.name,
wol.workorderline_id, we.wearernumber, we.fullname, we.emblemname, wole.qtyrequested
from purchaseorderline pol, purchaseorderheader poh,workorderlineemblem wole
        left outer join workorderlineemblempoline wolpole
          on wole.workorderlineemblem_id=wolpole.workorderlineemblem_id,
           workorderline wol , workorder wo, weareremployment wempl, wearer we, customer c
       where   pol.purchaseorderheader_id=poh.purchaseorderheader_id
         and nvl(wole.purchaseorderline_id ,wolpole.purchaseorderline_id)=pol.purchaseorderline_id
         and wole.workorderline_id=wol.workorderline_id
         and wol.workorder_id=wo.workorder_id
         and wo.weareremployment_link_id=wempl.weareremployment_id
         and wempl.wearer_id=we.wearer_id
         and we.customer_id=c.customer_id
/

  CREATE OR REPLACE VIEW "V_PURCHASEORDERLATECONFIRM" ("STOCKCODE", "STOCKNAME", "SUPPLIERNUMBER", "SUPPLIERNAME", "ORDERDATE", "STREET", "ZIPCODE", "CITY", "FAX", "PURCHASEORDERNUMBER", "PRODUCTCODE", "SIZECODE", "PRODUCTDESC", "DATEORDERED", "CONFIRMEDDATE", "QUANTITYORDERED", "QUANTITYRECEIVED", "EXPECTEDDATE", "DAYSDUE", "CUSTOMERNUMBER", "BUSINESSUNIT_ID", "OWNEDCUSTOMERNUMBER", "LANGUAGECODE") AS 
  select distinct
  sk.code stockCode, sk.name stockName, sp.suppliernumber, sp.name supplierName, ph.orderdate
, AddressSp.Street, AddressSp.Zipcode, AddressSp.City, sp.fax
, ph.purchaseordernumber, prd.code productCode, sz.code sizeCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( case ph.exportdate when GETABSMAXDATE() then ph.approvaldate
                     else ph.exportdate end ) DateOrdered, pl.confirmeddate
, ( select sum( purchaseorderline.quantityordered - purchaseorderline.quantitycancelled ) from purchaseorderline
  where pl.purchaseorderheader_id = purchaseorderline.purchaseorderheader_id
        and pl.product_link_id = purchaseorderline.product_link_id and pl.sizedefinition_link_id = purchaseorderline.sizedefinition_link_id
  group by purchaseorderline.purchaseorderheader_id
  ) quantityordered
, ( select sum(purchaseorderline.quantityreceived) from purchaseorderline
    where pl.purchaseorderheader_id = purchaseorderline.purchaseorderheader_id
        and pl.product_link_id = purchaseorderline.product_link_id and pl.sizedefinition_link_id = purchaseorderline.sizedefinition_link_id
  group by purchaseorderline.purchaseorderheader_id
  ) quantityreceived
, (( case ph.exportdate when GETABSMAXDATE() then  ph.approvaldate
                       else ph.exportdate end ) + spprd.deliverydays) ExpectedDate
, (( case pl.confirmeddate when GETABSMAXDATE() then trunc(sysdate)
                          else pl.confirmeddate end )  -
  (( case ph.exportdate when GETABSMAXDATE() then  ph.approvaldate
                                            else ph.exportdate end ) + spprd.deliverydays)) DaysDue
, culk.customernumber, sbu.businessunit_id
, CulkOwn.Customernumber OwnedCustomerNumber
, languages.code LanguageCode
from
  purchaseorderheader ph
    left outer join customer_link CulkOwn on ph.customer_link_id = CulkOwn.Customer_Link_Id
, supplier sp, stockroom sk, productsizepersupproduct pszspp, supplierproduct spprd, status
, purchaseorderline pl
    left outer join (workorderline wokli -- multiply lines : select distionct
                       join (workorder wok
                            join customer_link culk on culk.customer_link_id = wok.customer_link_id
                            )
                            on wok.workorder_id = wokli.workorder_id
          )
         on (wokli.purchaseorderline_id = pl.purchaseorderline_id
         or pl.purchaseorderline_id in (select wolpol.purchaseorderline_id from workorderlinepurchordline wolpol where wolpol.workorderline_id=wokli.workorderline_id))
            and wokli.product_link_id = pl.product_link_id
                and wokli.sizedefinition_link_id = pl.sizedefinition_link_id
, product prd, sizedefinition sz
, stockroomsservicingbu sbu
, address AddressSp, languages
where
    ph.status_id = status.status_id
  and status.code in ('10', '20', '25', '30')
and pl.quantityreceived < pl.quantityordered - pl.quantitycancelled
and ph.supplier_id = sp.supplier_id
    and sp.address_id = AddressSp.Address_Id
and ph.stockroom_id = sk.stockroom_id
    and sk.stockroom_id = sbu.stockroom_id
and ph.purchaseorderheader_id = pl.purchaseorderheader_id
    and pl.product_link_id = prd.product_id
    and pl.sizedefinition_link_id = sz.sizedefinition_id
        and pszspp.product_id = prd.product_id
        and pszspp.sizedefinition_id = sz.sizedefinition_id
            and pszspp.supplierproduct_id = spprd.supplierproduct_id
                and spprd.supplier_id = sp.supplier_id
/

  CREATE OR REPLACE VIEW "V_PURCHASEORDERLATEDELIVERY" ("STOCKCODE", "STOCKNAME", "SUPPLIERNUMBER", "SUPPLIERNAME", "ORDERDATE", "STREET", "ZIPCODE", "CITY", "FAX", "PURCHASEORDERNUMBER", "PRODUCTCODE", "SIZECODE", "PRODUCTDESC", "DATEORDERED", "CONFIRMEDDATE", "QUANTITYORDERED", "QUANTITYRECEIVED", "DAYSDUE", "WORKORDERNUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "WEARERNAME", "BUSINESSUNIT_ID", "OWNEDCUSTOMERNUMBER", "LANGUAGECODE", "EXPORTDATE", "APPROVALDATE", "DELIVERYDAYS") AS 
  select -- distinct
  sk.code stockCode, sk.name stockName, sp.suppliernumber, sp.name supplierName, ph.orderdate
, AddressSp.Street, AddressSp.Zipcode, AddressSp.City, sp.fax
, ph.purchaseordernumber, prd.code productCode, sz.code sizeCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( case ph.exportdate when GETABSMAXDATE() then ph.approvaldate
                       else ph.exportdate end ) DateOrdered, pl.confirmeddate
, ( select sum( purchaseorderline.quantityordered - purchaseorderline.quantitycancelled ) from purchaseorderline
  where pl.purchaseorderheader_id = purchaseorderline.purchaseorderheader_id
        and pl.product_link_id = purchaseorderline.product_link_id and pl.sizedefinition_link_id =
purchaseorderline.sizedefinition_link_id
  group by purchaseorderline.purchaseorderheader_id
  ) quantityordered
, ( select sum(purchaseorderline.quantityreceived) from purchaseorderline
    where pl.purchaseorderheader_id = purchaseorderline.purchaseorderheader_id
        and pl.product_link_id = purchaseorderline.product_link_id and pl.sizedefinition_link_id =
purchaseorderline.sizedefinition_link_id
  group by purchaseorderline.purchaseorderheader_id
  ) quantityreceived
, ( case when pl.confirmeddate = GETABSMAXDATE()
            then trunc(sysdate) - ( case when ph.exportdate = GETABSMAXDATE()
                                       then ph.approvaldate + spprd.deliverydays
                                            else ph.exportdate + spprd.deliverydays end )
                 else trunc(sysdate) - pl.confirmeddate end )DaysDue
, coalesce(wok.workordernumber, -1) workordernumber, culk.customernumber, culk.name customerName
, weylk.wearernumber, weylk.wearername, sbu.businessunit_id
, CulkOwn.Customernumber OwnedCustomerNumber
, languages.code LanguageCode
, ph.exportdate, ph.approvaldate, spprd.deliverydays
from
  purchaseorderheader ph
    left outer join customer_link CulkOwn on ph.customer_link_id = CulkOwn.Customer_Link_Id
, supplier sp, stockroom sk, productsizepersupproduct pszspp, supplierproduct spprd
, purchaseorderline pl
    left outer join (
               workorderline wokli join (
                                        workorder wok
                                                  left outer join customer_link culk
                                                       on wok.customer_link_id = culk.customer_link_id
                                                  left outer join weareremployment_link weylk
                                                       on wok.weareremployment_link_id = weylk.weareremployment_link_id
                                    ) on wokli.workorder_id = wok.workorder_id
         ) on (pl.purchaseorderline_id = wokli.purchaseorderline_id
           or pl.purchaseorderline_id in (select wolpol.purchaseorderline_id from workorderlinepurchordline wolpol where wolpol.workorderline_id=wokli.workorderline_id))
              and pl.product_link_id = wokli.product_link_id
                  and pl.sizedefinition_link_id = wokli.sizedefinition_link_id
, product prd, sizedefinition sz
, stockroomsservicingbu sbu, status, address AddressSp, languages
where
    ph.status_id = status.status_id
and status.code in ('10', '20', '25', '30')
and (( ph.confirmeddate = GETABSMAXDATE()
          and
        (case when ph.exportdate = GETABSMAXDATE()
                             then ph.approvaldate + spprd.deliverydays
                                  else ph.exportdate + spprd.deliverydays end)
                                       < trunc(sysdate) )
    or
     ( ph.confirmeddate <> GETABSMAXDATE() and ph.confirmeddate < trunc(sysdate) ))
and pl.quantityreceived < pl.quantityordered - pl.quantitycancelled
and ph.supplier_id = sp.supplier_id
and sp.address_id = AddressSp.Address_Id
and ph.stockroom_id = sk.stockroom_id
    and sk.stockroom_id = sbu.stockroom_id
and ph.purchaseorderheader_id = pl.purchaseorderheader_id
    and pl.product_link_id = prd.product_id
    and pl.sizedefinition_link_id = sz.sizedefinition_id
        and pszspp.product_id = prd.product_id
        and pszspp.sizedefinition_id = sz.sizedefinition_id
            and pszspp.supplierproduct_id = spprd.supplierproduct_id
                and spprd.supplier_id = sp.supplier_id
/

  CREATE OR REPLACE VIEW "V_PURCHASEORDERLINE" ("PURCHASEORDERHEADER_ID", "PURCHASEORDERLINE_ID", "WORKORDERNUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "FULLNAME", "NEEDEDDATE", "WORKORDER_ID") AS 
  select distinct
  pli.purchaseorderheader_id, pli.purchaseorderline_id, wok.workordernumber
--, cu.customernumber, cu.name customerName
, (case when wok.weareremployment_link_id is null then (select c.customernumber from customer c where wok.customer_link_id = c.customer_id)
  else cu.customernumber end) customernumber
, (case when wok.weareremployment_link_id is null then (select c.name from customer c where wok.customer_link_id = c.customer_id)
   else cu.name end) customerName
, w.wearernumber, w.fullname, wok.neededdate, wok.workorder_id
from
  purchaseorderline pli, workorderline wokli
, workorder wok
left outer join (weareremployment we
                left outer join
                ( wearer w join customer cu on w.customer_id = cu.customer_id
                )on w.wearer_id = we.wearer_id)
on wok.weareremployment_link_id = we.weareremployment_id
where
    pli.purchaseorderline_id = wokli.purchaseorderline_id
and wokli.workorder_id = wok.workorder_id
union
select distinct
  pli.purchaseorderheader_id, pli.purchaseorderline_id, wok.workordernumber
--, cu.customernumber, cu.name customerName
, (case when wok.weareremployment_link_id is null then (select c.customernumber from customer c where wok.customer_link_id = c.customer_id)
  else cu.customernumber end) customernumber
, (case when wok.weareremployment_link_id is null then (select c.name from customer c where wok.customer_link_id = c.customer_id)
   else cu.name end) customerName
, w.wearernumber, w.fullname, wok.neededdate, wok.workorder_id
from
  purchaseorderline pli, workorderline wokli
, workorder wok
left outer join (weareremployment we
                left outer join
                ( wearer w join customer cu on w.customer_id = cu.customer_id
                )on w.wearer_id = we.wearer_id)
on wok.weareremployment_link_id = we.weareremployment_id
, workorderlinepurchordline wolpol
where pli.purchaseorderline_id=wolpol.purchaseorderline_id
and wokli.workorderline_id=wolpol.workorderline_id
and wokli.workorder_id = wok.workorder_id
union
select distinct
  pli.purchaseorderheader_id, pli.purchaseorderline_id, wok.workordernumber
--, cu.customernumber, cu.name customerName
, (case when wok.weareremployment_link_id is null then (select c.customernumber from customer c where wok.customer_link_id = c.customer_id)
  else cu.customernumber end) customernumber
, (case when wok.weareremployment_link_id is null then (select c.name from customer c where wok.customer_link_id = c.customer_id)
   else cu.name end) customerName
, w.wearernumber, w.fullname, wok.neededdate, wok.workorder_id
from
  purchaseorderline pli, workorderlineemblem wokem, workorderline wokli
, workorder wok
left outer join (weareremployment we
                left outer join
                ( wearer w join customer cu on w.customer_id = cu.customer_id
                )on w.wearer_id = we.wearer_id)
on wok.weareremployment_link_id = we.weareremployment_id
where
    pli.purchaseorderline_id = wokem.purchaseorderline_id
and wokem.workorderline_id = wokli.workorderline_id
and wokli.workorder_id = wok.workorder_id
union
select distinct
  pli.purchaseorderheader_id, pli.purchaseorderline_id, wok.workordernumber
--, cu.customernumber, cu.name customerName
, (case when wok.weareremployment_link_id is null then (select c.customernumber from customer c where wok.customer_link_id = c.customer_id)
  else cu.customernumber end) customernumber
, (case when wok.weareremployment_link_id is null then (select c.name from customer c where wok.customer_link_id = c.customer_id)
   else cu.name end) customerName
, w.wearernumber, w.fullname, wok.neededdate, wok.workorder_id
from
  purchaseorderline pli, workorderlineemblem wokem, workorderline wokli
, workorder wok
left outer join (weareremployment we
                left outer join
                ( wearer w join customer cu on w.customer_id = cu.customer_id
                )on w.wearer_id = we.wearer_id)
on wok.weareremployment_link_id = we.weareremployment_id
, workorderlineemblempoline wolepl
where pli.purchaseorderline_id=wolepl.purchaseorderline_id
and wolepl.workorderlineemblem_id=wokem.workorderlineemblem_id
and wokem.workorderline_id = wokli.workorderline_id
and wokli.workorder_id = wok.workorder_id
/

  CREATE OR REPLACE VIEW "V_QTYPERBUDGETUNIT" ("QTYPERBUGET", "CUSTOMER_ID", "BUDGETUNIT_ID", "YEAR", "MONTH", "CODE") AS 
  select sum(bg.quantity) qtyperbuget, bg.customer_id, bg.budgetunit_id, bg.year, bg.month, cc.code
from budget2 bg, costcenter cc, department d
where  bg.department_id =d.department_id
and d.costcenter_id=cc.costcenter_id
group by bg.customer_id, bg.budgetunit_id, bg.year, bg.month,  cc.code
/

  CREATE OR REPLACE VIEW "V_QTYPERBUDGETUNIT_CUST" ("QTYPERBUGET", "CUSTOMER_ID", "BUDGETUNIT_ID", "YEAR", "MONTH", "DEPARTMENT_ID") AS 
  select sum(bg.quantity) qtyperbuget, bg.customer_id, bg.budgetunit_id, bg.year, bg.month, bg.department_id
from budget2 bg
group by bg.customer_id, bg.budgetunit_id, bg.year, bg.month, bg.department_id
/

  CREATE OR REPLACE VIEW "V_QTYREJECTED" ("CONSIGNMENTNOTE_ID", "PRODUCTCODE", "PRODUCTDESCRIPTION", "REJECTEDQTY", "LANGUAGECODE") AS 
  select /*version 2.0*/
 cn.consignmentnote_id, prd.code productcode,
 (select pd.description
     from product_desc pd
    where pd.product_id = prd.product_id
      and pd.language_id = lan.language_id) productdescription,
  sum(pnl.nochargeprevrejected) rejectedqty,
  lan.code languagecode
from consignmentnote cn
     join packingnote pn on cn.consignmentnote_id = pn.consignmentnote_id
          join packingnoteline pnl on pn.packingnote_id = pnl.packingnote_id
               join product prd on pnl.product_id = prd.product_id
     cross join languages lan
group by cn.consignmentnotenumber, cn.consignmentnote_id, prd.code, prd.product_id, lan.language_id, lan.code
/

  CREATE OR REPLACE VIEW "V_QTYSHORTAGE" ("CONSIGNMENTNOTE_ID", "PRODUCTCODE", "PRODUCTDESCRIPTION", "LANGUAGECODE", "SHORTAGEQTY") AS 
  SELECT
    CN.CONSIGNMENTNOTE_ID, PRD.CODE PRODUCTCODE
  , (SELECT PD.DESCRIPTION FROM PRODUCT_DESC PD WHERE PD.PRODUCT_ID = PRD.PRODUCT_ID
    AND PD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION
  , LANGUAGES.CODE LANGUAGECODE
  , SUM(DV.AMOUNT) SHORTAGEQTY
FROM
  CONSIGNMENTNOTE CN, PRODUCT PRD, LANGUAGES, DELIVERYVARIATIONS DV, PACKINGNOTE PN
WHERE
    CN.CONSIGNMENTNOTE_ID = PN.CONSIGNMENTNOTE_ID
    AND DV.PACKINGNOTE_ID = PN.PACKINGNOTE_ID
    AND DV.PRODUCT_ID = PRD.PRODUCT_ID
    AND DV.SOILCOUNTSUBTYPE = 2
GROUP BY CN.CONSIGNMENTNOTENUMBER, CN.CONSIGNMENTNOTE_ID
, PRD.CODE,PRD.PRODUCT_ID, LANGUAGES.LANGUAGE_ID , LANGUAGES.CODE
/

  CREATE OR REPLACE VIEW "V_QUALITYGRADE" ("CODE", "QUALITYGRADE_DESC", "PRIORITY", "INSTRUCTION", "MINWEEKSINUSE", "MAXWEEKSINUSE", "MINWASHES", "MAXWASHES", "SYSTEMUSER_ID", "TIMESTAMP", "QUALITYGRADE_ID", "LANGUAGECODE") AS 
  SELECT QUALITYGRADE.CODE,
(SELECT DESCRIPTION FROM QUALITYGRADE_DESC A WHERE A.QUALITYGRADE_ID = QUALITYGRADE.QUALITYGRADE_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) QUALITYGRADE_DESC,
 QUALITYGRADE.PRIORITY, QUALITYGRADE.INSTRUCTION, QUALITYGRADE.MINWEEKSINUSE,
 QUALITYGRADE.MAXWEEKSINUSE, QUALITYGRADE.MINWASHES, QUALITYGRADE.MAXWASHES,
 QUALITYGRADE.SYSTEMUSER_ID, QUALITYGRADE.TIMESTAMP, QUALITYGRADE.QUALITYGRADE_ID, LANGUAGES.CODE LANGUAGECODE
	FROM  QUALITYGRADE, LANGUAGES
/

  CREATE OR REPLACE VIEW "V_QUANTITIESRESTOCKING" ("WEBSESSION_ID", "WEBUSER_ID", "WEBUSERDEPARTMENT_ID", "DEPARTMENT_ID", "CUSTOMERNAME", "CUSTOMERNUMBER", "DEPARTMENTDESC", "DEPARTMENTNUMBER", "DISTRIBUTIONPOINTDESC", "DISTRIBUTIONPOINTNUMBER", "AMOUNTDELIVERED", "THEORETICALWEIGHT", "PRODUCTDESC", "PRODUCTCODE", "PRODUCTGROUPCODE", "SIZECODE", "FINISHINGMETHODCODE", "ACTIVITYCODE", "FINISHINGMETHODDESC", "PRICE", "DECIMALS", "CURRENCYCODE", "LANGUAGECODE", "REPORTPARAM_ID") AS 
  select ws.websession_id,
  wc.webuser_id, WD.DEPARTMENT_ID WEBUSERDEPARTMENT_ID, dl.DEPARTMENT_ID,
  cl.name customername, cl.customernumber,
  dl.description departmentdesc, dl.departmentnumber,
  dpl.description distributionpointdesc, dpl.distributionpointnumber,
  dh.amountdelivered,
  (case when (select ps.theoreticalweight from productsize ps where ps.product_id = p.product_id
              and ps.sizedefinition_id = sl.sizedefinition_id) = 0
        then  p.theoreticalweight
        else (select ps.theoreticalweight from productsize ps where ps.product_id = p.product_id
              and ps.sizedefinition_id = sl.sizedefinition_id)
   end) theoreticalweight,
  (select pld.description from product_link_desc pld
    where pld.product_link_id = pl.product_link_id and pld.language_id = languages.language_id) productdesc,
  pl.code productcode, pl.productgroupcode, sl.code sizecode,
  f.code finishingmethodcode, a.code activitycode,
  (select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = f.finishingmethod_id
    and fmd.language_id = languages.language_id) finishingmethoddesc,
  F_RESTOCKINGPRICE(cl.customer_id, pl.product_id, sl.sizedefinition_id, dh.finishingmethod_id, dh.deliverydate, p.typeofmerchandise) price,
  coalesce(cr.invoiceamountdecimals, 0) decimals, CR.CODE CURRENCYCODE,
  languages.code languagecode, rp.reportparam_id
from deliveryhistory dh,
  product_link pl
    left outer join (product p
      left outer join (productgroup pg
        left outer join activity a on a.activity_id = pg.activity_id)
        on pg.productgroup_id = p.product_id)
      on p.product_id = pl.product_id,
  finishingmethod f, sizedefinition_link sl, department_link dl, distributionpoint_link dpl,
  customer_link cl
    left outer join (customer cu
      left outer join currency cr on cu.currency_id = cr.currency_id)
    on cl.customer_id = cu.customer_id,
  reportparam rp, languages,
  webusercustomer wc
    left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  websession ws
where dh.product_link_id = pl.product_link_id
  and dh.sizedefinition_link_id = sl.sizedefinition_link_id
  and dh.customer_link_id = cl.customer_link_id
  and dh.finishingmethod_id = f.finishingmethod_id
  and dh.department_link_id = dl.department_link_id
  and dh.distributionpoint_link_id = dpl.distributionpoint_link_id
  and dh.deliverydate <= rp.date_value1
  and dh.deliverydate >= rp.date_value2
  and wc.customer_id = cl.customer_id
  and ws.customer_id = cl.customer_id
  and dh.packindication <> 2
/

  CREATE OR REPLACE VIEW "V_QUANTITIESRESTOCKINGNEW" ("WEBSESSION_ID", "WEBUSER_ID", "WEBUSERDEPARTMENT_ID", "DEPARTMENT_ID", "CUSTOMERNAME", "CUSTOMERNUMBER", "DEPARTMENTDESC", "DEPARTMENTNUMBER", "DISTRIBUTIONPOINTDESC", "DISTRIBUTIONPOINTNUMBER", "AMOUNTDELIVERED", "THEORETICALWEIGHT", "PRODUCTDESC", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTGROUP_ID", "PRODUCTGROUPCODE", "SIZECODE", "SIZEDESC", "FINISHINGMETHODCODE", "ACTIVITY_ID", "ACTIVITYCODE", "FINISHINGMETHODDESC", "PRICE", "PIECEWEIGHT", "POUNDPRICE", "DECIMALS", "CURRENCYCODE", "LANGUAGECODE", "REPORTPARAM_ID", "COSTPRICE", "BUDGETRELEVANT") AS 
  select wus.websession_id,
  wc.webuser_id, wd.department_id webuserdepartment_id, dl.department_id,
  cl.name customername, cl.customernumber,
  dl.description departmentdesc, dl.departmentnumber,
  dpl.description distributionpointdesc, dpl.distributionpointnumber,
  dh.amountdelivered,
  (case when (select ps.theoreticalweight from productsize ps where ps.product_id = p.product_id
              and ps.sizedefinition_id = sl.sizedefinition_id) = 0
        then  p.theoreticalweight
        else (select ps.theoreticalweight from productsize ps where ps.product_id = p.product_id
              and ps.sizedefinition_id = sl.sizedefinition_id)
   end) theoreticalweight,
  (select pld.description from product_link_desc pld
    where pld.product_link_id = pl.product_link_id and pld.language_id = languages.language_id) productdesc,
  pl.product_id product_id, pl.code productcode, pg.productgroup_id productgroup_id, pl.productgroupcode,
  sl.code sizecode,
  (select sld.description from sizedefinition_desc sld where sld.sizedefinition_id = sl.sizedefinition_id
    and sld.language_id = languages.language_id) sizedesc,
  f.code finishingmethodcode, a.activity_id activity_id, a.code activitycode,
  (select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = f.finishingmethod_id
    and fmd.language_id = languages.language_id) finishingmethoddesc,
  f_restockingprice_ang(cl.customer_id, pl.product_id, sl.sizedefinition_id, dh.finishingmethod_id, dh.deliverydate, p.typeofmerchandise) price,
  dh.pieceweight,
  f_getpoundprice(p.product_id, f.finishingmethod_id, sl.sizedefinition_link_id, cu.customer_id, p.weighingcategory_id, dh.deliverydate) poundprice,
  coalesce(cr.invoiceamountdecimals, 0) decimals, cr.code currencycode,
  languages.code languagecode, rp.reportparam_id,
  coalesce(
    f_getcostreportprice(dh.customer_link_id, p.product_id, sl.sizedefinition_link_id, f.finishingmethod_id, dh.deliverydate,
    p.typeofmerchandise, p.weighingcategory_id, cr.decimals),0) costprice,
    (select plpc.budgetrelevant
          from productlistpercustomer plpc
         where plpc.customer_id = cu.customer_id
           and plpc.product_id = dh.product_link_id
           and plpc.sizedefinition_id = dh.sizedefinition_link_id
           and plpc.finishingmethod_id = dh.finishingmethod_id) budgetrelevant
from deliveryhistory dh,
  product_link pl
    left outer join (product p
      left outer join (productgroup pg
        left outer join activity a on a.activity_id = pg.activity_id)
        on pg.productgroup_id = p.productgroup_id)
      on p.product_id = pl.product_id,
  finishingmethod f, sizedefinition_link sl, department_link dl, distributionpoint_link dpl,
  customer_link cl
    left outer join (customer cu
      left outer join currency cr on cu.currency_id = cr.currency_id)
    on cl.customer_id = cu.customer_id,
  reportparam rp, languages,
  webusercustomer wc
    left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  webusersession wus
where dh.product_link_id = pl.product_link_id
  and dh.sizedefinition_link_id = sl.sizedefinition_link_id
  and dh.customer_link_id = cl.customer_link_id
  and dh.finishingmethod_id = f.finishingmethod_id
  and dh.department_link_id = dl.department_link_id
  and dh.distributionpoint_link_id = dpl.distributionpoint_link_id
  and dh.deliverydate <= rp.date_value1
  and dh.deliverydate >= rp.date_value2
  and wc.customer_id = cl.customer_id
  and wus.customer_id = cl.customer_id
  and dh.packindication <> 2
/

  CREATE OR REPLACE VIEW "V_RAGGEDITEMSFROMCIRCULATION" ("OUTOFCIRCDATE", "OUTOFCIRCDATETRUNC", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMERCITY", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "WEARERNUMBER", "WEARERNAME", "PRODUCTCODE", "PRODUCTDESC", "QUALITYGRADEDESC", "QUALITYGRADECODE", "RAGREASONCODE", "REASONCODE", "QUANTITY", "LANGUAGECODE", "PROCESSBUSINESSUNIT_ID") AS 
  select
  ochy.outofcircdate, trunc(ochy.outofcircdate) outofcircdateTrunc
, cu.customer_id, cu.customernumber, cu.name customerName, addressCu.City CustomerCity
, delk.departmentnumber, delk.description departmentDesc
, weylk.wearernumber, weylk.wearername, prd.code ProductCode
, (select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) ProductDesc
, (select qualitygrade_desc.description from qualitygrade_desc where qualitygrade_desc.qualitygrade_id = qualitygrade.qualitygrade_id
  and qualitygrade_desc.language_id = languages.language_id) qualitygradeDesc
, qualitygrade.code qualitygradeCode, ragreason.code ragreasonCode, reasoncode.code  reasonCode
, ochy.quantity, languages.code languageCode
, ochy.processbusinessunit_id
from outofcirculationhistory ochy
     left outer join customer cu on ochy.customer_link_id = cu.customer_id
     left outer join qualitygrade on ochy.qualitygrade_id = qualitygrade.qualitygrade_id
, weareremployment_link weylk, distributionpoint_link dilk, department_link delk
, address addressCu, ragreason, reasoncode, product prd, languages
where
    ochy.ragreason_id is not null
and ochy.weareremployment_link_id = weylk.weareremployment_link_id
and ochy.distributionpoint_link_id = dilk.distributionpoint_link_id
    and dilk.department_link_id = delk.department_link_id
and ochy.ragreason_id = ragreason.ragreason_id
and ochy.reasoncode_id = reasoncode.reasoncode_id
and ochy.product_link_id = prd.product_id
    and cu.visitaddress_id = addressCu.Address_Id
/

  CREATE OR REPLACE VIEW "V_RAGGEDRETURNEDITEMS" ("OUTOFCIRCULATIONHISTORY_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "FULLNAME", "PRODUCTGROUPCODE", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "SIZEDESC", "REASONCODE", "REASONDESC", "QUANTITY", "PRIMARYID", "WEEKS", "RESIDUALVALUE", "ENTEREDPERCENTAGE", "VALUECHARGE", "OUTOFCIRCDATE", "OUTOFCIRCDATETRUNC", "STATUS", "USERNAME", "DEPARTMENTNUMBER", "CONSUMPTIONPOINT", "INVOICEDYN", "RAGGEDRETURNEDYN", "LANGUAGECODE", "CUSTOMER_LINK_ID", "REPORTPARAM_ID", "WASHESTOTAL", "PROCESSBUSINESSUNIT_ID", "FORBUSINESSUNIT_ID", "DEFAULTBUSINESSUNIT_ID", "CURRENT_BU_ID", "BU_CODE", "BU_DESC") AS 
  select /*version 2.1*/
       och.outofcirculationhistory_id, cu.customernumber, cu.name customername,
       wel.wearernumber, wel.wearername fullname, pg.code productgroupcode, prd.code productcode,
       (select prde.description
          from product_desc prde
         where prde.product_id = prd.product_id
           and prde.language_id = lan.language_id) productdesc, siz.code sizecode,
       (select sizd.description
          from sizedefinition_desc sizd
         where sizd.sizedefinition_id = siz.sizedefinition_id
           and sizd.language_id = lan.language_id) sizedesc,
       (select rc.code
          from reasoncode rc
         where rc.reasoncode_id = och.reasoncode_id) reasoncode,
       (select rcd.description
          from reasoncode_desc rcd
         where rcd.reasoncode_id = och.reasoncode_id
           and rcd.language_id = lan.language_id) reasondesc,
       och.quantity, och.primaryid, (och.weeksinusethisissue + och.weeksinuseprevissue) weeks,
       och.residualvalue, och.tobechargedpercentage enteredpercentage, och.amount valuecharge,
       och.outofcircdate, trunc(och.outofcircdate) outofcircdatetrunc, och.status,
       (select su.username
          from systemuser su
         where och.systemuser_id = su.systemuser_id) username,
       d.departmentnumber, dpl.distributionpointnumber consumptionpoint, och.invoiceheader_id invoicedyn,
       och.ragreason_id raggedreturnedyn, lan.code languagecode, och.customer_link_id, rp.reportparam_id,
       coalesce((select ui.washestotal
                   from uniqueitem ui
                  where ui.uniqueitem_id = och.uniqueitem_link_id),
                (select ri.washestotal
                   from raggeditem ri
                  where ri.raggeditem_id = och.uniqueitem_link_id), 0) washestotal,
       och.processbusinessunit_id, och.forbusinessunit_id, cu.defaultbusinessunit_id, rp.number_value9 current_bu_id,
       pbu.code bu_code, pbu.description bu_desc
  from outofcirculationhistory och
       left join weareremployment_link wel on och.weareremployment_link_id = wel.weareremployment_link_id
       join businessunit pbu on och.processbusinessunit_id = pbu.businessunit_id
       join product prd
            join productgroup pg on prd.productgroup_id = pg.productgroup_id
       on och.product_link_id = prd.product_id
       join sizedefinition siz on och.sizedefinition_link_id = siz.sizedefinition_id
       join distributionpoint_link dpl
            join department d
                 join customer cu on d.customer_id = cu.customer_id
            on dpl.department_link_id = d.department_id
       on och.distributionpoint_link_id = dpl.distributionpoint_link_id
       cross join reportparam rp
             join languages lan
       on rp.string_value = lan.code
 where och.chargetype = 1
   and och.customer_link_id = cu.customer_id
   and cu.customernumber >= rp.number_value1
   and cu.customernumber <= rp.number_value2
   and d.departmentnumber >= rp.number_value3
   and d.departmentnumber <= rp.number_value4
   and dpl.distributionpointnumber >= rp.number_value5
   and dpl.distributionpointnumber <= rp.number_value6
   and exists (select 1
                 from businessunitsperusergroup bus, systemuser s
                where cu.defaultbusinessunit_id = bus.businessunit_id
                  and bus.usergroup_id = s.usergroup_id
                  and s.systemuser_id = rp.number_value)
/

  CREATE OR REPLACE VIEW "V_RAGSPERWEARER" ("RAGTIMESTAMP", "RAGDATE", "CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "WEARERNUMBER", "WEARERSEARCHNAME", "WEARERFULLNAME", "ADMINNUMBER", "BANKLOCKER", "GARMENTDISPENSER", "WEARERFUNCTIONCODE", "WEARERFUNCTIONDESC", "EMPLOYMENT", "WEARERDATEACTIVE", "WEARERDATEINACTIVE", "COSTCENTERCODE", "COSTCENTERDESC", "WEARERACTIVE", "PRIMARYID", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "SIZEDESC", "FIRSTISSUEDATE", "LASTISSUEDATE", "WASHESTOTAL", "REPAIRSTOTAL", "REWASHTOTAL", "DAYSINCIRCULATION", "WEEKSINCIRCULATION", "CUSTOMEROWNED", "REASONCODE", "RAGREASONCODE", "RAGREASONDESC", "RIRESIDUALVALUE", "CUSTOMERLANGUAGE_ID", "LANGUAGE_ID", "LANGUAGECODE", "BUSINESSUNIT_ID", "RESIDUALVALUE", "TIMESTAMP", "SYSTEM_USER") AS 
  select /*version 2.0*/
       ragi.ragtimestamp, trunc(ragi.ragtimestamp) ragdate, cu.customernumber, cu.name customername,
       vad.city, de.departmentnumber, de.description departmentdesc, we.wearernumber,
       we.searchname wearersearchname, we.fullname wearerfullname,
       we.customeremployeenumber adminnumber,
       cast(concatenatewithblank(lk.bank, lk.locker) as varchar2(255)) banklocker,
       gd.code garmentdispenser, wef.code wearerfunctioncode, wef.description wearerfunctiondesc,
       wemp.sequencenumber employment, we.dateactive wearerdateactive,
       we.dateinactive wearerdateinactive, cc.code costcentercode, cc.description costcenterdesc,
       getdatediff(trunc(sysdate), we.dateactive) * getdatediff(we.dateinactive, trunc(sysdate)) weareractive,
       case when length(ragi.primaryid) = 24
             and nvl((select ss.value
                        from systemsetting ss
                       where ss.plant_id = bu.plant_id
                         and ss.name = 'USEURICODE'), 0) = 1
            then pack_epc_sgtin96.decode(ragi.primaryid)
       else ragi.primaryid end primaryid,
       (select prd.code
          from product prd
         where prd.product_id = ragi.product_link_id) productcode,
       (select prde.description
          from product_desc prde
         where prde.product_id = ragi.product_link_id
           and prde.language_id = lan.language_id) productdesc,
       (select sz.code
          from sizedefinition sz
         where sz.sizedefinition_id = ragi.sizedefinition_link_id) sizecode,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = ragi.sizedefinition_link_id
           and sdd.language_id = lan.language_id) sizedesc, ragi.firstissuedate,
       ragi.lastissuedate, ragi.washestotal, ragi.repairstotal, ragi.rewashtotal,
       ragi.daysincirculation, getroundtointeger(ragi.daysincirculation / 7) weeksincirculation,
       ragi.customerowned, rc.code reasoncode, rr.code ragreasoncode,
       (select rrd.description
          from ragreason_desc rrd
         where rrd.ragreason_id = rr.ragreason_id
           and rrd.language_id = lan.language_id) ragreasondesc,
       ragi.residualvalue riresidualvalue, cu.language_id customerlanguage_id,
       lan.language_id, lan.code languagecode, ragi.businessunit_id,
       nvl((select max(ochy.tobechargedpercentage)
              from outofcirculationhistory ochy
                   join uniqueitem_link uil on ochy.uniqueitem_link_id = uil.uniqueitem_link_id
             where ochy.weareremployment_link_id = wel.weareremployment_link_id
               and ochy.distributionpoint_link_id = dip.distributionpoint_id
               and ochy.customer_link_id = cu.customer_id
               and ochy.product_link_id = ragi.product_link_id
               and ochy.sizedefinition_link_id = ragi.sizedefinition_link_id
               and ochy.reasoncode_id = rc.reasoncode_id
               and ochy.ragreason_id = rr.ragreason_id
               and uil.raggeditem_id = ragi.raggeditem_id), 0) residualvalue, ragi.timestamp,
       (select su.username from systemuser su where su.systemuser_id = ragi.systemuser_id) system_user
  from raggeditem ragi
       left join reasoncode rc on ragi.reasoncode_id = rc.reasoncode_id
       join weareremployment_link wel
            left join weareremployment wemp
                 left join locker lk on wemp.locker_id = lk.locker_id
                 left join wearerfunction wef on wemp.wearerfunction_id = wef.wearerfunction_id
                 left join garmentdispenser gd on wemp.garmentdispenser_id = gd.garmentdispenser_id
            on wel.weareremployment_id = wemp.weareremployment_id
            join wearer we on wel.wearernumber = we.wearernumber
       on ragi.weareremployment_link_id = wel.weareremployment_link_id
       join distributionpoint dip
            join costcenter cc on dip.costcenter_id = cc.costcenter_id
            join department de
                 join customer cu
                      join businessunit bu on cu.defaultbusinessunit_id = bu.businessunit_id
                      join address vad on cu.visitaddress_id = vad.address_id
                 on de.customer_id = cu.customer_id
            on dip.department_id = de.department_id
       on ragi.distributionpoint_link_id = dip.distributionpoint_id
       join ragreason rr on ragi.ragreason_id = rr.ragreason_id
       cross join languages lan
 where wel.distributionpoint_link_id = dip.distributionpoint_id
   and cc.customer_id = cu.customer_id
   and ragi.poolitem = 2
   and nvl(wemp.wearer_id, we.wearer_id) = we.wearer_id
   and nvl(we.customer_id, cu.customer_id) = cu.customer_id
/

  CREATE OR REPLACE VIEW "V_REALTIME_STOCKQTY" ("CUSTOMERNUMBER", "WORKORDERNUMBER", "PRODUCTCODE", "SIZECODE", "QTYOPEN", "PURCHASEORDERNUMBER", "CONFIRMEDDATE", "PO_QTY_OPEN", "FREE_STOCKQTYUNIQUE", "FREE_STOCKQTYUNIQUEWITHMOD", "FREE_STOCKQTYNONUNIQUE", "CUSTOMER_ID", "PRODUCT_ID", "SIZE_ID") AS 
  select /*view v_realtime_stockqty version 0.1*/
 c.customernumber, wo.workordernumber, p.code productcode, s.code sizecode,
 (wol.quantityordered - wol.quantityfilled - wol.quantitycancelled) qtyopen, poh.purchaseordernumber,
 poh.confirmeddate, (pol.quantityordered - pol.quantityreceived - pol.quantitycancelled) po_qty_open,
 stockqty.qtyunique free_stockqtyunique,
 stockqty.qtyuniquewithmodifications free_stockqtyuniquewithmod,
 stockqty.qtynonunique free_stockqtynonunique, c.customer_id, wol.product_link_id product_id,
 wol.sizedefinition_link_id size_id
from   workorder wo
join   workorderline wol
on     wol.workorder_id = wo.workorder_id
join   status st
on     st.status_id = wo.status_id
join   product p
on     p.product_id = wol.product_link_id
join   sizedefinition s
on     s.sizedefinition_id = wol.sizedefinition_link_id
join   customer c
on     c.customer_id = wo.customer_link_id
left   outer join(purchaseorderline pol
join   purchaseorderheader poh
on     poh.purchaseorderheader_id = pol.purchaseorderheader_id) on pol.purchaseorderline_id = wol.purchaseorderline_id
left   outer join (select sti.product_id, sti.sizedefinition_id,
                          sum((select sum(sq.qtyunique)
                                from   stockquantity sq
                                where  sq.stockreservationpergrade_id = sr.stockreservationpergrade_id) -
                               sr.qtyuniquereserved) qtyunique,
                          sum((select sum(sq.qtyuniquewithmodifications)
                                from   stockquantity sq
                                where  sq.stockreservationpergrade_id = sr.stockreservationpergrade_id) -
                               sr.qtyuniquewiithmodifreserved) qtyuniquewithmodifications,
                          sum((select sum(sq.qtynonunique)
                                from   stockquantity sq
                                where  sq.stockreservationpergrade_id = sr.stockreservationpergrade_id) -
                               sr.qtynonuniquereserved) qtynonunique
                   from   stockreservationpergrade sr
                   join   stockdefinitionperitem sti
                   on     sti.stockdefinitionperitem_id = sr.stockdefinitionperitem_id
                   group  by sti.product_id, sti.sizedefinition_id) stockqty
on     stockqty.product_id = wol.product_link_id
and    stockqty.sizedefinition_id = wol.sizedefinition_link_id
where  st.code <> '40'
and    (wol.quantityordered - wol.quantityfilled - wol.quantitycancelled) <> 0
/

  CREATE OR REPLACE VIEW "V_REASONCODE" ("CODE", "REASONCODE_DESC", "FIRSTISSUE", "ALLOWPREPCHARGES", "INTERNETSELECTABLE", "LINENREASON", "GARMENTREASON", "EXPORTTOHANDHELD", "CANCELINVOICE", "AFFECTSNEXTINVOICE", "AFFECTSCURRENTINVOICE", "INVOICEADJUSTMENT", "CHARGERESTOCKINGFEE", "INVENTORYTRIGGER", "SYSTEMUSER_ID", "TIMESTAMP", "REASONCODE_ID", "LANGUAGECODE") AS 
  SELECT REASONCODE.CODE,
  (SELECT DESCRIPTION FROM REASONCODE_DESC A WHERE A.REASONCODE_ID = REASONCODE.REASONCODE_ID
     AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) REASONCODE_DESC,
  REASONCODE.FIRSTISSUE,REASONCODE.ALLOWPREPCHARGES, REASONCODE.INTERNETSELECTABLE,
  REASONCODE.LINENREASON, REASONCODE.GARMENTREASON,REASONCODE.EXPORTTOHANDHELD, REASONCODE.CANCELINVOICE,
  REASONCODE.AFFECTSNEXTINVOICE, REASONCODE.AFFECTSCURRENTINVOICE, REASONCODE.INVOICEADJUSTMENT,
  REASONCODE.CHARGERESTOCKINGFEE,
  REASONCODE.INVENTORYTRIGGER, REASONCODE.SYSTEMUSER_ID, REASONCODE.TIMESTAMP, REASONCODE.REASONCODE_ID,
  LANGUAGES.CODE LANGUAGECODE
FROM  REASONCODE, LANGUAGES
/

  CREATE OR REPLACE VIEW "V_RECEIVEDITEMSFROMSUPPLIER" ("STOCKCODE", "STOCKNAME", "STOCKROOM_ID", "RECEIVEDATE", "RECEIVEDATETRUNC", "RECEIVEDATETIME", "PURCHASEORDERNUMBER", "PICKINGSEQUENCE", "AREACODE", "ROWCODE", "LOCATIONCODE", "CUSTOMEROWNED", "CUSTOMERNAMEOWNED", "CUSTOMERNUMBER", "PRODUCTCODE", "SIZECODE", "PRODUCTDESC", "QUANTITY", "WORKSTATIONCODE", "CUSTOMER_LINK_ID", "SUPPLIERNUMBER", "SUPPLIERNAME", "PRDGRPCODE", "LANGUAGECODE", "STOCKLOCAREACODE", "GRADE") AS 
  select
  sk.code stockCode, sk.name stockName, sk.stockroom_id, recSkhis.Receivedate, trunc(recSkhis.Receivedate) ReceivedateTrunc
, GETTIMEASNUMERIC(recSkhis.Receivedate) ReceivedateTime
, coalesce(recSkhis.Purchaseordernumber, -1) Purchaseordernumber, coalesce(skl.pickingsequence, -1) pickingsequence
, skl.areacode, recSkhis.rowcode, recSkhis.locationcode, recSkhis.Customerowned, customer.name customerNameOwned, customer.customernumber
, prd.code productCode, sz.code sizeCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc, recSkhis.Quantity
, recSkhis.Workstationcode workstationCode, recSkhis.Customer_Link_Id, supplier.suppliernumber, supplier.name suppliername, pg.code prdgrpcode
, languages.code languageCode
, skl.areacode StockLocAreaCode
, (select QG.Code from qualitygrade QG where qg.qualitygrade_id = recSkhis.Qualitygrade_Id) Grade
from
  receiveinstockhistory recSkhis
LEFT OUTER JOIN customer ON recSkhis.Customerowned = 'Y' and customer.customer_id = recSkhis.Customer_Link_Id
left outer join  stockroomlocation skl on recSkhis.Stockroom_Id = skl.stockroom_id
                                       and recSkhis.Rowcode = skl.rowcode
                                       and recSkhis.Locationcode = skl.locationcode
                                       and recSkhis.Areacode = skl.Areacode
left outer join
           ( purchaseorderheader ph join supplier on ph.supplier_id = supplier.supplier_id )
     on recSkhis.Purchaseordernumber = ph.purchaseordernumber
        and recSkhis.Stockroom_Id = ph.stockroom_id
, stockroom sk, product prd,productgroup pg, sizedefinition sz
, languages
where
    -- recSkhis.Purchaseordernumber is not null and
    recSkhis.Stockroom_Id = sk.stockroom_id
and recSkhis.Product_Link_Id = prd.product_id
and recSkhis.Sizedefinition_Link_Id = sz.sizedefinition_id
and prd.productgroup_id=pg.productgroup_id
/

  CREATE OR REPLACE VIEW "V_RECEIVEDITEMSINSTOCK" ("STOCKCODE", "STOCKNAME", "STOCKROOM_ID", "OUTOFCIRCDATE", "OUTOFCIRCDATETRUNC", "OUTOFCIRCTIME", "PICKINGSEQUENCE", "ROWCODE", "LOCATIONCODE", "QUANTITY", "CUSTOMEROWNED", "CUSTOMERNUMBER", "CUSTOMERNAME", "PRODUCTCODE", "SIZECODE", "QUALITYGRADECODE", "PRIORITY", "PRODUCTDESC", "PRDGRPCODE", "WORKSTATIONCODE", "LANGUAGECODE", "STOCKLOCAREACODE") AS 
  select --count(*)
  sk.code stockCode, sk.name stockName, sk.stockroom_id, ochy.outofcircdate, trunc(ochy.outofcircdate) outofcircdateTrunc
, GETTIMEASNUMERIC(ochy.outofcircdate) outofcircTime
, coalesce(skl.pickingsequence, -1) pickingsequence
, ochy.rowcode rowcode, ochy.locationcode locationcode, ochy.quantity, ochy.Customerowned
, cu.customernumber, cu.name customerName
, prd.code productCode, sz.code sizeCode, qualitygrade.code qualitygradeCode, qualitygrade.priority
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc, pg.code prdgrpcode
, ochy.workstationcode, languages.code languageCode, skl.areacode StockLocAreaCode
from
  outofcirculationhistory ochy
     left outer join stockroom sk on ochy.stockroom_id = sk.stockroom_id
     left outer join stockroomlocation skl on ochy.stockroom_id = skl.stockroom_id
                                           and ochy.rowcode = skl.rowcode
                                           and ochy.locationcode = skl.locationcode
                                           and ochy.areacode=skl.areacode
     left outer join qualitygrade on ochy.qualitygrade_id = qualitygrade.qualitygrade_id
, customer cu, product prd,productgroup pg, sizedefinition sz, languages
where
    ochy.ragreason_id is null
and ochy.chargetype = 1
and ochy.customer_link_id = cu.customer_id
and ochy.product_link_id = prd.product_id
and prd.productgroup_id=pg.productgroup_id
and ochy.sizedefinition_link_id = sz.sizedefinition_id
union--not union all in order to select only one line for the two charge types 1 and 2
select --count(*)
  sk.code stockCode, sk.name stockName, sk.stockroom_id, ochy.outofcircdate, trunc(ochy.outofcircdate) outofcircdateTrunc
, GETTIMEASNUMERIC(ochy.outofcircdate) outofcircTime
, coalesce(skl.pickingsequence, -1) pickingsequence
, ochy.rowcode rowcode, ochy.locationcode locationcode, ochy.quantity, ochy.Customerowned
, cu.customernumber, cu.name customerName
, prd.code productCode, sz.code sizeCode, qualitygrade.code qualitygradeCode, qualitygrade.priority
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc, pg.code prdgrpcode
, ochy.workstationcode, languages.code languageCode, skl.areacode StockLocAreaCode
from
  outofcirculationhistory ochy
     left outer join stockroom sk on ochy.stockroom_id = sk.stockroom_id
     left outer join stockroomlocation skl on ochy.stockroom_id = skl.stockroom_id
                                           and ochy.rowcode = skl.rowcode
                                           and ochy.locationcode = skl.locationcode
                                           and ochy.areacode=skl.areacode
     left outer join qualitygrade on ochy.qualitygrade_id = qualitygrade.qualitygrade_id
, customer cu, product prd,productgroup pg, sizedefinition sz, languages
where
    ochy.ragreason_id is null
and ochy.chargetype = 2
and ochy.customer_link_id = cu.customer_id
and ochy.product_link_id = prd.product_id
and prd.productgroup_id=pg.productgroup_id
and ochy.sizedefinition_link_id = sz.sizedefinition_id
/

  CREATE OR REPLACE VIEW "V_REJECTEDSCANS" ("CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "TRANSACTIONTYPE_ID", "TRANSACTIONTYPEDESC", "WORKSTATIONCODE", "USERNAME", "FULLNAME", "SCANTIMESTAMP", "SCANDATE", "SCANTIME_NUMBER", "PRIMARYID", "BUSINESSUNITCODE", "BUSINESSUNIT_ID", "BUSINESSUNITDESC", "LANGUAGECODE", "MULTIREADEXCEPTIONREASON_ID", "REASON_CODE", "SCANTIME_CHAR", "PRODUCT_LINK_CODE", "PRODUCT_LINK_DESC", "USERGROUP_ID") AS 
  select culk.customer_id, culk.customernumber, culk.name customername,
       rs.transactiontype_id,
       coalesce((select transactiontype_desc.description
                   from transactiontype_desc
                  where transactiontype_desc.transactiontype_id =
                        rs.transactiontype_id
                    and transactiontype_desc.language_id =
                        languages.language_id), tt.factorydescription) transactiontypedesc,
       coalesce(rs.scanstation, ' ') workstationcode, sy.username,
       sy.fullname, rs.scantimestamp, trunc(rs.scantimestamp) scandate,
       gettimeasnumeric(rs.scantimestamp) scantime_number,
       rs.idcode primaryid, bu.code businessunitcode, bu.businessunit_id,
       bu.description businessunitdesc, languages.code languagecode,
       mre.multireadexceptionreason_id,
       coalesce((select mred.description
                   from multireadexceptionreason_desc mred
                  where mre.multireadexceptionreason_id =
                        mred.multireadexceptionreason_id
                    and mred.language_id = languages.language_id), mre.factorydescription) reason_code,
       to_char(rs.scantimestamp, 'fmHHfm:MI:AM') scantime_char,
       (select pr.code
           from product_link pr
          where pr.product_link_id = rs.product_link_id) product_link_code,
       (select prd.description
           from product_link_desc prd
          where prd.product_link_id = rs.product_link_id
            and prd.language_id = languages.language_id) product_link_desc,
       bug.usergroup_id
  from rejectedscan rs
  join businessunit bu on rs.businessunit_id = bu.businessunit_id
  join businessunitsperusergroup bug on bu.businessunit_id = bug.businessunit_id
  join systemuser sy on rs.systemuser_id = sy.systemuser_id
  join transactiontype tt on rs.transactiontype_id = tt.transactiontype_id
  join multireadexceptionreason mre on rs.multireadexceptionreason_id = mre.multireadexceptionreason_id
  left outer join customer culk on culk.customer_id = rs.customer_link_id
 cross join languages
/

  CREATE OR REPLACE VIEW "V_REJECTEDSCANSCONDENSED" ("TRANSACTIONTYPE_ID", "TRANSACTIONTYPEDESC", "WORKSTATIONCODE", "WORKSTATIONDESC", "USERNAME", "FULLNAME", "SCANDATE", "SCANTIME_NUMBER", "BUSINESSUNITCODE", "BUSINESSUNIT_ID", "BUSINESSUNITDESC", "MULTIREADEXCEPTIONREASON_ID", "REASON_CODE", "LANGUAGECODE", "USERGROUP_ID", "REJECTEDSCAN_ID") AS 
  select rs.transactiontype_id,
       coalesce((select transactiontype_desc.description
                   from transactiontype_desc
                  where transactiontype_desc.transactiontype_id =
                        rs.transactiontype_id
                    and transactiontype_desc.language_id =
                        languages.language_id), tt.factorydescription) transactiontypedesc,
       coalesce(rs.scanstation, ' ') workstationcode,
       (select w.description
           from workstation w
          where w.code = rs.scanstation) workstationdesc, sy.username,
       sy.fullname, rs.scantimestamp scandate,
       gettimeasnumeric(rs.scantimestamp) scantime_number,
       bu.code businessunitcode, bu.businessunit_id,
       bu.description businessunitdesc, mre.multireadexceptionreason_id,
       coalesce((select mred.description
                   from multireadexceptionreason_desc mred
                  where mre.multireadexceptionreason_id = mred.multireadexceptionreason_id
                    and mred.language_id = languages.language_id), mre.factorydescription) reason_code,
       languages.code languagecode, bug.usergroup_id, rs.rejectedscan_id
  from rejectedscan rs
  join businessunit bu on rs.businessunit_id = bu.businessunit_id
  join businessunitsperusergroup bug on bu.businessunit_id = bug.businessunit_id
  join systemuser sy on rs.systemuser_id = sy.systemuser_id
  join transactiontype tt on rs.transactiontype_id = tt.transactiontype_id
  join multireadexceptionreason mre on rs.multireadexceptionreason_id = mre.multireadexceptionreason_id
 cross join languages
/

  CREATE OR REPLACE VIEW "V_RENTALQTYADJUSTMENT" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "ADJUSTMENTDATE", "QUANTITY", "REMARK", "REASONCODE", "REASONCODEDESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION,
DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION,
PRODUCT.CODE,
(select description from product_desc a where a.product_id = product.product_id and a.language_id = languages.language_id) product_desc,
SIZEDEFINITION.CODE,
(select description from SIZEDEFINITION_desc b where b.SIZEDEFINITION_id = SIZEDEFINITION.SIZEDEFINITION_id and b.language_id = languages.language_id) SIZEDEFINITION_desc,
FINISHINGMETHOD.CODE,
(select description from FINISHINGMETHOD_desc c where c.FINISHINGMETHOD_id = FINISHINGMETHOD.FINISHINGMETHOD_id and c.language_id = languages.language_id) FINISHINGMETHOD_desc,
RENTALQTYADJUSTMENT.ADJUSTMENTDATE, RENTALQTYADJUSTMENT.QUANTITY, RENTALQTYADJUSTMENT.REMARK,
REASONCODE.CODE,
(select description from REASONCODE_desc d where d.REASONCODE_id = REASONCODE.REASONCODE_id and d.language_id = languages.language_id) REASONCODE_desc,
RENTALQTYADJUSTMENT.SYSTEMUSER_ID,
RENTALQTYADJUSTMENT. TIMESTAMP, languages.code languagecode
	FROM
CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT,
PRODUCT,SIZEDEFINITION,
FINISHINGMETHOD,  RENTALQTYADJUSTMENT, PRODUCTLISTPERDISTRIBPOINT, REASONCODE, languages
WHERE RENTALQTYADJUSTMENT.PRODUCTLISTPERDISTRIBPOINT_ID = PRODUCTLISTPERDISTRIBPOINT.PRODUCTLISTPERDISTRIBPOINT_ID
and PRODUCTLISTPERDISTRIBPOINT.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
and DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
and DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
and PRODUCTLISTPERDISTRIBPOINT.PRODUCT_ID = PRODUCT.PRODUCT_ID
and PRODUCTLISTPERDISTRIBPOINT.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
and PRODUCTLISTPERDISTRIBPOINT.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
AND RENTALQTYADJUSTMENT.REASONCODE_ID = REASONCODE.REASONCODE_ID
/

  CREATE OR REPLACE VIEW "V_RENTALUNITSAPPENDIX" ("UNIQUEITEMLOSS_ID", "UNIQUEITEM_LINK_ID", "CUSTOMERNUMBER", "NAME", "DEPARTMENTNUMBER", "DESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "COSTCENTERCODE", "COSTCENTERDESCRIPTION", "LOSSINVOICEHEADER_ID", "INVOICEHEADER_ID", "INVOICENUMBER", "INVOICEDATE", "INVOICEBUSINESSUNIT_ID", "INVOICEFREQUENCY_ID", "CLUSTER_ID", "CURRENCYCODE", "PERIODENDDATE", "YEAR", "PERIOD", "DAYSINPERIOD", "CHARGETYPE", "OUTSCANDATE", "RETURNEDDATE", "DAYSOFUSE", "PRODUCTCODE", "PRODUCTDESCRIPTION", "PRIMARYID", "AMOUNT") AS 
  select uil.uniqueitemloss_id, --loss charges
       uil.uniqueitem_link_id,
       cl.customernumber,
       cl.name,
       dl.departmentnumber,
       dl.description,
       dpl.distributionpointnumber,
       dpl.description distributionpointdescription,
       (select cc.code
          from costcenter cc, distributionpoint dp
         where dp.costcenter_id = cc.costcenter_id
           and dpl.distributionpoint_id = dp.distributionpoint_id) costcentercode,
       (select cc.description
          from costcenter cc, distributionpoint dp
         where dp.costcenter_id = cc.costcenter_id
           and dpl.distributionpoint_id = dp.distributionpoint_id) costcenterdescription,
       uil.lossinvoiceheader_id,
       ih.invoiceheader_id,
       ih.invoicenumber,
       ih.invoicedate,
       ih.invoicebusinessunit_id,
       ih.invoicefrequency_id,
       ih.cluster_id,
       (select c.code from currency c where c.currency_id = ih.currency_id) currencycode,
       lp.periodenddate,
       lp.year,
       lp.period,
       lp.daysinperiod,
       2 chargetype,
       uil.outscandate,
       uil.returneddate,
       (case
         when uil.returneddate = to_date('31-12-2099', 'dd-mm-yyyy') then
          trunc(lp.periodenddate) - trunc(uil.outscandate) + 1
         else
          trunc(uil.returneddate) - trunc(uil.outscandate) + 1
       end) daysofuse,
       p.code productcode,
       (select pd.description
          from product_desc pd, customer c
         where pd.product_id = ui.product_id
           and c.customer_id = cl.customer_id
           and pd.language_id = c.language_id) productdescription,
       ui.primaryid,
       uil.lossamount amount
  from uniqueitemloss         uil,
       invoiceheader          ih,
       customer_link          cl,
       distributionpoint_link dpl,
       department_link        dl,
       lossperiods            lp,
       uniqueitem             ui,
       product                p
 where uil.lossinvoiceheader_id = ih.invoiceheader_id
   and uil.customer_link_id = cl.customer_link_id
   and uil.distributionpoint_link_id = dpl.distributionpoint_link_id
   and dpl.department_link_id = dl.department_link_id
   and uil.lossperiods_id = lp.lossperiods_id
   and uil.uniqueitem_link_id = ui.uniqueitem_id
   and ui.product_id = p.product_id
/

  CREATE OR REPLACE VIEW "V_REPAIRHISTORY" ("YEAR", "WEEK", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "GROUPINGNO", "WEARERNUMBER", "WEARERNAME", "DISTRIBUTIONPOINTNUMBER", "DISTPOINTDESC", "REPAIRCODE", "REPAIRDESC", "MINUTES", "UNITPRICE", "PRICEPERMINUTE", "AMOUNT", "INVOICEHEADER_ID", "LANGUAGECODE", "LANGUAGE_ID", "CATEGORY", "QUANTITY", "CUSTOMEROWNED") AS 
  select /*version 1.0*/
       rh.year, rh.week, dep.departmentnumber, dep.description departmentdesc,
       (case
         when (rt.category = 1 and rh.weareremployment_link_id is not null) then
          1
         when (rt.category = 1 and rh.weareremployment_link_id is null) then
          2
         when (rt.category = 2 and rh.weareremployment_link_id is not null) then
          3
         when (rt.category = 2 and rh.weareremployment_link_id is null) then
          4
         else
          5
       end) groupingno,
       wel.wearernumber, wel.wearername,
       dp.distributionpointnumber, dp.description distpointdesc, rt.code repaircode,
       (select rtd.description
          from repairtype_desc rtd
         where rtd.repairtype_id = rh.repairtype_id
           and rtd.language_id = lan.language_id) repairdesc, rh.minutes, rh.unitprice,
       rh.priceperminute, rh.amount, rh.invoiceheader_id, lan.code languagecode,
       lan.language_id, rt.category, rh.quantity, rh.customerowned
  from repairhistory rh
       left join weareremployment_link wel on rh.weareremployment_link_id = wel.weareremployment_link_id
       left join distributionpoint_link dp
            left join department_link dep on dp.department_link_id = dep.department_link_id
       on rh.distributionpoint_link_id = dp.distributionpoint_link_id
       join repairtype rt on rh.repairtype_id = rt.repairtype_id
       cross join languages lan
 where rh.status = 0
   and rh.amount <> 0
/

  CREATE OR REPLACE VIEW "V_REPAIRHISTORYPERCUSTOMER" ("LINETYPE", "REPAIRHISTORY_ID", "QUANTITY", "YEAR", "WEEK", "YEARWEEK", "CUSTOMERNUMBER", "CUSTOMERNAME", "CHAIN_CODE", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "WEARERNUMBER", "WEARERNAME", "FUNCTIONCODE", "REPAIRTYPECODE", "STATUS", "REPAIRTYPEDESC", "MINUTES", "UNITPRICE", "PRICEPERMINUTE", "AMOUNT", "INVOICEAMOUNTDECIMALS", "INVOICEHEADER_ID", "CITY", "LANGUAGECODE", "PLANT_NAME", "BUSINESSUNIT_ID", "CUSTOMERBU_ID", "REPAIRDATE", "PRIMARYID") AS 
  select
  1 linetype, a.repairhistory_id, a.quantity, a.year, a.week, (a.year * 100 + a.week) yearweek,
  cl.customernumber, cl.name customername,
  (select ch.code from chain ch where ch.chain_id = cs.chain_id) chain_code,
  e.departmentnumber, e.description departmentdesc,
  NULL distributionpointnumber, NULL distributionpointdesc,
  wl.wearernumber, wl.wearername,
  wf.code functioncode,
  p.code repairtypecode, a.status,
  (select z.description from repairtype_desc z where z.repairtype_id = a.repairtype_id
    and z.language_id = languages.language_id) repairtypedesc,
  a.minutes, a.unitprice, a.priceperminute, a.amount, cr.invoiceamountdecimals,
  a.invoiceheader_id, ad.city, languages.code languagecode
, (SELECT pl.name FROM plant pl, businessunit bu WHERE a.businessunit_id = bu.businessunit_id AND bu.plant_id = pl.plant_id)  Plant_Name
, a.businessunit_id
, COALESCE(cs.defaultbusinessunit_id, a.businessunit_id) customerbu_id
, a.repairdate, --a.primaryid
coalesce((select ui.primaryid from uniqueitem ui, uniqueitem_link ul where ui.uniqueitem_id = ul.uniqueitem_id and ul.uniqueitem_link_id = a.uniqueitem_link_id )
        ,(select ri.primaryid from raggeditem ri, uniqueitem_link ul where ri.raggeditem_id = ul.raggeditem_id and ul.uniqueitem_link_id = a.uniqueitem_link_id)) PRIMARYID
from
  repairhistory a, --left outer join currency cr on a.currency_id = cr.currency_id,
  weareremployment_link wl
    left outer join weareremployment we
      left outer join wearerfunction wf on we.wearerfunction_id = wf.wearerfunction_id
    on wl.weareremployment_id = we.weareremployment_id,
  distributionpoint_link d, department_link e, repairtype p,
  customer_link cl
    left outer join (customer cs
      inner join address ad on cs.visitaddress_id = ad.address_id
      inner join currency cr on cs.currency_id = cr.currency_id)
    on cl.customer_id = cs.customer_id,
  languages
where
  wl.distributionpoint_link_id = d.distributionpoint_link_id
  and d.department_link_id = e.department_link_id
  and a.repairtype_id = p.repairtype_id
  and a.customer_link_id = cl.customer_link_id
  and a.weareremployment_link_id = wl.weareremployment_link_id
UNION ALL --there is no need for a distinct union since first branch HAS wearers and second one has NULL wearers
select
  2 linetype, a.repairhistory_id, a.quantity, a.year, a.week, (a.year * 100 + a.week) yearweek,
  cl.customernumber, cl.name customername,
  (select ch.code from chain ch where ch.chain_id = cs.chain_id) chain_code,
  e.departmentnumber, e.description departmentdesc,
  d.distributionpointnumber, d.description distributionpointdesc,
 NULL wearernumber, NULL wearername,
  NULL functioncode,
  p.code repairtypecode, a.status,
  (select z.description from repairtype_desc z where z.repairtype_id = a.repairtype_id
    and z.language_id = languages.language_id) repairtypedesc,
  a.minutes, a.unitprice, a.priceperminute, a.amount, cr.invoiceamountdecimals,
  a.invoiceheader_id, ad.city, languages.code languagecode
, (SELECT pl.name FROM plant pl, businessunit bu WHERE a.businessunit_id = bu.businessunit_id AND bu.plant_id = pl.plant_id)  Plant_Name
, a.businessunit_id
, COALESCE(cs.defaultbusinessunit_id, a.businessunit_id) customerbu_id
, a.repairdate, --a.primaryid
coalesce((select ui.primaryid from uniqueitem ui, uniqueitem_link ul where ui.uniqueitem_id = ul.uniqueitem_id and ul.uniqueitem_link_id = a.uniqueitem_link_id )
        ,(select ri.primaryid from raggeditem ri, uniqueitem_link ul where ri.raggeditem_id = ul.raggeditem_id and ul.uniqueitem_link_id = a.uniqueitem_link_id)) PRIMARYID
from
  repairhistory a,
  distributionpoint_link d, department_link e, repairtype p,
  customer_link cl
    left outer join (customer cs
      inner join address ad on cs.visitaddress_id = ad.address_id
      inner join currency cr on cs.currency_id = cr.currency_id)
    on cl.customer_id = cs.customer_id,
  languages
where
  d.department_link_id = e.department_link_id
  and a.repairtype_id = p.repairtype_id
  and a.customer_link_id = cl.customer_link_id
  and a.weareremployment_link_id is null
  and a.distributionpoint_link_id = d.distributionpoint_link_id
  and e.customer_link_id = cl.customer_link_id
/

  CREATE OR REPLACE VIEW "V_REPAIRHISTORYPERPRODUCTUSER" ("BU_CODE", "BU_DESC", "BUSINESSUNIT_ID", "REPAIRHISTORY_ID", "YEAR", "WEEK", "MINUTES", "REPAIRDATE", "PRIMARYID", "PRODUCT_CODE", "PRODUCTGROUP_CODE", "PRODUCT_DESC", "USERNAME", "FULLNAME", "SYSTEMUSER_ID", "REPAIRTYPE_CODE", "REPAIRTYPE_DESC", "LANGUAGE_CODE", "LANGUAGE_ID") AS 
  select bu.code bu_code, bu.description bu_desc, bu.businessunit_id
       , rh.repairhistory_id, rh.year, rh.week, rh.minutes, rh.repairdate
       , ui.primaryid, pr.code product_code, pg.code productgroup_code
       , (select pd.description from product_desc pd where pd.product_id = pr.product_id and pd.language_id = lan.language_id) product_desc
       , su.username, su.fullname, su.systemuser_id, rt.code repairType_code
       , (select rd.description from repairtype_desc rd where rd.repairtype_id = rt.repairtype_id and rd.language_id = lan.language_id) repairtype_desc
       , lan.code language_code, lan.language_id
from businessunit bu, repairhistory rh
     left outer join uniqueitem ui
          inner join product pr
                left outer join productgroup pg on pr.productgroup_id = pg.productgroup_id
          on ui.product_id = pr.product_id
     on rh.uniqueitem_link_id = ui.uniqueitem_id,
     systemuser su, repairtype rt, languages lan
where rh.businessunit_id = bu.businessunit_id and rh.systemuser_id = su.systemuser_id
      and rh.repairtype_id = rt.repairtype_id
/

  CREATE OR REPLACE VIEW "V_REPAIRQUOTIENT" ("BUSINESSUNIT_ID", "REPAIRDATE", "CHAINCODE", "CHAINNAME", "NATIONALACCOUNTCODE", "NATIONALACCOUNTNAME", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "WEARERNAME", "WEARERSEARCHNAME", "PRODUCT_LINKCODE", "PRODUCT_DESC", "REPAIRTYPECODE", "REPAIRTYPE_DESC", "NROFWASHES", "MINUTES", "QUANTITY", "CUSTOMEROWNED", "STATUS", "LANGUAGECODE", "LANGUAGE_ID", "REPORTPARAM_ID") AS 
  select rh.businessunit_id, trunc(rh.repairdate) repairdate
, ch.code ChainCode, ch.name ChainName
, na.code NationalAccountCode, na.name NationalAccountName
, cu.customernumber, cu.name CustomerName
, w.wearernumber, w.wearername, w.wearersearchname
, pl.code Product_LinkCode
, (select pd.description from product_desc pd where rh.product_link_id = pd.product_id
  and pd.language_id = lan.language_id) Product_Desc
, rt.code RepairTypeCode
, (select rtd.description from repairtype_desc rtd where rt.repairtype_id = rtd.repairtype_id
  and rtd.language_id = lan.language_id) RepairType_Desc
, coalesce((select sum(dh.amountdelivered) from deliveryhistory dh
  where dh.processbusinessunit_id = rh.businessunit_id and dh.customer_link_id = cu.customer_id
        and dh.product_link_id = rh.product_link_id and dh.deliverydate >= rp.date_value1 and dh.deliverydate <= rp.date_value2)
        , 0) NrOfWashes
, rh.minutes, rh.quantity, rh.customerowned, rh.status
, lan.code languagecode, lan.language_id
, rp.reportparam_id
from repairhistory rh
     left outer join weareremployment_link w on rh.weareremployment_link_id = w.weareremployment_link_id
     inner join repairtype rt on rh.repairtype_id = rt.repairtype_id
     inner join product pl on rh.product_link_id = pl.product_id and pl.typeofmerchandise in (1, 2)
     inner join customer cu
           left outer join chain ch on cu.chain_id = ch.chain_id
           left outer join nationalaccount na on cu.nationalaccount_id = na.nationalaccount_id
     on rh.customer_link_id = cu.customer_id
, languages lan
, reportparam rp
where lan.code = rp.string_value and rh.businessunit_id = rp.number_value
      and trunc(rh.repairdate) >= rp.date_value1 and trunc(rh.repairdate) <= rp.date_value2
      and ((rp.string_value1 = ' ' and rp.string_value2 = 'ZZZZZZ')
          or (ch.code >= rp.string_value1 and ch.code <= rp.string_value2))
      and ((rp.string_value3 = ' ' and rp.string_value4 = 'ZZZZZZ')
          or(na.code >= rp.string_value3 and na.code <= rp.string_value3))
      and ((rp.number_value1 = 0 and rp.number_value2 = 999999999999)
          or (cu.customernumber >= rp.number_value1 and cu.customernumber <= rp.number_value2))
      and ((rp.number_value3 = 0 and rp.number_value4 = 999999999999)
          or (w.wearernumber >= rp.number_value3 and w.wearernumber <= rp.number_value4))
      and ((rp.string_value5 = ' ' and rp.string_value6 = 'ZZZZZZZZZZZZ')
          or (pl.code >= rp.string_value5 and pl.code <= rp.string_value6))
      and ((rp.string_value7 = ' ' and rp.string_value8 = 'ZZZZZZ')
          or (rt.code >= rp.string_value7 and rt.code <= rp.string_value8))
/

  CREATE OR REPLACE VIEW "V_REPLACEMENTLIST" ("ENDDATEFULLRENT", "DATEACTIVE", "DATEINACTIVE", "SALESAREA_CODE", "CUSTOMERNUMBER", "DEPARTMENTNUMBER", "WEARERNUMBER", "PRODGROUP_CODE", "PROD_CODE", "SEQUENCENUMBER", "SIZE_CODE", "PRIMARYID", "NAME", "DEPARTMENT_DESC", "DISTRIBUTIONPOINTNUMBER", "DISTRIBPOINT_DESC", "PROD_DESC", "FULLNAME", "SEARCHNAME", "FIRSTNAME", "BANK", "LOCKER", "LASTISSUEDATE", "DECIMALS", "EXCHANGERATE", "PURCHASEPRICE", "LANGUAGE_CODE", "BUSINESSUNIT_ID", "REPORTPARAM_ID") AS 
  select ufi.enddatefullrent, wr.dateactive, wr.dateinactive
       , sa.code SalesArea_code, cu.customernumber, dpt.departmentnumber, wr.wearernumber
       , pg.code ProdGroup_code, pr.code Prod_code
       , we.sequencenumber, sd.code Size_code, ui.primaryid, cu.name, dpt.description Department_desc
       , dip.distributionpointnumber, dip.description DistribPoint_desc
       , (select prd.description from product_desc prd where pr.product_id = prd.product_id and prd.language_id = lan.language_id) Prod_desc
       , wr.fullname, wr.searchname, wr.firstname, lo.bank, lo.locker, ufi.lastissuedate
       , pcu.decimals
       , case when pcu.currency_id <> su.currency_id then scu.exchangerate
         else 1
         end exchangerate
       , case when rp.string_value = 'Y'
         then /*(SELECT spp.purchaseprice
               FROM supplierproductprice spp, productsizepersupproduct psp, supplierproduct sp
               WHERE psp.product_id = pr.product_id and psp.sizedefinition_id = sd.sizedefinition_id and psp.supplierproduct_id = sp.supplierproduct_id
                     AND spp.supplierproduct_id = sp.supplierproduct_id and sp.supplier_id = pr.supplier_id
                     AND spp.startdate IN (SELECT MAX (spp.startdate)
                                           FROM supplierproductprice spp, productsizepersupproduct psp, supplierproduct sp
                                           WHERE psp.product_id = pr.product_id and psp.sizedefinition_id = sd.sizedefinition_id and psp.supplierproduct_id = sp.supplierproduct_id
                                           AND spp.supplierproduct_id = sp.supplierproduct_id and sp.supplier_id = pr.supplier_id
                                           AND spp.startdate < rp.date_value1))*/
              F_PURCHASEPRICE(pr.supplier_id, pr.product_id, sd.sizedefinition_id, rp.date_value1)
         else 0
         end purchaseprice
       , lan.code Language_code, bu.businessunit_id
       , rp.reportparam_id
from uniqueitem ui, uniqueitemnonpool unp, uniqueitemfixedinfo ufi, wearer wr, weareremployment we
     LEFT OUTER JOIN locker lo ON we.locker_id = lo.locker_id,
     department dpt, distributionpoint dip, customer cu, salesarea sa, productgroup pg, product pr, sizedefinition sd,
     supplier su, currency scu, currency pcu, plant pl, country co,
     languages lan, businessunit bu,
     reportparam rp
where unp.weareremployment_id = we.weareremployment_id and we.wearer_id = wr.wearer_id and wr.customer_id = cu.customer_id
      and cu.salesarea_id = sa.salesarea_id and dip.distributionpoint_id = we.distributionpoint_id and dip.department_id = dpt.department_id
      and ui.uniqueitem_id = unp.uniqueitem_id and ui.product_id = pr.product_id
      and pr.productgroup_id = pg.productgroup_id and ui.sizedefinition_id = sd.sizedefinition_id
      AND pr.supplier_id = su.supplier_id and su.currency_id = scu.currency_id
      AND ufi.uniqueitem_id = ui.uniqueitem_id
      and ufi.enddatefullrent >= rp.date_value1 and ufi.enddatefullrent <= rp.date_value2
      and bu.plant_id = pl.plant_id and pl.country_id = co.country_id and co.defaultcurrency_id = pcu.currency_id
      and rp.number_value = bu.businessunit_id
      and ((rp.number_value = cu.defaultbusinessunit_id) or
          exists (select * from customeractivities caa where caa.customer_id=cu.customer_id and caa.processbusinessunit_id = rp.number_value))
/

  CREATE OR REPLACE VIEW "V_REPORTORDER" ("WEBORDERNUMBER", "DELIVERYDATE", "WEBORDER_ID", "DAYDESC", "CUSTOMERREFERENCE", "QUANTITYORDERED", "WEBUSERDEPARTMENT_ID", "WEBUSER_ID", "WEBSESSION_ID", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "FM_CODE", "DISTRIBUTIONPOINTNUMBER", "DISTR_DESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEP_DESC", "DEPARTMENT_ID", "LANGUAGECODE") AS 
  select wo.webordernumber, wo.deliverydate, wo.weborder_id,
       (select dd.description from day_desc dd where dd.language_id = lan.language_id and dd.day_id =  getabsdaynumber(wo.deliverydate)) daydesc,
       wo.customerreference, wol.quantityordered,
       wd.department_id webuserdepartment_id,
       wu.webuser_id, wus.websession_id,
       (select p.code from product_link p where p.product_link_id = wol.product_link_id) productcode,
       (select pd.description from product_link_desc pd where wol.product_link_id = pd.product_link_id and pd.language_id = lan.language_id) productdesc,
       (select s.code from sizedefinition_link s where s.sizedefinition_link_id = wol.sizedefinition_link_id) sizecode,
       (select f.code from finishingmethod f where f.finishingmethod_id = wol.finishingmethod_id) fm_code,
       distr.distributionpointnumber, distr.description distr_desc,
       cl.customernumber, cl.name customername,
       dep.departmentnumber, dep.description dep_desc, dep.department_id ,
       lan.code languagecode
from weborder wo, weborderline wol, customer_link cl, languages lan,
     department dep , distributionpoint_link distr,
     webuser wu,
     webusercustomer wuc left outer join webuserdepartment wd on (wuc.webusercustomer_id=wd.webusercustomer_id) , --!!!
     webusersession wus
where wo.weborder_id = wol.weborder_id
      and wo.customer_link_id = cl.customer_link_id
      and wuc.customer_id = cl.customer_id
      and wuc.webuser_id = wu.webuser_id
      and dep.customer_id = cl.customer_id
      and distr.department_link_id = dep.department_id
      and wol.distributionpoint_link_id = distr.distributionpoint_link_id
      and wus.customer_id = cl.customer_id
/

  CREATE OR REPLACE VIEW "V_REPORTPARAM" ("REPORTPARAM_ID") AS 
  select distinct r.reportparam_id
from reportparam r
/

  CREATE OR REPLACE VIEW "V_REPORTRETURNEDITEMS" ("BUSINESSUNIT_ID", "CUSTOMER_LINK_ID", "STATUS_ID", "STATUSTYPE", "ROUTENUMBER", "STATUSCHANGEDATE", "CUSTOMERNUMBER", "STOPNUMBER", "PRODUCTCODE", "LANGUAGECODE", "SIZECODE", "SIZEDESC", "DAYSAGO", "STAYCHANGEDATE", "PRIMARYID", "SECONDARYID", "ROUTEDESCRIPTION", "CUSTOMERNAME", "EMPLOYEENAME", "EMPLOYEENUMBER", "PRODUCT_DESC", "DRIVINGDATE") AS 
  SELECT  DISTINCT BU.BUSINESSUNIT_ID,  SCAN.CUSTOMER_LINK_ID, S.STATUS_ID, S.STATUSTYPE, R.ROUTENUMBER, TRUNC(UI.STATUSCHANGEDATE) STATUSCHANGEDATE, C.CUSTOMERNUMBER, stop.stopnumber, P.CODE PRODUCTCODE, L.CODE LANGUAGECODE,
SD.CODE sizecode, (SELECT SDESC.DESCRIPTION FROM SIZEDEFINITION_DESC SDESC WHERE SDESC.LANGUAGE_ID=L.LANGUAGE_ID AND SDESC.SIZEDEFINITION_ID=SD.SIZEDEFINITION_ID) SIZEDESC,
(TRUNC(SYSDATE)-TRUNC(UI.STATUSCHANGEDATE)) DAYSAGO, TRUNC(ui.staychangedate) staychangedate, SCAN.PRIMARYID, SCAN.SECONDARYID, R.DESCRIPTION ROUTEDESCRIPTION, C.NAME CUSTOMERNAME, EMPL.NAME EMPLOYEENAME, EMPL.EMPLOYEENUMBER EMPLOYEENUMBER
, (select pd.description from product_desc pd where pd.product_id=p.product_id and pd.language_id=l.language_id) product_desc,
rc.drivingdate
FROM
UNIQUEITEM UI INNER JOIN BUSINESSUNIT BU ON UI.BUSINESSUNIT_ID=BU.BUSINESSUNIT_ID
INNER JOIN STATUS S ON (UI.STATUS_ID=S.STATUS_ID AND S.STATUSTYPE='UI' AND S.CODE=70)
JOIN SCAN ON (SCAN.UNIQUEITEM_LINK_ID = UI.UNIQUEITEM_ID AND TRUNC(SCAN.SCANTIMESTAMP)=trunc(UI.STATUSCHANGEDATE))
JOIN CUSTOMER C ON SCAN.CUSTOMER_LINK_ID=C.CUSTOMER_ID
LEFT OUTER JOIN ROUTE R ON SCAN.ROUTE_ID=R.ROUTE_ID
LEFT OUTER JOIN EMPLOYEE EMPL ON R.DRIVER_ID=EMPL.EMPLOYEE_ID
JOIN PRODUCT P ON UI.PRODUCT_ID=P.PRODUCT_ID
JOIN SIZEDEFINITION SD ON UI.SIZEDEFINITION_ID=SD.SIZEDEFINITION_ID
join routetransaction rt on rt.numbervalue1=ui.uniqueitem_id
join routecontrol rc on rt.routecontrol_id=rc.routecontrol_id
join stop on rt.stop_id=stop.stop_id
CROSS JOIN LANGUAGES L
where scan.transactiontype_id=18
/

  CREATE OR REPLACE VIEW "V_RESIDENTIALDELNOTELINE" ("PACKINGNOTE_ID", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZECODE", "FMCODE", "DELIVEREDAMOUNT", "REGUNITCODE", "CORRRDN", "LANGUAGECODE") AS 
  SELECT pn.packingnote_id, p.code productcode,
 (select description from product_desc pdesc where p.product_id = pdesc.product_id and pdesc.language_id = lan.language_id)  productdescription,
sd.code sizecode, fm.code fmcode, pnl.deliveredamount, ru.code regunitcode,
F_RDNCORRECTED(pn.packingnote_id)corrRDN, lan.code languagecode
  from packingnote pn, packingnoteline pnl, product p, sizedefinition sd, finishingmethod fm, registrationunit ru,languages lan
  where pn.packingnote_id=pnl.packingnote_id
  and pnl.product_id=p.product_id
  and pnl.sizedefinition_id=sd.sizedefinition_id
  and pnl.finishingmethod_id=fm.finishingmethod_id
  and p.registrationunit_id=ru.registrationunit_id
  and pn.origin=13
/

  CREATE OR REPLACE VIEW "V_RESIDENTIALREPAIRS" ("PRIMARYID", "BUSINESSUNIT_ID", "INVOICENUMBER", "NOTENUMBER", "QUANTITY", "DURATION", "AMOUNT", "INVOICEHEADER_ID", "DOCUMENTTYPE", "STARTTIMESTAMP", "SPECIFICUNITPRICE", "REPAIRTYPE_CODE", "LANGUAGECODE", "CLIENTNUMBER", "CLIENTNAME", "CLIENTDELIVERYNOTE_ID", "STATUS", "PRODUCT_CODE", "PRODUCT_DESC", "REPAIRTYPE_DESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "PRINT_ID_CODE", "CURRENCY_DECIMALS") AS 
  select uri.primaryid, uri.businessunit_id, ih.invoicenumber, cdn.clientdeliverynotenumber notenumber,
       rr.quantity, rr.duration, rr.amount, rr.invoiceheader_id, ih.documenttype, rr.starttimestamp, rr.specificunitprice,
       rt.code repairtype_code, lan.code languagecode, cl.clientnumber, cl.name clientname, cdn.clientdeliverynote_id, rr.status,
       (select p.code from product p join uniqueresidentialitemproduct urip on urip.product_id = p.product_id and urip.uniqueresidentialitem_id = uri.uniqueresidentialitem_id) product_code,
       (select pd.description from product_desc pd join uniqueresidentialitemproduct urip on urip.product_id = pd.product_id
                                                   where urip.uniqueresidentialitem_id = uri.uniqueresidentialitem_id and pd.language_id = lan.language_id) product_desc,
       (select rtd.description from repairtype_desc rtd where rtd.repairtype_id = rt.repairtype_id and rtd.language_id = lan.language_id) repairtype_desc,
       (select c.customernumber from customer c where c.customer_id = cl.customer_id) customernumber,
       (select c.name from customer c where c.customer_id = cl.customer_id) customername,
       (select crs.printidcode from customerresidentialsettings crs where crs.customer_id = cl.customer_id) print_id_code,
       (select crc.decimals from currency crc where crc.currency_id = ih.currency_id) currency_decimals
from uniqueresidentialitem uri
     join client cl on cl.client_id = uri.client_id
     join residentialrepair rr on uri.uniqueresidentialitem_id = rr.uniqueresidentialitem_link_id
          left outer join invoiceheader ih on ih.invoiceheader_id = rr.invoiceheader_id
          left outer join clientdeliverynote cdn on cdn.clientdeliverynote_id = rr.clientdeliverynote_id
     join repairtype rt on rt.repairtype_id = rr.repairtype_id,
     languages lan
where rt.repairusage <> 1
/

  CREATE OR REPLACE VIEW "V_RESIDENTIALSCANS" ("BUSINESSUNIT_ID", "YEAR", "WEEK", "BATCHNUMBER", "BATCH_ID", "DAYDESC", "SEQUENCENUMBER", "CLIENTDELIVERYNOTENUMBER", "CLIENTDELIVERYNOTE_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_ID", "DEPARTMENTNUMBER", "CLIENTNUMBER", "CLIENTNAME", "ROOMNUMBER", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "FINMETHCODE", "FINMETHDESC", "QTYSCANNEDIN", "QTYSCANNEDOUT", "CLIENTDELIVERYNOTELINE_ID", "PRIMARYID", "TRANSACTIONTYPE_ID", "SCANTIMESTAMPCH", "SCANTIMESTAMP", "SCANDATE", "LANGUAGECODE") AS 
  select ris.businessunit_id,
  b.year, b.week, b.batchnumber, b.batch_id,
  (select dd.description from day_desc dd where b.day_id = dd.day_id
     and dd.language_id = languages.language_id) daydesc,
  cdn.sequencenumber, cdn.clientdeliverynotenumber, cdn.clientdeliverynote_id,
  cu.customernumber, cu.name customername, cu.customer_id,
  d.departmentnumber,
  cl.clientnumber, coalesce(cl.name, cdn.name) clientname,
  cdn.roomnumber,
  p.code productcode,
  (select pd.description from product_link_desc pd where pd.product_link_id = p.product_link_id
     and pd.language_id = languages.language_id) productdesc,
  s.code sizecode,
  f.code finmethcode,
  (select fd.description from finishingmethod_desc fd where fd.finishingmethod_id = f.finishingmethod_id
     and fd.language_id = languages.language_id) finmethdesc,
  cdl.qtyscannedin, cdl.qtyscannedout, cdl.clientdeliverynoteline_id,
  ris.primaryid, ris.transactiontype_id,
	to_char(ris.scantimestamp, 'DD.MM.YYYY HH24.MI.SS') scantimestampch,
	ris.scantimestamp,
  trunc(ris.scantimestamp) scandate,
  languages.code languagecode
from batch b, clientdeliverynote cdn, customer_link cu,
  client_link cl
    left outer join (clientresident cr
      left outer join (departmentroom dr
        left outer join department d on d.department_id = dr.department_id)
      on dr.departmentroom_id = cr.departmentroom_id)
    on cl.client_id = cr.client_id,
  clientdeliverynoteline cdl, product_link p, sizedefinition_link s, finishingmethod f,
  residentialitemscan ris,
  languages
where b.batch_id = cdn.batch_id
  and cdn.customer_link_id = cu.customer_id
  and cdn.client_link_id = cl.client_id
  and cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
  and cdl.product_link_id = p.product_link_id
  and cdl.sizedefinition_link_id = s.sizedefinition_link_id
  and cdl.finishingmethod_id = f.finishingmethod_id
  and cdl.clientdeliverynoteline_id = ris.clientdeliverynoteline_id
  AND RIS.BATCH_ID is not null
--  and ris.transactiontype_id in (1, 2, 6)
/

  CREATE OR REPLACE VIEW "V_RESIDENTIALSCANSTATISTICS" ("RESIDENTIALITEMSCAN_ID", "BU_CODE", "BU_DESC", "TRANSACTIONTYPE_CODE", "TRANSACTIONTYPE_ID", "TRANSACTIONTYPE_DESC", "SCANSTATION", "PRIMARYID", "CUSTOMERNUMBER", "NAME", "WORKSTATION_DESC", "EMPLOYEENUMBER", "EMPLOYEE_NAME", "TIMESTAMP", "SCANTIMESTAMP", "USERGROUP_ID", "USERNAME", "LANGUAGE_CODE", "SCANDATE") AS 
  select RIS.RESIDENTIALITEMSCAN_ID,
       BU.Code Bu_code, BU.Description BU_desc, TAT.FACTORYDESCRIPTION TransactionType_code, Ris.Transactiontype_Id,
       (select ttd.description from TransactionType_Desc TTD where tat.transactiontype_id = ttd.transactiontype_id and ttd.language_id = lan.language_id) TransactionType_desc,
       RIS.Scanstation, RIS.Primaryid, CU.CUSTOMERNUMBER, CU.Name,
       (select ws.description from workstation ws where ris.scanstation = ws.code) Workstation_desc,
     ( case when ris.employeenumber=0 and emp.employeenumber<>0 then emp.employeenumber
        else ris.employeenumber end ) employeenumber,
      Emp.Name Employee_name,
       RIS.Timestamp, RIS.Scantimestamp, UG.Usergroup_Id, SU.Username, LAN.Code Language_code, trunc(RIS.Scantimestamp) scandate
from ResidentialItemScan RIS
     left outer join Customer CU on RIS.Customer_Link_Id = Cu.Customer_Id
     left outer join Systemuser SU on ris.systemuser_id=su.systemuser_id
     left outer join employee emp on su.employee_id=emp.employee_id
     , TransactionType TAT, BusinessUnit BU, UserGroup UG,  Languages LAN
where ris.transactiontype_id = tat.transactiontype_id and ris.systemuser_id = su.systemuser_id
      and ris.businessunit_id = bu.businessunit_id
      and exists (select * from Businessunitsperusergroup BUG
                 where BUG.BUSINESSUNIT_ID = RIS.BusinessUnit_ID and BUG.USERGROUP_ID = UG.Usergroup_Id)
/

  CREATE OR REPLACE VIEW "V_RESIDUALVALUECHARGES" ("CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "REASONCODE", "REASONDESC", "PRODECTLKCODE", "PRODECTLKDESC", "OUTOFCIRCDATE", "STATUS", "PRIMARYID", "AMOUNT", "FORBUSINESSUNIT_ID", "LANGUAGECODE", "PROCESSBUSINESSUNIT_ID") AS 
  select distinct cu.customer_id,  cu.customernumber, cu.name customerName, address.city, rc.code reasonCode
, rc_d.description reasonDesc
, prd_lk.code prodectLKcode
, prd_lk_d.description prodectLKdesc
, trunc(och.outofcircdate) outofcircdate, och.status
, och.primaryid, sum(och.amount) amount
, och.forbusinessunit_id, lan.code languageCode
, och.processbusinessunit_id
from
  languages lan
  inner join OutOfCirculationHistory och on och.chargetype = 1
  inner join customer cu
        inner join address on cu.visitaddress_id = address.address_id
  on och.customer_link_id = cu.customer_id
  inner join reasoncode rc on och.reasoncode_id = rc.reasoncode_id
  left outer join reasoncode_desc rc_d on rc_d.reasoncode_id = och.reasoncode_id and rc_d.language_id = lan.language_id
  inner join product_link prd_lk on och.product_link_id = prd_lk.product_link_id
  left outer join product_link_desc prd_lk_d on prd_lk_d.product_link_id = och.product_link_id and prd_lk_d.language_id = lan.language_id
where rc.garmentreason = 'Y'
        and rc.invoiceadjustment <> 1 -- no invoice header adjustment reasons
            and rc.inventorytrigger not in (4, 7, 8) -- no flat rate adj or kill loss charge
group by cu.customer_id,
  cu.customernumber, cu.name, address.city
, rc.code
, rc_d.description
, prd_lk.code, prd_lk_d.description
, trunc(och.outofcircdate)
, och.status
, och.primaryid
, och.forbusinessunit_id--, languages.language_id
, lan.code
, och.processbusinessunit_id-- HAVING ( och.status = 1 AND  sum(och.amount)<>0 ) OR och.status <> 1 -- ! --
/

  CREATE OR REPLACE VIEW "V_RESIDUALVALUEPERWEARERPROD" ("CUSTOMERNUMBER", "CUSTOMERNAME", "STREET", "ZIPCODE", "CITY", "WEARERINVENTORY_ID", "WEARERNUMBER", "WEARERFULLNAME", "WEARERFIRSTNAME", "WEARERSEARCHNAME", "PRODUCT_ID", "PRODUCTCODE", "SIZECODE", "DATEACTIVE", "DATEINACTIVE", "PRODUCTDESC", "QTYTOBERETURNEDREPLACEMENT", "QTYTOBERETURNEDDECREASEMAX", "UNIQUEITEM_ID", "PRIMARYID", "LASTISSUEDATE", "DAYSINCIRCPREVISSUE", "LASTSCANDATE", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE", "WASHESTOTAL", "REWASHTOTAL", "REPAIRSTOTAL", "LAST_TRANSACTION") AS 
  select /*version 1.1*/
       cu.customernumber, cu.name customername, vad.street, vad.zipcode, vad.city, weinv.wearerinventory_id, we.wearernumber,
       we.fullname wearerfullname, we.firstname wearerfirstname, we.searchname wearersearchname,
       prd.product_id, prd.code productcode, sz.code sizecode, weinv.dateactive, weinv.dateinactive,
       (select prde.description
          from product_desc prde
         where prde.product_id = prd.product_id
           and prde.language_id = lan.language_id) productdesc, weinv.qtytobereturnedreplacement,
       coalesce(weinv.qtytobereturneddecreasemax, 0) +
       coalesce((select count(*)
                   from uniqueitemflag uif, automaticflag afl
                  where uqnp.uniqueitem_id = uif.uniqueitem_id
                    and uif.flag_id = afl.flag_id
                    and afl.event = 'Return to stock because of decrease max inventory'), 0) qtytobereturneddecreasemax,
       uq.uniqueitem_id, uq.primaryid, uqfx.lastissuedate, uqfx.daysincircprevissue, uq.lastscandate,
       cur.invoiceamountdecimals, lan.code languagecode, uq.washestotal, uq.rewashtotal, uq.repairstotal,
       (select tt.factorydescription
          from scan sc
               join transactiontype tt
               on sc.transactiontype_id = tt.transactiontype_id
         where sc.uniqueitem_link_id = uqnp.uniqueitem_id
         order by sc.scantimestamp desc
         fetch first 1 rows only) last_transaction
  from uniqueitemnonpool uqnp
       join uniqueitemfixedinfo uqfx on uqnp.uniqueitem_id = uqfx.uniqueitem_id
       join uniqueitem uq
            join product prd on uq.product_id = prd.product_id
            join sizedefinition sz on uq.sizedefinition_id = sz.sizedefinition_id
       on uqnp.uniqueitem_id = uq.uniqueitem_id
       join wearerinventory weinv
            join weareremployment wey
                 join wearer we
                      join customer cu
                           join address vad on cu.visitaddress_id = vad.address_id
                           join currency cur on cu.currency_id = cur.currency_id
                      on we.customer_id = cu.customer_id
                 on wey.wearer_id = we.wearer_id
            on weinv.weareremployment_id = wey.weareremployment_id
       on uqnp.wearerinventory_id = weinv.wearerinventory_id and uqnp.weareremployment_id = weinv.weareremployment_id
       , languages lan
 where uq.customerowned = 'N'
/

  CREATE OR REPLACE VIEW "V_RESIDUALVALUEPOOLITEMS" ("CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "STREET", "ZIPCODE", "CITY", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "PRODUCT_ID", "PRODUCTCODE", "SIZECODE", "SIZEDESC", "PRODUCTDESC", "UNIQUEITEM_ID", "PRIMARYID", "LASTISSUEDATE", "DAYSINCIRCPREVISSUE", "LASTSCANDATE", "WASHESTOTAL", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE", "REPORTPARAM_ID", "DISPLAY_FLAG", "WEEKSINCIRC", "DEPRECIATION", "REPLACEMENTPRICE", "ISINVOICED") AS 
  select cu.customer_id, cu.customernumber, cu.name customername, cad.street, cad.zipcode, cad.city, dp.department_id, dp.departmentnumber,
       dp.description departmentdesc, prd.product_id, prd.code productcode, sz.code sizecode,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sz.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedesc,
       (select prde.description
          from product_desc prde
         where prde.product_id = prd.product_id
           and prde.language_id = lan.language_id) productdesc,
       uq.uniqueitem_id, uq.primaryid, uqfx.lastissuedate, uqfx.daysincircprevissue,
       uq.lastscandate, uq.washestotal, cur.invoiceamountdecimals, lan.code languagecode, rp.reportparam_id,
       (select p.code
           from (select fl.code, uif.uniqueitem_id, uif.startdate
                   from uniqueitemflag uif, flag fl
                  where fl.flag_id = uif.flag_id
                  order by fl.priority, fl.code) p
          where rownum = 1
            and p.uniqueitem_id = uq.uniqueitem_id
            and p.startdate >= rp.date_value1) display_flag,
       ceil((uqfx.daysincircprevissue + (rp.date_value1 - uqfx.lastissuedate)) / 7) weeksincirc,
       case
         when rsc.calculationbasis = 1 -- 1=weeks in use, 2=washes
          then
          get_depreciation_percent(rsc.residualvaluescheme_id, ceil((uqfx.daysincircprevissue + (rp.date_value1 - uqfx.lastissuedate)) / 7))
         else
          get_depreciation_percent(rsc.residualvaluescheme_id, uq.washestotal)
       end depreciation,
       pack_price.replacement_price(cu.customer_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, rp.date_value1) replacementprice,
       coalesce((select max(1)
                   from uniqueitemloss uil, invoiceheader ih
                  where uil.uniqueitem_link_id = uq.uniqueitem_id and uil.lossstatus = 1
                    and uil.lossinvoiceheader_id = ih.invoiceheader_id and ih.invoicenumber <> 0), 0) isInvoiced
  from uniqueitem uq
       left outer join finishingmethod fm on fm.finishingmethod_id = uq.finishingmethod_id
       join distributionpoint cp on uq.distributionpoint_id = cp.distributionpoint_id
       join department dp on cp.department_id = dp.department_id
       join customer cu on dp.customer_id = cu.customer_id
       join address cad on cu.visitaddress_id = cad.address_id
       join currency cur on cu.currency_id = cur.currency_id
       join uniqueitemfixedinfo uqfx on uq.uniqueitem_id = uqfx.uniqueitem_id
       join product prd on uq.product_id = prd.product_id
       join sizedefinition sz on uq.sizedefinition_id = sz.sizedefinition_id,
       residualvaluescheme rsc, reportparam rp, languages lan
 where uq.customerowned = 'N'
   and uq.poolitem = 1
   and prd.uniquepoolitem = 'Y'
   and uq.status_id in (select s1.status_id
                          from status s1
                         where s1.statustype = 'UI'
                           and s1.code in ('20', '30'))
   and uq.stay_id in (select s2.stay_id
                        from stay s2
                       where s2.staytype = 1
                         and s2.staynr in (20, 27))
   and cu.customernumber = rp.number_value
   and lan.code = rp.string_value
   and dp.departmentnumber >= rp.number_value1
   and dp.departmentnumber <= rp.number_value2
   and prd.code >= rp.string_value1
   and prd.code <= rp.string_value2
   and ((rp.string_value3 = ' ' and rp.string_value4 = 'ZZZZZZ') --no filter on Fin Meth
       or (fm.code >= rp.string_value3 and fm.code <= rp.string_value4))
   and
   (
       (rp.string_value7 <> ' ' and rp.string_value8 <> 'ZZZZZZ' and
        rsc.residualvaluescheme_id = coalesce((select max(plpc.residualvaluescheme_id)
                                               from productlistpercustomer plpc
                                              where plpc.customer_id = cu.customer_id
                                                and plpc.product_id = prd.product_id
                                                and (plpc.sizedefinition_id = sz.sizedefinition_id or
                                                    plpc.sizedefinition_id = (select sdi.sizedefinition_id from sizedefinition sdi where sdi.code = '*'))
                                                and plpc.finishingmethod_id = fm.finishingmethod_id
                                                and plpc.dateactive <= rp.date_value1
                                                and plpc.dateinactive >= rp.date_value1), prd.defaultresidualvaluescheme_id)
         and rsc.code >= rp.string_value7
         and rsc.code <= rp.string_value8)
     or
     (rp.string_value7 = ' ' and rp.string_value8 = 'ZZZZZZ' and
        rsc.residualvaluescheme_id = coalesce((select max(plpc.residualvaluescheme_id)
                                               from productlistpercustomer plpc
                                              where plpc.customer_id = cu.customer_id
                                                and plpc.product_id = prd.product_id
                                                and (plpc.sizedefinition_id = sz.sizedefinition_id or
                                                    plpc.sizedefinition_id = (select sdi.sizedefinition_id from sizedefinition sdi where sdi.code = '*'))
                                                and plpc.finishingmethod_id = fm.finishingmethod_id
                                                and plpc.dateactive <= rp.date_value1
                                                and plpc.dateinactive >= rp.date_value1), prd.defaultresidualvaluescheme_id))
     )
   and (
       (rp.string_value5 = ' ' and rp.string_value6 = 'ZZZZZZ') -- if all flags then no filter on items with a flag
       or (rp.string_value5 <> ' ' and rp.string_value6 <> 'ZZZZZZ' and -- if not all flags then only select uniqueitems that have a flag in the selected range
       exists (select 1
                 from uniqueitemflag uif, flag f
                where uif.uniqueitem_id = uq.uniqueitem_id
                  and f.flag_id = uif.flag_id
                  and uif.startdate >= rp.date_value1
                  and f.code >= rp.string_value5
                  and f.code <= rp.string_value6)) )
/

  CREATE OR REPLACE VIEW "V_RESIDUALVALUESCHEME" ("CODE", "RESIDUALVALUESCHEME_DESC", "CALCULATIONWEEKS", "CALCULATIONBASIS", "SYSTEMUSER_ID", "TIMESTAMP", "RESIDUALVALUESCHEME_ID", "LANGUAGECODE") AS 
  SELECT RESIDUALVALUESCHEME.CODE,
 ( SELECT DESCRIPTION FROM RESIDUALVALUESCHEME_DESC A WHERE A.RESIDUALVALUESCHEME_ID =  RESIDUALVALUESCHEME.RESIDUALVALUESCHEME_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) RESIDUALVALUESCHEME_DESC,
RESIDUALVALUESCHEME.CALCULATIONWEEKS, RESIDUALVALUESCHEME.CALCULATIONBASIS,
RESIDUALVALUESCHEME.SYSTEMUSER_ID, RESIDUALVALUESCHEME.TIMESTAMP, RESIDUALVALUESCHEME.RESIDUALVALUESCHEME_ID, LANGUAGES.CODE LANGUAGECODE
       FROM RESIDUALVALUESCHEME, LANGUAGES
/

  CREATE OR REPLACE VIEW "V_RESVALSCHEMEDEFINITION" ("CODE", "RESIDUALVALUESCHEME_DESC", "RANGESTART", "RANGEEND", "DEFINITIONTYPE", "FIXEDPERCENTAGE", "STARTPERCENTAGE", "ENDPERCENTAGE", "SYSTEMUSER_ID", "TIMESTAMP", "RESIDUALVALUESCHEME_ID", "LANGUAGECODE") AS 
  SELECT RESIDUALVALUESCHEME.CODE,
( SELECT DESCRIPTION FROM RESIDUALVALUESCHEME_DESC A WHERE A.RESIDUALVALUESCHEME_ID =  RESVALSCHEMEDEFINITION.RESIDUALVALUESCHEME_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) RESIDUALVALUESCHEME_DESC,
RESVALSCHEMEDEFINITION.RANGESTART, RESVALSCHEMEDEFINITION.RANGEEND,
RESVALSCHEMEDEFINITION.DEFINITIONTYPE,RESVALSCHEMEDEFINITION.FIXEDPERCENTAGE,
RESVALSCHEMEDEFINITION.STARTPERCENTAGE, RESVALSCHEMEDEFINITION.ENDPERCENTAGE,
RESVALSCHEMEDEFINITION.SYSTEMUSER_ID, RESVALSCHEMEDEFINITION.TIMESTAMP, RESVALSCHEMEDEFINITION.RESIDUALVALUESCHEME_ID,
LANGUAGES.CODE LANGUAGECODE
   FROM RESVALSCHEMEDEFINITION, RESIDUALVALUESCHEME, LANGUAGES
   WHERE RESVALSCHEMEDEFINITION.RESIDUALVALUESCHEME_ID = RESIDUALVALUESCHEME.RESIDUALVALUESCHEME_ID
/

  CREATE OR REPLACE VIEW "V_RETAINEDITEMS" ("IDCODE", "UNIQUEITEM_ID", "LANGUAGECODE", "PLANNEDDELIVERYDATE", "STAYNR", "LASTINSCAN_DATE", "LASTSCAN_DATE", "PRODUCTCODE", "DISTRIBUTIONPOINT_ID", "SIZEDEFINITIONCODE", "WEARERNUMBER", "WEARERNAME", "PRODUCTDESC", "BANKLOCKER") AS 
  select /*version 2.0*/
       ui.primaryid idcode, ui.uniqueitem_id, lan.code languagecode, ui.planneddeliverydate, s.staynr,
       ui.lastinscandate lastinscan_date, ui.lastscandate lastscan_date, prod.code productcode,
       wem.distributionpoint_id, sd.code sizedefinitioncode, we.wearernumber, we.fullname wearername,
       (select w.description
          from product_desc w
         where w.product_id = prod.product_id
           and w.language_id = lan.language_id) productdesc,
       (select concat(concat(lc.bank,'/'),lc.locker)
          from locker lc
         where lc.locker_id = wem.locker_id) banklocker
  from uniqueitem ui
       join uniqueitemnonpool uinp
            join weareremployment wem
                 join wearer we on wem.wearer_id = we.wearer_id
            on uinp.weareremployment_id = wem.weareremployment_id
       on ui.uniqueitem_id = uinp.uniqueitem_id
       join status st on ui.status_id = st.status_id
       join stay s on ui.stay_id = s.stay_id
       join product prod on ui.product_id = prod.product_id
       join sizedefinition sd on ui.sizedefinition_id = sd.sizedefinition_id
       cross join languages lan
 where ui.poolitem = 2
   and prod.typeofmerchandise = 2
   and st.statustype = 'UI'
   and s.staytype = 1 and s.staynr in (31, 32)
/

  CREATE OR REPLACE VIEW "V_RETURNRENTINCOME" ("PROCESSBUSINESSUNIT_ID", "BUSINESSUNITCODE", "BUSINESSUNITDESC", "MASTERACCOUNT_ID", "MASTERACCOUNTNUMBER", "MASTERACCOUNTNAME", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEARER_ID", "WEARERNUMBER", "WEARERNAME", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITION_ID", "SIZECODE", "SIZEDESCRIPTION", "FINISHINGMETHOD_ID", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "PRIMARYID", "OUTOFCIRCDATE", "RENTYEAR", "RENTWEEK", "RENTPRICESTARTDATE", "RENTPRICEENDDATE", "RENTPRICE", "LANGUAGE_ID", "LANGUAGECODE") AS 
  SELECT C.DEFAULTBUSINESSUNIT_ID PROCESSBUSINESSUNIT_ID,
       BU.CODE BUSINESSUNITCODE,
       BU.DESCRIPTION BUSINESSUNITDESC,
       C.MASTERACCOUNT_ID MASTERACCOUNT_ID,
       (SELECT CU.CUSTOMERNUMBER
          FROM CUSTOMER CU
         WHERE CU.CUSTOMER_ID = C.MASTERACCOUNT_ID) MASTERACCOUNTNUMBER,
       (SELECT CUS.NAME
          FROM CUSTOMER CUS
         WHERE CUS.CUSTOMER_ID = C.MASTERACCOUNT_ID) MASTERACCOUNTNAME,
       UIR.CUSTOMER_LINK_ID CUSTOMER_ID,
       CL.CUSTOMERNUMBER CUSTOMERNUMBER,
       CL.NAME CUSTOMERNAME,
       WE.WEARER_ID WEARER_ID,
       WEL.WEARERNUMBER WEARERNUMBER,
       WEL.WEARERNAME WEARERNAME,
       UIR.PRODUCT_LINK_ID PRODUCT_ID,
       PDL.CODE PRODUCTCODE,
       (SELECT PLD.DESCRIPTION
          FROM PRODUCT_LINK_DESC PLD
         WHERE PLD.PRODUCT_LINK_ID = UIR.PRODUCT_LINK_ID
           AND PLD.LANGUAGE_ID = LG.LANGUAGE_ID) PRODUCTDESCRIPTION,
       UIR.SIZEDEFINITION_LINK_ID SIZEDEFINITION_ID,
       SDL.CODE SIZECODE,
       (SELECT SLD.DESCRIPTION
          FROM SIZEDEFINITION_LINK_DESC SLD
         WHERE SLD.SIZEDEFINITION_LINK_ID = UIR.SIZEDEFINITION_LINK_ID
           AND SLD.LANGUAGE_ID = LG.LANGUAGE_ID) SIZEDESCRIPTION,
       UIR.FINISHINGMETHOD_ID FINISHINGMETHOD_ID,
       FM.CODE FINISHINGMETHODCODE,
       (SELECT FMD.DESCRIPTION
          FROM FINISHINGMETHOD_DESC FMD
         WHERE FMD.FINISHINGMETHOD_ID = UIR.FINISHINGMETHOD_ID
           AND FMD.LANGUAGE_ID = LG.LANGUAGE_ID) FINISHINGMETHODDESCRIPTION,
       COALESCE((SELECT UI.PRIMARYID
                  FROM UNIQUEITEM UI, UNIQUEITEM_LINK UIL
                 WHERE UI.UNIQUEITEM_ID = UIL.UNIQUEITEM_ID
                   AND UIL.UNIQUEITEM_ID IS NOT NULL
                   AND UIL.RAGGEDITEM_ID IS NULL
                   AND UIL.UNIQUEITEM_LINK_ID = UIR.UNIQUEITEM_LINK_ID),
                (SELECT RI.PRIMARYID
                   FROM UNIQUEITEM_LINK UIL, RAGGEDITEM RI
                  WHERE RI.RAGGEDITEM_ID = UIL.RAGGEDITEM_ID
                    AND UIL.UNIQUEITEM_ID IS NULL
                    AND UIL.RAGGEDITEM_ID IS NOT NULL
                    AND UIL.UNIQUEITEM_LINK_ID = UIR.UNIQUEITEM_LINK_ID)) PRIMARYID,
       UIR.OUTOFCIRCDATE OUTOFCIRCDATE,
       UIR.RENTYEAR RENTYEAR,
       UIR.RENTWEEK RENTWEEK,
       GETDATEFORWEEKYEAR(1, UIR.RENTWEEK, UIR.RENTYEAR) RENTPRICESTARTDATE,
       GETDATEFORWEEKYEAR(7, UIR.RENTWEEK, UIR.RENTYEAR) RENTPRICEENDDATE,
       PACK_PRICE.RENT_PRICE(UIR.CUSTOMER_LINK_ID,
                             UIR.PRODUCT_LINK_ID,
                             UIR.SIZEDEFINITION_LINK_ID,
                             UIR.FINISHINGMETHOD_ID,
                             GETDATEFORWEEKYEAR(7,
                                                UIR.RENTWEEK,
                                                UIR.RENTYEAR)) RENTPRICE,
       LG.LANGUAGE_ID LANGUAGE_ID,
       LG.CODE LANGUAGECODE
  FROM CUSTOMER              C,
       CUSTOMER_LINK         CL,
       BUSINESSUNIT          BU,
       UNIQUEITEMRETURNRENT  UIR,
       WEAREREMPLOYMENT      WE,
       WEAREREMPLOYMENT_LINK WEL,
       WEARER                W,
       PRODUCT_LINK          PDL,
       SIZEDEFINITION_LINK   SDL,
       FINISHINGMETHOD       FM,
       LANGUAGES             LG
 WHERE C.CUSTOMER_ID = CL.CUSTOMER_LINK_ID
   AND UIR.CUSTOMER_LINK_ID = CL.CUSTOMER_LINK_ID
   AND BU.BUSINESSUNIT_ID = C.DEFAULTINVOICEBUSINESSUNIT_ID
   AND C.CUSTOMER_ID = W.CUSTOMER_ID
   AND W.WEARER_ID = WE.WEARER_ID
   AND WE.WEAREREMPLOYMENT_ID = WEL.WEAREREMPLOYMENT_ID
   AND WEL.WEAREREMPLOYMENT_LINK_ID = UIR.WEAREREMPLOYMENT_LINK_ID
   AND UIR.PRODUCT_LINK_ID = PDL.PRODUCT_LINK_ID
   AND UIR.SIZEDEFINITION_LINK_ID = SDL.SIZEDEFINITION_LINK_ID
   AND UIR.FINISHINGMETHOD_ID = FM.FINISHINGMETHOD_ID
   AND UIR.RETURNRENTTYPE = 1
/

  CREATE OR REPLACE VIEW "V_REVENUEMAINTENANCEMON_AUX" ("DELTOCUSTOMER_LINK_ID", "MININVOICEDATE", "MAXINVOICEDATE") AS 
  select ih1.deltocustomer_link_id, min(ih1.invoicedate) MinInvoicedate, max(ih1.invoicedate) MaxInvoicedate
from invoiceheader ih1
where ih1.prebillamount <> 0
      and ih1.invoicedate >= trunc(sysdate)-28 and ih1.invoicedate <= trunc(sysdate)
group by ih1.deltocustomer_link_id
/

  CREATE OR REPLACE VIEW "V_REVENUEMAINTENANCEQT_AUX" ("DELTOCUSTOMER_LINK_ID", "MININVOICEDATE", "MAXINVOICEDATE") AS 
  select ih1.deltocustomer_link_id, min(ih1.invoicedate) MinInvoicedate, max(ih1.invoicedate) MaxInvoicedate
from invoiceheader ih1
where ih1.prebillamount <> 0
      and ih1.invoicedate >= trunc(sysdate)-91 and ih1.invoicedate <= trunc(sysdate)
group by ih1.deltocustomer_link_id
/

  CREATE OR REPLACE VIEW "V_REVENUEPERCUSTOMER" ("INVOICEDATE", "CURRENCYCODE", "DELTOCITY", "BILLTOCITY", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "PAYTHISAMOUNT", "TOTALAMOUNTEXCLVAT", "REPORTPARAM_ID", "PARENTINVOICEHEADER_ID", "INVOICEHEADER_ID", "MSCODE", "INV_WEEK", "INV_YEAR", "INV_MONTH", "DC_TOTALAMOUNT", "DC_TOTALINVOICEAMOUNTEXCLVAT", "BC_TOTALAMOUNT", "BC_TOTALINVOICEAMOUNTEXCLVAT", "DELIVERYZIPCODE") AS 
  select /*version 2.0*/
       ih.invoicedate, cr.code currencycode, ih.deltocity, ih.city billtocity, dcu.customernumber deltocustomernumber,
       dcu.name deltocustomername, bcu.customernumber billtocustomernumber, bcu.name billtocustomername, ih.paythisamount,
       ih.totalamountexclvat, rp.reportparam_id, ih.parentinvoiceheader_id, ih.invoiceheader_id, ms.code mscode,
       getisoweek(ih.invoicedate) inv_week,
       case when month(ih.invoicedate) = 12 and getisoweek(ih.invoicedate) = 1 then year(ih.invoicedate) + 1
            else year(ih.invoicedate)
        end inv_year,
       case when month(ih.invoicedate) = 12 and getisoweek(ih.invoicedate) = 1 then 1
            else month(ih.invoicedate)
        end inv_month,
       (select sum(ih1.paythisamount)
          from invoiceheader ih1
         where ih1.invoicedate between rp.date_value1 and rp.date_value2
           and ih1.deltocustomer_link_id = ih.deltocustomer_link_id
           and ih1.status_id = ih.status_id
           and ih1.documenttype = 1
           and ih1.invoicebusinessunit_id = ih.invoicebusinessunit_id) dc_totalamount,
       (select sum(ih1.totalamountexclvat)
          from invoiceheader ih1
         where ih1.invoicedate between rp.date_value1 and rp.date_value2
           and ih1.deltocustomer_link_id = ih.deltocustomer_link_id
           and ih1.status_id = ih.status_id
           and ih1.documenttype = 1
           and ih1.invoicebusinessunit_id = ih.invoicebusinessunit_id) dc_totalinvoiceamountexclvat,
       (select sum(ih1.paythisamount)
          from invoiceheader ih1
         where ih1.invoicedate between rp.date_value1 and rp.date_value2
           and ih1.billtocustomer_link_id = ih.billtocustomer_link_id
           and ih1.status_id = ih.status_id
           and ih1.documenttype = 1
           and ih1.invoicebusinessunit_id = ih.invoicebusinessunit_id) bc_totalamount,
       (select sum(ih1.totalamountexclvat)
          from invoiceheader ih1
         where ih1.invoicedate between rp.date_value1 and rp.date_value2
           and ih1.billtocustomer_link_id = ih.billtocustomer_link_id
           and ih1.status_id = ih.status_id
           and ih1.documenttype = 1
           and ih1.invoicebusinessunit_id = ih.invoicebusinessunit_id) bc_totalinvoiceamountexclvat,
       (select a.zipcode
          from address a
         where dcu.visitaddress_id = a.address_id) deliveryzipcode
  from invoiceheader ih
       join customer dcu
            join  marketsegment ms on dcu.marketsegment_id = ms.marketsegment_id
            join salesarea sa on dcu.salesarea_id = sa.salesarea_id
            join currency cr on dcu.currency_id = cr.currency_id
       on ih.deltocustomer_link_id = dcu.customer_id
       join customer bcu on ih.billtocustomer_link_id = bcu.customer_id
       join reportparam rp on ih.invoicedate between rp.date_value1 and rp.date_value2
                          and ih.invoicebusinessunit_id = rp.number_value1
                          and ih.billtocustomernumber between rp.number_value2 and rp.number_value4
       join status st on ih.status_id = st.status_id
                     and sa.code between rp.string_value1 and rp.string_value2
 where ih.documenttype = 1
   and st.code = '2'
/

  CREATE OR REPLACE VIEW "V_ROUTE" ("PLANTCODE", "PLANTNAME", "DRIVINGDAY", "ROUTENUMBER", "DESCRIPTION", "DEPOTCODE", "DEPOTDESCRIPTION", "CODEONLABEL", "DRIVERNUMBER", "DRIVERNAME", "TRUCKCODE", "TRUCKDESCRIPTION", "STARTTIME", "ENDTIME", "PACKINGDAY", "PACKINGDEADLINE", "LOADINGDOCK", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  SELECT PLANT.CODE, PLANT.NAME, DAY.DAYNUMBER, ROUTE.ROUTENUMBER, ROUTE.DESCRIPTION,
DEPOT.CODE, DEPOT.DESCRIPTION, ROUTE.CODEONLABEL, EMPLOYEE.EMPLOYEENUMBER, EMPLOYEE.NAME,
TRUCK.CODE, TRUCK.DESCRIPTION, ROUTE.STARTTIME, ROUTE.ENDTIME, PACKINGDAY.DAYNUMBER,
 ROUTE.PACKINGDEADLINE, ROUTE.LOADINGDOCK, ROUTE.SYSTEMUSER_ID, ROUTE.TIMESTAMP
       FROM ROUTE
       LEFT OUTER JOIN DEPOT ON (ROUTE.DEPOT_ID = DEPOT.DEPOT_ID)
       LEFT OUTER JOIN EMPLOYEE ON (ROUTE.DRIVER_ID = EMPLOYEE.EMPLOYEE_ID)
       LEFT OUTER JOIN TRUCK ON (ROUTE.TRUCK_ID = TRUCK.TRUCK_ID)
       LEFT OUTER JOIN DAY PACKINGDAY ON (ROUTE.PACKINGDAY_ID = PACKINGDAY.DAY_ID), PLANT,DAY
       WHERE ROUTE.PLANT_ID = PLANT.PLANT_ID
AND ROUTE.DRIVINGDAY_ID = DAY.DAY_ID
/

  CREATE OR REPLACE VIEW "V_ROUTEBANKDEPOSIT" ("BUSINESSUNIT_ID", "BU_CODE", "BU_DESC", "DRIVINGDATE", "INVOICEDATE", "FINALIZATIONTIMESTAMP", "CASHINDATE", "ROUTENUMBER", "ROUTE_DESC", "EMPLOYEENUMBER", "EMPLOYEENAME", "CASHAMOUNT", "CHECKAMOUNT", "DELBU_ID", "DELBU_CODE", "DELBU_DESC") AS 
  select ibu.businessunit_id, ibu.code bu_code, ibu.description bu_desc, rc.drivingdate,
       max(ih.invoicedate) invoicedate,
       max(ih.finalizationtimestamp) finalizationtimestamp,
       trunc(max(ih.finalizationtimestamp)) CashInDate,
       ro.routenumber, ro.description route_desc,
       coalesce(emp1.employeenumber, emp2.employeenumber) employeenumber,
       coalesce(emp1.name, emp2.name) employeename,
       sum(case when (ihe.checknumber is null and ih.cashcollected > 0)
                then ih.cashcollected
                else 0 end) CashAmount,
       sum(case when (ihe.checknumber is not null and ih.cashcollected > 0)
                then ih.cashcollected
                else 0 end) CheckAmount,
       delbu.businessunit_id delbu_id, delbu.code delbu_code, delbu.description delbu_desc
  from invoiceheader ih
       left join invoiceheaderextrainfo ihe on ih.invoiceheader_id = ihe.invoiceheader_id
       join routecontrol rc
            left join employee emp1 on rc.plant_id = emp1.plant_id and rc.drivernumber = emp1.employeenumber
            join route ro
                 left join employee emp2 on ro.driver_id = emp2.employee_id
            on rc.route_id = ro.route_id
       on ih.routecontrol_id = rc.routecontrol_id
       join businessunit ibu on ih.invoicebusinessunit_id = ibu.businessunit_id
       join customer del
            join businessunit delbu on del.defaultinvoicebusinessunit_id = delbu.businessunit_id
       on ih.deltocustomer_link_id = del.customer_id
group by ibu.businessunit_id, ibu.code, ibu.description, rc.drivingdate,
         ro.routenumber, ro.description, coalesce(emp1.employeenumber, emp2.employeenumber),
         coalesce(emp1.name, emp2.name), delbu.businessunit_id, delbu.code, delbu.description
/

  CREATE OR REPLACE VIEW "V_ROUTECOMPLETION" ("ROUTENUMBER", "DRIVINGDATE", "ROUTE_ID", "PLANT_ID", "POCKETPCSTATUS", "ROUTECONTROL_ID", "LANGUAGECODE", "PRODUCTCODE", "SIZECODE", "FMCODE", "STOPNUMBER", "STATUS", "SEQUENCENUMBER", "MOVEDDAYS", "ORIGINALDRIVINGDATE", "ORIGINALROUTENUMBER", "PRODUCTDESCRIPTION", "DELIVEREDQTY", "ORDEREDQTY", "RENTPRICE", "WASHPRICE", "QTYNOTDELIVERED", "QTYEXPECTED", "QTYRETURNED", "DELIVERYSCHEMEFREQUENCY", "CUSTOMERNUMBER", "CUSTOMERNAME", "DELIVERYADDRESS", "REASONCODEDESCRIPTION", "QUALITYGRADECODE") AS 
  select ro.routenumber, rc.drivingdate, rc.route_id, rc.plant_id, rc.pocketpcstatus, rc.routecontrol_id, lan.code languagecode
     , pr.code productcode, sd.code sizecode, fm.code fmcode, st.stopnumber, st.status
     , (select ps.sequencenumber from productsize ps where ps.product_id = pr.product_id and ps.sizedefinition_id = sd.sizedefinition_id) sequencenumber
     , (case when st.status = 2 then getdatediff((select rcc.drivingdate from routecontrol rcc join stop stop1 on stop1.routecontrol_id = rcc.routecontrol_id and stop1.movedtostop_id = st.stop_id), rc.drivingdate)
             when st.status = 3 then getdatediff(rc.drivingdate, (select rc2.drivingdate from routecontrol rc2 where exists
                                                                  (select stop2.stop_id from stop stop2 where stop2.movedtostop_id = st.stop_id and rc2.routecontrol_id = stop2.routecontrol_id)))
             else 0
        end) moveddays
     , (case when st.status = 2 then (select rcc.drivingdate from routecontrol rcc join stop stop3 on stop3.routecontrol_id = rcc.routecontrol_id and stop3.movedtostop_id = st.stop_id)
             when st.status = 3 then (select rc2.drivingdate from routecontrol rc2 where exists
                                                                 (select stop4.stop_id from stop stop4 where stop4.movedtostop_id = st.stop_id and rc2.routecontrol_id = stop4.routecontrol_id))
             else null
        end) originaldrivingdate
     , (case when st.status = 2 then (select r1.routenumber from route r1 join routecontrol rc1 on rc1.route_id = r1.route_id
                                                                          join stop stop5 on stop5.routecontrol_id = rc1.routecontrol_id
                                                                                          and stop5.movedtostop_id = st.stop_id)
             when st.status = 3 then (select r2.routenumber from routecontrol rc2 join route r2 on r2.route_id = rc.route_id and exists
                                                            (select stop6.stop_id from stop stop6 where stop6.movedtostop_id = st.stop_id and rc2.routecontrol_id = stop6.routecontrol_id))
             else 0
        end) originalroutenumber
     , (select pd.description from product_desc pd where pd.product_id = pr.product_id and pd.language_id = lan.language_id) productdescription
     , pnl.deliveredamount deliveredqty,(pnl.standardamount + pnl.variationamount) orderedqty
     , pack_price.rent_price(c.customer_id, pnl.product_id, pnl.sizedefinition_id, pnl.finishingmethod_id, rc.drivingdate) rentprice
     , pack_price.wash_price(c.customer_id, pnl.product_id, pnl.sizedefinition_id, pnl.finishingmethod_id, rc.drivingdate) washprice
     , (case when ((pnl.standardamount + pnl.variationamount) - pnl.deliveredamount) > 0 then ((pnl.standardamount + pnl.variationamount) - pnl.deliveredamount)
            else 0
       end) qtynotdelivered
     , ser.qtyexpected, ser.qtyreturned, ds.frequency deliveryschemefrequency, c.customernumber, c.name customername
     , (case when st.deliverypoint_id is not null then (select ads.street||' '||ads.city||' '||ads.zipcode from address ads join deliverypoint dp on dp.deliveryaddress_id = ads.address_id and dp.deliverypoint_id = st.deliverypoint_id)
             else (select ads.street||' '||ads.city||' '||ads.zipcode from address ads where ads.address_id = c.visitaddress_id)
        end ) deliveryaddress
     , (select rcd.description from reasoncode_desc rcd where rcd.reasoncode_id = st.reasoncode_id and rcd.language_id = lan.language_id) reasoncodedescription
     , (select max(gr.code) from qualitygrade gr join uniqueitemfixedinfo uif on uif.qualitygrade_id = gr.qualitygrade_id
                                            join deliveryscan dsc on dsc.uniqueitem_link_id = uif.uniqueitem_id and dsc.packingnote_id = pn.packingnote_id) qualitygradecode
from routecontrol rc
     join route ro on ro.route_id = rc.route_id
     join stop st on st.routecontrol_id = rc.routecontrol_id
     join packingnote pn on pn.stop_id = st.stop_id
     join packingnoteline pnl on pnl.packingnote_id = pn.packingnote_id
     left outer join packingnotelineperdelscheme pnlds on pnlds.packingnoteline_id = pnl.packingnoteline_id
     left outer join straightevenreturn ser on ser.packingnoteline_id = pnl.packingnoteline_id
     left outer join deliveryscheme ds on ds.deliveryscheme_id = ser.deliveryscheme_id
     join product pr on pr.product_id = pnl.product_id
     join sizedefinition sd on sd.sizedefinition_id = pnl.sizedefinition_id
     join finishingmethod fm on fm.finishingmethod_id = pnl.finishingmethod_id
     join customer c on c.customer_id = st.customer_link_id
,languages lan
where pn.status_id <> (select sts.status_id from status sts where sts.statustype = 'PN' and sts.code = '40') --cancel
and rc.pocketpcstatus = 2
and st.status <> 1
/

  CREATE OR REPLACE VIEW "V_ROUTECONTROL" ("ROUTENUMBER", "ROUTEDESCRIPTION", "ROUTELISTPRINTED", "SOILTICKETSPRINTED", "SOILCOUNTSTATUS", "SETTLEMENTSTATUS", "PACKINGSTATUS", "ORIGINALDRIVINGDATE", "DRIVINGDATE", "PACKINGDAYNUMBER", "OVERAGEAMOUNT", "VOUCHERAMOUNT", "TOTALCASHCOLLECTED", "TOTALCODDELAYED", "TOTALCODPAYTHISAMNT", "TOTALCODUNDELIVERED", "TOTALCODPLUSADJ", "TOTALCODMINUSADJ", "TOTALCODPREBILLED", "TOTALCHARGEPLUSADJ", "TOTALCHARGECOLLECTIONS", "TOTALCHARGEPAYTHISAMNT", "TOTALCHARGEUNDELIVERED", "TOTALCHARGEMINUSADJ", "TOTALCHARGEPREBILLED", "RETURNTIME", "RETURNDATE", "STARTTIME", "LOADINGDOCK", "PACKINGDEADLINE", "TRUCKCODE", "DRIVERNUMBER", "PLANTCODE", "PLANTNAME", "ROUTECONTROL_ID", "PLANTSTREET", "PLANTZIPCODE", "PLANTCITY", "PLANTSTREET2", "DEPOTCODE", "LANGUAGE_CODE", "DAY_DESCRIPTION", "EMPLOYEE_NAME") AS 
  select /*version 1.0*/
       ro.routenumber, ro.description routedescription, rc.routelistprinted, rc.soilticketsprinted,
       rc.soilcountstatus, rc.settlementstatus, rc.packingstatus, rc.originaldrivingdate, rc.drivingdate,
       d.daynumber packingdaynumber, rc.overageamount, rc.voucheramount, rc.totalcashcollected,
       rc.totalcoddelayed, rc.totalcodpaythisamnt, rc.totalcodundelivered, rc.totalcodplusadj,
       rc.totalcodminusadj, rc.totalcodprebilled, rc.totalchargeplusadj, rc.totalchargecollections,
       rc.totalchargepaythisamnt, rc.totalchargeundelivered, rc.totalchargeminusadj,
       rc.totalchargeprebilled, rc.returntime, rc.returndate, rc.starttime, rc.loadingdock,
       rc.packingdeadline, rc.truckcode, rc.drivernumber, pl.code plantcode, pl.name plantname,
       rc.routecontrol_id, pad.street plantstreet, pad.zipcode plantzipcode, pad.city plantcity,
       pad.street2 plantstreet2, de.code depotcode, l.code language_code,
       (select dd.description
          from day_desc dd
         where dd.day_id = getabsdaynumber(rc.drivingdate)
           and dd.language_id = l.language_id) day_description,
       (select emp.name
          from employee emp
         where emp.plant_id = rc.plant_id
           and emp.employeenumber = rc.drivernumber) employee_name
  from routecontrol rc
       left join day d on rc.packingday_id = d.day_id
       join plant pl
            join address pad on pl.address_id = pad.address_id
       on rc.plant_id = pl.plant_id
       join route ro
            left join depot de on ro.depot_id = de.depot_id
       on rc.route_id = ro.route_id
       cross join languages l
/

  CREATE OR REPLACE VIEW "V_ROUTEDEFINITION" ("PLANTCODE", "PLANTNAME", "DEPOTCODE", "DEPOTDESC", "BUSINESSUNITCODE", "BUSINESSUNITDESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "STREET", "STREET2", "CITY", "DAYNUMBER", "ZIPCODE", "DELIVERYSCHEMECODE", "ROUTENUMBER", "ROUTEDESC", "DAYDESC", "STOPNUMBER", "DELIVERYPOINTCODE", "DRIVER", "TRUCKCODE", "TRUCKDESC", "USERGROUPID", "LANGUAGECODE") AS 
  select
  plant.code PlantCode, plant.name plantName
, coalesce(depot.code, 'NULL') DepotCode, depot.description DepotDesc
, bu.code businessunitCode, bu.description businessunitDesc
, cu.customernumber, cu.name CustomerName
, cast(( case CONCATENATEWITHBLANK(addressDlv.Street, addressDlv.Street2) when ' '
           then CONCATENATEWITHBLANK(addressCu.Street, addressCu.Street2)
             else CONCATENATEWITHBLANK(addressDlv.Street, addressDlv.Street2) end )
               as varchar2(255)) Street
--, coalesce(addressDlv.Street2, addressCu.Street2) Street2
, ' 'Street2
, coalesce(addressDlv.City, addressCu.City) City, day.daynumber
, coalesce(addressDlv.Zipcode, addressCu.Zipcode) Zipcode, dsk.code DeliveryschemeCode
, route.routenumber, route.description RouteDesc
, (select day_desc.description from day_desc where day_desc.day_id = day.day_id
  and day_desc.language_id = languages.language_id) DayDesc
, rst.stopnumber, deliverypoint.code deliverypointCode
, emp.name Driver, truck.code TruckCode, truck.description TruckDesc
, buusg.usergroup_id UsergroupID, languages.code LanguageCode
from --- observation: useful line are 'doubled' by UsergroupID
  customer cu, businessunit bu, plant, deliveryschemesperstop dskt,  businessunitsperusergroup buusg
, route
        left outer join truck on route.truck_id = truck.truck_id
        left outer join depot on route.depot_id = depot.depot_id
        left outer join employee emp on route.driver_id = emp.employee_id
, day, customerdeliveryscheme cudsk, deliveryscheme dsk, address addressCu
, routestop rst left outer join
                            (deliverypoint join address addressDlv
                                           on deliverypoint.deliveryaddress_id = addressDlv.address_id)
                      on deliverypoint.deliverypoint_id = rst.deliverypoint_id
, languages
where
    sysdate between cu.dateactive and cu.dateinactive
and cu.defaultbusinessunit_id = bu.businessunit_id-- and bu.plant_id = plant.plant_id
and bu.businessunit_id = buusg.businessunit_id
and cu.customer_id = rst.customer_id
    and rst.route_id = route.route_id
        and route.plant_id = plant.plant_id -- ! --
        and route.drivingday_id = day.day_id
and cu.customer_id = cudsk.customer_id
and route.drivingday_id = cudsk.day_id
and cudsk.customer_id = dskt.customer_id
    and cudsk.deliveryscheme_id = dskt.deliveryscheme_id
    and cudsk.day_id = dskt.day_id
        and rst.routestop_id = dskt.routestop_id
and cudsk.deliveryscheme_id = dsk.deliveryscheme_id
and cu.visitaddress_id = addressCu.address_id
and route.active = 'Y'
and rst.dateactive <= trunc(sysdate)
and rst.dateinactive > trunc(sysdate)
/

  CREATE OR REPLACE VIEW "V_ROUTEFOLLOWUP" ("REASONCODE_ID", "PROOFOFVISITHISTORY_ID", "CONTACT_ID", "ROUTECONTROL_ID", "ROUTENUMBER", "STOPNUMBER", "DRIVINGDATE", "ROUTEDESCRIPTION", "CUSTOMERNUMBER", "NAME", "STOP_ID", "CONTACTPERSONNUMBER", "CONTACTPERSONNAME", "CONTACTPERSONPHONE", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "PRIORITY", "STATUS", "CONTACTNOTES", "REPORTPARAM_ID", "LANGUAGECODE", "EVENTTYPE", "GPSLATITUDE", "GPSLONGITUDE", "ALLOWEDDISTANCE", "CALCULATEDDISTANCE", "GPS_STOP_ID", "DISTRIBUTIONPOINTNUMBER", "DISTRIBDESC", "VISITDATE", "DEPARTURETIME", "VISITTIME", "RECORDINGTIME", "REASONCODE", "NOSCANDELIVERY", "REASONDESC", "CONTACTCATEGORYCODE", "LENGTHUNIT") AS 
  select /*version 2.2*/
       st.reasoncode_id, pvh.proofofvisithistory_id, ct.contact_id, rc.routecontrol_id, r.routenumber, st.stopnumber, rc.drivingdate,
       r.description routedescription, cu.customernumber, cu.name, st.stop_id, cp.contactpersonnumber, cp.name contactpersonname,
       cp.phone contactpersonphone, dep.departmentnumber, dep.description departmentdesc, ct.priority, ct.status, ct.contactnotes,
       rp.reportparam_id, lan.code languagecode, gps.eventtype, gps.gpslatitude, gps.gpslongitude, gps.alloweddistance, gps.calculateddistance,
       gps.stop_id gps_stop_id, dp.distributionpointnumber, dp.description distribdesc, trunc(pvh.visitdatetime) visitdate,
       (select case when (select substr(rtrim(value), -2)
                            from nls_session_parameters p
                           where p.parameter = 'NLS_TIME_FORMAT') = 'AM' then to_char(st.departuretime, 'HH:MI AM')
                    else to_char(st.departuretime, 'HH24:MI')
                end from dual)  departuretime,
       (select case when (select substr(rtrim(value), -2)
                            from nls_session_parameters p
                           where p.parameter = 'NLS_TIME_FORMAT') = 'AM' then to_char(pvh.visitdatetime, 'HH:MI AM')
                    else to_char(pvh.visitdatetime, 'HH24:MI')
                end from dual)  visittime,
       (select case when (select substr(rtrim(value), -2)
                            from nls_session_parameters p
                           where p.parameter = 'NLS_TIME_FORMAT') = 'AM' then to_char(gps.gpstimestamp, 'HH:MI AM')
                    else to_char(gps.gpstimestamp, 'HH24:MI')
                end from dual) recordingtime,
       nvl(rsc.code, rscn.code) reasoncode, rscn.noscandelivery,
       nvl((select red.description
              from reasoncode_desc red
             where st.reasoncode_id = red.reasoncode_id
               and red.language_id = lan.language_id),
           (select red.description
              from reasoncode_desc red
             where st.noscanreasoncode_id = red.reasoncode_id
               and red.language_id = lan.language_id)) reasondesc,
       (select cc.code
          from contactcategory cc
         where ct.contactcategory_id = cc.contactcategory_id) contactcategorycode,
       (select ss.value
          from systemsetting ss
         where ss.plant_id = rc.plant_id
           and ss.name = 'LENGTHUNIT') lengthunit
  from stop st
       left join stopgpsdata gps
                 left join proofofvisithistory pvh
                           left join distributionpoint dp
                                     left join department dep on dp.department_id = dep.department_id
                           on pvh.distributionpoint_link_id = dp.distributionpoint_id
                 on gps.stop_id = pvh.stop_id and pvh.scanned = 'N'
       on st.stop_id = gps.stop_id
       left join contact ct on st.stop_id = ct.stop_id
       left join customer cu on st.customer_link_id = cu.customer_id
       left join reasoncode rsc on st.reasoncode_id = rsc.reasoncode_id
       left join reasoncode rscn on st.noscanreasoncode_id = rscn.reasoncode_id
       left join routestop rs
                 left join contactperson cp on rs.contactperson_id = cp.contactperson_id
       on st.routestop_id = rs.routestop_id
       join routecontrol rc
            join route r on rc.route_id = r.route_id
            join reportparam rp on rc.routecontrol_id = rp.number_value
       on st.routecontrol_id = rc.routecontrol_id
       cross join languages lan
 where st.status in (0, 3, 4)
   and st.departuretime is not null
   and rc.pocketpcstatus = 2
/

  CREATE OR REPLACE VIEW "V_ROUTELISTCONTAINERS" ("CONTAINERID", "STOP_ID", "ROUTE_ID") AS 
  select
  distinct (c.primaryid) ContainerID
, pn.stop_id, pn.route_id
from
  packingnote pn, packingnotecontainer pnc, container c
where
    pn.packingnote_id = pnc.packingnote_id
and pnc.container_id = c.container_id
/

  CREATE OR REPLACE VIEW "V_ROUTELISTPACKINGNOTE" ("NOTENUMBER", "DELIVERYPOINT_ID", "STOP_ID", "ROUTE_ID", "DELNOTEFORBULKPUTUPITEMS", "STATUSCODE", "STRAIGHTEVENRETURN", "PUTUP", "STRAIGHTEVENEXCHANGE") AS 
  select /*version 2.1*/
       pn.notenumber, pn.deliverypoint_id, pn.stop_id, pn.route_id, c.delnoteforbulkputupitems,
       st.code statuscode, pn.straightevenreturn,
       case when (select count(*)
                    from packingnoteline pnl
                   where pnl.putuptype > 1
                     and pnl.packingnote_id = pn.packingnote_id) > 0 then 1
            else 0
        end putup,
   case when (select count(*)
                from packingnoteline pnl2
                     join packingnotelineperdelscheme pnds on pnl2.packingnoteline_id = pnds.packingnoteline_id
               where pnl2.packingnote_id = pn.packingnote_id) > 0 then 1
        else 0
    end straightevenexchange
   from packingnote pn
        join stop sp
             join customer c on sp.customer_link_id = c.customer_id
             join routecontrol rc
                  join route r on rc.route_id = r.route_id
             on sp.routecontrol_id = rc.routecontrol_id
        on pn.stop_id = sp.stop_id
        join status st on pn.status_id = st.status_id
/

  CREATE OR REPLACE VIEW "V_ROUTELISTPACKINGNOTE_AUX" ("PACKINGNOTE_ID", "NOTENUMBER", "DELIVERYPOINT_ID", "STOP_ID") AS 
  select pn.packingnote_id, pn.notenumber, pn.deliverypoint_id, pn.stop_id
from packingnote pn, stop st, customer c, routecontrol rc, route r
where pn.stop_id = st.stop_id
  and st.customer_link_id = c.customer_id
  and st.routecontrol_id = rc.routecontrol_id
  and rc.route_id = r.route_id
  and c.delnoteforbulkputupitems = 0
  and r.putupreportpercustomer > 0
  and exists (select * from packingnoteline pnl
      where pnl.putuptype = 2 and pnl.packingnote_id = pn.packingnote_id)
/

  CREATE OR REPLACE VIEW "V_ROUTELISTRECEIPTS" ("INVOICENUMBER", "PREBILLAMOUNT", "CUSTOMERNUMBER", "CURRENCYCODE", "INVOICEAMOUNTDECIMALS", "STOP_ID", "ROUTECONTROL_ID", "CUSTOMER_ID", "CLIENT_NAME", "INVOICEBUSINESSUNIT_ID", "ROUTE_ID", "PLANT_ID", "DELPOINTID") AS 
  select /*version 2.0*/
       ih.invoicenumber, ih.prebillamount, c.customernumber, cr.code currencycode, cr.invoiceamountdecimals, ih.stop_id,
       ih.routecontrol_id, c.customer_id, cl.name client_name, ih.invoicebusinessunit_id, ih.route_id, ibu.plant_id,
       coalesce ((select dp.deliverypoint_id
                    from departmentroom dr
                         join distributionpoint dp on dr.distributionpoint_id = dp.distributionpoint_id
                   where cl.departmentroom_id = dr.departmentroom_id), cl.deliverypoint_link_id) delpointid
  from invoiceheader ih
       join customer c
            join currency cr on c.currency_id = cr.currency_id
       on ih.deltocustomer_link_id = c.customer_id
       join invoiceheaderclient ihc
            join client_link cl on ihc.client_link_id = cl.client_link_id
       on ih.invoiceheader_id = ihc.invoiceheader_id
       join businessunit ibu on ih.invoicebusinessunit_id = ibu.businessunit_id
 where ih.documenttype = 3
   and ihc.clientinvoicetype = 1
   and ihc.paiddate is null
   and ih.originalcollectiontype = 1
/

  CREATE OR REPLACE VIEW "V_ROUTESREADYTOBESORTED" ("PLANTCODE", "DRIVINGDATE", "ROUTENUMBER") AS 
  select p.code plantcode, rc.drivingdate, r.routenumber
from   routecontrol rc, plant p, route r
where  rc.plant_id = p.plant_id
and    rc.route_id = r.route_id
and    rc.sortingstatus = 1
/

  CREATE OR REPLACE VIEW "V_ROUTESTOP" ("PLANTCODE", "PLANTNAME", "DRIVINGDAY", "ROUTENUMBER", "ROUTEDESCRIPTION", "STOPNUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "CONTACTPERSONNUMBER", "CONTACTPERSONNAME", "DELIVERYPOINTCODE", "DELIVERYPOINTDESCRIPTION", "SOILTICKETS", "ROUTELISTINSTRUCTIONS", "RETURNROUTEDRIVINGDAY", "RETURNROUTENUMBER", "RETURNROUTEDESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP", "ROUTE_ID", "CUSTOMER_ID", "ROUTESTOP_ID") AS 
  SELECT PLANT.CODE, PLANT.NAME, DAY.DAYNUMBER, ROUTE.ROUTENUMBER, ROUTE.DESCRIPTION, ROUTESTOP.STOPNUMBER,
CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, CONTACTPERSON.CONTACTPERSONNUMBER, CONTACTPERSON.NAME,
DELIVERYPOINT.CODE, DELIVERYPOINT.DESCRIPTION, ROUTESTOP.SOILTICKETS, ROUTESTOP.ROUTELISTINSTRUCTIONS,
RETURNDAY.DAYNUMBER, RETURNROUTE.ROUTENUMBER, RETURNROUTE.DESCRIPTION,
ROUTESTOP.SYSTEMUSER_ID, ROUTESTOP.TIMESTAMP, route.route_id, customer.customer_id, routestop.routestop_id
       FROM ROUTESTOP
       left outer join (STOP
                        LEFT OUTER JOIN CONTACTPERSON ON (STOP.CONTACTPERSON_ID = CONTACTPERSON.CONTACTPERSON_ID)
                        LEFT OUTER JOIN DELIVERYPOINT ON (STOP.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID)
       ) on ROUTESTOP.ROUTESTOP_ID = STOP.ROUTESTOP_ID,
       ROUTE, CUSTOMER,
       ROUTE RETURNROUTE, DAY, PLANT, DAY RETURNDAY
       WHERE ROUTESTOP.ROUTE_ID = ROUTE.ROUTE_ID
AND ROUTESTOP.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
AND ROUTESTOP.RETURNROUTE_ID = RETURNROUTE.ROUTE_ID
AND ROUTE.PLANT_ID = PLANT.PLANT_ID
AND ROUTE.DRIVINGDAY_ID = DAY.DAY_ID
AND RETURNROUTE.DRIVINGDAY_ID = RETURNDAY.DAY_ID
/

  CREATE OR REPLACE VIEW "V_ROUTESTOPANALYSIS" ("ROUTE_YEAR", "ROUTE_WEEK", "ROUTE_DAY", "ROUTENUMBER", "ROUTEDESC", "DEPOTCODE", "DEPOTDESC", "ENDMILEAGE", "STARTMILEAGE", "VISITMINUTES", "TRAVELMINUTES", "PLANT_ID", "ROUTECONTROL_ID") AS 
  select YEAR(rc.drivingdate) route_year, GETISOWEEK(rc.drivingdate) route_week,
  GETABSDAYNUMBER(rc.drivingdate) route_day,
  r.routenumber, r.description routedesc,
  coalesce(d.code, ' ') depotcode, d.description depotdesc,
  rc.endmileage, rc.startmileage,
  s.visitminutes, s.travelminutes,
  rc.plant_id, rc.routecontrol_id
from routecontrol rc, stop s, route r
left outer join depot d on (r.depot_id = d.depot_id)
where rc.routecontrol_id = s.routecontrol_id
  and s.status in (0,3)
  and rc.route_id = r.route_id
/

  CREATE OR REPLACE VIEW "V_ROUTESTOPPUTUPLIST" ("ROUTECONTROL_ID", "PLANTCODE", "ROUTENUMBER", "ROUTEDESCRIPTION", "DEPOTDESCRIPTION", "DRIVERNAME", "DRIVINGDATE", "LOADINGDOCK", "STARTTIME", "TRUCKCODE", "TRUCKDESCRIPTION", "STOPNUMBER", "CUSTOMERNUMBER", "SEARCHNAME", "LEGALNAME", "CUSTOMERNAME", "PRODUCTCODE", "TYPEOFMERCHANDISE", "PRODUCTDESCRIPTION", "PUTUPREPORTROUTESTOP", "SIZECODE", "FINISHINGMETHODCODE", "TOBEDELIVEREDAMOUNT", "CUSTOMDESCRIPTION", "SIZEDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "REMARKONPACKINGNOTE", "PACKREMARKENDDATE", "LANGUAGECODE", "DEPARTMENTNUMBER", "PACKDEP_CODE", "PACKDEP_DESC", "REMARKFORPACKINGINSTRUCTIONS", "REPLACEMENTQTY", "REPLACEMENTLOSSQTY", "PACKINGLOCATION", "SDL_INSTRUCTION", "INTERNALPROCESSINGBU_ID", "PROCESSINGPLANT_ID") AS 
  select /*version 2.0*/
       rc.routecontrol_id, pl.code plantcode, ro.routenumber, ro.description routedescription, de.description depotdescription,
       (select emp.name
          from employee emp
         where emp.employeenumber = rc.drivernumber
           and emp.plant_id = rc.plant_id) drivername,
       rc.drivingdate, rc.loadingdock, rc.packingdeadline starttime, tr.code truckcode, tr.description truckdescription, s.stopnumber,
       cu.customernumber, cu.searchname, cu.legalname, cu.name customername, pr.code productcode, pr.typeofmerchandise,
       (select prd.description
          from product_desc prd
         where prd.product_id = pr.product_id
           and prd.language_id = lan.language_id) productdescription,
       ro.putupreportroutestop, sd.code sizecode, fm.code finishingmethodcode, pnl.tobedeliveredamount, pnl.customdescription,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sd.sizedefinition_id
           and sdd.language_id = lan.language_id) sizedescription,
       dp.distributionpointnumber, dp.remarkonpackingnote, dp.packremarkenddate, lan.code languagecode, dep.departmentnumber,
       pd.code packdep_code, pd.description packdep_desc, pnl.remarkforpackinginstructions, pnl.replacementqty, pnl.replacementlossqty,
       (select max(sdl.location)
          from standarddeliveryline sdl
          join productlistperdistribpoint plpd on sdl.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
         where plpd.distributionpoint_id = dp.distributionpoint_id
           and plpd.product_id = pr.product_id
           and plpd.sizedefinition_id = sd.sizedefinition_id
           and plpd.finishingmethod_id = fm.finishingmethod_id
           and (sdl.dateactive <= pn.deliverydate and sdl.dateinactive >= pn.deliverydate)) packinglocation,
       (select max(sdl.remarkforpackinginstructions)
          from standarddeliveryline sdl
          join productlistperdistribpoint plpd on sdl.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
         where plpd.distributionpoint_id = dp.distributionpoint_id
           and plpd.product_id = pr.product_id
           and plpd.sizedefinition_id = sd.sizedefinition_id
           and plpd.finishingmethod_id = fm.finishingmethod_id
           and (sdl.dateactive <= pn.deliverydate and sdl.dateinactive >= pn.deliverydate)) sdl_instruction, pn.internalprocessingbu_id,
       (select pbu.plant_id
          from businessunit pbu
         where pbu.businessunit_id = pn.processbusinessunit_id) processingplant_id
  from packingnoteline pnl
       join packingnote pn
            join stop s
                 join routecontrol rc
                      left join truck tr on rc.truckcode = tr.code and rc.plant_id = tr.plant_id
                      join route ro
                           left join depot de on ro.depot_id = de.depot_id
                      on rc.route_id = ro.route_id
                      join plant pl on rc.plant_id = pl.plant_id
                 on s.routecontrol_id = rc.routecontrol_id
                 join customer cu on s.customer_link_id = cu.customer_id
            on pn.stop_id = s.stop_id
            join distributionpoint dp
                 join department dep on dp.department_id = dep.department_id
            on pn.distributionpoint_id = dp.distributionpoint_id
            join plantdepartment pd on pn.plantdepartment_id = pd.plantdepartment_id
            join status st on pn.status_id = st.status_id
       on pnl.packingnote_id = pn.packingnote_id
       join product pr on pnl.product_id = pr.product_id
       join sizedefinition sd on pnl.sizedefinition_id = sd.sizedefinition_id
       join finishingmethod fm on pnl.finishingmethod_id = fm.finishingmethod_id
       cross join languages lan
 where s.status in (0, 3)
   and st.code <> '40'
   and not exists (select 1
                     from productlistpercustomer plpc
                    where plpc.customer_id = cu.customer_id
                      and plpc.product_id = pr.product_id
                      and plpc.sizedefinition_id = sd.sizedefinition_id
                      and plpc.finishingmethod_id = fm.finishingmethod_id
                      and plpc.suppressonpackingreports = 2)
   and not exists (select 1
                     from plantproductsettings pps
                    where pps.plant_id = pl.plant_id
                      and pps.product_id = pr.product_id
                      and pps.suppressonpackingreports = 2)
   and pr.suppressonpackingreports <> 2
/

  CREATE OR REPLACE VIEW "V_ROUTEVOLUMEVSCREDITS" ("PLANTCODE", "PLANTNAME", "DEPOTCODE", "DEPOTDESC", "ROUTENUMBER", "ROUTEDESC", "REPORTPARAM_ID", "COD_VOLUME", "CHARGE_VOLUME", "TOTAL_VOLUME", "COD_LOSSCHARGE", "CHARGE_LOSSCHARGE", "TOTAL_LOSSCHARGE", "COD_CREDIT", "CHARGE_CREDIT", "TOTAL_CREDIT", "COD_CREDITLOSS", "CHARGE_CREDITLOSS", "TOTAL_CREDITLOSS", "COD_CREDITQTY", "CHARGE_CREDITQTY", "TOTAL_CREDITQTY", "COD_CREDITLOSSQTY", "CHARGE_CREDITLOSSQTY", "TOTAL_CREDITLOSSQTY") AS 
  select x.plantcode, x.plantname, x.depotcode,x.depotdesc,
       x.routenumber, x.routedesc, x.reportparam_id,
       round(sum(x.COD_volume)) COD_volume, round(sum(x.Charge_volume)) Charge_volume,
       round(sum(x.Total_volume)) Total_Volume, round(sum(x.COD_Losscharge)) COD_Losscharge,
       round(sum(x.Charge_Losscharge)) Charge_Losscharge, round(sum(x.Total_Losscharge)) Total_Losscharge,
       round(sum(x.COD_credit)) COD_credit, round(sum(x.Charge_credit)) Charge_credit,
       round(sum(x.Total_credit)) Total_credit, round(sum(x.COD_creditloss)) COD_creditloss,
       round(sum(x.Charge_creditloss)) Charge_creditloss, round(sum(x.Total_creditloss)) Total_creditloss,
       sum(x.COD_creditqty) COD_creditqty, sum(x.Charge_creditqty) Charge_creditqty,
       sum(x.Total_creditqty) Total_creditqty, sum(x.COD_creditlossqty) COD_creditlossqty,
       sum(x.Charge_creditlossqty) Charge_creditlossqty, sum(x.Total_creditlossqty) Total_creditlossqty
from
(SELECT ih.invoicebusinessunit_id,
       ih.invoicedate,
       ro.routenumber,
       ro.description RouteDesc,
       pl.code PlantCode,
       pl.name PlantName,
       de.code DepotCode,
       de.description DepotDesc,
       ih.paythisamount,
       ih.originalcollectiontype,
       ih.invoicenumber,
       ih.invoiceheader_id,
       null invoiceline_id,-- il.invoiceline_id,
       null invoicelinetype_id,-- il.invoicelinetype_id,
       null ilamount,-- il.amount,
       null adjustedamount,-- il.adjustedamount,
       null adjustmentreason_id,-- il.adjustmentreason_id,
       case when ih.originalcollectiontype=1
         then ih.paythisamount
         else 0
       end COD_Volume,
       case when ih.originalcollectiontype=2
         then ih.paythisamount
         else 0
       end Charge_Volume,
       ih.paythisamount Total_Volume,
       0 COD_losscharge,
       0 Charge_Losscharge,
       0 Total_Losscharge,
       0 COD_credit,
       0 Charge_credit,
       0 Total_credit,
       0 COD_creditloss,
       0 Charge_creditloss,
       0 Total_creditloss,
       0 COD_creditqty,
       0 Charge_creditqty,
       0 Total_creditqty,
       0 COD_creditlossqty,
       0 Charge_creditlossqty,
       0 Total_creditlossqty,
       rp.reportparam_id
  FROM reportparam rp, plant pl, businessunitsperusergroup bug, Systemuser su, invoiceheader ih, route ro
  LEFT OUTER JOIN depot de ON ro.depot_id = de.depot_id
 WHERE ih.status_id in (select st.status_id
                          from status st
                         where st.statustype = 'IN'
                           AND st.code = '2') --only settled invoices
   AND ih.documenttype = 1
   AND ih.route_id = ro.route_id
   AND ro.plant_id = pl.plant_id
   AND bug.businessunit_id = ih.invoicebusinessunit_id
   AND bug.usergroup_id = su.usergroup_id
   AND su.systemuser_id = rp.number_value4
   AND ih.invoicebusinessunit_id = rp.number_value
   and ih.invoicedate >= rp.date_value1
   and ih.invoicedate <= rp.date_value2
   AND pl.code >= rp.string_value and pl.code <= rp.string_value1
AND --depot filter
((rp.string_value2 = ' ' and rp.string_value3 = 'ZZZZZZZZZZZZ')
or (de.code >= rp.string_value2 and de.code <= rp.string_value3))
AND ro.routenumber >= rp.number_value1 and ro.routenumber <= rp.number_value2
UNION ALL
-- loss charges
SELECT ih.invoicebusinessunit_id,
       ih.invoicedate,
       ro.routenumber,
       ro.description RouteDesc,
       pl.code PlantCode,
       pl.name PlantName,
       de.code DepotCode,
       de.description DepotDesc,
       ih.paythisamount,
       ih.originalcollectiontype,
       ih.invoicenumber,
       ih.invoiceheader_id,
       il.invoiceline_id,
       il.invoicelinetype_id,
       il.amount,
       il.adjustedamount,
       il.adjustmentreason_id,
       0 COD_Volume,
       0 Charge_Volume,
       0 Total_Volume,
       case when ih.originalcollectiontype=1
         then
           case when il.adjustmentreason_id is null
            then il.amount
            else il.adjustedamount
           end
         else 0
       end COD_losscharge,
       case when ih.originalcollectiontype=2
         then
           case when il.adjustmentreason_id is null
            then il.amount
            else il.adjustedamount
           end
         else 0
       end Charge_Losscharge,
       case
         when il.adjustmentreason_id is null then
          il.amount
         else
          il.adjustedamount
       end Total_Losscharge,
       0 COD_credit,
       0 Charge_credit,
       0 Total_credit,
       0 COD_creditloss,
       0 Charge_creditloss,
       0 Total_creditloss,
       0 COD_creditqty,
       0 Charge_creditqty,
       0 Total_creditqty,
       0 COD_creditlossqty,
       0 Charge_creditlossqty,
       0 Total_creditlossqty,
       rp.reportparam_id
  FROM reportparam rp, plant pl, businessunitsperusergroup bug, Systemuser su, invoiceheader ih, invoiceline il, route ro
  LEFT OUTER JOIN depot de ON ro.depot_id = de.depot_id
 WHERE ih.status_id in (select st.status_id
                          from status st
                         where st.statustype = 'IN'
                           AND st.code = '2') --only settled invoices
   AND ih.documenttype = 1
   AND ih.invoiceheader_id = il.invoiceheader_id
   AND ih.route_id = ro.route_id
   AND ro.plant_id = pl.plant_id
   AND il.extend = 'Y'
   and il.invoicelinetype_id in (8,9)
   AND bug.businessunit_id = ih.invoicebusinessunit_id
   AND bug.usergroup_id = su.usergroup_id
   AND su.systemuser_id = rp.number_value4
   AND ih.invoicebusinessunit_id = rp.number_value
   and ih.invoicedate >= rp.date_value1
   and ih.invoicedate <= rp.date_value2
   AND pl.code >= rp.string_value and pl.code <= rp.string_value1
AND --depot filter
((rp.string_value2 = ' ' and rp.string_value3 = 'ZZZZZZZZZZZZ')
or (de.code >= rp.string_value2 and de.code <= rp.string_value3))
AND ro.routenumber >= rp.number_value1 and ro.routenumber <= rp.number_value2
UNION ALL
-- credits
SELECT ih.invoicebusinessunit_id,
       ih.invoicedate,
       ro.routenumber,
       ro.description RouteDesc,
       pl.code PlantCode,
       pl.name PlantName,
       de.code DepotCode,
       de.description DepotDesc,
       ih.paythisamount,
       ih.originalcollectiontype,
       ih.invoicenumber,
       ih.invoiceheader_id,
       il.invoiceline_id,
       il.invoicelinetype_id,
       il.amount,
       il.adjustedamount,
       il.adjustmentreason_id,
       0 COD_Volume,
       0 Charge_Volume,
       0 Total_Volume,
       0 COD_losscharge,
       0 Charge_Losscharge,
       0 Total_Losscharge,
       case when ih.originalcollectiontype=1
         then
           case when il.adjustmentreason_id is null
            then il.amount * -1
            else il.amount - il.adjustedamount
           end
         else 0
       end COD_credit,
       case when ih.originalcollectiontype=2
         then
           case when il.adjustmentreason_id is null
            then il.amount * -1
            else il.amount - il.adjustedamount
           end
         else 0
       end Charge_credit,
       case when il.adjustmentreason_id is null
       then il.amount * -1
       else il.amount - il.adjustedamount
       end Total_credit,
       0 COD_creditloss,
       0 Charge_creditloss,
       0 Total_creditloss,
       case when ih.originalcollectiontype=1
         then
           case when il.invoicelinetype_id<>18
            then 1
            else 0
           end
         else 0
       end COD_creditqty,
       case when ih.originalcollectiontype=2
         then
           case when il.invoicelinetype_id<>18
            then 1
            else 0
           end
         else 0
       end Charge_creditqty,
       case when il.invoicelinetype_id<>18
        then 1
        else 0
       end Total_Creditqty,
       0 COD_creditlossqty,
       0 Charge_creditlossqty,
       0 Total_creditlossqty,
       rp.reportparam_id
  FROM reportparam rp, plant pl, businessunitsperusergroup bug, Systemuser su, invoiceheader ih, invoiceline il, route ro
  LEFT OUTER JOIN depot de ON ro.depot_id = de.depot_id
 WHERE ih.status_id in (select st.status_id
                          from status st
                         where st.statustype = 'IN'
                           AND st.code = '2') --only settled invoices
   AND ih.documenttype = 1
   AND ih.invoiceheader_id = il.invoiceheader_id
   AND ih.route_id = ro.route_id
   AND ro.plant_id = pl.plant_id
   AND il.extend = 'Y'
   and ((il.adjustedamount < il.amount and il.adjustmentreason_id is not null) or
        (il.amount<0 and il.adjustmentreason_id is null))
--   and il.invoicelinetype_id in (8,9)
   AND bug.businessunit_id = ih.invoicebusinessunit_id
   AND bug.usergroup_id = su.usergroup_id
   AND su.systemuser_id = rp.number_value4
   AND ih.invoicebusinessunit_id = rp.number_value
   and ih.invoicedate >= rp.date_value1
   and ih.invoicedate <= rp.date_value2
   AND pl.code >= rp.string_value and pl.code <= rp.string_value1
AND --depot filter
((rp.string_value2 = ' ' and rp.string_value3 = 'ZZZZZZZZZZZZ')
or (de.code >= rp.string_value2 and de.code <= rp.string_value3))
AND ro.routenumber >= rp.number_value1 and ro.routenumber <= rp.number_value2
UNION ALL
-- loss credits
SELECT ih.invoicebusinessunit_id,
       ih.invoicedate,
       ro.routenumber,
       ro.description RouteDesc,
       pl.code PlantCode,
       pl.name PlantName,
       de.code DepotCode,
       de.description DepotDesc,
       ih.paythisamount,
       ih.originalcollectiontype,
       ih.invoicenumber,
       ih.invoiceheader_id,
       il.invoiceline_id,
       il.invoicelinetype_id,
       il.amount,
       il.adjustedamount,
       il.adjustmentreason_id,
       0 COD_Volume,
       0 Charge_Volume,
       0 Total_Volume,
       0 COD_losscharge,
       0 Charge_Losscharge,
       0 Total_Losscharge,
       0 COD_credit,
       0 Charge_credit,
       0 Total_credit,
       case when ih.originalcollectiontype=1
         then
           case when il.adjustmentreason_id is null
            then il.amount * -1
            else il.amount - il.adjustedamount
           end
         else 0
       end COD_creditloss,
       case when ih.originalcollectiontype=2
         then
           case when il.adjustmentreason_id is null
            then il.amount * -1
            else il.amount - il.adjustedamount
           end
         else 0
       end Charge_creditloss,
       case when il.adjustmentreason_id is null
       then il.amount * -1
       else il.amount - il.adjustedamount
       end Total_creditloss,
       0 COD_creditqty,
       0 Charge_creditqty,
       0 Total_creditqty,
       case when ih.originalcollectiontype=1
         then 1
         else 0
       end COD_creditlossqty,
       case when ih.originalcollectiontype=2
         then 1
         else 0
       end Charge_creditlossqty,
       1 Total_creditlossqty,
       rp.reportparam_id
  FROM reportparam rp, plant pl, businessunitsperusergroup bug, Systemuser su, invoiceheader ih, invoiceline il, route ro
  LEFT OUTER JOIN depot de ON ro.depot_id = de.depot_id
 WHERE ih.status_id in (select st.status_id
                          from status st
                         where st.statustype = 'IN'
                           AND st.code = '2') --only settled invoices
   AND ih.documenttype = 1
   AND ih.invoiceheader_id = il.invoiceheader_id
   AND ih.route_id = ro.route_id
   AND ro.plant_id = pl.plant_id
   AND il.extend = 'Y'
   and ((il.adjustedamount < il.amount and il.adjustmentreason_id is not null) or
        (il.amount<0 and il.adjustmentreason_id is null))
   and il.invoicelinetype_id in (8,9)
   AND bug.businessunit_id = ih.invoicebusinessunit_id
   AND bug.usergroup_id = su.usergroup_id
   AND su.systemuser_id = rp.number_value4
   AND ih.invoicebusinessunit_id = rp.number_value
   and ih.invoicedate >= rp.date_value1
   and ih.invoicedate <= rp.date_value2
   AND pl.code >= rp.string_value and pl.code <= rp.string_value1
AND --depot filter
((rp.string_value2 = ' ' and rp.string_value3 = 'ZZZZZZZZZZZZ')
or (de.code >= rp.string_value2 and de.code <= rp.string_value3))
AND ro.routenumber >= rp.number_value1 and ro.routenumber <= rp.number_value2
) x
group BY
       x.reportparam_id,
       x.routenumber,
       x.routedesc,
       x.plantcode,
       x.plantname,
       x.depotcode,
       x.depotdesc--order by x.plantcode, x.routenumber
/

  CREATE OR REPLACE VIEW "V_ROUTE_CLUSTER" ("PLANTCODE", "PLANTNAME", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_ID", "DEPOTCODE", "ZIPCODE", "CITY", "DAYNUMBER", "DAYDESC", "DELIVERYSCHEMECODE", "DELIVERYPOINTCODE", "ROUTESTRING", "STOPSTRING", "ROUTE_STOP", "CLUSTERCODE", "GARMENTCUSTOMER", "LANGUAGECODE", "REPORTPARAM_ID") AS 
  select distinct plant.code PlantCode,
                plant.name plantName,
                cu.customernumber,
                cu.name CustomerName,
                cu.customer_id,
                coalesce(depot.code, '-1') DepotCode,
                addressCu.Zipcode,
                addressCu.City,
                day.daynumber,
                (select day_desc.code
                   from day_desc
                  where day_desc.day_id = day.day_id
                    and day_desc.language_id = languages.language_id) DayDesc,
                dsk.code DeliveryschemeCode,
                coalesce(deliverypoint.code, '-x') deliverypointCode,
                cast(route.routenumber as varchar(20)) routeString,
                cast(rst.stopnumber as varchar(9)) stopString,
                cast(CONCATENATEWITHSIGN(cast(route.routenumber as
                                              varchar(20)),
                                         ' / ',
                                         cast(rst.stopnumber as varchar(9))) as
                     varchar(30)) ROUTE_STOP,
                '-1' ClusterCode,
                case
                  when (select count(*)
                          from customerdeliveryday cuddy
                         where cu.customer_id = cuddy.customer_id
                           and cuddy.typeofmerchadise = 2
                           and cuddy.day_id = day.day_id) > 0 then
                   1
                  else
                   0
                end GarmentCustomer,
                languages.code LanguageCode,
                rp.reportparam_id
  from customer cu, plant, deliveryschemesperstop dskt, route
  left outer join depot
    on route.depot_id = depot.depot_id, routestop rst
  left outer join deliverypoint
    on deliverypoint.deliverypoint_id = rst.deliverypoint_id, day,
 customerdeliveryscheme cudsk, deliveryscheme dsk, address addressCu,
 languages, reportparam rp
 where cu.dateinactive >= trunc(sysdate)
   and exists
 (select bu1.code --customer filter on BusinessUnit
          from customeractivities ca1, businessunit bu1
         where ca1.customer_id = cu.customer_id
           and (ca1.processbusinessunit_id = bu1.businessunit_id or
               bu1.businessunit_id = cu.defaultbusinessunit_id)
           and bu1.plant_id = plant.plant_id
           and bu1.code between rp.string_value1 and rp.string_value2)
   and exists
 (select bu2.code --user group filter on BusinessUnit
          from businessunit bu2, businessunitsperusergroup bg2
         where bu2.businessunit_id = bg2.businessunit_id
           and bg2.usergroup_id = rp.number_value1
           and bu2.code between rp.string_value1 and rp.string_value2
           and bu2.plant_id = plant.plant_id)
   and cu.customer_id = rst.customer_id
   and rst.route_id = route.route_id
   and route.plant_id = plant.plant_id -- ! --
   and route.drivingday_id = day.day_id
   and exists
 (select bu3.code --route filter on bu and usergroup
          from businessunit bu3, businessunitsperusergroup bug3
         where bu3.plant_id = plant.plant_id
           and bu3.businessunit_id = bug3.businessunit_id
           and bug3.usergroup_id = rp.number_value1
           and bu3.code between rp.string_value1 and rp.string_value2)
   and cu.customer_id = cudsk.customer_id
   and route.drivingday_id = cudsk.day_id
   and cudsk.customer_id = dskt.customer_id
   and cudsk.deliveryscheme_id = dskt.deliveryscheme_id
   and cudsk.day_id = dskt.day_id
   and rst.routestop_id = dskt.routestop_id
   and cudsk.deliveryscheme_id = dsk.deliveryscheme_id
   and cu.visitaddress_id = addressCu.address_id
   and rp.string_value3 = ' '
   and rp.string_value4 = 'ZZZZZZ'
   and rst.dateactive <= trunc(sysdate)
   and rst.dateinactive>= trunc(sysdate)
union all
select distinct plant.code PlantCode,
                plant.name plantName,
                cu.customernumber,
                cu.name CustomerName,
                cu.customer_id,
                coalesce(depot.code, '-1') DepotCode,
                addressCu.Zipcode,
                addressCu.City,
                day.daynumber,
                (select day_desc.code
                   from day_desc
                  where day_desc.day_id = day.day_id
                    and day_desc.language_id = languages.language_id) DayDesc,
                dsk.code DeliveryschemeCode,
                coalesce(deliverypoint.code, '-x') deliverypointCode,
                cast(route.routenumber as varchar(20)) routeString,
                cast(rst.stopnumber as varchar(9)) stopString,
                cast(CONCATENATEWITHSIGN(cast(route.routenumber as
                                              varchar(20)),
                                         ' / ',
                                         cast(rst.stopnumber as varchar(9))) as
                     varchar(30)) ROUTE_STOP,
                coalesce(customercluster.code, '-1') ClusterCode,
                case
                  when (select count(*)
                          from customerdeliveryday cuddy
                         where cu.customer_id = cuddy.customer_id
                           and cuddy.typeofmerchadise = 2
                           and cuddy.day_id = day.day_id) > 0 then
                   1
                  else
                   0
                end GarmentCustomer,
                languages.code LanguageCode,
                rp.reportparam_id
  from customer cu, plant, deliveryschemesperstop dskt, route
  left outer join depot
    on route.depot_id = depot.depot_id, routestop rst
  left outer join deliverypoint
    on deliverypoint.deliverypoint_id = rst.deliverypoint_id, day,
 customerdeliveryscheme cudsk, deliveryscheme dsk, address addressCu,
 languages, reportparam rp, customercluster, customerspercluster cpc
 where cu.dateinactive >= trunc(sysdate)
   and exists
 (select bu1.code --customer filter on BusinessUnit
          from customeractivities ca1, businessunit bu1
         where ca1.customer_id = cu.customer_id
           and (ca1.processbusinessunit_id = bu1.businessunit_id or
               bu1.businessunit_id = cu.defaultbusinessunit_id)
           and bu1.plant_id = plant.plant_id
           and bu1.code between rp.string_value1 and rp.string_value2)
   and exists
 (select bu2.code --user group filter on BusinessUnit
          from businessunit bu2, businessunitsperusergroup bg2
         where bu2.businessunit_id = bg2.businessunit_id
           and bg2.usergroup_id = rp.number_value1
           and bu2.code between rp.string_value1 and rp.string_value2
           and bu2.plant_id = plant.plant_id)
   and cu.customer_id = rst.customer_id
   and rst.route_id = route.route_id
   and route.plant_id = plant.plant_id -- ! --
   and route.drivingday_id = day.day_id
   and exists
 (select bu3.code --route filter on bu and usergroup
          from businessunit bu3, businessunitsperusergroup bug3
         where bu3.plant_id = plant.plant_id
           and bu3.businessunit_id = bug3.businessunit_id
           and bug3.usergroup_id = rp.number_value1
           and bu3.code between rp.string_value1 and rp.string_value2)
   and cu.customer_id = cudsk.customer_id
   and route.drivingday_id = cudsk.day_id
   and cudsk.customer_id = dskt.customer_id
   and cudsk.deliveryscheme_id = dskt.deliveryscheme_id
   and cudsk.day_id = dskt.day_id
   and rst.routestop_id = dskt.routestop_id
   and cudsk.deliveryscheme_id = dsk.deliveryscheme_id
   and cu.visitaddress_id = addressCu.address_id
   and (rp.string_value3 <> ' ' or rp.string_value4 <> 'ZZZZZZ')
   and cpc.customer_id = cu.customer_id
   and cpc.cluster_id = customercluster.cluster_id
   and customercluster.code between rp.string_value3 and rp.string_value4
   and rst.dateactive <= trunc(sysdate)
   and rst.dateinactive>= trunc(sysdate)
/

  CREATE OR REPLACE VIEW "V_ROUTE_DELIVERY_CUSTOMER" ("PLANTCODE", "PLANTNAME", "BUSINESSUNITCODE", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_ID", "DEPOTCODE", "STREET", "STREET2", "CITY", "DAYNUMBER", "ZIPCODE", "DELIVERYSCHEMECODE", "DELIVERYSCHEMEDESC", "ROUTENUMBER", "RETURNROUTENUMBER", "DAYCODE", "RETURNDAYCODE", "STOPNUMBER", "DELIVERYPOINTCODE", "DRIVER", "GARMENTCUSTOMER", "LANGUAGECODE", "REPORTPARAM_ID") AS 
  select
  plant.code PlantCode, plant.name plantName
, cast(F_GETBUSINESSUNIT(route.plant_id, cu.customer_id, rp.number_value1) as varchar2(6)) businessunitCode
, cu.customernumber, cu.name CustomerName, cu.customer_id, depot.code DepotCode
, cast(( case
         when deliverypoint.code is null then CONCATENATEWITHBLANK(addressCu.Street, addressCu.Street2)
              else CONCATENATEWITHBLANK(addressDlv.Street, addressDlv.Street2) end
                 ) as varchar2(255)) Street
, '' Street2
, coalesce(addressDlv.City, addressCu.City) City, day.daynumber
, coalesce(addressDlv.Zipcode, addressCu.Zipcode) Zipcode, dsk.code DeliveryschemeCode
, (select dskd.description from deliveryscheme_desc dskd where dsk.deliveryscheme_id = dskd.deliveryscheme_id
     and dskd.language_id = languages.language_id) DeliveryschemeDesc
, route.routenumber
, returnroute.routenumber returnroutenumber
, (select day_desc.code from day_desc where day_desc.day_id = day.day_id
  and day_desc.language_id = languages.language_id) DayCode
, (select day_desc.code from day_desc where day_desc.day_id = returnday.day_id
  and day_desc.language_id = languages.language_id) ReturnDayCode
, rst.stopnumber, deliverypoint.code deliverypointCode, emp.name Driver
--, customercluster.code ClusterCode
, case when ( select count(*) from customerdeliveryday cuddy
              where cu.customer_id = cuddy.customer_id and cuddy.typeofmerchadise = 2
              and cuddy.day_id = day.day_id ) > 0
     then 1 else 0 end GarmentCustomer
, languages.code LanguageCode, rp.reportparam_id
from
  customer cu
          -- left outer join customercluster on customercluster.cluster_id = cu.cluster_id
, plant, deliveryschemesperstop dskt
, route
        left outer join depot on route.depot_id = depot.depot_id
        left outer join employee emp on route.driver_id = emp.employee_id
, day
, route returnroute, day returnday
, customerdeliveryscheme cudsk, deliveryscheme dsk, address addressCu
, routestop rst left outer join
                            (deliverypoint join address addressDlv
                                           on deliverypoint.deliveryaddress_id = addressDlv.address_id)
                      on deliverypoint.deliverypoint_id = rst.deliverypoint_id
, languages, reportparam rp
where
  exists (select bu1.code --customer filter on BusinessUnit
    from customeractivities ca1, businessunit bu1
    where ca1.customer_id = cu.customer_id
      and (ca1.processbusinessunit_id = bu1.businessunit_id
           or
           bu1.businessunit_id = cu.defaultbusinessunit_id)
      and bu1.plant_id = plant.plant_id
      and bu1.code between rp.string_value1 and rp.string_value2)
and
   exists (select bu2.code --user group filter on BusinessUnit
     from businessunit bu2, businessunitsperusergroup bg2
     where bu2.businessunit_id = bg2.businessunit_id
       and bg2.usergroup_id = rp.number_value1
       and bu2.code between rp.string_value1 and rp.string_value2
       and bu2.plant_id = plant.plant_id)
and cu.dateinactive >= trunc(sysdate)
and cu.customer_id = rst.customer_id
    and rst.route_id = route.route_id
      and route.plant_id = plant.plant_id -- ! --
      and exists (select bu3.code --route filter on bu and usergroup
        from businessunit bu3, businessunitsperusergroup bug3
        where bu3.plant_id = plant.plant_id
          and bu3.businessunit_id = bug3.businessunit_id
          and bug3.usergroup_id = rp.number_value1
          and bu3.code between rp.string_value1 and rp.string_value2)
        and route.drivingday_id = day.day_id
and returnroute.drivingday_id = returnday.day_id
and cu.customer_id = cudsk.customer_id
and route.drivingday_id = cudsk.day_id
    and cudsk.customer_id = dskt.customer_id
    and cudsk.deliveryscheme_id = dskt.deliveryscheme_id
    and cudsk.day_id = dskt.day_id
        and rst.routestop_id = dskt.routestop_id
and cudsk.deliveryscheme_id = dsk.deliveryscheme_id
and cu.visitaddress_id = addressCu.address_id
and rst.returnroute_id = returnroute.route_id
and ((rp.string_value3 = ' ' and rp.string_value4 = 'ZZZZZZ')
    or
    (exists (select cpc.customerspercluster_id --customer filter on Cluster
     from customerspercluster cpc, customercluster cc
     where cpc.cluster_id = cc.cluster_id
       and cpc.customer_id = cu.customer_id
       and cc.code between rp.string_value3 and rp.string_value4)))
and rst.dateactive <= trunc(sysdate)
and rst.dateinactive > trunc(sysdate)
/

  CREATE OR REPLACE VIEW "V_ROUTE_STOP_CLUSTER" ("PLANTCODE", "CUSTOMERNUMBER", "DEPOTCODE", "DAYNUMBER", "DELIVERYSCHEMECODE", "DELIVERYPOINTCODE", "ROUTESTRING", "STOPSTRING", "ROUTE_STOP", "CLUSTERCODE", "GARMENTCUSTOMER", "REPORTPARAM_ID") AS 
  select distinct
  plant.code PlantCode
--, bu.code businessunitCode
, cu.customernumber
, coalesce(depot.code, '-1') DepotCode
, day.daynumber
, dsk.code DeliveryschemeCode, coalesce(deliverypoint.code, '-x') deliverypointCode
, cast(route.routenumber as varchar(99)) routeString, cast(rst.stopnumber as varchar(99)) stopString
, cast(CONCATENATEWITHSIGN(cast(route.routenumber as varchar(99)), ' / ', cast(rst.stopnumber as varchar(9))
  ) as varchar(99)) ROUTE_STOP
--, buusg.usergroup_id UsergroupID
, '-1' ClusterCode
, case when ( select count(*) from customerdeliveryday cuddy
              where cu.customer_id = cuddy.customer_id and cuddy.typeofmerchadise = 2
              and cuddy.day_id = day.day_id ) > 0
     then 1 else 0 end GarmentCustomer, rp.reportparam_id
from
  customer cu
          -- left outer join customercluster on customercluster.cluster_id = cu.cluster_id
--, businessunit bu, businessunitsperusergroup buusg
, plant, deliveryschemesperstop dskt
, route
        left outer join depot on route.depot_id = depot.depot_id
, routestop rst
            left outer join deliverypoint on deliverypoint.deliverypoint_id = rst.deliverypoint_id
, day, customerdeliveryscheme cudsk, deliveryscheme dsk, reportparam rp
--, customercluster, customerspercluster cpc
where
    cu.dateinactive >= trunc(sysdate)
and   exists (select bu1.code --customer filter on BusinessUnit
    from customeractivities ca1, businessunit bu1
    where ca1.customer_id = cu.customer_id
      and (ca1.processbusinessunit_id = bu1.businessunit_id
           or
           bu1.businessunit_id = cu.defaultbusinessunit_id)
      and bu1.plant_id = plant.plant_id
      and bu1.code between rp.string_value1 and rp.string_value2)
and
   exists (select bu2.code --user group filter on BusinessUnit
     from businessunit bu2, businessunitsperusergroup bg2
     where bu2.businessunit_id = bg2.businessunit_id
       and bg2.usergroup_id = rp.number_value1
       and bu2.code between rp.string_value1 and rp.string_value2
       and bu2.plant_id = plant.plant_id)
--and cu.defaultbusinessunit_id = bu.businessunit_id
--and bu.businessunit_id = buusg.businessunit_id
and cu.customer_id = rst.customer_id
    and rst.route_id = route.route_id
      and route.plant_id = plant.plant_id -- ! --
        and route.drivingday_id = day.day_id
        and exists (select bu3.code --route filter on bu and usergroup
              from businessunit bu3, businessunitsperusergroup bug3
              where bu3.plant_id = plant.plant_id
                and bu3.businessunit_id = bug3.businessunit_id
                and bug3.usergroup_id = rp.number_value1
                and bu3.code between rp.string_value1 and rp.string_value2)
and cu.customer_id = cudsk.customer_id
and route.drivingday_id = cudsk.day_id
    and cudsk.customer_id = dskt.customer_id
    and cudsk.deliveryscheme_id = dskt.deliveryscheme_id
    and cudsk.day_id = dskt.day_id
        and rst.routestop_id = dskt.routestop_id
and cudsk.deliveryscheme_id = dsk.deliveryscheme_id
and rp.string_value3 = ' ' and rp.string_value4 = 'ZZZZZZ'
union all
select distinct
  plant.code PlantCode
--, bu.code businessunitCode
, cu.customernumber
, coalesce(depot.code, '-1') DepotCode
, day.daynumber
, dsk.code DeliveryschemeCode, coalesce(deliverypoint.code, '-x') deliverypointCode
, cast(route.routenumber as varchar(99)) routeString, cast(rst.stopnumber as varchar(99)) stopString
, cast(CONCATENATEWITHSIGN(cast(route.routenumber as varchar(99)), ' / ', cast(rst.stopnumber as varchar(9))
  ) as varchar(99)) ROUTE_STOP
--, buusg.usergroup_id UsergroupID
, coalesce(customercluster.code, '-1') ClusterCode
, case when ( select count(*) from customerdeliveryday cuddy
              where cu.customer_id = cuddy.customer_id and cuddy.typeofmerchadise = 2
              and cuddy.day_id = day.day_id ) > 0
     then 1 else 0 end GarmentCustomer, rp.reportparam_id
from
  customer cu
          -- left outer join customercluster on customercluster.cluster_id = cu.cluster_id
--, businessunit bu, businessunitsperusergroup buusg
, plant, deliveryschemesperstop dskt
, route
        left outer join depot on route.depot_id = depot.depot_id
, routestop rst
            left outer join deliverypoint on deliverypoint.deliverypoint_id = rst.deliverypoint_id
, day, customerdeliveryscheme cudsk, deliveryscheme dsk, reportparam rp
, customercluster, customerspercluster cpc
where
    cu.dateinactive >= trunc(sysdate)
and   exists (select bu1.code --customer filter on BusinessUnit
    from customeractivities ca1, businessunit bu1
    where ca1.customer_id = cu.customer_id
      and (ca1.processbusinessunit_id = bu1.businessunit_id
           or
           bu1.businessunit_id = cu.defaultbusinessunit_id)
      and bu1.plant_id = plant.plant_id
      and bu1.code between rp.string_value1 and rp.string_value2)
and
   exists (select bu2.code --user group filter on BusinessUnit
     from businessunit bu2, businessunitsperusergroup bg2
     where bu2.businessunit_id = bg2.businessunit_id
       and bg2.usergroup_id = rp.number_value1
       and bu2.code between rp.string_value1 and rp.string_value2
       and bu2.plant_id = plant.plant_id)
--and cu.defaultbusinessunit_id = bu.businessunit_id
--and bu.businessunit_id = buusg.businessunit_id
and cu.customer_id = rst.customer_id
    and rst.route_id = route.route_id
      and route.plant_id = plant.plant_id -- ! --
        and route.drivingday_id = day.day_id
        and exists (select bu3.code --route filter on bu and usergroup
              from businessunit bu3, businessunitsperusergroup bug3
              where bu3.plant_id = plant.plant_id
                and bu3.businessunit_id = bug3.businessunit_id
                and bug3.usergroup_id = rp.number_value1
                and bu3.code between rp.string_value1 and rp.string_value2)
and cu.customer_id = cudsk.customer_id
and route.drivingday_id = cudsk.day_id
    and cudsk.customer_id = dskt.customer_id
    and cudsk.deliveryscheme_id = dskt.deliveryscheme_id
    and cudsk.day_id = dskt.day_id
        and rst.routestop_id = dskt.routestop_id
and cudsk.deliveryscheme_id = dsk.deliveryscheme_id
and (rp.string_value3 <> ' ' or rp.string_value4 <> 'ZZZZZZ')
and cpc.customer_id = cu.customer_id and cpc.cluster_id = customercluster.cluster_id
and customercluster.code between rp.string_value3 and rp.string_value4
/

  CREATE OR REPLACE VIEW "V_SACKSNOTGENERATED" ("CUSTOMERNUMBER", "CUSTOMERNAME", "RC_NUMBER", "DELIVERYDATE", "PN_DELIVERYDATE", "DISTRIBUTIONPOINT_ID", "STAYTYPE", "STAYNR", "BT_LASTSCAN", "BT_SORTEDDATE", "BU_CODE", "NOTENUMBER", "PN_STATUSCODE") AS 
  select c.customernumber,
       c.name customername,
       (select r.routenumber
          from routecontrol rc, route r
         where rc.routecontrol_id = pn.routecontrol_id
           and rc.route_id = r.route_id) rc_number,
       bt.deliverydate,
       --bt.planneddeliverydate,
       pn.deliverydate pn_deliverydate,
       pn.distributionpoint_id,
       st.staytype,
       st.staynr,
       lastscantimestamp bt_lastscan,
       bt.sorteddate bt_sorteddate,
       (select bu.code
          from businessunit bu
         where bu.businessunit_id = pn.processbusinessunit_id) bu_code,
       pn.notenumber,
       (select s.code from status s where pn.status_id = s.status_id) pn_statuscode
  from bagtag bt, packingnote pn, distributionpoint dp, department d, customer c, stay st
 where pn.distributionpoint_id = dp.distributionpoint_id
   and dp.department_id = d.department_id
   and d.customer_id = c.customer_id
   and bt.packingnote_id = pn.packingnote_id
   and bt.stay_id = st.stay_id
   and st.staytype = 6
   and st.staynr not in (60, 70)
   and pn.status_id not in (select s.status_id
                          from status s
                         where s.statustype = 'PN'
                           and s.code in (40, 60))
union
select c.customernumber,
       c.name customername,
       (select r.routenumber
          from routecontrol rc, route r
         where rc.routecontrol_id = pn.routecontrol_id
           and rc.route_id = r.route_id) rc_number,
       bt.planneddeliverydate deliverydate,
       pn.deliverydate pn_deliverydate,
       pn.distributionpoint_id,
       st.staytype,
       st.staynr,
       lastscantimestamp bt_lastscan,
       bt.sorteddate bt_sorteddate,
       (select bu.code
          from businessunit bu
         where bu.businessunit_id = pn.processbusinessunit_id) bu_code,
       pn.notenumber,
       (select s.code from status s where pn.status_id = s.status_id) pn_statuscode
  from bagtag bt, packingnote pn, distributionpoint dp, department d, customer c, stay st
 where pn.distributionpoint_id = dp.distributionpoint_id
   and dp.department_id = d.department_id
   and d.customer_id = c.customer_id
   and bt.packingnote_id = pn.packingnote_id
   and bt.stay_id = st.stay_id
   and st.staytype = 6
   and st.staynr in (60, 70)
   and pn.status_id not in (select s.status_id
                          from status s
                         where s.statustype = 'PN'
                           and s.code in (40, 60))
/

  CREATE OR REPLACE VIEW "V_SALESCREDITNOTE" ("CUSTOMERNUMBER", "CUSTOMERNAME", "STREET", "ZIPCODE", "CITY", "WORKORDER_ID", "ORIGIN", "WORKORDERNUMBER", "REFERENCENUMBER", "ORDERDATE", "NEEDEDDATE", "ROUTENUMBER", "ROUTE_DESC", "DAY_DESC", "REMARK", "CREDITWORKORDERNUMBER", "PRODUCTCODE", "SIZECODE", "FINISHINGCODE", "QUALITYGRADECODE", "PRIORITY", "PRODUCTDESC", "QTYSALES", "QUANTITYTOBECREDITED", "INSTRUCTIONS", "LANGUAGECODE", "PRINT_BARCODE", "EMPLOYEENUMBER1", "EMPLOYEENAME1", "EMPLOYEENUMBER2", "EMPLOYEENAME2", "EMP_EMPLOYEENUMBER", "EMP_NAME", "EMP_PHONENO", "EMP_MOBILENO", "EMP_FAXNO", "EMP_EMAIL", "EMP_REMARK", "SALES1_EMPLOYEENUMBER", "SALES1_NAME", "SALES1_PHONENO", "SALES1_MOBILENO", "SALES1_FAXNO", "SALES1_EMAIL", "SALES1_REMARK", "SALES2_EMPLOYEENUMBER", "SALES2_NAME", "SALES2_PHONENO", "SALES2_MOBILENO", "SALES2_FAXNO", "SALES2_EMAIL", "SALES2_REMARK", "SALESPRICE", "DISCOUNTPERCENTAGE", "CODE", "DESCRIPTION", "DELIVERYPOINT_STREET", "DELIVERYPOINT_ZIPCODE", "DELIVERYPOINT_CITY", "DAY_ID", "STARTTIME", "ENDTIME", "BREAKSTARTTIME", "BREAKENDTIME", "WOREFERENCENUMBER_ID", "WOREFERENCENR", "WOREFNR_DESC") AS 
  select
  cu.customernumber, cu.name customerName, address.street, address.zipcode, address.city
, wk.workorder_id, wk.origin -- 6: sales, 7: credit
, wk.workordernumber, wk.referencenumber, wk.requestdate orderDate, wk.neededdate
, r.routenumber, r.description Route_desc
, (select dd.description from day_desc dd where r.drivingday_id=dd.day_id and dd.language_id=languages.language_id) Day_desc
, wk.remark
, wkCredit.Workordernumber CreditWorkordernumber
, prd.code productCode, szlk.code sizecode, fm.code finishingcode, qg.code qualitygradeCode, qg.priority
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( wkli.quantityordered - wkli.quantitycancelled ) QtySales
, wkli.quantitytobecredited
, wkli.instructions
, languages.code languageCode
, (select max(ss.value) from SYSTEMSETTING SS, businessunit bu where wk.businessunit_id = bu.businessunit_id
and bu.plant_id = ss.plant_id and ss.name='PRINTBARCODEONWORKORDER' ) Print_Barcode,
( SELECT emp1.employeenumber FROM employee emp1 WHERE wk.salesemployee1_id = emp1.employee_id) employeenumber1,
( SELECT emp1.name FROM employee emp1 WHERE wk.salesemployee1_id = emp1.employee_id) employeename1,
( SELECT emp2.employeenumber FROM employee emp2 WHERE wk.salesemployee2_id = emp2.employee_id) employeenumber2,
( SELECT emp2.name FROM employee emp2 WHERE wk.salesemployee2_id = emp2.employee_id) employeename2
, emp.employeenumber emp_employeenumber, emp.name emp_name, emp.phoneno emp_phoneno, emp.mobileno emp_mobileno, emp.faxno emp_faxno, emp.email emp_email, emp.remark emp_remark
, sales1_emp.employeenumber sales1_employeenumber, sales1_emp.name  sales1_name, sales1_emp.phoneno sales1_phoneno, sales1_emp.mobileno sales1_mobileno, sales1_emp.faxno sales1_faxno, sales1_emp.email sales1_email, sales1_emp.remark sales1_remark
, sales2_emp.employeenumber sales2_employeenumber, sales2_emp.name sales2_name, sales2_emp.phoneno sales2_phoneno, sales2_emp.mobileno sales2_mobileno, sales2_emp.faxno sales2_faxno, sales2_emp.email sales2_email, sales2_emp.remark sales2_remark
, wkli.salesprice
, wkli.discountpercentage
, dp.code, dp.description
, adr.street deliverypoint_street, adr.zipcode deliverypoint_zipcode, adr.city deliverypoint_city
, getabsdaynumber(wk.neededdate) day_id,
( select dpoh.starttime from deliverypointopeninghour dpoh  where  dp.deliverypoint_id=dpoh.deliverypoint_id
   and disp.deliverypoint_id=dp.deliverypoint_id and dpoh.day_id = getabsdaynumber(wk.neededdate))starttime,
( select dpoh.endtime from deliverypointopeninghour dpoh  where  dp.deliverypoint_id=dpoh.deliverypoint_id
   and disp.deliverypoint_id=dp.deliverypoint_id and dpoh.day_id = getabsdaynumber(wk.neededdate))endtime,
dp.breakstarttime, dp.breakendtime,
wk.woreferencenumber_id,
worefnr.referencenumber woreferencenr,
worefnr.description worefnr_desc
from
  workorder wk
    left outer join workorder wkCredit on wk.creditworkorder_id = wkCredit.Workorder_Id
    left outer join route r on wk.route_id=r.route_id
 left outer join systemuser su on wk.creationuser_id=su.systemuser_id
 left outer join employee emp on su.employee_id=emp.employee_id
left outer join employee sales1_emp on  sales1_emp.employee_id=wk.salesemployee1_id
left outer join employee sales2_emp on  sales2_emp.employee_id=wk.salesemployee2_id
left outer join woreferencenumber worefnr on wk.woreferencenumber_id = worefnr.woreferencenumber_id
, customer cu, workorderline wkli
, product prd, sizedefinition_link szlk, finishingmethod fm, qualitygrade qg
, address, languages
, distributionpoint disp, deliverypoint dp
left outer join address  adr on dp.deliveryaddress_id=adr.address_id
where
    wk.origin in (6, 7)
and wk.customer_link_id = cu.customer_id
and wk.workorder_id = wkli.workorder_id
and wkli.product_link_id = prd.product_id
and wkli.sizedefinition_link_id = szlk.sizedefinition_link_id
and wkli.finishingmethod_id = fm.finishingmethod_id
and wkli.requestedgrade_id = qg.qualitygrade_id
and cu.visitaddress_id=address.address_id
and wk.distributionpoint_link_id=disp.distributionpoint_id
and disp.deliverypoint_id=dp.deliverypoint_id
/

  CREATE OR REPLACE VIEW "V_SALESCREDITNOTETRADE" ("CUSTOMERNUMBER", "CUSTOMERNAME", "STREET", "ZIPCODE", "CITY", "WORKORDER_ID", "ORIGIN", "WORKORDERNUMBER", "REFERENCENUMBER", "ORDERDATE", "NEEDEDDATE", "ROUTENUMBER", "ROUTE_DESC", "DAY_DESC", "REMARK", "CREDITWORKORDERNUMBER", "PRODUCTCODE", "SIZECODE", "FINISHINGCODE", "QUALITYGRADECODE", "PRIORITY", "PRODUCTDESC", "QTYSALES", "QUANTITYTOBECREDITED", "QUANTITYFILLED", "INSTRUCTIONS", "LANGUAGECODE", "PRINT_BARCODE", "EMPLOYEENUMBER1", "EMPLOYEENAME1", "EMPLOYEENUMBER2", "EMPLOYEENAME2", "EMP_EMPLOYEENUMBER", "EMP_NAME", "EMP_PHONENO", "EMP_MOBILENO", "EMP_FAXNO", "EMP_EMAIL", "EMP_REMARK", "SALES1_EMPLOYEENUMBER", "SALES1_NAME", "SALES1_PHONENO", "SALES1_MOBILENO", "SALES1_FAXNO", "SALES1_EMAIL", "SALES1_REMARK", "SALES2_EMPLOYEENUMBER", "SALES2_NAME", "SALES2_PHONENO", "SALES2_MOBILENO", "SALES2_FAXNO", "SALES2_EMAIL", "SALES2_REMARK", "SALESPRICE", "DISCOUNTPERCENTAGE", "CODE", "DESCRIPTION", "DELIVERYPOINT_STREET", "DELIVERYPOINT_ZIPCODE", "DELIVERYPOINT_CITY", "DAY_ID", "STARTTIME", "ENDTIME", "BREAKSTARTTIME", "BREAKENDTIME", "WOREFERENCENUMBER_ID", "WOREFERENCENR", "WOREFNR_DESC", "DEBTORNUMBER", "DEBTORNAME", "CONTACTPERSONNUMBER", "CONTACTPERSON", "COMMMETHODCODE", "COMMMETHODDESCR", "SHIPMENTTYPECODE", "SHIPMENTTYPEDESCR", "DELIVERYTERMCODE", "DELIVERYTERMDESCR", "EMPLOYEENUMBER", "EMPLOYEENAME", "APPROVALTIMESTAMP", "OFFER", "BLOCKEDFORINVOICING", "BLOCKED", "ALLOWPARTIALINVOICING", "WODISCOUNTPERCENTAGE", "EXTERNALREMARK", "SALESORDERLINESTOTALAMOUNT", "SALESORDERLINESTOTALNETAMOUNT", "SALESORDERLINESEMBLTOTALAMT", "SALESORDERLINESEMBTOTNETAMT", "SALESORDERLINESTOTALDISCOUNT", "SALESORDERLINESEMBTOTDISC", "THEORETICALWEIGHT", "DELIVERYTERMUNITPRICE", "TRANSPORTCOSTS", "VATAMOUNT", "SALESORDERTOTALNETAMOUNT", "SALESORDERTOTALGROSSAMOUNT", "SALESORDERGODAMOUNT", "DECIMALS", "INVOICEAMOUNTDECIMALS") AS 
  select /*version 1.0*/
       cu.customernumber, cu.name customername, vad.street, vad.zipcode, vad.city,
       wk.workorder_id, wk.origin,-- 6: sales, 7: credit
       wk.workordernumber, wk.referencenumber, wk.requestdate orderdate, wk.neededdate,
       r.routenumber, r.description route_desc,
       (select dd.description
          from day_desc dd
         where r.drivingday_id = dd.day_id
           and dd.language_id = lan.language_id) day_desc,
       wk.remark, wkcredit.workordernumber creditworkordernumber,
       prdlk.code productcode, szlk.code sizecode,
       fm.code finishingcode, qg.code qualitygradecode, qg.priority,
       (select prlkd.description
          from product_link_desc prlkd
         where prlkd.product_link_id = prdlk.product_link_id
           and prlkd.language_id = lan.language_id) productdesc,
       (wkli.quantityordered - wkli.quantitycancelled) qtysales, wkli.quantitytobecredited,
       wkli.quantityfilled, wkli.instructions, lan.code languagecode,
       (select max(ss.value)
          from systemsetting ss, businessunit bu
         where wk.businessunit_id = bu.businessunit_id
           and bu.plant_id = ss.plant_id
           and ss.name = 'PRINTBARCODEONWORKORDER') print_barcode,
       sales1_emp.employeenumber employeenumber1, sales1_emp.name employeename1,
       sales2_emp.employeenumber employeenumber2, sales2_emp.name employeename2,
       cemp.employeenumber emp_employeenumber, cemp.name emp_name, cemp.phoneno emp_phoneno,
       cemp.mobileno emp_mobileno, cemp.faxno emp_faxno, cemp.email emp_email, cemp.remark emp_remark,
       sales1_emp.employeenumber sales1_employeenumber, sales1_emp.name sales1_name,
       sales1_emp.phoneno sales1_phoneno, sales1_emp.mobileno sales1_mobileno,
       sales1_emp.faxno sales1_faxno, sales1_emp.email sales1_email, sales1_emp.remark sales1_remark,
       sales2_emp.employeenumber sales2_employeenumber, sales2_emp.name sales2_name,
       sales2_emp.phoneno sales2_phoneno, sales2_emp.mobileno sales2_mobileno,
       sales2_emp.faxno sales2_faxno, sales2_emp.email sales2_email, sales2_emp.remark sales2_remark,
       wkli.salesprice, wkli.discountpercentage, dp.code, dp.description,
       adr.street deliverypoint_street, adr.zipcode deliverypoint_zipcode,
       adr.city deliverypoint_city, getabsdaynumber(wk.neededdate) day_id,
       (select dpoh.starttime
          from deliverypointopeninghour dpoh
         where dp.deliverypoint_id = dpoh.deliverypoint_id
           and disp.deliverypoint_id = dp.deliverypoint_id
           and dpoh.day_id = getabsdaynumber(wk.neededdate)) starttime,
       (select dpoh.endtime
          from deliverypointopeninghour dpoh
         where dp.deliverypoint_id = dpoh.deliverypoint_id
           and disp.deliverypoint_id = dp.deliverypoint_id
           and dpoh.day_id = getabsdaynumber(wk.neededdate)) endtime, dp.breakstarttime,
       dp.breakendtime, wk.woreferencenumber_id, worefnr.referencenumber woreferencenr,
       worefnr.description worefnr_desc,
       (select cu_debtor.customernumber
          from customer cu_debtor
         where cu_debtor.customer_id = wk.debtor_id) debtornumber,
       (select cu_debtor.name from customer cu_debtor where cu_debtor.customer_id = wk.debtor_id) debtorname,
       (select cp.contactpersonnumber
          from contactperson cp
         where cp.contactperson_id = wk.contactperson_id) contactpersonnumber,
       (select cp.name from contactperson cp where cp.contactperson_id = wk.contactperson_id) contactperson,
       (select cm.code
          from communicationmethod cm
         where cm.communicationmethod_id = wk.communicationmethod_id) commmethodcode,
       (select cmdesc.description
          from communicationmethod_desc cmdesc
         where cmdesc.communicationmethod_id = wk.communicationmethod_id
           and cmdesc.language_id = lan.language_id) commmethoddescr,
       (select shipt.code from shipmenttype shipt where shipt.shipmenttype_id = wk.shipmenttype_id) shipmenttypecode,
       (select shiptdesc.description
          from shipmenttype_desc shiptdesc
         where shiptdesc.shipmenttype_id = wk.shipmenttype_id
           and shiptdesc.language_id = lan.language_id) shipmenttypedescr,
       (select dt.code from deliveryterm dt where dt.deliveryterm_id = wk.deliveryterm_id) deliverytermcode,
       (select dtdesc.description
          from deliveryterm_desc dtdesc
         where dtdesc.deliveryterm_id = wk.deliveryterm_id
           and dtdesc.language_id = lan.language_id) deliverytermdescr,
       aemp.employeenumber employeenumber, aemp.name employeename,
       wk.approvaltimestamp, wk.offer, wk.blockedforinvoicing, wk.blocked, wk.allowpartialinvoicing,
       wk.discountpercentage wodiscountpercentage, wk.externalremark,
       pack_trade.getsalesorderlinestotalamount(wk.workorder_id) salesorderlinestotalamount,
       pack_trade.getsalesorderlinestotalnetamt(wk.workorder_id) salesorderlinestotalnetamount,
       pack_trade.getsalesorderlinesembltotalamt(wk.workorder_id) salesorderlinesembltotalamt,
       pack_trade.getsalesordlinesembtotnetamt(wk.workorder_id, bu.plant_id) salesorderlinesembtotnetamt,
       pack_trade.getsalesordlinestotaldisc(wk.workorder_id) salesorderlinestotaldiscount,
       pack_trade.getsalesordlinesembtotdisc(wk.workorder_id, bu.plant_id) salesorderlinesembtotdisc,
       wk.theoreticalweight,
       pack_trade.getdeliverytermunitprice(wk.workorder_id, wk.theoreticalweight, sysdate) deliverytermunitprice,
       wk.transportcosts, pack_trade.getsalesordertotalvat(wk.workorder_id, bu.plant_id) vatamount,
       pack_trade.getsalesordertotalnetamount(wk.workorder_id, bu.plant_id) salesordertotalnetamount,
       pack_trade.getsalesordertotalgrossamount(wk.workorder_id, bu.plant_id) salesordertotalgrossamount,
       pack_trade.getsalesordergodamount(wk.workorder_id, bu.plant_id) salesordergodamount,
       cur.decimals, cur.invoiceamountdecimals
  from workorderline wkli
       join workorder wk
            left join workorder wkcredit on wk.creditworkorder_id = wkcredit.workorder_id
            left join route r on wk.route_id = r.route_id
            left join employee sales1_emp on wk.salesemployee1_id = sales1_emp.employee_id
            left join employee sales2_emp on wk.salesemployee2_id = sales2_emp.employee_id
            left join woreferencenumber worefnr on wk.woreferencenumber_id = worefnr.woreferencenumber_id
            left join systemuser csu
                 left join employee cemp on csu.employee_id = cemp.employee_id
            on wk.creationuser_id = csu.systemuser_id
            left join systemuser asu
                 left join employee aemp on asu.employee_id = aemp.employee_id
            on wk.approvaluser_id = asu.systemuser_id
            join customer cu
                 join address vad on cu.visitaddress_id = vad.address_id
                 join languages lan on cu.language_id = lan.language_id
                 join currency cur on cu.currency_id = cur.currency_id
            on wk.customer_link_id = cu.customer_id
            join businessunit bu on wk.businessunit_id = bu.businessunit_id
       on wkli.workorder_id = wk.workorder_id
       join product_link prdlk on wkli.product_link_id = prdlk.product_link_id
       join sizedefinition_link szlk on wkli.sizedefinition_link_id = szlk.sizedefinition_link_id
       join finishingmethod fm on wkli.finishingmethod_id = fm.finishingmethod_id
       join qualitygrade qg on wkli.requestedgrade_id = qg.qualitygrade_id
       join distributionpoint disp
            join deliverypoint dp
                 join address adr on dp.deliveryaddress_id = adr.address_id
            on disp.deliverypoint_id = dp.deliverypoint_id
       on wk.distributionpoint_link_id = disp.distributionpoint_id
 where wk.origin in (6, 7)
/

  CREATE OR REPLACE VIEW "V_SALESJOURNALGROUP" ("CODE", "DESCRIPTION", "ACTIVE", "SYSTEMUSER_ID", "TIMESTAMP", "SALESJOURNALGROUP_ID", "LANGUAGECODE") AS 
  select a.code,
 (SELECT description FROM salesjournalgroup_DESC b WHERE b.salesjournalgroup_id = a.salesjournalgroup_id
  AND b.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) description,
 a.active, a.systemuser_id, a.timestamp, a.salesjournalgroup_id, languages.code LANGUAGECODE
from salesjournalgroup a, languages
/

  CREATE OR REPLACE VIEW "V_SALESJOURNALHISTORY" ("INVOICEBUSINESSUNIT_ID", "BU_CODE", "BU_DESC", "PLANT_ID", "PL_CODE", "PL_NAME", "INVOICEDATE", "INVOICELINETYPE", "TURNOVERGROUP_CODE", "TURNOVERGROUP_DESC", "PRODUCT_DESC", "PRODUCT_CODE", "PRODUCTGROUPCODE", "PRODUCTGROUPDESCRIPTION", "ROUTENUMBER", "WEEKNR", "AMOUNT", "LANGUAGE_CODE", "BILLEDQTY", "PRICE") AS 
  select ih.invoicebusinessunit_id, bu.code Bu_code, bu.description Bu_desc, pl.plant_id, Pl.Code Pl_code, Pl.Name Pl_name,
       ih.invoicedate, ilt.type InvoicelineType, tg.code TurnoverGroup_code,
       (select tgd.description from turnovergroup_desc tgd where tg.turnovergroup_id = tgd.turnovergroup_id and tgd.language_id = lan.language_id) TurnoverGroup_desc,
       (select pd.description from product_desc pd where p.product_id = pd.product_id and pd.language_id = pl.language_id) Product_desc,
       p.code Product_code, ilp.productgroupcode, ilp.productgroupdescription, ih.routenumber,
       GETISOWEEK(ih.invoicedate) weeknr,
       case when il.adjustmentreason_id is null then il.amount else il.adjustedamount end Amount,
       lan.code Language_code, il.billedqty, il.price
from invoiceheader ih, status st, invoiceline il
       left outer join turnovergroup tg on il.turnovergroup_id = tg.turnovergroup_id
     , invoicelinetype ilt, invoicelineproduct ilp, product p, businessunit bu , plant pl, languages lan
where ih.documenttype = 1 and ih.status_id = st.status_id and st.statustype = 'IN' and st.code = 2
      and il.extend='Y'
      and ih.invoiceheader_id = il.invoiceheader_id and il.invoicelinetype_id = ilt.invoicelinetype_id
      ---select only lines with ilp and with products linked to that ilp
      and il.invoiceline_id=ilp.invoiceline_id and ilp.product_link_id = p.product_id
      and ih.invoicebusinessunit_id = bu.businessunit_id --and bu.plant_id = pl.plant_id
/

  CREATE OR REPLACE VIEW "V_SALESSTATISTICS" ("DELIVERYDATE", "BILLNUMBER", "CUSTOMERNUMBER", "NETTOAMOUNT", "TOTALAMOUNT") AS 
  select
  pn.deliverydate, bill.customernumber billNumber, cu.customernumber
, sum( F_GETDELPRODPRICEWITHDISC( cu.customer_id, pnl.product_id, pnl.sizedefinition_id, pnl.finishingmethod_id, pn.deliverydate, prd.typeofmerchandise
  ) * pnl.deliveredamount ) NettoAmount
, sum( F_GETDELPRODPRICEWITHDISC( cu.customer_id, pnl.product_id, pnl.sizedefinition_id, pnl.finishingmethod_id, pn.deliverydate, prd.typeofmerchandise )
  * pnl.deliveredamount
  * (( 100 + F_TAXRATE(cu.customer_id, pnl.product_id, cu.country_id, trunc(sysdate))) / 100 )
  ) TotalAmount
from
  packingnote pn, status st, packingnoteline pnl, product prd
, distributionpoint dip, department dep, customer cu, customer bill
where
    pn.status_id = st.status_id
and st.statustype = 'PN'
    and st.code = '30'
and pn.packingnote_id = pnl.packingnote_id
    and pnl.product_id = prd.product_id
and pn.distributionpoint_id = dip.distributionpoint_id
    and dip.department_id = dep.department_id
        and dep.customer_id = cu.customer_id
            and cu.debtor_id = bill.customer_id
group by pn.deliverydate, bill.customernumber, cu.customernumber
/

  CREATE OR REPLACE VIEW "V_SCANNINGRECON" ("BU_CODE", "BU_DESC", "ROUTENUMBER", "DAYNR", "PRIMARYID", "TRANSACTIONTYPE_ID", "SCANDAYNR", "SCANTIMESTAMP", "SCANDATE", "TRANSACTIONTYPEDESC", "PROD_CODE", "PROD_DESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "WEARERNAME", "LANGUAGECODE") AS 
  select /*version 1.4*/
       bu.code bu_code, bu.description bu_desc,
       nvl(ro.routenumber, (select min(ro2.routenumber)
                              from routestop rs
                                   join route ro2 on rs.route_id = ro2.route_id
                             where rs.customer_id = s.customer_link_id
                               and rs.dateactive <= trunc(s.scantimestamp)
                               and rs.dateinactive >= trunc(s.scantimestamp))) routenumber,
       nvl(ro.drivingday_id, (select min(ro2.drivingday_id)
                                from routestop rs
                                     join route ro2 on rs.route_id = ro2.route_id
                               where rs.customer_id = s.customer_link_id
                                 and rs.dateactive <= trunc(s.scantimestamp)
                                 and rs.dateinactive >= trunc(s.scantimestamp))) daynr,
       s.primaryid, s.transactiontype_id,
       getabsdaynumber(s.scantimestamp) scandaynr,
       s.scantimestamp, trunc(s.scantimestamp) scandate,
       (select ttd.description
          from transactiontype_desc ttd
         where ttd.transactiontype_id = s.transactiontype_id
           and ttd.language_id = lan.language_id) transactiontypedesc,
       (select pr.code from product pr where s.product_link_id = pr.product_id) prod_code,
       (select prd.description
          from product_desc prd
         where prd.product_id = s.product_link_id
           and prd.language_id = lan.language_id) prod_desc,
       cu.customernumber, cu.name customername,
       wel.wearernumber, wel.wearername, lan.code languagecode
  from scan s
       left join route ro on s.route_id = ro.route_id
       left join customer cu on s.customer_link_id = cu.customer_id
       left join weareremployment_link wel on s.weareremployment_link_id = wel.weareremployment_link_id
       join businessunit bu on s.businessunit_id = bu.businessunit_id
       cross join languages lan
 where s.transactiontype_id in (2, 15, 16, 42, 75)
/

  CREATE OR REPLACE VIEW "V_SCANNINGSPERCUSTOMER" ("CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEBTORNUMBER", "MASTERACCOUNT", "MASTERACCOUNTNUMBER", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "CITY", "PHONENO", "FAXNO", "PRODUCTCODE", "TRANSACTIONTYPE", "SCANDATE", "BUSINESSUNIT_ID", "SCANDATETRUNC", "LANGUAGECODE", "DEFAULTBUSINESSUNIT_ID", "WEARERNUMBER", "WEARERNAME", "BANK", "LOCKER", "LOCKERSTATUS", "BU_CODE", "PHONELEN", "PRODUCTDESCRIPTION", "PRIMARYID") AS 
  select /*version 2.0*/
       cu.customer_id, cu.customernumber, cu.name customername, deb.customernumber debtornumber,
       cu.masteraccount, macc.customernumber masteraccountnumber,delk.departmentnumber departmentnumber,
       delk.description departmentdesc, mad.city, cu.phoneno, cu.faxno, prd.code productcode,
       trt.transactiontype_id transactiontype, sc.scantimestamp scandate, sc.businessunit_id,
       trunc(sc.scantimestamp) scandatetrunc, lan.code languagecode, cu.defaultbusinessunit_id,
       wel.wearernumber, wel.wearername, lo.bank, lo.locker, lo.lockerstatus,
       (select bus.code from businessunit bus
         where bus.businessunit_id = sc.businessunit_id) bu_code,
       cast((select ss.value
               from systemsetting ss
              where ss.plant_id = bu.plant_id
                and ss.name = 'PHONEFAXLENGTH') as varchar2(16)) phonelen,
       (select prde.description
          from product_desc prde
         where prde.product_id = prd.product_id
           and prde.language_id = lan.language_id) productdescription,
       case when length(sc.primaryid) = 24
             and nvl((select ss.value
                        from systemsetting ss
                       where ss.plant_id = bu.plant_id
                         and ss.name = 'USEURICODE'), 0) = 1
       then pack_epc_sgtin96.decode(sc.primaryid)
       else sc.primaryid end primaryid
  from scan sc
       left join weareremployment_link wel
            left join weareremployment we
                 left join locker lo on we.locker_id = lo.locker_id
            on nvl(wel.weareremployment_id, wel.weareremployment_link_id) = we.weareremployment_id
       on sc.weareremployment_link_id = wel.weareremployment_link_id
       left join distributionpoint_link dilk
            join department_link delk on dilk.department_link_id = delk.department_link_id
       on sc.distributionpoint_link_id = dilk.distributionpoint_link_id
       join customer cu
            join customer deb on cu.debtor_id = deb.customer_id
            join customer macc on cu.masteraccount_id = macc.customer_id
            join businessunit bu on cu.defaultbusinessunit_id = bu.businessunit_id
            join address mad on cu.mailaddress_id = mad.address_id
       on sc.customer_link_id = cu.customer_id
       join product prd on sc.product_link_id = prd.product_id
       join stay on sc.stay_id = stay.stay_id
       join transactiontype trt on sc.transactiontype_id = trt.transactiontype_id
       cross join languages lan
 where (stay.staynr <> 21 and stay.staynr <> 22 and stay.staynr <> 23)
   and (trt.transactiontype_id <> 10 and trt.transactiontype_id <> 11 and
       trt.transactiontype_id <> 30 and trt.transactiontype_id <> 31 and
       trt.transactiontype_id <> 32 and trt.transactiontype_id <> 33 and
       trt.transactiontype_id <> 40 and trt.transactiontype_id <> 41 and
       trt.transactiontype_id <> 50 and trt.transactiontype_id <> 51 and
       trt.transactiontype_id <> 52 and trt.transactiontype_id <> 53 and
       trt.transactiontype_id <> 60 and trt.transactiontype_id <> 80 and
       trt.transactiontype_id <> 81 and trt.transactiontype_id <> 0)
/

  CREATE OR REPLACE VIEW "V_SCANNINGSPERCUSTOMERTOTALNRP" ("CUSTOMER_ID", "CUSTOMERNUMBER", "DEBTORNUMBER", "MASTERACCOUNT", "MASTERACCOUNTNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "CITY", "PHONENO", "FAXNO", "PRODUCTCODE", "PRODUCTDESCRIPTION", "TRANSACTIONTYPE", "SCANDATE", "SCANDATETRUNC", "LANGUAGECODE", "BUSINESSUNIT_ID", "DEFAULTBUSINESSUNIT_ID", "COUNTID") AS 
  select cu.customer_id, cu.customernumber,
       deb.customernumber debtornumber,
       cu.masteraccount,
       macc.customernumber masteraccountnumber,
       cu.name customername,
       coalesce((select de.departmentnumber
                 from   department de, distributionpoint di
                 where  de.department_id = di.department_id
                 and    di.distributionpoint_id = scan.distributionpoint_link_id), -1) departmentnumber,
       (select de.description
         from   department de, distributionpoint di
         where  de.department_id = di.department_id
         and    di.distributionpoint_id = scan.distributionpoint_link_id) departmentdesc,
       address.city, cu.phoneno, cu.faxno, prd.code productcode,
       (select product_desc.description
         from   product_desc
         where  product_desc.product_id = prd.product_id
         and    product_desc.language_id = languages.language_id) productdescription,
       transactiontype.transactiontype_id transactiontype, scan.scantimestamp scandate, TRUNC(scan.scantimestamp) scandatetrunc,
       languages.code languagecode, scan.businessunit_id, cu.defaultbusinessunit_id,
       count(scan.primaryid) CountID --rp.reportparam_id
from customer cu, customer deb, customer macc, address, product prd, stay, transactiontype, languages, scan  --reportparam rp
where cu.mailaddress_id = address.address_id
and cu.customer_id = scan.customer_link_id
and prd.product_id = scan.product_link_id
and stay.stay_id = scan.stay_id
and (stay.staynr <> 21 and stay.staynr <> 22 and stay.staynr <> 23)
and transactiontype.transactiontype_id = scan.transactiontype_id
and (transactiontype.transactiontype_id <> 10 and transactiontype.transactiontype_id <> 11 and
    transactiontype.transactiontype_id <> 30 and transactiontype.transactiontype_id <> 31 and
    transactiontype.transactiontype_id <> 32 and transactiontype.transactiontype_id <> 33 and
    transactiontype.transactiontype_id <> 40 and transactiontype.transactiontype_id <> 41 and
    transactiontype.transactiontype_id <> 50 and transactiontype.transactiontype_id <> 51 and
    transactiontype.transactiontype_id <> 52 and transactiontype.transactiontype_id <> 53 and
    transactiontype.transactiontype_id <> 60 and transactiontype.transactiontype_id <> 80 and
    transactiontype.transactiontype_id <> 81)
and deb.customer_id = cu.debtor_id
and macc.customer_id = cu.masteraccount_id
/*and (
    (rp.number_value5 = 1 and cu.customernumber >= rp.number_value1 and cu.customernumber <= rp.number_value2)
    or (rp.number_value5 = 2 and deb.customernumber >= rp.number_value1 and deb.customernumber <= rp.number_value2)
    or (rp.number_value5 = 3 and macc.customernumber >= rp.number_value1 and macc.customernumber <= rp.number_value2)
)*/
--and prd.code >= rp.string_value1 and prd.code <= rp.string_value2
--and languages.code = rp.string_value
--and trunc(scan.scantimestamp) >= rp.date_value1 and trunc(scan.scantimestamp) < rp.date_value2 --filter also in the report, if is slow here then it must be commented
--and ((upper(rp.string_value3) <> 'TRUE')--Customer BU Filter
  --  or (upper(rp.string_value3) = 'TRUE'
    -- and --(cu.defaultbusinessunit_id = rp.number_value9 or
          --  exists (select 1 from customeractivities ca where ca.customer_id = cu.customer_id /*and
            --( ca.processbusinessunit_id = rp.number_value9 or ca.internalprocessingbu_id = rp.number_value9 ) */)
    --)
--and ((upper(rp.string_value4) <> 'TRUE')--Product BU Filter
 --   or (upper(rp.string_value4) = 'TRUE' and scan.businessunit_id = rp.number_value9)
 --   )
group by /*rp.reportparam_id,*/ cu.customer_id, cu.customernumber, deb.customernumber, cu.masteraccount, macc.customernumber, cu.name, languages.code, scan.businessunit_id,
       scan.distributionpoint_link_id, address.city, cu.phoneno, cu.faxno, prd.code, prd.product_id, languages.language_id, transactiontype.transactiontype_id, scan.scantimestamp,cu.defaultbusinessunit_id
/

  CREATE OR REPLACE VIEW "V_SCANNINGSPERCUSTOMER_NORP" ("CUSTOMER_ID", "CUSTOMERNUMBER", "DEBTORNUMBER", "MASTERACCOUNT", "MASTERACCOUNTNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "CITY", "PHONENO", "FAXNO", "PRODUCTCODE", "PRODUCTDESCRIPTION", "TRANSACTIONTYPE", "SCANDATE", "SCANDATETRUNC", "LANGUAGECODE", "BUSINESSUNIT_ID", "DEFAULTBUSINESSUNIT_ID", "PRIMARYID", "WEARERNUMBER", "WEARERNAME") AS 
  select cu.customer_id, cu.customernumber,
       deb.customernumber debtornumber,
       cu.masteraccount,
       macc.customernumber masteraccountnumber,
       cu.name customername,
       coalesce((select de.departmentnumber
                 from   department de, distributionpoint di
                 where  de.department_id = di.department_id
                 and    di.distributionpoint_id = scan.distributionpoint_link_id), -1) departmentnumber,
       (select de.description
         from   department de, distributionpoint di
         where  de.department_id = di.department_id
         and    di.distributionpoint_id = scan.distributionpoint_link_id) departmentdesc,
       address.city, cu.phoneno, cu.faxno, prd.code productcode,
       (select product_desc.description
         from   product_desc
         where  product_desc.product_id = prd.product_id
         and    product_desc.language_id = languages.language_id) productdescription,
 transactiontype.transactiontype_id transactiontype,  scan.scantimestamp scandate, TRUNC(scan.scantimestamp) scandatetrunc,
       languages.code languagecode, scan.businessunit_id, cu.defaultbusinessunit_id,
       scan.primaryid, we.wearernumber, we.wearername  --, rp.reportparam_id
from customer cu, customer deb, customer macc, address, product prd, stay, transactiontype, scan
       left outer join weareremployment_link we on scan.weareremployment_link_id = we.weareremployment_link_id
       , languages --, reportparam rp
where cu.mailaddress_id = address.address_id
and cu.customer_id = scan.customer_link_id
and prd.product_id = scan.product_link_id
and stay.stay_id = scan.stay_id
and (stay.staynr <> 21 and stay.staynr <> 22 and stay.staynr <> 23)
and transactiontype.transactiontype_id = scan.transactiontype_id
and (transactiontype.transactiontype_id <> 10 and transactiontype.transactiontype_id <> 11 and
    transactiontype.transactiontype_id <> 30 and transactiontype.transactiontype_id <> 31 and
    transactiontype.transactiontype_id <> 32 and transactiontype.transactiontype_id <> 33 and
    transactiontype.transactiontype_id <> 40 and transactiontype.transactiontype_id <> 41 and
    transactiontype.transactiontype_id <> 50 and transactiontype.transactiontype_id <> 51 and
    transactiontype.transactiontype_id <> 52 and transactiontype.transactiontype_id <> 53 and
    transactiontype.transactiontype_id <> 60 and transactiontype.transactiontype_id <> 80 and
    transactiontype.transactiontype_id <> 81)
and deb.customer_id = cu.debtor_id
and macc.customer_id = cu.masteraccount_id
/*and (
    (rp.number_value5 = 1 and cu.customernumber >= rp.number_value1 and cu.customernumber <= rp.number_value2)
    or (rp.number_value5 = 2 and deb.customernumber >= rp.number_value1 and deb.customernumber <= rp.number_value2)
    or (rp.number_value5 = 3 and macc.customernumber >= rp.number_value1 and macc.customernumber <= rp.number_value2)
)
and prd.code >= rp.string_value1 and prd.code <= rp.string_value2
and languages.code = rp.string_value
and trunc(scan.scantimestamp) >= rp.date_value1 and trunc(scan.scantimestamp) < rp.date_value2 --filter also in the report, if is slow here then it must be commented
and ((upper(rp.string_value3) <> 'TRUE')--Customer BU Filter
    or (upper(rp.string_value3) = 'TRUE'
       and (cu.defaultbusinessunit_id = rp.number_value9 or
            exists (select 1 from customeractivities ca where ca.customer_id = cu.customer_id
            and (ca.processbusinessunit_id = rp.number_value9 or ca.internalprocessingbu_id = rp.number_value9) )))
    )
and ((upper(rp.string_value4) <> 'TRUE')--Product BU Filter
    or (upper(rp.string_value4) = 'TRUE' and scan.businessunit_id = rp.number_value9)
    )
    */
/*group by rp.reportparam_id, cu.customer_id, cu.customernumber,
       deb.customernumber, cu.masteraccount,
       macc.customernumber, cu.name,
       scan.distributionpoint_link_id,
       address.city, cu.phoneno, cu.faxno, prd.code,
       prd.product_id, languages.language_id, transactiontype.transactiontype_id,
       languages.code, scan.businessunit_id, scan.primaryid, we.wearernumber, we.wearername*/
/

  CREATE OR REPLACE VIEW "V_SCANNINGSPERCUSTOMER_TOTAL" ("CUSTOMER_ID", "CUSTOMERNUMBER", "DEBTORNUMBER", "MASTERACCOUNT", "MASTERACCOUNTNUMBER", "CUSTOMERNAME", "CITY", "PHONENO", "FAXNO", "PRODUCTCODE", "TRANSACTIONTYPE", "BUSINESSUNIT_ID", "SCANDATETRUNC", "LANGUAGECODE", "DEFAULTBUSINESSUNIT_ID", "BU_CODE", "PHONELEN", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "PRODUCTDESCRIPTION", "COUNTID") AS 
  select /*version 2.0*/
       cu.customer_id, cu.customernumber, deb.customernumber debtornumber, cu.masteraccount,
       macc.customernumber masteraccountnumber, cu.name customername, mad.city, cu.phoneno,
       cu.faxno, prd.code productcode, trt.transactiontype_id transactiontype, sc.businessunit_id,
       trunc(sc.scantimestamp) scandatetrunc, lan.code languagecode, cu.defaultbusinessunit_id,
       (select bus.code from businessunit bus where bus.businessunit_id = sc.businessunit_id) bu_code,
       cast((select ss.value
               from systemsetting ss, businessunit bu
              where cu.defaultbusinessunit_id = bu.businessunit_id
                and ss.plant_id = bu.plant_id
                and ss.name = 'PHONEFAXLENGTH') as varchar2(16)) phonelen,
       coalesce((select de.departmentnumber
                   from distributionpoint di
                        join department de on di.department_id = de.department_id
                  where di.distributionpoint_id = sc.distributionpoint_link_id), -1) departmentnumber,
       (select de.description
          from distributionpoint di
               join department de on di.department_id = de.department_id
         where di.distributionpoint_id = sc.distributionpoint_link_id) departmentdesc,
       (select prde.description
          from product_desc prde
         where prde.product_id = prd.product_id
           and prde.language_id = lan.language_id) productdescription,
       count(sc.primaryid) countid
  from scan sc
       join customer cu
            join customer macc on cu.masteraccount_id = macc.customer_id
            join customer deb on cu.debtor_id = deb.customer_id
            join address mad on cu.mailaddress_id = mad.address_id
       on sc.customer_link_id = cu.customer_id
       join product prd on sc.product_link_id = prd.product_id
       join stay on sc.stay_id = stay.stay_id
       join transactiontype trt on sc.transactiontype_id = trt.transactiontype_id
       cross join languages lan
 where (stay.staynr <> 21 and stay.staynr <> 22 and stay.staynr <> 23)
   and (trt.transactiontype_id <> 10 and trt.transactiontype_id <> 11 and
       trt.transactiontype_id <> 30 and trt.transactiontype_id <> 31 and
       trt.transactiontype_id <> 32 and trt.transactiontype_id <> 33 and
       trt.transactiontype_id <> 40 and trt.transactiontype_id <> 41 and
       trt.transactiontype_id <> 50 and trt.transactiontype_id <> 51 and
       trt.transactiontype_id <> 52 and trt.transactiontype_id <> 53 and
       trt.transactiontype_id <> 60 and trt.transactiontype_id <> 80 and
       trt.transactiontype_id <> 81 and trt.transactiontype_id <> 0)
 group by cu.customer_id, cu.customernumber, deb.customernumber, cu.masteraccount,
          macc.customernumber, cu.name, lan.code, sc.businessunit_id, sc.distributionpoint_link_id,
          mad.city, cu.phoneno, cu.faxno, prd.code, prd.product_id, lan.language_id,
          trt.transactiontype_id, trunc(sc.scantimestamp), cu.defaultbusinessunit_id
/

  CREATE OR REPLACE VIEW "V_SCANS" ("CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "TRANSACTIONTYPE_ID", "TRANSACTIONTYPEDESC", "WORKSTATIONCODE", "WORKSTATIONDESC", "USERNAME", "FULLNAME", "SCANTIMESTAMP", "SCANDATE", "LANGUAGECODE", "SCANTIME_NUMBER", "PRIMARYID", "BUSINESSUNITCODE", "BUSINESSUNIT_ID", "PLANTDEPARTMENTCODE", "PLANTDEPARTMENTDESC", "REASON_CODE", "ROUTENUMBER", "QUALITYTESTTYPE_CODE", "QUALITYTESTTYPE_DESC", "TREATMENTTYPE_CODE", "TREATMENTTYPE_DESC", "SCANTIME_CHAR", "REPORTPARAM_ID", "NUMBER_VALUE5", "NUMBER_VALUE6") AS 
  select --+ INDEX (scan XSPEEDSCAN)
       /*version 2.1*/
       culk.customer_id, culk.customernumber, culk.name customername, s.transactiontype_id,
       (select ttd.description
          from transactiontype_desc ttd
         where ttd.transactiontype_id = s.transactiontype_id
           and ttd.language_id = lan.language_id) transactiontypedesc,
       nvl(wst.code, ' ') workstationcode, wst.description workstationdesc, sy.username,
       sy.fullname, s.scantimestamp, trunc(s.scantimestamp) scandate, lan.code languagecode,
       gettimeasnumeric(s.scantimestamp) scantime_number, s.primaryid, bu.code businessunitcode,
       bu.businessunit_id, pd.code plantdepartmentcode, pd.description plantdepartmentdesc,
       (select rc.code from reasoncode rc where s.reasoncode_id = rc.reasoncode_id) reason_code,
       (select r.routenumber from route r where s.route_id = r.route_id) routenumber,
       (select qtt.code from qualitytesttype qtt where s.qualitytesttype_id = qtt.qualitytesttype_id) qualitytesttype_code,
       (select qttd.description
          from qualitytesttype_desc qttd
         where s.qualitytesttype_id = qttd.qualitytesttype_id
           and qttd.language_id = lan.language_id) qualitytesttype_desc,
       (select tt.code
          from treatmenttype tt, treatmentscan ts
         where ts.scan_id = s.scan_id
           and ts.treatmenttype_id = tt.treatmenttype_id) treatmenttype_code,
       (select ttd.description
          from treatmenttype_desc ttd, treatmentscan ts
         where ts.scan_id = s.scan_id
           and ts.treatmenttype_id = ttd.treatmenttype_id
           and ttd.language_id = lan.language_id) treatmenttype_desc,
       to_char(s.scantimestamp, 'HH24:MI:SS') scantime_char, rp.reportparam_id, rp.number_value5,
       rp.number_value6
  from scan s
       left join workstation wst
            join plantdepartment pd on wst.plantdepartment_id = pd.plantdepartment_id
       on s.scanstation = wst.code
       left join customer culk on s.customer_link_id = culk.customer_id
       join businessunit bu on s.businessunit_id = bu.businessunit_id
       join systemuser sy on s.systemuser_id = sy.systemuser_id
       join transactiontype tt on s.transactiontype_id = tt.transactiontype_id
       join reportparam rp
            join languages lan on rp.string_value = lan.code
       on (trunc(s.scantimestamp) >= trunc(rp.date_value1) and trunc(s.scantimestamp) < trunc(rp.date_value2))
 where nvl(culk.customernumber, 0) >= rp.number_value1
   and nvl(culk.customernumber, 999999999999) <= rp.number_value2
   and nvl(sy.username, ' ') >= nvl(rp.string_value3, ' ')
   and nvl(sy.username, ' ') <= nvl(rp.string_value4, 'ZZZZZZZZZZZZZZZZZZZZZ')
   and (nvl(wst.code, ' ') >= nvl(rp.string_value5, ' '))
   and (nvl(wst.code, ' ') <= nvl(rp.string_value6, 'ZZZZZZZZZZZZ'))
   and (nvl(rp.string_value8, '-') = '-' or
        (nvl(rp.string_value8, ' ') <> '-' and nvl(pd.code, ' ') >= rp.string_value7 and
         nvl(pd.code, ' ') <= rp.string_value8))
   and tt.transactiontype_id between rp.number_value3 and rp.number_value4
   and ((upper(rp.string_value1) = 'TRUE' and
        (culk.customernumber is null
           or culk.defaultbusinessunit_id = rp.number_value9
           or exists (select 1
                        from customeractivities ca
                       where ca.customer_id = culk.customer_id
                         and ca.processbusinessunit_id = rp.number_value9)))
        or (upper(rp.string_value1) <> 'TRUE'))
   and ((upper(rp.string_value2) = 'TRUE' and bu.businessunit_id = rp.number_value9
         and nvl(wst.businessunit_id, bu.businessunit_id) = rp.number_value9)
        or
        (upper(rp.string_value2) <> 'TRUE' and
        bu.businessunit_id in (select bug.businessunit_id
                                 from businessunitsperusergroup bug
                                where bug.usergroup_id = rp.number_value8)))
/

  CREATE OR REPLACE VIEW "V_SCANSANDCOUNTS" ("DELIVERYVARIATIONS_ID") AS 
  select DV.DELIVERYVARIATIONS_ID
    from DELIVERYVARIATIONS DV, CLEANCOUNTDELIVERY CCD
/

  CREATE OR REPLACE VIEW "V_SCANSBYROUTE_PICKUP" ("ROUTENUMBER", "BATCHNUMBER", "DAYNUMBER", "DESCRIPTION", "CODE", "GARMENTSOILSCANNED", "DEPOTDESC", "SORTBATCHDESC", "LASTINDATE", "PLANT_ID") AS 
  SELECT /*+ ordered use_nl(UI A S)
           index(UIR XIF6UNQUEITEMROUTE)
           index(A XPKROUTE)
           index(UI XPKUNIQUEITEM)
           index(S XPKSORTBATCHDEFINITION) */
 A.ROUTENUMBER ROUTENUMBER,
 S.BATCHNUMBER BATCHNUMBER,
 D.DAYNUMBER DAYNUMBER,
 A.DESCRIPTION DESCRIPTION,
 DEPOT.CODE CODE,
 COUNT(1) GARMENTSOILSCANNED,
 DEPOT.DESCRIPTION DEPOTDESC,
 S.DESCRIPTION SORTBATCHDESC,
 UIR.LASTINDATE LASTINDATE,
 A.PLANT_ID PLANT_ID
  FROM UNIQUEITEMROUTE UIR, UNIQUEITEM UI, ROUTE A
  LEFT OUTER JOIN DEPOT ON A.DEPOT_ID = DEPOT.DEPOT_ID, SORTBATCHDEFINITION S, DAY D
 WHERE A.SORTBATCHDEFINITION_ID = S.SORTBATCHDEFINITION_ID
   AND A.DRIVINGDAY_ID = D.DAY_ID
   AND UIR.UNIQUEITEM_ID = UI.UNIQUEITEM_ID
   AND EXISTS (SELECT ST.STATUS_ID
          FROM STATUS ST
         WHERE ST.STATUS_ID = UI.STATUS_ID
           AND ST.STATUSTYPE = 'UI'
           AND ST.CODE = 20)
   AND EXISTS (SELECT SY.STAY_ID
          FROM STAY SY
         WHERE SY.STAY_ID = UI.STAY_ID
           AND SY.STAYTYPE = 1
           AND SY.STAYNR in (30,33)) -- HVH Todo 8177 Include checkpoint scan Nr 33
   AND UIR.LASTINROUTE_ID = A.ROUTE_ID
  GROUP BY A.ROUTENUMBER,
          S.BATCHNUMBER,
          D.DAYNUMBER,
          A.DESCRIPTION,
          DEPOT.CODE,
          DEPOT.DESCRIPTION,
          S.DESCRIPTION,UIR.LASTINDATE,A.PLANT_ID
/

  CREATE OR REPLACE VIEW "V_SCANSPERROUTE_DELIVERY" ("ROUTENUMBER", "BATCHNUMBER", "DAYNUMBER", "DESCRIPTION", "CODE", "GARMENTSOILSCANNED", "DEPOTDESC", "SORTBATCHDESC", "PLANNEDOUTDATE", "PLANT_ID") AS 
  SELECT /*+ ordered use_nl(UI A S)
           index(UIR XIF5UNQUEITEMROUTE)
           index(A XPKROUTE)
           index(UI XPKUNIQUEITEM)
           index(S XPKSORTBATCHDEFINITION) */
 A.ROUTENUMBER ROUTENUMBER,
 S.BATCHNUMBER BATCHNUMBER,
 D.DAYNUMBER DAYNUMBER,
 A.DESCRIPTION DESCRIPTION,
 DEPOT.CODE CODE,
 COUNT(1) GARMENTSOILSCANNED,
 DEPOT.DESCRIPTION DEPOTDESC,
 S.DESCRIPTION SORTBATCHDESC,
 UIR.PLANNEDOUTDATE PLANNEDOUTDATE,
 A.PLANT_ID PLANT_ID
  FROM UNIQUEITEMROUTE UIR, UNIQUEITEM UI, ROUTE A
  LEFT OUTER JOIN DEPOT ON A.DEPOT_ID = DEPOT.DEPOT_ID, SORTBATCHDEFINITION S, DAY D
 WHERE A.SORTBATCHDEFINITION_ID = S.SORTBATCHDEFINITION_ID
   AND A.DRIVINGDAY_ID = D.DAY_ID
   AND UIR.UNIQUEITEM_ID = UI.UNIQUEITEM_ID
   AND EXISTS (SELECT ST.STATUS_ID
          FROM STATUS ST
         WHERE ST.STATUS_ID = UI.STATUS_ID
           AND ST.STATUSTYPE = 'UI'
           AND ST.CODE = 20)
   AND EXISTS (SELECT SY.STAY_ID
          FROM STAY SY
         WHERE SY.STAY_ID = UI.STAY_ID
           AND SY.STAYTYPE = 1
           AND SY.STAYNR in (30,33)) -- HVH Todo 8177 Include checkpoint scan Nr 33
   AND UIR.PLANNEDOUTROUTE_ID = A.ROUTE_ID
  GROUP BY A.ROUTENUMBER,
          S.BATCHNUMBER,
          D.DAYNUMBER,
          A.DESCRIPTION,
          DEPOT.CODE,
          DEPOT.DESCRIPTION,
          S.DESCRIPTION,UIR.PLANNEDOUTDATE, A.PLANT_ID
/

  CREATE OR REPLACE VIEW "V_SCANSPERWEARER" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "WEARERNUMBER", "WEARERNAME", "WEARERLASTNAME", "WEARERFIRSTNAME", "PRODUCTCODE", "SIZECODE", "YEAR", "WEEK", "DAYNO", "FACTORYDESCRIPTION", "LANGUAGECODE", "REASON_CODE", "SCANTIMESTAMP", "SCANDATE", "TRANSACTIONTYPE_ID", "REPORTPARAM_ID", "NUMBER_VALUE9", "NUMBER_VALUE", "BUSINESSUNIT_ID", "BANK", "LOCKER", "LOCKERSTATUS", "PRIMARYID", "PRODUCTDESC", "SIZEDESC", "DAYCODE", "TRANSACTIONTYPEDESC") AS 
  select /*version 1.0*/
-- only if needed + index(sc xspeedscan) index(dilk xpkdistributionpoint_link) index(prdlk xpkproduct_link)
       cu.customernumber,  cu.name customername, cu.customer_id, delk.departmentnumber, delk.description departmentdesc,
       wel.wearernumber, wel.wearername, wel.wearersearchname wearerlastname,
       (select w.firstname from wearer w where we.wearer_id = w.wearer_id) wearerfirstname,
       prdlk.code productcode, szlk.code sizecode, sc.year, sc.week, sc.dayno,
       trt.factorydescription, lan.code languagecode, rc.code reason_code,
       to_char(sc.scantimestamp, 'HH24.MI.SS') scantimestamp, trunc(sc.scantimestamp) scandate, trt.transactiontype_id,
       rp.reportparam_id, rp.number_value9, rp.number_value, sc.businessunit_id, lo.bank, lo.locker, lo.lockerstatus,
       case when length(sc.primaryid) = 24 and nvl((select ss.value from systemsetting ss where ss.plant_id = bu.plant_id and ss.name = 'USEURICODE'), 0) = 1
            then pack_epc_sgtin96.decode(sc.primaryid) else sc.primaryid end primaryid,
       (select prd.description from product_desc prd
         where prd.product_id = prdlk.product_id
           and prd.language_id = lan.language_id) productdesc,
       (select sdd.description from sizedefinition_desc sdd
         where sdd.sizedefinition_id = szlk.sizedefinition_link_id
           and sdd.language_id = lan.language_id) sizedesc,
       (select day_desc.code from day_desc where day_desc.day_id = sc.dayno
           and day_desc.language_id = lan.language_id) daycode,
       (select trtd.description from transactiontype_desc trtd
         where trtd.transactiontype_id = trt.transactiontype_id
           and trtd.language_id = lan.language_id) transactiontypedesc
  from scan sc
       left join reasoncode rc on sc.reasoncode_id = rc.reasoncode_id
       join weareremployment_link wel
            left join weareremployment we
                 left join locker lo on we.locker_id = lo.locker_id
            on wel.weareremployment_id = we.weareremployment_id
            join distributionpoint_link dilk
                 join department_link delk
                      join customer cu
                          join businessunit bu on cu.defaultbusinessunit_id = bu.businessunit_id
                      on delk.customer_link_id = cu.customer_id
                 on dilk.department_link_id = delk.department_link_id
            on wel.distributionpoint_link_id = dilk.distributionpoint_link_id
       on sc.weareremployment_link_id = wel.weareremployment_link_id
       join product_link prdlk on sc.product_link_id = prdlk.product_link_id
       join sizedefinition_link szlk on sc.sizedefinition_link_id = szlk.sizedefinition_link_id
       join transactiontype trt on sc.transactiontype_id = trt.transactiontype_id
       cross join reportparam rp
	     join languages lan on rp.string_value = lan.code
 where sc.customer_link_id = cu.customer_id
   and trt.transactiontype_id not in (0, 10, 11, 40, 41, 50, 53, 60, 70, 71, 72, 73, 99)
   and cu.customernumber >= rp.number_value1 and cu.customernumber <= rp.number_value2
   and delk.departmentnumber >= rp.number_value3 and delk.departmentnumber <= rp.number_value4
   and wel.wearernumber >= rp.number_value5 and wel.wearernumber <= rp.number_value6
   and trt.transactiontype_id >= rp.number_value7 and trt.transactiontype_id <= rp.number_value8
   and prdlk.code >= rp.string_value1 and prdlk.code <= rp.string_value2
   and ((rc.code >= rp.string_value3 and rc.code <= rp.string_value4) or rc.code is null)
   and trunc(sc.scantimestamp) >= rp.date_value1 and trunc(sc.scantimestamp) <= rp.date_value2
   and sc.businessunit_id = decode(rp.number_value, 0, rp.number_value9, sc.businessunit_id)
   and (cu.defaultbusinessunit_id = rp.number_value9
       or exists (select 1 from customeractivities ca where ca.customer_id = cu.customer_id
	                   and (ca.processbusinessunit_id = rp.number_value9 or ca.internalprocessingbu_id = rp.number_value9)))
/

  CREATE OR REPLACE VIEW "V_SCANSWITHFLAGS" ("FLAGCODE", "FLAGDESC", "WORKSTATIONCODE", "WORKSTATIONDESC", "TRANSACTIONTYPE_ID", "TRANSACTIONTYPEDESC", "SCANTIMESTAMP", "SCANDATE", "PRIMARYID", "CUSTOMERNUMBER", "CUSTOMERNAME", "FLAGRESPONSE", "LANGUAGECODE", "BUSINESSUNIT_ID") AS 
  select
  flag.code FlagCode
, (select flag_desc.description from flag_desc where flag_desc.flag_id = flag.flag_id
   and flag_desc.language_id = languages.language_id) FlagDesc
, scan.scanstation workstationCode
, (select wst.description from workstation wst where wst.code = scan.scanstation) workstationDesc
, scan.transactiontype_id
, (select transactiontype_desc.description from transactiontype_desc where transactiontype_desc.transactiontype_id = scan.transactiontype_id
  and transactiontype_desc.language_id = languages.language_id) transactiontypeDesc
, scan.scantimestamp, trunc(scan.scantimestamp) ScanDate, scan.primaryid
, culk.customernumber, culk.name CustomerName
, scanflag.flagresponse
, languages.code languageCode
, scan.businessunit_id
from scanflag, flag
, scan
       left outer join customer_link culk on culk.customer_link_id = scan.customer_link_id
, languages
where scanflag.scan_id = scan.scan_id
      and scanflag.flag_id = flag.flag_id
      and flag.flagtype = 1
/

  CREATE OR REPLACE VIEW "V_SCANS_TOTAL" ("SCANDATE", "BUSINESSUNIT_ID", "CUSTOMER_ID", "CUSTOMERBU_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "TRANSACTIONTYPE_ID", "TRANSACTIONTYPEDESC", "WORKSTATIONCODE", "WORKSTATIONDESC", "USERNAME", "FULLNAME", "COUNTID", "BUSINESSUNITCODE", "PLANTDEPARTMENTCODE", "PLANTDEPARTMENTDESC", "LANGUAGECODE", "REASON_CODE", "ROUTENUMBER", "QUALITYTESTTYPE_CODE", "QUALITYTESTTYPE_DESC", "TREATMENTTYPE_CODE", "TREATMENTTYPE_DESC", "REPORTPARAM_ID") AS 
  select /*version 2.1*/
       trunc(s.scantimestamp) scandate, s.businessunit_id, s.customer_link_id customer_id,
       coalesce(culk.defaultbusinessunit_id,s.businessunit_id) customerbu_id,
       culk.customernumber, max(culk.name) customername, s.transactiontype_id,
       (select transactiontype_desc.description
          from transactiontype_desc
         where transactiontype_desc.transactiontype_id = s.transactiontype_id
           and transactiontype_desc.language_id = l.language_id) transactiontypedesc,
       s.scanstation workstationcode, wst.description workstationdesc, sy.username username,
       sy.fullname fullname, count(s.primaryid) countid, bu.code businessunitcode,
       pd.code plantdepartmentcode, max(pd.description) plantdepartmentdesc, l.code languagecode,
       (select rc.code from reasoncode rc where s.reasoncode_id = rc.reasoncode_id) reason_code,
       (select r.routenumber from route r where s.route_id = r.route_id) routenumber,
       (select qtt.code from qualitytesttype qtt where s.qualitytesttype_id = qtt.qualitytesttype_id) qualitytesttype_code,
       (select qttd.description
          from qualitytesttype_desc qttd
         where s.qualitytesttype_id = qttd.qualitytesttype_id
           and qttd.language_id = l.language_id) qualitytesttype_desc,
       (select tt.code from treatmenttype tt where s.treatmenttype_id = tt.treatmenttype_id) treatmenttype_code,
       (select ttd.description from treatmenttype_desc ttd where s.treatmenttype_id = ttd.treatmenttype_id and ttd.language_id = l.language_id) treatmenttype_desc,
       rp.reportparam_id
  from scan s
       left join workstation wst
            join plantdepartment pd on wst.plantdepartment_id = pd.plantdepartment_id
       on s.scanstation = wst.code
       left join customer culk on s.customer_link_id = culk.customer_id
       join businessunit bu on s.businessunit_id = bu.businessunit_id
       join systemuser sy on s.systemuser_id = sy.systemuser_id
       cross join languages l
       cross join reportparam rp
 where ((upper(rp.string_value1) = 'TRUE'
         and (culk.customernumber is null or culk.defaultbusinessunit_id = rp.number_value9 or exists (select 1 from customeractivities ca where ca.customer_id = culk.customer_id and ca.processbusinessunit_id = rp.number_value9)))
         or (upper(rp.string_value1) <> 'TRUE'))
   and ((upper(rp.string_value2) = 'TRUE' and bu.businessunit_id = rp.number_value9
                and nvl(wst.businessunit_id, bu.businessunit_id) = rp.number_value9)
         or (upper(rp.string_value2) <> 'TRUE' and bu.businessunit_id in
              (select bug.businessunit_id from businessunitsperusergroup bug
                where bug.usergroup_id = rp.number_value8)))
group by l.language_id, rp.reportparam_id, trunc(s.scantimestamp), s.businessunit_id,
         culk.defaultbusinessunit_id, s.customer_link_id, culk.customernumber, s.transactiontype_id,
         s.scanstation, wst.description, bu.code, pd.code, l.code, s.reasoncode_id,
         s.route_id, s.qualitytesttype_id, s.treatmenttype_id, sy.username, sy.fullname
/

  CREATE OR REPLACE VIEW "V_SENDINVOICETO_ADDRESS" ("LINETYPE", "PURCHASEORDERHEADER_ID", "NAME", "STREET", "ZIPCODE", "CITY") AS 
  select 1 linetype, poh.purchaseorderheader_id, le.name, a.street, a.zipcode, a.city --current stockroom
from purchaseorderheader poh
     join stockroom sk on poh.stockroom_id = sk.stockroom_id
     join legalentity le on sk.legalentity_id = le.legalentity_id
     join address a on le.sendinvoicetoaddress_id = a.address_id
where poh.billtocompany = 0
union
select 2 linetype, poh.purchaseorderheader_id, le.name, a.street, a.zipcode, a.city --ship to stockroom
from purchaseorderheader poh
     join stockroom sk on poh.shiptostockroom_id = sk.stockroom_id
     join legalentity le on sk.legalentity_id = le.legalentity_id
     join address a on le.sendinvoicetoaddress_id = a.address_id
where poh.billtocompany = 1
union
select 3 linetype, poh.purchaseorderheader_id, le.name, a.street, a.zipcode, a.city --other
from purchaseorderheader poh
     join legalentity le on poh.legalentity_id = le.legalentity_id
     join address a on le.sendinvoicetoaddress_id = a.address_id
where poh.billtocompany = 2
/

  CREATE OR REPLACE VIEW "V_SERVICEEMBLEMCHARGE" ("BUSINESSUNIT_CODE", "BUSINESSUNIT_DESC", "BUSINESSUNIT_ID", "PLANT_CODE", "PLANT_NAME", "PLANT_ID", "ROUTENUMBER", "ROUTE_DESC", "ROUTE_ID", "STOPNUMBER", "ROUTESTOP_ID", "ROUTESTOPCODE", "CUSTOMERNUMBER", "CUSTOMER_NAME", "CUSTOMER_ID", "EMBTEMP_CODE", "EMBTEMP_DESC", "PREPCHARGE", "TOTALAMTEMBLEMS", "COMPANYEMBLEM", "NAMEEMBLEM", "OTHER", "TITLE", "BUDGETPROTECTION", "GARMENTSETUPPROTECTION") AS 
  select /*version 2.0*/
       bu.code businessunit_code, bu.description businessunit_desc, bu.businessunit_id, pl.code plant_code, pl.name plant_name, pl.plant_id,
       ro.routenumber, ro.description route_desc, ro.route_id, rs.stopnumber, rs.routestop_id, getroutestopcode(rs.routestop_id) routestopcode,
       cu.customernumber, cu.name customer_name, cu.customer_id, et.code embtemp_code, et.description embtemp_desc,
       coalesce((select castnumberasvarcharwithformat(max(cpc.price), '$999999999999990D00')
                   from customerprepcharge cpc
                  where cpc.customer_id = cu.customer_id
                    and cpc.startdate in (select max(cpc2.startdate)
                                            from customerprepcharge cpc2
                                           where cpc2.customer_id = cu.customer_id
                                             and cpc2.startdate <= sysdate)), '-') prepcharge,
       coalesce(castnumberasvarcharwithformat(get_serviceemblemcharge(et.emblemtemplate_id, null), '$999999999999990D00'), '-') totalamtemblems,
       coalesce(castnumberasvarcharwithformat(get_serviceemblemcharge(et.emblemtemplate_id, 1), '$999999999999990D00'), '-') companyemblem,
       coalesce(castnumberasvarcharwithformat(get_serviceemblemcharge(et.emblemtemplate_id, 2), '$999999999999990D00'), '-') nameemblem,
       coalesce(castnumberasvarcharwithformat(get_serviceemblemcharge(et.emblemtemplate_id, 3), '$999999999999990D00'), '-') other,
       coalesce(castnumberasvarcharwithformat(get_serviceemblemcharge(et.emblemtemplate_id, 4), '$999999999999990D00'), '-') title,
       (select max(bp.garmentemblem)
          from plpcbudgetprotection bp, productlistpercustomer plpc
         where bp.garmentemblem = 'Y'
           and bp.productlistpercustomer_id = plpc.productlistpercustomer_id
           and plpc.customer_id = cu.customer_id
           and plpc.dateactive <= sysdate) budgetprotection,
       (select max(bp.garmentsetup)
          from plpcbudgetprotection bp, productlistpercustomer plpc
         where bp.garmentemblem = 'Y'
           and bp.productlistpercustomer_id = plpc.productlistpercustomer_id
           and plpc.customer_id = cu.customer_id
           and plpc.dateactive <= sysdate) garmentsetupprotection
  from emblemtemplate et
       join customer cu
            join businessunit bu
                 join plant pl on bu.plant_id = pl.plant_id
            on cu.defaultinvoicebusinessunit_id = bu.businessunit_id
       on et.customer_id = cu.customer_id
       join routestop rs
            join route ro on rs.route_id = ro.route_id
       on et.customer_id = rs.customer_id and rs.dateactive <= sysdate
 where cu.active = 'Y'
   and cu.dateinactive >= trunc(sysdate)
/

  CREATE OR REPLACE VIEW "V_SETCONTENTS" ("SETPRODUCTCODE", "SETPRODUCTDESCRIPTION", "PRODUCTCODE", "PRODUCTDESCRIPTION", "AMOUNT", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT SETCONT.CODE,
 (SELECT description FROM PRODUCT_DESC A WHERE A.PRODUCT_ID = SETCONTENTS.SET_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) setproductdescription,
 PRODUCT.CODE,
 (SELECT description FROM PRODUCT_DESC B WHERE B.PRODUCT_ID = SETCONTENTS.PRODUCT_ID
  AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
 SETCONTENTS.AMOUNT, SETCONTENTS.SYSTEMUSER_ID, SETCONTENTS.TIMESTAMP, LANGUAGES.CODE
FROM SETCONTENTS, PRODUCT, PRODUCT SETCONT, LANGUAGES
WHERE SETCONTENTS.SET_ID = SETCONT.PRODUCT_ID
 and SETCONTENTS.PRODUCT_ID = PRODUCT.PRODUCT_ID
/

  CREATE OR REPLACE VIEW "V_SHIPMENT" ("REPORTPARAM_ID", "SHIPMENTLIST_ID", "SHIPMENTLISTNUMBER", "SHIPMENTLISTLINE_ID", "COMPLETIONDATE", "BUCODE", "BUDESCR", "BUSTREET", "BUZIPCODE", "BUCITY", "BUCOUNTRY", "STOCKCODE", "STOCKNAME", "STSTREET", "STCITY", "STZIPCODE", "STCOUNTRY", "NOTRUNIT", "NOITEMS", "NOWO", "TRANSPORTUNITNUMBER", "WORKORDERNUMBER", "PRODCODE", "PROD_DESC", "SZCODE", "WEARERNUMBER", "FULLNAME", "PRIMARYID", "POLPRICE", "CURRENCYCODE", "DECIMALS", "LANGUAGECODE") AS 
  select /*version 1.2*/
       rp.reportparam_id, sl.shipmentlist_id, sl.shipmentlistnumber, sll.shipmentlistline_id,
       sl.completiondate, bu.code bucode, bu.description budescr, plad.street bustreet,
       plad.zipcode buzipcode, plad.city bucity, plco.description bucountry, st.code stockcode,
       st.name stockname, stad.street ststreet, stad.city stcity, stad.zipcode stzipcode,
       (select stco.description
          from businessunit stbu
               join plant stpl
                    join country stco on stpl.country_id = stco.country_id
               on stbu.plant_id = stpl.plant_id
         where st.managedbybu_id = stbu.businessunit_id) stcountry,
       coalesce((select max(sl1.transportunitnumber)
                   from shipmentlistline sl1
                  where sl1.shipmentlist_id = sl.shipmentlist_id), 0) notrunit,
       coalesce((select sum(sl2.quantityshipped)
                   from shipmentlistline sl2
                  where sl2.shipmentlist_id = sl.shipmentlist_id), 0) noitems,
       (select count(distinct(wol.workorder_id))
          from shipmentlistline sl3
               join workorderline wol on sl3.workorderline_id = wol.workorderline_id
         where sl3.shipmentlist_id = sl.shipmentlist_id) nowo,
       sll.transportunitnumber, wo.workordernumber,
       (select pr.code
          from product pr
         where pr.product_id = wol.product_link_id) prodcode,
       (select pdesc.description
          from product_desc pdesc
         where pdesc.product_id = wol.product_link_id
           and pdesc.language_id = lan.language_id) prod_desc,
       (select sz.code
          from sizedefinition sz
         where sz.sizedefinition_id = wol.sizedefinition_link_id) szcode,
       w.wearernumber, w.fullname,
       (select ui.primaryid
          from uniqueitem ui
         where ui.uniqueitem_id = ih.uniqueitem_link_id) primaryid,
       coalesce((select pol.purchaseprice
                   from purchaseorderline pol
                  where wol.purchaseorderline_id = pol.purchaseorderline_id),
                (select max(pol2.purchaseprice)
                   from workorderlinepurchordline wolpol
                        join purchaseorderline pol2
                        on wolpol.purchaseorderline_id = pol2.purchaseorderline_id
                  where wolpol.workorderline_id = wol.workorderline_id),
                (select f_purchaseprice(s.supplier_id, wol.product_link_id, wol.sizedefinition_link_id, trunc(ih.timestamp))
                   from stockdefinitionperitem sdi
                        join supplier s on sdi.defaultsupplier_id = s.supplier_id
                  where ih.originalstockdefperitem_id = sdi.stockdefinitionperitem_id)
       ) polprice,
       coalesce((select cu1.code
                   from purchaseorderline pol
                        join purchaseorderheader poh
                             join currency cu1 on poh.currency_id = cu1.currency_id
                        on pol.purchaseorderheader_id = poh.purchaseorderheader_id
                  where wol.purchaseorderline_id = pol.purchaseorderline_id),
                (select cu2.code
                   from workorderlinepurchordline wolpol
                        join purchaseorderline pol2
                             join purchaseorderheader poh2
                                  join currency cu2 on poh2.currency_id = cu2.currency_id
                             on pol2.purchaseorderheader_id = poh2.purchaseorderheader_id
                        on wolpol.purchaseorderline_id = pol2.purchaseorderline_id
                  where wolpol.workorderline_id = wol.workorderline_id),
                (select cu3.code
                   from stockdefinitionperitem sdi
                        join supplier s
                             join currency cu3 on s.currency_id = cu3.currency_id
                        on sdi.defaultsupplier_id = s.supplier_id
                  where ih.originalstockdefperitem_id = sdi.stockdefinitionperitem_id),
                cu4.code) currencycode,
       coalesce((select cu1.decimals
                   from purchaseorderline pol
                        join purchaseorderheader poh
                             join currency cu1 on poh.currency_id = cu1.currency_id
                        on pol.purchaseorderheader_id = poh.purchaseorderheader_id
                  where wol.purchaseorderline_id = pol.purchaseorderline_id),
                (select cu2.decimals
                   from workorderlinepurchordline wolpol
                        join purchaseorderline pol2
                             join purchaseorderheader poh2
                                  join currency cu2 on poh2.currency_id = cu2.currency_id
                             on pol2.purchaseorderheader_id = poh2.purchaseorderheader_id
                        on wolpol.purchaseorderline_id = pol2.purchaseorderline_id
                  where wolpol.workorderline_id = wol.workorderline_id),
                (select cu3.decimals
                   from stockdefinitionperitem sdi
                        join supplier s
                             join currency cu3 on s.currency_id = cu3.currency_id
                        on sdi.defaultsupplier_id = s.supplier_id
                  where ih.originalstockdefperitem_id = sdi.stockdefinitionperitem_id),
                cu4.decimals) decimals,
       lan.code languagecode
  from reportparam rp
       join shipmentlist sl
            join stockroom st
                 join address stad on st.deliveryaddress_id = stad.address_id
            on sl.supplyingstockroom_id = st.stockroom_id
            join businessunit bu
                 join plant pl
                      join address plad on pl.address_id = plad.address_id
                      join country plco
                           join currency cu4 on plco.defaultcurrency_id = cu4.currency_id
                      on pl.country_id = plco.country_id
                 on bu.plant_id = pl.plant_id
            on sl.shiptobusinessunit_id = bu.businessunit_id
       on rp.number_value = sl.shipmentlist_id
       join shipmentlistline sll
            join workorderline wol
                 join workorder wo
                      left join weareremployment we
                                join wearer w on we.wearer_id = w.wearer_id
                      on wo.weareremployment_link_id = we.weareremployment_id
                 on wol.workorder_id = wo.workorder_id
                 join issuehistory ih
                 on wol.workorder_id = ih.workorder_id and wol.product_link_id = ih.product_link_id
                    and wol.sizedefinition_link_id = ih.sizedefinition_link_id
            on sll.workorderline_id = wol.workorderline_id
       on rp.number_value = sll.shipmentlist_id
       cross join languages lan
 where ih.shipmentlistline_id = sll.shipmentlistline_id
/

  CREATE OR REPLACE VIEW "V_SHIPMENTLISTORPACKS" ("REPORTPARAM_ID", "SHIPMENTLISTNUMBER", "SHIPBYBUCODE", "SHIPBYBUDESC", "SHBYSTR", "SHBYADDRZIP", "SHBYADDRCITY", "SHBYCOUNTRY", "SHTOBUCODE", "SHTOBUDESC", "SHTOADSTR", "SHTOADZIP", "SHTOADCITY", "SHTOCOUN", "TSHIPPED", "NOTRUNIT", "PRODCODE", "PDESC", "SDCODE", "FMCODE", "FMDESC", "STERILE", "TRANSPORTUNITNUMBER", "QUANTITYSHIPPED", "LANGUAGECODE") AS 
  select rp.reportparam_id,
       slor.shipmentlistnumber,
       shipbybu.code shipbybucode,
       shipbybu.description shipbybudesc,
       shbyaddr.street shbystr,
       shbyaddr.zipcode shbyaddrzip,
       shbyaddr.city shbyaddrcity,
       shbyco.description shbycountry,
       shtobu.code shtobucode,
       shtobu.description shtobudesc,
       shtoad.street shtoadstr,
       shtoad.zipcode shtoadzip,
       shtoad.city shtoadcity,
       shtoco.description shtocoun,
       (select sum(sll.quantityshipped)
          from shipmentlistlineor sll
         where sll.shipmentlistor_id = slor.shipmentlistor_id) Tshipped,
       coalesce((select count(distinct(a.transportunitnumber)) from shipmentlistlineor a where a.shipmentlistor_id=slor.shipmentlistor_id),0) notrunit,
       p.code prodcode,
       (select pdesc.description
          from product_link_desc pdesc
         where pdesc.product_link_id = p.product_link_id
           and pdesc.language_id = lan.language_id) pdesc,
       sd.code sdcode,
       fm.code fmcode,
       (select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id and fmd.language_id = lan.language_id) fmdesc,
       sllor.sterile,
       sllor.transportunitnumber,
       sllor.quantityshipped,
       lan.code languagecode
  from shipmentlistor     slor,
       businessunit       shipbybu,
       plant              shpl,
       address            shbyaddr,
       country            shbyco,
       businessunit       shtobu,
       plant              shtopl,
       address            shtoad,
       country            shtoco,
       reportparam        rp,
       languages          lan,
       shipmentlistlineor sllor,
       product_link       p,
       sizedefinition     sd,
       finishingmethod    fm
 where slor.shipbybusinessunit_id = shipbybu.businessunit_id
   and shipbybu.plant_id = shpl.plant_id
   and shpl.address_id = shbyaddr.address_id
   and shpl.country_id = shbyco.country_id
   and slor.shiptobusinessunit_id = shtobu.businessunit_id
   and shtobu.plant_id = shtopl.plant_id
   and shtopl.address_id = shtoad.address_id
   and shtopl.country_id = shtoco.country_id
   and slor.shipmentlistor_id = sllor.shipmentlistor_id
   and sllor.product_link_id = p.product_link_id
   and sllor.sizedefinition_link_id = sd.sizedefinition_id
   and sllor.finishingmethod_id = fm.finishingmethod_id
   and rp.number_value = slor.shipmentlistor_id
/

  CREATE OR REPLACE VIEW "V_SHORTAGES" ("BUSINESSUNITCODE", "BUSINESSUNITDESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "PRODUCTGROUPCODE", "PROCESSBUSINESSUNIT_ID", "PRODUCTCODE", "SIZEDEFINITIONCODE", "FINISHINGMETHODCODE", "PRODUCTDESC", "SIZEDEFINITIONDESC", "FINISHINGMETHODDESC", "YEAR", "WEEK", "DAYNUMBER", "YEARWEEK", "AMOUNTSHORTAGE", "CUSTOMERLANGUAGECODE", "LANGUAGECODE", "DEFAULTBUSINESSUNIT_ID") AS 
  select bu.code businessunitCode, bu.description businessunitDesc, cu.customernumber, cu.name customerName
, delk.departmentnumber, delk.description departmentDesc, dilk.distributionpointnumber, dilk.description distributionpointDesc
, prdlk.productgroupcode productgroupCode, dh.processbusinessunit_id
, prdlk.code productCode, szlk.code sizedefinitionCode, fm.code finishingmethodCode
, (select product_link_desc.description from product_link_desc where product_link_desc.product_link_id = prdlk.product_link_id
  and product_link_desc.language_id = languages.language_id) productDesc
, (select szd.description from sizedefinition_desc szd where szd.sizedefinition_id = szlk.sizedefinition_id
  and szd.language_id = languages.language_id) sizedefinitionDesc
, (select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
  and fmd.language_id = languages.language_id) finishingmethodDesc
, dh.year, dh.week, dh.daynumber, (dh.year*100)+dh.week YEARWEEK, dh.amountshortage
, (select lan.code from languages lan where cu.language_id = lan.language_id) CustomerLanguageCode
, languages.code languageCode
, default_bu.businessunit_id DefaultBusinessunit_id
from deliveryhistory dh, customer cu, businessunit bu, department_link delk, distributionpoint_link dilk
, product_link prdlk
, sizedefinition_link szlk, finishingmethod fm
, languages
, businessunit default_bu
where --dh.amountshortage <> 0 and
    dh.customer_link_id = cu.customer_id
and dh.processbusinessunit_id = bu.businessunit_id
and dh.department_link_id = delk.department_link_id
and dh.distributionpoint_link_id = dilk.distributionpoint_link_id
and dh.product_link_id = prdlk.product_link_id
and dh.sizedefinition_link_id = szlk.sizedefinition_link_id
and dh.finishingmethod_id = fm.finishingmethod_id
and (cu.defaultbusinessunit_id = default_bu.businessunit_id
    or exists (select 1 from customeractivities ca
            where ca.customer_id = cu.customer_id and ca.processbusinessunit_id = default_bu.businessunit_id))
/

  CREATE OR REPLACE VIEW "V_SIZEDEFINITION" ("CODE", "DESCRIPTION", "UNFINISHEDLENGTH", "LEGACYSIZECODE", "WIDTH", "LENGTH", "SYSTEMUSER_ID", "TIMESTAMP", "SIZEDEFINITION_ID", "LANGUAGECODE") AS 
  SELECT SIZEDEFINITION.CODE,
 (SELECT description FROM SIZEDEFINITION_DESC A WHERE A.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) DESCRIPTION,
 SIZEDEFINITION.UNFINISHEDLENGTH,
 SIZEDEFINITION.LEGACYSIZECODE, SIZEDEFINITION.WIDTH, SIZEDEFINITION.LENGTH,
 SIZEDEFINITION.SYSTEMUSER_ID, SIZEDEFINITION.TIMESTAMP, SIZEDEFINITION.SIZEDEFINITION_ID,
 LANGUAGES.CODE LANGUAGECODE
FROM SIZEDEFINITION, LANGUAGES
/

  CREATE OR REPLACE VIEW "V_SIZESPERSIZETYPE" ("SIZETYPECODE", "SYZETYPEDESCRIPTION", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESCRIPTION", "SEQUENCENUMBER", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT SIZETYPE.CODE,
 (SELECT description FROM SIZETYPE_DESC A WHERE A.SIZETYPE_ID = SIZESPERSIZETYPE.SIZETYPE_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) DESCRIPTION1,
 SIZEDEFINITION.CODE,
 (SELECT description FROM SIZEDEFINITION_DESC B WHERE B.SIZEDEFINITION_ID = SIZESPERSIZETYPE.SIZEDEFINITION_ID
  AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) DESCRIPTION2,
 SIZESPERSIZETYPE.SEQUENCENUMBER, SIZESPERSIZETYPE.SYSTEMUSER_ID, SIZESPERSIZETYPE.TIMESTAMP, LANGUAGES.CODE
FROM SIZESPERSIZETYPE, SIZETYPE, SIZEDEFINITION, LANGUAGES
WHERE SIZESPERSIZETYPE.SIZETYPE_ID = SIZETYPE.SIZETYPE_ID
 AND SIZESPERSIZETYPE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
/

  CREATE OR REPLACE VIEW "V_SIZETYPE" ("CODE", "DESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP", "SIZETYPE_ID", "LANGUAGECODE") AS 
  SELECT SIZETYPE.CODE,
 (SELECT description FROM SIZETYPE_DESC A WHERE A.SIZETYPE_ID = SIZETYPE.SIZETYPE_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) DESCRIPTION,
 SIZETYPE.SYSTEMUSER_ID, SIZETYPE.TIMESTAMP, SIZETYPE.SIZETYPE_ID,  LANGUAGES.CODE LANGUAGECODE
FROM SIZETYPE, LANGUAGES
/

  CREATE OR REPLACE VIEW "V_SKDEFINITIONPERITEM_CHANGE" ("STOCKCODE", "STOCKNAME", "PRODUCTCODE", "SIZECODE", "PRODUCTGROUPCODE", "SEQUENCENUMBER", "PRODUCTDESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "STOCKVALUEFIFO_ID", "PURCHASEORDERNUMBER", "WORKORDERNUMBER", "DELIVERYNOTENUMBER", "TRANSACTIONDATE", "TRANSACTIONTYPE", "ORIGIN", "PIECEVALUE", "QUANTITY", "QTYACTUALSTOCK", "ORIGINALVALUE", "ACTUALVALUE", "REMARK", "DECIMALS", "INVOICEAMOUNTDECIMALS", "CURRENCYCODE", "LANGUAGECODE") AS 
  select
  sk.code stockCode, sk.name stockName
, prd.code productCode, sz.code sizeCode, prdgr.code productGroupCode
, pz.sequencenumber
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, cu.customernumber, cu.name customerName
, skff.stockvaluefifo_id
, skff.purchaseordernumber, skff.workordernumber, skff.deliverynotenumber
, skff.transactiondate, skff.transactiontype, skff.origin
, skff.piecevalue, skff.quantity, skff.qtyactualstock
, ( skff.piecevalue * skff.quantity ) OriginalValue
, ( skff.piecevalue * skff.qtyactualstock ) ActualValue
, skff.remark
, currency.decimals, currency.invoiceamountdecimals, currency.code currencyCode
, languages.code languageCode
from
  stockroom sk
, stockDefinitionPerItem ski
    left outer join customer cu on ski.customer_id = cu.customer_id
, product prd
    left outer join productgroup prdgr on prd.productgroup_id = prdgr.productgroup_id
, sizedefinition sz, productsize pz
, stockReservationPerGrade skgr, stockValueFIFO skff
, businessunit bu, plant, country, currency
, languages
where
    sk.stockroom_id = ski.stockroom_id
and ski.product_id = prd.product_id
and ski.sizedefinition_id = sz.sizedefinition_id
    and prd.product_id = pz.product_id
        and pz.sizedefinition_id = sz.sizedefinition_id
and ski.stockdefinitionperitem_id = skgr.stockdefinitionperitem_id
    and skgr.stockreservationpergrade_id = skff.stockreservationpergrade_id
and sk.managedbybu_id = bu.businessunit_id
    and bu.plant_id = plant.plant_id
        and plant.country_id = country.country_id
            and country.defaultcurrency_id = currency.currency_id
/

  CREATE OR REPLACE VIEW "V_SKSUMRECONCILIATIONTRANS" ("BUSINESSUNITCODE", "STOCKROOMCODE", "STOCKROOMNAME", "CUSTOMEROWNED", "CUSTOMER_ID", "NEWGARMENT", "REPORTPARAM_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "PRICELISTCODE", "PRICELISTDESC", "PRODUCTGROUPCODE", "PRODUCTCODE", "SIZECODE", "PRODUCTDESC", "RECEIVED", "ISSUED", "RAGGED", "STOCKCORRECTION", "SOLD", "PRICE", "STOCKTRANSQUANTITY", "TRANSACTIONSVALUE", "DECIMALS", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE") AS 
  select distinct
  bu.code businessunitCode, sk.code stockroomCode, sk.name stockroomName
, sdi.customerowned, sdi.customer_id, qg.newgarment
, rp.reportparam_id, cu.customernumber, cu.name customerName
, rp.string_value1 priceListCode, rp.string_value2 priceListDesc
, pg.code productgroupCode, prd.code productCode, sz.code sizeCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, case when skt.transactiontype_id in (10, 12, 15,401) then sum(skt.quantity) else 0 end Received
, case when skt.transactiontype_id in (22, 23) then sum(skt.quantity) else 0 end Issued
, case when skt.transactiontype_id in (40, 41) then sum(skt.quantity) else 0 end Ragged
, case when skt.transactiontype_id in (84, 44) then sum(skt.quantity) else 0 end StockCorrection
, case when skt.transactiontype_id = 50 then sum(skt.quantity) else 0 end Sold
, F_GENERALREPLACEMENTSALESPRICE( rp.reportparam_id
                                  , ( case when rp.number_value1 in (1, 2) then rp.number_value2
                                         when rp.number_value1 = 3 then sdi.defaultsupplier_id end )
                                  , sdi.product_id, sdi.sizedefinition_id
                                  ) price
, sum(skt.quantity) StockTransQuantity
, F_GENERALREPLACEMENTSALESPRICE( rp.reportparam_id
                                  , ( case when rp.number_value1 in (1, 2) then rp.number_value2
                                         when rp.number_value1 = 3 then sdi.defaultsupplier_id end )
                                  , sdi.product_id, sdi.sizedefinition_id
                                  ) * sum(skt.quantity) TransactionsValue
, currency.decimals, currency.invoiceamountdecimals
, languages.code languageCode
from
  stockdefinitionperitem sdi
      left outer join customer cu on sdi.customer_id = cu.customer_id
, stockroom sk, product prd, productgroup pg, sizedefinition sz
, businessunit bu, stockreservationpergrade srg, qualitygrade qg, stocktransaction skt
, reportparam rp, currency
, languages
where
    sdi.stockroom_id = sk.stockroom_id
    and sk.managedbybu_id = bu.businessunit_id
and sdi.product_id = prd.product_id
    and prd.productgroup_id = pg.productgroup_id
and sdi.sizedefinition_id = sz.sizedefinition_id
and sdi.stockdefinitionperitem_id = srg.stockdefinitionperitem_id
    and srg.qualitygrade_id = qg.qualitygrade_id
    and srg.stockreservationpergrade_id = skt.stockreservationpergrade_id
        and skt.transactiontype_id in (10, 12, 15, 22, 23, 40, 41, 84, 44, 50,401)
        and skt.transactiondate between rp.date_value1 and rp.date_value2
and currency.currency_id = F_CURRENCY( rp.reportparam_id
                                       , ( case when rp.number_value1 in (1, 2) then rp.number_value2
                                                 when rp.number_value1 = 3 then sdi.defaultsupplier_id end ))
group by
  bu.code, sk.code, sk.name
, sdi.customerowned, sdi.customer_id, cu.customernumber, cu.name, rp.string_value1, rp.string_value2
, sdi.defaultsupplier_id, sdi.product_id, sdi.sizedefinition_id, qg.newgarment
, rp.reportparam_id, rp.number_value1, rp.number_value2
, pg.code, prd.code, sz.code, prd.product_id, skt.transactiontype_id
, currency.decimals, currency.invoiceamountdecimals
, languages.language_id, languages.code
/

  CREATE OR REPLACE VIEW "V_SKSUMRECONCILIATIONVALUE" ("BUSINESSUNITCODE", "STOCKROOMCODE", "STOCKROOMNAME", "CUSTOMEROWNED", "CUSTOMER_ID", "REPORTPARAM_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "PRICELISTCODE", "PRICELISTDESC", "PRODUCTGROUPCODE", "PRODUCTCODE", "SIZECODE", "PRODUCTDESC", "PRICE", "STARTQTY", "STARTVALUE", "ENDQTY", "ENDVALUE", "DIFFQTY", "DIFFVALUE", "DECIMALS", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE") AS 
  select distinct
  bu.code businessunitCode, sk.code stockroomCode, sk.name stockroomName
, sqq.customerowned, sqq.customer_link_id customer_id
, rp.reportparam_id, cu.customernumber, cu.name customerName
, rp.string_value1 priceListCode, rp.string_value2 priceListDesc
, pg.code productgroupCode, prd.code productCode, sz.code sizeCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, F_REPLACEMENTSALESPRICE( rp.reportparam_id
                           , ( case when rp.number_value1 in (1, 2) then rp.number_value2
                                         when rp.number_value1 = 3 then sdi.defaultsupplier_id end )
                           , prd.product_id, sz.sizedefinition_id ) Price
, case when sqh.year*100+sqh.week = rp.number_value3*100+rp.number_value4
    then ( case when rp.string_value3 = '1' then sum(sqq.qtynew) when rp.string_value3 = '2' then sum(sqq.qtyused) else sum(sqq.qtyonstock) end )
      else 0 end StartQty
, ( case when sqh.year*100+sqh.week = rp.number_value3*100+rp.number_value4
      then ( case when rp.string_value3 = '1' then sum(sqq.qtynew) when rp.string_value3 = '2' then sum(sqq.qtyused) else sum(sqq.qtyonstock) end )
        else 0 end )* F_REPLACEMENTSALESPRICE( rp.reportparam_id
                                                  , ( case when rp.number_value1 in (1, 2) then rp.number_value2
                                                  when rp.number_value1 = 3 then sdi.defaultsupplier_id end )
                                                  , prd.product_id, sz.sizedefinition_id
                                                  ) StartValue
, case when sqh.year*100+sqh.week = rp.number_value5*100+rp.number_value6
    then ( case when rp.string_value3 = '1' then sum(sqq.qtynew) when rp.string_value3 = '2' then sum(sqq.qtyused) else sum(sqq.qtyonstock) end )
      else 0 end EndQty
, ( case when sqh.year*100+sqh.week = rp.number_value5*100+rp.number_value6
      then ( case when rp.string_value3 = '1' then sum(sqq.qtynew) when rp.string_value3 = '2' then sum(sqq.qtyused) else sum(sqq.qtyonstock) end )
        else 0 end )* F_REPLACEMENTSALESPRICE( rp.reportparam_id
                                                  , ( case when rp.number_value1 in (1, 2) then rp.number_value2
                                                  when rp.number_value1 = 3 then sdi.defaultsupplier_id end )
                                                  , prd.product_id, sz.sizedefinition_id
                                                  ) EndValue
, ( case when sqh.year*100+sqh.week = rp.number_value5*100+rp.number_value6
          then ( case when rp.string_value3 = '1' then sum(sqq.qtynew) when rp.string_value3 = '2' then sum(sqq.qtyused) else sum(sqq.qtyonstock) end ) else 0 end )
  - ( case when sqh.year*100+sqh.week = rp.number_value3*100+rp.number_value4
           then ( case when rp.string_value3 = '1' then sum(sqq.qtynew) when rp.string_value3 = '2' then sum(sqq.qtyused) else sum(sqq.qtyonstock) end ) else 0 end ) DiffQty
, ( case when sqh.year*100+sqh.week = rp.number_value5*100+rp.number_value6
         then ( case when rp.string_value3 = '1' then sum(sqq.qtynew) when rp.string_value3 = '2' then sum(sqq.qtyused) else sum(sqq.qtyonstock) end ) else 0 end )
  - ( case when sqh.year*100+sqh.week = rp.number_value3*100+rp.number_value4
           then ( case when rp.string_value3 = '1' then sum(sqq.qtynew) when rp.string_value3 = '2' then sum(sqq.qtyused) else sum(sqq.qtyonstock) end ) else 0 end )
  * F_REPLACEMENTSALESPRICE( rp.reportparam_id,
                             ( case when rp.number_value1 in (1, 2) then rp.number_value2 when rp.number_value1 = 3 then sdi.defaultsupplier_id end )
                            , prd.product_id, sz.sizedefinition_id ) DiffValue
, currency.decimals, currency.invoiceamountdecimals
, languages.code languageCode
from
  statusquoheader sqh
, sqstockquantity sqq
     left outer join customer cu on sqq.customer_link_id = cu.customer_id
, stockroom sk, businessunit bu, product prd, productgroup pg, sizedefinition sz
, stockdefinitionperitem sdi
, reportparam rp, currency
, languages
where
    sqh.statusquoheader_id = sqq.statusquoheader_id
and sqq.stockroom_id = sdi.stockroom_id
and sqq.product_link_id = sdi.product_id
and sqq.sizedefinition_link_id = sdi.sizedefinition_id
and coalesce(sqq.customer_link_id, 0) = coalesce(sdi.customer_id, 0)
and sqq.customerowned = sdi.customerowned
and sqq.stockroom_id = sk.stockroom_id
        and sk.managedbybu_id = bu.businessunit_id
and sqq.product_link_id = prd.product_id
    and prd.productgroup_id = pg.productgroup_id
and sqq.sizedefinition_link_id = sz.sizedefinition_id
    and sqh.year*100+sqh.week in ( rp.number_value3*100+rp.number_value4, rp.number_value5*100+rp.number_value6)
and currency.currency_id = F_CURRENCY( rp.reportparam_id
                                       , ( case when rp.number_value1 in (1, 2) then rp.number_value2
                                                 when rp.number_value1 = 3 then sdi.defaultsupplier_id end ))
group by
  bu.code, sk.code, sk.name
, sqq.customerowned, sqq.customer_link_id, cu.customernumber, cu.name, rp.string_value1, rp.string_value2
, sdi.defaultsupplier_id
, rp.reportparam_id, rp.number_value1, rp.number_value2, rp.string_value3
, sqh.year*100+sqh.week, rp.number_value3*100+rp.number_value4, rp.number_value5*100+rp.number_value6
, pg.code, prd.code, sz.code, prd.product_id, sz.sizedefinition_id
, currency.decimals, currency.invoiceamountdecimals
, languages.language_id, languages.code
/

  CREATE OR REPLACE VIEW "V_SNISSUEHISTORY" ("WORKORDER_ID", "ASSIGNDATE", "PRODUCTCODE", "PRODUCTDESC", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESC", "ISSUEDQTY", "QDDESC", "LANGUAGECODE") AS 
  select wo.workorder_id, trunc(a.salesdate) assigndate,
  p.code productcode, pld.description productdesc, s.code sizedefinitionCode,
  sld.description sizedefinitionDesc,
  sum(a.quantity) issuedqty,
  coalesce(qd.description, qg.code) qddesc,
  lan.code languagecode
from garmentsaleshistory a
     inner join workorderline wol
           inner join workorder wo on wol.workorder_id = wo.workorder_id
     on a.workorderline_id = wol.workorderline_id
     inner join product_link p
           left outer join product_link_desc pld on p.product_link_id = pld.product_link_id
     on a.product_link_id = p.product_link_id
     inner join sizedefinition_link s
           left outer join sizedefinition_link_desc sld on s.sizedefinition_link_id = sld.sizedefinition_link_id
     on a.sizedefinition_link_id = s.sizedefinition_link_id
     inner join qualitygrade qg
           left outer join qualitygrade_desc qd on qg.qualitygrade_id = qd.qualitygrade_id
     on a.qualitygrade_id = qg.qualitygrade_id, languages lan
where coalesce(pld.language_id, lan.language_id) = lan.language_id
      and coalesce(sld.language_id, lan.language_id) = lan.language_id
      and coalesce(qd.language_id, lan.language_id) = lan.language_id
group by wo.workorder_id, trunc(a.salesdate), p.code, pld.description, s.code,
         sld.description, coalesce(qd.description, qg.code), lan.code
/

  CREATE OR REPLACE VIEW "V_SOILCOUNTEDPRODUCTS" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "PRODUCTGROUPCODE", "PRODUCTGROUPDESCRIPTION", "PRODUCTCODE", "PRODUCTDESCRIPTION", "ACTIVITYCODE", "THEORETICALWEIGHT", "TYPEOFMERCHANDISE", "MODEL", "PRODSIZE_THEORETICALWEIGHT", "SIZECODE", "SIZEDESCRIPTION", "RECEIVINGDATE", "YEARWEEK", "WEEK", "YEAR", "REALMONTH", "REALYEAR", "DAYNUMBER", "BUSINESSUNIT_ID", "PROCESSBU_ID", "INVOICEBU_ID", "PROCESSBUCODE", "PROCESSBUDESCRIPTION", "INVOICEBUCODE", "INVOICEBUDESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP", "DECIMALS", "INVOICEAMOUNTDECIMALS", "TAXABLE", "DEFAULTBUSINESSUNIT_ID", "CUSTOMERLANGUAGECODE", "LANGUAGECODE", "QUANTITYSOIL", "QUANTITYABUSED", "CUSTOMER_ID", "PRODUCT_ID", "SIZEDEFINITION_ID", "PLANT_CODE", "PLANT_NAME") AS 
  select customer_link.customernumber, customer_link.name customername,
       department_link.departmentnumber, department_link.description departmentdescription,
       distributionpoint_link.distributionpointnumber, distributionpoint_link.description distributionpointdescription,
       productgroup.code productgroupcode,
       (select a.description from productgroup_desc a where a.productgroup_id = productgroup.productgroup_id
                and a.language_id = languages.language_id) productgroupdescription,
       pr.code productcode,
       (select b.description from product_link_desc b where b.product_link_id = sh.product_link_id and b.language_id = languages.language_id) productdescription,
       (select f.code from activity f where f.activity_id = productgroup.activity_id) activitycode,
       pr.theoreticalweight, pr.typeofmerchandise, pr.model,
       productsize.theoreticalweight prodsize_theoreticalweight,
       sizedefinition.code sizecode,
       (select c.description from sizedefinition_link_desc c where c.sizedefinition_link_id = sh.sizedefinition_link_id and c.language_id = languages.language_id) sizedescription,
       sh.receivingdate, sh.year*100 + sh.week yearweek,
       sh.week, sh.year,
       month(sh.receivingdate) realmonth,
       year(sh.receivingdate) realyear,
       sh.daynumber, processbu.businessunit_id, processbu.businessunit_id processbu_ID, invoicebu.businessunit_id invoicebu_ID,
       processbu.code processbucode, processbu.description processbudescription, invoicebu.code invoicebucode,
       invoicebu.description invoicebudescription, sh.systemuser_id, sh.timestamp,
       cur.decimals, cur.invoiceamountdecimals,
       cu.taxable, processbu.businessunit_id defaultbusinessunit_id,
       customer_link.languagecode customerlanguagecode, languages.code languagecode, sh.quantitysoil, sh.quantityabused,
       cu.customer_id, pr.product_id, sizedefinition.sizedefinition_id, pl.code plant_code, pl.name plant_name
 from soilhistory sh, product pr, productgroup, sizedefinition, productsize, customer_link
        left outer join customer cu
        on cu.customer_id = customer_link.customer_id,
      department_link, distributionpoint_link,
      businessunit processbu, businessunit invoicebu, languages,
      currency cur, plant pl
 where sh.distributionpoint_link_id = distributionpoint_link.distributionpoint_link_id
  and distributionpoint_link.department_link_id = department_link.department_link_id
  and department_link.customer_link_id = customer_link.customer_link_id
  and sh.product_link_id = pr.product_id and pr.productgroup_id = productgroup.productgroup_id
  and sh.sizedefinition_link_id = sizedefinition.sizedefinition_id
  and sh.processbusinessunit_id = processbu.businessunit_id
  and sh.invoicebusinessunit_id = invoicebu.businessunit_id
  and pr.product_id = productsize.product_id
  and sizedefinition.sizedefinition_id = productsize.sizedefinition_id
  and cu.currency_id = cur.currency_id
  and (exists (select 1
                from   customeractivities ca
                where  ca.customer_id = cu.customer_id
                and    ca.processbusinessunit_id = processbu.businessunit_id)
        or processbu.businessunit_id = cu.defaultbusinessunit_id)
  and processbu.plant_id = pl.plant_id
/

  CREATE OR REPLACE VIEW "V_SOILPLPC" ("CUSTOMER_ID", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "FINMETHODCODE", "LANGUAGECODE") AS 
  SELECT plpc.customer_id, p.code productcode,
  (select pd.description from product_desc pd where pd.product_id = p.product_id
     and pd.language_id = l.language_id) productdesc,
  s.code sizecode, f.code finmethodcode,
  l.code languagecode
from productlistpercustomer plpc, product p, sizedefinition s, finishingmethod f, languages l
where plpc.soilcountmethod <> 0
  and plpc.product_id = p.product_id
  and plpc.sizedefinition_id = s.sizedefinition_id
  and plpc.finishingmethod_id = f.finishingmethod_id
  and trunc(sysdate) between plpc.dateactive and plpc.dateinactive
/

  CREATE OR REPLACE VIEW "V_SOILREASONABILITY_AUX" ("CUSTOMERNUMBER", "CUSTOMERNAME", "PRODUCT_CODE", "PRODUCT_DESCRIPTION", "SIZEDEFINITION_CODE", "SIZEDEFINITION_DESCRIPTION", "ROUTE_ID", "PICKUPDATE", "SOILTICKETNUMBER", "CURRENTQTY", "NULLQTY", "INVENTORYQTY", "PICKUPQTY1", "PICKUPQTY2", "PICKUPQTY3", "PICKUPQTY4", "PICKUPQTY5", "PICKUPQTY6", "PICKUPQTY7", "PICKUPQTY8", "PICKUPQTY9", "PICKUPQTY10", "PICKUPQTY11", "PICKUPQTY12", "PICKUPQTY13", "LANGUAGECODE") AS 
  select b.customernumber, b.name customername,
  e.code product_code,
  (SELECT description FROM PRODUCT_LINK_DESC pd WHERE pd.PRODUCT_LINK_ID = a.product_link_id
    AND pd.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCT_DESCRIPTION,
  f.code sizedefinition_code,
  (SELECT description FROM SIZEDEFINITION_LINK_DESC sd WHERE sd.sizedefinition_link_id = a.sizedefinition_link_id
    AND sd.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEDEFINITION_DESCRIPTION,
  c.route_id, a.pickupdate, a.soilticketnumber,
  a.currentqty,
  --coalesce(a.currentqty, -1) nullqty,
  (CASE WHEN a.currentqty is null then -1 ELSE 0 END) nullqty,
  a.inventoryqty,
  a.pickupqty1, a.pickupqty2, a.pickupqty3, a.pickupqty4, a.pickupqty5, a.pickupqty6, a.pickupqty7,
  a.pickupqty8, a.pickupqty9, a.pickupqty10, a.pickupqty11, a.pickupqty12, a.pickupqty13,
  languages.code languagecode
from soilreasonability a, customer_link b, route c, product_link e,
  sizedefinition_link f, languages
where a.customer_link_id = b.customer_link_id
 and a.route_id = c.route_id
 and a.product_link_id = e.product_link_id
 and a.sizedefinition_link_id = f.sizedefinition_link_id
/

  CREATE OR REPLACE VIEW "V_SOILREASONABILITY_MISS" ("ROUTE_ID", "DRIVINGDATE", "SOILTICKETNUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "STOPNUMBER") AS 
  select rc.route_id, rc.drivingdate,
  st.soilticketnumber,
  cu.customernumber, cu.name customername,
  s.stopnumber
from soilticket st, routecontrol rc, customer cu, stop s
where st.routecontrol_id = rc.routecontrol_id
  and st.customer_id = cu.customer_id
  and st.stop_id = s.stop_id
  and not exists
  (select *
   from soilreasonability sr
   where sr.soilticketnumber = st.soilticketnumber
     and sr.pickupdate = rc.drivingdate
     and sr.route_id = rc.route_id
     and sr.customer_link_id = st.customer_id)
/

  CREATE OR REPLACE VIEW "V_SOILRECEPTIONTICKET" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "PRIMARYID", "CONTAINERTYPE", "WEIGHINGTRANSACTION_ID", "WEIGHINGDATE", "DELIVERYDATE", "GROSSWEIGHT", "WEIGHINGCATEGORY", "WEIGHTUNIT", "LANGUAGE_ID", "LANGUAGE_CODE") AS 
  select /*version 1.0*/
       cu.customernumber, cu.name customername, de.departmentnumber, de.description departmentdesc,
       dp.distributionpointnumber, dp.description distributionpointdesc,
       (select co.primaryid
          from container co
         where co.container_id = wt.container_id) primaryid,
       (select ctd.description
          from containertype_desc ctd
         where ctd.containertype_id = wt.containertype_id
           and ctd.language_id = lan.language_id) containertype,
       wt.weighingtransaction_id, wt.weighingdate, wt.deliverydate, wt.grossweight,
       (select wcd.description
          from weighingcategory_desc wcd
         where wcd.weighingcategory_id = wt.weighingcategory_link_id
           and wcd.language_id = lan.language_id) weighingcategory,
       (select ss.value
          from businessunit bu
               join systemsetting ss on bu.plant_id = ss.plant_id
         where bu.businessunit_id = wt.businessunit_id
           and ss.name = 'WEIGHTUNIT') weightunit,
       lan.language_id, lan.code language_code
  from weighingtransaction wt
       left join distributionpoint dp on wt.distributionpoint_link_id = dp.distributionpoint_id
       join department de on wt.department_link_id = de.department_id
       join customer cu on wt.customer_link_id = cu.customer_id
       cross join languages lan
/

  CREATE OR REPLACE VIEW "V_SOILTICKETHEADER" ("SOILTICKETNUMBER", "SOILTICKETCOPIES", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMERSTREET", "SOILTICKET_ID", "CUSTOMERZIPCODE", "CUSTOMERCITY", "CUSTOMERSTREET2", "CUSTOMERSTATE", "CUSTOMERMARKINGGARMENT", "ROUTECONTROL_ID", "ROUTENUMBER", "ROUTESTOPNUMBER", "DEPOTCODE", "PROCESSBUSINESSUNITCODE", "PLANTCODE", "INVOICENUMBER", "INVOICEDATE", "IMPORTDATE", "COUNTDATE", "EMPLOYEENUMBER", "EMPLOYEENAME", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  select /*version 2.0*/
       st.soilticketnumber, rs.soiltickets soilticketcopies, c.customernumber, c.name customername, ads.street customerstreet, st.soilticket_id,
       ads.zipcode customerzipcode, ads.city customercity, ads.street2 customerstreet2,ads.state customerstate, c.customermarkinggarment,
       rc.routecontrol_id, ro.routenumber, st.routestopnumber, dep.code depotcode, bu.code processbusinessunitcode, p.code plantcode,
       st.invoicenumber, st.invoicedate, st.importdate, st.countdate, e.employeenumber, e.name employeename, st.systemuser_id, st.timestamp
  from soilticket st
       left join employee e on st.employee_id = e.employee_id
       join businessunit bu
            join plant p on bu.plant_id = p.plant_id
       on st.processbusinessunit_id = bu.businessunit_id
       join customer c
            join address ads on c.visitaddress_id = ads.address_id
       on st.customer_id = c.customer_id
       join routecontrol rc
            join route ro
                 left join depot dep on ro.depot_id = dep.depot_id
                 join routestop rs on ro.route_id = rs.route_id
            on rc.route_id = ro.route_id
       on st.routecontrol_id = rc.routecontrol_id
 where rs.customer_id = st.customer_id
   and rs.dateactive <= st.invoicedate
   and rs.dateinactive >= st.invoicedate
/

  CREATE OR REPLACE VIEW "V_SOILTICKETLINE" ("SOILTICKETNUMBER", "PRODUCTCODE", "FINISHINGMETHODCODE", "SIZEDEFINITIONCODE", "COUNTKEYPAD", "TIMESTAMP", "COUNTCONVERTED", "COUNTABUSED", "SOILWEIGHT", "INVOICELINENUMBER", "INVENTORY", "DELAYEDEVENEXCHANGE", "SYSTEMUSER_ID", "LANGUAGECODE", "COUNTLIGHTFRAME", "PRODUCTDESCRIPTION") AS 
  select /*version 2.0*/
       st.soilticketnumber, p.code productcode, fm.code finishingmethodcode, sd.code sizedefinitioncode,
       stl.countkeypad, stl.timestamp, stl.countconverted, stl.countabused, stl.soilweight, stl.invoicelinenumber,
       stl.inventory, stl.delayedevenexchange, stl.systemuser_id, lan.code languagecode, stl.countlightframe,
       (select pds.description
          from product_desc pds
         where pds.product_id = stl.product_id
           and pds.language_id = lan.language_id) productdescription
  from soilticketline stl
       join soilticket st on stl.soilticket_id = st.soilticket_id
       join product p on stl.product_id = p.product_id
       join sizedefinition sd on stl.sizedefinition_id = sd.sizedefinition_id
       join finishingmethod fm on stl.finishingmethod_id = fm.finishingmethod_id
       cross join languages lan
/

  CREATE OR REPLACE VIEW "V_SOILWEIGHTPERDAYANDROUTE" ("ROUTENUMBER", "ROUTEDESC", "DAYNUMBER", "WEIGHINGDATE", "WEIGHINGDATEDAY", "WEIGHINGWEEK", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_ID", "WEIGHINGCATEGORYCODE", "WEIGHINGCATEGORYDESC", "GROSSWEIGHT", "TAREWEIGHT", "NETWEIGHT", "TICKETNUMBER", "WEIGHINGTICKETLINE_ID", "WEIGHTUNIT", "LANGUAGECODE") AS 
  select
  route.routenumber, route.description routeDesc, weit.daynumber, weit.weighingdate
, ( select day_desc.description from day_desc where day_desc.day_id = weit.daynumber and day_desc.language_id = languages.language_id) weighingdateDay
, weit.weighingweek
, cu.customernumber, cu.name customerName, cu.customer_id
, weicat.code weighingcategoryCode
, ( select weighingcategory_desc.description from weighingcategory_desc where weighingcategory_desc.weighingcategory_id = weicat.weighingcategory_id
  and weighingcategory_desc.language_id = languages.language_id ) weighingcategoryDesc
, weitli.grossweight, weitli.tareweight, ( weitli.grossweight - weitli.tareweight ) NetWeight
, weit.ticketnumber, weitli.weighingticketline_id
, (select ss.value from systemsetting ss where processBU.plant_id = ss.plant_id and ss.name = 'WEIGHTUNIT') WeightUnit
, languages.code languageCode
from
  weighingticket weit, weighingticketline weitli, weighingcategory weicat, customer cu
, route
, businessunit processBU
, languages
where
    weit.origin = 1
and weit.soilticket = 'Y'
and weit.weighingticket_id = weitli.weighingticket_id
    and weitli.weighingcategory_id = weicat.weighingcategory_id
and weit.customer_id = cu.customer_id
and route.route_id = F_FirstRouteIDperDay(cu.customer_id, weit.daynumber)
and weit.processbusinessunit_id = processBU.Businessunit_Id
and route.active = 'Y'
/

  CREATE OR REPLACE VIEW "V_SORTBATCHCONTENTS" ("BATCHNUMBER", "SEQUENCENUMBER", "IDCODE", "EXPECTATIONLEVEL", "LASTSCANDATE", "UPDATEDSINCEEXPORT", "SORTSTRING", "CUSTOMERNUMBER", "CUSTOMERNAME", "BATCHDATE", "FINISHSELECTION", "FINISHINGMETHOD", "PRODUCTCODE", "FOLDINGPROGRAM") AS 
  select sc.sortbatch_id batchnumber,
       sc.sequencenumber,
       sc.idcode,
       sc.expectationlevel,
       yearmonthday(sc.lastscantime) lastscandate,
       (case
         when sc.lastscantime > s.exporttime and s.exporttime is not null then
          'Y'
         else
          'N'
       end) updatedsinceexport,
       sc.sortstring,
       c.customernumber,
       c.name customername,
       s.batchdate,
       sc.finishselection,
       f.code finishingmethod,
       p.code productcode,
       fp.foldingprogram
from   sortbatchcontents sc
join   sortbatch s
on     s.sortbatch_id = sc.sortbatch_id
join   customer c
on     c.customer_id = sc.customer_id
left   outer join(uniqueitem u
join   product p
on     p.product_id = u.product_id
join   finishingmethod f
on     f.finishingmethod_id = u.finishingmethod_id
left   outer join foldingprogramdefinition fp
on     (fp.product_id = u.product_id and fp.finishingmethod_id = u.finishingmethod_id)) on u.uniqueitem_id = sc.uniqueitem_id
where  not exists (select 1
        from   uniqueitem u
        join   product p
        on     p.product_id = u.product_id
        join   finishingcode f
        on     f.finishingcode_id = p.finishingcode_id
        where  u.uniqueitem_id = sc.uniqueitem_id
        and    f.finishingcode = 'BYPASS')
/

  CREATE OR REPLACE VIEW "V_SORTINGLIST" ("ODD_EVEN_AS_STRING", "ODD_EVEN_AS_NUMBER", "ROUTENUMBER", "ROUTEDESC", "ROUTECONTROL_ID", "DRIVINGDATE", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMERMARKINGGARMENT", "WEARERNUMBER", "FULLNAME", "CITY") AS 
  select -- null and alphanumeric := 00
  case
       when (cu.customermarkinggarment is null) then '00'
            else '02'
                 end ODD_EVEN_as_string
, 0 ODD_EVEN_as_number
, route.routenumber, route.description routeDesc, rc.routecontrol_id, rc.drivingdate
, cu.customernumber, cu.name customerName, coalesce(cu.customermarkinggarment, ' ') customermarkinggarment
, we.wearernumber, we.fullname, address.city
from
  routecontrol rc, stop st, route
, customer cu, wearer we
, address
where
    rc.routecontrol_id = st.routecontrol_id
and st.status in (0, 3)
and rc.route_id = route.route_id
and st.customer_link_id = cu.customer_id
    and ISNUMERIC(cu.customermarkinggarment) = 0
    and cu.customer_id = we.customer_id
        and trunc(sysdate) between we.dateactive and we.dateinactive
and cu.visitaddress_id = address.address_id
UNION ALL -- numeric odd := 01, even := 2
select
  case F_ODD_EVEN(cu.customermarkinggarment) when 'ODD' then '01'
       else '2'
            end ODD_EVEN_as_string
, cast(cu.customermarkinggarment as numeric) ODD_EVEN_as_number
, route.routenumber, route.description routeDesc, rc.routecontrol_id, rc.drivingdate
, cu.customernumber, cu.name customerName, cu.customermarkinggarment
, we.wearernumber, we.fullname, address.city
from
  routecontrol rc, stop st, route
, customer cu, wearer we
, address
where
    rc.routecontrol_id = st.routecontrol_id
and st.status in (0, 3)
and rc.route_id = route.route_id
and st.customer_link_id = cu.customer_id
    and ISNUMERIC(cu.customermarkinggarment) = 1
    and cu.customer_id = we.customer_id
        and trunc(sysdate) between we.dateactive and we.dateinactive
and cu.visitaddress_id = address.address_id
/

  CREATE OR REPLACE VIEW "V_SORTINGLOCATIONS" ("LTXSORTINGSTATION_ID", "LTXSORTINGSTATIONLOCATION_ID", "ROWCODE", "POSITIONCODE", "LTXSORTSESSION_ID", "LTXSORTSESSIONLOCATION_ID", "STATUS", "ITEMSINLOCATION") AS 
  select STATIONLOC.LTXSORTINGSTATION_ID, STATIONLOC.LTXSORTINGSTATIONLOCATION_ID,
       STATIONLOC.ROWCODE, STATIONLOC.Positioncode,
       SESSIONLOC.LTXSORTSESSION_ID, SESSIONLOC.LTXSORTSESSIONLOCATION_ID, SESSIONLOC.STATUS,
       SESSIONLOC.ITEMSINLOCATION
from ltxsortingstationlocation STATIONLOC left outer join ltxsortsessionlocation SESSIONLOC
     on STATIONLOC.LTXSORTINGSTATIONLOCATION_ID = SESSIONLOC.LTXSORTINGSTATIONLOCATION_ID
     where STATIONLOC.ACTIVE = 'Y'
     order by STATIONLOC.LTXSORTINGSTATION_ID, STATIONLOC.ROWNR,STATIONLOC.POSITION
/

  CREATE OR REPLACE VIEW "V_SPECIALCHARGETAX" ("SPECIALCHARGECODE", "SPECIALCHARGEDESCRIPTION", "COUNTRYCODE", "COUNTRYDESCRIPTION", "TAXGROUPCODE", "TAXGROUPDESCRIPTION", "TIMESTAMP", "SYSTEMUSER_ID", "LANGUAGECODE") AS 
  select b.code specialchargecode,
( select description from specialcharge_desc x where x.specialcharge_id = a.specialcharge_id and x.language_id = languages.language_id) specialchargedescription,
 c.code countrycode, c.description countrydescription,
d.code taxgroupcode, d.description taxgroupdescription, a.timestamp, a.systemuser_id, languages.code languagecode
from specialchargetax a
left outer join taxgroup d on (a.taxgroup_id = d.taxgroup_id), specialcharge b,country c, languages
where a.specialcharge_id = b.specialcharge_id
and a.country_id = c.country_id
/

  CREATE OR REPLACE VIEW "V_SPECIFICATIONCOSTSPERCOSTC" ("INVOICEFREQUENCYNUMBER", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "STREET", "ZIPCODE", "CITY", "COUNTY", "INVOICENUMBER", "INVOICEDATE", "TYPE", "STARTMONTH", "ENDMONTH", "STARTYEAR", "ENDYEAR", "STARTWEEK", "STARTYEARWEEK", "COSTCENTERCODE", "COSTCENTERDESC", "INVOICELINE_ID", "COSTCENTER_ID", "CURRENCYCODE", "INVOICEAMOUNTDECIMALS", "INVOICEHEADER_ID") AS 
  select ifq.invoicefrequencynumber,
  ih.deltocustomernumber, ih.deltocustomername
, cast(CONCATENATEWITHBLANK(ih.deltostreet, ih.deltostreet2) as varchar2(255)) street
, ih.deltozipcode zipcode, ih.deltocity city, ih.deltocounty county
, ih.invoicenumber, ih.invoicedate, ilty.type
, ih.startmonth, ih.endmonth, ih.startyear, ih.endyear
, ih.startweek
, ih.startyear*100+ih.startweek startyearweek
, cc.code costcenterCode, cc.description costcenterDesc
, il.invoiceline_id, cc.costcenter_id
, currency.code currencyCode, currency.invoiceamountdecimals, ih.invoiceheader_id
from
  invoiceheader ih, invoiceline il
, invoicefrequency ifq, invoicelinetype ilty, status, costcenterinvoiceline ccil, costcenter cc
, currency
where
    ih.documenttype = 1   -- invoice
and (ih.invoicetype = 1 or ih.invoicetype = 4)  -- generated
and ih.status_id = status.status_id
    and status.statustype = 'IN' and status.code = '2' -- Settled (US) / Final Invoice (EU)
and ih.invoicefrequency_id = ifq.invoicefrequency_id
and ih.invoiceheader_id = il.invoiceheader_id
and il.invoicelinetype_id = ilty.invoicelinetype_id
    and il.invoiceline_id = ccil.invoiceline_id
        and ccil.costcenter_link_id = cc.costcenter_id
and ih.currency_id = currency.currency_id
/

  CREATE OR REPLACE VIEW "V_SQITEMSINCIRCULATION" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "YEARWEEK", "YEAR", "WEEK", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "WEARERNUMBER", "WEARERNAME", "PRODUCTCODE", "SIZECODE", "FINISHINGCODE", "PRODUCTDESC", "SIZEDESC", "FINISHINGDESC", "TOTALCIRCINV", "QTYRENTEDPERPIECE", "QTYRENTEDOTHER", "COGCIRCINV", "QTYASSIGNED", "FREEISSUEDCIRCINV", "FREESEASONCIRCINV", "QTYRENTSTOP", "QTYCUSTOMERRENTSTOP", "BEYONDLIFETIMECIRC", "QTYREPLACEMENT", "QTYSUBSTITUTE", "QTYRENTEDDEPOSITSTOCK", "CHARGEAFTERDEPRECIATION", "INVOICEREPLACEMENTS", "LANGUAGECODE", "SQITEMINCIRCULATION_ID", "INVOICEBUSINESSUNIT_ID", "DEFAULTBUSINESSUNIT_ID", "MIN_ACTIVITY_ID", "ACTIVITYBUSINESSUNIT_ID", "QTYRENTEDRETURNRENT", "QTYRENTEDMINRENT", "QTYFULLYAMORTIZED") AS 
  select
  culk.customernumber, culk.name customerName, address.city
, ( sqh.year*100 + sqh.week ) yearweek, sqh.year, sqh.week
, delk.departmentnumber, delk.description departmentDesc
, coalesce(weylk.wearernumber, -1) wearernumber, weylk.wearername
, prdlk.code productCode, szlk.code sizeCode, fm.code finishingCode
, ( select product_desc.description from product_desc where product_desc.product_id = prdlk.product_link_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( select szd.description from sizedefinition_desc szd where szd.sizedefinition_id = szlk.sizedefinition_id
  and szd.language_id = languages.language_id ) sizeDesc
, ( select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
  and fmd.language_id = languages.language_id ) finishingDesc
, sqcirc.totalcircinv
, case sqcirc.chargeafterdepreciation when 'Y' then ( sqcirc.qtyrentedperpiece + sqcirc.beyondlifetimecirc )
       else sqcirc.qtyrentedperpiece end qtyrentedperpiece
, sqcirc.qtyrentedother, sqcirc.cogcircinv
, sqcirc.qtyassigned, sqcirc.freeissuedcircinv, sqcirc.freeseasoncircinv, sqcirc.qtyrentstop
, sqcirc.qtycustomerrentstop
, case sqcirc.chargeafterdepreciation when 'Y' then  0
       else sqcirc.beyondlifetimecirc end beyondlifetimecirc
, sqcirc.qtyreplacement
, sqcirc.qtysubstitute, sqcirc.qtyrenteddepositstock, sqcirc.chargeafterdepreciation
, ss.value INVOICEREPLACEMENTS
, languages.code languageCode , sqcirc.sqitemincirculation_id
, sqh.invoicebusinessunit_id, cu.defaultbusinessunit_id
, (select min(caa.activity_id) from customeractivities caa where caa.customer_id=cu.customer_id and caa.invoicebusinessunit_id = abu.businessunit_id) min_ACTIVITY_ID
, abu.businessunit_id ACTIVITYBUSINESSUNIT_ID
, sqcirc.qtyrentedreturnrent
, sqcirc.qtyrentedminrent
, nvl(sqcirc.qtyfullyamortized,0) qtyfullyamortized
from
  statusquoheader sqh
, sqitemincirculation sqcirc
    left outer join weareremployment_link weylk
          on sqcirc.weareremployment_link_id = weylk.weareremployment_link_id
, customer_link culk
    left outer join
          ( customer cu join address on cu.visitaddress_id = address.address_id )
         on culk.customer_id = cu.customer_id
, department_link delk
, product_link prdlk, sizedefinition_link szlk, finishingmethod fm
, businessunit processBU, plant, systemsetting ss
, languages
, businessunit abu
where
    sqh.statusquotype = 1
and sqh.statusquoheader_id = sqcirc.statusquoheader_id
    and sqcirc.customer_link_id = culk.customer_link_id
        and sqcirc.department_link_id = delk.department_link_id
and sqcirc.product_link_id = prdlk.product_link_id
and sqcirc.sizedefinition_link_id = szlk.sizedefinition_link_id
and sqcirc.finishingmethod_id = fm.finishingmethod_id
and sqh.processbusinessunit_id = processBU.Businessunit_Id
    and processBU.Plant_Id = plant.plant_id
        and plant.plant_id = ss.plant_id
            and ss.name = 'INVOICEREPLACEMENTS'
and sqh.subtype in (0, 2)
/

  CREATE OR REPLACE VIEW "V_SQLEASE" ("CUSTOMERLKNUMBER", "CUSTOMERLKNAME", "PRODUCTLKCODE", "PRODUCTLKDESC", "YEARWEEK", "YEAR", "WEEK", "QUANTITY", "AMOUNT", "CURRENCYCODE", "CURRENCYDECIMALS", "LANGUAGECODE") AS 
  select
  culk.customernumber customerLKnumber, culk.name customerLKname, prdlk.code productLKcode
, ( select product_link_desc.description from product_link_desc where product_link_desc.product_link_id = prdlk.product_link_id
  and product_link_desc.language_id = languages.language_id ) productLKdesc
, ( ( sqh.year * 100 ) + sqh.week ) YearWeek
, sqh.year, sqh.week, sqlease.quantity, ( sqlease.price * sqlease.quantity ) Amount
, currency.code currencyCode, coalesce( currency.decimals, 2 ) currencyDecimals
, languages.code languageCode
from
  statusquoheader sqh, sqlease, product_link prdlk
, customer_link culk
    left outer join
               ( customer cu join currency on cu.currency_id = currency.currency_id )
          on culk.Customer_Id = cu.customer_id
, languages
where
    sqh.statusquoheader_id = sqlease.statusquoheader_id
and sqlease.customer_link_id = culk.customer_link_id
and sqlease.product_link_id = prdlk.product_link_id
/

  CREATE OR REPLACE VIEW "V_SQMATSINCIRCULATION" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "YEARWEEK", "YEAR", "WEEK", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "PRODUCTCODE", "SIZECODE", "FINISHINGCODE", "PRODUCTDESC", "QTYTOTAL", "TOTALFREE", "QTYRENTED", "QTYFREESEASON", "QTYRENTSTOP", "LANGUAGECODE", "INVOICEBUSINESSUNIT_ID", "DEFAULTBUSINESSUNIT_ID", "MIN_ACTIVITY_ID", "ACTIVITYBUSINESSUNIT_ID") AS 
  select
  culk.customernumber, culk.name customerName, address.city
, ( sqh.year*100 + sqh.week) yearweek, sqh.year, sqh.week
, delk.departmentnumber, delk.description departmentDesc
, dilk.distributionpointnumber, dilk.description distributionpointDesc
, prdlk.code productCode, szlk.code sizeCode, fm.code finishingCode
, ( select product_desc.description from product_desc where product_desc.product_id = prdlk.product_link_id
  and product_desc.language_id = languages.language_id ) productDesc
, sqmat.qtyrented + sqmat.qtyfreeseason + sqmat.qtyrentstop QtyTotal
, sqmat.qtyfreeseason + sqmat.qtyrentstop TotalFree
, sqmat.qtyrented, sqmat.qtyfreeseason, sqmat.qtyrentstop
, languages.code languageCode
, sqh.invoicebusinessunit_id, cu.defaultbusinessunit_id
, (select min(caa.activity_id) from customeractivities caa where caa.customer_id=cu.customer_id and caa.invoicebusinessunit_id = abu.businessunit_id) min_ACTIVITY_ID
, abu.businessunit_id ACTIVITYBUSINESSUNIT_ID
from
  statusquoheader sqh, sqmatincirculation sqmat
, customer_link culk
    left outer join
          ( customer cu join address on cu.Visitaddress_Id = address.address_id )
         on culk.customer_id = cu.customer_id
, department_link delk, distributionpoint_link dilk
, product_link prdlk, sizedefinition_link szlk, finishingmethod fm
, languages
, businessunit abu
where
    sqh.statusquoheader_id = sqmat.statusquoheader_id
and sqmat.customer_link_id = culk.customer_link_id
and sqmat.department_link_id = delk.department_link_id
and sqmat.distributionpoint_link_id = dilk.distributionpoint_link_id
and sqmat.product_link_id = prdlk.product_link_id
and sqmat.sizedefinition_link_id = szlk.sizedefinition_link_id
and sqmat.finishingmethod_id = fm.finishingmethod_id
and sqh.subtype in (0, 2)
/

  CREATE OR REPLACE VIEW "V_SQSETSINCIRCULATION" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "YEARWEEK", "YEAR", "WEEK", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "WEARERNUMBER", "WEARERNAME", "CHANGESPERWEEK", "PRODUCTCODE", "SIZECODE", "FINISHINGCODE", "PRODUCTDESC", "TOTALQTY", "QTYRENTED", "FREESEASON", "CUSTOMERRENTSTOP", "WEARERRENTSTOP", "TOTALMAXINV", "TOTALINCIRC", "FREEMAXINV", "FREECIRCINV", "LANGUAGECODE", "INVOICEBUSINESSUNIT_ID", "DEFAULTBUSINESSUNIT_ID", "MIN_ACTIVITY_ID", "ACTIVITYBUSINESSUNIT_ID") AS 
  select
  culk.customernumber, culk.name customerName, address.city
, ( sqh.year*100 + sqh.week) yearweek, sqh.year, sqh.week
, delk.departmentnumber, delk.description departmentDesc
, weylk.wearernumber, weylk.wearername
, sqset.changesperweek
, prdlk.code productCode, szlk.code sizeCode, fm.code finishingCode
, ( select product_desc.description from product_desc where product_desc.product_id = prdlk.product_link_id
  and product_desc.language_id = languages.language_id ) productDesc
, sqset.numberemploymentscharge + sqset.numberemploymentsfree + sqset.numberemplcustrentstop + sqset.numberemploymentsrentstop totalQty
, sqset.numberemploymentscharge QtyRented
, sqset.numberemploymentsfree FreeSeason
, sqset.numberemplcustrentstop customerrentstop, sqset.numberemploymentsrentstop wearerrentstop
, sqset.maxinv totalMaxInv, sqset.totalcircinv totalInCirc, sqset.freemaxinv, sqset.freecircinv
, languages.code languageCode
, sqh.invoicebusinessunit_id, cu.defaultbusinessunit_id
, (select min(caa.activity_id) from customeractivities caa where caa.customer_id=cu.customer_id and caa.invoicebusinessunit_id = abu.businessunit_id) min_ACTIVITY_ID
, abu.businessunit_id ACTIVITYBUSINESSUNIT_ID
from
  statusquoheader sqh, sqsetincirculation sqset
  left outer join weareremployment_link weylk on weylk.weareremployment_link_id = sqset.weareremployment_link_id
, customer_link culk
    left outer join
          ( customer cu join address on cu.visitaddress_id = address.address_id )
         on culk.customer_id = cu.customer_id
, department_link delk
, product_link prdlk, sizedefinition_link szlk, finishingmethod fm
, languages
, businessunit abu
where
    sqh.statusquotype = 2 -- sets
and sqh.statusquoheader_id = sqset.statusquoheader_id
and sqset.customer_link_id = culk.customer_link_id
    and sqset.department_link_id = delk.department_link_id
and sqset.product_link_id = prdlk.product_link_id
and sqset.sizedefinition_link_id = szlk.sizedefinition_link_id
and sqset.finishingmethod_id = fm.finishingmethod_id
/

  CREATE OR REPLACE VIEW "V_SQSTOCKCHARGE" ("CUSTOMERLKNUMBER", "CUSTOMERLKNAME", "PRODUCTLKCODE", "SIZELKCODE", "PRODUCTLKDESC", "YEARWEEK", "YEAR", "WEEK", "QUANTITY", "CURRENCYCODE", "CURRENCYDECIMALS", "LANGUAGECODE") AS 
  select
  culk.customernumber customerLKnumber, culk.name customerLKname, prdlk.code productLKcode, szlk.code sizeLKcode
, ( select product_link_desc.description from product_link_desc where product_link_desc.product_link_id = prdlk.product_link_id
  and product_link_desc.language_id = languages.language_id ) productLKdesc
, ( ( sqh.year * 100 ) + sqh.week ) YearWeek
, sqh.year, sqh.week, sqStockcharge.quantity
, currency.code currencyCode, coalesce( currency.decimals, 2 ) currencyDecimals
, languages.code languageCode
from
  statusquoheader sqh, sqStockcharge, product_link prdlk, sizedefinition_link szlk
, customer_link culk
    left outer join
               ( customer cu join currency on cu.currency_id = currency.currency_id )
          on culk.Customer_Id = cu.customer_id
, languages
where
    sqh.statusquoheader_id = sqStockcharge.statusquoheader_id
and sqStockcharge.customer_link_id = culk.customer_link_id
and sqStockcharge.product_link_id = prdlk.product_link_id
and sqStockcharge.Sizedefinition_Link_Id = szlk.sizedefinition_link_id
/

  CREATE OR REPLACE VIEW "V_SQSTOCKQUANTITY" ("YEARWEEK", "YEAR", "WEEK", "PRODUCTGROUPCODE", "PRODUCTGROUP_DESC", "PARENTPRODUCTCODE", "PARENTPRODUCT_DESC", "PRODUCTCODE", "PRODUCT_DESC", "STOCKROOMCODE", "STOCKROOMNAME", "CUSTOMEROWNED", "CUSTOMERNUMBER", "CUSTOMERNAME", "STOCKUNIQUE", "SIZEDEFINITIONCODE", "SIZEDEFINITION_DESC", "QTYONSTOCK", "QTYUNIQUEWITHMODIF", "QTYNEW", "QTYUSED", "QTYNEWRESERVED", "QTYUSEDRESERVED", "QTYORDERED", "STATUSQUOHEADER_ID", "LANGUAGECODE") AS 
  select a.year*100 + a.week yearweek, a.year, cast(CONCATENATE('Week ', CASTNUMBERASVARCHAR(a.week)) as varchar2(7)) week,
  e.code productgroupcode,
  (SELECT description FROM productgroup_DESC ed WHERE ed.productgroup_id = e.productgroup_id
     AND ed.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productgroup_desc,
  pd.code parentproductcode,
  (SELECT description FROM product_DESC pdd WHERE pdd.product_id = pd.product_id
     AND pdd.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) parentproduct_desc,
  d.code productcode,
  (SELECT description FROM product_DESC dd WHERE dd.product_id = d.product_id
     AND dd.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) product_desc,
  c.code stockroomcode, c.name stockroomname,
  b.customerowned, x.customernumber customernumber, x.name customername,
  b.stockunique,
  f.code sizedefinitioncode,
  (SELECT description FROM sizedefinition_link_DESC fd WHERE fd.sizedefinition_link_id = f.sizedefinition_link_id
     AND fd.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) sizedefinition_desc,
  coalesce(b.qtyonstock, 0) qtyonstock, coalesce(b.qtyuniquewithmodif, 0) qtyuniquewithmodif,
  coalesce(b.qtynew, 0) qtynew, coalesce(b.qtyused, 0) qtyused,
  coalesce(b.qtynewreserved, 0) qtynewreserved, coalesce(b.qtyusedreserved, 0) qtyusedreserved,
  coalesce(b.qtyordered, 0) qtyordered, a.statusquoheader_id,
  languages.code languagecode
from statusquoheader a,
  sqstockquantity b
    left outer join customer_link x on (x.customer_link_id = b.customer_link_id),
  stockroom c, product d, product pd, productgroup e,
  sizedefinition_link f, languages
where a.statusquoheader_id = b.statusquoheader_id
  and b.stockroom_id = c.stockroom_id
  and b.product_link_id = d.product_id
  and d.parentproduct_id = pd.product_id
  and b.stockroom_id = c.stockroom_id
  and b.sizedefinition_link_id = f.sizedefinition_link_id
  and e.productgroup_id = d.productgroup_id
  and c.managedbybu_id = a.processbusinessunit_id
/

  CREATE OR REPLACE VIEW "V_STANDARDDELIVERY" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "SEQUENCENUMBER", "DELIVERSTERILE", "CLEANRETURN", "GENERATEZEROLINES", "PLANTCODE", "PLANTNAME", "PLANTDEPARTMENTCODE", "PLANTDEPARTMENTDESCRIPTION", "TRANSPORTARTICLECODE", "TRANSPORTARTICLEDESCRIPTION", "NUMBEROFTRANSPORTARTICLES", "LASTPACKINGDATE", "CORRECTSHORTAGES", "CORRECTOVERDELIVERIES", "TRUCKLOADPOSITION", "SYSTEMUSER_ID", "TIMESTAMP", "STANDARDDELIVERY_ID", "LANGUAGECODE") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION,
 DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION, STANDARDDELIVERY.SEQUENCENUMBER,
 STANDARDDELIVERY.DELIVERSTERILE, STANDARDDELIVERY.CLEANRETURN, STANDARDDELIVERY.GENERATEZEROLINES,
 PLANT.CODE, PLANT.NAME,
 PLANTDEPARTMENT.CODE, PLANTDEPARTMENT.DESCRIPTION,
 TRANSPORTARTICLE.CODE,
 ( select description from TRANSPORTARTICLE_DESC x where x.transportarticle_id = STANDARDDELIVERY.TRANSPORTARTICLE_ID and x.language_id = languages.language_id) TRANSPORTARTICLE_DESC,
 STANDARDDELIVERY.NUMBEROFTRANSPORTARTICLES, STANDARDDELIVERY.LASTPACKINGDATE,
 STANDARDDELIVERY.CORRECTSHORTAGES, STANDARDDELIVERY.CORRECTOVERDELIVERIES,
 STANDARDDELIVERY.TRUCKLOADPOSITION, STANDARDDELIVERY.SYSTEMUSER_ID, STANDARDDELIVERY.TIMESTAMP,
 standarddelivery.standarddelivery_id, LANGUAGES.CODE
	FROM STANDARDDELIVERY, CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT, PLANTDEPARTMENT, PLANT,
  TRANSPORTARTICLE, LANGUAGES
	WHERE STANDARDDELIVERY.PLANTDEPARTMENT_ID = PLANTDEPARTMENT.PLANTDEPARTMENT_ID
and  PLANTDEPARTMENT.PLANT_ID = PLANT.PLANT_ID
and STANDARDDELIVERY.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
and  DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
and DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
and STANDARDDELIVERY.TRANSPORTARTICLE_ID = TRANSPORTARTICLE.TRANSPORTARTICLE_ID
/

  CREATE OR REPLACE VIEW "V_STANDARDDELIVERYANDSTOCK" ("CUSTOMERNUMBER", "NAME", "DEPARTMENTNUMBER", "DESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "DELIVERYPOINTCODE", "DELIVERYPOINTDESC", "PRODUCTCODE", "PRODUCTGROUPCODE", "SIZECODE", "FINISHINGMETHODCODE", "DELIVERYSCHEMECODE", "SEASONCODE", "DAYNUMBER", "AMOUNT", "STOCK_DAYNUMBER", "STOCK_AMOUNT", "ORDERINGMETHOD", "GENERATEZEROLINES", "CLEANRETURN", "DELIVERSTERILE", "CORRECTSHORTAGES", "CORRECTOVERDELIVERIES", "NUMBEROFTRANSPORTARTICLES", "OCCUPANCY", "STANDARDQTYDEFINITION", "DATEACTIVE", "DATEINACTIVE", "SYSTEMUSER_ID", "TIMESTAMP", "STANDARDDELIVERY_ID", "LANGUAGECODE", "ISTEMPDELSTOP", "BUSINESSUNIT_ID", "REPORTPARAM_ID", "FIXEDRENTQUANTITY", "STANDARDDELIVERYLINE_ID", "RENEWALSTARTDATE", "RENEWALENDDATE", "DATE_VALUE2", "DATE_VALUE3", "CUSTOMERLANGUAGECODE", "PRODUCTDESC", "SEASONDESC", "TRANSPORTARTICLE_DESC") AS 
  select /*version 2.1*/
       cu.customernumber, cu.name, de.departmentnumber, de.description, dp.distributionpointnumber, dp.description distributionpointdesc, delp.code deliverypointcode,
       delp.description deliverypointdesc, pr.code productcode, pg.code productgroupcode, szd.code sizecode, fm.code finishingmethodcode, dsc.code deliveryschemecode, se.code seasoncode,
       d1.daynumber, sda.amount, ns_amount.stock_daynumber, ns_amount.stock_amount, plpd.orderingmethod, sd.generatezerolines, sd.cleanreturn, sd.deliversterile, sd.correctshortages,
       sd.correctoverdeliveries, sd.numberoftransportarticles, de.occupancy, cu.standardqtydefinition, trunc(sdl.dateactive) dateactive, trunc(sdl.dateinactive) dateinactive,
       sdl.systemuser_id, sdl.timestamp, sdl.standarddelivery_id, lan.code languagecode,
       istemporarydeliverystop(rp.number_value1, rp.number_value2, sdl.standarddeliveryline_id) + istemporarydeliverystop_date(rp.date_value1, sdl.standarddeliveryline_id) istempdelstop,
       bu.businessunit_id, rp.reportparam_id, sdl.fixedrentquantity, sdl.standarddeliveryline_id, sdl.renewalstartdate, sdl.renewalenddate, rp.date_value2, rp.date_value3,
       (select clan.code
          from languages clan
         where clan.language_id = cu.language_id) customerlanguagecode,
       (select prd.description
          from product_desc prd
         where prd.product_id = plpd.product_id
           and prd.language_id = lan.language_id) productdesc,
       (select std.description
          from seasontype_desc std
         where se.seasontype_id = std.seasontype_id
           and std.language_id = lan.language_id) seasondesc,
       (select tad.description
          from transportarticle_desc tad
         where tad.transportarticle_id = sd.transportarticle_id
           and tad.language_id = lan.language_id) transportarticle_desc
  from standarddeliveryline sdl
       left join season se on sdl.season_id = se.season_id
       left join deliveryscheme dsc on sdl.deliveryscheme_id = dsc.deliveryscheme_id
       join standarddelivery sd on sdl.standarddelivery_id = sd.standarddelivery_id
       join standarddeliveryamount sda
            join day d1 on sda.day_id = d1.day_id
       on sdl.standarddeliveryline_id = sda.standarddeliveryline_id
       join productlistperdistribpoint plpd
            left join (select n1.productlistperdistribpoint_id, n1.amount stock_amount, d2.daynumber stock_daynumber
                         from normstockamount n1, day d2
                        where n1.day_id = d2.day_id) ns_amount
            on (plpd.productlistperdistribpoint_id = ns_amount.productlistperdistribpoint_id)
            join distributionpoint dp
                 join deliverypoint delp on dp.deliverypoint_id = delp.deliverypoint_id
                 join department de
                      join customer cu on de.customer_id = cu.customer_id
                 on dp.department_id = de.department_id
            on plpd.distributionpoint_id = dp.distributionpoint_id
            join product pr on plpd.product_id = pr.product_id
            join productgroup pg on pr.productgroup_id = pg.productgroup_id
            join sizedefinition szd on plpd.sizedefinition_id = szd.sizedefinition_id
            join finishingmethod fm on plpd.finishingmethod_id = fm.finishingmethod_id
       on sdl.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
       , languages lan, reportparam rp, businessunit bu
 where de.active = 'Y'
   and exists (select ca.customer_id
                 from customeractivities ca
                where ca.activity_id = pg.activity_id
                  and ca.customer_id = cu.customer_id
                  and ca.processbusinessunit_id = bu.businessunit_id)
/

  CREATE OR REPLACE VIEW "V_STANDARDINVENTORY" ("CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERFUNCTIONCODE", "WEARERFUNCTIONDESCRIPTION", "PRODUCTCODE", "PRODUCTDESCRIPTION", "EMBLEMTEMPLATECODE", "EMBLEMTEMPLATEDESCRIPTION", "PUTINUSE", "CHANGESPERWEEK", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, WEARERFUNCTION.CODE, WEARERFUNCTION.DESCRIPTION,
PRODUCT.CODE,
(SELECT DESCRIPTION FROM PRODUCT_DESC A WHERE A.PRODUCT_ID = STANDARDINVENTORY.PRODUCT_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCT_DESC,
 EMBLEMTEMPLATE.CODE, EMBLEMTEMPLATE.DESCRIPTION,
STANDARDINVENTORY.PUTINUSE, STANDARDINVENTORY.CHANGESPERWEEK, STANDARDINVENTORY.SYSTEMUSER_ID, STANDARDINVENTORY.TIMESTAMP, LANGUAGES.CODE
	FROM  STANDARDINVENTORY
  LEFT OUTER JOIN EMBLEMTEMPLATE ON(STANDARDINVENTORY.EMBLEMTEMPLATE_ID = EMBLEMTEMPLATE.EMBLEMTEMPLATE_ID),
   CUSTOMER, WEARERFUNCTION, PRODUCT,  LANGUAGES
	WHERE STANDARDINVENTORY.WEARERFUNCTION_ID = WEARERFUNCTION.WEARERFUNCTION_ID
  AND WEARERFUNCTION.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND STANDARDINVENTORY.PRODUCT_ID = PRODUCT.PRODUCT_ID
/

  CREATE OR REPLACE VIEW "V_STATEMENTHEADER" ("STATEMENTDATE", "STATEMENTNUMBER", "INVOICEBUSINESSUNIT_ID", "INVOICEBUSINESSUNITCODE", "INVOICEBUSINESSUNITDESC", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "STARTWEEK", "ENDWEEK", "STARTMONTH", "ENDMONTH", "STARTYEAR", "ENDYEAR", "CITY", "COUNTY", "STATE", "ZIPCODE", "STREET2", "STREET", "CONTACTPERSONNAME", "CONTACTPERSONPHONE", "EMAILSTATUS", "EMAILADDRESS", "REALCOLLECTIONTYPE", "ORIGINALCOLLECTIONTYPE", "EXPORTED", "STATEMENTCOMMENTS", "PREBILLAMOUNT", "STATEMENTFREQUENCYNUMBER", "CURRENCYCODE", "CURRENCYDESC", "STATUSTYPE", "STATUSCODE", "STATUSFACTORYDESCRIPTION", "COUNTYTAXRATE", "CITYTAXRATE", "STATESTAXRATE", "PLANTCODE", "PLANTNAME", "PLANTSTREET", "PLANTSTREET2", "PLANTZIPCODE", "PLANTCITY", "PLANTSTATE", "PLANTCOUNTY", "PURCHASEORDER", "ROUTENUMBER", "SYSTEMUSER_ID", "TIMESTAMP", "STATEMENTHEADER_ID", "DAYS0", "DAYS30", "DAYS60", "DAYS90", "DAYS120", "PREVIOUSBALANCE", "STATEMENTLAYOUTCODE", "PAYMENTTERMSDESCRIPTION", "BILLTO_CHAIN", "CUSTDELIVERYSCHEME", "REPORTPARAM_ID", "COPY_NUMBER", "PLANTPHONENO", "PLANTFAX", "PLANTEMAIL", "PLANTLOGO", "NETPAYMENTDAYS", "STARTDATE", "ENDDATE") AS 
  select /*version 1.2*/
       sh.invoicedate statementdate, sh.invoicenumber statementnumber, sh.invoicebusinessunit_id, ibu.code invoicebusinessunitcode,
       ibu.description invoicebusinessunitdesc, sh.billtocustomernumber, sh.billtocustomername, sh.deltocustomernumber, sh.deltocustomername, sh.startweek,
       sh.endweek, sh.startmonth, sh.endmonth, sh.startyear, sh.endyear, sh.city, sh.county, sh.state, sh.zipcode, sh.street2, sh.street,
       sh.contactpersonname, sh.contactpersonphone, sh.emailstatus, sh.emailaddress, sh.realcollectiontype, sh.originalcollectiontype, sh.exported,
       sh.invoicecomments statementcomments, sh.prebillamount, sh.invoicefrequency_id statementfrequencynumber, cur.code currencycode,
       cur.description currencydesc, s.statustype, s.code statuscode, s.factorydescription statusfactorydescription, ihus.countytaxrate, ihus.citytaxrate,
       ihus.statestaxrate, p.code plantcode, p.name plantname, pad.street plantstreet, pad.street2 plantstreet2, pad.zipcode plantzipcode,
       pad.city plantcity, pad.state plantstate, pad.county plantcounty, sh.purchaseorder, sh.routenumber, sh.systemuser_id, sh.timestamp, sh.invoiceheader_id statementheader_id,
       f_getaragingamount(sh.billtocustomer_link_id, rp.number_value2, 0, getdateasvarcharfixedformat(rp.date_value1), getdateasvarcharfixedformat(rp.date_value2), getdateasvarcharfixedformat(rp.date_value3), getdateasvarcharfixedformat(rp.date_value4), null, sh.invoiceheader_id) days0,
       f_getaragingamount(sh.billtocustomer_link_id, rp.number_value2, 1, getdateasvarcharfixedformat(rp.date_value1), getdateasvarcharfixedformat(rp.date_value2), getdateasvarcharfixedformat(rp.date_value3), getdateasvarcharfixedformat(rp.date_value4), null, sh.invoiceheader_id) days30,
       f_getaragingamount(sh.billtocustomer_link_id, rp.number_value2, 2, getdateasvarcharfixedformat(rp.date_value1), getdateasvarcharfixedformat(rp.date_value2), getdateasvarcharfixedformat(rp.date_value3), getdateasvarcharfixedformat(rp.date_value4), null, sh.invoiceheader_id) days60,
       f_getaragingamount(sh.billtocustomer_link_id, rp.number_value2, 3, getdateasvarcharfixedformat(rp.date_value1), getdateasvarcharfixedformat(rp.date_value2), getdateasvarcharfixedformat(rp.date_value3), getdateasvarcharfixedformat(rp.date_value4), null, sh.invoiceheader_id) days90,
       f_getaragingamount(sh.billtocustomer_link_id, rp.number_value2, 4, getdateasvarcharfixedformat(rp.date_value1), getdateasvarcharfixedformat(rp.date_value2), getdateasvarcharfixedformat(rp.date_value3), getdateasvarcharfixedformat(rp.date_value4), null, sh.invoiceheader_id) days120,
       f_previousstatement(sh.invoicedate, sh.billtocustomernumber, sh.deltocustomernumber) previousbalance, ihe.formlayoutcode statementlayoutcode, ihe.paymenttermsdescription,
       (select ch.code
          from customer billto
          join chain ch on billto.chain_id = ch.chain_id
         where billto.customer_id = sh.billtocustomer_link_id) billto_chain,
       cast(fsget_cust_delivery_days(sh.billtocustomer_link_id) as varchar2(7)) custdeliveryscheme,
       rp.reportparam_id, rp.copy_number, p.phoneno plantphoneno,
       p.faxno plantfax, p.email plantemail, p.logo plantlogo,
       sh.netpaymentdays, sh.startdate, sh.enddate
  from reportparam rp
       join invoiceheader sh
            left join invoiceheaderus ihus on sh.invoiceheader_id = ihus.invoiceheader_id
            join invoiceheaderextrainfo ihe on sh.invoiceheader_id = ihe.invoiceheader_id
            join currency cur on sh.currency_id = cur.currency_id
            join status s on sh.status_id = s.status_id
            join businessunit ibu
                 join plant p
                      join address pad on p.address_id = pad.address_id
                 on ibu.plant_id = p.plant_id
            on sh.invoicebusinessunit_id = ibu.businessunit_id
       on rp.number_value = sh.invoicenumber and sh.documenttype = 2
 where rp.copy_number = 0
/

  CREATE OR REPLACE VIEW "V_STATEMENTLINE" ("INVOICEDATE", "STATEMENTNUMBER", "INVOICELINETYPE", "TRANSACTIONTYPE_ID", "TRANSACTIONTYPENUMBER", "TRANSACTIONTYPECODE", "TRANSACTIONREFERENCE", "TRANSACTIONDATE", "DEBITCREDIT", "AMOUNT", "PERCENTAGE", "SYSTEMUSER_ID", "TIMESTAMP", "STATEMENTLINE_ID", "STATEMENTHEADER_ID", "DELTOCUSTOMER_LINK_ID", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME") AS 
  select /*version 1.0*/
       sh.invoicedate, sh.invoicenumber statementnumber, ilt.type invoicelinetype,
       sl.transactiontype_id, art.typenumber transactiontypenumber, art.code transactiontypecode,
       sl.transactionreference, sl.transactiondate, sl.debitcredit, sl.amount, sl.percentage,
       sl.systemuser_id, sl.timestamp, sl.statementline_id, sl.invoiceheader_id statementheader_id,
       sl.deltocustomer_link_id, del.customernumber deltocustomernumber, del.name deltocustomername
  from statementline sl
       left join artransactiontype art on sl.transactiontype_id = art.artransactiontype_id
       left join customer del on sl.deltocustomer_link_id = del.customer_id
       join invoicelinetype ilt on sl.invoicelinetype_id = ilt.invoicelinetype_id
       join invoiceheader sh on sl.invoiceheader_id = sh.invoiceheader_id
 where sh.documenttype = 2
/

  CREATE OR REPLACE VIEW "V_STATES" ("CODE", "NAME", "TAXAUTHORITYCODE", "OLDTAXRATE", "NEWTAXRATE", "STARTDATETAXRATE", "COUNTRYCODE", "COUNTRYDESCRIPTION", "SPLITTAXONINVOICE", "TURNOVERGROUPCODE", "TURNOVERGROUPDESCRIPTION", "TIMESTAMP", "SYSTEMUSER_ID", "STATES_ID", "LANGUAGECODE") AS 
  select states.code, states.name, states.taxauthoritycode, statestaxrate.oldtaxrate, statestaxrate.newtaxrate,
 statestaxrate.startdatetaxrate, country.code countrycode, country.description countrydescription,
 states.splittaxoninvoice,
 turnovergroup.code turnovergroupcode,
 (SELECT description FROM turnovergroup_desc a WHERE a.turnovergroup_id = states.turnovergroup_id
  AND a.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) turnovergroupdescription,
 states.timestamp, states.systemuser_id, states.states_id, languages.code languagecode
from country, statestaxrate, languages, states
 left outer join turnovergroup on(turnovergroup.turnovergroup_id = states.turnovergroup_id)
where states.country_id = country.country_id
 and states.states_id = statestaxrate.states_id
/

  CREATE OR REPLACE VIEW "V_STATISTICSRAGGEDITEMS" ("LINETYPE", "BUSINESSUNIT_ID", "STAYNR", "WEAREREMPLOYMENT_LINK_ID", "LASTWEAREREMPLOYMENT_LINK_ID", "DISTRIBUTIONPOINT_LINK_ID", "LASTDISTRIBUTIONPOINT_LINK_ID", "REASONCODE", "REASONCODE_DESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "PRODUCTGROUP_CODE", "PRODUCT_CODE", "RAGREASON_CODE", "SUPPLIERNUMBER", "SUPPLIERNAME", "FABRIC_CODE", "PRODUCTGROUP_DESC", "PRODUCT_DESC", "RAGREASON_DESC", "RAGGEDITEM_ID", "DAYSINCIRCULATION", "DAYSINSTOCK", "WASHESTOTAL", "NUMBEROFISSUES", "REPAIRSTOTAL", "RAGDATE", "LANGUAGE_CODE", "SIZECODE", "SIZEDESC") AS 
  select /*version 2.1*/
       1 linetype, ri.businessunit_id, coalesce((select st.staynr from stay st where ri.prevstay_id=st.stay_id), 10) staynr,
       ri.weareremployment_link_id, ri.lastweareremployment_link_id, ri.distributionpoint_link_id, ri.lastdistributionpoint_link_id, rc.code reasoncode,
       (select rcd.description
          from reasoncode_desc rcd
         where rcd.reasoncode_id = ri.reasoncode_id
           and rcd.language_id = l.language_id) reasoncode_desc, cl.customernumber, cl.name customername, pg.code productgroup_code,
       p.code product_code, rr.code ragreason_code, su.suppliernumber, su.name suppliername, fa.code fabric_code,
       (select pgd.description
          from productgroup_desc pgd
         where pg.productgroup_id=pgd.productgroup_id
           and pgd.language_id=l.language_id) productgroup_desc,
       (select prd.description
          from product_desc prd
         where p.product_id=prd.product_id
           and prd.language_id=l.language_id) product_desc,
       (select rrd.description
          from ragreason_desc rrd
         where rrd.ragreason_id=rr.ragreason_id
           and rrd.language_id=l.language_id) ragreason_desc,
       ri.raggeditem_id, ri.daysincirculation, ri.daysinstock, ri.washestotal, ri.numberofissues, ri.repairstotal,
       ri.ragtimestamp ragdate, l.code language_code, sdl.code sizecode,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id=sdl.sizedefinition_link_id
           and sdd.language_id=l.language_id) sizedesc
  from raggeditem ri
       left join reasoncode rc on ri.reasoncode_id = rc.reasoncode_id
       join weareremployment_link wel
            join distributionpoint_link dpl
                 join department_link dl
                      join customer_link cl on dl.customer_link_id=cl.customer_link_id
                 on dpl.department_link_id=dl.department_link_id
            on wel.distributionpoint_link_id=dpl.distributionpoint_link_id
       on ri.weareremployment_link_id=wel.weareremployment_link_id
       join product p
            join productgroup pg on p.productgroup_id=pg.productgroup_id
            join fabric fa on p.fabric_id=fa.fabric_id
       on ri.product_link_id=p.product_id
       join supplier su on ri.supplier_id=su.supplier_id
       join ragreason rr on ri.ragreason_id=rr.ragreason_id
       join sizedefinition_link sdl on ri.sizedefinition_link_id=sdl.sizedefinition_link_id
       cross join languages l
union all
select 2 linetype, ri.businessunit_id, coalesce((select st.staynr from stay st where ri.prevstay_id=st.stay_id), 10) staynr,
       ri.weareremployment_link_id, ri.lastweareremployment_link_id, ri.distributionpoint_link_id,
       ri.lastdistributionpoint_link_id, rc.code reasoncode,
       (select rcd.description
          from reasoncode_desc rcd
         where rcd.reasoncode_id = ri.reasoncode_id
           and rcd.language_id = l.language_id) reasoncode_desc,
       cl2.customernumber, cl2.name customername, pg.code productgroup_code, p.code product_code, rr.code ragreason_code,
       su.suppliernumber, su.name suppliername, fa.code fabric_code,
       (select pgd.description
          from productgroup_desc pgd
         where pg.productgroup_id=pgd.productgroup_id
           and pgd.language_id=l.language_id) productgroup_desc,
       (select prd.description
          from product_desc prd
         where p.product_id=prd.product_id
           and prd.language_id=l.language_id) product_desc,
       (select rrd.description
          from ragreason_desc rrd
         where rrd.ragreason_id=rr.ragreason_id
           and rrd.language_id=l.language_id) ragreason_desc,
       ri.raggeditem_id, ri.daysincirculation, ri.daysinstock, ri.washestotal, ri.numberofissues, ri.repairstotal,
       ri.ragtimestamp ragdate, l.code language_code, sdl.code sizecode,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id=sdl.sizedefinition_link_id
           and sdd.language_id=l.language_id) sizedesc
  from raggeditem ri
       left join reasoncode rc on ri.reasoncode_id = rc.reasoncode_id
       join weareremployment_link wel2
            join distributionpoint_link dpl2
                 join department_link dl2
                      join customer_link cl2 on dl2.customer_link_id=cl2.customer_link_id
                 on dpl2.department_link_id=dl2.department_link_id
            on wel2.distributionpoint_link_id=dpl2.distributionpoint_link_id
       on ri.lastweareremployment_link_id=wel2.weareremployment_link_id
       join product p
            join productgroup pg on p.productgroup_id=pg.productgroup_id
            join fabric fa on p.fabric_id=fa.fabric_id
       on ri.product_link_id=p.product_id
       join supplier su on ri.supplier_id=su.supplier_id
       join ragreason rr on ri.ragreason_id=rr.ragreason_id
       join sizedefinition_link sdl on ri.sizedefinition_link_id=sdl.sizedefinition_link_id
       cross join languages l
 where ri.weareremployment_link_id is null
union all
select 3 linetype, ri.businessunit_id, coalesce((select st.staynr from stay st where ri.prevstay_id=st.stay_id), 10) staynr,
       ri.weareremployment_link_id, ri.lastweareremployment_link_id, ri.distributionpoint_link_id,
       ri.lastdistributionpoint_link_id, rc.code reasoncode,
       (select rcd.description
          from reasoncode_desc rcd
         where rcd.reasoncode_id = ri.reasoncode_id
           and rcd.language_id = l.language_id) reasoncode_desc,
       cl3.customernumber, cl3.name customername, pg.code productgroup_code, p.code product_code, rr.code ragreason_code,
       su.suppliernumber, su.name suppliername, fa.code fabric_code,
       (select pgd.description
          from productgroup_desc pgd
         where pg.productgroup_id=pgd.productgroup_id
           and pgd.language_id=l.language_id) productgroup_desc,
       (select prd.description
          from product_desc prd
         where p.product_id=prd.product_id
           and prd.language_id=l.language_id) product_desc,
       (select rrd.description
          from ragreason_desc rrd
         where rrd.ragreason_id=rr.ragreason_id
           and rrd.language_id=l.language_id) ragreason_desc, ri.raggeditem_id, ri.daysincirculation, ri.daysinstock,
       ri.washestotal, ri.numberofissues, ri.repairstotal, ri.ragtimestamp ragdate, l.code language_code, sdl.code sizecode,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id=sdl.sizedefinition_link_id
           and sdd.language_id=l.language_id) sizedesc
  from raggeditem ri
       left join reasoncode rc on ri.reasoncode_id = rc.reasoncode_id
       join distributionpoint_link dpl3
            join department_link dl3
                 join customer_link cl3 on dl3.customer_link_id=cl3.customer_link_id
            on dpl3.department_link_id=dl3.department_link_id
       on ri.distributionpoint_link_id=dpl3.distributionpoint_link_id
       join product p
            join productgroup pg on p.productgroup_id=pg.productgroup_id
            join fabric fa on p.fabric_id=fa.fabric_id
       on ri.product_link_id=p.product_id
       join supplier su on ri.supplier_id=su.supplier_id
       join ragreason rr on ri.ragreason_id=rr.ragreason_id
       join sizedefinition_link sdl on ri.sizedefinition_link_id=sdl.sizedefinition_link_id
       cross join languages l
 where ri.lastweareremployment_link_id is null
   and ri.weareremployment_link_id is null
union all
select 4 linetype, ri.businessunit_id, coalesce((select st.staynr from stay st where ri.prevstay_id=st.stay_id), 10) staynr,
       ri.weareremployment_link_id, ri.lastweareremployment_link_id, ri.distributionpoint_link_id,
       ri.lastdistributionpoint_link_id, rc.code reasoncode,
       (select rcd.description
          from reasoncode_desc rcd
         where rcd.reasoncode_id = ri.reasoncode_id
           and rcd.language_id = l.language_id) reasoncode_desc,
       cl4.customernumber, cl4.name customername, pg.code productgroup_code, p.code product_code,
       rr.code ragreason_code, su.suppliernumber, su.name suppliername, fa.code fabric_code,
       (select pgd.description
          from productgroup_desc pgd
         where pg.productgroup_id=pgd.productgroup_id
           and pgd.language_id=l.language_id) productgroup_desc,
       (select prd.description
          from product_desc prd
         where p.product_id=prd.product_id
           and prd.language_id=l.language_id) product_desc,
       (select rrd.description
          from ragreason_desc rrd
         where rrd.ragreason_id=rr.ragreason_id
           and rrd.language_id=l.language_id) ragreason_desc,
       ri.raggeditem_id, ri.daysincirculation, ri.daysinstock, ri.washestotal, ri.numberofissues, ri.repairstotal,
       ri.ragtimestamp ragdate, l.code language_code, sdl.code sizecode,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id=sdl.sizedefinition_link_id
           and sdd.language_id=l.language_id) sizedesc
  from raggeditem ri
       left join reasoncode rc on ri.reasoncode_id = rc.reasoncode_id
       join distributionpoint_link dpl4
            join department_link dl4
                 join customer_link cl4 on dl4.customer_link_id=cl4.customer_link_id
            on dpl4.department_link_id=dl4.department_link_id
       on ri.lastdistributionpoint_link_id=dpl4.distributionpoint_link_id
       join product p
            join productgroup pg on p.productgroup_id=pg.productgroup_id
            join fabric fa on p.fabric_id=fa.fabric_id
       on ri.product_link_id=p.product_id
       join supplier su on ri.supplier_id=su.supplier_id
       join ragreason rr on ri.ragreason_id=rr.ragreason_id
       join sizedefinition_link sdl on ri.sizedefinition_link_id=sdl.sizedefinition_link_id
       cross join languages l
 where ri.distributionpoint_link_id is null
   and ri.lastweareremployment_link_id is null
   and ri.weareremployment_link_id is null
union all
select 5 linetype, ri.businessunit_id, coalesce((select st.staynr from stay st where ri.prevstay_id=st.stay_id), 10) staynr,
       ri.weareremployment_link_id, ri.lastweareremployment_link_id, ri.distributionpoint_link_id,
       ri.lastdistributionpoint_link_id, rc.code reasoncode,
       (select rcd.description
          from reasoncode_desc rcd
         where rcd.reasoncode_id = ri.reasoncode_id
           and rcd.language_id = l.language_id) reasoncode_desc,
       coalesce((select c.customernumber
                   from customer c
                  where c.customer_id = ri.relatedcustomerlink_id), 0) customernumber,
       coalesce((select c.name
                   from customer c
                  where c.customer_id = ri.relatedcustomerlink_id), ' ') customername,
       pg.code productgroup_code, p.code product_code, rr.code ragreason_code, su.suppliernumber, su.name suppliername, fa.code fabric_code,
       (select pgd.description
          from productgroup_desc pgd
         where pg.productgroup_id=pgd.productgroup_id
           and pgd.language_id=l.language_id) productgroup_desc,
       (select prd.description
          from product_desc prd
         where p.product_id=prd.product_id
           and prd.language_id=l.language_id) product_desc,
       (select rrd.description
          from ragreason_desc rrd
         where rrd.ragreason_id=rr.ragreason_id and rrd.language_id=l.language_id) ragreason_desc,
       ri.raggeditem_id, ri.daysincirculation, ri.daysinstock, ri.washestotal, ri.numberofissues, ri.repairstotal,
       ri.ragtimestamp ragdate, l.code language_code, sdl.code sizecode,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id=sdl.sizedefinition_link_id
           and sdd.language_id=l.language_id) sizedesc
  from raggeditem ri
       left join reasoncode rc on ri.reasoncode_id = rc.reasoncode_id
       join product p
            join productgroup pg on p.productgroup_id=pg.productgroup_id
            join fabric fa on p.fabric_id=fa.fabric_id
       on ri.product_link_id=p.product_id
       join ragreason rr on ri.ragreason_id=rr.ragreason_id
       join supplier su on ri.supplier_id=su.supplier_id
       join sizedefinition_link sdl on ri.sizedefinition_link_id=sdl.sizedefinition_link_id
       cross join languages l
 where ri.lastdistributionpoint_link_id is null
   and ri.distributionpoint_link_id is null
   and ri.lastweareremployment_link_id is null
   and ri.weareremployment_link_id is null
/

  CREATE OR REPLACE VIEW "V_STATUS" ("STATUSTYPE", "STATUSCODE", "STATUS_DESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP", "STATUS_ID", "LANGUAGECODE") AS 
  SELECT STATUS.STATUSTYPE, STATUS.CODE STATUSCODE,
(SELECT DESCRIPTION FROM STATUS_DESC A WHERE A.STATUS_ID = STATUS.STATUS_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID )STATUS_DESCRIPTION,
STATUS.SYSTEMUSER_ID, STATUS.TIMESTAMP, STATUS.STATUS_ID, LANGUAGES.CODE LANGUAGECODE
       FROM STATUS, LANGUAGES
/

  CREATE OR REPLACE VIEW "V_STATUSQUOMATSINCIRC" ("YEARWEEK", "YEAR", "WEEK", "CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "PRODUCTCODE", "SIZECODE", "FINMETHODCODE", "PRODUCTDESC", "FINMETHODDESC", "QTYRENTED", "QTYFREESEASON", "QTYFREERENTSTOP", "QTYFREE", "VARIATIONQTYRENTED", "VARIATIONQTYFREESEASON", "VARIATIONQTYRENTSTOP", "VARIATIONFREE", "LANGUAGECODE", "INVOICEBUSINESSUNIT_ID", "DEFAULTBUSINESSUNIT_ID", "MIN_ACTIVITY_ID", "ACTIVITYBUSINESSUNIT_ID") AS 
  select
  sh.year*100 + sh.week yearweek, sh.year, sh.week
, cu.customernumber, cu.name customername
, ( select adr.city from address adr where cu.visitaddress_id = adr.address_id ) city
, delk.departmentnumber, delk.description departmentdesc
, dilk.distributionpointnumber, dilk.description distributionpointDesc
, prdlk.code productcode, szlk.code sizecode, fmlk.code finmethodcode
, ( select pd.description from product_link_DESC pd where pd.product_link_id = prdlk.product_link_id
  and pd.language_id = languages.language_id ) productdesc
, ( select fmlkd.description from  finishingmethod_DESC fmlkd where fmlkd.finishingmethod_id = fmlk.finishingmethod_id
  and fmlkd.language_id = languages.language_id ) finmethoddesc
, sqm.qtyrented, sqm.qtyfreeseason, sqm.qtyrentstop qtyfreerentstop
, sqm.qtyfreeseason + sqm.qtyrentstop qtyfree
, sqm.variationqtyrented, sqm.variationqtyfreeseason, sqm.variationqtyrentstop
, sqm.variationqtyfreeseason + sqm.variationqtyrentstop variationfree
, languages.code languagecode
, sh.invoicebusinessunit_id, cu.defaultbusinessunit_id
, (select min(caa.activity_id) from customeractivities caa where caa.customer_id=cu.customer_id and caa.invoicebusinessunit_id = abu.businessunit_id) min_ACTIVITY_ID
, abu.businessunit_id ACTIVITYBUSINESSUNIT_ID
from
  statusquoheader sh, sqmatincirculation sqm
, customer_link culk
    left outer join customer cu on (culk.customer_id = cu.customer_id)
, department_link delk, distributionpoint_link dilk
, product_link prdlk, sizedefinition_link szlk, finishingmethod fmlk
, languages
, businessunit abu
where
    sh.statusquoheader_id = sqm.statusquoheader_id
and sqm.customer_link_id = culk.customer_link_id
    and sqm.department_link_id = delk.department_link_id
        and sqm.distributionpoint_link_id = dilk.distributionpoint_link_id
and sqm.product_link_id = prdlk.product_link_id
    and sqm.sizedefinition_link_id = szlk.sizedefinition_link_id
        and sqm.finishingmethod_id = fmlk.finishingmethod_id
and sh.subtype in (0, 2)
/

  CREATE OR REPLACE VIEW "V_STATUSQUOSETSINCIRC" ("YEARWEEK", "YEAR", "WEEK", "CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "WEARERNUMBER", "WEARERNAME", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "SIZEDESC", "FINMETHODCODE", "FINMETHODDESC", "QTOTALINCIRC", "QFREEINCIRC", "QWEARERRENTSTOP", "QCUSTOMERRENTSTOP", "VTOTALINCIRC", "VFREEINCIRC", "VWEARERRENTSTOP", "VCUSTOMERRENTSTOP", "CHANGESPERWEEK", "LANGUAGECODE", "INVOICEBUSINESSUNIT_ID", "DEFAULTBUSINESSUNIT_ID", "MIN_ACTIVITY_ID", "ACTIVITYBUSINESSUNIT_ID") AS 
  select
  a.year*100 + a.week yearweek, a.year, a.week, d.customernumber, d.name customername,
  (select adr.city from address adr where d.visitaddress_id = adr.address_id) city,
  e.departmentnumber, e.description departmentdesc
, weylk.wearernumber, weylk.wearername
, g.code productcode,
  (SELECT pd.description FROM product_link_DESC pd WHERE pd.product_link_id = g.product_link_id
    AND pd.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
  i.code sizecode,
  (SELECT sdd.description FROM sizedefinition_desc sdd WHERE sdd.sizedefinition_id = i.sizedefinition_link_id
    AND sdd.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) sizedesc,
  k.code finmethodcode,
  (SELECT kd.description FROM finishingmethod_DESC kd WHERE kd.finishingmethod_id = k.finishingmethod_id
    AND kd.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finmethoddesc,
--  b.totalcircinv qtotalincirc, b.freecircinv qfreeincirc,
  b.numberemploymentscharge qtotalincirc, b.numberemploymentsfree qfreeincirc,
  b.numberemploymentsrentstop qwearerrentstop, b.numberemplcustrentstop qcustomerrentstop,
--  b.variationtotalcircinv vtotalincirc, b.variationfreecircinv vfreeincirc,
  b.variationemploymentscharge vtotalincirc, b.variationemploymentsfree vfreeincirc,
  b.variationemploymentsrentstop vwearerrentstop, b.variationemplcustrentstop vcustomerrentstop,
  b.changesperweek changesperweek,
  languages.code languagecode
, a.invoicebusinessunit_id, d.defaultbusinessunit_id
, (select min(caa.activity_id) from customeractivities caa where caa.customer_id=d.customer_id and caa.invoicebusinessunit_id = abu.businessunit_id) min_ACTIVITY_ID
, abu.businessunit_id ACTIVITYBUSINESSUNIT_ID
from statusquoheader a,  sqsetincirculation b
     left outer join weareremployment_link weylk on weylk.weareremployment_link_id = b.weareremployment_link_id,
  customer_link c
    left outer join customer d on (c.customer_id = d.customer_id),
  department_link e
, product_link g,  sizedefinition_link i, finishingmethod k
, languages
, businessunit abu
where
      a.statusquoheader_id = b.statusquoheader_id
  and b.customer_link_id = c.customer_link_id
  and b.department_link_id = e.department_link_id
  and b.product_link_id = g.product_link_id
  and b.sizedefinition_link_id = i.sizedefinition_link_id
  and b.finishingmethod_id = k.finishingmethod_id
  and a.statusquotype = 2
/

  CREATE OR REPLACE VIEW "V_STERILIZATION" ("CARTID", "CARTNUMBER", "CHR_CARTNR", "PRIMARYID", "PRODUCTCODE", "STERILIZATIONRUN_ID", "STERILIZERCODE", "STERILIZERDESC", "TREATMENTTYPE_ID", "TREATMENT_CODE", "EMPLOYEENUMBER", "EMPLOYEENAME", "CHARGENUMBER", "TIMESTAMP", "SR_TIMESTAMP", "REJECTREASONCODE_ID", "BUSINESSUNIT_ID", "BUCODE", "BUDESC", "LANGUAGECODE", "PRIMARYID_CHR", "CARTDESC", "PRODUCTDESC", "TREATMENT_DESC", "REJECTREASONCODE", "REJECTRC_DESC") AS 
  select /*version 3.0*/
       cuid.primaryid cartid, crt.cartnumber, to_char(crt.cartnumber) chr_cartnr,  ui.primaryid, pr.code productcode,
       ups.sterilizationrun_id, st.code sterilizercode, st.description sterilizerdesc, tt.treatmenttype_id, tt.code treatment_code,
       em.employeenumber, em.name employeename, sr.chargenumber, sr.timestamp, to_char(sr.timestamp, 'DD/MM/YYYY HH:MI:SS AM') sr_timestamp,
       sr.rejectreasoncode_id, sr.businessunit_id, bu.code bucode, bu.description budesc, lan.code languagecode,
       f_getidforsterilizationrun(ups.sterilizationrun_id, crt.cart_id, pr.product_id) primaryid_chr,
       (select ctd.description
          from carttype ct
               join carttype_desc ctd on ct.carttype_id = ctd.carttype_id
         where crt.carttype_id = ct.carttype_id
           and ctd.language_id = lan.language_id) cartdesc,
       (select pd.description
          from product_desc pd
         where pd.product_id = pr.product_id
           and pd.language_id = lan.language_id) productdesc,
       (select tt_d.description
          from treatmenttype_desc tt_d
         where tt.treatmenttype_id = tt_d.treatmenttype_id
           and tt_d.language_id = lan.language_id) treatment_desc,
       (select rc.code
          from reasoncode rc
         where sr.rejectreasoncode_id = rc.reasoncode_id) rejectreasoncode,
       (select rcd.description
          from reasoncode rc
               join reasoncode_desc rcd on rc.reasoncode_id = rcd.reasoncode_id
         where sr.rejectreasoncode_id = rc.reasoncode_id
           and rcd.language_id = lan.language_id) rejectrc_desc
  from uniqueitem ui
       join product pr on ui.product_id = pr.product_id
       join uniqueorpacksterile ups
            join sterilizationrun sr
                 join sterilizer st on sr.sterilizer_id = st.sterilizer_id
                 join treatmenttype tt on sr.treatmenttype_id = tt.treatmenttype_id
                 join employee em on sr.employee_id = em.employee_id
                 join businessunit bu on sr.businessunit_id = bu.businessunit_id
            on ups.sterilizationrun_id = sr.sterilizationrun_id
            join cart crt
                 left join cartuniqueid cuid on crt.cart_id = cuid.cart_id
            on ups.cart_id = crt.cart_id
       on ui.uniqueitem_id = ups.uniqueitem_id
       cross join languages lan
/

  CREATE OR REPLACE VIEW "V_STERILIZATIONRUN_PACKS" ("UNIQUEITEM_ID", "UNIQUEITEM_BUSINESSUNIT_ID", "PRIMARYID", "PRODUCT_ID", "SIZEDEFINITION_ID", "FINISHINGMETHOD_ID", "STATUS_ID", "STAY_ID", "TREATMENTTYPE_ID", "EXPIRATIONDATE", "STOCKEXPIRATIONDATE", "CART_ID", "DELIVERYTIMESTAMP", "DELIVERYEMPLOYEE_ID", "DISTRIBUTIONPOINT_ID", "CUSTOMER_ID", "PACKINGNOTE_ID", "DELIVERYSCAN_BUSINESSUNIT_ID", "CANCELTIMESTAMP", "CANCELEMPLOYEE_ID", "CANCELREASONCODE_ID", "LASTDISTRIBUTIONPOINT_LINK_ID", "STERILIZATIONRUN_ID", "DEPARTMENTNUMBER", "DESCRIPTION", "CHARGENUMBER", "ASSEMBLEEMPLOYEE_ID", "LOADEMPLOYEE_ID", "RECALLEMPLOYEE_ID", "LABELLAYOUT_ID", "STERILIZATIONEMPLOYEE_ID", "STERILIZATIONTIMESTAMP", "CREATIONEMPLOYEE_ID", "RECALLTIMESTAMP", "LOADTIMESTAMP", "ASSEMBLETIMESTAMP", "CREATIONTIMESTAMP", "STERILIZER_ID", "RECALLREASONCODE_ID", "REJECTREASONCODE_ID", "PLANTDEPARTMENT_ID") AS 
  select uorp.uniqueitem_id,
       ui.businessunit_id uniqueitem_businessunit_id,
       ui.primaryid,
       ui.product_id,
       ui.sizedefinition_id,
       ui.finishingmethod_id,
       ui.status_id,
       ui.stay_id,
       uorp.treatmenttype_id,
       ui.expirationdate,
       uorp.stockexpirationdate,
       uorps.cart_id,
       uorp.deliverytimestamp,
       uorp.deliveryemployee_id,
       ui.distributionpoint_id,
       case nvl(ui.distributionpoint_id,0) when 0 then null
       --else d.customer_id
       else (select d.customer_id from department d, distributionpoint dp where d.department_id=dp.department_id and ui.distributionpoint_id=dp.distributionpoint_id)
       end customer_id, --customer
       ds.packingnote_id,
       ds.businessunit_id deliveryscan_businessunit_id,
       uorp.canceltimestamp,
       uorp.cancelemployee_id,
       case nvl(uorp.canceltimestamp, to_date('31-12-2099', 'dd-mm-yyyy')) when to_date('31-12-2099', 'dd-mm-yyyy') then null
       else uorp.reasoncode_id
       end cancelreasoncode_id, --cancelreasoncode_id
       ui.lastdistributionpoint_link_id,
       sr.sterilizationrun_id,
       (select d.departmentnumber from department d, distributionpoint dp where d.department_id=dp.department_id and ui.distributionpoint_id=dp.distributionpoint_id ) departmentnumber,
       (select d.description from department d, distributionpoint dp where d.department_id=dp.department_id and ui.distributionpoint_id=dp.distributionpoint_id ) description,
       --d.departmentnumber,
       --d.description,
       sr.chargenumber,
       uorp.assembleemployee_id,
       uorp.loademployee_id,
       uorp.recallemployee_id,
       uorp.labellayout_id,
       uorps.sterilizationemployee_id,
       uorps.sterilizationtimestamp,
       uorp.creationemployee_id,
       uorp.recalltimestamp,
       uorp.loadtimestamp,
       uorp.assembletimestamp,
       uorp.creationtimestamp,
       sr.sterilizer_id,
       case nvl(uorp.recalltimestamp, to_date('31-12-2099', 'dd-mm-yyyy')) when to_date('31-12-2099', 'dd-mm-yyyy') then null
       else uorp.reasoncode_id
       end recallreasoncode_id,
       sr.rejectreasoncode_id,
       ( select pn.plantdepartment_id from deliveryscan ds, packingnote pn where uorp.uniqueitem_id=ds.uniqueitem_link_id
       and ds.packingnote_id=pn.packingnote_id)plantdepartment_id
from uniqueorpack uorp
--left outer join uniqueorpackcart uorpc on uorp.uniqueitem_id = uorpc.uniqueitem_id
left outer join deliveryscan ds on uorp.uniqueitem_id = ds.uniqueitem_link_id
join (uniqueorpacksterile uorps
 join sterilizationrun sr on uorps.sterilizationrun_id = sr.sterilizationrun_id)
on uorp.uniqueitem_id = uorps.uniqueitem_id,
uniqueitem ui
 --left outer join (distributionpoint dp
  --join department d on dp.department_id = d.department_id) on ui.distributionpoint_id = dp.distributionpoint_id
where
uorp.uniqueitem_id = ui.uniqueitem_id
/

  CREATE OR REPLACE VIEW "V_STERILIZATION_CHR" ("CHARACTERISTIC_CODE", "TS_VALUE", "TSC_NUMBERVALUE", "TSC_STRINGVALUE", "TSC_DATEVALUE", "TSC_DV_STRING", "TREATMENT_NOTES", "TREATMENTTYPE_ID", "STERILIZATIONRUN_ID") AS 
  select c.code characteristic_code,
       coalesce(to_char(tsc.numbervalue), tsc.stringvalue, to_char(tsc.datevalue, 'DD/MM/YYYY HH:MI:SS AM'), ts.notes) ts_value,
       tsc.numbervalue tsc_numbervalue,
       tsc.stringvalue tsc_stringvalue,
       tsc.datevalue tsc_datevalue,
       to_char(tsc.datevalue, 'DD/MM/YYYY HH:MI:SS AM') tsc_dv_string,
       ts.notes treatment_notes,
       ts.treatmenttype_id,
       sr.sterilizationrun_id
from treatmentscan ts, treatmentscancharacteristic tsc, characteristic c, scan sc
     , sterilizationrun sr
where tsc.treatmentscan_id = ts.treatmentscan_id
      and tsc.characteristic_id = c.characteristic_id
      and sr.treatmenttype_id = ts.treatmenttype_id
      and sc.batchnumber = sr.chargenumber
      and sc.treatmenttype_id = ts.treatmenttype_id
      and ts.scan_id = sc.scan_id
group by
       c.code,
       tsc.numbervalue,
       tsc.stringvalue,
       tsc.datevalue,
       to_char(tsc.datevalue, 'DD/MM/YYYY HH:MI:SS AM'),
       ts.notes,
       ts.treatmenttype_id,
			 sr.sterilizationrun_id
/

  CREATE OR REPLACE VIEW "V_STOCKCORRECTION" ("STOCKCODE", "STOCKNAME", "MANAGEDBYBU_ID", "ROWCODE", "LOCATIONCODE", "CYCLECOUNTGROUP", "PICKINGSEQUENCE", "CUSTOMEROWNED", "PRODUCTCODE", "SIZECODE", "SEQUENCENUMBER", "PRODGRCODE", "QUALITYGRADECODE", "PRIORITY", "QTYCOUNTED", "QTYSTOCKDIFF", "QTYSTOCK", "LANGUAGECODE", "DATECOUNTED", "SKQTIMESTAMP", "SKRESGTIMESTAMP", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMERRELATED", "PRODUCTDESC", "PRODUCTLONGDESC", "SIZEDESC", "QUALITYGRADEDESC", "MULTIPLELOCATIONS", "PRICE") AS 
  select /*version 2.1*/
       sk.code stockcode, sk.name stockname, sk.managedbybu_id, skl.rowcode, skl.locationcode, skl.cyclecountgroup, skl.pickingsequence,
       ski.customerowned, prd.code productcode, sz.code sizecode, ps.sequencenumber, pg.code prodgrcode, qg.code qualitygradecode, qg.priority, skq.qtycounted,
       skq.stockdifference qtystockdiff, ( skq.qtyunique + skq.qtyuniquewithmodifications + skq.qtynonunique) qtystock, lan.code languagecode,
       skq.datecounted,  trunc(skq.timestamp) skqtimestamp, trunc(skresg.timestamp) skresgtimestamp, cu.customernumber, cu.name customername,
       case when ski.customer_id is null then 0
            else 1
        end customerrelated,
       (select pds.description
          from product_desc pds
         where pds.product_id = prd.product_id
           and pds.language_id = lan.language_id ) productdesc,
       (select pdss.longdescription
          from product_desc pdss
         where pdss.product_id = prd.product_id
           and pdss.language_id = lan.language_id ) productlongdesc,
       (select szds.description
          from sizedefinition_desc szds
         where szds.sizedefinition_id = sz.sizedefinition_id
           and szds.language_id = lan.language_id ) sizedesc,
       (select qds.description
          from qualitygrade_desc qds
         where qds.qualitygrade_id = qg.qualitygrade_id
           and qds.language_id = lan.language_id ) qualitygradedesc,
       coalesce(( select count(sqt.stockroomlocation_id)
                    from stockquantity sqt
                   where sqt.stockreservationpergrade_id = skresg.stockreservationpergrade_id), 0) multiplelocations,
       f_purchaseprice(ski.defaultsupplier_id, prd.product_id, sz.sizedefinition_id, trunc(sysdate)) price
  from stockroom sk
       join stockroomlocation skl on sk.stockroom_id = skl.stockroom_id
       join stockdefinitionperitem ski
            left join customer cu on ski.customer_id = cu.customer_id
            join stockreservationpergrade skresg
                 join qualitygrade qg on skresg.qualitygrade_id = qg.qualitygrade_id
            on ski.stockdefinitionperitem_id = skresg.stockdefinitionperitem_id
            join product prd on ski.product_id = prd.product_id
            join sizedefinition sz on ski.sizedefinition_id = sz.sizedefinition_id
            join productsize ps on prd.product_id = ps.product_id and ps.sizedefinition_id = sz.sizedefinition_id
            join productgroup pg on prd.productgroup_id=pg.productgroup_id
       on sk.stockroom_id = ski.stockroom_id
       join stockquantity skq on skresg.stockreservationpergrade_id = skq.stockreservationpergrade_id and skl.stockroomlocation_id = skq.stockroomlocation_id
       , languages lan
/

  CREATE OR REPLACE VIEW "V_STOCKCOUNTCUSTPERDATE" ("CUSTOMERNUMBER", "ORDERDATE") AS 
  select  c.customernumber, io.orderdate
from internetorder io
INNER JOIN distributionpoint DP ON  dp.distributionpoint_id = io.distributionpoint_link_id
INNER JOIN DEPARTMENT DEP ON DP.DEPARTMENT_ID = DEP.DEPARTMENT_ID
INNER JOIN CUSTOMER C ON C.CUSTOMER_ID = DEP.CUSTOMER_ID
/

  CREATE OR REPLACE VIEW "V_STOCKCOUNTSCHEDULEDEPT" ("CUSTOMERNUMBER", "CUSTOMERNAME", "STOCKCOUNTSCHEDULECODE", "STOCKCOUNTSCHEDULEDESCRIPTION", "COUNTSEQUENCE", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, STOCKCOUNTSCHEDULE.CODE,
STOCKCOUNTSCHEDULE.DESCRIPTION, STOCKCOUNTSCHEDULEDEPT.COUNTSEQUENCE,
 DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION, STOCKCOUNTSCHEDULE.SYSTEMUSER_ID, STOCKCOUNTSCHEDULEDEPT.TIMESTAMP
       FROM CUSTOMER, STOCKCOUNTSCHEDULE, DEPARTMENT, STOCKCOUNTSCHEDULEDEPT
       WHERE STOCKCOUNTSCHEDULEDEPT.STOCKCOUNTSCHEDULE_ID = STOCKCOUNTSCHEDULE.STOCKCOUNTSCHEDULE_ID
and STOCKCOUNTSCHEDULEDEPT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
and DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
UNION
SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, STOCKCOUNTSCHEDULE.CODE,
STOCKCOUNTSCHEDULE.DESCRIPTION, STOCKCOUNTSCHEDULEDIST.COUNTSEQUENCE,
 DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION, STOCKCOUNTSCHEDULE.SYSTEMUSER_ID, STOCKCOUNTSCHEDULEDIST.TIMESTAMP
       FROM CUSTOMER, STOCKCOUNTSCHEDULE, DEPARTMENT, STOCKCOUNTSCHEDULEDIST, DISTRIBUTIONPOINT
       WHERE STOCKCOUNTSCHEDULEDIST.STOCKCOUNTSCHEDULE_ID = STOCKCOUNTSCHEDULE.STOCKCOUNTSCHEDULE_ID
and STOCKCOUNTSCHEDULEDIST.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
AND DISTRIBUTIONPOINT.DEPARTMENT_ID= DEPARTMENT.DEPARTMENT_ID
and DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
/

  CREATE OR REPLACE VIEW "V_STOCKINVENTORY" ("STOCKROOMCODE", "STOCKROOMNAME", "BUSINESSUNITCODE", "BUSINESSUNITDESC", "EMPLOYEENUMBER", "EMPLOYEENAME", "CUSTOMEROWNED", "CUSTOMERNUMBER", "PRODUCTCODE", "PRODUCTGROUPCODE", "PRODUCTDESCRIPTION", "COLORCODE", "FABRICODE", "SUPPLIERNUMBER", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESCRIPTION", "GRADE1", "GRADE2", "GRADE3", "PRIORITY", "SEQUENCENUMBER", "QTYSTOCK", "LANGUAGECODE", "REPORTPARAM_ID", "CIRCINV", "STATUSQUODATE") AS 
  select st.code stockroomcode, st.name stockroomname, bu.code businessunitcode, bu.description businessunitdesc,
       emp.employeenumber, emp.name employeename, sdi.customerowned, cu.customernumber, prd.code productcode,
       pg.code productgroupcode,
       (select prde.description
          from product_desc prde
         where prde.product_id = prd.product_id
           and prde.language_id = lan.language_id) productdescription,
       col.code colorcode, fab.code fabricode, sup.suppliernumber, szd.code sizedefinitioncode,
       (select szde.description
           from sizedefinition_desc szde
          where szde.sizedefinition_id = szd.sizedefinition_id
            and szde.language_id = lan.language_id) sizedefinitiondescription,
       coalesce((select qgd.description
                   from qualitygrade_desc qgd
                  where qgd.qualitygrade_id = qg.qualitygrade_id
                    and qgd.language_id = lan.language_id
                    and qg.priority = 2), (select qg2.code from qualitygrade qg2 where qg2.priority = 2)) grade1,
       coalesce((select qgd.description
                   from qualitygrade_desc qgd
                  where qgd.qualitygrade_id = qg.qualitygrade_id
                    and qgd.language_id = lan.language_id
                    and qg.priority = 3), (select qg3.code from qualitygrade qg3 where qg3.priority = 3)) grade2,
       coalesce((select qgd.description
                   from qualitygrade_desc qgd
                  where qgd.qualitygrade_id = qg.qualitygrade_id
                    and qgd.language_id = lan.language_id
                    and qg.priority = 4), (select qg4.code from qualitygrade qg4 where qg4.priority = 4)) grade3,
       qg.priority, psz.sequencenumber,
       coalesce((select sum(sq.qtynonunique + sq.qtyunique + sq.qtyuniquewithmodifications)
                   from stockquantity sq
                  where sq.stockreservationpergrade_id = srg.stockreservationpergrade_id), 0) qtystock,
       lan.code languagecode, rp.reportparam_id,
       coalesce((select sum(sqin.totalcircinv)
           from statusquoheader sqh, sqitemincirculation sqin
          where sqh.statusquotype = 1
            and sqh.statusquoheader_id = sqin.statusquoheader_id
            and sqin.totalcircinv <> 0
            and sqh.processbusinessunit_id = bu.businessunit_id
            and sqin.product_link_id = prd.product_id
            and sqin.sizedefinition_link_id = szd.sizedefinition_id
            and sqh.statusquodate = x.MaxSQdate), 0) circinv,
       x.MaxSQdate statusquodate
  from reportparam rp
  join languages lan on rp.string_value = lan.code
  join stockroom st on rp.string_value7 = st.code
  join stockdefinitionperitem sdi on st.stockroom_id = sdi.stockroom_id
  left outer join customer cu on sdi.customer_id = cu.customer_id
  join stockreservationpergrade srg on sdi.stockdefinitionperitem_id = srg.stockdefinitionperitem_id
  join qualitygrade qg on srg.qualitygrade_id = qg.qualitygrade_id
  join employee emp on st.responsibleemployee_id = emp.employee_id
  join businessunit bu on st.managedbybu_id = bu.businessunit_id
  join (select sqh2.processbusinessunit_id, max(sqh2.statusquodate) MaxSQdate
          from statusquoheader sqh2 where sqh2.statusquotype = 1
      group by sqh2.processbusinessunit_id) X on x.processbusinessunit_id = bu.businessunit_id
  join product prd on sdi.product_id = prd.product_id
  join productgroup pg on prd.productgroup_id = pg.productgroup_id
  join sizedefinition szd on sdi.sizedefinition_id = szd.sizedefinition_id
  join productsize psz on sdi.product_id = psz.product_id
                      and sdi.sizedefinition_id = psz.sizedefinition_id
  join color col on prd.color_id = col.color_id
  join fabric fab on prd.fabric_id = fab.fabric_id
  join supplier sup on prd.supplier_id = sup.supplier_id
 where sup.suppliernumber >= rp.number_value1
   and sup.suppliernumber <= rp.number_value2
   and prd.code >= rp.string_value1
   and prd.code <= rp.string_value2
   and szd.code >= rp.string_value3
   and szd.code <= rp.string_value4
   and fab.code >= rp.string_value5
   and fab.code <= rp.string_value6
   and ((rp.number_value = 1 and sdi.customerowned = 'N' and cu.customernumber is null) or
        (rp.number_value = 2 and sdi.customerowned = 'N' and cu.customernumber >= rp.number_value3 and cu.customernumber <= rp.number_value4) or
        (rp.number_value = 3 and sdi.customerowned = 'Y' and cu.customernumber >= rp.number_value3 and cu.customernumber <= rp.number_value4)
       )
/

  CREATE OR REPLACE VIEW "V_STOCKINVENTORY_AUX" ("BUSINESSUNITCODE", "STOCKROOMCODE", "STATUSQUODATE", "CIRCINV", "PRODUCTCODE", "SIZEDEFINITIONCODE") AS 
  select (select bu.code from businessunit bu where bu.businessunit_id = sqh.processbusinessunit_id) businessunitcode,
       stockroom.code stockroomcode, sqh.statusquodate, sum(sqin.totalcircinv) circinv,
       (select prd.code from product prd where sqin.product_link_id = prd.product_id) productcode,
       (select sizdef.code
         from   sizedefinition sizdef
         where  sqin.sizedefinition_link_id = sizdef.sizedefinition_id) sizedefinitioncode
from   stockroom, statusquoheader sqh, sqitemincirculation sqin
where  stockroom.managedbybu_id = sqh.processbusinessunit_id
and    sqh.statusquodate =
       (select max(statusquoheader.statusquodate)
         from   statusquoheader
         where  statusquoheader.processbusinessunit_id = sqh.processbusinessunit_id
         and    statusquoheader.statusquotype = 1)
and    sqh.statusquotype = 1
and    sqh.statusquoheader_id = sqin.statusquoheader_id
and    sqin.totalcircinv <> 0
group  by sqh.processbusinessunit_id, stockroom.code, sqh.statusquodate, sqin.product_link_id,
          sqin.sizedefinition_link_id
/

  CREATE OR REPLACE VIEW "V_STOCKMOVEMENTS" ("STOCKROOM_ID", "STOCKROOM_CODE", "STOCKROOM_NAME", "STOCKTRANSACTION_ID", "TRANSACTIONDATE", "TRANSACTIONTYPE_ID", "QUANTITY", "QTYNONUNIQUE", "PROD_CODE", "SIZE_CODE", "QUALITYGRADE_CODE", "QUALITYGRADE_PRIORITY", "PROD_DESC", "SIZE_DESC", "LAN_CODE", "TOTAL_STOCK", "TRANSACTIONTYPE_DESC") AS 
  select sr.stockroom_id, sr.code Stockroom_code, sr.name StockRoom_name
, st.stocktransaction_id, st.transactiondate, st.transactiontype_id
, st.quantity, srg.qtynonunique--, sq.qtyunique, sq.qtyuniquewithmodifications
, p.code Prod_code, sd.code Size_code, qg.code QualityGrade_code, qg.priority QualityGrade_priority
, (select pd.description from product_desc pd where p.product_id = pd.product_id and languages.language_id = pd.language_id ) Prod_desc
, (select sdd.description from sizedefinition_desc sdd where sd.sizedefinition_id = sdd.sizedefinition_id and languages.language_id = sdd.language_id) Size_desc
, languages.code Lan_code
, GET_TOTALSTOCK_QUANTITY(p.product_id, sd.sizedefinition_id, sr.stockroom_id) Total_stock
, (select ttd.description from transactiontype_desc ttd where st.transactiontype_id = ttd.transactiontype_id and ttd.language_id = languages.language_id ) transactiontype_desc
from stocktransaction ST,
stockreservationpergrade SRG, stockdefinitionperitem SDI,
--Stockquantity SQ,
product P, sizedefinition SD, qualitygrade QG, stockroom sr,
languages
where st.stockreservationpergrade_id = srg.stockreservationpergrade_id and srg.stockdefinitionperitem_id = sdi.stockdefinitionperitem_id
and sdi.product_id = p.product_id and sdi.sizedefinition_id = sd.sizedefinition_id and srg.qualitygrade_id = qg.qualitygrade_id
and sdi.stockroom_id = sr.stockroom_id
and st.transactiontype_id in (10, 12, 15, 16, 22, 23, 32, 33, 40, 41, 44, 84, 50, 93)
--and srg.stockreservationpergrade_id = sq.stockreservationpergrade_id
-- StockMovements.rpt
/

  CREATE OR REPLACE VIEW "V_STOCKQUANTITY" ("LANGUAGECODE", "STOCKROOMCODE", "CUSTOMEROWNED", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMERCITY", "CUSTOMERSTREET", "CUSTOMERZIPCODE", "PRODUCTCODE", "SIZEDEFINITIONCODE", "PRODUCTDESCRIPTION", "QUALITYGRADECODE", "PRIORITY", "NEWGARMENT", "DEFECTITEM", "QTYUNIQUE_ACTUAL", "QTYNONUNIQUE_ACTUAL", "QTYUNIQUE_BLOCKED", "QTYNONUNIQUE_BLOCKED", "QTYUNIQUERESERVED", "QTYNONUNIQUERESERVED", "QTYUNIQUEWIITHMODIFRESERVED", "QTYUNIQUEORDERED", "QTYNONUNIQUEORDERED", "QTYUNIQUEORDEREDDIRECTISSUE", "QTYNONUNIQUEORDEREDDIRECTISSUE", "MINQTYNEW", "MINQTYUSED", "MAXQTYNEW", "MAXQTYUSED", "BUSINESSUNIT_ID", "CUSTOMER_ID", "PRODUCT_ID", "SIZEDEFINITION_ID", "QTYNEWAVAILABLE", "QTYUSEDAVAILABLE") AS 
  select
 l.code languagecode, x.stockroomcode, x.customerowned, c.customernumber, c.name customername,
 ad.city customercity, ad.street customerstreet, ad.zipcode customerzipcode, p.code productcode, s.code sizedefinitioncode,
 (select pd.description from product_desc pd where pd.product_id = x.product_id and pd.language_id = l.language_id) productdescription,
 x.qualitygradecode, x.priority, x.newgarment, x.defectitem, x.qtyunique_actual,
 x.qtynonunique_actual, x.qtyunique_blocked, x.qtynonunique_blocked, x.qtyuniquereserved,
 x.qtynonuniquereserved, x.qtyuniquewiithmodifreserved, x.qtyuniqueordered, x.qtynonuniqueordered,
 x.qtyuniqueordereddirectissue, x.qtynonuniqueordereddirectissue, x.minqtynew, x.minqtyused,
 x.maxqtynew, x.maxqtyused, x.businessunit_id, x.customer_id, x.product_id, x.sizedefinition_id,
 X.qtynewavailable qtynewavailable, X.qtyusedavailable qtyusedavailable
from (select ssb.businessunit_id, sr.stockroom_id, sr.code stockroomcode, sti.customerowned,
             sti.customer_id, sti.product_id, sti.sizedefinition_id, qg.code qualitygradecode,
             qg.priority, qg.newgarment, qg.defectitem,
             sum(case when lt.pickinglocation = 'Y' then (sq.qtyunique + sq.qtyuniquewithmodifications) else 0 end) qtyunique_actual,
             sum(case when lt.pickinglocation = 'Y' then sq.qtynonunique else 0 end) qtynonunique_actual,
             sum(case when lt.code = 'BLOCK' then (sq.qtyunique + sq.qtyuniquewithmodifications) else 0 end) qtyunique_blocked,
             sum(case when lt.code = 'BLOCK' then sq.qtynonunique else 0 end) qtynonunique_blocked,
             srg.qtyuniquereserved, srg.qtynonuniquereserved, srg.qtyuniquewiithmodifreserved, srg.qtyuniqueordered,
             srg.qtynonuniqueordered, srg.qtyuniqueordereddirectissue, srg.qtynonuniqueordereddirectissue,
             sti.minqtynew, sti.minqtyused, sti.maxqtynew, sti.maxqtyused,
             sum(case when lt.pickinglocation = 'Y' and qg.newgarment = 'Y' then sq.qtynonunique + sq.qtyunique + Sq.Qtyuniquewithmodifications
                      else 0 end) qtynewavailable,
             sum(case when lt.pickinglocation = 'Y' and qg.newgarment = 'N' and qg.defectitem = 'N' then sq.qtynonunique + sq.qtyunique + Sq.Qtyuniquewithmodifications
                      else 0 end) qtyusedavailable
  from stockdefinitionperitem sti
  join (stockroom sr join stockroomsservicingbu ssb on ssb.stockroom_id = sr.stockroom_id) on sti.stockroom_id = sr.stockroom_id
  join stockreservationpergrade srg on sti.stockdefinitionperitem_id = srg.stockdefinitionperitem_id
  left outer join (stockquantity sq join stockroomlocation srl on sq.stockroomlocation_id = srl.stockroomlocation_id
             join locationtype lt on lt.locationtype_id = srl.locationtype_id
  ) on srg.stockreservationpergrade_id = sq.stockreservationpergrade_id and srl.stockroom_id = sr.stockroom_id
  join qualitygrade qg on qg.qualitygrade_id = srg.qualitygrade_id
  group by ssb.businessunit_id, sr.stockroom_id, sr.code, sti.customerowned, sti.customer_id, sti.product_id,
           sti.sizedefinition_id, qg.code, qg.priority, qg.newgarment, qg.defectitem, srg.qtyuniquereserved,
           srg.qtynonuniquereserved, srg.qtyuniquewiithmodifreserved, srg.qtyuniqueordered, srg.qtynonuniqueordered,
           srg.qtyuniqueordereddirectissue, srg.qtynonuniqueordereddirectissue, sti.minqtynew, sti.minqtyused,
           sti.maxqtynew, sti.maxqtyused
  having(sum(case when lt.pickinglocation = 'Y' then (sq.qtyunique + sq.qtyuniquewithmodifications) else 0 end) +
         sum(case when lt.pickinglocation = 'Y' then sq.qtynonunique else 0 end) +
         sum(srg.qtyuniquereserved) + (srg.qtynonuniquereserved) + (srg.qtyuniquewiithmodifreserved) +
         sum(case when lt.code = 'BLOCK' then (sq.qtyunique + sq.qtyuniquewithmodifications) else 0 end) +
         (srg.qtyuniqueordered) + (srg.qtynonuniqueordered) +
         sum(case when lt.code = 'BLOCK' then sq.qtynonunique else 0 end) -
         (srg.qtynonuniqueordereddirectissue) - (srg.qtyuniqueordereddirectissue)) <> 0) x
join  product p on p.product_id = x.product_id
join  sizedefinition s on s.sizedefinition_id = x.sizedefinition_id
left  outer join (customer c join address ad on ad.address_id = c.visitaddress_id) on c.customer_id = x.customer_id
cross join languages l
/

  CREATE OR REPLACE VIEW "V_STOCKQUANTITYPERLOCATION" ("STOCKROOM_ID", "STOCKROOMCODE", "STOCKROOMNAME", "ROWCODE", "LOCATIONCODE", "LOCATIONTYPE_ID", "LOCATIONTYPECODE", "PRODUCTCODE", "SIZECODE", "PRODUCT_DESC", "SIZE_DESC", "LT_DESC", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMEROWNED", "QTYUNIQUE", "QTYNONUNIQUE", "GRADECODE", "NEWGARMENT", "DEFECTITEM", "USERGROUP_ID", "LANGUAGECODE", "STOCKLOCAREACODE") AS 
  select sr.stockroom_id stockroom_id, sr.code stockroomcode, sr.name stockroomname, sl.rowcode rowcode, sl.locationcode locationcode,
       lt.locationtype_id locationtype_id, lt.code locationtypecode, pr.code productcode, sd.code sizecode,
       coalesce((select prd.description from product_desc prd where pr.product_id = prd.product_id and prd.language_id = lan.language_id),'') Product_desc,
       coalesce((select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sd.sizedefinition_id and sdd.language_id = lan.language_id),'') size_desc,
       coalesce((select ltd.description from locationtype_desc ltd where ltd.locationtype_id = lt.locationtype_id and ltd.language_id = lan.language_id),'') lt_desc,
       cus.customer_id customer_id,
       coalesce(cus.customernumber, -2)customernumber,--customernumber-1 is used for all owned or related location
       cus.name customername, sdi.customerowned customerowned,
       (sq.qtyunique+sq.qtyuniquewithmodifications) qtyunique,
       sq.qtynonunique,
       qg.code gradecode,qg.newgarment newgarment, qg.defectitem defectitem,
       bug.usergroup_id usergroup_id,lan.code languagecode, sl.areacode StockLocAreaCode
from stockroom sr,stockroomlocation sl, stockquantity sq, stockreservationpergrade srg,stockdefinitionperitem sdi
     left outer join customer cus on sdi.customer_id=cus.customer_id,
     locationtype lt, product pr,sizedefinition sd,productsize ps,qualitygrade qg, businessunitsperusergroup bug,languages lan
where sr.stockroom_id=sl.stockroom_id
      and sl.stockroomlocation_id=sq.stockroomlocation_id
      and sq.stockreservationpergrade_id=srg.stockreservationpergrade_id
      and srg.stockdefinitionperitem_id=sdi.stockdefinitionperitem_id
      and sdi.stockroom_id=sr.stockroom_id
      and sdi.product_id=pr.product_id
      and sdi.sizedefinition_id=sd.sizedefinition_id
      and sl.locationtype_id=lt.locationtype_id
      and pr.product_id=ps.product_id
      and ps.sizedefinition_id=sd.sizedefinition_id
      and srg.qualitygrade_id=qg.qualitygrade_id
      and sr.managedbybu_id=bug.businessunit_id
/

  CREATE OR REPLACE VIEW "V_STOCKRECEPTIONPRODWO" ("STOCKCODE", "STOCKNAME", "STOCKROOM_ID", "RECEIVEDATE", "RECEIVEDATETRUNC", "RECEIVEDATETIME", "PURCHASEORDERNUMBER", "PRODUCTCODE", "SIZECODE", "PRODUCTDESC", "QUANTITY", "WORKSTATIONCODE", "PRDGRPCODE", "QCODE", "QDESC", "QUANTITYRECEIVED", "QTYOPEN", "ORDERDATE", "SUPPLNAME", "SUPPLIERNUMBER", "PURCHASEORDERHEADER_ID", "PURCHASEORDERLINE_ID", "RECEIVEINSTOCKHISTORY_ID", "PRIORITY", "LANGUAGECODE", "STQTY") AS 
  select
  sk.code stockCode, sk.name stockName, sk.stockroom_id, recSkhis.Receivedate, trunc(recSkhis.Receivedate) ReceivedateTrunc
, GETTIMEASNUMERIC(recSkhis.Receivedate) ReceivedateTime
, recSkhis.Purchaseordernumber  Purchaseordernumber
, prd.code productCode, sz.code sizeCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc, recSkhis.Quantity, recSkhis.WorkstationCode, pg.code prdgrpcode
, qq.code qcode
, ( select  qde.description from   qualitygrade_desc qde where qde.qualitygrade_id=qq.qualitygrade_id and qde.language_id=languages.language_id) qdesc
,phli.quantityreceived,
(case when (phli.quantityordered-phli.quantityreceived-phli.quantitycancelled)<0 then 0
  else phli.quantityordered-phli.quantityreceived-phli.quantitycancelled end ) qtyopen
, ph.orderdate, s.name supplname, s.suppliernumber suppliernumber
, ph.purchaseorderheader_id, phli.purchaseorderline_id, recSkhis.Receiveinstockhistory_Id,qq.priority
, languages.code languageCode
,COALESCE((select sum(sq.qtyunique + sq.qtyuniquewithmodifications+sq.qtynonunique)
from  stockquantity sq, stockroomlocation sl, stockreservationpergrade srg, stockdefinitionperitem sdi
where srg.stockreservationpergrade_id = sq.stockreservationpergrade_id
      and  sq.stockroomlocation_id = sl.stockroomlocation_id
      and srg.stockdefinitionperitem_id =sdi.stockdefinitionperitem_id
      and sdi.stockroom_id=sk.stockroom_id
      and srg.qualitygrade_id=qq.qualitygrade_id
      and sdi.product_id=prd.product_id
      and sdi.sizedefinition_id=sz.sizedefinition_id),0) stqty
from   receiveinstockhistory recSkhis,  purchaseorderheader ph, purchaseorderline phli
      , stockroom sk , product prd,productgroup pg, sizedefinition sz, supplier s,qualitygrade qq,languages
where recSkhis.Stockroom_Id = sk.stockroom_id
and recSkhis.Purchaseordernumber = ph.purchaseordernumber
and recSkhis.Stockroom_Id = ph.stockroom_id
and recSkhis.Qualitygrade_Id=qq.qualitygrade_id
and ph.supplier_id=s.supplier_id
and ph.purchaseorderheader_id=phli.purchaseorderheader_id
and recSkhis.Product_Link_Id = phli.product_link_id
and phli.product_link_id=prd.product_id
and recSkhis.Sizedefinition_Link_Id = phli.sizedefinition_link_id
and phli.sizedefinition_link_id=sz.sizedefinition_id
and prd.productgroup_id=pg.productgroup_id
and qq.newgarment='Y'
/

  CREATE OR REPLACE VIEW "V_STOCKRECEPTIONPRODWO_AUX" ("STOCKROOM_ID", "PRODUCTCODE", "PRODUCTDESC", "QDESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "FULLNAME", "WEARERSEARCHNAME", "WORKORDERNUMBER", "QTYDIFF", "BUCODE", "NEEDEDDATE", "ENTRYDATE", "REFERENCENUMBER", "WOREFERENCENR", "RCCODE", "ORDSIZE", "ORDSIZEDESC", "REZSIZECODE", "WORKORDERLINE_ID", "REQGRAD", "PRIORITY", "LANGUAGECODE") AS 
  Select distinct
 sk.stockroom_id,  prd.code productCode,  ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( select  qde.description from   qualitygrade_desc qde where qde.qualitygrade_id=wokli.requestedgrade_id and qde.language_id=languages.language_id) qdesc
, cu.customernumber, cu.name customerName, we.wearernumber, we.wearername fullname, we.wearersearchname
,wok.workordernumber workordernumber --, (wokli.quantityordered -  wokli.quantitycancelled-wokli.quantityfilled) QtyDiff ABS-50069
,(select sum(wolrA.Quantity) from workorderlinereservation wolrA where wolrA.Stockreservationpergrade_Id = srg.stockreservationpergrade_id and wolrA.Workorderline_Id = wokli.workorderline_id) QtyDiff --qtyRez --ABS-50069
,(select bu.code from businessunit bu where wok.businessunit_id=bu.businessunit_id) bucode
, wok.neededdate, wok.entrydate, wok.referencenumber
, coalesce((select worefnr.referencenumber from  woreferencenumber worefnr where wok.woreferencenumber_id = worefnr.woreferencenumber_id),-1)woreferencenr
,(select rc.code from reasoncode rc where wokli.reasoncode_id=rc.reasoncode_id) rccode
,(select sd.code from sizedefinition sd where sd.sizedefinition_id=wokli.sizedefinition_link_id) ordsize
,(select sdde.description from sizedefinition_desc sdde
    where sdde.sizedefinition_id=wokli.sizedefinition_link_id and sdde.language_id=languages.language_id) ordsizedesc
,sz.code rezsizecode,wokli.workorderline_id
,( select a.code from qualitygrade a where wokli.requestedgrade_id=a.qualitygrade_id) reqgrad,
( select a.priority from qualitygrade a where wokli.requestedgrade_id=a.qualitygrade_id) priority, languages.code languagecode
from    workorderline wokli, workorder wok
    left outer join customer_link cu on wok.customer_link_id = cu.customer_link_id
    left outer join weareremployment_link we on wok.weareremployment_link_id = we.weareremployment_link_id
   , stockroom sk , product prd, sizedefinition sz,workorderlinereservation wolr,
   stockreservationpergrade srg,stockdefinitionperitem sdi, qualitygrade qq,  languages
where wok.processingstockroom_id = sk.stockroom_id
and wokli.product_link_id = prd.product_id
and wokli.workorder_id = wok.workorder_id
and wokli.workorderline_id=wolr.workorderline_id
and wolr.stockreservationpergrade_id=srg.stockreservationpergrade_id
and srg.qualitygrade_id=qq.qualitygrade_id
and srg.stockdefinitionperitem_id=sdi.stockdefinitionperitem_id
and sdi.stockroom_id=sk.stockroom_id
and sdi.product_id=prd.product_id
and sdi.sizedefinition_id=sz.sizedefinition_id
--and (wokli.quantityordered -  wokli.quantitycancelled-wokli.quantityfilled) > 0
and wok.status_id in (select s.status_id from status  s where s.statustype='WO' and s.code in('10','15','20','25'))
/

  CREATE OR REPLACE VIEW "V_STOCKRECEPTIONSTICKER" ("REPORTPARAM_ID", "UNIQUEITEM_ID", "PRIMARYID", "PRODUCTCODE", "PRODUCTDESCRIPTION", "PRODUCTLONGDESCRIPTION", "SIZECODE", "QUALITYGRADECODE", "EMBLEM", "MODIFICATIONS", "LASTCUSTOMER", "ROWCODE", "LOCATIONCODE", "LANGUAGECODE") AS 
  select rp.reportparam_id,
       ui.uniqueitem_id,
       ui.primaryid,
       (select p.code from product p where ui.product_id = p.product_id) productCode,
       (select pd.description
          from product_desc pd, product p
         where pd.product_id = p.product_id
           and p.product_id = ui.product_id
           and pd.language_id = l.language_id) productDescription,
       (select pd.longdescription
          from product_desc pd, product pp
         where pd.product_id = pp.product_id
           and pp.product_id = ui.product_id
           and pd.language_id = l.language_id) productLongDescription,
       (select sz.code
          from sizedefinition sz
         where ui.sizedefinition_id = sz.sizedefinition_id) sizeCode,
       (select qg.code
          from qualitygrade qg
         where qg.qualitygrade_id = uifi.qualitygrade_id) qualitygradecode,
       (select max(wi.weareremployment_id)
          from wearerinventory wi
         where ui.lastweareremployment_link_id = wi.weareremployment_id
           and wi.emblemtemplate_id is not null) emblem,
       f_concat_modificationcode(ui.uniqueitem_id) modifications,
       f_getuniqueitemlastcust(ui.uniqueitem_id)lastcustomer,
       sl.rowcode RowCode,
       sl.locationcode LocationCode,
       l.code languagecode
  from uniqueitem ui, uniqueitemfixedinfo uifi ,stockroomlocation sl, languages l, reportparam rp
 where ui.uniqueitem_id = uifi.uniqueitem_id
       and uifi.stockroomlocation_id = sl.stockroomlocation_id
       and ui.uniqueitem_id=rp.number_value
       and rp.number_value1=0
union
 select rp.reportparam_id,
        ui.uniqueitem_id,
       ui.primaryid,
       (select p.code from product p where ui.product_id = p.product_id) productCode,
       (select pd.description
          from product_desc pd, product p
         where pd.product_id = p.product_id
           and p.product_id = ui.product_id
           and pd.language_id = l.language_id) productDescription,
       (select pd.longdescription
          from product_desc pd, product pp
         where pd.product_id = pp.product_id
           and pp.product_id = ui.product_id
           and pd.language_id = l.language_id) productLongDescription,
       (select sz.code
          from sizedefinition sz
         where ui.sizedefinition_id = sz.sizedefinition_id) sizeCode,
       (select qg.code
          from qualitygrade qg
         where qg.qualitygrade_id = uifi.qualitygrade_id) qualitygradecode,
       (select max(wi.weareremployment_id)
          from wearerinventory wi
         where ui.lastweareremployment_link_id = wi.weareremployment_id
           and wi.emblemtemplate_id is not null) emblem,
       f_concat_modificationcode(ui.uniqueitem_id) modifications,
       f_getuniqueitemlastcust(ui.uniqueitem_id)lastcustomer,
       sl.rowcode RowCode,
       sl.locationcode LocationCode,
       l.code languagecode
  from uniqueitem ui, uniqueitemfixedinfo uifi ,stockroomlocation sl, languages l, reportparam rp
 where ui.uniqueitem_id = uifi.uniqueitem_id
       --and uifi.stockroomlocation_id is null-- needed for move within stock
       and ui.uniqueitem_id=rp.number_value
       and rp.number_value1 = sl.stockroomlocation_id
/

  CREATE OR REPLACE VIEW "V_STOCKRECEPTIONSTICKER_UNIQUE" ("UNIQUEITEM_ID", "PRIMARYID", "PRODUCT_ID", "SIZEDEFINITION_ID", "SIZECODE", "SIZECODEDESCRIPTION", "MODIFICATIONS", "MODIFICATION1_DESC", "MODIFICATION2_DESC", "MODIFICATION3_DESC", "LANGUAGECODE", "EMBLEM", "NAMELABEL_WEARERFUNCTION") AS 
  select ui.uniqueitem_id,
       ui.primaryid,
       ui.product_id,
       ui.sizedefinition_id,
       sz.code sizeCode,
       (select szd.description
          from sizedefinition_desc szd
         where sz.sizedefinition_id = szd.sizedefinition_id
           and szd.language_id = l.language_id) sizeCodeDescription,
       f_concat_modificationcode(ui.uniqueitem_id) modifications,
      -- m1.code modification1code,
       (select md1.description
          from modification_desc md1
         where md1.modification_id = m1.modification_id
           and md1.language_id = l.language_id) modification1_desc,
      -- m2.code modification2code,
       (select md2.description
          from modification_desc md2
         where md2.modification_id = m2.modification_id
           and md2.language_id = l.language_id) modification2_desc,
      -- m3.code modification3code,
       (select md3.description
          from modification_desc md3
         where md3.modification_id = m3.modification_id
           and md3.language_id = l.language_id) modification3_desc,
       l.code languagecode,
       (select wi.weareremployment_id
          from wearerinventory wi
         where ui.lastweareremployment_link_id = wi.weareremployment_id
           and wi.emblemtemplate_id is not null) emblem,
       (select we.weareremployment_id
          from weareremployment we, wearerfunction wf
         where ui.lastweareremployment_link_id = we.weareremployment_id
           and we.wearerfunction_id = wf.wearerfunction_id
           and wf.codelabellayout_id is not null) namelabel_wearerfunction
  from uniqueitem             ui,
       sizedefinition         sz,
       languages              l,
       uniqueitemmodification uim1,
       uniqueitemmodification uim2,
       uniqueitemmodification uim3,
       modification           m1,
       modification           m2,
       modification           m3
 where ui.sizedefinition_id = sz.sizedefinition_id
   and ui.uniqueitem_id = uim1.uniqueitem_id
   and uim1.modification_id = m1.modification_id
   and ui.uniqueitem_id = uim2.uniqueitem_id
   and uim2.modification_id = m2.modification_id
   and ui.uniqueitem_id = uim3.uniqueitem_id
   and uim3.modification_id = m3.modification_id
/

  CREATE OR REPLACE VIEW "V_STOCKRECEPTIONSTICK_LOCATION" ("STOCKROOMLOCATION_ID", "STOCKROOM_ID", "STOCKROOMCODE", "STOCKROOMNAME", "ROWCODE", "LOCATIONCODE", "UNIQUEID", "LOCATIONTYPE", "PRIORITY", "BUSINESSUNIT_ID") AS 
  select sl.stockroomlocation_id Stockroomlocation_ID,
       sr.stockroom_id Stockroom_ID,
       sr.code StockroomCode,
       sr.name StockroomName,
       sl.rowcode RowCode,
       sl.locationcode LocationCode,
       sl.uniqueid UniqueID,
       lt.code LocationType,
       nvl(srb.priority, 1) Priority,
       srb.businessunit_id businessunit_ID
  from stockroom sr
  left outer join stockroomsservicingbu srb
    on srb.stockroom_id = sr.stockroom_id, stockroomlocation sl,
 locationtype lt
 where sr.stockroom_id = sl.stockroom_id
   and sl.locationtype_id = lt.locationtype_id
/

  CREATE OR REPLACE VIEW "V_STOCKRECEPTIONSTICK_PRODUCT" ("PRODUCT_ID", "PRODUCTCODE", "SUPPLIER_ID", "PRODUCTDESCRIPTION", "PRODUCTLONGDESCRIPTION", "PRODUCTRANKING", "REGISTRATIONUNITCODE", "REGISTRATIONUNITDESC", "PRODUCTGROUPCODE", "PRODUCTGROUPDESC", "MODIFICATIONGROUP1CODE", "MODIFICATIONGROUP1DESC", "MODIFICATIONGROUP2CODE", "MODIFICATIONGROUP2DESC", "MODIFICATIONGROUP3CODE", "MODIFICATIONGROUP3DESC", "LANGUAGECODE") AS 
  select p.product_id,
       p.code productCode,
       p.supplier_id,
       (select pd.description
          from product_desc pd
         where pd.product_id = p.product_id
           and pd.language_id = la.language_id) productDescription,
       (select pd.longdescription
          from product_desc pd
         where pd.product_id = p.product_id
           and pd.language_id = la.language_id) productLongDescription,
       pr.ranking Productranking,
       ru.code RegistrationUnitCode,
       (select rud.description
          from registrationunit_desc rud
         where rud.registrationunit_id = ru.registrationunit_id
           and rud.language_id = la.language_id) registrationunitdesc,
       pg.code productGroupCode,
       (select pgd.description
          from productgroup_desc pgd
         where pgd.productgroup_id = pg.productgroup_id
           and pgd.language_id = la.language_id) productgroupdesc,
       mg1.code ModificationGroup1Code,
       (select mgd1.description
          from modificationgroup_desc mgd1
         where mgd1.modificationgroup_id = mg1.modificationgroup_id
           and mgd1.language_id = la.language_id) modificationgroup1desc,
       mg2.code ModificationGroup2Code,
       (select mgd2.description
          from modificationgroup_desc mgd2
         where mgd2.modificationgroup_id = mg2.modificationgroup_id
           and mgd2.language_id = la.language_id) modificationgroup2desc,
       mg3.code ModificationGroup3Code,
       (select mgd3.description
          from modificationgroup_desc mgd3
         where mgd3.modificationgroup_id = mg3.modificationgroup_id
           and mgd3.language_id = la.language_id) modificationgroup3desc,
       la.code languagecode
  from product p
  left outer join productranking pr
    on pr.productranking_id = p.productranking_id
  left outer join (Select pm.product_id, mg.modificationgroup_id, mg.code
                     from productmodificationgroup pm, modificationgroup mg
                     where mg.modificationgroup_id = pm.modificationgroup_id
                     and pm.sequencenumber = 1) mg1 on  mg1.product_id = p.product_id
  left outer join (Select pm.product_id, mg.modificationgroup_id, mg.code
                     from productmodificationgroup pm, modificationgroup mg
                     where mg.modificationgroup_id = pm.modificationgroup_id
                     and pm.sequencenumber = 2) mg2 on  mg2.product_id = p.product_id
   left outer join (Select pm.product_id, mg.modificationgroup_id, mg.code
                     from productmodificationgroup pm, modificationgroup mg
                     where mg.modificationgroup_id = pm.modificationgroup_id
                     and pm.sequencenumber = 3) mg3 on  mg3.product_id = p.product_id,
  registrationunit ru, productgroup pg,
 languages la
 where
    ru.registrationunit_id = p.registrationunit_id
   and pg.productgroup_id = p.productgroup_id
/

  CREATE OR REPLACE VIEW "V_STOCKRESERVATIONPERGRADE" ("BUSINESSUNITCODE", "BUSINESSUNITDESC", "STOCKROOMCODE", "STOCKROOMNAME", "CUSTOMEROWNED", "CUSTOMERNUMBER", "PRODUCTCODE", "PRODUCTDESCRIPTION", "COLORCODE", "FABRICODE", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESCRIPTION", "QUALITYGRADECODE", "QUALITYGRADEDESC", "PRIORITY", "QTYUNIQUERESERVED", "QTYNONUNIQUERESERVED", "QTYUNIQUEWIITHMODIFRESERVED", "QTYUNIQUEORDERED", "QTYNONUNIQUEORDERED", "QTYNONUNIQUE", "LANGUAGECODE") AS 
  select
bu.code businessunitCode, bu.description businessunitDesc,
  stockroom.code stockroomCode, stockroom.name stockroomName,
  sit.customerowned, cu.customernumber
, prd.code ProductCode
, (select product_desc.description from product_desc where prd.product_id = product_desc.product_id
and product_desc.language_id = languages.language_id ) ProductDescription
, color.code colorCode, fabric.code fabriCode, sizdef.code SizedefinitionCode
, (select sizedefinition_desc.description from sizedefinition_desc where sizdef.sizedefinition_id = sizedefinition_desc.sizedefinition_id
and sizedefinition_desc.language_id = languages.language_id ) SizedefinitionDescription
,qualitygrade.code qualitygradecode,(select qd.description from qualitygrade_desc qd where qd.qualitygrade_id = qualitygrade.qualitygrade_id
and qd.language_id = languages.language_id) qualitygradedesc,
 qualitygrade.priority,
 srg.qtyuniquereserved, srg.qtynonuniquereserved, srg.qtyuniquewiithmodifreserved,
 srg.qtyuniqueordered, srg.qtynonuniqueordered,srg.qtynonunique,
 languages.code  languageCode
from
  stockroom, BUSINESSUNIT BU
, stockdefinitionperitem sit left outer join customer cu on sit.customer_id = cu.customer_id
, stockreservationpergrade srg, qualitygrade, product prd, sizedefinition sizdef,
 color, fabric, languages
where
    stockroom.stockroom_id = sit.stockroom_id
and sit.stockdefinitionperitem_id = srg.stockdefinitionperitem_id
and srg.qualitygrade_id = qualitygrade.qualitygrade_id
and sit.product_id = prd.product_id
and prd.color_id = color.color_id
and prd.fabric_id = fabric.fabric_id
and sit.sizedefinition_id = sizdef.sizedefinition_id
AND stockroom.managedbybu_id = BU.BUSINESSUNIT_ID
/

  CREATE OR REPLACE VIEW "V_STOCKROOMACTIVITY" ("SYSTEMUSER_ID", "COMPLETIONDATE", "PLANTCODE", "PLANTNAME", "WORKORDERNUMBER", "ROUTENUMBER", "ROUTEDESC", "DEPOTCODE", "DEPOTDESC", "REASONCODE", "REASONDESC", "QUANTITY", "REQUESTEDGRADE_NEWGARMENT", "ISSUEGRADE_NEWGARMENT", "PRICE", "LANGUAGECODE", "REPORTPARAM_ID", "TOTALCIRCINV", "REVENUE") AS 
  SELECT su.systemuser_id, wo.completiondate, pl.code PlantCode, pl.name PlantName, wo.workordernumber
       , ro.routenumber, ro.description RouteDesc, de.code DepotCode, de.description DepotDesc, rc.code ReasonCode
       , (SELECT rcd.description FROM Reasoncode_Desc rcd WHERE rc.reasoncode_id = rcd.reasoncode_id AND rcd.language_id = lan.language_id) ReasonDesc
       , ih.quantity, rqg.newgarment requestedgrade_newgarment, iqg.newgarment issuegrade_newgarment
       , COALESCE(
       (SELECT F_PURCHASEPRICE(sup.supplier_id, ih.product_link_id, ih.sizedefinition_link_id, trunc(sysdate))
        FROM uniqueitemfixedinfo uifi, supplier sup WHERE uifi.uniqueitem_id = ih.uniqueitem_link_id AND uifi.supplier_id = sup.supplier_id),
       (SELECT F_PURCHASEPRICE(p.supplier_id, ih.product_link_id, ih.sizedefinition_link_id, trunc(sysdate))
        FROM product p WHERE ih.product_link_id = p.product_id),
        0
       ) price
       , lan.code LanguageCode, rp.reportparam_id
       , F_GetStockActivity_Items(pl.plant_id, rp.reportparam_id) totalcircinv
       , F_GetStockActivity_Revenue(pl.plant_id, rp.reportparam_id) revenue
FROM IssueHistory ih, businessunit bu, plant pl, systemuser su
     , reasoncode rc, qualitygrade rqg, qualitygrade iqg, WorkOrder wo
        LEFT OUTER JOIN route ro
                   LEFT OUTER JOIN depot de ON ro.depot_id = de.depot_id
        ON wo.route_id = ro.route_id
     , languages lan, reportparam rp
WHERE ih.workorder_id = wo.workorder_id --AND wo.businessunit_id = bug.businessunit_id AND bug.usergroup_id = su.usergroup_id
      AND wo.businessunit_id = bu.businessunit_id AND bu.plant_id = pl.plant_id AND wo.reasoncode_id = rc.reasoncode_id
      AND ih.requestedgrade_id = rqg.qualitygrade_id AND ih.issuegrade_id = iqg.qualitygrade_id
			and su.systemuser_id  = rp.number_value4
			and lan.code = rp.string_value8
			and rp.date_value1 <= wo.completiondate and wo.completiondate <= rp.date_value2
			and          ((rp.string_value1 = ' ' and rp.string_value2 = 'ZZZZZZ' )
                   or
                   (rp.string_value1 <= pl.code and rp.string_value2 <= pl.code)) and
                  ((rp.string_value3 = ' ' and rp.string_value4 = 'ZZZZZZZZZZZZ')
                   or
                   (rp.string_value3 <= de.code and rp.string_value4 <= de.code)) and
                  ((rp.number_value1 = 0 and rp.number_value2 = 999999 )
                   or
                   (rp.number_value1 <= ro.routenumber and rp.number_value2 <= ro.routenumber)) and
                  ((rp.string_value5 = ' ' and rp.string_value6 = 'ZZZZZZ')
                   or
                   (rp.string_value5 <= rc.code and rp.string_value6 <= rc.code))
    and exists (select * from businessunitsperusergroup bug
    where bug.businessunit_id = bu.businessunit_id and bug.usergroup_id = su.usergroup_id)
/

  CREATE OR REPLACE VIEW "V_STOCKROOMACTIVITY_ITEMS" ("PLANTCODE", "TOTALCIRCINV", "REPORTPARAM_ID") AS 
  select t.code PlantCode, sum(i.totalcircinv) totalcircinv, rp.reportparam_id
from   statusquoheader h, sqitemincirculation i, businessunit bu, plant t,
       (select t.code, max(q.statusquodate) statusquodate, rp2.reportparam_id
         from   statusquoheader q, businessunit bu, plant t, reportparam rp2
         where  q.processbusinessunit_id = bu.businessunit_id
         and    bu.plant_id = t.plant_id
         AND rp2.date_value2 >= q.statusquodate
         group  by t.code, rp2.reportparam_id) x, reportparam rp
where  h.statusquoheader_id = i.statusquoheader_id
and    x.statusquodate = h.statusquodate
and    h.processbusinessunit_id = bu.businessunit_id
and    bu.plant_id = t.plant_id
and    t.code = x.code
AND rp.reportparam_id = x.reportparam_id
group  by t.code, rp.reportparam_id
/

  CREATE OR REPLACE VIEW "V_STOCKROOMACTIVITY_REVENUE" ("PLANTCODE", "REPORTPARAM_ID", "REVENUE") AS 
  SELECT --rc.drivingdate,
pl.code PlantCode, rp.reportparam_id,
SUM (CASE WHEN il.adjustmentreason_id IS NULL THEN il.amount
    ELSE il.adjustedamount
    END) Revenue
FROM invoiceheader ih, invoiceline il, routecontrol rc, businessunit bu, plant pl, status st,
     invoicelinetype ilt, invoicelineproduct ilp, product p, reportparam rp
WHERE ih.invoiceheader_id = il.invoiceheader_id AND ih.routecontrol_id = rc.routecontrol_id
      AND ih.invoicebusinessunit_id = bu.businessunit_id AND bu.plant_id = pl.plant_id
      AND ih.status_id = st.status_id AND il.invoiceline_id = ilp.invoiceline_id
      AND ilp.product_link_id = p.product_id AND ilt.invoicelinetype_id = il.invoicelinetype_id
      AND ih.documenttype = 1 AND st.statustype = 'IN' AND st.code = '2' AND il.Extend = 'Y'
      AND ilt.type = 1 AND p.typeofmerchandise = 2
      AND rc.drivingdate >= rp.date_value1
      AND rc.drivingdate <= rp.date_value2
GROUP BY pl.code, rp.reportparam_id--, rc.drivingdate
/

  CREATE OR REPLACE VIEW "V_STOCKROOMBUSINESSUNITS" ("MANAGINGBU_ID", "BU_ID") AS 
  select SR.MANAGEDBYBU_ID MANAGINGBU_ID, SRSBU.BUSINESSUNIT_ID BU_ID
    from STOCKROOMSSERVICINGBU SRSBU, STOCKROOM SR
   where SRSBU.STOCKROOM_ID = SR.STOCKROOM_ID
/

  CREATE OR REPLACE VIEW "V_STOCKROOMITEMPICKLIST" ("LINETYPE", "QGORDERCODE", "STOCKROOMCODE", "STOCKROOMDESCRIPTION", "ROWCODE", "LOCATIONCODE", "PICKINGSEQUENCE", "UNIQUEYN", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "QGRESERVEDCODE", "MODIFICATIONCODEA", "MODIFICATIONCODEB", "MODIFICATIONCODEC", "QTYUNIQUE", "QTYUNIQUERESERVED", "QTYNONUNIQUE", "QTYNONUNIQUERESERVED", "ROUTENUMBER", "DAYCODE", "WORKORDERNUMBER", "REQSTDDELIVERY", "WORKORDERQUANTITYORDERED", "WORKORDERLINERESERVATIONQTY", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "WEARERSEARCHNAME", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "LANGUAGECODE", "ORIGIN", "ORDEREDSIZECODE", "STOCKLOCAREACODE") AS 
  select 1 linetype,
  qgOrder.Code qgOrderCode, s.code stockroomCode, s.name stockroomDescription, sl.rowcode rowCode
, sl.locationcode locationCode, sl.pickingsequence, wokli.codeuniquely UniqueYN, prd.code ProductCode
, (select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id) productDescription
, sizedef.code SizedefinitionCode, qgReserved.code qgReservedCode
, (select modification.code from modification, workorderlinemodification where workorderlinemodification.modification_id = modification.modification_id
  and wokli.workorderline_id = workorderlinemodification.workorderline_id and workorderlinemodification.sequencenumber=1 ) modificationCodeA
, (select modification.code from modification, workorderlinemodification where workorderlinemodification.modification_id = modification.modification_id
  and wokli.workorderline_id = workorderlinemodification.workorderline_id and workorderlinemodification.sequencenumber=2 ) modificationCodeB
, (select modification.code from modification, workorderlinemodification where workorderlinemodification.modification_id = modification.modification_id
  and wokli.workorderline_id = workorderlinemodification.workorderline_id and workorderlinemodification.sequencenumber=3 ) modificationCodeC
, (sq.qtyunique + sq.qtyuniquewithmodifications) qtyunique, (srg.qtyuniquereserved+srg.qtyuniquewiithmodifreserved) qtyuniquereserved
, sq.qtynonunique , srg.qtynonuniquereserved ,  route.routenumber
, (select day_desc.code from day_desc where day_desc.day_id = route.drivingday_id
  and day_desc.language_id = languages.language_id) DayCode, wok.workordernumber
, wok.requestdate ReqstdDelivery, wokli.quantityordered WorkOrderquantityordered
, WRE.QUANTITY WorkOrderLineReservationQTY
, cu.customernumber, cu.name customerName, we.wearernumber, we.wearersearchname wearerSearchname
, 0 distributionpointnumber,'' distributionpointdescription
, languages.code languageCode
, wok.origin
, (select osd.code from sizedefinition_link osd where wokli.sizedefinition_link_id = osd.sizedefinition_link_id)  OrderedSizeCode
, sl.areacode StockLocAreaCode
from
  workorder wok
    left outer join route on wok.route_id = route.route_id
, weareremployment_link we
, workorderline wokli
, workorderlinereservation wre, product_link prd, qualitygrade qgReserved, qualitygrade qgOrder
, stockroom s
, stockdefinitionperitem sdi,
  stockreservationpergrade srg
    left outer
    join (
      stockquantity sq join stockroomlocation sl on sl.stockroomlocation_id = sq.stockroomlocation_id
          ) on srg.stockreservationpergrade_id = sq.stockreservationpergrade_id
, sizedefinition_link sizedef, customer_link cu, languages
where wok.weareremployment_link_id = we.weareremployment_id
and cu.customer_id = wok.customer_link_id
and wok.workorder_id = wokli.workorder_id
and wokli.requestedgrade_id = qgOrder.Qualitygrade_Id
and wokli.workorderline_id = wre.workorderline_id
and wre.stockreservationpergrade_id = srg.stockreservationpergrade_id
and s.stockroom_id = sdi.stockroom_id
and sdi.stockdefinitionperitem_id = srg.stockdefinitionperitem_id
and srg.qualitygrade_id = qgReserved.qualitygrade_id
and sdi.product_id = prd.product_id
and sdi.sizedefinition_id = sizedef.sizedefinition_id
and wok.origin not in (7, 10, 11) --exclude credit notes, mounting and dismounting orders
and (sl.locationtype_id is null
    OR
    sl.locationtype_id in (select lt.locationtype_id from locationtype lt where lt.pickinglocation = 'Y'))
union all
select 2 linetype, qgOrder.Code qgOrderCode, s.code stockroomCode, s.name stockroomDescription, sl.rowcode rowCode
, sl.locationcode locationCode, sl.pickingsequence, wokli.codeuniquely UniqueYN, prd.code ProductCode
, (select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id) productDescription
, sizedef.code SizedefinitionCode, qgReserved.code qgReservedCode
, (select modification.code from modification, workorderlinemodification where workorderlinemodification.modification_id = modification.modification_id
  and wokli.workorderline_id = workorderlinemodification.workorderline_id and workorderlinemodification.sequencenumber=1 ) modificationCodeA
, (select modification.code from modification, workorderlinemodification where workorderlinemodification.modification_id = modification.modification_id
  and wokli.workorderline_id = workorderlinemodification.workorderline_id and workorderlinemodification.sequencenumber=2 ) modificationCodeB
, (select modification.code from modification, workorderlinemodification where workorderlinemodification.modification_id = modification.modification_id
  and wokli.workorderline_id = workorderlinemodification.workorderline_id and workorderlinemodification.sequencenumber=3 ) modificationCodeC
, (sq.qtyunique + sq.qtyuniquewithmodifications) qtyunique, (srg.qtyuniquereserved+srg.qtyuniquewiithmodifreserved) qtyuniquereserved
, sq.qtynonunique , srg.qtynonuniquereserved ,  route.routenumber
, (select day_desc.code from day_desc where day_desc.day_id = route.drivingday_id
  and day_desc.language_id = languages.language_id) DayCode, wok.workordernumber
, wok.requestdate ReqstdDelivery, wokli.quantityordered WorkOrderquantityordered
, WRE.QUANTITY WorkOrderLineReservationQTY
,(select c.customernumber from customer_link c where c.customer_link_id = wok.customer_link_id) customernumber,
(select c.name from customer_link c where c.customer_link_id = wok.customer_link_id) customerName
, null wearernumber, '' wearerSearchname,
(select d.distributionpointnumber from distributionpoint_link d where d.distributionpoint_link_id = wok.distributionpoint_link_id) distributionpointnumber,
(select d.description from distributionpoint_link d where d.distributionpoint_link_id = wok.distributionpoint_link_id) distributionpointdescription
, languages.code languageCode
, wok.origin
, (select osd.code from sizedefinition_link osd where wokli.sizedefinition_link_id = osd.sizedefinition_link_id)  OrderedSizeCode
, sl.areacode StockLocAreaCode
from
  workorder wok
    left outer join route on wok.route_id = route.route_id
, workorderline wokli
, workorderlinereservation wre, product_link prd, qualitygrade qgReserved, qualitygrade qgOrder
, stockroom s
, stockdefinitionperitem sdi,
  stockreservationpergrade srg
    left outer
    join (
      stockquantity sq join stockroomlocation sl on sl.stockroomlocation_id = sq.stockroomlocation_id
          ) on srg.stockreservationpergrade_id = sq.stockreservationpergrade_id
, sizedefinition_link sizedef
, languages
where wok.weareremployment_link_id is null
and wok.workorder_id = wokli.workorder_id
and wokli.requestedgrade_id = qgOrder.Qualitygrade_Id
and wokli.workorderline_id = wre.workorderline_id
and wre.stockreservationpergrade_id = srg.stockreservationpergrade_id
and s.stockroom_id = sdi.stockroom_id
and sdi.stockdefinitionperitem_id = srg.stockdefinitionperitem_id
and srg.qualitygrade_id = qgReserved.qualitygrade_id
and sdi.product_id = prd.product_id
and sdi.sizedefinition_id = sizedef.sizedefinition_id
and wok.origin not in (7, 10, 11) --exclude credit notes, mounting and dismounting orders
and (sl.locationtype_id is null
    OR
    sl.locationtype_id in (select lt.locationtype_id from locationtype lt where lt.pickinglocation = 'Y'))
/

  CREATE OR REPLACE VIEW "V_STOCKROOMLOCATIONLABEL" ("STOCKROOMLOCATION_ID", "STANDARDLOCATIONPERPRODUCT_ID", "PLANT_ID", "BUCODE", "PLANT", "STOCKROOM", "UNIQUEID", "AREACODE", "ROWCODE", "LOCATIONCODE", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZECODE", "SUPPLIERPRODUCTCODE", "LANGUAGECODE", "REPORTPARAM_ID") AS 
  select /*version 2.0*/
       sl.stockroomlocation_id,
       slpp.standardlocationperproduct_id,
       pl.plant_id,
       bu.code bucode,
       pl.code plant,
       st.code stockroom,
       sl.uniqueid,
       sl.areacode,
       sl.rowcode,
       sl.locationcode,
       pr.code productcode,
       pd.description productdescription,
       case
         when (slpp.definepersize = 'N') then
          '*'
         when (slpp.definepersize = 'Y') then
          sd.code
       end sizecode,
       case
         when (slpp.definepersize = 'N') then
          ''
         when (slpp.definepersize = 'Y') then
          pr.code
       end supplierproductcode,
       l.code languagecode,
       rp.reportparam_id
 from stockroom st, businessunit bu, plant pl, stockroomlocation sl,
      standardlocationperproduct slpp, standardlocationpersize slps,
      product pr, sizedefinition sd, product_desc pd, languages l, reportparam rp
where sl.stockroom_id = st.stockroom_id
  and bu.businessunit_id = st.managedbybu_id
  and pl.plant_id = bu.plant_id
  and slpp.stockroomlocation_id(+) = sl.stockroomlocation_id
  and slps.standardlocationperproduct_id(+) = slpp.standardlocationperproduct_id
  and pr.product_id(+) = slpp.product_id
  and pd.product_id(+) = pr.product_id
  and pd.language_id = l.language_id
  and sd.sizedefinition_id(+) = slps.sizedefinition_id
  and rp.number_value = slpp.standardlocationperproduct_id
/

  CREATE OR REPLACE VIEW "V_STOCKROOMPERROUTE" ("ROUTECONTROL_ID", "ROUTE_ID", "ROUTENUMBER", "PRINTPICKLISTRSC", "TRUCKCODE", "STOCKROOM_ID", "STOCKROOMLOCATION_ID", "TRUCK_ID", "MANAGEDBYBU_ID", "STOCKROOM_CODE", "STOCKROOM_NAME") AS 
  select rc.routecontrol_id, rt.route_id,  rt.routenumber, rt.printpicklistrsc, rc.truckcode, tr.stockroom_id, tr.stockroomlocation_id, tr.truck_id
,sr.managedbybu_id, sr.code stockroom_code, sr.name stockroom_name
from routecontrol rc, route rt, truck tr, stockroom sr
where rt.route_id = rc.route_id
and tr.code(+) = rc.truckcode
and tr.plant_id(+) = rc.plant_id
and sr.stockroom_id(+) = tr.stockroom_id
order by rt.route_id, rt.routenumber
/

  CREATE OR REPLACE VIEW "V_STOCKROOMPICKLIST" ("QGORDERCODE", "STOCKROOMCODE", "STOCKROOMDESCRIPTION", "ROWCODE", "LOCATIONCODE", "PICKINGSEQUENCE", "UNIQUEYN", "PRODUCTCODE", "ROUTENUMBER", "WORKORDERNUMBER", "REQSTDDELIVERY", "WORKORDERQUANTITYORDERED", "WORKORDERLINERESERVATIONQTY", "CUSTOMERNUMBER", "CUSTOMERNAME", "ORIGIN", "STOCKLOCAREACODE", "INSTRUCTIONS", "SIZEDEFINITIONCODE", "QGRESERVEDCODE", "LANGUAGECODE", "QTYUNIQUE", "WEARERNUMBER", "WEARERSEARCHNAME", "QTYNONUNIQUE", "SUMQTYUNIQUE", "PRODUCTDESCRIPTION", "MODIFICATIONCODEA", "MODIFICATIONCODEB", "MODIFICATIONCODEC", "DAYCODE", "ORDEREDSIZECODE", "SUMQTYNONUNIQUE", "COLORDESC", "QTYUNIQUERESERVED", "QTYNONUNIQUERESERVED") AS 
  select /*version 2.0*/
       qgorder.code qgordercode, s.code stockroomcode, s.name stockroomdescription, sl.rowcode rowcode, sl.locationcode locationcode,
       sl.pickingsequence, wokli.codeuniquely uniqueyn, prd.code productcode, ro.routenumber, wok.workordernumber, wok.neededdate reqstddelivery,
       wokli.quantityordered workorderquantityordered, wre.quantity workorderlinereservationqty, cu.customernumber, cu.name customername,
       wok.origin, sl.areacode stocklocareacode, wokli.instructions, sizedef.code sizedefinitioncode, qgreserved.code qgreservedcode, lan.code languagecode,
       coalesce((sq.qtyunique + sq.qtyuniquewithmodifications), 0) qtyunique,
       coalesce(we.wearernumber, dp.distributionpointnumber) wearernumber,
       coalesce(we.wearersearchname, dp.description) wearersearchname,
       coalesce((select sq.qtynonunique
                   from locationtype lt
                  where sl.locationtype_id = lt.locationtype_id
                    and lt.pickinglocation = 'Y'),0) qtynonunique,
       coalesce((select sum(a.qtyunique)
                   from stockquantity a
                  where a.stockreservationpergrade_id = srg.stockreservationpergrade_id), 0) sumqtyunique,
       (select prde.description
          from product_desc prde
         where prde.product_id = prd.product_id
           and prde.language_id = lan.language_id) productdescription,
       (select mm.code
          from modification mm
               join workorderlinemodification wolm on mm.modification_id = wolm.modification_id
         where wokli.workorderline_id = wolm.workorderline_id
           and wolm.sequencenumber = 1) modificationcodea,
       (select mm.code
          from modification mm
               join workorderlinemodification wolm on mm.modification_id = wolm.modification_id
         where wokli.workorderline_id = wolm.workorderline_id
           and wolm.sequencenumber = 2) modificationcodeb,
       (select mm.code
          from modification mm
               join workorderlinemodification wolm on mm.modification_id = wolm.modification_id
         where wokli.workorderline_id = wolm.workorderline_id
           and wolm.sequencenumber = 3) modificationcodec,
       (select dds.code
          from day_desc dds
         where dds.day_id = ro.drivingday_id
           and dds.language_id = lan.language_id) daycode,
       (select osd.code
          from sizedefinition_link osd
         where wokli.sizedefinition_link_id = osd.sizedefinition_link_id) orderedsizecode,
       (select sum(a.qtynonunique)
          from stockquantity a
         where a.stockreservationpergrade_id = srg.stockreservationpergrade_id) sumqtynonunique,
       (select cod.description
          from color_desc cod
               join product pr on cod.color_id = pr.color_id
         where pr.product_id = wokli.product_link_id
           and cod.language_id = lan.language_id) colordesc,
       case when wre.stocktype in (2, 3) then wre.quantity
            else 0
        end qtyuniquereserved,
       case when wre.stocktype = 1 then wre.quantity
            else 0
        end qtynonuniquereserved
  from workorder wok
       left join route ro on wok.route_id = ro.route_id
       left join weareremployment_link we on wok.weareremployment_link_id = we.weareremployment_link_id
       left join distributionpoint_link dp on wok.distributionpoint_link_id = dp.distributionpoint_link_id
       join workorderline wokli
            join qualitygrade qgorder on wokli.requestedgrade_id = qgorder.qualitygrade_id
            join workorderlinereservation wre
                 join stockreservationpergrade srg
                      left join stockquantity sq
                                join stockroomlocation sl on sq.stockroomlocation_id = sl.stockroomlocation_id
                      on srg.stockreservationpergrade_id = sq.stockreservationpergrade_id
                      join qualitygrade qgreserved on srg.qualitygrade_id = qgreserved.qualitygrade_id
                      join stockdefinitionperitem sdi
                           join stockroom s on sdi.stockroom_id = s.stockroom_id
                           join product_link prd on sdi.product_id = prd.product_id
                           join sizedefinition_link sizedef on sdi.sizedefinition_id = sizedef.sizedefinition_id
                      on srg.stockdefinitionperitem_id = sdi.stockdefinitionperitem_id
                 on wre.stockreservationpergrade_id = srg.stockreservationpergrade_id
            on wokli.workorderline_id = wre.workorderline_id
       on wok.workorder_id = wokli.workorder_id
       join customer_link cu on wok.customer_link_id = cu.customer_id
       cross join languages lan
/

  CREATE OR REPLACE VIEW "V_STOCKROOMPICKLIST_GR" ("WORKORDERNUMBER", "PCODE", "STOCKROOMCODE", "UNIQUEYN", "PICKINGSEQUENCE", "AREACODE", "ROWCODE", "LOCATIONCODE", "SIZEDEFINITIONCODE", "QGRESERVATIONCODE", "ROUTENUMBER", "DAYCODE") AS 
  select
 wok.workordernumber, min(prd.code) pcode, s.code stockroomcode, wokli.codeuniquely uniqueyn, min(sl.pickingsequence) pickingsequence, sl.areacode,
 min(sl.rowcode) rowcode, min(sl.locationcode) locationcode, min(sizedef.code) sizedefinitioncode, qgReserved.Code qgreservationcode, r.routenumber, dd.code DayCode
from
 workorder wok
    left outer join route r on wok.route_id = r.route_id
, day_desc dd
, weareremployment_link we
, workorderline wokli
, workorderlinereservation wre, product_link prd, qualitygrade qgReserved, qualitygrade qgOrder
, stockroom s
, stockdefinitionperitem sdi,
  stockreservationpergrade srg
    left outer
join (stockquantity sq join stockroomlocation sl on sl.stockroomlocation_id = sq.stockroomlocation_id) on srg.stockreservationpergrade_id = sq.stockreservationpergrade_id
, sizedefinition_link sizedef, customer_link cu, languages l
where wok.weareremployment_link_id = we.weareremployment_id
and cu.customer_id = wok.customer_link_id
and wok.workorder_id = wokli.workorder_id
and wokli.requestedgrade_id = qgOrder.Qualitygrade_Id
and wokli.workorderline_id = wre.workorderline_id
and wre.stockreservationpergrade_id = srg.stockreservationpergrade_id
and s.stockroom_id = sdi.stockroom_id
and sdi.stockdefinitionperitem_id = srg.stockdefinitionperitem_id
and srg.qualitygrade_id = qgReserved.qualitygrade_id
and sdi.product_id = prd.product_id
and sdi.sizedefinition_id = sizedef.sizedefinition_id
and dd.day_id = r.drivingday_id
and l.language_id = dd.language_id
group by
  wok.workordernumber,s.code,wokli.codeuniquely,sl.areacode, --sl.pickingsequence, --sl.rowcode, sl.locationcode,  sizedef.code,
  qgReserved.Code, r.routenumber, dd.code
union
select
  wok.workordernumber, min(prd.code) pcode, s.code stockroomcode, wokli.codeuniquely uniqueyn, min(sl.pickingsequence) pickingsequence,sl.areacode,
 min(sl.rowcode) rowcode, min(sl.locationcode) locationcode, min(sizedef.code) sizedefinitioncode, qgReserved.Code qgreservationcode, r.routenumber,
 dd.code DayCode
from
  workorder wok
    left outer join route r on wok.route_id = r.route_id
, day_desc dd
, workorderline wokli
, workorderlinereservation wre, product_link prd, qualitygrade qgReserved, qualitygrade qgOrder
, stockroom s
, stockdefinitionperitem sdi,
  stockreservationpergrade srg
    left outer
join (
      stockquantity sq join stockroomlocation sl on sl.stockroomlocation_id = sq.stockroomlocation_id
          ) on srg.stockreservationpergrade_id = sq.stockreservationpergrade_id
, sizedefinition_link sizedef
, languages l
where   wok.workorder_id = wokli.workorder_id
and wokli.requestedgrade_id = qgOrder.Qualitygrade_Id
and wokli.workorderline_id = wre.workorderline_id
and wre.stockreservationpergrade_id = srg.stockreservationpergrade_id
and s.stockroom_id = sdi.stockroom_id
and sdi.stockdefinitionperitem_id = srg.stockdefinitionperitem_id
and srg.qualitygrade_id = qgReserved.qualitygrade_id
and sdi.product_id = prd.product_id
and sdi.sizedefinition_id = sizedef.sizedefinition_id
and dd.day_id = r.drivingday_id
and l.language_id = dd.language_id
group by
  wok.workordernumber,s.code,wokli.codeuniquely,sl.areacode, --sl.pickingsequence, --sl.rowcode, sl.locationcode,sizedef.code,
  qgReserved.Code, r.routenumber, dd.code
order by 2,1
/

  CREATE OR REPLACE VIEW "V_STOCKROOMTRANSACTIONS" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DEBTORNUMBER", "DEBNAME", "STREET", "ZIPCODE", "CITY", "STATE", "SICCODE", "SCANDATE", "PRODUCTCODE", "REASONCODE", "PRODUCTDESC", "REASONDESC", "WEARERNUMBER", "WEARERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "PRODUCTGROUP", "MARKETSEGMENT", "TRANSACTIONTYPE", "LANGUAGECODE", "LANGUAGE_ID", "CUSTOMERLANGUAGE_ID", "PRIMARYID", "BU_CODE", "PLANT_CODE", "PLANT_NAME", "NUMBEROFSCANS", "SIZECODE", "SIZESEQ") AS 
  select   cu.customernumber, cu.name customername, deb.customernumber debtornumber, deb.name debname,
         invad.street, invad.zipcode, invad.city, invad.state, cu.siccode,
         trunc(scan.scantimestamp) scandate, prd.code productcode, rc.code reasoncode,
         (select prde.description from product_desc prde
           where prde.product_id = prd.product_id and prde.language_id = lan.language_id) productdesc,
         (select rcd.description from reasoncode_desc rcd
           where rcd.reasoncode_id = rc.reasoncode_id and rcd.language_id = lan.language_id) reasondesc,
         wl.wearernumber wearernumber, wl.wearername wearername,
         d.departmentnumber departmentnumber, d.description departmentdesc, pg.code productgroup,
         (select ms.code from marketsegment ms
           where ms.marketsegment_id = cu.marketsegment_id) marketsegment,
         scan.transactiontype_id transactiontype, lan.code languagecode, lan.language_id,
         cu.language_id customerlanguage_id,
         nvl(scan.primaryid,
             (select ri.primaryid from raggeditem ri where ri.raggeditem_id = scan.uniqueitem_link_id)) primaryid,
         bu.code bu_code, p.code plant_code, p.name plant_name, 1 numberofscans, sd.code sizecode,
         (select prsz.sequencenumber from productsize prsz where prsz.product_id = prd.product_id
                                          and prsz.sizedefinition_id = sd.sizedefinition_id) sizeseq
from scan
     left outer join reasoncode rc on scan.reasoncode_id = rc.reasoncode_id
     left outer join weareremployment_link wl
          inner join weareremployment w
                inner join wearer we on w.wearer_id = we.wearer_id
          on wl.weareremployment_id = w.weareremployment_id
     on scan.weareremployment_link_id = wl.weareremployment_link_id
     left outer join distributionpoint_link l
          inner join department d on l.department_link_id = d.department_id
     on scan.distributionpoint_link_id = l.distributionpoint_link_id
     inner join product prd
           inner join productgroup pg on prd.productgroup_id = pg.productgroup_id
     on scan.product_link_id = prd.product_id
     inner join sizedefinition sd on scan.sizedefinition_link_id = sd.sizedefinition_id
     inner join businessunit bu
           inner join plant p on bu.plant_id = p.plant_id
     on scan.businessunit_id = bu.businessunit_id
     inner join customer cu
           inner join customer deb
                 inner join address invad on deb.invoiceaddress_id = invad.address_id
           on cu.debtor_id = deb.customer_id
     on scan.customer_link_id = cu.customer_id,
     languages lan
where nvl(d.customer_id, cu.customer_id) = cu.customer_id
      and nvl(we.customer_id, cu.customer_id) = cu.customer_id
/

  CREATE OR REPLACE VIEW "V_STOCKTAKELOSSES" ("REPORTPARAM_ID", "DATE_VALUE1", "DATE_VALUE2", "DATE_VALUE3", "DATE_VALUE4", "COUNTDATE", "BUCODE", "CUSTOMERNUMBER", "CUSTOMERNAME", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "CHARGEABLE", "LOANS", "COUNT", "DELIVERY", "PICKUP1", "PICKUP2", "PICKUP3", "PICKUP4", "PICKUP5", "SHORTAGE", "REPLACEMENTPRICE", "LANGUAGECODE") AS 
  select rp.reportparam_id,
rp.date_value1,
rp.date_value2,
rp.date_value3,
rp.date_value4,
cic.countdate,
(select bu.code from businessunit bu where bu.businessunit_id = c.defaultbusinessunit_id) bucode,
c.customernumber,
c.name customername,
p.code productcode,
(select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = l.language_id) productdesc,
sd.code sizecode,
(select coalesce(sum(rqa.quantity),0) from rentalqtyadjustment rqa where rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
        and rqa.adjustmentdate <= cic.countdate
        and rqa.origin <> 2
        and rqa.sampleitem = 'N') chargeable,
(select coalesce(sum(rqa.quantity),0) from rentalqtyadjustment rqa where rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
        and rqa.adjustmentdate <= cic.countdate
        and rqa.origin = 2) loans,
cic.count,
(case when cic.delivery = 1 then
      (select coalesce(sum(dh.amountdelivered),0) from deliveryhistory dh where dh.distributionpoint_link_id = dp.distributionpoint_id
       and dh.product_link_id = p.product_id
       and dh.sizedefinition_link_id = sd.sizedefinition_id
       and dh.finishingmethod_id = fm.finishingmethod_id
       and dh.deliverydate = (select max(bt.deliverydate) from bagtag bt where bt.deliverydate <= cic.countdate
                                      and bt.distributionpoint_id = dp.distributionpoint_id
                                      and bt.deliverydate is not null))
       else 0
  end) delivery,
(case when cic.pickup1 = 1 then
      (select sum(scl.countkeypad) from soilcountline scl, soilcount sc, bagtag bt where scl.product_link_id = p.product_id
       and scl.sizedefinition_link_id = sd.sizedefinition_id
       and scl.finishingmethod_id = fm.finishingmethod_id
       and scl.soilcount_id = sc.soilcount_id
       and sc.distributionpoint_link_id = dp.distributionpoint_id
       and sc.bagtag_id = bt.bagtag_id
       and bt.pickupdate = getpickupdate(1, cic.countdate, dp.distributionpoint_id))
       else 0
  end) pickup1,
(case when cic.pickup2 = 1 then
      (select sum(scl.countkeypad) from soilcountline scl, soilcount sc, bagtag bt where scl.product_link_id = p.product_id
       and scl.sizedefinition_link_id = sd.sizedefinition_id
       and scl.finishingmethod_id = fm.finishingmethod_id
       and scl.soilcount_id = sc.soilcount_id
       and sc.distributionpoint_link_id = dp.distributionpoint_id
       and sc.bagtag_id = bt.bagtag_id
       and bt.pickupdate = getpickupdate(2, cic.countdate, dp.distributionpoint_id))
       else 0
  end) pickup2,
(case when cic.pickup3 = 1 then
      (select sum(scl.countkeypad) from soilcountline scl, soilcount sc, bagtag bt where scl.product_link_id = p.product_id
       and scl.sizedefinition_link_id = sd.sizedefinition_id
       and scl.finishingmethod_id = fm.finishingmethod_id
       and scl.soilcount_id = sc.soilcount_id
       and sc.distributionpoint_link_id = dp.distributionpoint_id
       and sc.bagtag_id = bt.bagtag_id
       and bt.pickupdate = getpickupdate(3, cic.countdate, dp.distributionpoint_id))
       else 0
  end) pickup3,
(case when cic.pickup4 = 1 then
      (select sum(scl.countkeypad) from soilcountline scl, soilcount sc, bagtag bt where scl.product_link_id = p.product_id
       and scl.sizedefinition_link_id = sd.sizedefinition_id
       and scl.finishingmethod_id = fm.finishingmethod_id
       and scl.soilcount_id = sc.soilcount_id
       and sc.distributionpoint_link_id = dp.distributionpoint_id
       and sc.bagtag_id = bt.bagtag_id
       and bt.pickupdate = getpickupdate(4, cic.countdate, dp.distributionpoint_id))
       else 0
  end) pickup4,
(case when cic.pickup5 = 1 then
      (select sum(scl.countkeypad) from soilcountline scl, soilcount sc, bagtag bt where scl.product_link_id = p.product_id
       and scl.sizedefinition_link_id = sd.sizedefinition_id
       and scl.finishingmethod_id = fm.finishingmethod_id
       and scl.soilcount_id = sc.soilcount_id
       and sc.distributionpoint_link_id = dp.distributionpoint_id
       and sc.bagtag_id = bt.bagtag_id
       and bt.pickupdate = getpickupdate(5, cic.countdate, dp.distributionpoint_id))
       else 0
  end) pickup5,
(select coalesce(sum(dv.amount),0) from deliveryvariations dv where dv.distributionpoint_id = dp.distributionpoint_id
        and dv.product_id = p.product_id
        and dv.sizedefinition_id = sd.sizedefinition_id
        and dv.finishingmethod_id = fm.finishingmethod_id
        and dv.origin = 5
        and dv.processed = 'N'
        and dv.deliverydate <= cic.countdate) shortage,
pack_price.Replacement_Price(c.customer_id,p.product_id,sd.sizedefinition_id,fm.finishingmethod_id,rp.date_value4) replacementprice,
l.code languagecode
from customerinventorycount cic
inner join distributionpoint dp on cic.distributionpoint_id = dp.distributionpoint_id
inner join department d on dp.department_id = d.department_id
inner join customer c on d.customer_id = c.customer_id
inner join product p on cic.product_id = p.product_id
inner join sizedefinition sd on cic.sizedefinition_id = sd.sizedefinition_id
inner join finishingmethod fm on cic.finishingmethod_id = fm.finishingmethod_id
inner join productlistperdistribpoint plpd on plpd.distributionpoint_id = dp.distributionpoint_id
                                           and plpd.product_id = p.product_id
                                           and plpd.sizedefinition_id = sd.sizedefinition_id
                                           and plpd.finishingmethod_id = fm.finishingmethod_id,
languages l, reportparam rp
where (cic.countdate = rp.date_value1 or cic.countdate = rp.date_value2)
order by cic.countdate,p.code,sd.code
/

  CREATE OR REPLACE VIEW "V_STOCKTRANSACTIONS2EXPORT" ("STOCKTRANSACTION_ID", "STOCKRESERVATIONPERGRADE_ID", "TRANSACTIONDATE", "REASONCODE_ID", "TRANSACTIONTYPE_ID", "UNIQUESTOCK", "QUANTITY", "SYSTEMUSER_ID", "EXPORTED", "DELAYED", "TRANSACTIONTIMESTAMP", "FROMSTOCKROOMLOCATION_ID", "TOSTOCKROOMLOCATION_ID", "TIMESTAMP", "BUSINESSUNIT_ID", "QUALITYGRADE_ID", "STOCKROOM", "PRODUCT_ID", "SIZEDEFINITION_ID", "CUSTOMER_ID") AS 
  select st."STOCKTRANSACTION_ID",st."STOCKRESERVATIONPERGRADE_ID",st."TRANSACTIONDATE",st."REASONCODE_ID",st."TRANSACTIONTYPE_ID",st."UNIQUESTOCK",st."QUANTITY",st."SYSTEMUSER_ID",st."EXPORTED",st."DELAYED",st."TRANSACTIONTIMESTAMP",st."FROMSTOCKROOMLOCATION_ID",st."TOSTOCKROOMLOCATION_ID",st."TIMESTAMP",sr.managedbybu_id businessunit_id, srg.qualitygrade_id, sr.code stockroom,
       sdi.product_id, sdi.sizedefinition_id, sdi.customer_id
from   stocktransaction st, stockreservationpergrade srg, stockdefinitionperitem sdi, stockroom sr
where  st.exported = 'N'
and    st.delayed = 'N'
and    srg.stockreservationpergrade_id = st.stockreservationpergrade_id
and    sdi.stockdefinitionperitem_id = srg.stockdefinitionperitem_id
and    sr.stockroom_id = sdi.stockroom_id
/

  CREATE OR REPLACE VIEW "V_STOCKUTILIZATION" ("ASSIGNDATE", "CUSTOMERNUMBER", "CUSTOMERNAME", "STOCKROOMCODE", "STOCKROOMNAME", "REASONCODE", "RESASONCODEDESC", "PRODUCTCODE", "PRODUCTGROUPCODE", "PRODUCTDESC", "ISSUEGRADE_ID", "ISSUENEWGARMENT", "REQUESTEDGRADE_ID", "REQUESTEDNEWGARMENT", "QUANTITY", "LANGUAGECODE") AS 
  select
  ih.assigndate, cl.customernumber, cl.name customername, sr.code stockroomcode, sr.name stockroomname,
  rc.code reasoncode,
  (select rcd.description from reasoncode_desc rcd where rcd.reasoncode_id = rc.reasoncode_id
     and rcd.language_id = languages.language_id) resasoncodedesc,
  pl.code productcode, pl.productgroupcode,
  (select prd.description from product_desc prd where pr.product_id = prd.product_id
     and prd.language_id = languages.language_id) productdesc,
  ih.issuegrade_id, qgi.newgarment issuenewgarment, ih.requestedgrade_id, qgr.newgarment requestednewgarment,
  ih.quantity, languages.code languagecode
from
  issuehistory ih
    left outer join customer_link cl on ih.customer_link_id = cl.customer_link_id
    join stockroom sr on ih.stockroom_id = sr.stockroom_id,
  reasoncode rc, qualitygrade qgr, qualitygrade qgi,
  product_link pl
    left outer join product pr on pl.product_id = pr.product_id,
  languages
where
  ih.reasoncode_id = rc.reasoncode_id
  and ih.product_link_id = pl.product_link_id
  and ih.issuegrade_id = qgi.qualitygrade_id
  and ih.requestedgrade_id = qgr.qualitygrade_id
/

  CREATE OR REPLACE VIEW "V_STOCKVALUEFIFO_CHANGE" ("STOCKCODE", "STOCKNAME", "PRODUCTCODE", "SIZECODE", "PRODUCTDESC", "SIZEDESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "PURCHASEORDERNUMBER", "WORKORDERNUMBER", "TRANSACTIONDATE", "TRANSACTIONTYPE", "ORIGIN", "QUANTITY", "PIECEVALUE", "AMOUNT", "LANGUAGECODE") AS 
  select
  sk.code stockCode, sk.name stockName
, prd.code productCode, sz.code sizeCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( select sizedefinition_desc.description from sizedefinition_desc where sizedefinition_desc.sizedefinition_id = sz.sizedefinition_id
  and sizedefinition_desc.language_id = languages.language_id ) sizeDesc
, cu.customernumber, cu.name customerName
, skff.purchaseordernumber, skff.workordernumber
, skff.transactiondate, skff.transactiontype
, skff.origin
, skff.quantity, skff.piecevalue
, ( skff.quantity * skff.piecevalue ) Amount
, languages.code languageCode
from
  stockroom sk
, stockDefinitionPerItem ski
    left outer join customer cu on ski.customer_id = cu.customer_id
, product prd, sizedefinition sz
, stockReservationPerGrade skgr, stockValueFIFO skff
, languages
where
    sk.stockroom_id = ski.stockroom_id
and ski.product_id = prd.product_id
and ski.sizedefinition_id = sz.sizedefinition_id
and ski.stockdefinitionperitem_id = skgr.stockdefinitionperitem_id
    and skgr.stockreservationpergrade_id = skff.stockreservationpergrade_id
/

  CREATE OR REPLACE VIEW "V_STOCKVALUEFIFO_VALUE" ("STOCKCODE", "STOCKNAME", "PRODUCTCODE", "SIZECODE", "PRODUCTGROUPCODE", "PRODUCTDESC", "SIZEDESC", "PRODUCTGROUPDESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "QTYACTUALSTOCK", "QTYACTUALAMOUNT", "INVOICEAMOUNTDECIMALS", "CURRENCYCODE", "LANGUAGECODE") AS 
  select
  sk.code stockCode, sk.name stockName
, prd.code productCode, sz.code sizeCode, prdgr.code productGroupCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( select sizedefinition_desc.description from sizedefinition_desc where sizedefinition_desc.sizedefinition_id = sz.sizedefinition_id
  and sizedefinition_desc.language_id = languages.language_id ) sizeDesc
, ( select productgroup_desc.description from productgroup_desc where productgroup_desc.productgroup_id = prdgr.productgroup_id
  and productgroup_desc.language_id = languages.language_id ) productGroupDesc
, cu.customernumber, cu.name customerName
, skff.qtyactualstock qtyActualStock
, ( skff.qtyactualstock * skff.piecevalue ) qtyActualAmount
, currency.invoiceamountdecimals, currency.code currencyCode
, languages.code languageCode
from
  stockroom sk
, stockDefinitionPerItem ski
    left outer join customer cu on ski.customer_id = cu.customer_id
, product prd
    left outer join productgroup prdgr on prd.productgroup_id = prdgr.productgroup_id
, sizedefinition sz
, stockReservationPerGrade skgr, stockValueFIFO skff
, businessunit bu, plant, country, currency
, languages
where
    sk.stockroom_id = ski.stockroom_id
and ski.product_id = prd.product_id
and ski.sizedefinition_id = sz.sizedefinition_id
and ski.stockdefinitionperitem_id = skgr.stockdefinitionperitem_id
    and skgr.stockreservationpergrade_id = skff.stockreservationpergrade_id
        and skff.qtyactualstock > 0
and sk.managedbybu_id = bu.businessunit_id
    and bu.plant_id = plant.plant_id
        and plant.country_id = country.country_id
            and country.defaultcurrency_id = currency.currency_id
/

  CREATE OR REPLACE VIEW "V_STOCKVALUEPERTRTYPE" ("REPORTPARAM_ID", "SCAN_ID", "RELATEDCUSTOMER_ID", "CUSTOMEROWNED", "BUCODE", "BUDESC", "STOCKROOMCODE", "STOCKROOMNAME", "STOCKROOMBU_ID", "BUSINESSUNIT_ID", "SCANTIMESTAMP", "REASONCODE", "TRANSACTIONTYPECODE", "TRANSACTIONTYPEDESC", "PRODUCTGROUPCODE", "PRODUCTGROUPDESC", "SIZECODE", "PRODUCTCODE", "PRODUCT_ID", "SIZEDEFINITION_ID", "LANGAUGECODE", "PRICE") AS 
  select rp.reportparam_id, sc.scan_id, ui.relatedcustomer_id, ui.customerowned,
  bu.code bucode, bu.description budesc, sr.code stockroomcode, sr.name stockroomname,
  sr.managedbybu_id stockroombu_id, BU.BUSINESSUNIT_ID,
  sc.scantimestamp, rc.code reasoncode,
  sc.transactiontype_id transactiontypecode,
  (select ttd.description from transactiontype_desc ttd where ttd.transactiontype_id = tt.transactiontype_id
    and ttd.language_id = languages.language_id) transactiontypedesc,
  pg.code productgroupcode,
  (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pr.productgroup_id
    and pgd.language_id = languages.language_id) productgroupdesc,
  szl.code sizecode, pr.code productcode,
  pr.product_id, szl.sizedefinition_id,
  languages.code langaugecode,
  pack_price.Replacement_Price(rp.number_value1, pr.product_id, szl.sizedefinition_id,NULL, rp.date_value1) price
from scan sc
    left outer join reasoncode rc on sc.reasoncode_id = rc.reasoncode_id,
  uniqueitem_link uil, uniqueitem ui,
  uniqueitemfixedinfo uif
    left outer join (stockroomlocation srl
      left outer join stockroom sr on srl.stockroom_id = sr.stockroom_id)
      on uif.stockroomlocation_id = srl.stockroomlocation_id,
  businessunit bu,
  product_link prl, product pr, productgroup pg,
  sizedefinition_link szl,
  transactiontype tt,
  qualitygrade qg,
  languages, reportparam rp
where sc.uniqueitem_link_id = uil.uniqueitem_link_id
  and uil.uniqueitem_id = ui.uniqueitem_id --
  and ui.uniqueitem_id = uif.uniqueitem_id
  and ui.businessunit_id = bu.businessunit_id
--  and uif.stockroomlocation_id = srl.stockroomlocation_id --
--  and srl.stockroom_id = sr.stockroom_id
--  and bu.businessunit_id = sr.managedbybu_id
--  and sc.reasoncode_id = rc.reasoncode_id --
  and sc.product_link_id = prl.product_link_id
  and prl.product_id = pr.product_id
  and pr.productgroup_id = pg.productgroup_id
  and sc.sizedefinition_link_id = szl.sizedefinition_link_id
  and sc.transactiontype_id = tt.transactiontype_id
  and sc.qualitygrade_id = qg.qualitygrade_id --
  and sc.transactiontype_id in (10,11,12,15,16,22,23,32,33,40,41,44,50,54)
  and qg.newgarment = 'Y'
/

  CREATE OR REPLACE VIEW "V_STRAPLABEL" ("CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "LEGALNAME", "PHONENO", "CUSTOMERSTREET", "CUSTOMERZIP", "CUSTOMERCITY", "CUSTOMERSTREET2", "CUSTOMERSTATE", "CUSTOMERCOUNTY", "DELIVERYPOINT_ID", "DELIVERYPOINTCODE", "DELIVERYPOINTDESCRIPTION", "DRIVINGDAY_DESC", "ROUTENUMBER", "ROUTEDESCRIPTION", "LOADINGDOCK", "REPORTPARAM_ID", "TIMESTAMP", "COPY_NUMBER", "LANGUAGECODE", "DELPOINT_STREET", "DELPOINT_STREET2", "DELPOINT_ZIPCODE", "DELPOINT_CITY", "DELPOINT_STATE", "DELPOINT_COUNTY", "DUMMYGRP", "CU_LABELCOLOR", "SORTSTRING", "SORTPOSITION", "LOTNR", "BU_CODE", "BU_DESC", "PLANT_CODE", "PLANT_NAME", "PLANT_PHONENO", "STOPNUMBER", "LOCKERSORTGROUPNUMBER") AS 
  select c.customer_id, c.customernumber, c.name customername, c.legalname,
       c.phoneno, a.street customerstreet, a.zipcode customerzip,
       a.city customercity, a.street2 customerstreet2, a.state customerstate,
       a.county customercounty, dvp.deliverypoint_id,
       dvp.code deliverypointcode, dvp.description deliverypointdescription,
       (select dd.description
           from day_desc dd
          where dd.day_id = ro.drivingday_id
            and dd.language_id = l.language_id) drivingday_desc,
       ro.routenumber, ro.description routedescription, ro.loadingdock,
       rp.reportparam_id, rp.timestamp, rp.copy_number, l.code languagecode,
       delpoint_address.street delpoint_street,
       delpoint_address.street2 delpoint_street2,
       delpoint_address.zipcode delpoint_zipcode,
       delpoint_address.city delpoint_city,
       delpoint_address.state delpoint_state,
       delpoint_address.county delpoint_county, rp.string_value dummygrp,
       c.labelcolor cu_labelcolor, dld.sortstring, dld.sortposition, dl.code LotNr,
       bu.code bu_code, bu.description bu_desc, pl.code plant_code, pl.name plant_name,
       pl.phoneno plant_phoneno, coalesce(st.stopnumber, 0) stopnumber,
       (select lsg.description from wearerinventory wi, weareremployment we, locker lo, lockersortgroup lsg
        where wi.wearerinventory_id = dld.wearerinventory_id and we.weareremployment_id = wi.weareremployment_id
              and lo.locker_id = we.locker_id and lsg.lockersortgroup_id = lo.lockersortgroup_id) lockersortgroupnumber
from reportparam rp
     inner join deliveryloaddetail dld
           inner join deliveryload dl
                 inner join deliverypoint dvp
                       inner join customer c
                             inner join address a on c.visitaddress_id = a.address_id
                       on dvp.customer_id = c.customer_id
                       inner join address delpoint_address on dvp.deliveryaddress_id = delpoint_address.address_id
                 on dl.deliverypoint_id = dvp.deliverypoint_id
                 inner join businessunit bu
                       inner join plant pl
                             inner join routecontrol rc
                                   inner join route ro
                                         left outer join depot de on ro.depot_id = de.depot_id
                                   on rc.route_id = ro.route_id
                                   left join stop st on st.routecontrol_id = rc.routecontrol_id
                             on pl.plant_id = rc.plant_id
                       on bu.plant_id = pl.plant_id
                 on dl.businessunit_id = bu.businessunit_id
          on dld.deliveryload_id = dl.deliveryload_id
     on rp.number_value = dld.deliveryloaddetail_id --dp.distributionpoint_id
    , languages l
where rc.drivingdate = dl.deliverydate --and rp.string_value2 = l.code
      and coalesce(st.customer_link_id, c.customer_id) = c.customer_id
      and coalesce(st.deliverypoint_id, dvp.deliverypoint_id) = dvp.deliverypoint_id
/

  CREATE OR REPLACE VIEW "V_SUMMARYINVOICERECON" ("L", "NOTENUMBER", "DELIVERYDATE", "ORIGIN", "TYPE", "INVOICEHEADER_ID", "INVOICENUMBER", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "REMARK", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "SHOWONINVOICEAPPENDIX", "EXTERNALID", "PRODUCTCODE", "PRODUCTDESC", "DELIVEREDQTY", "STARTDATE", "ENDDATE", "LANGUAGECODE", "SIZEDEFINITION_ID") AS 
  select distinct 1 l,
cast(/*LEFTPAD(*/b.notenumber/*,22,' ')*/ as varchar2(255)) notenumber,b.deliverydate, b.origin,1 type, l.INVOICEHEADER_ID, ih.invoicenumber, ih.deltocustomernumber,
ih.deltocustomername, CAST(b.remark AS VARCHAR2(255))REMARK, ih.billtocustomernumber, ih.billtocustomername
, b.showoninvoiceappendix, cast(/*LEFTPAD(*/pd.externalid/*,22,' ')*/ as varchar2(255)) externalid,
p.code PRODUCTCODE, (select pd.description from product_desc pd where pd.product_id=p.product_id and pd.language_id=lan.language_id)  PRODUCTDESC, l.deliveredamount deliveredqty,
ih.startdate, ih.enddate, lan.code languagecode, l.SIZEDEFINITION_ID
from packingnote b left outer join packingnotepod pd on b.packingnote_id=pd.packingnote_id
left outer join packingnotecontainer pnc on b.packingnote_id=pnc.packingnote_id,
 packingnoteline l, product p, languages lan, invoiceheader ih
where b.packingnote_id = l.packingnote_id and b.origin in (0,1,2) and b.freeofchargereason_id is null
and l.product_id=p.product_id
and ih.invoiceheader_id=l.invoiceheader_id
and pnc.packingnotecontainer_id is null
union all
select distinct 2 l,
cast(/*LEFTPAD(*/b.notenumber/*,22,' ')*/ as varchar2(255)) notenumber,b.deliverydate, b.origin,2 type, l.INVOICEHEADER_ID, ih.invoicenumber, ih.deltocustomernumber,
ih.deltocustomername, CAST(b.remark AS VARCHAR2(255))REMARK
, ih.billtocustomernumber, ih.billtocustomername, b.showoninvoiceappendix, cast(/*LEFTPAD(*/pd.externalid/*,22,' ')*/ as varchar2(255)) externalid,
p.code PRODUCTCODE, (select pd.description from product_desc pd where pd.product_id=p.product_id and pd.language_id=lan.language_id)  PRODUCTDESC, l.deliveredamount deliveredqty,
ih.startdate, ih.enddate, lan.code languagecode, l.SIZEDEFINITION_ID
from packingnote b left outer join packingnotepod pd on b.packingnote_id=pd.packingnote_id
left outer join packingnotecontainer pnc on b.packingnote_id=pnc.packingnote_id
, packingnoteline l, product p, languages lan, invoiceheader ih
where b.packingnote_id = l.packingnote_id and b.origin = 6 and b.freeofchargereason_id is null
and l.product_id=p.product_id
and ih.invoiceheader_id=l.invoiceheader_id
and pnc.packingnotecontainer_id is null
union all
select distinct 3 l,
cast(/*LEFTPAD(*/b.notenumber/*,22,' ')*/ as varchar2(255)) notenumber,b.deliverydate, b.origin, 3 type, l.INVOICEHEADER_ID,ih.invoicenumber, ih.deltocustomernumber,
ih.deltocustomername, CAST(b.remark AS VARCHAR2(255))REMARK, ih.billtocustomernumber, ih.billtocustomername
, b.showoninvoiceappendix, cast(/*LEFTPAD(*/pd.externalid/*,22,' ')*/ as varchar2(255)) externalid,
p.code PRODUCTCODE, (select pd.description from product_desc pd where pd.product_id=p.product_id and pd.language_id=lan.language_id)  PRODUCTDESC, l.deliveredamount deliveredqty,
ih.startdate, ih.enddate, lan.code languagecode, l.SIZEDEFINITION_ID
from packingnote b left outer join packingnotepod pd on b.packingnote_id=pd.packingnote_id
left outer join packingnotecontainer pnc on b.packingnote_id=pnc.packingnote_id,
 packingnoteline l, product p, languages lan, invoiceheader ih
where b.packingnote_id = l.packingnote_id and b.origin = 3 and b.freeofchargereason_id is null
and l.product_id=p.product_id
and ih.invoiceheader_id=l.invoiceheader_id
and pnc.packingnotecontainer_id is null
union all
select distinct 4 l,
cast(/*LEFTPAD(*/b.notenumber/*,22,' ')*/ as varchar2(255)) notenumber,b.deliverydate, b.origin
, case when b.origin in (0,1,2) then 1
  when b.origin = 6 then 2
  else b.origin end type
, l.INVOICEHEADER_ID,ih.invoicenumber, ih.deltocustomernumber,
ih.deltocustomername, b.remark, ih.billtocustomernumber, ih.billtocustomername,
 b.showoninvoiceappendix, cast(/*LEFTPAD(*/pd.externalid/*,22,' ')*/ as varchar2(255)) externalid,
p.code PRODUCTCODE, (select pd.description from product_desc pd where pd.product_id=p.product_id and pd.language_id=lan.language_id)  PRODUCTDESC, pnl.deliveredamount deliveredqty,
ih.startdate, ih.enddate, lan.code languagecode, pnl.SIZEDEFINITION_ID
from packingnote b left outer join packingnotepod pd on b.packingnote_id=pd.packingnote_id
, packingnotecontainer l, packingnoteline pnl, product p, languages lan, invoiceheader ih
where b.packingnote_id = l.packingnote_id  and b.freeofchargereason_id is null
and pnl.packingnote_id=b.packingnote_id
and pnl.product_id =p.product_id
and ih.invoiceheader_id=pnl.invoiceheader_id
union all
select distinct 5 l,
cast(/*LEFTPAD(*/b.notenumber/*,22,' ')*/ as varchar2(255)) notenumber,b.deliverydate, b.origin, 4 type , l.INVOICEHEADER_ID, ih.invoicenumber, ih.deltocustomernumber,
ih.deltocustomername, CAST(b.remark AS VARCHAR2(255))REMARK, ih.billtocustomernumber, ih.billtocustomername,
 b.showoninvoiceappendix, cast(/*LEFTPAD(*/pd.externalid/*,22,' ')*/ as varchar2(255)) externalid,
p.code PRODUCTCODE, (select pd.description from product_desc pd where pd.product_id=p.product_id and pd.language_id=lan.language_id)  PRODUCTDESC, l.deliveredamount deliveredqty,
ih.startdate, ih.enddate, lan.code languagecode, l.SIZEDEFINITION_ID
from packingnote b left outer join packingnotepod pd on b.packingnote_id=pd.packingnote_id
left outer join packingnotecontainer pnc on b.packingnote_id=pnc.packingnote_id
, packingnoteline l,product p, languages lan, invoiceheader ih
where b.packingnote_id = l.packingnote_id and b.origin = 4 and b.freeofchargereason_id is null
and l.product_id=p.product_id
and ih.invoiceheader_id=l.invoiceheader_id
and pnc.packingnotecontainer_id is null
/

  CREATE OR REPLACE VIEW "V_SUMMARYSETTLEMENTSHEETS" ("ROUTENUMBER", "DRIVINGDATE", "TOTALCHARGEPREBILLED", "TOTALCHARGEPLUSADJ", "TOTALCHARGEMINUSADJ", "TOTALCHARGEUNDELIVERED", "TOTALCHARGEPAYTHISAMNT", "TOTALCODPREBILLED", "TOTALCODMINUSADJ", "TOTALCODPLUSADJ", "TOTALCODUNDELIVERED", "TOTALCODPAYTHISAMNT", "TOTALCODDELAYED", "TOTALCASHCOLLECTED", "TOTALCHARGECOLLECTIONS", "ROUTECONTROL_ID", "VOUCHERAMOUNT", "OVERAGEAMOUNT") AS 
  select
  ro.routenumber, rc.drivingdate, rc.totalchargeprebilled, rc.totalchargeplusadj, rc.totalchargeminusadj
, rc.totalchargeundelivered, rc.totalchargepaythisamnt, rc.totalcodprebilled, rc.totalcodminusadj
, rc.totalcodplusadj, rc.totalcodundelivered, rc.totalcodpaythisamnt, rc.totalcoddelayed, rc.totalcashcollected
, rc.totalchargecollections, rc.routecontrol_id, rc.voucheramount
, rc.overageamount
from
   route ro, routecontrol rc
where
    ro.route_id = rc.route_id
and rc.settlementstatus = 3
/

  CREATE OR REPLACE VIEW "V_SUMMARYUNIQUEPOOL" ("BU_CODE", "BU_DESC", "PRODUCTGROUP_CODE", "PRODUCTGROUP_DESC", "PRODUCT_CODE", "PRODUCT_DESC", "SIZE_CODE", "SIZE_DESC", "QTY", "POOLSTATUS", "FLAGGEDFORLOSS", "LANGUAGE_CODE", "LANGUAGE_ID", "SYSTEMUSER_ID") AS 
  select bu.code BU_code, bu.description BU_desc, pg.code ProductGroup_Code,
       (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pg.productgroup_id and pgd.language_id = lan.language_id) ProductGroup_Desc,
       p.code Product_Code,
       (select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = lan.language_id) Product_Desc,
       sd.code Size_Code,
       (select sdd.description from Sizedefinition_desc sdd where sdd.Sizedefinition_Id = sd.Sizedefinition_Id and sdd.language_id = lan.language_id) Size_Desc,
       count(ui.primaryid) Qty,
       case when UI.PoolItem = 0 then 1 -- Stock
       when UI.DistributionPoint_ID is not null then 3 -- At customer
       Else 2 --In laundry
       end PoolStatus,
       case when coalesce(UIL.Lossstatus, -1) in (0, 1) then 1 else 0 end FlaggedForLoss,
       lan.code Language_Code, lan.language_id, su.systemuser_id
from UniqueItem UI
     left outer join UniqueItemLoss UIL on UIL.Uniqueitem_Link_Id = UI.UniqueItem_ID and UIL.ReturnedDate = getABSMaxDate()
     inner join Product P
           inner join ProductGroup PG on PG.Productgroup_Id = P.Productgroup_Id
     on P.Product_Id = UI.Product_Id And P.UniquePoolItem = 'Y'
     inner join Sizedefinition SD on SD.Sizedefinition_Id = UI.Sizedefinition_Id
     inner join BusinessUnit BU on BU.Businessunit_Id = UI.Businessunit_Id,
     languages lan, systemuser su
where (UI.PoolItem = 0 -- Stock
	    Or UI.PoolItem = 1) -- Pool
      and bu.businessunit_id in (Select BUPU.Businessunit_Id
          from BusinessUnitsPerUsergroup BUPU, SystemUser SU
          Where BUPU.Usergroup_ID = SU.Usergroup_ID)
Group By bu.code, bu.description, pg.code, pg.productgroup_id,
       p.code, p.product_id, sd.code, sd.Sizedefinition_Id,
       case when UI.PoolItem = 0 then 1
       when UI.DistributionPoint_ID is not null then 3
       Else 2 end,
       case when coalesce(UIL.Lossstatus, -1) in (0, 1) then 1 else 0 end,
       lan.code, lan.language_id, su.systemuser_id
/

  CREATE OR REPLACE VIEW "V_SUPPLIER" ("SUPPLIERNUMBER", "NAME", "FAX", "PHONE", "EMAIL", "WEBSITE", "CREDITORNUMBER", "STREET", "ZIPCODE", "CITY", "COUNTY", "STATE", "ORDERFORMREMARK", "CODE", "DESCRIPTION", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  select /*version 2.0*/
       sup.suppliernumber, sup.name, sup.fax, sup.phone, sup.email, sup.website,
       sup.creditornumber, ads.street, ads.zipcode, ads.city, ads.county, ads.state,
       sup.orderformremark, cr.code, cr.description, sup.systemuser_id, sup.timestamp
  from supplier sup
       join address ads on sup.address_id = ads.address_id
       join currency cr on sup.currency_id = cr.currency_id
/

  CREATE OR REPLACE VIEW "V_SURVEYANALYSIS" ("BUSINESSUNITCODE", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_ID", "MARKETSEGMENTCODE", "SALESAREACODE", "SERVICETEAMCODE", "FILTERONROUTE", "REPORTPARAM_ID", "PLANTCODE", "PLANTNAME") AS 
  select bu.code businessunitcode,
  cu.customernumber, cu.name customername, cu.customer_id,
  ms.code marketsegmentcode, sa.code salesareacode, st.code serviceteamcode,
  (select count(*) from routestop rs, route r--, reportparam rp2
    where rs.customer_id = cu.customer_id
      and rs.route_id = r.route_id--      and rp2.reportparam_id = rp.reportparam_id
      and r.routenumber between rp.number_value1 and rp.number_value2) filteronroute,
  rp.reportparam_id, pl.code plantCode, pl.name plantName
from customer cu
    left outer join serviceteam st on cu.serviceteam_id = st.serviceteam_id,
  businessunit bu, marketsegment ms, salesarea sa, plant pl,
  reportparam rp
where cu.marketsegment_id = ms.marketsegment_id
  and cu.salesarea_id = sa.salesarea_id
	and bu.plant_id = pl.plant_id and pl.code = rp.string_value
  and ((rp.string_value1 = ' ' and rp.string_value2 = 'ZZZZZZ')
      or (bu.code >= rp.string_value1 and bu.code <= rp.string_value2))
	and (cu.defaultbusinessunit_id = bu.businessunit_id
	    or exists (select 1 from customeractivities ca where ca.customer_id = cu.customer_id and ca.processbusinessunit_id = bu.businessunit_id))
/

  CREATE OR REPLACE VIEW "V_SURVEYANALYSIS_DET" ("CUSTOMER_ID", "SURVEYTYPECATEGORYDESC", "QUESTIONNUMBER", "SURVEYTYPEQUESTIONDESC", "OPTION1", "OPTION2", "OPTION3", "OPTION4", "OPTION5", "SURVEYDATE", "SURVEYTPECODE", "SCORE1", "SCORE2", "SCORE3", "SCORE4", "SCORE5", "REMARK") AS 
  SELECT cst.customer_id,
  stqc.description surveytypecategorydesc,
  stq.questionnumber, stq.description surveytypequestiondesc,
  stq.option1, stq.option2, stq.option3, stq.option4, stq.option5,
  ss.surveydate, st.code surveytpecode,
  sum (CASE WHEN ss.score = 1 and (stq.option1 is not null) THEN 1 else 0 end) score1,
  sum (CASE WHEN ss.score = 2 and (stq.option2 is not null) THEN 1 else 0 end) score2,
  sum (CASE WHEN ss.score = 3 and (stq.option3 is not null) THEN 1 else 0 end) score3,
  sum (CASE WHEN ss.score = 4 and (stq.option4 is not null) THEN 1 else 0 end) score4,
  sum (CASE WHEN ss.score = 5 and (stq.option5 is not null) THEN 1 else 0 end) score5,
  ss.remark
FROM customersurveytype cst, surveytype st, surveytypequestioncategory stqc, surveytypequestion stq,
  surveyscore ss
WHERE cst.surveytype_id = st.surveytype_id
  and st.surveytype_id = stqc.surveytype_id
  and stqc.surveytypequestioncategory_id = stq.surveytypequestioncategory_id
  and stq.surveytypequestion_id = ss.surveytypequestion_id
  and cst.customer_id = ss.customer_link_id
group by cst.customer_id, stqc.description, stq.questionnumber, stq.description,
  stq.option1, stq.option2, stq.option3, stq.option4, stq.option5, ss.surveydate, ss.remark, st.code
/

  CREATE OR REPLACE VIEW "V_SURVEYFORM" ("CUSTOMERNUMBER", "CUSTOMERNAME", "STREET", "STREET2", "CITY", "STATE", "ZIPCODE", "PHONENO", "FAXNO", "BUSINESSUNITCODE", "SURVEYTYPECODE", "SURVEYTYPEDESC", "SURVEYFREQUENCY", "CONTACTPERSONNUMBER", "CONTACTPERSONNAME", "RANDOMSURVEYCONTACTPERSON", "CONTACTPERSON_ID", "EMPLOYEENUMBER", "LASTSURVEYDATE", "NEXTSURVEYDATE", "SURVEYTYPEQUESTIONCATDESC", "SURVEYTYPEQUESTIONDESC", "QUESTIONNUMBER", "OPTION1", "OPTION2", "OPTION3", "OPTION4", "OPTION5", "ROUTESTOPFREQUENCY", "REPORTPARAM_ID") AS 
  select cu.customernumber, cu.name customername,
  ad.street, ad.street2, ad.city, ad.state, ad.zipcode, cu.phoneno, cu.faxno,
  bu.code businessunitcode,
  st.code surveytypecode, st.description surveytypedesc,
  st.frequency surveyfrequency,
  cp.contactpersonnumber contactpersonnumber, cp.name contactpersonname,
	ss.randomsurveycontactperson, ss.contactperson_id,
  em.employeenumber,
  cst.lastsurveydate, cst.nextsurveydate,
  sqc.description surveytypequestioncatdesc,
  sq.description surveytypequestiondesc,
  sq.questionnumber, sq.option1, sq.option2, sq.option3, sq.option4, sq.option5,
  CAST(GET_ROUTESTOPFREQUENCY(RP.REPORTPARAM_ID, CU.CUSTOMER_ID) AS VARCHAR2(24)) routestopfrequency,
  rp.reportparam_id
from customer cu
    left outer join surveyscore ss
         left outer join contactperson cp on ss.contactperson_id = cp.contactperson_id
    on ss.customer_link_id = cu.customer_id,
    address ad, customersurveytype cst
    left outer join employee em on cst.employee_id = em.employee_id,
  surveytype st
         left outer join surveytypequestioncategory sqc
              left outer join surveytypequestion sq on sq.surveytypequestioncategory_id = sqc.surveytypequestioncategory_id
         on sqc.surveytype_id = st.surveytype_id,
         businessunit bu, reportparam rp
where cu.visitaddress_id = ad.address_id
  and cst.customer_id = cu.customer_id
  and cst.surveytype_id = st.surveytype_id
  and cu.defaultbusinessunit_id = bu.businessunit_id
/

  CREATE OR REPLACE VIEW "V_SYSTEMSETTINGS" ("LINETYPE", "DUMMYGROUP", "PLANTCODE", "PLANTNAME", "PLANT_ID", "STREET", "STREET2", "ZIPCODE", "CITY", "STATE", "GROUPNAME", "NAME", "VALUE", "DESCRIPTION", "USEDASDEFAULT", "DEFAULTALLOWED") AS 
  select 1 linetype, 1 DummyGroup
       , pl.code PlantCode, pl.name PlantName, pl.plant_id Plant_id
       , pa.street, pa.street2, pa.zipcode, pa.city, pa.state
       , ss.groupname, ss.name, ss.value, ss.description
			 , ss.usedasdefault, ss.defaultallowed
from systemsetting ss, plant pl, address pa
where ss.plant_id = pl.plant_id and pl.address_id = pa.address_id and ss.active = 'Y'
union all
select 2 linetype, 1 DummyGroup
       , pl.code PlantCode, pl.name PlantName, pl.plant_id Plant_id
       , '' street, '' street2, '' zipcode, '' city, '' state
       , ss.groupname, ss.name, ss.value, ss.description
			 , ss.usedasdefault, ss.defaultallowed
from systemsetting ss, plant pl
where ss.plant_id = pl.plant_id and ss.active = 'Y'
union all
select 3 linetype, 1 DummyGroup
       , pl.code PlantCode, pl.name PlantName, pl.plant_id Plant_id
       , '' street, '' street2, '' zipcode, '' city, '' state
       , ss.groupname, ss.name, ss.value, ss.description
			 , ss.usedasdefault, ss.defaultallowed
from systemsetting ss, plant pl
where ss.plant_id = pl.plant_id and ss.active = 'Y'
/

  CREATE OR REPLACE VIEW "V_SYSTEMUSER" ("FULLNAME", "USERNAME", "PASSWORD", "USERGROUPNAME", "USERGROUPDESCRIPTION", "LANGUAGECODE", "LANGUAGEDESCRIPTION", "ACTIVE", "REMARK", "SYSTEMUSER_ID") AS 
  SELECT SYSTEMUSER.FULLNAME, SYSTEMUSER.USERNAME, SYSTEMUSER.PASSWORD, USERGROUP.GROUPNAME, USERGROUP.DESCRIPTION, LANGUAGES.CODE, LANGUAGES.DESCRIPTION, SYSTEMUSER.ACTIVE, SYSTEMUSER.REMARK, SYSTEMUSER.SYSTEMUSER_ID
       FROM SYSTEMUSER, USERGROUP, LANGUAGES
       WHERE SYSTEMUSER.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID
and SYSTEMUSER.USERGROUP_ID = USERGROUP.USERGROUP_ID
/

  CREATE OR REPLACE VIEW "V_TAXAMOUNT" ("STATECODE", "AUTHORITYCODE", "NAME", "AMOUNT", "SALESRENTMISCTYPE", "INVOICENUMBER", "INVOICEBUSINESSUNITCODE", "INVOICEDATE", "CURRENCYCODE", "INVOICEAMOUNTDECIMALS", "PLANTNAME", "PLANTCITY", "PLANTSTREET", "PLANTZIPCODE", "PLANTSTATE", "STATECITYCOUNTYTYPE") AS 
  select
  states.code StateCode, states.taxauthoritycode authoritycode, states.name Name,
 case when il.adjustmentreason_id is null then il.amount else il.adjustedamount end Amount
, il.taxtype SalesRentMiscType--, r.drivingdate
, ih.invoicenumber, businessunit.code invoicebusinessunitCode
, ih.invoicedate, currency.code currencyCode, currency.invoiceamountdecimals
, plant.name PlantName, address.city plantcity, address.street plantStreet, address.zipcode plantZipcode
, address.state plantState, 3 StateCityCountyTYPE
from
   states, invoiceline il, currency, businessunit, plant, address , status, invoiceheader ih
	         --LEFT OUTER JOIN  routecontrol r ON ih.routecontrol_id = r.routecontrol_id
where
    il.code = states.code
and il.taxtype <>0
and ih.invoiceheader_id = il.invoiceheader_id
and ih.currency_id = currency.currency_id
and ih.invoicebusinessunit_id = businessunit.businessunit_id
and businessunit.plant_id = plant.plant_id
and plant.address_id = address.address_id
and ih.status_id = status.status_id
and status.statustype = 'IN'
and status.code = '2'
UNION ALL
select
  states.code StateCode, CITYCOUNTY.taxauthoritycode authoritycode, CITYCOUNTY.name Name
, case when il.adjustmentreason_id is null then il.amount else il.adjustedamount end Amount
, il.taxtype SalesRentMiscType--, r.drivingdate
, ih.invoicenumber, businessunit.code invoicebusinessunitCode
, ih.invoicedate, currency.code currencyCode, currency.invoiceamountdecimals
, plant.name PlantName, address.city plantcity, address.street plantStreet, address.zipcode plantZipcode
, address.state plantState, CITYCOUNTY.TYPE StateCityCountyTYPE
from
   states, CITYCOUNTY, invoiceline il, currency, businessunit, plant, address , status, invoiceheader ih
	         --LEFT OUTER JOIN  routecontrol r ON ih.routecontrol_id = r.routecontrol_id
where
    il.code = CITYCOUNTY.TAXAUTHORITYCODE
AND CITYCOUNTY.STATES_ID = STATES.STATES_ID
and il.taxtype <>0
and ih.invoiceheader_id = il.invoiceheader_id
and ih.currency_id = currency.currency_id
and ih.invoicebusinessunit_id = businessunit.businessunit_id
and businessunit.plant_id = plant.plant_id
and plant.address_id = address.address_id
and ih.status_id = status.status_id
and status.statustype = 'IN'
and status.code = '2'
/

  CREATE OR REPLACE VIEW "V_TAXDEFINITION" ("STATESCODE", "STATESNAME", "TAXGROUPCODE", "TAXGROUPDESCRIPTION", "TIMESTAMP", "SYSTEMUSER_ID") AS 
  select b.code statescode, b.name statesname, c.code taxgroupcode, c.description taxgroupdescription,
a.timestamp, a.systemuser_id
from taxdefinition a, states b, taxgroup c
where a.states_id = b.states_id
and a.taxgroup_id = c.taxgroup_id
/

  CREATE OR REPLACE VIEW "V_TEMPGARMENTASSORTMENT" ("BILLNUMBER", "BILLNAME", "BILLSTREET", "BILLZIPCODE", "BILLCITY", "BILLPHONENO", "DELNUMBER", "DELNAME", "FUNCTIONCODE", "FUNCTIONDESCRIPTION", "PRODUCTCODE", "PRODUCTDESCRIPTION", "WEAREREMPLOYMENT", "WEARERDATEACTIVE", "WEARERDATEINACTIVE", "MAXINVENTORY", "PRICEDECIMALSBILL", "AMOUNTDECIMALSBILL", "CURRENCYCODEBILL", "PRICEDECIMALSDELL", "AMOUNTDECIMALSDELL", "CURRENCYCODEDELL", "LANGUAGECODE", "STANDARDINVENTORY_ID", "WEARERFUNCTION_ID", "PRODUCT_ID") AS 
  select
  bill.customernumber billNumber, bill.name billName, address.street billstreet, address.zipcode billzipcode
, address.city billcity, bill.phoneno billphoneno, del.customernumber delNumber, del.name delName
, wef.code FunctionCode, wef.description functionDescription, prd.code ProductCode
, (select description from product_desc where prd.product_id = product_desc.product_id
  and product_desc.language_id = languages.language_id) ProductDescription, wei.weareremployment_id weareremployment
, we.dateactive WearerDateActive, we.dateinactive WearerDateInActive, sty.putinuse MaxInventory
, currency.decimals PriceDecimalsBill
, currency.invoiceamountdecimals AmountDecimalsBill, currency.code currencyCodeBill
, c.decimals PriceDecimalsDell, c.invoiceamountdecimals AmountDecimalsDell
, c.code currencyCodeDell, languages.code languageCode
, sty.standardinventory_id, wef.wearerfunction_id, sty.product_id
from
  customer bill, customer del, address
, wearerfunction wef, standardinventory sty, product prd
, wearer we, weareremployment wei, currency, currency c
, languages
where
    del.garmentrentspecification = 6
and del.customer_id = wef.customer_id
and wef.wearerfunction_id = sty.wearerfunction_id
and sty.product_id = prd.product_id
and del.customer_id = we.customer_id
and we.wearer_id = wei.wearer_id
and wei.wearerfunction_id = wef.wearerfunction_id
and bill.customer_id = del.debtor_id
and address.address_id = bill.mailaddress_id
and currency.currency_id = bill.currency_id
and c.currency_id = del.currency_id
/

  CREATE OR REPLACE VIEW "V_TESTCOSTCENTER" ("COSTCENTER_LINK_ID", "INVOICEHEADER_ID", "TOTALAMOUNTEXCLVAT") AS 
  select  cil.costcenter_link_id , il.invoiceheader_id,
       sum(cil.amount) TotalAmountExclVAT
from costcenterinvoiceline cil, invoiceline il, invoicelinetype ilt
where cil.invoiceline_id = il.invoiceline_id
      and il.invoicelinetype_id = ilt.invoicelinetype_id
      and ilt.type <> 18
      and cil.amount <> 0
group by il.invoiceheader_id, cil.costcenter_link_id
/

  CREATE OR REPLACE VIEW "V_TESTSTATEMENT" ("ARTRANSACTION_ID", "ARTRANSACTIONDATE", "DEFAULTBUSINESSUNIT_ID", "CHAIN_CODE", "STATEMENTFREQUENCY_ID", "STATEMENTLAYOUT_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "NAME", "ZIPCODE", "STREET", "CITY", "COMMONCUSTOMERUMBER", "PNNUMBER", "COMMONCUSTOMERNAME", "DEBITCREDIT", "AMOUNT", "AMOUNTEXCLVAT", "INVOICEHEADER_ID", "DELTOCUSTOMER_LINK_ID", "ARTRANSACTIONTYPE_ID", "INVOICEAMOUNTDECIMALS", "STATEMENTCUTOFFDATE") AS 
  select art.artransaction_id,
art.artransactiondate, bill.defaultbusinessunit_id,
(select ch.code from chain ch where ch.chain_id=bill.chain_id) chain_code,
cbi.statementfrequency_id, cbi.statementlayout_id, bill.customer_id, bill.customernumber, bill.name,
ad.zipcode, ad.street, ad.city,
cc.customernumber commoncustomerumber, del.pnnumber, cc.name commoncustomername,
art.debitcredit,
(case when art.debitcredit='D' then art.amount else ((-1)*art.amount) end) Amount,
(case when art.invoiceheader_id is null or tt.typenumber=2 then
            case when art.debitcredit='D'
              then  art.amount
              else ((-1)*art.amount)
            end
           else
             case when art.debitcredit='D'
               then coalesce((select ih.totalamountexclvat from invoiceheader ih where art.invoiceheader_id=ih.invoiceheader_id),0)
               else coalesce((select ((-1)*ih.totalamountexclvat) from invoiceheader ih where art.invoiceheader_id=ih.invoiceheader_id),0) end
           end) AmountExclVAT,
art.invoiceheader_id, art.deltocustomer_link_id, tt.artransactiontype_id
, (select cur.invoiceamountdecimals from currency cur where bill.currency_id = cur.currency_id) invoiceamountdecimals
, coalesce(cbi.statementcutoffdate, GETABSMINDATE()) statementcutoffdate
from customerbillinginfo cbi, customer bill, artransaction art,
artransactiontype tt, customer del, customer cc, address ad
where cbi.customer_id=del.debtor_id
and art.billtocustomer_link_id=bill.customer_id
and bill.customer_id=del.debtor_id
and art.artransactiontype_id=tt.artransactiontype_id
and art.closingtransaction_id is null
and coalesce(art.deltocustomer_link_id, art.billtocustomer_link_id) = del.customer_id
and coalesce(del.commoncustomer_id, del.customer_id) = cc.customer_id
and coalesce(bill.invoiceaddress_id, bill.visitaddress_id) = ad.address_id
and art.artransactiondate > coalesce(cbi.statementcutoffdate, GETABSMINDATE())
/

  CREATE OR REPLACE VIEW "V_THEORETICALWEIGHTCOMPARISON" ("LINETYPE", "CUSTOMERNUMBER", "CUSTOMER_ID", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "WEIGHINGCATCODE", "WEIGHINGCATDESC", "CLEANWEIGHT", "SOILWEIGHT", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "THEORETICALWEIGHT", "AMOUNTDELIVERED", "CALCULATEDWEIGHT", "WEIGHINGCATEGORY_ID", "DEPARTMENT_LINK_ID", "LANGUAGECODE", "REPORTPARAM_ID", "REALWEIGHTCLEAN", "REALWEIGHTSOIL", "SYSTEMSETTINGVALUE", "PLANTCODE", "PLANTNAME") AS 
  select v.linetype,
  v.customernumber, v.customer_id, v.customerName
, v.departmentnumber, v.departmentDesc, v.WeighingCatCode
, v.WeighingCatDesc, sum(v.cleanweight) cleanweight, sum(v.soilweight) soilweight
, v.ProductCode, v.ProductDesc, v.SizeCode, v.theoreticalweight
, sum(v.amountdelivered) amountdelivered, sum(v.CalculatedWeight) CalculatedWeight
, v.weighingcategory_id, v.department_link_id, v.LanguageCode
, v.reportparam_id, v.RealWeightClean, v.RealWeightSoil
, cast(ss.value as numeric) systemsettingValue
, pla.code PlantCode, pla.name PlantName
from  (
      select distinct
      1 linetype, c.customernumber, c.customer_id, c.name customerName
      , case when rp.string_value4 = 'true' then delk.departmentnumber else 0 end departmentnumber
      , case when rp.string_value4 = 'true' then delk.description else ' ' end departmentDesc
      , (select wc.code from weighingcategory wc where wc.weighingcategory_id = prd.weighingcategory_id) WeighingCatCode
      , (select weighingcategory_desc.description from weighingcategory_desc where weighingcategory_desc.weighingcategory_id = prd.weighingcategory_id
         and weighingcategory_desc.language_id = lan.language_id) WeighingCatDesc
      , 0 cleanweight, 0 soilweight
      , case when rp.string_value3 = 'true' then prd.code else ' ' end ProductCode
      , case when rp.string_value3 = 'true' then (select product_desc.description from product_desc where product_desc.product_id = prd.product_id
        and product_desc.language_id = lan.language_id) else ' ' end ProductDesc
      , case when rp.string_value3 = 'true' then sz.code else ' ' end SizeCode
      , dh.deliveryhistory_id, -1 weighinghistory_id
      , case when rp.string_value3 = 'true' then coalesce(ps.theoreticalweight, 0) else 0 end theoreticalweight
      , case when rp.string_value3 = 'true' then coalesce(dh.amountdelivered, 0) else 0 end amountdelivered
			, coalesce((ps.theoreticalweight * coalesce(dh.amountdelivered,0)),0) CalculatedWeight
      , dh.deliverydate weighingdate, prd.weighingcategory_id
      , case when rp.string_value4 = 'true' then delk.department_link_id else 0 end department_link_id
      , rp.reportparam_id, -1 number_value, 0 RealWeightClean, 0 RealWeightSoil
      , rp.string_value3, rp.string_value4,  dh.processbusinessunit_id bu_id,lan.code LanguageCode
      from  deliveryhistory dh, product prd
      , productsize ps, sizedefinition sz, department_link delk
      , reportparam rp, customer c, languages lan
      where dh.customer_link_id = c.customer_id  and  prd.product_id = ps.product_id and dh.sizedefinition_link_id = sz.sizedefinition_id
            and prd.product_id = dh.product_link_id and dh.sizedefinition_link_id = ps.sizedefinition_id
            and dh.department_link_id = delk.department_link_id
            and coalesce(dh.packindication, 1) in (1, 2)
            and prd.weighingcategory_id = rp.number_value1
            and dh.deliverydate >= rp.date_value1
            and dh.deliverydate <= rp.date_value2
            and (rp.number_value9 = c.defaultbusinessunit_id
                 or rp.number_value9 in (select ca.processbusinessunit_id from customeractivities ca where ca.customer_id = c.customer_id))
            and c.customernumber >= rp.number_value2
            and c.customernumber <= rp.number_value4
            and delk.departmentnumber >= rp.number_value6
            and delk.departmentnumber <= rp.number_value8
            and ((rp.string_value4 = 'true' and rp.number_value = delk.department_link_id)
                or
                (rp.string_value4 <> 'true' and rp.number_value = c.customernumber))
      union all
      select
      2 linetype, culk.customernumber, culk.customer_id, culk.name customerName
      , case when rp.string_value4 = 'true' then delk.departmentnumber else 0 end departmentnumber
      , case when rp.string_value4 = 'true' then delk.description else ' ' end departmentDesc
      , weigcat.code WeighingCatCode
      , (select weighingcategory_desc.description from weighingcategory_desc where weighingcategory_desc.weighingcategory_id = weigcat.weighingcategory_id
         and weighingcategory_desc.language_id = lan.language_id) WeighingCatDesc
      , weighis.cleanweight, weighis.soilweight
      , ' ' ProductCode, ' ' ProductDesc, ' ' SizeCode, -1 deliveryhistory_id
      , weighis.weighinghistory_id, 0 theoreticalweight, 0 amountdelivered, 0 CalculatedWeight
      , weighis.weighingdate, weigcat.weighingcategory_id
      , case when rp.string_value4 = 'true' then delk.department_link_id else 0 end department_link_id
      , rp.reportparam_id, rp.number_value, rp.number_value3 RealWeightClean, rp.number_value5 RealWeightSoil
      , rp.string_value3, rp.string_value4, weighis.processbusinessunit_id bu_id,lan.code LanguageCode
      from
        customer culk, department_link delk
      , weighingcategory weigcat,  weighinghistory weighis, reportparam rp, languages lan
      where rp.number_value1 = weigcat.weighingcategory_id and
          weighis.customer_link_id = culk.customer_id
      and weighis.department_link_id = delk.department_link_id
      and weighis.weighingcategory_link_id = weigcat.weighingcategory_id
            and (rp.number_value9 = culk.defaultbusinessunit_id
                 or rp.number_value9 in (select ca.processbusinessunit_id from customeractivities ca where ca.customer_id = culk.customer_id))
            and weighis.weighingdate >= rp.date_value1
            and weighis.weighingdate <= rp.date_value2
            and culk.customernumber >= rp.number_value2
            and culk.customernumber <= rp.number_value4
            and delk.departmentnumber >= rp.number_value6
            and delk.departmentnumber <= rp.number_value8
            and ((rp.string_value4 = 'true' and rp.number_value = delk.department_link_id)
                or
                (rp.string_value4 <> 'true' and rp.number_value = culk.customernumber))
) v,  businessunit bu, plant pla, systemsetting ss
where v.bu_id = bu.businessunit_id
and bu.plant_id = pla.plant_id
and ss.plant_id = pla.plant_id
and ss.name = 'WEIGHTDECIMALSMANUALINPUT'
group by pla.code, pla.name, v.LanguageCode, v.linetype, ss.value
, v.reportparam_id, v.string_value3, v.string_value4
, v.customernumber, v.customer_id, v.customerName
, v.departmentnumber
, v.departmentDesc
, v.department_link_id
, v.WeighingCatCode, v.WeighingCatDesc, v.weighingcategory_id
, v.ProductCode
, v.ProductDesc
, v.SizeCode
, v.theoreticalweight
, v.RealWeightClean, v.RealWeightSoil
, v.number_value
/

  CREATE OR REPLACE VIEW "V_THEORETICALWEIGHT_AUX" ("LINETYPE", "CUSTOMERNUMBER", "CUSTOMER_ID", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "WEIGHINGCATCODE", "WEIGHINGCATDESC", "CLEANWEIGHT", "SOILWEIGHT", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "DELIVERYHISTORY_ID", "WEIGHINGHISTORY_ID", "THEORETICALWEIGHT", "AMOUNTDELIVERED", "CALCULATEDWEIGHT", "WEIGHINGDATE", "WEIGHINGCATEGORY_ID", "DEPARTMENT_LINK_ID", "SYSTEMSETTINGVALUE", "PLANTCODE", "PLANTNAME", "LANGUAGECODE", "REPORTPARAM_ID", "NUMBER_VALUE", "REALWEIGHTCLEAN", "REALWEIGHTSOIL", "STRING_VALUE3", "STRING_VALUE4") AS 
  select 1 linetype,
  c.customernumber, c.customer_id, c.name customerName
, case when rp.string_value4 = 'true' then delk.departmentnumber else 0 end departmentnumber
, case when rp.string_value4 = 'true' then delk.description else ' ' end departmentDesc
, (select wc.code from weighingcategory wc where wc.weighingcategory_id = prd.weighingcategory_id) WeighingCatCode
, (select weighingcategory_desc.description from weighingcategory_desc where weighingcategory_desc.weighingcategory_id = prd.weighingcategory_id
   and weighingcategory_desc.language_id = lan.language_id) WeighingCatDesc
, 0 cleanweight, 0 soilweight
, case when rp.string_value3 = 'true' then prd.code else ' ' end ProductCode
, case when rp.string_value3 = 'true' then (select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = lan.language_id) else ' ' end ProductDesc
, case when rp.string_value3 = 'true' then sz.code else ' ' end SizeCode
, dh.deliveryhistory_id, -1 weighinghistory_id
, coalesce(ps.theoreticalweight, 0) theoreticalweight, coalesce(dh.amountdelivered, 0) amountdelivered
, coalesce((ps.theoreticalweight * coalesce(dh.amountdelivered,0)),0) CalculatedWeight
, dh.deliverydate weighingdate, prd.weighingcategory_id
, case when rp.string_value4 = 'true' then delk.department_link_id else 0 end department_link_id
, (select cast(ss.value as numeric) from systemsetting ss where
    pla.plant_id = ss.plant_id and ss.name = 'WEIGHTDECIMALSMANUALINPUT') systemsettingValue
, pla.code PlantCode, pla.name PlantName, lan.code LanguageCode
, rp.reportparam_id, -1 number_value, 0 RealWeightClean, 0 RealWeightSoil
, rp.string_value3, rp.string_value4
from  deliveryhistory dh, product prd
, productsize ps, sizedefinition sz, department_link delk
, businessunit bu, plant pla, languages lan
, reportparam rp, customer c
where dh.customer_link_id = c.customer_id  and  prd.product_id = ps.product_id and dh.sizedefinition_link_id = sz.sizedefinition_id
      and prd.product_id = dh.product_link_id and dh.sizedefinition_link_id = ps.sizedefinition_id
      and dh.department_link_id = delk.department_link_id
      and dh.processbusinessunit_id = bu.businessunit_id and bu.plant_id = pla.plant_id
      and coalesce(dh.packindication, 1) in (1, 2)
      and prd.weighingcategory_id = rp.number_value1
      and dh.deliverydate >= rp.date_value1
      and dh.deliverydate <= rp.date_value2
      and (c.defaultbusinessunit_id = rp.number_value9
           or rp.number_value9 in (select ca.processbusinessunit_id from customeractivities ca where ca.customer_id = c.customer_id))
      and c.customernumber >= rp.number_value2
      and c.customernumber <= rp.number_value4
      and delk.departmentnumber >= rp.number_value6
      and delk.departmentnumber <= rp.number_value8
      and ((rp.string_value4 = 'true')
          or
          (rp.string_value4 <> 'true' and rp.number_value = c.customernumber))
union all
select 2 linetype,
  culk.customernumber, culk.customer_id, culk.name customerName
, case when rp.string_value4 = 'true' then delk.departmentnumber else 0 end departmentnumber
, case when rp.string_value4 = 'true' then delk.description else ' ' end departmentDesc
, weigcat.code WeighingCatCode
, (select weighingcategory_desc.description from weighingcategory_desc where weighingcategory_desc.weighingcategory_id = weigcat.weighingcategory_id
   and weighingcategory_desc.language_id = lan.language_id) WeighingCatDesc
, weighis.cleanweight, weighis.soilweight
, null ProductCode, null ProductDesc, null SizeCode, -1 deliveryhistory_id
, weighis.weighinghistory_id, 0 theoreticalweight, 0 amountdelivered, 0 CalculatedWeight
, weighis.weighingdate, weigcat.weighingcategory_id
, case when rp.string_value4 = 'true' then delk.department_link_id else 0 end department_link_id
, ( select cast(ss.value as numeric) from systemsetting ss where
    pla.plant_id = ss.plant_id and ss.name = 'WEIGHTDECIMALSMANUALINPUT') systemsettingValue
, pla.code PlantCode, pla.name PlantName, lan.code LanguageCode
, rp.reportparam_id, rp.number_value, rp.number_value3 RealWeightClean, rp.number_value5 RealWeightSoil
, rp.string_value3, rp.string_value4
from
  customer culk, department_link delk
, weighingcategory weigcat,  weighinghistory weighis, reportparam rp
, businessunit bu, plant pla, languages lan
where rp.number_value1 = weigcat.weighingcategory_id and
    weighis.customer_link_id = culk.customer_id
and weighis.department_link_id = delk.department_link_id
and weighis.weighingcategory_link_id = weigcat.weighingcategory_id
      and weighis.processbusinessunit_id = bu.businessunit_id and bu.plant_id = pla.plant_id
      and (culk.defaultbusinessunit_id = rp.number_value9
           or rp.number_value9 in (select ca.processbusinessunit_id from customeractivities ca where ca.customer_id = culk.customer_id))
      and weighis.weighingdate >= rp.date_value1
      and weighis.weighingdate <= rp.date_value2
      and culk.customernumber >= rp.number_value2
      and culk.customernumber <= rp.number_value4
      and delk.departmentnumber >= rp.number_value6
      and delk.departmentnumber <= rp.number_value8
      and ((rp.string_value4 = 'true' and rp.number_value = delk.department_link_id)
          or
          (rp.string_value4 <> 'true' and rp.number_value = culk.customernumber))
/

  CREATE OR REPLACE VIEW "V_TOBERETURNEDGARMENTS" ("LINETYPE", "PRODUCTCODE", "SIZECODE", "PRODUCTDESC", "FUNCTIONCODE", "FUNCTIONDESC", "EMPLOYMENT", "BANKLOCKER", "GARMENTDISPENSER", "IDCODE", "SEQNUMBER", "ISSUEDATE", "WASHNO", "REPAIRNO", "REWASHNO", "FLAG", "UIFLAGCODE", "MODIFICATIONS", "REASON", "CUSTOMEROWNED", "FREEEXTRAGARMENT", "LASTSCANDATE", "LASTOUTSCANDATE", "FINMETHOD", "FINMETHODDESC", "INVOICEAMOUNTDECIMALS", "RESIDUALVALUE", "FLAGCODE", "STAY", "STAYNR", "STATUS", "ADMINNUMBER", "COSTCENTERCODE", "COSTCENTERDESC", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "PROCESSBUSINESSUNIT_ID", "CITY", "DEFAULTBUSINESSUNIT_ID", "WEARERNUMBER", "WEARERNAME", "WEARERSEARCHNAME", "WEARERACTIVE", "WEARERDATEACTIVE", "WEARERDATEINACTIVE", "LANGUAGECODE", "LANGUAGE_ID", "CUSTOMERLANGUAGE_ID", "SUBSTITUTEYN", "QUALITYGRADE_CODE", "LEASEWEEKS", "SPLITUPCODE", "INVOICENUMBER", "INVOICEHEADER_ID", "INVOICEDATE") AS 
  select 1 linetype,
 prd.code productcode
, sz.code sizecode
, ( SELECT description FROM product_desc pd WHERE pd.product_id = prd.product_id
  AND pd.LANGUAGE_ID = languages.LANGUAGE_ID) productdesc
, wf.code functioncode, wf.description functiondesc, wey.sequencenumber employment
, cast(CONCATENATEWITHBLANK(lk.bank, lk.locker) as varchar2(255)) banklocker
, gd.code garmentdispenser, uq.primaryid idcode, uq.idcodesequencenumber seqnumber
, uqfx.lastissuedate issuedate, uq.washestotal washno, uq.repairstotal repairno, uq.rewashtotal rewashno
, ( SELECT COUNT(*) FROM UNIQUEITEMFLAG uf WHERE uf.UNIQUEITEM_ID = uq.UNIQUEITEM_ID) flag
, ( SELECT max(fg.code) FROM UNIQUEITEMFLAG uf, flag fg WHERE uf.UNIQUEITEM_ID = uq.UNIQUEITEM_ID and uf.flag_id = fg.flag_id) uiflagcode
, ( select count(*) from uniqueitemmodification um where um.uniqueitem_id=uq.uniqueitem_id) modifications
, r.code reason, uq.customerowned, uqnp.freeextragarment
, trunc(uq.lastscandate) lastscandate, trunc(uq.lastoutscandate) lastoutscandate
, fm.code finmethod
, (select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
     and fmd.language_id = languages.language_id) finmethoddesc
,currency.invoiceamountdecimals, coalesce(uq.residualvalueAmount, uq.residualvalue) residualvalue, flag.code flagcode
, ( SELECT cast(sty.description as varchar2(10)) FROM stay_desc sty WHERE sty.stay_id = stay.stay_id
  AND sty.LANGUAGE_ID = languages.LANGUAGE_ID) stay, stay.staynr
, ( SELECT description FROM status_desc sd WHERE sd.status_id = uq.status_id
  AND sd.LANGUAGE_ID = languages.LANGUAGE_ID) status
, we.customeremployeenumber adminnumber,  cc.code costcentercode, cc.description costcenterdesc
, de.departmentnumber, de.description departmentdesc
, cu.customernumber, cu.name customername,
 coalesce((select max(ca.processbusinessunit_id) from productgroup pg,  customeractivities ca
where prd.productgroup_id=pg.productgroup_id and pg.activity_id=ca.activity_id and ca.customer_id=cu.customer_id),cu.defaultbusinessunit_id) processbusinessunit_id,
address.city, cu.defaultbusinessunit_id
, we.wearernumber, we.fullname wearername, we.searchname wearersearchname
, GETDATEDIFF(trunc(sysdate), we.dateactive)*GETDATEDIFF(we.dateinactive, trunc(sysdate)) weareractive
, we.dateactive WearerDateActive, we.dateinactive WearerDateInactive
, languages.code languagecode, languages.language_id, cu.language_id customerlanguage_id
, case when uq.substituteforproduct_id is null then 'N' else 'Y' end substituteYN
, coalesce(qg.code, '') QualityGrade_Code
, uq.leaseweeks leaseWeeks
,ih.splitupcode
,ih.invoicenumber
,ih.invoiceheader_id
,ih.invoicedate
from
  customer cu
, wearer we
    left outer join flag on we.flag_id = flag.flag_id
, weareremployment wey
    left outer join garmentdispenser gd on gd.garmentdispenser_id = wey.garmentdispenser_id
    left outer join locker lk on lk.locker_id = wey.locker_id
    left outer join wearerfunction wf on wey.wearerfunction_id = wf.wearerfunction_id
, uniqueitemnonpool uqnp
, uniqueitem uq
    left outer join stay on uq.stay_id = stay.stay_id
    left outer join finishingmethod fm on fm.finishingmethod_id = uq.finishingmethod_id
, uniqueitemfixedinfo uqfx
    left outer join qualitygrade qg on uqfx.qualitygrade_id=qg.qualitygrade_id
, reasoncode r
, product prd,  sizedefinition sz
, distributionpoint dip, department de, costcenter cc
, address, currency, languages, invoiceheader ih
where
    cu.customer_id = we.customer_id
and we.wearer_id = wey.wearer_id
and wey.weareremployment_id = uqnp.weareremployment_id
and uqnp.uniqueitem_id = uq.uniqueitem_id
    and uq.uniqueitem_id = uqfx.uniqueitem_id
        and uqfx.reasoncode_id = r.reasoncode_id
and uq.product_id = prd.product_id
and uq.sizedefinition_id = sz.sizedefinition_id
and wey.distributionpoint_id = dip.distributionpoint_id
    and dip.department_id = de.department_id
        and dip.costcenter_id = cc.costcenter_id
and cu.mailaddress_id = address.address_id
and cu.currency_id = currency.currency_id
and ih.deltocustomernumber = cu.customernumber
and coalesce(ih.splitupcode,cc.code)= cc.code
AND (we.dateactive <= trunc(sysdate))
Union all
select 2 linetype,
  coalesce(subtPrd.Code, prd.code) productcode
, coalesce(subtSz.Code, sz.code) sizecode
, coalesce(
  ( SELECT description FROM product_desc WHERE product_desc.product_id = subtPrd.product_id
  AND product_desc.LANGUAGE_ID = languages.LANGUAGE_ID )
  , ( SELECT description FROM product_desc pd WHERE pd.product_id = prd.product_id
  AND pd.LANGUAGE_ID = languages.LANGUAGE_ID)
  ) productdesc
, wf.code functioncode, wf.description functiondesc, wey.sequencenumber employment
, cast(CONCATENATEWITHBLANK(lk.bank, lk.locker) as varchar2(255)) banklocker
, gd.code garmentdispenser, null idcode, nuq.sequencenumber seqnumber
, nuq.issuedate issuedate, null washno, null repairno, null rewashno, null flag, null uiflagcode
, ( SELECT count(*) FROM wearerinventorymodification wim WHERE wim.wearerinventory_id = weinv.wearerinventory_id) modifications
, rc.code reason, 'N' customerowned, 'X' freeextragarment
, null lastscandate, null lastoutscandate
, fm.code finmethod
, (select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
     and fmd.language_id = languages.language_id) finmethoddesc
, currency.invoiceamountdecimals, 0 residualvalue, flag.code flagcode
, null stay, null staynr, null status
, we.customeremployeenumber adminnumber, cc.code costcentercode, cc.description costcenterdesc
, de.departmentnumber, de.description departmentdesc
, cu.customernumber, cu.name customername,
coalesce((select max(ca.processbusinessunit_id) from productgroup pg,  customeractivities ca
where prd.productgroup_id=pg.productgroup_id and pg.activity_id=ca.activity_id and ca.customer_id=cu.customer_id),cu.defaultbusinessunit_id) processbusinessunit_id,
 address.city, cu.defaultbusinessunit_id
, we.wearernumber, we.fullname wearername, we.searchname wearersearchname
, GETDATEDIFF(trunc(sysdate), we.dateactive)*GETDATEDIFF(we.dateinactive, trunc(sysdate)) weareractive
, we.dateactive WearerDateActive, we.dateinactive WearerDateInactive
, languages.code languagecode, languages.language_id, cu.language_id customerlanguage_id
, case when nuq.substituteforproduct_id is null then 'N' else 'Y' end substituteYN
, '' QualityGrade_Code
, null leaseWeeks
,ih.splitupcode
,ih.invoicenumber
,ih.invoiceheader_id
,ih.invoicedate
from
  customer cu
, wearer we
    left outer join flag  on we.flag_id = flag.flag_id
, weareremployment wey
    left outer join garmentdispenser gd on gd.garmentdispenser_id = wey.garmentdispenser_id
    left outer join locker lk on lk.locker_id = wey.locker_id
    left outer join wearerfunction wf on wey.wearerfunction_id = wf.wearerfunction_id
, wearerinventory weinv
, nonuniqueitem nuq
    left outer join product subtPrd on subtPrd.product_id = nuq.substituteforproduct_id
    left outer join sizedefinition subtSz on subtSz.Sizedefinition_Id = nuq.substituteforsizedefinition_id
, product prd, sizedefinition sz, finishingmethod fm
, reasoncode rc
, distributionpoint dip, department de, costcenter cc
, address, currency, languages, invoiceheader ih
where
    cu.customer_id = we.customer_id
and we.wearer_id = wey.wearer_id
and wey.weareremployment_id = weinv.weareremployment_id
AND weinv.product_id = prd.product_id
and weinv.sizedefinition_id = sz.sizedefinition_id
and weinv.finishingmethod_id = fm.finishingmethod_id
and weinv.wearerinventory_id = nuq.wearerinventory_id
    and nuq.reasoncode_id = rc.reasoncode_id
and wey.distributionpoint_id = dip.distributionpoint_id
    and dip.department_id = de.department_id
        and dip.costcenter_id = cc.costcenter_id
and cu.mailaddress_id = address.address_id
    and cu.currency_id = currency.currency_id
    and ih.deltocustomernumber = cu.customernumber
and coalesce(ih.splitupcode,cc.code) = cc.code
AND (we.dateactive <= trunc(sysdate))
Union all --20013161 Show also garments that need to be replaced or returned.
select 3 linetype,
 prd.code productcode
, sz.code sizecode
, ( SELECT description FROM product_desc pd WHERE pd.product_id = prd.product_id
  AND pd.LANGUAGE_ID = languages.LANGUAGE_ID) productdesc
, wf.code functioncode, wf.description functiondesc, wey.sequencenumber employment
, cast(CONCATENATEWITHBLANK(lk.bank, lk.locker) as varchar2(255)) banklocker
, gd.code garmentdispenser, uq.primaryid idcode, uq.idcodesequencenumber seqnumber
, uqfx.lastissuedate issuedate, uq.washestotal washno, uq.repairstotal repairno, uq.rewashtotal rewashno
, ( SELECT COUNT(*) FROM UNIQUEITEMFLAG uf, automaticflag af WHERE uf.UNIQUEITEM_ID = uq.UNIQUEITEM_ID and af.flag_id = uf.flag_id
           and uf.startdate <= trunc(sysdate) and af.automaticflag_id in (12, 4, 5, 7, 2)) flag
, ( SELECT max(fg.code) FROM UNIQUEITEMFLAG uf, flag fg, automaticflag af WHERE uf.UNIQUEITEM_ID = uq.UNIQUEITEM_ID and uf.flag_id = fg.flag_id and af.flag_id = uf.flag_id
           and uf.startdate <= trunc(sysdate) and af.automaticflag_id in (12, 4, 5, 7, 2)) uiflagcode
, ( select count(*) from uniqueitemmodification um where um.uniqueitem_id=uq.uniqueitem_id) modifications
, r.code reason, uq.customerowned, uqnp.freeextragarment
, trunc(uq.lastscandate) lastscandate, trunc(uq.lastoutscandate) lastoutscandate
, fm.code finmethod
, (select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
     and fmd.language_id = languages.language_id) finmethoddesc
,currency.invoiceamountdecimals, coalesce(uq.residualvalueAmount, uq.residualvalue) residualvalue, flag.code flagcode
, ( SELECT cast(sty.description as varchar2(10)) FROM stay_desc sty WHERE sty.stay_id = stay.stay_id
  AND sty.LANGUAGE_ID = languages.LANGUAGE_ID) stay, stay.staynr
, ( SELECT description FROM status_desc sd WHERE sd.status_id = uq.status_id
  AND sd.LANGUAGE_ID = languages.LANGUAGE_ID) status
, we.customeremployeenumber adminnumber,  cc.code costcentercode, cc.description costcenterdesc
, de.departmentnumber, de.description departmentdesc
, cu.customernumber, cu.name customername,
 coalesce((select max(ca.processbusinessunit_id) from productgroup pg,  customeractivities ca
where prd.productgroup_id=pg.productgroup_id and pg.activity_id=ca.activity_id and ca.customer_id=cu.customer_id),cu.defaultbusinessunit_id) processbusinessunit_id,
address.city, cu.defaultbusinessunit_id
, we.wearernumber, we.fullname wearername, we.searchname wearersearchname
, (-1)*GETDATEDIFF(trunc(sysdate), we.dateactive)*GETDATEDIFF(we.dateinactive, trunc(sysdate)) weareractive--select only active wearers
, we.dateactive WearerDateActive, we.dateinactive WearerDateInactive
, languages.code languagecode, languages.language_id, cu.language_id customerlanguage_id
, case when uq.substituteforproduct_id is null then 'N' else 'Y' end substituteYN
, coalesce(qg.code, '') QualityGrade_Code
, uq.leaseweeks leaseWeeks
,ih.splitupcode
,ih.invoicenumber
,ih.invoiceheader_id
,ih.invoicedate
from
  customer cu
, wearer we
    left outer join flag on we.flag_id = flag.flag_id
, weareremployment wey
    left outer join garmentdispenser gd on gd.garmentdispenser_id = wey.garmentdispenser_id
    left outer join locker lk on lk.locker_id = wey.locker_id
    left outer join wearerfunction wf on wey.wearerfunction_id = wf.wearerfunction_id
, uniqueitemnonpool uqnp
, uniqueitem uq
    left outer join stay on uq.stay_id = stay.stay_id
    left outer join finishingmethod fm on fm.finishingmethod_id = uq.finishingmethod_id
, uniqueitemfixedinfo uqfx
    left outer join qualitygrade qg on uqfx.qualitygrade_id = qg.qualitygrade_id
, reasoncode r
, product prd,  sizedefinition sz
, distributionpoint dip, department de, costcenter cc
, address, currency, languages, invoiceheader ih
where
    cu.customer_id = we.customer_id
and we.wearer_id = wey.wearer_id
and wey.weareremployment_id = uqnp.weareremployment_id
and uqnp.uniqueitem_id = uq.uniqueitem_id
    and uq.uniqueitem_id = uqfx.uniqueitem_id
        and uqfx.reasoncode_id = r.reasoncode_id
and uq.product_id = prd.product_id
and uq.sizedefinition_id = sz.sizedefinition_id
and wey.distributionpoint_id = dip.distributionpoint_id
    and dip.department_id = de.department_id
        and dip.costcenter_id = cc.costcenter_id
and cu.mailaddress_id = address.address_id
and cu.currency_id = currency.currency_id
and exists (SELECT 1 FROM UNIQUEITEMFLAG uf, automaticflag af WHERE uf.UNIQUEITEM_ID = uq.UNIQUEITEM_ID and af.flag_id = uf.flag_id
           and uf.startdate <= trunc(sysdate) and af.automaticflag_id in (12, 4, 5, 7, 2) )
and ih.deltocustomernumber = cu.customernumber
and coalesce(ih.splitupcode,cc.code)= cc.code
AND (we.dateactive <= trunc(sysdate))
/

  CREATE OR REPLACE VIEW "V_TOBEVISITEDCUST" ("ROUTENUMBER", "ROUTEDESCRIPTION", "DRIVINGDATE", "DRIVINGDAY_ID", "STOPNUMBER", "STOPSTATUS", "CUSTOMERNUMBER", "CUSTOMERNAME", "STREET", "CITY", "ZIPCODE", "HOUSENUMBER") AS 
  select  r.routenumber, r.description routedescription, rc.drivingdate,R.DRIVINGDAY_ID, s.stopnumber,s.status stopstatus, c.customernumber, c.name customername,
 a.street , a.city, a.zipcode , a.housenumber
from  stop s
      left join (routestop rs
  join route r
    on rs.route_id = r.route_id) on s.ROUTESTOP_ID = RS.ROUTESTOP_ID,
    routecontrol rc,  customer c, address a
where s.routecontrol_id = rc.routecontrol_id
and s.customer_link_id = c.customer_id
and c.visitaddress_id = a.address_id
AND s.STATUS in (0,3)
/

  CREATE OR REPLACE VIEW "V_TOTALSALES" ("SUM_AMOUNT", "MONTHNUMBER", "YEARNUMBER", "DELTOCUSTOMER_LINK_ID", "SYSTEMUSER_ID", "BUSINESSUNIT_ID", "ROUTEID") AS 
  select  sum(a.amount) sum_amount,
month(a.artransactiondate) monthnumber, year(a.artransactiondate) yearnumber,
a.deltocustomer_link_id,
s.systemuser_id,
bu.businessunit_id,coalesce(a.route_id, -1) routeid
from artransaction a, artransactiontype at, businessunitsperusergroup bu, usergroup u, systemuser s
where  a.artransactiontype_id = at.artransactiontype_id
and at.typenumber in (1,3)
and a.debitcredit = 'D'
and a.businessunit_id = bu.businessunit_id
and bu.usergroup_id = u.usergroup_id
and s.usergroup_id = u.usergroup_id
and (a.parentartransaction_id is null or
             a.parentartransaction_id = a.artransaction_id)
group by
month(a.artransactiondate), year(a.artransactiondate),
a.deltocustomer_link_id,
s.systemuser_id,
bu.businessunit_id,coalesce(a.route_id, -1)
/

  CREATE OR REPLACE VIEW "V_TRANSACTIONREGISTER" ("LINETYPE", "ARTRANSACTIONDATE", "DEBITCREDIT", "REMITIDENTIFICATION", "AMOUNT", "BUCODE", "CUSTOMERNUMBER", "CUSTOMERNAME", "ARTRANSACTIONTYPECODE", "PREDEFINED", "ARTRANSACTIONTYPEDESC", "LANGUAGECODE", "USERNAME", "TIMESTAMP", "REMARK") AS 
  select 0 linetype, art.artransactiondate, art.debitcredit, art.remitidentification, art.amount
, (select bu.code from businessunit bu where art.businessunit_id = bu.businessunit_id) BUCode
, dc.customernumber, dc.name customername
, artt.code artransactiontypecode, artt.predefined
, (select arttd.description from artransactiontype_desc arttd where art.artransactiontype_id = arttd.artransactiontype_id and arttd.language_id=lan.language_id) artransactiontypedesc
, lan.code LanguageCode
, s.username
, art.timestamp, art.remark
from artransaction art
               left outer join customer dc on art.deltocustomer_link_id = dc.customer_id
     , artransactiontype artt, languages lan, systemuser s
where artt.artransactiontype_id = art.artransactiontype_id
and art.systemuser_id = s.systemuser_id
union all
select 1 linetype, art.artransactiondate, art.debitcredit, art.remitidentification, art.amount
, (select bu.code from businessunit bu where art.businessunit_id = bu.businessunit_id) BUCode
, bc.customernumber, bc.name customername
, artt.code artransactiontypecode, artt.predefined
, (select arttd.description from artransactiontype_desc arttd where art.artransactiontype_id = arttd.artransactiontype_id and arttd.language_id=lan.language_id) artransactiontypedesc
, lan.code LanguageCode
, s.username
, art.timestamp, art.remark
from artransaction art, customer bc, artransactiontype artt, languages lan, systemuser s
where artt.artransactiontype_id = art.artransactiontype_id AND art.billtocustomer_link_id = bc.customer_id
and art.systemuser_id = s.systemuser_id
/

  CREATE OR REPLACE VIEW "V_TRANSPORTUNITSTICKER" ("SHIPMENTLIST_ID", "SHIPMENTLISTNUMBER", "COMPLETIONDATE", "TRANSPORTUNITNUMBER", "BUCODE", "BUDESCR", "BUSTREET", "BUZIPCODE", "BUCITY", "BUCOUNTRY", "NOITEMS", "STOCKCODE", "STOCKNAME", "STSTREET", "STCITY", "STZIPCODE", "STCOUNTRY") AS 
  select sl.shipmentlist_id,sl.shipmentlistnumber, to_char(sl.completiondate,'YYYY-MM-DD') completiondate,
 sll.transportunitnumber,
bu.code bucode, bu.description budescr,
pladdr.street bustreet, pladdr.zipcode buzipcode, pladdr.city bucity, co.description bucountry,
coalesce((select sum(b.quantityshipped) from shipmentlistline b where b.shipmentlist_id=sl.shipmentlist_id
and b.transportunitnumber=sll.transportunitnumber),0)noitems,
st.code stockcode, st.name stockname,
staddress.street ststreet, staddress.city stcity, staddress.zipcode stzipcode,
( select stcountry.description from businessunit stbu, plant stplant, country stcountry
where  st.managedbybu_id=stbu.businessunit_id  and stbu.plant_id=stplant.plant_id
 and stplant.country_id=stcountry.country_id)stcountry
from shipmentlist sl,shipmentlistline sll,  businessunit bu, plant pl,
 address pladdr, country co,stockroom st, address staddress
 where  sl.supplyingstockroom_id=st.stockroom_id
 and sl.shiptobusinessunit_id=bu.businessunit_id
 and sll.shipmentlist_id=sl.shipmentlist_id
 and bu.plant_id=pl.plant_id
 and pl.address_id=pladdr.address_id
 and pl.country_id=co.country_id
 and st.deliveryaddress_id=staddress.address_id
union all
select slor.shipmentlistor_id,
       slor.shipmentlistnumber,
       to_char(slor.completiondate,'YYYY-MM-DD') completiondate,
       sllor.transportunitnumber,
       bu1.code bucode,
       bu1.description budescr,
       pladdr1.street bustreet,
       pladdr1.zipcode buzipcode,
       pladdr1.city bucity,
       co1.description bucountry,
       coalesce((select sum(b1.quantityshipped)
                  from shipmentlistlineor b1
                 where b1.shipmentlistor_id = slor.shipmentlistor_id
                 and b1.transportunitnumber=sllor.transportunitnumber),
                0) noitems,
       shipbybu1.code stockcode,
       shipbybu1.description stockname,
       shipbypladdress1.street ststreet,
       shipbypladdress1.city stcity,
       shipbypladdress1.zipcode stzipcode,
       (select c.description
          from country c
         where c.country_id = shipbypl1.country_id) stcountry
  from shipmentlistor     slor,
       shipmentlistlineor sllor,
       businessunit     bu1,
       plant            pl1,
       address          pladdr1,
       country          co1,
       businessunit     shipbybu1,
       plant            shipbypl1,
       address          shipbypladdress1
 where slor.shipmentlistor_id = sllor.shipmentlistor_id
   and slor.shipbybusinessunit_id= shipbybu1.businessunit_id
   and shipbybu1.plant_id = shipbypl1.plant_id
   and slor.shiptobusinessunit_id = bu1.businessunit_id
   and bu1.plant_id = pl1.plant_id
   and pl1.address_id = pladdr1.address_id
   and pl1.country_id = co1.country_id
   and shipbypl1.address_id = shipbypladdress1.address_id
/

  CREATE OR REPLACE VIEW "V_TREATMENTCERTIFICATION" ("TREATMENTTYPE_CODE", "SCANTIMESTAMP", "TREATMENTDATE", "PRIMARYID", "BATCHNUMBER", "PRODUCT_CODE", "PRODUCT_DESC", "SIZE_CODE", "CHARACTERISTIC_ID", "LENGTH", "DATATYPE", "DECIMALS", "NUMBERVALUE", "STRINGVALUE", "DATEVALUE", "SCIENTIFICVALUE", "CHARACTERISTIC_DESC", "SEQUENCENUMBER", "CUSTOMERNAME", "CUSTOMERNUMBER", "DAYNUMBER", "ROUTENUMBER", "REPORTPARAM_ID", "LANGUAGE_CODE") AS 
  SELECT TT.CODE TREATMENTTYPE_CODE, SC.SCANTIMESTAMP, TS.TREATMENTDATE, SC.PRIMARYID, SC.BATCHNUMBER
       , (SELECT PL.CODE FROM PRODUCT_LINK PL WHERE SC.PRODUCT_LINK_ID = PL.PRODUCT_LINK_ID ) PRODUCT_CODE
       , (SELECT PLD.DESCRIPTION FROM PRODUCT_LINK_DESC PLD WHERE SC.PRODUCT_LINK_ID = PLD.PRODUCT_LINK_ID AND PLD.LANGUAGE_ID = LAN.LANGUAGE_ID) PRODUCT_DESC
       , (SELECT SDL.CODE FROM SIZEDEFINITION_LINK SDL WHERE SC.SIZEDEFINITION_LINK_ID = SDL.SIZEDEFINITION_LINK_ID ) SIZE_CODE
       , TSC.CHARACTERISTIC_ID, CH.LENGTH, CH.DATATYPE, CH.DECIMALS
       , TSC.NUMBERVALUE, TSC.STRINGVALUE, TSC.DATEVALUE, CASTNUMBERASVARCHARWITHFORMAT(TSC.NUMBERVALUE, '9.99999999EEEE') SCIENTIFICVALUE
       , (SELECT CHD.DESCRIPTION FROM CHARACTERISTIC_DESC CHD WHERE TSC.CHARACTERISTIC_ID = CHD.CHARACTERISTIC_ID AND CHD.LANGUAGE_ID = LAN.LANGUAGE_ID) CHARACTERISTIC_DESC
       , (SELECT MAX(CTL.SEQUENCENUMBER) FROM CHARACTERISTICSTEMPLINE CTL WHERE CTL.CHARACTERISTIC_ID = CH.CHARACTERISTIC_ID AND CTL.CHARACTERISTICSTEMPLATE_ID = TT.CHARACTERISTICSTEMPLATE_ID) SEQUENCENUMBER
       , (SELECT CU.NAME FROM CUSTOMER_LINK CU WHERE SC.CUSTOMER_LINK_ID=CU.CUSTOMER_LINK_ID) CUSTOMERNAME
       , (SELECT CU.CUSTOMERNUMBER FROM CUSTOMER_LINK CU WHERE SC.CUSTOMER_LINK_ID=CU.CUSTOMER_LINK_ID) CUSTOMERNUMBER
       , (SELECT D.DAYNUMBER FROM ROUTE RO, DAY D WHERE SC.ROUTE_ID = RO.ROUTE_ID AND RO.DRIVINGDAY_ID = D.DAY_ID) DAYNUMBER
       , (SELECT RO.ROUTENUMBER FROM ROUTE RO WHERE SC.ROUTE_ID = RO.ROUTE_ID) ROUTENUMBER
       , RP.REPORTPARAM_ID, LAN.CODE LANGUAGE_CODE
FROM SCAN SC, TREATMENTTYPE TT, TREATMENTSCAN TS, TREATMENTSCANCHARACTERISTIC TSC, CHARACTERISTIC CH
     , REPORTPARAM RP, LANGUAGES LAN
WHERE RP.NUMBER_VALUE1 = SC.CUSTOMER_LINK_ID AND RP.NUMBER_VALUE2 = TS.TREATMENTTYPE_ID AND
      RP.DATE_VALUE1 = TS.TREATMENTDATE AND TS.TREATMENTTYPE_ID = TT.TREATMENTTYPE_ID AND
      TSC.CHARACTERISTIC_ID = CH.CHARACTERISTIC_ID AND TSC.TREATMENTSCAN_ID = TS.TREATMENTSCAN_ID AND
      (RP.STRING_VALUE IS NULL OR (RP.STRING_VALUE IS not NULL and RP.STRING_VALUE = SC.BATCHNUMBER)) AND
      TS.SCAN_ID = SC.SCAN_ID
/

  CREATE OR REPLACE VIEW "V_TRUCK" ("PLANTCODE", "PLANTNAME", "CODE", "DESCRIPTION", "DEFAULTDRIVERNUMBER", "DEFAULTDRIVERNAME", "MAXCONTAINERS", "MAXWEIGHT", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  SELECT PLANT.CODE, PLANT.NAME, TRUCK.CODE, TRUCK.DESCRIPTION, EMPLOYEE.EMPLOYEENUMBER,
 EMPLOYEE.NAME, TRUCK.MAXCONTAINERS, TRUCK.MAXWEIGHT, TRUCK.SYSTEMUSER_ID, TRUCK.TIMESTAMP
       FROM TRUCK
       LEFT OUTER JOIN EMPLOYEE ON (TRUCK.DEFAULTDRIVER_ID = EMPLOYEE.EMPLOYEE_ID),
        PLANT
       WHERE TRUCK.PLANT_ID = PLANT.PLANT_ID
/

  CREATE OR REPLACE VIEW "V_TRUCKMOVELIST" ("TRANSACTIONDATE", "FROMTRUCK", "FROMTRUCKDESC", "TOTRUCK", "TOTRUCKDESC", "UNIQUESTOCK", "PRODCODE", "PRODUCTDESCRIPTION", "SIZECODE", "QUANTITY", "USERGROUP_ID", "LANGUAGECODE") AS 
  SELECT
st.transactiondate transactiondate,tr1.code fromtruck, tr1.description fromtruckdesc,
tr2.code totruck, tr2.description totruckdesc,
st.uniquestock uniquestock,
p.code prodcode,
(SELECT A.DESCRIPTION FROM PRODUCT_DESC A WHERE A.PRODUCT_ID = p.PRODUCT_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
sd.code sizecode,  st.quantity quantity,bug.usergroup_id usergroup_id,LANGUAGES.CODE languagecode
FROM stocktransaction st, truck tr1, truck tr2, stockroomlocation sl1, stockroomlocation sl2,
stockreservationpergrade srg,stockdefinitionperitem sdi, product p, sizedefinition sd,
stockroom s1, stockroom s2,
businessunit bu1,businessunit bu2, plant pl,businessunitsperusergroup bug,LANGUAGES
where st.fromstockroomlocation_id=sl1.stockroomlocation_id
and sl1.stockroomlocation_id=tr1.stockroomlocation_id
and st.tostockroomlocation_id=sl2.stockroomlocation_id
and sl2.stockroomlocation_id=tr2.stockroomlocation_id
and st.stockreservationpergrade_id=srg.stockreservationpergrade_id
and srg.stockdefinitionperitem_id=sdi.stockdefinitionperitem_id
and sl1.stockroom_id=s1.stockroom_id
and s1.managedbybu_id=bu1.businessunit_id
and bu1.plant_id=pl.plant_id
and sl2.stockroom_id=s2.stockroom_id
and s2.managedbybu_id=bu2.businessunit_id
and bu2.plant_id=pl.plant_id
and bug.businessunit_id=bu1.businessunit_id and bug.businessunit_id=bu2.businessunit_id
and sdi.product_id=p.product_id
and sdi.sizedefinition_id=sd.sizedefinition_id
and st.transactiontype_id=493
and st.quantity>0
/

  CREATE OR REPLACE VIEW "V_TRUCKRELOAD" ("TRUCKRELOAD_ID", "VARIATIONQTYINTRUCK", "TRUCK_ID", "TRUCKCODE", "PRODUCT_ID", "PRODUCT_CODE", "RECORDPASSIVESTOCK", "DELIVERFROMONPICKLISTRSC", "SIZEDEFINITION_ID", "SIZEDEFINITION_CODE") AS 
  select
trl.truckreload_id,
trl.variationqtyintruck,
tr.truck_id,
tr.code truckcode, pr.product_id as product_id,
pr.code as product_code, pr.recordpassivestock,
pr.deliverfromonpicklistrsc, sd.sizedefinition_id,  sd.code as sizedefinition_code
from truckreload trl, truck tr, product pr, sizedefinition sd
where tr.truck_id = trl.truck_id
and pr.product_id = trl.product_id
and sd.sizedefinition_id = trl.sizedefinition_id
and trl.baselinetype=0
/

  CREATE OR REPLACE VIEW "V_TRUCKSAFETYCHECKS" ("CHECKDATE", "PLANTCODE", "PLANTNAME", "SYSTEMUSER_ID", "TRUCKCODE", "TRUCKDESC", "ROUTENUMBER", "ROUTECONTROL_ID", "DRIVINGDATE", "STARTMILEAGE", "ENDMILEAGE", "SAFETYREMARKS", "SAFETYCODE", "SAFETYDESC", "NEEDSMAINTENANCE") AS 
  select distinct -- can be multiplied by bu.businessunit_id
  sfhy.checkdate, plant.code plantCode, plant.name plantName, SY.SYSTEMUSER_ID
, truck.code truckCode, truck.description truckDesc
, route.routenumber
, rc.routecontrol_id, rc.drivingdate, rc.startmileage, rc.endmileage, rc.safetyremarks
, sf.code safetyCode, sf.description safetyDesc, sfhy.needsmaintenance
from
  safetycheckhistory sfhy, safetycheck sf, truck, route, routecontrol rc, plant
, BUSINESSUNIT BU, BUSINESSUNITSPERUSERGROUP BUUSRG, USERGROUP UG, SYSTEMUSER SY
where
    sfhy.safetycheck_id = sf.safetycheck_id
and sfhy.checkdate = rc.drivingdate
and sfhy.truck_id = truck.truck_id
    and truck.code = rc.truckcode
        and truck.plant_id = rc.plant_id
        and rc.route_id = route.route_id
            and rc.plant_id = plant.plant_id
AND PLANT.PLANT_ID= BU.PLANT_ID
    AND BU.BUSINESSUNIT_ID = BUUSRG.BUSINESSUNIT_ID
            AND BUUSRG.USERGROUP_ID = UG.USERGROUP_ID
                AND UG.USERGROUP_ID = SY.USERGROUP_ID
/

  CREATE OR REPLACE VIEW "V_TRUCKSAFETYCHECKSDUE" ("PLANTCODE", "PLANTNAME", "SYSTEMUSER_ID", "TRUCKCODE", "TRUCKDESC", "SAFETYCODE", "SAFETYDESC", "SCHEDULEDDATE", "FREQUENCY", "LASTCHECKDATE") AS 
  select distinct -- can be multiplied by bu.businessunit_id
  plant.code plantCode, plant.name plantName, SY.SYSTEMUSER_ID
, truck.code truckCode, truck.description truckDesc
, sf.code safetyCode, sf.description safetyDesc
, sftk.lastcheckdate + ( case sf.frequency
                                      when 0 then 1
                                           when 1 then 7
                                                when 2 then 30 end ) ScheduledDate
, sf.frequency, sftk.lastcheckdate
from
  safetycheckpertruck sftk, safetycheck sf, truck, plant
, BUSINESSUNIT BU, BUSINESSUNITSPERUSERGROUP BUUSRG, USERGROUP UG, SYSTEMUSER SY
where
    sftk.safetycheck_id = sf.safetycheck_id
and sftk.lastcheckdate + ( case sf.frequency
                                      when 0 then 1
                                           when 1 then 7
                                                when 2 then 30
                                   end ) < trunc(sysdate)
and sftk.truck_id = truck.truck_id
    and truck.plant_id = plant.plant_id
AND PLANT.PLANT_ID= BU.PLANT_ID
    AND BU.BUSINESSUNIT_ID = BUUSRG.BUSINESSUNIT_ID
            AND BUUSRG.USERGROUP_ID = UG.USERGROUP_ID
                AND UG.USERGROUP_ID = SY.USERGROUP_ID
/

  CREATE OR REPLACE VIEW "V_TRUCKSTOCKMANAGEMENT" ("LINETYPE", "TRUCKCODE", "TRUCKDESC", "LASTCHECKDATE", "TRANSACTIONTYPE_ID", "TRANSACTIONDATE", "STOCKTRANSACTIONQTY", "PRODUCTCODE", "SIZECODE", "PRODUCTDESC", "SIZEDESC", "DIRECTION", "ORIGIN", "STANDARDTRUCKLOAD", "CHECK1", "CHECK2", "CHECK3", "LANGUAGECODE", "NOTENUMBER", "STANDARDSTOCK", "CURRENTSTOCK", "CUSTOMERNUMBER") AS 
  SELECT 1 LINETYPE --RAGGED FROM TRUCK STOCK
, TR.CODE TRUCKCODE, TR.DESCRIPTION TRUCKDESC, TR.LASTCHECKDATE
, ST.TRANSACTIONTYPE_ID, ST.TRANSACTIONDATE, ST.QUANTITY STOCKTRANSACTIONQTY
, PR.CODE PRODUCTCODE, SD.CODE SIZECODE
, (SELECT PRD.DESCRIPTION FROM PRODUCT_DESC PRD WHERE PRD.PRODUCT_ID = PR.PRODUCT_ID AND PRD.LANGUAGE_ID = LAN.LANGUAGE_ID) PRODUCTDESC
, (SELECT SDD.DESCRIPTION FROM SIZEDEFINITION_DESC SDD WHERE SDD.SIZEDEFINITION_ID = SD.SIZEDEFINITION_ID AND SDD.LANGUAGE_ID = LAN.LANGUAGE_ID ) SIZEDESC
, '-' DIRECTION
, '4RG' ORIGIN
, (SELECT COALESCE(SLS.STANDARDTRUCKLOAD, SLP.STANDARDTRUCKLOAD) FROM STANDARDLOCATIONPERPRODUCT SLP, STANDARDLOCATIONPERSIZE SLS
 WHERE SLP.STANDARDLOCATIONPERPRODUCT_ID = SLS.STANDARDLOCATIONPERPRODUCT_ID(+) AND SLS.SIZEDEFINITION_ID(+) = SD.SIZEDEFINITION_ID
 AND SLP.STOCKROOMLOCATION_ID = TR.STOCKROOMLOCATION_ID AND SLP.PRODUCT_ID=PR.PRODUCT_ID) STANDARDTRUCKLOAD
, COALESCE((SELECT MAX(1) FROM ROUTECONTROL RC1, PACKINGNOTE PN1
WHERE RC1.TRUCKCODE = TR.CODE AND PN1.ROUTECONTROL_ID = RC1.ROUTECONTROL_ID
AND RC1.DRIVINGDATE = (SELECT MAX(RC4.DRIVINGDATE) FROM ROUTECONTROL RC4 WHERE RC4.TRUCKCODE = TR.CODE AND RC4.DRIVINGDATE <= SYSDATE)
AND PN1.STATUS_ID NOT IN (SELECT ST1.STATUS_ID FROM STATUS ST1 WHERE ST1.STATUSTYPE = 'PN' AND ST1.CODE IN ('30','40'))), 0) CHECK1
, COALESCE((SELECT MAX(1) FROM ROUTECONTROL RC2, WORKORDER WO2
WHERE RC2.TRUCKCODE = TR.CODE AND WO2.ROUTECONTROL_ID = RC2.ROUTECONTROL_ID AND WO2.ORIGIN = 10
AND RC2.DRIVINGDATE = (SELECT MAX(RC5.DRIVINGDATE) FROM ROUTECONTROL RC5 WHERE RC5.TRUCKCODE = TR.CODE AND RC5.DRIVINGDATE <= SYSDATE)
AND WO2.STATUS_ID NOT IN (SELECT ST2.STATUS_ID FROM STATUS ST2 WHERE ST2.STATUSTYPE = 'MO' AND ST2.CODE IN ('30','40'))) , 0) CHECK2
, COALESCE((SELECT MAX(1) FROM ROUTECONTROL RC3, WORKORDER WO3
WHERE RC3.TRUCKCODE = TR.CODE AND WO3.ROUTECONTROL_ID = RC3.ROUTECONTROL_ID AND WO3.ORIGIN = 6
AND RC3.DRIVINGDATE = (SELECT MAX(RC6.DRIVINGDATE) FROM ROUTECONTROL RC6 WHERE RC6.TRUCKCODE = TR.CODE AND RC6.DRIVINGDATE <= SYSDATE)
AND WO3.STATUS_ID NOT IN (SELECT ST3.STATUS_ID FROM STATUS ST3 WHERE ST3.STATUSTYPE = 'WO' AND ST3.CODE IN ('30','40'))) , 0) CHECK3
, LAN.CODE LANGUAGECODE
, -1 NOTENUMBER, 0 STANDARDSTOCK, 0 CURRENTSTOCK
, -1 CUSTOMERNUMBER
FROM TRUCK TR, PRODUCT PR, SIZEDEFINITION SD, STOCKTRANSACTION ST,
     STOCKRESERVATIONPERGRADE SRG, STOCKDEFINITIONPERITEM SDI, LANGUAGES LAN
WHERE (TR.STOCKROOMLOCATION_ID = ST.FROMSTOCKROOMLOCATION_ID OR TR.STOCKROOMLOCATION_ID = ST.TOSTOCKROOMLOCATION_ID)
AND ST.STOCKRESERVATIONPERGRADE_ID = SRG.STOCKRESERVATIONPERGRADE_ID AND SRG.STOCKDEFINITIONPERITEM_ID = SDI.STOCKDEFINITIONPERITEM_ID AND SDI.PRODUCT_ID = PR.PRODUCT_ID AND SDI.SIZEDEFINITION_ID = SD.SIZEDEFINITION_ID
AND ST.TRANSACTIONTYPE_ID = 444
UNION ALL
SELECT 2 LINETYPE --PACKING NOTE STOCK TRANSACTIONS
, TR.CODE TRUCKCODE, TR.DESCRIPTION TRUCKDESC, TR.LASTCHECKDATE
, ST.TRANSACTIONTYPE_ID, ST.TRANSACTIONDATE, ST.QUANTITY STOCKTRANSACTIONQTY
, PR.CODE PRODUCTCODE, SD.CODE SIZECODE
, (SELECT PRD.DESCRIPTION FROM PRODUCT_DESC PRD WHERE PRD.PRODUCT_ID = PR.PRODUCT_ID AND PRD.LANGUAGE_ID = LAN.LANGUAGE_ID) PRODUCTDESC
, (SELECT SDD.DESCRIPTION FROM SIZEDEFINITION_DESC SDD WHERE SDD.SIZEDEFINITION_ID = SD.SIZEDEFINITION_ID AND SDD.LANGUAGE_ID = LAN.LANGUAGE_ID ) SIZEDESC
, CASE WHEN ST.TRANSACTIONTYPE_ID IN (405,406,414) THEN '+'
ELSE '-'
END DIRECTION
, '1PN' ORIGIN
, (SELECT COALESCE(SLS.STANDARDTRUCKLOAD, SLP.STANDARDTRUCKLOAD) FROM STANDARDLOCATIONPERPRODUCT SLP, STANDARDLOCATIONPERSIZE SLS
 WHERE SLP.STANDARDLOCATIONPERPRODUCT_ID = SLS.STANDARDLOCATIONPERPRODUCT_ID(+) AND SLS.SIZEDEFINITION_ID(+) = SD.SIZEDEFINITION_ID
 AND SLP.STOCKROOMLOCATION_ID = TR.STOCKROOMLOCATION_ID AND SLP.PRODUCT_ID=PR.PRODUCT_ID) STANDARDTRUCKLOAD
, COALESCE((SELECT MAX(1) FROM ROUTECONTROL RC1, PACKINGNOTE PN1
WHERE RC1.TRUCKCODE = TR.CODE AND PN1.ROUTECONTROL_ID = RC1.ROUTECONTROL_ID
AND RC1.DRIVINGDATE = (SELECT MAX(RC4.DRIVINGDATE) FROM ROUTECONTROL RC4 WHERE RC4.TRUCKCODE = TR.CODE AND RC4.DRIVINGDATE <= SYSDATE)
AND PN1.STATUS_ID NOT IN (SELECT ST1.STATUS_ID FROM STATUS ST1 WHERE ST1.STATUSTYPE = 'PN' AND ST1.CODE IN ('30','40'))), 0) CHECK1
, COALESCE((SELECT MAX(1) FROM ROUTECONTROL RC2, WORKORDER WO2
WHERE RC2.TRUCKCODE = TR.CODE AND WO2.ROUTECONTROL_ID = RC2.ROUTECONTROL_ID AND WO2.ORIGIN = 10
AND RC2.DRIVINGDATE = (SELECT MAX(RC5.DRIVINGDATE) FROM ROUTECONTROL RC5 WHERE RC5.TRUCKCODE = TR.CODE AND RC5.DRIVINGDATE <= SYSDATE)
AND WO2.STATUS_ID NOT IN (SELECT ST2.STATUS_ID FROM STATUS ST2 WHERE ST2.STATUSTYPE = 'MO' AND ST2.CODE IN ('30','40'))) , 0) CHECK2
, COALESCE((SELECT MAX(1) FROM ROUTECONTROL RC3, WORKORDER WO3
WHERE RC3.TRUCKCODE = TR.CODE AND WO3.ROUTECONTROL_ID = RC3.ROUTECONTROL_ID AND WO3.ORIGIN = 6
AND RC3.DRIVINGDATE = (SELECT MAX(RC6.DRIVINGDATE) FROM ROUTECONTROL RC6 WHERE RC6.TRUCKCODE = TR.CODE AND RC6.DRIVINGDATE <= SYSDATE)
AND WO3.STATUS_ID NOT IN (SELECT ST3.STATUS_ID FROM STATUS ST3 WHERE ST3.STATUSTYPE = 'WO' AND ST3.CODE IN ('30','40'))) , 0) CHECK3
, LAN.CODE LANGUAGECODE
, PN.NOTENUMBER NOTENUMBER, PNL.STANDARDAMOUNT STANDARDSTOCK, PNL.DELIVEREDAMOUNT CURRENTSTOCK
, (SELECT CU.CUSTOMERNUMBER FROM DISTRIBUTIONPOINT DP, DEPARTMENT DEP, CUSTOMER CU WHERE DP.DISTRIBUTIONPOINT_ID=PN.DISTRIBUTIONPOINT_ID AND DEP.DEPARTMENT_ID = DP.DEPARTMENT_ID AND CU.CUSTOMER_ID = DEP.CUSTOMER_ID) CUSTOMERNUMBER
FROM TRUCK TR, PRODUCT PR, SIZEDEFINITION SD, STOCKTRANSACTION ST,
     STOCKRESERVATIONPERGRADE SRG, STOCKDEFINITIONPERITEM SDI, LANGUAGES LAN,
     PACKINGNOTESTOCKTRANSACTION PNST, PACKINGNOTELINE PNL, PACKINGNOTE PN
WHERE (TR.STOCKROOMLOCATION_ID = ST.FROMSTOCKROOMLOCATION_ID OR TR.STOCKROOMLOCATION_ID = ST.TOSTOCKROOMLOCATION_ID)
AND ST.STOCKRESERVATIONPERGRADE_ID = SRG.STOCKRESERVATIONPERGRADE_ID AND SRG.STOCKDEFINITIONPERITEM_ID = SDI.STOCKDEFINITIONPERITEM_ID AND SDI.PRODUCT_ID = PR.PRODUCT_ID AND SDI.SIZEDEFINITION_ID = SD.SIZEDEFINITION_ID
AND ST.TRANSACTIONTYPE_ID IN (405,406,414,415,416,422,423,424,450,453,454)
AND ST.STOCKTRANSACTION_ID = PNST.STOCKTRANSACTION_ID AND PNST.PACKINGNOTELINE_ID = PNL.PACKINGNOTELINE_ID
AND PN.PACKINGNOTE_ID = PNL.PACKINGNOTE_ID
UNION ALL
SELECT 3 LINETYPE --SALES NOTE OR MOUNTING ORDERS STOCK TRANSACTIONS
, TR.CODE TRUCKCODE, TR.DESCRIPTION TRUCKDESC, TR.LASTCHECKDATE
, ST.TRANSACTIONTYPE_ID, ST.TRANSACTIONDATE, ST.QUANTITY STOCKTRANSACTIONQTY
, PR.CODE PRODUCTCODE, SD.CODE SIZECODE
, (SELECT PRD.DESCRIPTION FROM PRODUCT_DESC PRD WHERE PRD.PRODUCT_ID = PR.PRODUCT_ID AND PRD.LANGUAGE_ID = LAN.LANGUAGE_ID) PRODUCTDESC
, (SELECT SDD.DESCRIPTION FROM SIZEDEFINITION_DESC SDD WHERE SDD.SIZEDEFINITION_ID = SD.SIZEDEFINITION_ID AND SDD.LANGUAGE_ID = LAN.LANGUAGE_ID ) SIZEDESC
, CASE WHEN ST.TRANSACTIONTYPE_ID IN (405,406,414) THEN '+'
ELSE '-'
END DIRECTION
, CASE WHEN WO.ORIGIN = 6
THEN '2SN'
ELSE CASE WHEN WO.ORIGIN = 10
THEN '3MO'
END
END ORIGIN
, (SELECT COALESCE(SLS.STANDARDTRUCKLOAD, SLP.STANDARDTRUCKLOAD) FROM STANDARDLOCATIONPERPRODUCT SLP, STANDARDLOCATIONPERSIZE SLS
 WHERE SLP.STANDARDLOCATIONPERPRODUCT_ID = SLS.STANDARDLOCATIONPERPRODUCT_ID(+) AND SLS.SIZEDEFINITION_ID(+) = SD.SIZEDEFINITION_ID
 AND SLP.STOCKROOMLOCATION_ID = TR.STOCKROOMLOCATION_ID AND SLP.PRODUCT_ID=PR.PRODUCT_ID) STANDARDTRUCKLOAD
, COALESCE((SELECT MAX(1) FROM ROUTECONTROL RC1, PACKINGNOTE PN1
WHERE RC1.TRUCKCODE = TR.CODE AND PN1.ROUTECONTROL_ID = RC1.ROUTECONTROL_ID
AND RC1.DRIVINGDATE = (SELECT MAX(RC4.DRIVINGDATE) FROM ROUTECONTROL RC4 WHERE RC4.TRUCKCODE = TR.CODE AND RC4.DRIVINGDATE <= SYSDATE)
AND PN1.STATUS_ID NOT IN (SELECT ST1.STATUS_ID FROM STATUS ST1 WHERE ST1.STATUSTYPE = 'PN' AND ST1.CODE IN ('30','40'))), 0) CHECK1
, COALESCE((SELECT MAX(1) FROM ROUTECONTROL RC2, WORKORDER WO2
WHERE RC2.TRUCKCODE = TR.CODE AND WO2.ROUTECONTROL_ID = RC2.ROUTECONTROL_ID AND WO2.ORIGIN = 10
AND RC2.DRIVINGDATE = (SELECT MAX(RC5.DRIVINGDATE) FROM ROUTECONTROL RC5 WHERE RC5.TRUCKCODE = TR.CODE AND RC5.DRIVINGDATE <= SYSDATE)
AND WO2.STATUS_ID NOT IN (SELECT ST2.STATUS_ID FROM STATUS ST2 WHERE ST2.STATUSTYPE = 'MO' AND ST2.CODE IN ('30','40'))) , 0) CHECK2
, COALESCE((SELECT MAX(1) FROM ROUTECONTROL RC3, WORKORDER WO3
WHERE RC3.TRUCKCODE = TR.CODE AND WO3.ROUTECONTROL_ID = RC3.ROUTECONTROL_ID AND WO3.ORIGIN = 6
AND RC3.DRIVINGDATE = (SELECT MAX(RC6.DRIVINGDATE) FROM ROUTECONTROL RC6 WHERE RC6.TRUCKCODE = TR.CODE AND RC6.DRIVINGDATE <= SYSDATE)
AND WO3.STATUS_ID NOT IN (SELECT ST3.STATUS_ID FROM STATUS ST3 WHERE ST3.STATUSTYPE = 'WO' AND ST3.CODE IN ('30','40'))) , 0) CHECK3
, LAN.CODE LANGUAGECODE
, WO.WORKORDERNUMBER NOTENUMBER, WOL.QUANTITYORDERED STANDARDSTOCK, WOL.QUANTITYFILLED CURRENTSTOCK
, (SELECT CU.CUSTOMERNUMBER FROM CUSTOMER CU WHERE WO.CUSTOMER_LINK_ID = CU.CUSTOMER_ID) CUSTOMERNUMBER
FROM TRUCK TR, PRODUCT PR, SIZEDEFINITION SD, STOCKTRANSACTION ST,
     STOCKRESERVATIONPERGRADE SRG, STOCKDEFINITIONPERITEM SDI, LANGUAGES LAN,
     WORKORDERSTOCKTRANSACTION WOST, WORKORDERLINE WOL, WORKORDER WO
WHERE (TR.STOCKROOMLOCATION_ID = ST.FROMSTOCKROOMLOCATION_ID OR TR.STOCKROOMLOCATION_ID = ST.TOSTOCKROOMLOCATION_ID)
AND ST.STOCKRESERVATIONPERGRADE_ID = SRG.STOCKRESERVATIONPERGRADE_ID AND SRG.STOCKDEFINITIONPERITEM_ID = SDI.STOCKDEFINITIONPERITEM_ID AND SDI.PRODUCT_ID = PR.PRODUCT_ID AND SDI.SIZEDEFINITION_ID = SD.SIZEDEFINITION_ID
AND ST.TRANSACTIONTYPE_ID IN (405,406,414,415,416,422,423,424,450,453,454)
AND NOT EXISTS (SELECT 1 FROM PACKINGNOTESTOCKTRANSACTION PNST WHERE ST.STOCKTRANSACTION_ID = PNST.STOCKTRANSACTION_ID)
AND WOST.STOCKTRANSACTION_ID = ST.STOCKTRANSACTION_ID AND WOL.WORKORDERLINE_ID = WOST.WORKORDERLINE_ID
AND WO.WORKORDER_ID = WOL.WORKORDER_ID AND WO.ORIGIN IN (6, 10)
UNION ALL
SELECT 4 LINETYPE --NOT APPLICABLE
, TR.CODE TRUCKCODE, TR.DESCRIPTION TRUCKDESC, TR.LASTCHECKDATE
, ST.TRANSACTIONTYPE_ID, ST.TRANSACTIONDATE, ST.QUANTITY STOCKTRANSACTIONQTY
, PR.CODE PRODUCTCODE, SD.CODE SIZECODE
, (SELECT PRD.DESCRIPTION FROM PRODUCT_DESC PRD WHERE PRD.PRODUCT_ID = PR.PRODUCT_ID AND PRD.LANGUAGE_ID = LAN.LANGUAGE_ID) PRODUCTDESC
, (SELECT SDD.DESCRIPTION FROM SIZEDEFINITION_DESC SDD WHERE SDD.SIZEDEFINITION_ID = SD.SIZEDEFINITION_ID AND SDD.LANGUAGE_ID = LAN.LANGUAGE_ID ) SIZEDESC
, CASE WHEN ST.TRANSACTIONTYPE_ID IN (405,406,414) THEN '+'
ELSE '-'
END DIRECTION
, '5NA'  ORIGIN
, (SELECT COALESCE(SLS.STANDARDTRUCKLOAD, SLP.STANDARDTRUCKLOAD) FROM STANDARDLOCATIONPERPRODUCT SLP, STANDARDLOCATIONPERSIZE SLS
 WHERE SLP.STANDARDLOCATIONPERPRODUCT_ID = SLS.STANDARDLOCATIONPERPRODUCT_ID(+) AND SLS.SIZEDEFINITION_ID(+) = SD.SIZEDEFINITION_ID
 AND SLP.STOCKROOMLOCATION_ID = TR.STOCKROOMLOCATION_ID AND SLP.PRODUCT_ID=PR.PRODUCT_ID) STANDARDTRUCKLOAD
, COALESCE((SELECT MAX(1) FROM ROUTECONTROL RC1, PACKINGNOTE PN1
WHERE RC1.TRUCKCODE = TR.CODE AND PN1.ROUTECONTROL_ID = RC1.ROUTECONTROL_ID
AND RC1.DRIVINGDATE = (SELECT MAX(RC4.DRIVINGDATE) FROM ROUTECONTROL RC4 WHERE RC4.TRUCKCODE = TR.CODE AND RC4.DRIVINGDATE <= SYSDATE)
AND PN1.STATUS_ID NOT IN (SELECT ST1.STATUS_ID FROM STATUS ST1 WHERE ST1.STATUSTYPE = 'PN' AND ST1.CODE IN ('30','40'))), 0) CHECK1
, COALESCE((SELECT MAX(1) FROM ROUTECONTROL RC2, WORKORDER WO2
WHERE RC2.TRUCKCODE = TR.CODE AND WO2.ROUTECONTROL_ID = RC2.ROUTECONTROL_ID AND WO2.ORIGIN = 10
AND RC2.DRIVINGDATE = (SELECT MAX(RC5.DRIVINGDATE) FROM ROUTECONTROL RC5 WHERE RC5.TRUCKCODE = TR.CODE AND RC5.DRIVINGDATE <= SYSDATE)
AND WO2.STATUS_ID NOT IN (SELECT ST2.STATUS_ID FROM STATUS ST2 WHERE ST2.STATUSTYPE = 'MO' AND ST2.CODE IN ('30','40'))) , 0) CHECK2
, COALESCE((SELECT MAX(1) FROM ROUTECONTROL RC3, WORKORDER WO3
WHERE RC3.TRUCKCODE = TR.CODE AND WO3.ROUTECONTROL_ID = RC3.ROUTECONTROL_ID AND WO3.ORIGIN = 6
AND RC3.DRIVINGDATE = (SELECT MAX(RC6.DRIVINGDATE) FROM ROUTECONTROL RC6 WHERE RC6.TRUCKCODE = TR.CODE AND RC6.DRIVINGDATE <= SYSDATE)
AND WO3.STATUS_ID NOT IN (SELECT ST3.STATUS_ID FROM STATUS ST3 WHERE ST3.STATUSTYPE = 'WO' AND ST3.CODE IN ('30','40'))) , 0) CHECK3
, LAN.CODE LANGUAGECODE
, -1 NOTENUMBER, 0 STANDARDSTOCK, 0 CURRENTSTOCK
, -1 CUSTOMERNUMBER
FROM TRUCK TR, PRODUCT PR, SIZEDEFINITION SD, STOCKTRANSACTION ST,
     STOCKRESERVATIONPERGRADE SRG, STOCKDEFINITIONPERITEM SDI, LANGUAGES LAN
WHERE (TR.STOCKROOMLOCATION_ID = ST.FROMSTOCKROOMLOCATION_ID OR TR.STOCKROOMLOCATION_ID = ST.TOSTOCKROOMLOCATION_ID)
AND ST.STOCKRESERVATIONPERGRADE_ID = SRG.STOCKRESERVATIONPERGRADE_ID AND SRG.STOCKDEFINITIONPERITEM_ID = SDI.STOCKDEFINITIONPERITEM_ID AND SDI.PRODUCT_ID = PR.PRODUCT_ID AND SDI.SIZEDEFINITION_ID = SD.SIZEDEFINITION_ID
AND ST.TRANSACTIONTYPE_ID IN (405,406,414,415,416,422,423,424,450,453,454)
AND NOT EXISTS (SELECT 1 FROM PACKINGNOTESTOCKTRANSACTION PNST WHERE ST.STOCKTRANSACTION_ID = PNST.STOCKTRANSACTION_ID)
AND NOT EXISTS (SELECT 1 FROM WORKORDERSTOCKTRANSACTION WOST, WORKORDERLINE WOL, WORKORDER WO
WHERE WOST.STOCKTRANSACTION_ID = ST.STOCKTRANSACTION_ID AND WOL.WORKORDERLINE_ID = WOST.WORKORDERLINE_ID
AND WO.WORKORDER_ID = WOL.WORKORDER_ID AND WO.ORIGIN IN (6, 10))
/

  CREATE OR REPLACE VIEW "V_TSPACKING" ("UNIQUEITEM_LINK_ID", "BUSINESSUNIT_ID", "SCANTIMESTAMP", "DEPARTMENT_LINK_ID", "SCANSTATION", "PLANTDEPARTMENT_ID") AS 
  select /*version 2.0*/
       ds.uniqueitem_link_id, ds.businessunit_id, ds.scantimestamp, dp.department_link_id, ds.scanstation, ds.plantdepartment_id
  from deliveryscan ds
       join distributionpoint_link dp on ds.distributionpoint_link_id = dp.distributionpoint_link_id
 where ds.outscannodelivery = 0
   and nvl(packingnote_id, 0) = 0
 order by ds.scantimestamp asc
/

  CREATE OR REPLACE VIEW "V_TURNOVERCOMPARISON" ("REPORTPARAM_ID", "CURRENCYCODE", "INVOICEAMOUNTDECIMALS", "GROUPCODE", "GROUPDESC", "TURNOVERGROUPCODE", "TURNOVERGROUPDESCRIPTION", "CUSTOMERPHONENO", "CUSTOMERCITY", "LANGUAGECODE", "PERIOD_1_AMOUNT", "PERIOD_2_AMOUNT") AS 
  select
       rp.reportparam_id,
       art.currencycode,
       art.invoiceamountdecimals,
       art.groupcode,
       art.groupdesc,
       tog.turnovergroupcode,
       tog.turnovergroupdescription,
       art.customerphoneno,
       art.customercity,
       la.code languagecode,
       SUM(case when art.ARTRANSACTIONDATE between rp.date_value1 and rp.date_value2
                then AD.AMOUNT
                else 0
           end) PERIOD_1_AMOUNT,
       SUM(case when art.ARTRANSACTIONDATE between rp.date_value3 and rp.date_value4
                then AD.AMOUNT
                else 0
           end) PERIOD_2_AMOUNT
  from artransactiondetail ad,
       reportparam rp,
       languages la,
       (select tg.turnovergroup_id,
               tg.code turnovergroupcode,
               tod.description turnovergroupdescription,
               tod.language_id,
               rp.reportparam_id,
               ss.plant_id
          from turnovergroup tg, turnovergroup_desc tod, reportparam rp, systemsetting ss
         where tg.turnovergroup_id = tod.turnovergroup_id and ss.name='TAXDEFINITION'
           and ((
               case ss.value
                 when 'US' then (select count(states_id) from states where states.turnovergroup_id = tg.turnovergroup_id)
                 when 'EU' then (select count(taxgroup_id) from taxgroup where taxgroup.turnovergroup_id = tg.turnovergroup_id)
                   else 0 end = 0
                )
                or rp.string_value = 'N')
       ) tog,
     (select -- TurnoverGr
             a.artransaction_id,
             a.artransactiondate,
             cur.code currencycode,
             cur.invoiceamountdecimals,
             '1' groupcode,
             '1' groupdesc,
             null customerphoneno,
             null customercity,
             rp.reportparam_id,
             l.language_id, bu.plant_id
        from artransaction a,
             currency cur,
             businessunit bu,
             businessunit procbu,
             reportparam rp,
             languages l
       where (
             a.artransactiondate between rp.date_value1 and rp.date_value2
          or
             a.artransactiondate between rp.date_value3 and rp.date_value4)
         and bu.businessunit_id = a.businessunit_id
         and procbu.businessunit_id = a.processbusinessunit_id
         and cur.currency_id = a.currency_id
         and bu.code BETWEEN rp.string_value1 AND rp.string_value2
         and procbu.code BETWEEN rp.string_value3 AND rp.string_value4
         and a.debitcredit='D'
         and rp.number_value1=1 -- TurnoverGr
      UNION ALL --=======
      select -- chain
             a.artransaction_id,
             a.artransactiondate,
             cur.code currencycode,
             cur.invoiceamountdecimals,
             cu.groupcode,
             cu.groupdesc,
             cu.customerphoneno,
             cu.customercity,
             rp.reportparam_id,
             l.language_id, bu.plant_id
        from artransaction a,
             currency cur,
             businessunit bu,
             businessunit procbu,
             reportparam rp,
             languages l,
             (select c.customer_id,
                     c.customer_id GROUPID,
                     H.CODE GROUPCODE,
                     H.NAME GROUPDESC,
                     null CUSTOMERPHONENO,
                     null CUSTOMERCITY,
                     RP.REPORTPARAM_ID
                FROM CUSTOMER C
                     LEFT OUTER JOIN CHAIN H ON C.CHAIN_ID = H.CHAIN_ID,
                     REPORTPARAM RP
               WHERE H.CODE between rp.string_value7 and rp.string_value8
                 AND rp.number_value1=2 -- CHAIN
             ) cu
       where (
             a.artransactiondate between rp.date_value1 and rp.date_value2
          or
             a.artransactiondate between rp.date_value3 and rp.date_value4)
         and cu.customer_id = a.billtocustomer_link_id
         and cu.reportparam_id = rp.reportparam_id
         and bu.businessunit_id = a.businessunit_id
         and procbu.businessunit_id = a.processbusinessunit_id
         and cur.currency_id = a.currency_id
         and bu.code BETWEEN rp.string_value1 AND rp.string_value2
         and procbu.code BETWEEN rp.string_value3 AND rp.string_value4
         and a.debitcredit='D'
         AND rp.number_value1=2 -- CHAIN
      UNION ALL --=======
      select  -- market segment
             a.artransaction_id,
             a.artransactiondate,
             cur.code currencycode,
             cur.invoiceamountdecimals,
             cu.groupcode,
             cu.groupdesc,
             cu.customerphoneno,
             cu.customercity,
             rp.reportparam_id,
             l.language_id, bu.plant_id
        from artransaction a,
             currency cur,
             businessunit bu,
             businessunit procbu,
             reportparam rp,
             languages l,
             (select c.customer_id,
                     c.customer_id GROUPID,
                     M.CODE GROUPCODE,
                     (SELECT MSD.DESCRIPTION
                        FROM MARKETSEGMENT_DESC MSD
                       WHERE MSD.MARKETSEGMENT_ID = M.MARKETSEGMENT_ID
                         AND MSD.LANGUAGE_ID = LAN.LANGUAGE_ID) GROUPDESC,
                     null CUSTOMERPHONENO,
                     null CUSTOMERCITY,
                     LAN.LANGUAGE_ID,
                     RP.REPORTPARAM_ID
                FROM CUSTOMER C,
                     MARKETSEGMENT M,
                     REPORTPARAM RP,
                     LANGUAGES LAN
               WHERE M.MARKETSEGMENT_ID = C.MARKETSEGMENT_ID
                 AND M.CODE between rp.string_value7 and rp.string_value8
                 AND rp.number_value1=3 -- MARKETSEGEMENT
             ) cu
       where (
             a.artransactiondate between rp.date_value1 and rp.date_value2
          or
             a.artransactiondate between rp.date_value3 and rp.date_value4)
         and cu.customer_id = a.billtocustomer_link_id
         and cu.reportparam_id = rp.reportparam_id
         and cu.language_id = l.language_id
         and bu.businessunit_id = a.businessunit_id
         and procbu.businessunit_id = a.processbusinessunit_id
         and cur.currency_id = a.currency_id
         and bu.code BETWEEN rp.string_value1 AND rp.string_value2
         and procbu.code BETWEEN rp.string_value3 AND rp.string_value4
         and a.debitcredit='D'
         AND rp.number_value1=3 -- MARKETSEGEMENT
      UNION ALL --=======
      select -- sales area
             a.artransaction_id,
             a.artransactiondate,
             cur.code currencycode,
             cur.invoiceamountdecimals,
             cu.groupcode,
             cu.groupdesc,
             cu.customerphoneno,
             cu.customercity,
             rp.reportparam_id,
             l.language_id, bu.plant_id
        from artransaction a,
             currency cur,
             businessunit bu,
             businessunit procbu,
             reportparam rp,
             languages l,
             (select c.customer_id,
                     c.customer_id GROUPID,
                     S.CODE GROUPCODE,
                     (SELECT SAD.DESCRIPTION
                        FROM SALESAREA_DESC SAD
                       WHERE SAD.SALESAREA_ID = S.SALESAREA_ID
                         AND SAD.LANGUAGE_ID = LAN.LANGUAGE_ID) GROUPDESC,
                     null CUSTOMERPHONENO,
                     null CUSTOMERCITY,
                     LAN.LANGUAGE_ID,
                     RP.REPORTPARAM_ID
                FROM CUSTOMER C,
                     SALESAREA S,
                     REPORTPARAM RP,
                     LANGUAGES LAN
               WHERE S.SALESAREA_ID = C.SALESAREA_ID
                 AND S.CODE between rp.string_value7 and rp.string_value8
                 AND rp.number_value1=4 -- SALES AREA
             ) cu
       where (
             a.artransactiondate between rp.date_value1 and rp.date_value2
          or
             a.artransactiondate between rp.date_value3 and rp.date_value4)
         and cu.customer_id = a.deltocustomer_link_id
         and cu.reportparam_id = rp.reportparam_id
         and cu.language_id = l.language_id
         and bu.businessunit_id = a.businessunit_id
         and procbu.businessunit_id = a.processbusinessunit_id
         and cur.currency_id = a.currency_id
         and bu.code BETWEEN rp.string_value1 AND rp.string_value2
         and procbu.code BETWEEN rp.string_value3 AND rp.string_value4
         and a.debitcredit='D'
         AND rp.number_value1=4 -- SALES AREA
      UNION ALL --=======
      select -- Route
             a.artransaction_id,
             a.artransactiondate,
             cur.code currencycode,
             cur.invoiceamountdecimals,
             to_char(R.ROUTENUMBER) groupcode,
             R.description groupdesc,
             null customerphoneno,
             null customercity,
             rp.reportparam_id,
             l.language_id, bu.plant_id
        from artransaction a,
             route r,
             currency cur,
             businessunit bu,
             businessunit procbu,
             reportparam rp,
             languages l
       where (
             a.artransactiondate between rp.date_value1 and rp.date_value2
          or
             a.artransactiondate between rp.date_value3 and rp.date_value4)
         and bu.businessunit_id = a.businessunit_id
         and procbu.businessunit_id = a.processbusinessunit_id
         and cur.currency_id = a.currency_id
         and A.ROUTE_ID = R.ROUTE_ID
         and bu.code BETWEEN rp.string_value1 AND rp.string_value2
         and procbu.code BETWEEN rp.string_value3 AND rp.string_value4
         and r.routenumber BETWEEN rp.number_value2 and rp.number_value3
         and a.debitcredit='D'
         AND rp.number_value1=5 -- ROUTE
      UNION ALL --=======
      select -- Customer
             a.artransaction_id,
             a.artransactiondate,
             cur.code currencycode,
             cur.invoiceamountdecimals,
             cu.groupcode,
             cu.groupdesc,
             cu.customerphoneno,
             cu.customercity,
             rp.reportparam_id,
             l.language_id, bu.plant_id
        from artransaction a,
             currency cur,
             businessunit bu,
             businessunit procbu,
             reportparam rp,
             languages l,
             (select c.customer_id,
                     c.customer_id GROUPID,
                     TO_CHAR(C.CUSTOMERNUMBER) GROUPCODE,
                     C.NAME GROUPDESC,
                     C.PHONENO CUSTOMERPHONENO,
                     ADR.CITY CUSTOMERCITY,
                     RP.REPORTPARAM_ID
                FROM CUSTOMER C,
                     ADDRESS ADR,
                     REPORTPARAM RP
               WHERE ADR.ADDRESS_ID = C.Visitaddress_Id
                 AND C.CUSTOMERNUMBER between rp.number_value2 and rp.number_value3
                 AND rp.number_value1=6 -- CUSTOMER
             ) cu
       where (
             a.artransactiondate between rp.date_value1 and rp.date_value2
          or
             a.artransactiondate between rp.date_value3 and rp.date_value4)
         and cu.customer_id = a.billtocustomer_link_id
         and cu.reportparam_id = rp.reportparam_id
         and bu.businessunit_id = a.businessunit_id
         and procbu.businessunit_id = a.processbusinessunit_id
         and cur.currency_id = a.currency_id
         and bu.code BETWEEN rp.string_value1 AND rp.string_value2
         and procbu.code BETWEEN rp.string_value3 AND rp.string_value4
         and a.debitcredit='D'
         AND rp.number_value1=6 -- CUSTOMER
      UNION ALL --=======
      select -- Depot
             a.artransaction_id,
             a.artransactiondate,
             cur.code currencycode,
             cur.invoiceamountdecimals,
             de.code groupcode,
             de.description groupdesc,
             null customerphoneno,
             null customercity,
             rp.reportparam_id,
             l.language_id, bu.plant_id
        from artransaction a,
             route r,
             depot de,
             currency cur,
             businessunit bu,
             businessunit procbu,
             reportparam rp,
             languages l
       where (
             a.artransactiondate between rp.date_value1 and rp.date_value2
          or
             a.artransactiondate between rp.date_value3 and rp.date_value4)
         and bu.businessunit_id = a.businessunit_id
         and procbu.businessunit_id = a.processbusinessunit_id
         and cur.currency_id = a.currency_id
         and A.ROUTE_ID = R.ROUTE_ID
         and R.DEPOT_ID = DE.DEPOT_ID
         and bu.code BETWEEN rp.string_value1 AND rp.string_value2
         and procbu.code BETWEEN rp.string_value3 AND rp.string_value4
         and de.code BETWEEN rp.string_value7 AND rp.string_value8
         and a.debitcredit='D'
         and rp.number_value1=7 -- DEPOT
     ) art
where ad.artransaction_id = art.artransaction_id
   and ad.turnovergroup_id = tog.turnovergroup_id
   and tog.language_id = la.language_id
   and tog.reportparam_id = rp.reportparam_id
   and art.reportparam_id = rp.reportparam_id
   and art.language_id = la.language_id
   and tog.turnovergroupcode BETWEEN rp.string_value5 AND rp.string_value6
   and tog.plant_id = art.plant_id
group by rp.reportparam_id,
         art.currencycode,
         art.invoiceamountdecimals,
         art.groupcode,
         art.groupdesc,
         tog.turnovergroupcode,
         tog.turnovergroupdescription,
         art.customerphoneno,
         art.customercity,
         la.code
/

  CREATE OR REPLACE VIEW "V_TURNOVERFORECAST" ("PLANTCODE", "PLANTNAME", "BUSINESSUNITCODE", "BUSINESSUNITDESC", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "MARKETSEGMENTCODE", "MARKETSEGMENTNAME", "TURNOVERGROUPCODE", "TURNOVERGROUPDESC", "YEAR", "WEEK", "YEARWEEK", "TURNOVERFORECASTDATE", "AMOUNTINPLANTCURRENCY", "LANGUAGECODE") AS 
  select pl.code plantcode, pl.name plantname,
  bu.code businessunitcode, bu.description businessunitdesc,
  cb.customernumber billtocustomernumber, cb.name billtocustomername,
  cd.customernumber deltocustomernumber, cd.name deltocustomername,
  ms.code marketsegmentcode,
  (select msd.description from marketsegment_desc msd where ms.marketsegment_id = msd.marketsegment_id
    and msd.language_id = languages.language_id) marketsegmentname,
  tg.code turnovergroupcode,
  (select tgd.description from turnovergroup_desc tgd where tg.turnovergroup_id = tgd.turnovergroup_id
    and tgd.language_id = languages.language_id) turnovergroupdesc,
  tfh.year, tfh.week, tfh.week*100+tfh.year yearweek,
  tfh.turnoverforecastdate, tfd.amountinplantcurrency,
  languages.code languagecode
from turnoverforecastheader tfh, turnoverforecastdetail tfd, turnovergroup tg,
  customer cb, customer cd, marketsegment ms, businessunit bu, plant pl,
  languages
where tfh.turnoverforecastheader_id = tfd.turnoverforecastheader_id
  and tfd.billtocustomer_link_id = cb.customer_id
  and tfd.deltocustomer_link_id = cd.customer_id
  and tfd.turnovergroup_id = tg.turnovergroup_id
  and cb.marketsegment_id = ms.marketsegment_id
  and tfh.invoicebusinessunit_id = bu.businessunit_id
  and bu.plant_id = pl.plant_id
/

  CREATE OR REPLACE VIEW "V_TURNOVERONROUTELEVEL" ("PLANTCODE", "PLANTNAME", "DEPOTCODE", "DEPOTDESC", "BUSINESSUNITCODE", "BUSINESSUNITDESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_ID", "DEBTOR_ID", "STREET", "CITY", "DAYNUMBER", "ZIPCODE", "DELIVERYSCHEMECODE", "ROUTENUMBER", "ROUTEDESC", "ROUTE_ID", "DAYDESC", "STOPNUMBER", "DELIVERYPOINTCODE", "DRIVER", "TRUCKCODE", "TRUCKDESC", "USERGROUPID", "LANGUAGECODE", "INVOICE_VALUE", "INVOICEAMOUNTDECIMALS", "NROFDELIVERYDAYS") AS 
  select pl.code plantcode, pl.name plantname, coalesce(depot.code, 'NULL') depotcode, depot.description depotdesc,
       bu.code businessunitcode, bu.description businessunitdesc, cu.customernumber, cu.name customername, cu.customer_id, cu.debtor_id,
       cast((case concatenatewithblank(delad.street, delad.street2)
               when ' ' then concatenatewithblank(cuad.street, cuad.street2)
               else concatenatewithblank(delad.street, delad.street2)
             end) as varchar2(255)) street,
       coalesce(delad.city, cuad.city) city, day.daynumber,
       coalesce(delad.zipcode, cuad.zipcode) zipcode,
       dsk.code deliveryschemecode, route.routenumber, route.description routedesc, route.route_id,
       (select dd.description
          from day_desc dd
         where dd.day_id = day.day_id
           and dd.language_id = lan.language_id) daydesc,
       rst.stopnumber, delp.code deliverypointcode, emp.name driver,
       truck.code truckcode, truck.description truckdesc, buusg.usergroup_id usergroupid, lan.code languagecode,
       (coalesce((select case when f_getdaysforlastmonthinvoices(ih.billtocustomer_link_id, day.daynumber) = 0
                         then sum(ih.totalamountexclvat)
                         else sum(ih.totalamountexclvat) / f_getdaysforlastmonthinvoices(ih.billtocustomer_link_id, day.daynumber)
                         end invoice_value
                    from invoiceheader ih
                         join status st on ih.status_id = st.status_id and st.code = '2' --Finalized
                   where ih.billtocustomer_link_id = cu.debtor_id --and ih.route_id = route.route_id
                     and ih.invoicedate between add_months(trunc(sysdate, 'mm'), -1) and last_day(add_months(trunc(sysdate, 'mm'), -1))
                     and ih.startdate < trunc(sysdate)
                     and ih.enddate < trunc(sysdate)
                   group by ih.billtocustomer_link_id), 0)) invoice_value,
       (select cur.invoiceamountdecimals from currency cur where cur.currency_id = cu.currency_id) invoiceamountdecimals,
       (select count(distinct(cdd.day_id)) from customerdeliveryday cdd where cdd.customer_id = cu.customer_id) nrofdeliverydays
  from deliveryschemesperstop dskt
       join customerdeliveryscheme cudsk on dskt.customer_id = cudsk.customer_id
                                        and dskt.deliveryscheme_id = cudsk.deliveryscheme_id and dskt.day_id = cudsk.day_id
       join deliveryscheme dsk on cudsk.deliveryscheme_id = dsk.deliveryscheme_id
       join routestop rst on dskt.routestop_id = rst.routestop_id and dskt.customer_id = rst.customer_id
       left join deliverypoint delp
            join address delad on delp.deliveryaddress_id = delad.address_id
       on rst.deliverypoint_id = delp.deliverypoint_id
       join customer cu on rst.customer_id = cu.customer_id
       join address cuad on cu.visitaddress_id = cuad.address_id
       join businessunit bu on cu.defaultbusinessunit_id = bu.businessunit_id
       join businessunitsperusergroup buusg on bu.businessunit_id = buusg.businessunit_id
       join route
            left join truck on route.truck_id = truck.truck_id
            left join depot on route.depot_id = depot.depot_id
            left join employee emp on route.driver_id = emp.employee_id
            join plant pl on route.plant_id = pl.plant_id
            join day on route.drivingday_id = day.day_id
       on rst.route_id = route.route_id,
       languages lan
 where trunc(sysdate) between cu.dateactive and cu.dateinactive
   and route.drivingday_id = dskt.day_id
   and route.active = 'Y'
   and rst.dateactive <= trunc(sysdate)
   and rst.dateinactive > trunc(sysdate)
/

  CREATE OR REPLACE VIEW "V_TURNOVERREPORT" ("PRODUCTCODE", "PRODUCTDESC", "PRODUCTGROUPCODE", "INVOICEDATE", "MARKETSEGMENTCODE", "INVOICEBUCODE", "INVOICEBUDESC", "PLANTCODE", "PLANTNAME", "AMOUNT", "BILLEDQTY", "INVLINETYPE", "INVLINETYPEDESC") AS 
  select il.code productcode, il.description productdesc, ilp.productgroupcode,
       ih.invoicedate, ms.code marketsegmentcode, bu.code invoicebucode, bu.description invoicebudesc,
       plnt.code plantcode, plnt.name plantname,
       il.amount, il.billedqty, il.invoicelinetype_id invlinetype,
       --cast(
       (select iltdesc.description from invoicelinetype_desc iltdesc where iltdesc.invoicelinetype_id = il.invoicelinetype_id and iltdesc.language_id = plnt.language_id)
       --as varchar2(60))
       invlinetypedesc
from invoiceline il left outer join invoicelineproduct ilp on il.invoiceline_id = ilp.invoiceline_id,
     invoicelinetype ilt, invoiceheader ih,
     customer bilto, marketsegment ms,
     --product p, product_desc pdesc, productgroup pg, languages lan,
     businessunit bu, plant plnt
where il.invoiceheader_id = ih.invoiceheader_id
      and il.invoicelinetype_id = ilt.invoicelinetype_id
      and il.invoicelinetype_id <> 18
      and ih.billtocustomer_link_id = bilto.customer_id
      and bilto.marketsegment_id = ms.marketsegment_id
      and ih.invoicebusinessunit_id = bu.businessunit_id
      and bu.plant_id = plnt.plant_id
/

  CREATE OR REPLACE VIEW "V_TURNOVERREPORTACCOUNTMANAGER" ("EMPLOYEENUMBER", "EMPLOYEENAME", "CUSTOMERNUMBER", "CUSTOMERNAME", "TOTAL", "PLANTCODE", "BUCODE", "INVOICEDATE") AS 
  SELECT EM1.EMPLOYEENUMBER EMPLOYEENUMBER,
       EM1.NAME EMPLOYEENAME,
       CU1.CUSTOMERNUMBER CUSTOMERNUMBER,
       CU1.NAME CUSTOMERNAME,
       SUM(IH1.TOTALAMOUNTEXCLVAT) TOTAL,
       PLNT1.CODE PLANTCODE,
       BU1.CODE BUCODE,
       IH1.INVOICEDATE
  FROM ARTRANSACTION ART1,
       CUSTOMER      CU1,
       CONTRACT      CT1,
       EMPLOYEE      EM1,
       INVOICEHEADER IH1,
       BUSINESSUNIT  BU1,
       PLANT         PLNT1
 WHERE ART1.DELTOCUSTOMER_LINK_ID = CU1.CUSTOMER_ID
   AND CU1.CUSTOMER_ID = CT1.CUSTOMER_LINK_ID
   AND CT1.ACCOUNTMANAGER_ID = EM1.EMPLOYEE_ID
   AND ART1.INVOICEHEADER_ID = IH1.INVOICEHEADER_ID
   AND IH1.INVOICEBUSINESSUNIT_ID = BU1.BUSINESSUNIT_ID
   AND BU1.PLANT_ID = PLNT1.PLANT_ID
   AND CU1.ACTIVE = 'Y'
 GROUP BY EM1.EMPLOYEENUMBER, EM1.NAME, CU1.CUSTOMERNUMBER, CU1.NAME,PLNT1.CODE,BU1.CODE,IH1.INVOICEDATE
UNION ALL
SELECT EM.EMPLOYEENUMBER EMPLOYEENUMBER,
       EM.NAME EMPLOYEENAME,
       CU.CUSTOMERNUMBER CUSTOMERNUMBER,
       CU.NAME CUSTOMERNAME,
       SUM(IH.TOTALAMOUNTEXCLVAT) TOTAL,
       PLNT.CODE PLANTCODE,
       BU.CODE BUCODE,
       IH.INVOICEDATE
  FROM ARTRANSACTION            ART,
       CUSTOMER                 CU,
       CONTRACTSPERCUSTOMER     CPC,
       EMPLOYEE                 EM,
       INVOICEHEADER            IH,
       BUSINESSUNIT             BU,
       PLANT                    PLNT
 WHERE ART.DELTOCUSTOMER_LINK_ID = CU.CUSTOMER_ID
   AND CU.CUSTOMER_ID = CPC.CUSTOMER_ID
   AND CPC.ACCOUNTMANAGER_ID = EM.EMPLOYEE_ID
   AND ART.INVOICEHEADER_ID = IH.INVOICEHEADER_ID
   AND IH.INVOICEBUSINESSUNIT_ID = BU.BUSINESSUNIT_ID
   AND BU.PLANT_ID = PLNT.PLANT_ID
   AND CU.ACTIVE = 'Y'
 GROUP BY EM.EMPLOYEENUMBER, EM.NAME, CU.CUSTOMERNUMBER, CU.NAME,PLNT.CODE,BU.CODE,IH.INVOICEDATE
 ORDER BY EMPLOYEENUMBER, CUSTOMERNUMBER
/

  CREATE OR REPLACE VIEW "V_TURNOVERREPORTDETAIL" ("REPORTPARAM_ID", "PRODUCTCODE", "PRODUCTGROUPCODE", "PRODUCTDESC", "AMOUNT", "BILLEDQTY", "PLANTCODE", "PLANTNAME", "SUMCIRCINV", "CUSTWITHPRD", "INVOICEBUCODE", "MARKETSEGMENTCODE") AS 
  select rp.reportparam_id,
       p.code productcode,
       ilp.productgroupcode,
       (select pdesc.description from product_desc pdesc where pdesc.product_id = p.product_id and pdesc.language_id = plnt.language_id) productdesc,
       --ilt.type invlinetype,
       sum(il.amount) amount,
       sum(il.billedqty) billedqty,
       plnt.code plantcode,
       plnt.name plantname,
       (select sum(sqic.totalcircinv)
        from sqitemincirculation sqic, statusquoheader sqh
        where sqic.statusquoheader_id = sqh.statusquoheader_id
              and sqh.invoicebusinessunit_id = ih.invoicebusinessunit_id
              and sqic.product_link_id = ilp.product_link_id
              and (select max(sqh1.statusquodate)
                   from statusquoheader sqh1
                   where sqh1.statusquoheader_id = sqh.statusquoheader_id
                         and sqh1.statusquodate <= rp.date_value2) <= rp.date_value2
       ) sumcircinv,
       sum(case when
        (select max(plpc.customer_id)
        from productlistpercustomer plpc
        where plpc.customer_id = ih.deltocustomer_link_id
       ) is not null then 1
       else 0 end) custwithprd,
       bu.code invoicebucode,
       ms.code marketsegmentcode
from invoiceline il, --invoicelinetype ilt,
     invoicelineproduct ilp, invoiceheader ih,
     businessunit bu, plant plnt,
     product p, reportparam rp, customer c, marketsegment ms
where il.invoiceline_id = ilp.invoiceline_id
      --and il.invoicelinetype_id = ilt.invoicelinetype_id
      and il.invoiceheader_id = ih.invoiceheader_id
      and ih.invoicebusinessunit_id = bu.businessunit_id
      and bu.plant_id = plnt.plant_id
      and ilp.product_link_id = p.product_id
      and ih.deltocustomer_link_id = c.customer_id
      and c.marketsegment_id = ms.marketsegment_id
      and ih.invoicedate >= rp.date_value1
      and ih.invoicedate <= rp.date_value2
group by rp.reportparam_id, rp.date_value2, plnt.code, plnt.name, plnt.language_id, bu.code, ih.invoicebusinessunit_id, ms.code,
       ilp.productgroupcode,
       p.code, p.product_id, ilp.product_link_id
/

  CREATE OR REPLACE VIEW "V_UIPERBUSINESSUNIT" ("BUSINESSUNIT_ID", "UNIQUEITEM_ID") AS 
  select /*version 2.0*/
       ui.businessunit_id, ui.uniqueitem_id
  from uniqueitem ui
union
select ordb.orbusinessunit_id, ui.uniqueitem_id
  from ordeliverbusinessunit ordb
       join uniqueitem ui on ordb.delivertobusinessunit_id = ui.businessunit_id
/

  CREATE OR REPLACE VIEW "V_UNDELIVERABLESTOPANALYSIS" ("ROUTE_YEAR", "ROUTE_WEEK", "ROUTE_DAY", "DRIVINGDATE", "PLANT_ID", "PLANT_CODE", "PLANT_NAME", "ROUTENUMBER", "ROUTEDESC", "CUSTOMERNUMBER", "CUSTOMER_NAME", "ROUTECONTROL_ID", "REASON_CODE", "REASON_DESC", "LANGUAGE_ID", "LANGUAGE_CODE") AS 
  select YEAR(rc.drivingdate) route_year, GETISOWEEK(rc.drivingdate) route_week,
  GETABSDAYNUMBER(rc.drivingdate) route_day, rc.drivingdate,
  rc.plant_id, pl.code Plant_Code, pl.name Plant_Name,
  r.routenumber, r.description routedesc,
  cl.customernumber, cl.name customer_Name,
  rc.routecontrol_id, rsc.code Reason_code,
  (select rscd.description from reasoncode_desc rscd where rscd.reasoncode_id = rsc.reasoncode_id and rscd.language_id = lan.language_id) Reason_desc,
  lan.language_id, lan.code Language_Code
from routecontrol rc, plant pl, stop s, customer_link cl, reasoncode rsc, route r, languages lan
where rc.plant_id = pl.plant_id and rc.routecontrol_id = s.routecontrol_id
  and s.reasoncode_id = rsc.reasoncode_id-- 'Undeliverable' means reason is not null
  and s.customer_link_id = cl.customer_link_id and rc.route_id = r.route_id
/

  CREATE OR REPLACE VIEW "V_UNEMPLOYEDWEARER" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_ID", "DEBTORNUMBER", "DEBTORNAME", "WEARER_ID", "WEARERNUMBER", "SEQUENCENUMBER", "FULLNAME", "CUSTOMEREMPLOYEENUMBER", "FUNCTIONCODE", "COSTCENTERCODE", "DATEACTIVE", "DATEINACTIVE") AS 
  select
  cu.customernumber, cu.name customerName, cu.customer_id
, debtor.customernumber debtorNumber, debtor.name debtorName
, we.wearer_id
, we.wearernumber, wey.sequencenumber, we.fullname, we.customeremployeenumber, wef.code functionCode
, cc.code costcenterCode, we.dateActive, we.dateInactive
from
  customer cu, customer debtor
, wearer we
, weareremployment wey
    left outer join wearerfunction wef on wey.wearerfunction_id = wef.wearerfunction_id
, distributionpoint dip, department dep, costcenter cc
where
    cu.debtor_id = debtor.customer_id
and cu.customer_id = we.customer_id
and we.wearer_id = wey.wearer_id
and wey.distributionpoint_id = dip.distributionpoint_id
    and dip.department_id = dep.department_id
    and dip.costcenter_id = cc.costcenter_id
/

  CREATE OR REPLACE VIEW "V_UNEMPLOYEDWEARERAPPENDIX" ("INVOICEHEADER_ID", "INVOICENUMBER", "INVOICEDATE", "STARTDATE", "ENDDATE", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "WEARERNUMBER", "SEQUENCENUMBER", "FULLNAME", "CUSTOMEREMPLOYEENUMBER", "FUNCTIONCODE", "COSTCENTERCODE", "DATEACTIVE", "DATEINACTIVE", "EMPLOYED", "UN_EMPLOYED") AS 
  select distinct
  ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.startdate, ih.enddate
, ih.billtocustomernumber, ih.billtocustomername
, ih.deltocustomernumber, ih.deltocustomername
, we.wearernumber, wey.sequencenumber, we.fullname, we.customeremployeenumber, wef.code functionCode
, cc.code costcenterCode, we.dateActive, we.dateInactive
, case when  we.dateActive between ih.startdate and ih.enddate then we.wearernumber else 0 end employed
, case when  we.dateInactive between ih.startdate and ih.enddate then we.wearernumber else 0 end un_employed
from
  invoiceheader ih
, customer bill
, wearer we
, weareremployment wey
    left outer join wearerfunction wef on wey.wearerfunction_id = wef.wearerfunction_id
, distributionpoint dip, department dep, costcenter cc
where
    ih.invoicefrequency_id <> 0 -- direct
and ih.billtocustomer_link_id = bill.customer_id
and bill.customer_id = we.customer_id
and we.wearer_id = wey.wearer_id
and wey.distributionpoint_id = dip.distributionpoint_id
    and dip.department_id = dep.department_id
    and dip.costcenter_id = cc.costcenter_id
/

  CREATE OR REPLACE VIEW "V_UNIQUEBUNDLESTICKER" ("PLANT_CODE", "PLANT_NAME", "PLANT_PHONE", "PLANT_FAX", "BU_CODE", "DU_DESCRIPTION", "BUSINESSUNIT_ID", "PRIMARYID", "CREATIONDATE", "CONTENTSTYPE", "QUANTITY", "MAXQUANTITY", "OUTSCANDATE", "DELIVERYNOTENUMBER", "UNIQUEBUNDLE_ID", "PROD_CODE", "SIZE_CODE", "FINMETH_CODE", "STATUSCODE", "CUSTOMERNUMBER", "CUSTOMERNAME", "NEWITEM", "PROD_DESC", "SIZE_DESC", "FINMETH_DESC") AS 
  select /*version 3.3*/
       pl.code plant_code, pl.name plant_name, pl.phoneno plant_phone, pl.faxno plant_fax,  bu.code bu_code, bu.description du_description, ub.businessunit_id,
       ub.primaryid, ub.creationdate, ub.contentstype, ub.quantity, ub.maxquantity, ub.outscandate, ub.deliverynotenumber, ub.uniquebundle_id,
       p.code prod_code, s.code size_code, f.code finMeth_code, st.code statuscode, cu.customernumber, cu.name customername, ub.newitem,
       (select pd.description
          from product_desc pd
         where pd.product_id = p.product_id
           and pd.language_id = pl.language_id) prod_desc,
       (select sd.description
          from sizedefinition_desc sd
         where sd.sizedefinition_id = s.sizedefinition_id
           and sd.language_id = pl.language_id) size_desc,
       (select fd.description
          from finishingmethod_desc fd
         where fd.finishingmethod_id = f.finishingmethod_id
           and fd.language_id = pl.language_id) finMeth_desc
  from uniquebundle ub
       left join finishingmethod f on ub.finishingmethod_id = f.finishingmethod_id
       left join customer cu on ub.customer_link_id = cu.customer_id
       join status st on ub.status_id = st.status_id
       join product p on ub.product_link_id = p.product_id
       join sizedefinition s on ub.sizedefinition_link_id = s.sizedefinition_id
       join businessunit bu
            join plant pl on bu.plant_id = pl.plant_id
       on ub.businessunit_id = bu.businessunit_id
union
select pl.code plant_code, pl.name plant_name, pl.phoneno plant_phone, pl.faxno plant_fax, bu.code bu_code, bu.description du_description, bu.businessunit_id,
       'ERRORSTICKER' primaryid, trunc(sysdate) creationdate, 'U' contentstype, 0 quantity, 0 maxquantity, null outscandate, null deliverynotenumber, -1 uniquebundle_id,
       null prod_code, null size_code, null finMeth_code, null statuscode, null customernumber, null customername, 'N' newitem, null prod_desc, null size_desc, null finMeth_desc
  from businessunit bu
       join plant pl on bu.plant_id = pl.plant_id
/

  CREATE OR REPLACE VIEW "V_UNIQUEITEMSONSTOCK" ("STOCKCODE", "STOCKNAME", "RELATEDCUSTOMER_ID", "CUSTOMEROWNED", "RELATEDCUSTOMER", "PRODUCTCODE", "SIZECODE", "COLORCODE", "FABRICCODE", "SEQUENCENUMBER", "PRODUCTDESC", "SIZEDESC", "COLORDESC", "FABRICDESC", "PRIMARYID", "WASHESTOTAL", "REPAIRSTOTAL", "WEEKSUSED", "WEEKSSTOCK", "PURCHASEDATE", "LASTISSUEDATE", "LASTSCANDATE", "QUALITYGRADECODE", "QUALITYGRADEPRIORITY", "MODIFICATIONCODE", "ISMODIFIED", "LANGUAGECODE") AS 
  select --+ INDEX(uq XPKUNIQUEITEMFIXEDINFO) INDEX(uqfx XPKUNIQUEITEMFIXEDINFO) INDEX(modif XPKMODIFICATION) INDEX(prd XPKPRODUCT)--distinct
  sk.code stockCode, sk.name stockName
, uq.relatedcustomer_id, uq.customerowned
, ( select customer.customernumber from customer where customer.customer_id = uq.relatedcustomer_id ) relatedCustomer
, prd.code productCode, sz.code sizeCode, color.code colorCode, fabric.code fabricCode,
(select psz.sequencenumber from productsize psz where psz.product_id = prd.product_id and psz.sizedefinition_id = sz.sizedefinition_id) sequencenumber
, ( select product_desc.description from product_desc where prd.product_id = product_desc.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( select sizedefinition_desc.description from sizedefinition_desc where sizedefinition_desc.sizedefinition_id = sz.sizedefinition_id
  and sizedefinition_desc.language_id = languages.language_id ) sizeDesc
, ( select color_desc.description from color_desc where color_desc.color_id = color.color_id
  and color_desc.language_id = languages.language_id ) colorDesc
, ( select fabric_desc.description from fabric_desc where fabric_desc.fabric_id = fabric.fabric_id
  and fabric_desc.language_id = languages.language_id ) fabricDesc
, uq.primaryid, uq.washestotal, uq.repairstotal
, F_CEIL( uqfx.daysincircprevissue / 7 ) weeksUsed
, F_CEIL( (uqfx.daysinstockprevious + GETDATEDIFF(sysdate, uqfx.lastonstockdate)) / 7 ) weeksStock
, uqfx.purchasedate, uqfx.lastissuedate, uq.lastscandate
, qg.code qualitygradeCode, coalesce(qg.priority,0) QualitygradePriority, modif.code modificationCode
, case when modif.stockwithstandardsize <> 'Y' then 1 else 0 end  IsModified
, languages.code languageCode
from
  uniqueitem uq
    left outer join uniqueitemmodification uqm
         inner join modification modif on modif.modification_id = uqm.modification_id
    on uqm.uniqueitem_id = uq.uniqueitem_id
    inner join status on status.status_id = uq.status_id and status.statustype = 'UI' and status.code = '10'  -- stock
    inner join uniqueitemfixedinfo uqfx
          left outer join qualitygrade qg on qg.qualitygrade_id = uqfx.qualitygrade_id
    on uqfx.uniqueitem_id = uq.uniqueitem_id
    inner join stockroomlocation skl
          inner join stockroom sk on sk.stockroom_id = skl.stockroom_id
    on skl.stockroomlocation_id = uqfx.stockroomlocation_id
    inner join product prd
          inner join color on color.color_id = prd.color_id
          inner join fabric on fabric.fabric_id = prd.fabric_id
    on prd.product_id = uq.product_id
    inner join sizedefinition sz on sz.sizedefinition_id = uq.sizedefinition_id
, languages
/

  CREATE OR REPLACE VIEW "V_UNIQUEITEM_LINK" ("UNIQUEITEM_LINK_ID", "BUSINESSUNIT_ID", "PLANT_ID") AS 
  select ui.uniqueitem_id, b.businessunit_id, b.plant_id
	from uniqueitem ui, businessunit b
	where ui.businessunit_id = b.businessunit_id
union all
select ri.raggeditem_id, b.businessunit_id, b.plant_id
	from raggeditem ri, businessunit b
	where ri.businessunit_id = b.businessunit_id
/

  CREATE OR REPLACE VIEW "V_UNIQUEPOOLAVGDELIVERY" ("REPORTPARAM_ID", "WEEKSINYEAR", "CUSTOMERID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINTID", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITION_ID", "SIZEDEFINITIONCODE", "SIZEDESCRIPTION", "FINISHINGMETHOD_ID", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "QTYPOOL", "CIRCINVENTORY", "QTYDELIVERED1", "QTYDELIVERED2", "QTYDELIVERED3", "QTYDELIVERED4", "QTYDELIVERED5", "LANGUAGECODES") AS 
  select /*version 1.0*/
       v2.reportparam_id, getweeksinyear(yeardel) weeksinyear, v1.customerid, v1.customernumber,
       v1.customername, v1.departmentid, v1.departmentnumber, v1.departmentdesc,
       v1.distributionpointid, v1.distributionpointnumber, v1.distributionpointdesc, v1.product_id,
       v1.productcode, v1.productdescription, v1.sizedefinition_id, v1.sizedefinitioncode,
       v1.sizedescription, v1.finishingmethod_id, v1.finishingmethodcode,
       v1.finishingmethoddescription, v1.qtypool, v1.circinventory, v2.qtydelivered1,
       v2.qtydelivered2, v2.qtydelivered3, v2.qtydelivered4, v2.qtydelivered5, v1.languagecodes
  from (select c.customer_id customerid, c.customernumber, c.name customername,
               d.department_id departmentid, d.departmentnumber, d.description departmentdesc,
               x.distributionpoint_id distributionpointid, dp.distributionpointnumber,
               dp.description distributionpointdesc, x.product_id product_id, p.code productcode,
               (select pld.description
                  from product_link_desc pld
                 where pld.product_link_id = x.product_id
                   and pld.language_id = l.language_id) productdescription,
               x.sizedefinition_id sizedefinition_id, sd.code sizedefinitioncode,
               (select sld.description
                  from sizedefinition_link_desc sld
                 where sld.sizedefinition_link_id = x.sizedefinition_id
                   and sld.language_id = l.language_id) sizedescription,
               x.finishingmethod_id finishingmethod_id, fm.code finishingmethodcode,
               (select fmd.description
                  from finishingmethod_desc fmd
                 where fmd.finishingmethod_id = x.finishingmethod_id
                   and fmd.language_id = l.language_id) finishingmethoddescription,
               (select sum(rqa.quantity)
                  from rentalqtyadjustment rqa, productlistperdistribpoint pldp
                 where rqa.productlistperdistribpoint_id = pldp.productlistperdistribpoint_id
                    and pldp.distributionpoint_id = x.distributionpoint_id
                    and pldp.product_id = x.product_id
                    and pldp.sizedefinition_id = x.sizedefinition_id
                    and pldp.finishingmethod_id = x.finishingmethod_id
                    and trunc(rqa.adjustmentdate) <= trunc(sysdate)) circinventory, x.qtypool,
               l.code languagecodes
          from (select /*+ INDEX(UI XIF12UNIQUEITEM) */
                       ui.distributionpoint_id, ui.product_id, ui.sizedefinition_id,
                       ui.finishingmethod_id, count(ui.uniqueitem_id) qtypool
                  from uniqueitem ui
                 where ui.poolitem = 1
                 group by ui.distributionpoint_id, ui.product_id,
                          ui.sizedefinition_id, ui.finishingmethod_id) x,
               distributionpoint dp
               join department d
                    join customer c on d.customer_id = c.customer_id
               on dp.department_id = d.department_id,
               product p, sizedefinition sd, finishingmethod fm, languages l
         where p.product_id = x.product_id
           and sd.sizedefinition_id = x.sizedefinition_id
           and fm.finishingmethod_id = x.finishingmethod_id
           and dp.distributionpoint_id = x.distributionpoint_id
           and p.uniquepoolitem = 'Y') v1,
       (select x.reportparam_id, x.yeardel, x.distributionpoint_id, x.product_id, x.size_id,
               x.finishingmethod_id, sum(x.qtydelivered1) qtydelivered1,
               sum(x.qtydelivered2) qtydelivered2, sum(x.qtydelivered3) qtydelivered3,
               sum(x.qtydelivered4) qtydelivered4, sum(x.qtydelivered5) qtydelivered5
          from (select /*+ INDEX(DH XSPEEDDELIVERYHISTORY) */
                       rp.reportparam_id, year(rp.date_value1) yeardel, dh.customer_link_id customer_id,
                       dh.distributionpoint_link_id distributionpoint_id, dh.product_link_id product_id,
                       dh.sizedefinition_link_id size_id, dh.finishingmethod_id, dh.year, dh.week,
                       case when dh.year * 100 + dh.week = rp.number_value1
                         then sum(dh.amountdelivered)
                       else 0 end qtydelivered1,
                       case when dh.year * 100 + dh.week = rp.number_value2
                         then sum(dh.amountdelivered)
                       else 0 end qtydelivered2,
                       case when dh.year * 100 + dh.week = rp.number_value3
                         then sum(dh.amountdelivered)
                       else 0 end qtydelivered3,
                       case when dh.year * 100 + dh.week = rp.number_value4
                         then sum(dh.amountdelivered)
                       else 0 end qtydelivered4,
                       case when dh.year * 100 + dh.week = rp.number_value5
                         then sum(dh.amountdelivered)
                       else 0 end qtydelivered5
                  from deliveryhistory dh
                       join distributionpoint dp
                            join department d on dp.department_id = d.department_id
                       on dh.distributionpoint_link_id = dp.distributionpoint_id,
                       reportparam rp
                 where d.customer_id = rp.number_value
                   and dh.deliverydate >= rp.date_value1
                   and dh.deliverydate <= rp.date_value2
                 group by rp.reportparam_id, rp.date_value1, rp.number_value1, rp.number_value2,
                          rp.number_value3, rp.number_value4, rp.number_value5, dh.customer_link_id,
                          dh.distributionpoint_link_id, dh.product_link_id, dh.sizedefinition_link_id,
                          dh.finishingmethod_id, dh.year, dh.week) x
         group by x.reportparam_id, x.yeardel, x.customer_id, x.distributionpoint_id,
                  x.product_id, x.size_id, x.finishingmethod_id) v2
 where v1.distributionpointid = v2.distributionpoint_id
   and v1.product_id = v2.product_id
   and v1.sizedefinition_id = v2.size_id
   and v1.finishingmethod_id = v2.finishingmethod_id
/

  CREATE OR REPLACE VIEW "V_UNIQUERESIDENTIALITEMS" ("CUSTOMER_ID", "STATUSCODE", "STAY_ID", "STATUSCHANGEDATE", "LASTSTAYDATE", "CURRENTDATE", "CLIENTNUMBER", "CLIENTNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "ROOMNUMBER", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "FINMETHCODE", "FINMETHDESC", "PRIMARYID", "STATUSDESC", "STAYDESC", "LASTSCANDATE", "NUMBEROFWASHES", "UNIQUERESIDENTIALITEM_ID", "LASTINSCANDATE", "LASTOUTSCANDATE", "REMARK", "ASSIGNDATE", "LANGUAGECODE") AS 
  select cl.customer_id, st.code statuscode, sy.stay_id, uri.statuschangedate, uri.laststaydate, trunc(sysdate) currentdate, cl.clientnumber,
       cl.name clientname, d.departmentnumber, d.description departmentdesc, dr.roomnumber,
       coalesce((select plpc.customcode from productlistpercustomer plpc
                  where plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC(cl.customer_id, urip.product_id, urip.sizedefinition_id, urip.finishingmethod_id,
                                                         (select szstar.sizedefinition_id from sizedefinition szstar where szstar.code = '*'), trunc(sysdate), 0))
              , pr.code) productcode,
       coalesce((select plpc.customdescription from productlistpercustomer plpc
                  where plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC(cl.customer_id, urip.product_id, urip.sizedefinition_id, urip.finishingmethod_id,
                                                         (select szstar.sizedefinition_id from sizedefinition szstar where szstar.code = '*'), trunc(sysdate), 0))
              , (select prd.description
                   from product_desc prd
                  where prd.product_id = pr.product_id
                    and prd.language_id = languages.language_id)) productdesc, sz.code sizecode, fm.code finmethcode,
       (select fmd.description
          from finishingcode_desc fmd
         where fmd.finishingcode_id = fm.finishingmethod_id
           and fmd.language_id = languages.language_id) finmethdesc, uri.primaryid,
       (select std.description
          from status_desc std
         where std.status_id = st.status_id
           and std.language_id = languages.language_id) statusdesc,
       (select syd.description
          from stay_desc syd
         where syd.stay_id = sy.stay_id
           and syd.language_id = languages.language_id) staydesc,
       (select max(ris.scantimestamp)
          from residentialitemscan ris
         where ris.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id) lastscandate,
       uri.numberofwashes, uri.uniqueresidentialitem_id, uri.lastinscandate, uri.lastoutscandate, uri.remark, urip.assigndate, languages.code languagecode
  from uniqueresidentialitemproduct urip
  join uniqueresidentialitem uri
       left join clientresident cr
            join departmentroom dr
                 join department d on dr.department_id = d.department_id
            on cr.departmentroom_id = dr.departmentroom_id
       on uri.client_id = cr.client_id
       join client cl on uri.client_id = cl.client_id
       join status st on uri.status_id = st.status_id
       join stay sy on uri.stay_id = sy.stay_id
  on urip.uniqueresidentialitem_id = uri.uniqueresidentialitem_id
  join product pr on urip.product_id = pr.product_id
  join sizedefinition sz on urip.sizedefinition_id = sz.sizedefinition_id
  join finishingmethod fm on urip.finishingmethod_id = fm.finishingmethod_id
  , languages
union all
select cl.customer_id, st.code statuscode, sy.stay_id, uri.statuschangedate, uri.laststaydate, trunc(sysdate) currentdate, cl.clientnumber,
       cl.name clientname, d.departmentnumber, d.description departmentdesc, dr.roomnumber, null productcode, null productdesc, null sizecode,
       null finmethcode, null finmethdesc, uri.primaryid,
       (select std.description
          from status_desc std
         where std.status_id = st.status_id
           and std.language_id = languages.language_id) statusdesc,
       (select syd.description
          from stay_desc syd
         where syd.stay_id = sy.stay_id
           and syd.language_id = languages.language_id) staydesc,
       (select max(ris.scantimestamp)
          from residentialitemscan ris
         where ris.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id) lastscandate,
       uri.numberofwashes, uri.uniqueresidentialitem_id, uri.lastinscandate, uri.lastoutscandate, uri.remark, null assigndate, languages.code languagecode
  from uniqueresidentialitem uri
  left join clientresident cr
       join departmentroom dr
            join department d on dr.department_id = d.department_id
       on cr.departmentroom_id = dr.departmentroom_id
  on uri.client_id = cr.client_id
  join client cl on uri.client_id = cl.client_id
  join status st on uri.status_id = st.status_id
  join stay sy on uri.stay_id = sy.stay_id
  , languages
 where not exists (select 1 from uniqueresidentialitemproduct urip2 where urip2.uniqueresidentialitem_id = uri.uniqueresidentialitem_id)
/

  CREATE OR REPLACE VIEW "V_UNIQUESTOCKROOMITEMPICKLIST" ("LINETYPE", "QGORDERCODE", "STOCKROOMCODE", "STOCKROOMDESCRIPTION", "ROWCODE", "LOCATIONCODE", "PICKINGSEQUENCE", "UNIQUEYN", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "QGRESERVEDCODE", "MODIFICATIONCODEA", "MODIFICATIONCODEB", "MODIFICATIONCODEC", "QTYUNIQUE", "QTYUNIQUERESERVED", "QTYNONUNIQUE", "QTYNONUNIQUERESERVED", "ROUTENUMBER", "DAYCODE", "WORKORDERNUMBER", "REQSTDDELIVERY", "WORKORDERQUANTITYORDERED", "WORKORDERLINERESERVATIONQTY", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "WEARERSEARCHNAME", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "LANGUAGECODE", "ORIGIN", "PRODUCT_ID", "PICKLIST_ID", "PICKLISTNUMBER", "ORDEREDSIZECODE", "QTYTOPICK", "QTYPICKED", "STOCKTYPE", "STOCKLOCAREACODE") AS 
  select 1 linetype,
  qgOrder.Code qgOrderCode, s.code stockroomCode, s.name stockroomDescription, sl.rowcode rowCode
, sl.locationcode locationCode, sl.pickingsequence, wokli.codeuniquely UniqueYN, prd.code ProductCode
, (select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id) productDescription
, sizedef.code SizedefinitionCode, qgReserved.code qgReservedCode
, (select modification.code from modification, workorderlinemodification where workorderlinemodification.modification_id = modification.modification_id
  and wokli.workorderline_id = workorderlinemodification.workorderline_id and workorderlinemodification.sequencenumber=1 ) modificationCodeA
, (select modification.code from modification, workorderlinemodification where workorderlinemodification.modification_id = modification.modification_id
  and wokli.workorderline_id = workorderlinemodification.workorderline_id and workorderlinemodification.sequencenumber=2 ) modificationCodeB
, (select modification.code from modification, workorderlinemodification where workorderlinemodification.modification_id = modification.modification_id
  and wokli.workorderline_id = workorderlinemodification.workorderline_id and workorderlinemodification.sequencenumber=3 ) modificationCodeC
, (sq.qtyunique + sq.qtyuniquewithmodifications) qtyunique, (srg.qtyuniquereserved+srg.qtyuniquewiithmodifreserved) qtyuniquereserved
, sq.qtynonunique , srg.qtynonuniquereserved ,  route.routenumber
, (select day_desc.code from day_desc where day_desc.day_id = route.drivingday_id
  and day_desc.language_id = languages.language_id) DayCode, wok.workordernumber
, wok.requestdate ReqstdDelivery, wokli.quantityordered WorkOrderquantityordered
,  nvl(WRE.QUANTITY, plo.qtypicked) WorkOrderLineReservationQTY
, cu.customernumber, cu.name customerName, we.wearernumber, we.wearersearchname wearerSearchname
, 0 distributionpointnumber,'' distributionpointdescription
, languages.code languageCode
, wok.origin
, prd.product_id
, pl.picklist_id
, pl.picklistnumber
, (select osd.code from sizedefinition_link osd where wokli.sizedefinition_link_id = osd.sizedefinition_link_id)  OrderedSizeCode
, pll.qtytopick qtytopick, pll.qtypicked qtypicked, pll.stocktype stocktype, sl.areacode StockLocAreaCode
from
  workorder wok
    left outer join route on wok.route_id = route.route_id
, weareremployment_link we
, workorderline wokli left outer join workorderlinereservation wre on  wokli.workorderline_id = wre.workorderline_id,
product_link prd, qualitygrade qgReserved, qualitygrade qgOrder
, stockroom s
, stockdefinitionperitem sdi,
  stockreservationpergrade srg
    --left outer
    join (
      stockquantity sq join stockroomlocation sl on sl.stockroomlocation_id = sq.stockroomlocation_id
          ) on srg.stockreservationpergrade_id = sq.stockreservationpergrade_id
, sizedefinition_link sizedef, customer_link cu, languages
, picklist pl, picklistline pll, picklistlineorigin plo, picklistlinelocation pllo
where wok.weareremployment_link_id = we.weareremployment_id
and cu.customer_id = wok.customer_link_id
and wok.workorder_id = wokli.workorder_id
and wokli.requestedgrade_id = qgOrder.Qualitygrade_Id
--and wokli.workorderline_id = wre.workorderline_id
--and wre.stockreservationpergrade_id = srg.stockreservationpergrade_id
and s.stockroom_id = sdi.stockroom_id
and sdi.stockdefinitionperitem_id = srg.stockdefinitionperitem_id
and srg.qualitygrade_id = qgReserved.qualitygrade_id
and sdi.product_id = prd.product_id
and sdi.sizedefinition_id = sizedef.sizedefinition_id
and wok.origin not in (7, 10, 11) --exclude credit notes, mounting and dismounting orders
and sl.locationtype_id in (select lt.locationtype_id from locationtype lt where lt.pickinglocation = 'Y')
and pl.picklist_id = pll.picklist_id and pll.picklistline_id = plo.picklistline_id and pll.picklistline_id=pllo.picklistline_id
and Upper(plo.baselinetable) = 'WORKORDERLINE' and plo.baselinetable_link_id = wokli.workorderline_id and plo.baselinetype = wok.origin
--and wre.stockreservationpergrade_id = pll.stockreservationpergrade_id and wre.stocktype = pll.stocktype
and decode(wokli.codeuniquely, 'N', 1, 'Y', 2, wre.stocktype  ) = pll.stocktype
and wok.processingstockroom_id=s.stockroom_id
and wokli.sizedefinition_link_id=sdi.sizedefinition_id
and wokli.product_link_id=sdi.product_id
and nvl(sdi.customer_id, 0) in (wok.customer_link_id, 0)
and sdi.customerowned = wok.customerowned
and wokli.requestedgrade_id = srg.qualitygrade_id
and pllo.stockroomlocation_id=sl.stockroomlocation_id
union all
select 2 linetype, qgOrder.Code qgOrderCode, s.code stockroomCode, s.name stockroomDescription, sl.rowcode rowCode
, sl.locationcode locationCode, sl.pickingsequence, wokli.codeuniquely UniqueYN, prd.code ProductCode
, (select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id) productDescription
, sizedef.code SizedefinitionCode, qgReserved.code qgReservedCode
, (select modification.code from modification, workorderlinemodification where workorderlinemodification.modification_id = modification.modification_id
  and wokli.workorderline_id = workorderlinemodification.workorderline_id and workorderlinemodification.sequencenumber=1 ) modificationCodeA
, (select modification.code from modification, workorderlinemodification where workorderlinemodification.modification_id = modification.modification_id
  and wokli.workorderline_id = workorderlinemodification.workorderline_id and workorderlinemodification.sequencenumber=2 ) modificationCodeB
, (select modification.code from modification, workorderlinemodification where workorderlinemodification.modification_id = modification.modification_id
  and wokli.workorderline_id = workorderlinemodification.workorderline_id and workorderlinemodification.sequencenumber=3 ) modificationCodeC
, (sq.qtyunique + sq.qtyuniquewithmodifications) qtyunique, (srg.qtyuniquereserved+srg.qtyuniquewiithmodifreserved) qtyuniquereserved
, sq.qtynonunique , srg.qtynonuniquereserved ,  route.routenumber
, (select day_desc.code from day_desc where day_desc.day_id = route.drivingday_id
  and day_desc.language_id = languages.language_id) DayCode, wok.workordernumber
, wok.requestdate ReqstdDelivery, wokli.quantityordered WorkOrderquantityordered
,  nvl(WRE.QUANTITY, plo.qtypicked) WorkOrderLineReservationQTY
,(select c.customernumber from customer_link c where c.customer_link_id = wok.customer_link_id) customernumber,
(select c.name from customer_link c where c.customer_link_id = wok.customer_link_id) customerName
, 0 wearernumber, '' wearerSearchname,
(select d.distributionpointnumber from distributionpoint_link d where d.distributionpoint_link_id = wok.distributionpoint_link_id) distributionpointnumber,
(select d.description from distributionpoint_link d where d.distributionpoint_link_id = wok.distributionpoint_link_id) distributionpointdescription
, languages.code languageCode
, wok.origin
, prd.product_id
, pl.picklist_id
, pl.picklistnumber
, (select osd.code from sizedefinition_link osd where wokli.sizedefinition_link_id = osd.sizedefinition_link_id)  OrderedSizeCode
, pll.qtytopick qtytopick, pll.qtypicked qtypicked,pll.stocktype stocktype, sl.areacode StockLocAreaCode
from
  workorder wok
    left outer join route on wok.route_id = route.route_id
, workorderline wokli left outer join workorderlinereservation wre on  wokli.workorderline_id = wre.workorderline_id, product_link prd, qualitygrade qgReserved, qualitygrade qgOrder
, stockroom s
, stockdefinitionperitem sdi,
  stockreservationpergrade srg
    --left outer
    join (
      stockquantity sq join stockroomlocation sl on sl.stockroomlocation_id = sq.stockroomlocation_id
          ) on srg.stockreservationpergrade_id = sq.stockreservationpergrade_id
, sizedefinition_link sizedef, languages
, picklist pl, picklistline pll, picklistlineorigin plo, picklistlinelocation pllo
where wok.weareremployment_link_id is null
and wok.workorder_id = wokli.workorder_id
and wokli.requestedgrade_id = qgOrder.Qualitygrade_Id
--and wokli.workorderline_id = wre.workorderline_id
--and wre.stockreservationpergrade_id = srg.stockreservationpergrade_id
and s.stockroom_id = sdi.stockroom_id
and sdi.stockdefinitionperitem_id = srg.stockdefinitionperitem_id
and srg.qualitygrade_id = qgReserved.qualitygrade_id
and sdi.product_id = prd.product_id
and sdi.sizedefinition_id = sizedef.sizedefinition_id
and wok.origin not in (7, 10, 11) --exclude credit notes, mounting and dismounting orders
and sl.locationtype_id in (select lt.locationtype_id from locationtype lt where lt.pickinglocation = 'Y')
and pl.picklist_id = pll.picklist_id and pll.picklistline_id = plo.picklistline_id and pll.picklistline_id=pllo.picklistline_id
and Upper(plo.baselinetable) = 'WORKORDERLINE' and plo.baselinetable_link_id = wokli.workorderline_id and plo.baselinetype = wok.origin
--and wre.stockreservationpergrade_id = pll.stockreservationpergrade_id and wre.stocktype = pll.stocktype
and decode(wokli.codeuniquely, 'N', 1, 'Y', 2, wre.stocktype  ) = pll.stocktype
and wok.processingstockroom_id=s.stockroom_id
and wokli.sizedefinition_link_id=sdi.sizedefinition_id
and wokli.product_link_id=sdi.product_id
and nvl(sdi.customer_id, 0) in (wok.customer_link_id, 0)
and sdi.customerowned = wok.customerowned
and wokli.requestedgrade_id = srg.qualitygrade_id
and pllo.stockroomlocation_id=sl.stockroomlocation_id
/

  CREATE OR REPLACE VIEW "V_UNIQUETRUCKLOADLIST" ("PICKLIST_ID", "PICKLISTNUMBER", "ROUTENUMBER", "ROUTEDESCRIPTION", "DRIVINGDATE", "TRUCKCODE", "TRUCKDESCRIPION", "ROUTECONTROL_ID", "STOCKROOMCODE", "STOCKROOMNAME", "DRIVERNUMBER", "DRIVERNAME") AS 
  select pl.picklist_id, pl.picklistnumber, rt.routenumber, rt.description routedescription, rc.drivingdate,
       rc.truckcode, tr.description truckdescripion, rc.routecontrol_id,
       sr.code stockroomcode, sr.name stockroomname, rc.drivernumber--, empl.name drivername
, (select empl.name from employee empl where empl.employeenumber = rc.drivernumber and empl.plant_id = rc.plant_id) drivername
from picklist pl, routecontrol rc, route rt, truck tr, stockroom sr--, employee empl
where rc.routecontrol_id = pl.routecontrol_id
and rt.route_id = rc.route_id
and tr.code = rc.truckcode
and tr.plant_id = rc.plant_id
and sr.stockroom_id = tr.stockroom_id
--and empl.employeenumber = rc.drivernumber
--and empl.plant_id = rc.plant_id
/

  CREATE OR REPLACE VIEW "V_UNIQUETRUCKLOADLISTAS" ("PICKLIST_ID", "PICKLISTLINEAS_ID", "QTYREQUIRED", "QTYTRUCKDIFFERENCE", "QTYTOPICK", "QTYPICKED", "STOCKTYPE", "PRODUCTCODE", "SIZECODE", "LANGUAGE_CODE", "PRODUCTDESCRIPTION") AS 
  select plla.picklist_id, plla.picklistlineas_id, plla.qtyrequired, plla.qtytruckdifference, plla.qtytopick,
       plla.qtypicked, plla.stocktype, pr.code productcode, sd.code sizecode, lan.code Language_code,
(select prd.description from product_desc prd where prd.product_id = pr.product_id and prd.language_id=lan.language_id) productdescription
from picklistlineas plla, product pr, sizedefinition sd, languages lan
where pr.product_id = plla.product_link_id
and plla.sizedefinition_link_id = sd.sizedefinition_id
/

  CREATE OR REPLACE VIEW "V_UNIQUETRUCKLOADLISTPS" ("PICKLIST_ID", "PICKLISTLINE_ID", "STOCKTYPE", "QTYTOPICK", "QTYPICKED", "QTYTOPICKFROMLOCATION", "QTYPICKEDFROMLOCATION", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZECODE", "QUALITYGRADECODE", "QTYNONUNIQUERESERVED", "QTYUNIQUERESERVED", "QTYNONUNIQUE", "QTYUNIQUE", "QTYONSTOCKNONUNIQUE", "QTYONSTOCKUNIQUE", "ROWCODE", "LOCATIONCODE", "PICKINGSEQUENCE", "QTYREQUIRED", "QTYTRUCKDIFFERENCE", "LANGUAGE_CODE", "STOCKLOCAREACODE") AS 
  select pll.picklist_id, pll.picklistline_id, pll.stocktype, pll.qtytopick, pll.qtypicked,
pllo.qtytopick qtytopickfromlocation, pllo.qtypicked qtypickedfromlocation, pr.code productcode,
(select prd.description from product_desc prd where prd.product_id = pr.product_id and prd.language_id=lan.language_id) productdescription, sd.code sizecode, qg.code qualitygradecode,
srg.qtynonuniquereserved, (srg.qtyuniquereserved + srg.qtyuniquewiithmodifreserved) qtyuniquereserved,
sq.qtynonunique, (sq.qtyunique + sq.qtyuniquewithmodifications) qtyunique,
(select sum(qtynonunique) from stockquantity where stockreservationpergrade_id = pll.stockreservationpergrade_id) qtyonstocknonunique,
(select sum(qtyunique + sq.qtyuniquewithmodifications) from stockquantity where stockreservationpergrade_id = pll.stockreservationpergrade_id) qtyonstockunique,
slo.rowcode, slo.locationcode, slo.pickingsequence, pll.qtyrequired, pll.qtytruckdifference,
lan.code Language_code,slo.areacode StockLocAreaCode
from picklistline pll, picklistlinelocation pllo, stockreservationpergrade srg, stockdefinitionperitem sdi, stockroomlocation slo, stockquantity sq, product pr, sizedefinition sd, qualitygrade qg, languages lan
where pllo.picklistline_id = pll.picklistline_id
and srg.stockreservationpergrade_id = pll.stockreservationpergrade_id
and sdi.stockdefinitionperitem_id = srg.stockdefinitionperitem_id
and pllo.stockroomlocation_id = slo.stockroomlocation_id
and sq.stockroomlocation_id = pllo.stockroomlocation_id
and sq.stockreservationpergrade_id = pll.stockreservationpergrade_id
and sdi.product_id = pr.product_id
and sdi.sizedefinition_id = sd.sizedefinition_id
and srg.qualitygrade_id = qg.qualitygrade_id
/

  CREATE OR REPLACE VIEW "V_URI_FLAG" ("UNIQUERESIDENTIALITEM_ID", "FLAG_ID", "LANGUAGECODE", "FLAGCODE", "FLAGDESC", "STARTDATE", "FREETEXTITEM") AS 
  select /*version 2.0*/
       urif.uniqueresidentialitem_id, f.flag_id, l.code languagecode, f.code flagcode,
       fd.description flagdesc, urif.startdate, urif.freetextitem
  from uniqueresidentialitemflag urif
       join flag f
            left join flag_desc fd
                      left join languages l on fd.language_id = l.language_id
            on f.flag_id = fd.flag_id
       on urif.flag_id = f.flag_id
/

  CREATE OR REPLACE VIEW "V_USAGEREPORT" ("CUSTOMERNUMBER", "CUSTOMERNAME", "PRODUCT_CODE", "PRODUCTLISTPERDISTRIBPOINT_ID", "PRODUCT_DESC", "DELIVERYDATE", "DELAMOUNT", "REJECTS", "ADJUSTMENTS", "STOCKLEVEL", "MINIMUMTURNAROUND", "LANGUAGE_CODE", "LANGUAGE_ID", "REPORTPARAM_ID") AS 
  select cu.customernumber, cu.name CustomerName, pr.code Product_Code, plpd.productlistperdistribpoint_id,
(select prd.description from product_desc prd where prd.product_id = pr.product_id and prd.language_id = lan.language_id) Product_Desc,
trunc(sysdate) deliverydate,
coalesce((select sum(dh.amountdelivered) from deliveryhistory dh where dh.customer_link_id = cu.customer_id and dh.distributionpoint_link_id = dp.distributionpoint_id
         and dh.department_link_id = de.department_id and dh.product_link_id = pr.product_id
         and dh.deliverydate >= rp.date_value1 and dh.deliverydate <= rp.date_value2), 0) DelAmount,
coalesce((select sum(dv.amount) from deliveryvariations dv where dv.distributionpoint_id = dp.distributionpoint_id and dv.product_id = pr.product_id
        and dv.origin = 1 and dv.soilcountsubtype = 3 --means REJECTS
        and dv.deliverydate >= rp.date_value1 and dv.deliverydate <= rp.date_value2), 0) Rejects,
coalesce((select sum(rqa1.quantity) from rentalqtyadjustment rqa1 where rqa1.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
         and rqa1.adjustmentdate >= rp.date_value1 and rqa1.adjustmentdate <= rp.date_value2), 0) Adjustments,
coalesce((select sum(rqa2.quantity) from rentalqtyadjustment rqa2 where rqa2.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
         and rqa2.adjustmentdate <= rp.date_value2), 0) StockLevel,
plpc.minimumturnaround,
lan.code Language_Code, lan.language_id, rp.reportparam_id
from productlistpercustomer plpc, productlistperdistribpoint plpd, product pr,
     distributionpoint dp, department de, customer cu, reportparam rp, languages lan
where plpd.product_id = pr.product_id and plpd.distributionpoint_id = dp.distributionpoint_id
      and dp.department_id = de.department_id and de.customer_id = cu.customer_id
      and plpc.product_id = pr.product_id and plpc.customer_id = cu.customer_id
      and cu.customernumber >= rp.number_value1 and cu.customernumber <= rp.number_value2
      and rp.string_value1 = 'false'--summarized layout
union all
select cu.customernumber, cu.name CustomerName, pr.code Product_Code, plpd.productlistperdistribpoint_id,
(select prd.description from product_desc prd where prd.product_id = pr.product_id and prd.language_id = lan.language_id) Product_Desc,
dh.deliverydate, coalesce(dh.amountdelivered, 0) DelAmount,
coalesce((select sum(dv.amount) from deliveryvariations dv where dv.distributionpoint_id = dp.distributionpoint_id and dv.product_id = pr.product_id
        and dv.origin = 1 and dv.soilcountsubtype = 3 --means REJECTS
        and dv.deliverydate = dh.deliverydate-->= rp.date_value1 and dv.deliverydate <= rp.date_value2
        ), 0) Rejects,
coalesce((select sum(rqa1.quantity) from rentalqtyadjustment rqa1 where rqa1.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
         and rqa1.adjustmentdate = dh.deliverydate-->= rp.date_value1 and rqa1.adjustmentdate <= rp.date_value2
         ), 0) Adjustments,
f_sumrqa(rp.reportparam_id, rp.date_value2, dh.deliverydate, pr.code) StockLevel,
plpc.minimumturnaround,
lan.code Language_Code, lan.language_id, rp.reportparam_id
from productlistpercustomer plpc, productlistperdistribpoint plpd, product pr, deliveryhistory dh,
     distributionpoint dp, department de, customer cu, reportparam rp, languages lan
where plpd.product_id = pr.product_id and plpd.distributionpoint_id = dp.distributionpoint_id
      and dp.department_id = de.department_id and de.customer_id = cu.customer_id
      and plpc.product_id = pr.product_id and plpc.customer_id = cu.customer_id
      and dh.customer_link_id = cu.customer_id and dh.distributionpoint_link_id = dp.distributionpoint_id
      and dh.department_link_id = de.department_id and dh.product_link_id = pr.product_id
      and dh.deliverydate >= rp.date_value1 and dh.deliverydate <= rp.date_value2
      and cu.customernumber >= rp.number_value1 and cu.customernumber <= rp.number_value2
      and rp.string_value1 = 'true'
/

  CREATE OR REPLACE VIEW "V_USERDEFDIRINVPERROUTE" ("ROUTECONTROL_ID", "ORIGDRIVINGDATE", "ROUTENUMBER", "ROUTEDESC", "DAYDESC", "INVOICEHEADER_ID", "INVOICENUMBER", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "PREBILLAMOUNT", "INVOICEAMOUNTDECIMALS", "CURRENC", "INVOICEFREQUENCY_ID", "STOPNUMBER", "PLANTCODE", "NAME") AS 
  select rc.routecontrol_id,
       --to_date(rc.originaldrivingdate, 'dd.mm.yyyy') OrigDrivingdate,
       rc.originaldrivingdate OrigDrivingdate,
       r.routenumber, r.description routedesc,
       (select dd.description from day_desc dd where dd.day_id=r.drivingday_id and dd.language_id=p.language_id) daydesc,
       ih.invoiceheader_id, ih.invoicenumber,
       ih.deltocustomernumber, ih.deltocustomername,
       ih.billtocustomernumber, ih.billtocustomername,
       ih.prebillamount,
       cu.invoiceamountdecimals, cu.code currenc,
       ih.invoicefrequency_id,ih.stopnumber,
       p.code plantcode, p.name--, lan.code languagecode
from invoiceheader ih, routecontrol rc, route r, plant p, currency cu--,languages lan
where ih.routecontrol_id = rc.routecontrol_id
and ih.currency_id = cu.currency_id
and rc.route_id = r.route_id
and r.plant_id = p.plant_id
and ih.prebillamount <> 0
/

  CREATE OR REPLACE VIEW "V_USERGROUP" ("GROUPNAME", "DESCRIPTION", "ACTIVE", "REMARK") AS 
  SELECT USERGROUP.GROUPNAME, USERGROUP.DESCRIPTION, USERGROUP.ACTIVE, USERGROUP.REMARK
       FROM USERGROUP
/

  CREATE OR REPLACE VIEW "V_USERINSTRCUSTOMER_BATCH" ("CUSTOMER_ID", "USERINSTRDESC", "DATEACTIVE", "LANGUAGECODE") AS 
  SELECT c.customer_id,
          (SELECT cuid.instruction
             FROM customeruserinstruction_desc cuid
            WHERE     cuid.customeruserinstruction_id =
                         cui.customeruserinstruction_id
                  AND cuid.language_id = l.language_id)
             userinstrdesc,
          cui.dateactive,
          l.code languagecode
     FROM customer c
          LEFT OUTER JOIN customeruserinstruction cui
             ON     cui.customer_id = c.customer_id
                AND EXISTS
                       (SELECT usc.customeruserinstruction_id
                          FROM userinstructionperscreen usc,
                               dialogs d
                         WHERE     usc.customeruserinstruction_id =
                                      cui.customeruserinstruction_id
                               AND cui.dateactive <= SYSDATE   -- KLO 20110321
                               AND cui.dateinactive > SYSDATE  -- KLO 20110321
                               AND usc.dialog_id = d.dialog_id
                               AND upper(d.code) = upper('GarmentDeliveryNote')),
          languages l
/

  CREATE OR REPLACE VIEW "V_USERINSTRCUSTOMER_OUTSCAN" ("CUSTOMER_ID", "USERINSTRDESC", "DATEACTIVE", "LANGUAGECODE") AS 
  SELECT c.customer_id,
          (SELECT cuid.instruction
             FROM customeruserinstruction_desc cuid
            WHERE     cuid.customeruserinstruction_id =
                         cui.customeruserinstruction_id
                  AND cuid.language_id = l.language_id)
             userinstrdesc,
          cui.dateactive,
          l.code languagecode
     FROM customer c
          LEFT OUTER JOIN customeruserinstruction cui
             ON     cui.customer_id = c.customer_id
                AND EXISTS
                       (SELECT usc.customeruserinstruction_id
                          FROM userinstructionperscreen usc,
                               dialogs d
                         WHERE     usc.customeruserinstruction_id =
                                      cui.customeruserinstruction_id
                               AND cui.dateactive <= SYSDATE   -- KLO 20110321
                               AND cui.dateinactive > SYSDATE  -- KLO 20110321
                               AND usc.dialog_id = d.dialog_id
                               AND upper(d.code) = upper('OutScan')),
          languages l
/

  CREATE OR REPLACE VIEW "V_USERINSTRUCTIONSPERCUSTOMER" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DEFAULTBUSINESSUNIT_ID", "BUCODE", "CITY", "ACTIVE", "USERINSTRCODE", "USERINSTRDESC", "USERINSTRUCTION", "CONTAINING_TEXT", "DATEACTIVE", "DATEINACTIVE", "REPORTPARAM_ID", "LANGUAGECODE", "INCLUDETYPE") AS 
  select c.customernumber, c.name customername, c.defaultbusinessunit_id, bu.code bucode, a.city, c.active,
  gui.code userinstrcode,
  (select guid.description from generaluserinstruction_desc guid where guid.generaluserinstruction_id = gui.generaluserinstruction_id
     and guid.language_id = l.language_id) userinstrdesc,
  (select (dbms_lob.substr( guid.instruction))   from generaluserinstruction_desc guid where guid.generaluserinstruction_id = gui.generaluserinstruction_id
     and guid.language_id = l.language_id) userinstruction,
/*  CAST((select lower(guid.description) from generaluserinstruction_desc guid where guid.generaluserinstruction_id = gui.generaluserinstruction_id
     and guid.language_id = l.language_id) as varchar2(255))  userinstrdesc_lower,     */
--  (select instr(lower(guid.description), lower(rp.string_value)) from generaluserinstruction_desc guid where guid.generaluserinstruction_id = gui.generaluserinstruction_id
--     and guid.language_id = l.language_id) containing_text,
  1 containing_text,
  gui.dateactive, gui.dateinactive,
  rp.reportparam_id, l.code languagecode, 1 includetype
from Generaluserinstruction gui, generaluserinstructionpercust guic, customer c, address a, businessunit bu,
  reportparam rp, languages l
where gui.generaluserinstruction_id = guic.generaluserinstruction_id
  and guic.customer_id = c.customer_id
  and exists (select bug.businessunit_id from businessunitsperusergroup bug, systemuser su
      where bug.businessunit_id = c.defaultbusinessunit_id
        and bug.usergroup_id = su.usergroup_id
        and su.systemuser_id = rp.systemuser_id)--rp.number_value)
  and c.visitaddress_id = a.address_id
  and c.defaultbusinessunit_id = bu.businessunit_id
union all -- layout 2
select c.customernumber, c.name customername, c.defaultbusinessunit_id, bu.code bucode, a.city, c.active,
  '' userinstrcode,
  (select (dbms_lob.substr( cuid.instruction)) from customeruserinstruction_desc cuid where cuid.customeruserinstruction_id = cui.customeruserinstruction_id
     and cuid.language_id = l.language_id) userinstrdesc,
  '' userinstruction,
/*  CAST((select lower(cuid.instruction) from customeruserinstruction_desc cuid where cuid.customeruserinstruction_id = cui.customeruserinstruction_id
     and cuid.language_id = l.language_id) as varchar2(255))  userinstrdesc_lower,    */
  (select instr(lower(cuid.instruction), lower(rp.string_value)) from customeruserinstruction_desc cuid where cuid.customeruserinstruction_id = cui.customeruserinstruction_id
     and cuid.language_id = l.language_id) containing_text,
  cui.dateactive, cui.dateinactive,
  rp.reportparam_id, l.code languagecode, 2 includetype
from customeruserinstruction cui, customer c, address a, businessunit bu,
  reportparam rp, languages l
where cui.customer_id = c.customer_id
  and exists (select bug.businessunit_id  from businessunitsperusergroup bug, systemuser su
      where bug.businessunit_id = c.defaultbusinessunit_id
        and bug.usergroup_id = su.usergroup_id
        and su.systemuser_id = rp.systemuser_id)--rp.number_value)
  and c.visitaddress_id = a.address_id
  and c.defaultbusinessunit_id = bu.businessunit_id
--UserInstructionsPerCustomer.RPT
union all --layout 3
select c.customernumber, c.name customername, c.defaultbusinessunit_id, bu.code bucode, a.city, c.active,
  gui.code userinstrcode,
  (select guid.description from generaluserinstruction_desc guid where guid.generaluserinstruction_id = gui.generaluserinstruction_id
     and guid.language_id = l.language_id) userinstrdesc,
  (select (dbms_lob.substr( guid.instruction))   from generaluserinstruction_desc guid where guid.generaluserinstruction_id = gui.generaluserinstruction_id
     and guid.language_id = l.language_id) userinstruction,
  1 containing_text,
  gui.dateactive, gui.dateinactive,
  rp.reportparam_id, l.code languagecode, 3 includetype
from Generaluserinstruction gui,
     customer c, address a, businessunit bu,
     reportparam rp, languages l
  where a.address_id = c.visitaddress_id
  and bu.businessunit_id = c.defaultbusinessunit_id
  and not exists (select 1
                  from generaluserinstructionpercust guic
                  where guic.generaluserinstruction_id = gui.generaluserinstruction_id
                  and   guic.customer_id = c.customer_id
                  )
  and exists (select bug.businessunit_id from businessunitsperusergroup bug, systemuser su
      where bug.businessunit_id = c.defaultbusinessunit_id
        and bug.usergroup_id = su.usergroup_id
        and su.systemuser_id = rp.systemuser_id)
/

  CREATE OR REPLACE VIEW "V_USERINSTRUCTIONSPERCUSTOMER1" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DEFAULTBUSINESSUNIT_ID", "BUCODE", "CITY", "ACTIVE", "USERINSTRCODE", "USERINSTRDESC", "USERINSTRUCTION", "CONTAINING_TEXT", "DATEACTIVE", "DATEINACTIVE", "REPORTPARAM_ID", "LANGUAGECODE", "INCLUDETYPE") AS 
  select c.customernumber, c.name customername, c.defaultbusinessunit_id, bu.code bucode, a.city, c.active,
  gui.code userinstrcode,
  (select guid.description from generaluserinstruction_desc guid where guid.generaluserinstruction_id = gui.generaluserinstruction_id
     and guid.language_id = l.language_id) userinstrdesc,
  (select (dbms_lob.substr( guid.instruction))  from generaluserinstruction_desc guid where guid.generaluserinstruction_id = gui.generaluserinstruction_id
     and guid.language_id = l.language_id) userinstruction,
/*  CAST((select lower(guid.description) from generaluserinstruction_desc guid where guid.generaluserinstruction_id = gui.generaluserinstruction_id
     and guid.language_id = l.language_id) as varchar2(255))  userinstrdesc_lower,     */
--  (select instr(lower(guid.description), lower(rp.string_value)) from generaluserinstruction_desc guid where guid.generaluserinstruction_id = gui.generaluserinstruction_id
--     and guid.language_id = l.language_id) containing_text,
  1 containing_text,
  gui.dateactive, gui.dateinactive,
  rp.reportparam_id, l.code languagecode, 1 includetype
from Generaluserinstruction gui, generaluserinstructionpercust guic, customer c, address a, businessunit bu,
  reportparam rp, languages l
where gui.generaluserinstruction_id = guic.generaluserinstruction_id
  and guic.customer_id = c.customer_id
  and exists (select bug.businessunit_id from businessunitsperusergroup bug, systemuser su
      where bug.businessunit_id = c.defaultbusinessunit_id
        and bug.usergroup_id = su.usergroup_id
        and su.systemuser_id = rp.systemuser_id)--rp.number_value)
  and c.visitaddress_id = a.address_id
  and c.defaultbusinessunit_id = bu.businessunit_id
union all -- layout 2
select c.customernumber, c.name customername, c.defaultbusinessunit_id, bu.code bucode, a.city, c.active,
  '' userinstrcode,
  (select  (dbms_lob.substr( cuid.instruction)) from customeruserinstruction_desc cuid where cuid.customeruserinstruction_id = cui.customeruserinstruction_id
     and cuid.language_id = l.language_id) userinstrdesc,
  '' userinstruction,
/*  CAST((select lower(cuid.instruction) from customeruserinstruction_desc cuid where cuid.customeruserinstruction_id = cui.customeruserinstruction_id
     and cuid.language_id = l.language_id) as varchar2(255))  userinstrdesc_lower,    */
  (select instr(lower(cuid.instruction), lower(rp.string_value)) from customeruserinstruction_desc cuid where cuid.customeruserinstruction_id = cui.customeruserinstruction_id
     and cuid.language_id = l.language_id) containing_text,
  cui.dateactive, cui.dateinactive,
  rp.reportparam_id, l.code languagecode, 2 includetype
from customeruserinstruction cui, customer c, address a, businessunit bu,
  reportparam rp, languages l
where cui.customer_id = c.customer_id
  and exists (select bug.businessunit_id  from businessunitsperusergroup bug, systemuser su
      where bug.businessunit_id = c.defaultbusinessunit_id
        and bug.usergroup_id = su.usergroup_id
        and su.systemuser_id = rp.systemuser_id)--rp.number_value)
  and c.visitaddress_id = a.address_id
  and c.defaultbusinessunit_id = bu.businessunit_id
--UserInstructionsPerCustomer.RPT
/

  CREATE OR REPLACE VIEW "V_VISITSPERCUSTOMER" ("LINE_TYPE", "BUSINESSUNIT_ID", "BU_NUMBER", "BU_DESC", "PLANT_CODE", "PLANT_NAME", "CUSTOMER_ID", "CUSTOMERNUMBER", "NAME", "CITY", "ROUTENUMBER", "ROUTE_DESC", "DELIVERYPOINT_DESC", "STOPNUMBER", "STATUS", "DRIVINGDATE", "DAYNUMBER", "STOP_TRAVELMINUTES", "STOP_VISITMINUTES", "ROUTESTOP_TRAVELMINUTES", "ROUTESTOP_SERVICEMINUTES", "DAY_DESC", "LANGUAGE_CODE") AS 
  SELECT 1 line_type
, bu.businessunit_id, bu.code BU_number, bu.description BU_desc
, pl.code Plant_code, pl.name Plant_name
, cu.customer_id, cu.customernumber, cu.name, a.city
, r.routenumber, r.description Route_desc, dp.description Deliverypoint_desc
, st.stopnumber, st.status, rc.drivingdate, d.daynumber
, st.travelminutes Stop_travelminutes, st.visitminutes Stop_visitminutes
, rs.travelminutes RouteStop_travelminutes, rs.ServiceMinutes RouteStop_ServiceMinutes
, (select dd.description from day_desc dd where d.day_id=dd.day_id and dd.language_id=lan.language_id) Day_desc
, lan.code Language_code
FROM customer cu, businessunit bu, address a, plant pl,
routecontrol rc, route r,
stop st left outer join Deliverypoint dp on st.deliverypoint_id=dp.deliverypoint_id,
day d,
routestop rs,
languages lan
WHERE cu.visitaddress_id=a.address_id and
cu.defaultbusinessunit_id=bu.businessunit_id and
rc.plant_id=bu.plant_id and bu.plant_id=pl.plant_id and
st.routecontrol_id=rc.routecontrol_id and
rc.route_id=r.route_id and
r.route_id=rs.route_id and
st.routestop_id=rs.routestop_id and
st.status in (0,3) and
d.day_id=r.drivingday_id
and st.customer_link_id=cu.customer_id
union
SELECT 2 line_type
, bu.businessunit_id, bu.code BU_number, bu.description BU_desc
, pl.code Plant_code, pl.name Plant_name
, cu.customer_id, cu.customernumber, cu.name, a.city
, r.routenumber, r.description Route_desc, '' Deliverypoint_desc
, st.stopnumber, st.status, rc.drivingdate, d.daynumber
, st.travelminutes Stop_travelminutes, st.visitminutes Stop_visitminutes
, 0 RouteStop_travelminutes, 0 RouteStop_ServiceMinutes
, (select dd.description from day_desc dd where d.day_id=dd.day_id and dd.language_id=lan.language_id) Day_desc
, lan.code Language_code
FROM customer cu, businessunit bu, address a, plant pl, day d,
routecontrol rc, route r, stop st ,--routestop rs left outer join Deliverypoint dp on rs.deliverypoint_id=dp.deliverypoint_id,
languages lan
WHERE cu.visitaddress_id=a.address_id and
cu.defaultbusinessunit_id=bu.businessunit_id and
rc.plant_id=pl.plant_id and
bu.plant_id=pl.plant_id and
st.routecontrol_id=rc.routecontrol_id and
rc.route_id=r.route_id and --r.route_id=rs.route_id and --
st.routestop_id is null
and st.status in (0,3) and
d.day_id=r.drivingday_id
and st.customer_link_id=cu.customer_id
/

  CREATE OR REPLACE VIEW "V_VOLUMEREVENUE" ("CUSTOMERNUMBER", "CUSTOMERNAME", "LINETYPE", "WEIGHINGCATEGORYCODE", "DELIVERYDATE", "NETWEIGHT", "AMOUNTINVOICED") AS 
  select cl.customernumber, cl.name customername, 1 linetype,
       wcat.code weighingcategorycode,
       wh.weighingdate deliverydate,
       sum(wh.cleanweight) netweight, --+ wh.cleanweight,
       (sum(wh.cleanweight)*pack_price.Weight_Price(cl.customer_id, wcat.weighingcategory_id, 'N', wh.weighingdate)) amountinvoiced
from weighinghistory wh, customer_link cl, weighingcategory_link wcat
where wh.customer_link_id = cl.customer_link_id
      and wh.weighingcategory_link_id = wcat.weighingcategory_link_id
group by cl.customernumber, cl.name, cl.customer_id, wh.weighingdate, wcat.code, wcat.weighingcategory_id
union all
select --not used + INDEX(dp XPKDISTRIBUTIONPOINT_LINK) INDEX(d XPKDEPARTMENT) INDEX(c XPKCUSTOMER_LINK) INDEX(wpc XAK2WEIGHINGCATEGPERCUSTOMER)
      c.customernumber, c.name customername, 2 linetype,
      (select wc.code from weighingcategory_link wc, product p where pnl.product_id = p.product_id
              and p.weighingcategory_id = wc.weighingcategory_id) weighingcategorycode,
       pn.deliverydate, 0 netweight,
       ( sum(pnl.deliveredamount) * pack_price.Wash_Price(c.customer_id, pnl.product_id, pnl.sizedefinition_id, pnl.finishingmethod_id, pn.deliverydate)) amountinvoiced
from customer_link c,
      packingnote pn,
      packingnoteline pnl
      , distributionpoint_link dp, department d
where pn.packingnote_id = pnl.packingnote_id
     and pn.distributionpoint_id = dp.distributionpoint_id
     and dp.department_link_id = d.department_id
     and d.customer_id = c.customer_link_id
     and pn.status_id = (select s.status_id from status s where s.statustype = 'PN' and s.code = '30')
group by c.customernumber, c.name, pnl.product_id, pn.deliverydate, c.customer_id, pnl.sizedefinition_id, pnl.finishingmethod_id
union all--Invoiced Loss for pool + Credit for pool
select --not used + INDEX(il XIF934INVOICELINE)
       ih.deltocustomernumber customernumber, ih.deltocustomername customername, 3 linetype,
       '0' weighingcategorycode,
       ih.enddate deliverydate, sum(il.billedqty) netweight,
       sum(il.amount) amountinvoiced
from invoiceheader ih, invoiceline il, status st
where ih.invoiceheader_id = il.invoiceheader_id
      and il.invoicelinetype_id = 9 and il.invoicelinesubtype in (37, 38)--Loss for pool + Credit for pool
      and ih.status_id = st.status_id and st.code='2'--td20639 SSB - select only finalized invoices
group by ih.deltocustomernumber, ih.deltocustomername, ih.enddate
/

  CREATE OR REPLACE VIEW "V_V_CONTRACTEXPIRATION_RC" ("CUSTOMERNUMBER", "ROUTENUMBER", "ROUTE_ID", "CUSTOMER_ID") AS 
  select distinct cu.customernumber, r.routenumber, r.route_id, cu.customer_id
from route r, routestop rs, customer cu
where r.route_id = rs.route_id
  and rs.customer_id = cu.customer_id
/

  CREATE OR REPLACE VIEW "V_WAITINGMOUNTINGORDER" ("WORKORDER_ID", "WORKORDERNUMBER", "STATUS_ID", "BUSINESSUNIT_ID", "ROUTE_ID", "REQUESTDATE", "ENTRYDATE", "NEEDEDDATE", "EXPECTEDCOMPLETEDATE", "COMPLETIONDATE", "REFERENCENUMBER", "CUSTOMEROWNED", "DELIVERFROM", "SYSTEMUSER_ID", "TIMESTAMP", "CUSTOMER_LINK_ID", "ORDERED", "ORIGIN", "AVAILABILITY", "DISTRIBUTIONPOINT_LINK_ID", "SLADELIVERYDATE", "PLANTDEPARTMENT_ID", "PROCESSINGSTOCKROOM_ID", "DRIVERSALES", "TRUCK_ID", "BILLTOCUSTOMERRELATED", "CODESTATUS") AS 
  SELECT T.WORKORDER_ID ,T.WORKORDERNUMBER,T.STATUS_ID,T.BUSINESSUNIT_ID,T.ROUTE_ID,T.REQUESTDATE,T.ENTRYDATE,T.NEEDEDDATE,
T.EXPECTEDCOMPLETEDATE,T.COMPLETIONDATE,T.REFERENCENUMBER,T.CUSTOMEROWNED,T.DELIVERFROM,
T.SYSTEMUSER_ID,T.TIMESTAMP,T.CUSTOMER_LINK_ID,T.ORDERED,T.ORIGIN,T.AVAILABILITY,T.DISTRIBUTIONPOINT_LINK_ID,
T.SLADELIVERYDATE,T.PLANTDEPARTMENT_ID,T.PROCESSINGSTOCKROOM_ID,T.DRIVERSALES,T.TRUCK_ID, T.BILLTOCUSTOMERRELATED, S.CODE AS CODESTATUS
FROM WORKORDER T, STATUS S
WHERE T.ORIGIN = 10
AND T.STATUS_ID = S.STATUS_ID
AND S.STATUSTYPE = 'MO'
AND S.CODE IN ('05','12')
/

  CREATE OR REPLACE VIEW "V_WASHPROCESSPERCHIP" ("PLANTCODE", "CHIPNUMBER", "WASHINGPROCESS", "ITEMWEIGHT", "PRODUCTCODE", "CUSTOMERNUMBER") AS 
  select (select pl.code from plant pl where pl.plant_id = b.plant_id) plantcode,
       u.primaryid chipnumber, nvl(wp.sortaddress, 0) washingprocess,
       nvl((select ps.theoreticalweight
            from   productsize ps
            where  ps.product_id = u.product_id
            and    ps.sizedefinition_id = u.sizedefinition_id), p.theoreticalweight) itemweight,
       p.code productcode,
       nvl((select c.customernumber
            from   uniqueitemnonpool un, weareremployment we, wearer w, customer c
            where  un.uniqueitem_id = u.uniqueitem_id
            and    un.weareremployment_id = we.weareremployment_id
            and    we.wearer_id = w.wearer_id
            and    w.customer_id = c.customer_id), 0) customernumber
from   uniqueitem u, businessunit b, product p, status s, sortaddressperwashprocess wp
where  u.businessunit_id = b.businessunit_id
and    u.product_id = p.product_id
and    wp.plant_id = b.plant_id
and    wp.washingprocess_id =
coalesce((select plpc.washingprocess_id from productlistpercustomer plpc
          where plpc.productlistpercustomer_id
          = F_GetIDColumnFromActivePLPC((select c.customer_id
            from   uniqueitemnonpool un, weareremployment we, wearer w, customer c
            where  un.uniqueitem_id = u.uniqueitem_id
            and    un.weareremployment_id = we.weareremployment_id
            and    we.wearer_id = w.wearer_id
            and    w.customer_id = c.customer_id), p.product_id, u.sizedefinition_id, u.finishingmethod_id,
						(select sizedefinition.sizedefinition_id from sizedefinition where sizedefinition.code = '*'),
						sysdate, 0))
						, (select pps.washingprocess_id from plantproductsettings pps where pps.product_id = p.product_id
                                                   and pps.plant_id=b.plant_id)
						, p.washingprocess_id)
and    u.status_id = s.status_id
and    s.statustype = 'UI'
and    s.code in ('20', '30', '50') -- in circ, assigned or sold
/

  CREATE OR REPLACE VIEW "V_WASHRENTREVENUEPERCUSTOMER" ("DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "BU_CODE", "DELCHAIN_CODE", "BILLCHAIN_CODE", "MACHAIN_CODE", "MA_NUMBER", "MA_NAME", "INVOICEDATE", "PROD_CODE", "PRODGROUP_CODE", "PROD_DESC", "PRODGROUP_DESC", "INVOICELINETYPE_ID", "INVOICELINESUBTYPE", "BILLEDQTY", "AMOUNT", "THEORETICALWEIGHT", "QTYRENT", "QTYWASHLOG", "TURNOVERLOG", "QTYWASHCOG", "TURNOVERCOG", "SALESQTY", "SALESTURNOVER", "LAN_CODE", "DELTODEFAULTBU", "BILLTODEFAULTBU", "MADEFAULTBU", "SYSTEMUSER_ID") AS 
  select --Rent
ih.deltocustomernumber, ih.deltocustomername, ih.billtocustomernumber, ih.billtocustomername
, (select ibu.code from businessunit ibu where ibu.businessunit_id = ih.invoicebusinessunit_id) Bu_code
, (select ch.code from customer del join chain ch on del.chain_id = ch.chain_id where ih.deltocustomer_link_id = del.customer_id) DelChain_code
, (select ch.code from customer bill join chain ch on bill.chain_id = ch.chain_id where ih.billtocustomer_link_id = bill.customer_id) BillChain_code
, (select ch.code from customer cl join customer ma on cl.masteraccount_id = ma.customer_id
                       join chain ch on ma.chain_id = ch.chain_id where ih.billtocustomer_link_id = cl.customer_id) MAChain_code
, (select ma.customernumber from customer cl join customer ma on cl.masteraccount_id = ma.customer_id where ih.billtocustomer_link_id = cl.customer_id) MA_number
, (select ma.name from customer cl join customer ma on cl.masteraccount_id = ma.customer_id where ih.billtocustomer_link_id = cl.customer_id) MA_name
, ih.invoicedate, pr.code Prod_code, pg.code ProdGroup_code
, (select prd.description from product_desc prd where pr.product_id = prd.product_id and prd.language_id = lan.language_id) Prod_desc
, (select pgd.description from productgroup_desc pgd where pg.productgroup_id = pgd.productgroup_id and pgd.language_id = lan.language_id) ProdGroup_desc
, il.invoicelinetype_id, il.invoicelinesubtype, il.billedqty, il.amount
, 0 theoreticalweight
, il.billedqty QTYRent, 0 QTYWashLog, il.amount TurnoverLog, 0 QTYWashCog, 0 TurnoverCog, 0 SalesQty, 0 SalesTurnover
, lan.code Lan_code
, (select dbu.code from businessunit dbu join customer delto on dbu.businessunit_id = delto.defaultbusinessunit_id
          where ih.deltocustomer_link_id = delto.customer_id) deltodefaultbu
, (select bbu.code from businessunit bbu join customer billto on bbu.businessunit_id = billto.defaultbusinessunit_id
          where ih.billtocustomer_link_id = billto.customer_id) billtodefaultbu
, (select mabu.code from businessunit mabu join customer ma on mabu.businessunit_id = ma.defaultbusinessunit_id
                         join customer bill on ma.customer_id = bill.masteraccount_id
   where ih.billtocustomer_link_id = bill.customer_id) madefaultbu
, su.systemuser_id
from invoiceheader ih
join status st on ih.status_id = st.status_id
join invoiceline il on ih.invoiceheader_id = il.invoiceheader_id
join invoicelineproduct ip on ip.invoiceline_id = il.invoiceline_id
join product pr on ip.product_link_id = pr.product_id
join productgroup pg on pr.productgroup_id = pg.productgroup_id
, languages lan, systemuser su
where  ih.documenttype = 1 and  st.statustype = 'IN' and st.code = 2
and il.invoicelinetype_id = 1
and exists (select * from businessunitsperusergroup bug
    where bug.businessunit_id = ih.invoicebusinessunit_id and bug.usergroup_id = su.usergroup_id)
union all
select --Wash LOG
ih.deltocustomernumber, ih.deltocustomername, ih.billtocustomernumber, ih.billtocustomername
, (select ibu.code from businessunit ibu where ibu.businessunit_id = ih.invoicebusinessunit_id) Bu_code
, (select ch.code from customer del join chain ch on del.chain_id = ch.chain_id where ih.deltocustomer_link_id = del.customer_id) DelChain_code
, (select ch.code from customer bill join chain ch on bill.chain_id = ch.chain_id where ih.billtocustomer_link_id = bill.customer_id) BillChain_code
, (select ch.code from customer cl join customer ma on cl.masteraccount_id = ma.customer_id
                       join chain ch on ma.chain_id = ch.chain_id where ih.billtocustomer_link_id = cl.customer_id) MAChain_code
, (select ma.customernumber from customer cl join customer ma on cl.masteraccount_id = ma.customer_id where ih.billtocustomer_link_id = cl.customer_id) MA_number
, (select ma.name from customer cl join customer ma on cl.masteraccount_id = ma.customer_id where ih.billtocustomer_link_id = cl.customer_id) MA_name
, ih.invoicedate, pr.code Prod_code, pg.code ProdGroup_code
, (select prd.description from product_desc prd where pr.product_id = prd.product_id and prd.language_id = lan.language_id) Prod_desc
, (select pgd.description from productgroup_desc pgd where pg.productgroup_id = pgd.productgroup_id and pgd.language_id = lan.language_id) ProdGroup_desc
, il.invoicelinetype_id, il.invoicelinesubtype, il.billedqty, il.amount
, il.billedqty * coalesce((select max(ps.theoreticalweight) from productsize ps where ps.product_id = pr.product_id and ip.sizedefinition_link_id = ps.sizedefinition_id), 0) theoreticalweight
, 0 QTYRent
, il.billedqty QTYWashLog
, round((select sum(pnl.deliveredamount) * pack_price.Wash_Price(ih.billtocustomer_link_id, ip.product_link_id, ip.sizedefinition_link_id, ip.finishingmethod_id, ih.invoicedate, 1)
          from packingnoteline pnl
          where pnl.invoiceheader_id = ih.invoiceheader_id and pnl.product_id = ip.product_link_id and pnl.finishingmethod_id = ip.finishingmethod_id), 2) TurnoverLog
, 0 QTYWashCog, 0 TurnoverCog, 0 SalesQty, 0 SalesTurnover
, lan.code Lan_code
, (select dbu.code from businessunit dbu join customer delto on dbu.businessunit_id = delto.defaultbusinessunit_id
          where ih.deltocustomer_link_id = delto.customer_id) deltodefaultbu
, (select bbu.code from businessunit bbu join customer billto on bbu.businessunit_id = billto.defaultbusinessunit_id
          where ih.billtocustomer_link_id = billto.customer_id) billtodefaultbu
, (select mabu.code from businessunit mabu join customer ma on mabu.businessunit_id = ma.defaultbusinessunit_id
                         join customer bill on ma.customer_id = bill.masteraccount_id
   where ih.billtocustomer_link_id = bill.customer_id) madefaultbu
, su.systemuser_id
from invoiceheader ih
join status st on ih.status_id = st.status_id
join invoiceline il on ih.invoiceheader_id = il.invoiceheader_id
join invoicelineproduct ip on ip.invoiceline_id = il.invoiceline_id
join product pr on ip.product_link_id = pr.product_id
join productgroup pg on pr.productgroup_id = pg.productgroup_id
, languages lan, systemuser su
where ih.documenttype = 1 and st.statustype = 'IN' and st.code = 2
and il.invoicelinetype_id = 2 and il.invoicelinesubtype <> 15
and exists (select * from businessunitsperusergroup bug
    where bug.businessunit_id = ih.invoicebusinessunit_id and bug.usergroup_id = su.usergroup_id)
union all
select --Wash COG
ih.deltocustomernumber, ih.deltocustomername, ih.billtocustomernumber, ih.billtocustomername
, (select ibu.code from businessunit ibu where ibu.businessunit_id = ih.invoicebusinessunit_id) Bu_code
, (select ch.code from customer del join chain ch on del.chain_id = ch.chain_id where ih.deltocustomer_link_id = del.customer_id) DelChain_code
, (select ch.code from customer bill join chain ch on bill.chain_id = ch.chain_id where ih.billtocustomer_link_id = bill.customer_id) BillChain_code
, (select ch.code from customer cl join customer ma on cl.masteraccount_id = ma.customer_id
                       join chain ch on ma.chain_id = ch.chain_id where ih.billtocustomer_link_id = cl.customer_id) MAChain_code
, (select ma.customernumber from customer cl join customer ma on cl.masteraccount_id = ma.customer_id where ih.billtocustomer_link_id = cl.customer_id) MA_number
, (select ma.name from customer cl join customer ma on cl.masteraccount_id = ma.customer_id where ih.billtocustomer_link_id = cl.customer_id) MA_name
, ih.invoicedate, pr.code Prod_code, pg.code ProdGroup_code
, (select prd.description from product_desc prd where pr.product_id = prd.product_id and prd.language_id = lan.language_id) Prod_desc
, (select pgd.description from productgroup_desc pgd where pg.productgroup_id = pgd.productgroup_id and pgd.language_id = lan.language_id) ProdGroup_desc
, il.invoicelinetype_id, il.invoicelinesubtype, il.billedqty, il.amount
, coalesce((select max(ps.theoreticalweight) from productsize ps where ps.product_id = pr.product_id and ip.sizedefinition_link_id = ps.sizedefinition_id), 0) theoreticalweight
, 0 QTYRent, 0 QTYWashLog, 0 TurnoverLog
, il.billedqty QTYWashCog
, round((select sum(pnl.deliveredcogqty) * pack_price.Wash_Price(ih.billtocustomer_link_id, ip.product_link_id, ip.sizedefinition_link_id, ip.finishingmethod_id, ih.invoicedate, 2)
          from packingnoteline pnl
          where pnl.invoiceheader_id = ih.invoiceheader_id and pnl.product_id = ip.product_link_id and pnl.finishingmethod_id = ip.finishingmethod_id), 2) TurnoverCog
, 0 SalesQty, 0 SalesTurnover
, lan.code Lan_code
, (select dbu.code from businessunit dbu join customer delto on dbu.businessunit_id = delto.defaultbusinessunit_id
          where ih.deltocustomer_link_id = delto.customer_id) deltodefaultbu
, (select bbu.code from businessunit bbu join customer billto on bbu.businessunit_id = billto.defaultbusinessunit_id
          where ih.billtocustomer_link_id = billto.customer_id) billtodefaultbu
, (select mabu.code from businessunit mabu join customer ma on mabu.businessunit_id = ma.defaultbusinessunit_id
                         join customer bill on ma.customer_id = bill.masteraccount_id
   where ih.billtocustomer_link_id = bill.customer_id) madefaultbu
, su.systemuser_id
from invoiceheader ih
join status st on ih.status_id = st.status_id
join invoiceline il on ih.invoiceheader_id = il.invoiceheader_id
join invoicelineproduct ip on ip.invoiceline_id = il.invoiceline_id
join product pr on ip.product_link_id = pr.product_id
join productgroup pg on pr.productgroup_id = pg.productgroup_id
, languages lan, systemuser su
where ih.documenttype = 1 and st.statustype = 'IN' and st.code = 2
and il.invoicelinetype_id = 2 and il.invoicelinesubtype = 15
and exists (select * from businessunitsperusergroup bug
    where bug.businessunit_id = ih.invoicebusinessunit_id and bug.usergroup_id = su.usergroup_id)
union all
select --Sales
ih.deltocustomernumber, ih.deltocustomername, ih.billtocustomernumber, ih.billtocustomername
, (select ibu.code from businessunit ibu where ibu.businessunit_id = ih.invoicebusinessunit_id) Bu_code
, (select ch.code from customer del join chain ch on del.chain_id = ch.chain_id where ih.deltocustomer_link_id = del.customer_id) DelChain_code
, (select ch.code from customer bill join chain ch on bill.chain_id = ch.chain_id where ih.billtocustomer_link_id = bill.customer_id) BillChain_code
, (select ch.code from customer cl join customer ma on cl.masteraccount_id = ma.customer_id
                       join chain ch on ma.chain_id = ch.chain_id where ih.billtocustomer_link_id = cl.customer_id) MAChain_code
, (select ma.customernumber from customer cl join customer ma on cl.masteraccount_id = ma.customer_id where ih.billtocustomer_link_id = cl.customer_id) MA_number
, (select ma.name from customer cl join customer ma on cl.masteraccount_id = ma.customer_id where ih.billtocustomer_link_id = cl.customer_id) MA_name
, ih.invoicedate, pr.code Prod_code, pg.code ProdGroup_code
, (select prd.description from product_desc prd where pr.product_id = prd.product_id and prd.language_id = lan.language_id) Prod_desc
, (select pgd.description from productgroup_desc pgd where pg.productgroup_id = pgd.productgroup_id and pgd.language_id = lan.language_id) ProdGroup_desc
, il.invoicelinetype_id, il.invoicelinesubtype, il.billedqty, il.amount
, il.billedqty * coalesce((select max(ps.theoreticalweight) from productsize ps where ps.product_id = pr.product_id and ip.sizedefinition_link_id = ps.sizedefinition_id), 0) theoreticalweight
, 0 QTYRent, 0 QTYWashLog, 0 TurnoverLog, 0 QTYWashCog, 0 TurnoverCog, il.billedqty SalesQty, il.amount SalesTurnover
, lan.code Lan_code
, (select dbu.code from businessunit dbu join customer delto on dbu.businessunit_id = delto.defaultbusinessunit_id
          where ih.deltocustomer_link_id = delto.customer_id) deltodefaultbu
, (select bbu.code from businessunit bbu join customer billto on bbu.businessunit_id = billto.defaultbusinessunit_id
          where ih.billtocustomer_link_id = billto.customer_id) billtodefaultbu
, (select mabu.code from businessunit mabu join customer ma on mabu.businessunit_id = ma.defaultbusinessunit_id
                         join customer bill on ma.customer_id = bill.masteraccount_id
   where ih.billtocustomer_link_id = bill.customer_id) madefaultbu
, su.systemuser_id
from invoiceheader ih
join status st on ih.status_id = st.status_id
join invoiceline il on ih.invoiceheader_id = il.invoiceheader_id
join invoicelineproduct ip on ip.invoiceline_id = il.invoiceline_id
join product pr on ip.product_link_id = pr.product_id
join productgroup pg on pr.productgroup_id = pg.productgroup_id
, languages lan, systemuser su
where ih.documenttype = 1 and st.statustype = 'IN' and st.code = 2
and il.invoicelinetype_id = 5
and exists (select * from businessunitsperusergroup bug
    where bug.businessunit_id = ih.invoicebusinessunit_id and bug.usergroup_id = su.usergroup_id)
/

  CREATE OR REPLACE VIEW "V_WEARER" ("CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "FULLNAME", "SEARCHNAME", "EMBLEMNAME", "CUSTOMEREMPLOYEENUMBER", "SEX", "DUMMYFORPOOL", "DATEACTIVE", "DATEINACTIVE", "REMARK", "WEARERFLAGCODE", "WEARERFLAGDESC", "SEQUENCENUMBER", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "WEARERFUNCTIONCODE", "WEARERFUNCTIONDESCRIPTION", "EMPLOYMENTFLAGCODE", "EMPLOYMENTFLAGDESC", "DELIVERYPOINTCODE", "DELIVERYPOINTDESCRIPTION", "LOCKERBANK", "LOCKERLOCKER", "GARMENTDISPENSERCODE", "GARMENTDISPENSERDESCRIPTION", "DISPENSECREDIT", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, WEARER.WEARERNUMBER, WEARER.FULLNAME,
 WEARER.SEARCHNAME, WEARER.EMBLEMNAME, WEARER.CUSTOMEREMPLOYEENUMBER, WEARER.SEX, WEARER.DUMMYFORPOOL,
 WEARER.DATEACTIVE, WEARER.DATEINACTIVE, WEARER.REMARK,
 WEARERFLAG.CODE FLAGCODE,
 (select  y.description from  FLAG_desc y where WEARER.FLAG_ID = y.flag_id and y.language_id = LANGUAGES.language_id),
 WEAREREMPLOYMENT.SEQUENCENUMBER, DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION,
 DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION, WEARERFUNCTION.CODE, WEARERFUNCTION.DESCRIPTION,
 EMPLOYMENTFLAG.CODE FLAGCODE,
 (select  y.description from FLAG_desc y where WEAREREMPLOYMENT.FLAG_ID = y.flag_id and y.language_id = LANGUAGES.language_id),
 DELIVERYPOINT.CODE, DELIVERYPOINT.DESCRIPTION,
 LOCKER.BANK, LOCKER.LOCKER, GARMENTDISPENSER.CODE, GARMENTDISPENSER.DESCRIPTION, WEAREREMPLOYMENT.DISPENSECREDIT,
 WEARER.SYSTEMUSER_ID, WEARER.TIMESTAMP, LANGUAGES.CODE
	FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT,
      WEARER
      LEFT OUTER JOIN FLAG WEARERFLAG ON (WEARER.FLAG_ID = WEARERFLAG.FLAG_ID),
   WEAREREMPLOYMENT
   LEFT OUTER JOIN FLAG EMPLOYMENTFLAG ON (WEAREREMPLOYMENT.FLAG_ID = EMPLOYMENTFLAG.FLAG_ID)
   LEFT OUTER JOIN LOCKER  ON (WEAREREMPLOYMENT.LOCKER_ID = LOCKER.LOCKER_ID)
   LEFT OUTER JOIN GARMENTDISPENSER ON (WEAREREMPLOYMENT.GARMENTDISPENSER_ID = GARMENTDISPENSER.GARMENTDISPENSER_ID)
   LEFT OUTER JOIN DELIVERYPOINT  ON (WEAREREMPLOYMENT.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID)
   LEFT OUTER JOIN WEARERFUNCTION  ON (WEAREREMPLOYMENT.WEARERFUNCTION_ID = WEARERFUNCTION.WEARERFUNCTION_ID),LANGUAGES
	WHERE WEARER.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
    AND WEARER.WEARER_ID = WEAREREMPLOYMENT.WEARER_ID
    AND WEAREREMPLOYMENT.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
    AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
/

  CREATE OR REPLACE VIEW "V_WEARERDELIVERYNOTE" ("GARMENTBATCH_ID", "GARMENTBATCHNUMBER", "BOXNUMBER", "WEARERNUMBER", "WEARERNAME", "WEARER_REMARK", "PRODUCT_CODE", "PRODUCT_DESC", "PRIMARYID", "GARMENTBATCHSORTING", "CUSTOMERNUMBER", "CUSTOMERNAME", "NOTENUMBER", "PLANNEDDELIVERYDATE", "ROUTENUMBER", "ROUTEDESC", "STOPNUMBER", "PLANNEDDELIVERYWEEKNR", "PLANNEDDELIVERYDAYOFWKNR", "PLANNEDDELIVERYDAYOFWKDESC", "BANK", "LOCKER", "DELPOINT_DESC", "DEPARTMENTDESCRIPTION", "STREET", "STREET2", "ZIPCODE", "CITY", "BUSINESSUNIT_CODE", "BUSINESSUNIT_DESC", "BUSINESSUNIT_ID", "PLANTCODE", "PLANTNAME", "PHONENO", "EMAIL", "PLANTSTREET", "PLANTSTREET2", "PLANTZIPCODE", "PLANTCITY", "PRINTSTICKERATOUTSCAN", "LANGUAGE_CODE", "SIZEDEF") AS 
  select /*version 1.0*/
       gb.garmentbatch_id, gb.garmentbatchnumber, gbsrt.boxnumber, wr.wearernumber,
       wr.fullname wearername, wr.remark wearer_remark, pr.code product_code,
       (select pd.description
          from product_desc pd
         where pd.product_id = pr.product_id
           and pd.language_id = lan.language_id) product_desc,
       ui.primaryid, gbsrt.garmentbatchsorting, cu.customernumber, cu.name customername, pn.notenumber,
       pn.deliverydate planneddeliverydate, ro.routenumber, ro.description routedesc, pn.stopnumber,
       getweeknumber(pn.deliverydate) planneddeliveryweeknr,
       getabsdaynumber(pn.deliverydate) planneddeliverydayofwknr,
       (select dad.description
          from day_desc dad, day da
         where da.daynumber = getabsdaynumber(pn.deliverydate)
           and dad.day_id = da.day_id
           and dad.language_id = lan.language_id) planneddeliverydayofwkdesc,
       lo.bank, lo.locker, delp.description delpoint_desc, dep.description departmentdescription,
       adr.street, adr.street2, adr.zipcode, adr.city, bu.code businessunit_code, bu.description businessunit_desc,
       bu.businessunit_id, pl.code plantcode, pl.name plantname, pl.phoneno, pl.email,
       plad.street plantstreet, plad.street2 plantstreet2, plad.zipcode plantzipcode, plad.city plantcity,
       (select fm.printstickeratoutscan
          from finishingmethod fm
         where fm.finishingmethod_id = ui.finishingmethod_id) printstickeratoutscan,
       lan.code language_code,
       (select sd.code
          from sizedefinition sd
         where sd.sizedefinition_id = ui.sizedefinition_id) sizedef
  from garmentbatch gb
       join businessunit bu
            join plant pl
                 join address plad on plad.address_id = pl.address_id
            on pl.plant_id = bu.plant_id
       on gb.businessunit_id = bu.businessunit_id
       join garmentbatchsort gbsrt
            join customer cu on gbsrt.customer_link_id = cu.customer_id
            join garmentbatchscan gbscan
                 join uniqueitemnonpool uinp
                      join weareremployment we
                           join wearer wr on we.wearer_id = wr.wearer_id
                           join locker lo on we.locker_id = lo.locker_id
                           join distributionpoint dp
                                join department dep on dp.department_id = dep.department_id
                           on we.distributionpoint_id = dp.distributionpoint_id
                      on uinp.weareremployment_id = we.weareremployment_id
                      join uniqueitem ui
                           join product pr on ui.product_id = pr.product_id
                      on uinp.uniqueitem_id = ui.uniqueitem_id
                 on gbscan.uniqueitem_id = uinp.uniqueitem_id
                 join deliveryscan ds
                      join packingnote pn
                           left join route ro on pn.route_id = ro.route_id
                      on ds.packingnote_id = pn.packingnote_id
                      join deliverypoint delp
                           join address adr on delp.deliveryaddress_id = adr.address_id
                      on ds.deliverypoint_link_id = delp.deliverypoint_id
                 on gbscan.uniqueitem_id = ds.uniqueitem_link_id
            on gbsrt.garmentbatchsort_id = gbscan.garmentbatchsort_id
       on gb.garmentbatch_id = gbsrt.garmentbatch_id
       cross join languages lan
 where cu.boxdeliverydocument = 'Y'
   and gbscan.scantype = 1 --Outscan
   and ds.batchnumber = cast(gb.garmentbatchnumber as varchar2(15))
/

  CREATE OR REPLACE VIEW "V_WEARERFUNCTION" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CODE", "DESCRIPTION", "DEFAULTDISPENSECREDIT", "SYSTEMUSER_ID", "TIMESTAMP") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, WEARERFUNCTION.CODE, WEARERFUNCTION.DESCRIPTION,
 WEARERFUNCTION.DEFAULTDISPENSECREDIT,WEARERFUNCTION.SYSTEMUSER_ID, WEARERFUNCTION.TIMESTAMP
	FROM WEARERFUNCTION, CUSTOMER
	WHERE WEARERFUNCTION.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
/

  CREATE OR REPLACE VIEW "V_WEARERINVENTORY" ("CUSTOMERNUMBER", "NAME", "WEARERNUMBER", "SEARCHNAME", "SEQUENCENUMBER", "CODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "FINISHINGMETHODCODE", "EMBLEMTEMPLATECODE", "EMBLEMTEMPLATEDESCRIPTION", "MAXFREEOFCHARGE", "FREEOFCHARGEQTY", "MAXINVENTORY", "CIRCINVENTORY", "CHANGESPERWEEK", "DATEACTIVE", "DATEINACTIVE", "SWINGSUITSTATUS", "SYSTEMUSER_ID", "TIMESTAMP", "WEARERINVENTORY_ID", "LANGUAGECODE", "LOCKER", "BANK") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, WEARER.WEARERNUMBER, WEARER.SEARCHNAME,
 WEAREREMPLOYMENT.SEQUENCENUMBER,
 PRODUCT.CODE,
 (SELECT DESCRIPTION FROM PRODUCT_DESC A WHERE A.PRODUCT_ID = WEARERINVENTORY.PRODUCT_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
 SIZEDEFINITION.CODE SIZEDEFINITIONCODE,
 FINISHINGMETHOD.CODE FINISHINGMETHODCODE,
  EMBLEMTEMPLATE.CODE EMBLEMTEMPLATECODE, EMBLEMTEMPLATE.DESCRIPTION EMBLEMTEMPLATEDESCRIPTION,
  WEARERINVENTORY.MAXFREEOFCHARGE,WEARERINVENTORY.FREEOFCHARGEQTY, WEARERINVENTORY.MAXINVENTORY,  WEARERINVENTORY.CIRCINVENTORY,
  WEARERINVENTORY.CHANGESPERWEEK, WEARERINVENTORY.DATEACTIVE,WEARERINVENTORY.DATEINACTIVE,
  WEARERINVENTORY.SWINGSUITSTATUS,WEARERINVENTORY.SYSTEMUSER_ID,
   WEARERINVENTORY.TIMESTAMP,WEARERINVENTORY.WEARERINVENTORY_ID, LANGUAGES.CODE LANGUAGECODE
, lo.locker, lo.bank
FROM  WEARERINVENTORY
  LEFT OUTER JOIN EMBLEMTEMPLATE ON (WEARERINVENTORY.EMBLEMTEMPLATE_ID =  EMBLEMTEMPLATE.EMBLEMTEMPLATE_ID)
  LEFT OUTER JOIN QUALITYGRADE ON (WEARERINVENTORY.SPECIALGRADE_ID = QUALITYGRADE.QUALITYGRADE_ID)
  , CUSTOMER
  , WEARER, PRODUCT, SIZEDEFINITION, FINISHINGMETHOD, WEAREREMPLOYMENT
  left outer join locker lo on WEAREREMPLOYMENT.Locker_Id = lo.locker_id
  , LANGUAGES
WHERE WEARERINVENTORY.WEAREREMPLOYMENT_ID = WEAREREMPLOYMENT.WEAREREMPLOYMENT_ID
  AND WEAREREMPLOYMENT.WEARER_ID =  WEARER.WEARER_ID
  AND WEARER.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND WEARERINVENTORY.PRODUCT_ID = PRODUCT.PRODUCT_ID
  AND WEARERINVENTORY.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
  AND WEARERINVENTORY.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
/

  CREATE OR REPLACE VIEW "V_WEARERINVENTORYCOUNT" ("CUSTOMERNUMBER", "NAME", "CUSTOMER_ID", "WEARERNUMBER", "WEARERNAME", "SEARCHNAME", "SEQUENCENUMBER", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "SIZEDESCRIPTION", "FINISHINGMETHODCODE", "EMBLEMTEMPLATECODE", "EMBLEMTEMPLATEDESCRIPTION", "MAXFREEOFCHARGE", "FREEOFCHARGEQTY", "MAXINVENTORY", "CIRCINVENTORY", "CHANGESPERWEEK", "DATEACTIVE", "DATEINACTIVE", "SWINGSUITSTATUS", "SYSTEMUSER_ID", "TIMESTAMP", "WEARERINVENTORY_ID", "LANGUAGECODE", "LOCKER", "BANK", "DEFAULTBUSINESSUNIT_ID", "BUSINESSUNIT_ID", "MIN_ACTIVITY_ID") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, CUSTOMER.CUSTOMER_ID,
 WEARER.WEARERNUMBER, WEARER.FULLNAME WEARERNAME, WEARER.SEARCHNAME, WEAREREMPLOYMENT.SEQUENCENUMBER,
 PRODUCT.CODE PRODUCTCODE,
 (SELECT DESCRIPTION FROM PRODUCT_DESC A WHERE A.PRODUCT_ID = WEARERINVENTORY.PRODUCT_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
 SIZEDEFINITION.CODE SIZEDEFINITIONCODE,
 (SELECT DESCRIPTION FROM SIZEDEFINITION_DESC B WHERE B.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEDESCRIPTION,
 FINISHINGMETHOD.CODE FINISHINGMETHODCODE,
  EMBLEMTEMPLATE.CODE EMBLEMTEMPLATECODE, EMBLEMTEMPLATE.DESCRIPTION EMBLEMTEMPLATEDESCRIPTION,
  WEARERINVENTORY.MAXFREEOFCHARGE,WEARERINVENTORY.FREEOFCHARGEQTY, WEARERINVENTORY.MAXINVENTORY,  WEARERINVENTORY.CIRCINVENTORY,
  WEARERINVENTORY.CHANGESPERWEEK, WEARERINVENTORY.DATEACTIVE,WEARERINVENTORY.DATEINACTIVE,
  WEARERINVENTORY.SWINGSUITSTATUS,WEARERINVENTORY.SYSTEMUSER_ID,
   WEARERINVENTORY.TIMESTAMP,WEARERINVENTORY.WEARERINVENTORY_ID, LANGUAGES.CODE LANGUAGECODE,
lo.locker, lo.bank,
CUSTOMER.DEFAULTBUSINESSUNIT_ID, BU.BUSINESSUNIT_ID,
(select min(caa.activity_id) from customeractivities caa where caa.customer_id = CUSTOMER.customer_id and caa.processbusinessunit_id = bu.businessunit_id) min_ACTIVITY_ID
FROM  WEARERINVENTORY
  LEFT OUTER JOIN EMBLEMTEMPLATE ON (WEARERINVENTORY.EMBLEMTEMPLATE_ID =  EMBLEMTEMPLATE.EMBLEMTEMPLATE_ID)
  LEFT OUTER JOIN QUALITYGRADE ON (WEARERINVENTORY.SPECIALGRADE_ID = QUALITYGRADE.QUALITYGRADE_ID)
  , CUSTOMER, BUSINESSUNIT BU
  , WEARER, PRODUCT, SIZEDEFINITION, FINISHINGMETHOD, WEAREREMPLOYMENT
  left outer join locker lo on WEAREREMPLOYMENT.Locker_Id = lo.locker_id
  , LANGUAGES
WHERE WEARERINVENTORY.WEAREREMPLOYMENT_ID = WEAREREMPLOYMENT.WEAREREMPLOYMENT_ID
  AND WEAREREMPLOYMENT.WEARER_ID =  WEARER.WEARER_ID
  AND WEARER.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND WEARERINVENTORY.PRODUCT_ID = PRODUCT.PRODUCT_ID
  AND WEARERINVENTORY.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
  AND WEARERINVENTORY.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
/

  CREATE OR REPLACE VIEW "V_WEARERINVENTORYMODIF" ("MODIFICATIONCODE", "CUSTOMERNUMBER", "NAME", "WEARERNUMBER", "SEARCHNAME", "FULLNAME", "FIRSTNAME", "PRODUCTCODE", "SYSTEMUSER_ID", "TIMESTAMP", "LOCKER", "BANK", "PRODUCTDESCRIPTION", "MODIFICATIONDESCRIPTION", "LANGUAGECODE", "SEQUENCENUMBER") AS 
  select /*version 1.0*/
       mo.code modificationcode, cu.customernumber, cu.name,
       w.wearernumber, w.searchname, w.fullname, w.firstname,
       pr.code productcode, wim.systemuser_id, wim.timestamp, lo.locker, lo.bank,
       (select prd.description
          from product_desc prd
         where prd.product_id = wi.product_id
           and prd.language_id = lan.language_id) productdescription,
       (select mde.description
          from modification_desc mde
         where mde.modification_id = wim.modification_id
           and mde.language_id = lan.language_id) modificationdescription,
       lan.code languagecode, wim.sequencenumber
  from wearerinventorymodification wim
       join modification mo on wim.modification_id = mo.modification_id
       join wearerinventory wi
            join product pr on wi.product_id = pr.product_id
            join weareremployment we
                 left join locker lo on we.locker_id = lo.locker_id
                 join wearer w
                      join customer cu on w.customer_id = cu.customer_id
                 on we.wearer_id = w.wearer_id
            on wi.weareremployment_id = we.weareremployment_id
       on wim.wearerinventory_id = wi.wearerinventory_id
       cross join languages lan
/

  CREATE OR REPLACE VIEW "V_WEARERINVENTORYREPORT" ("CUSTOMER_ID", "SIZEDEFINITION_ID", "FINISHINGMETHOD_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMERCITY", "WEARERNUMBER", "WEARERNAME", "ADMINNUMBER", "EMPLOYMENT", "WEARERFUNCTIONCODE", "WEARERFUNCTIONDESC", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "COSTCENTERCODE", "COSTCENTERDESCRIPTION", "BANK", "LOCKER", "GARMENTDISPENSERCODE", "PRODUCTCODE", "SIZEDEFINITIONCODE", "FINISHINGMETHODCODE", "MAXINVENTORY", "CHANGESPERWEEK", "CIRCINVENTORY", "STARTDATE", "ENDDATE", "EMBLEMTEMPLATEDESC", "PRICEDECIMALS", "LANGUAGECODE", "REPORTPARAM_ID", "MAXFREEOFCHARGE", "WEARERACTIVE", "PRODUCTDESCRIPTION", "SIZEDESCRIPTION", "MODIFICATIONSQTY", "SEASONDESCRIPTION", "CUSTOMERLANGUAGECODE", "RENTPRICE", "CHANGESPERWEEKBOOL", "BILLINGMETHOD", "INVENTORYBILLINGTYPE", "DELIVERYPOINTCODE", "DELIVERYPOINTDESC", "COG_QTY") AS 
  select/*version 2.0*/
      cu.customer_id, sdf.sizedefinition_id, fm.finishingmethod_id, cu.customernumber, cu.name customername, ads.city customercity, we.wearernumber,
      we.fullname wearername, we.customeremployeenumber adminnumber, wey.sequencenumber employment, wef.code wearerfunctioncode, wef.description wearerfunctiondesc,
      dep.departmentnumber, dep.description departmentdescription, coc.code costcentercode, coc.description costcenterdescription, lk.bank, lk.locker,
      gds.code garmentdispensercode, prd.code productcode, sdf.code sizedefinitioncode, fm.code finishingmethodcode,
      wi.maxinventory, wi.changesperweek, wi.circinventory, wi.dateactive startdate, wi.dateinactive enddate,
      emb.description emblemtemplatedesc, cur.decimals pricedecimals, lan.code languagecode, rp.reportparam_id, wi.maxfreeofcharge,
      getdatediff(trunc(sysdate), we.dateactive)*getdatediff(we.dateinactive, trunc(sysdate)) weareractive,
      (select pds.description
         from product_desc pds
        where lan.language_id = pds.language_id
          and pds.product_id = prd.product_id) productdescription,
      (select sdd.description
         from sizedefinition_desc sdd
        where sdd.language_id = lan.language_id
          and sdd.sizedefinition_id = sdf.sizedefinition_id) sizedescription,
      (select count(wm.modification_id)
         from wearerinventorymodification wm
        where wm.wearerinventory_id = wi.wearerinventory_id) modificationsqty,
      (select std.description
         from seasontype_desc std, season sea
        where wi.season_id = sea.season_id
          and sea.seasontype_id = std.seasontype_id
          and std.language_id = lan.language_id) seasondescription,
      (select l.code
         from languages l
        where l.language_id = cu.language_id) customerlanguagecode,
      case when rp.string_value = 'true'
           then pack_price.rent_price(cu.customer_id, prd.product_id, sdf.sizedefinition_id, fm.finishingmethod_id, trunc(sysdate),
                                      case when (select plp.changesperweek
                                                   from productlistpercustomer plp
                                                  where plp.customer_id = cu.customer_id
                                                    and plp.product_id = prd.product_id
                                                    and plp.sizedefinition_id = sdf.sizedefinition_id
                                                    and plp.dateinactive>trunc(sysdate)
                                                    and plp.finishingmethod_id = fm.finishingmethod_id ) = 'Y'
                                           then wi.changesperweek
                                           else 0
                                      end)
           else -1
      end rentprice,
      (select plp.changesperweek
         from productlistpercustomer plp
        where plp.customer_id = cu.customer_id
          and plp.product_id = prd.product_id
          and plp.sizedefinition_id = nvl(sdf.sizedefinition_id, (select s.sizedefinition_id from sizedefinition s where s.code='*'))
          and plp.finishingmethod_id = fm.finishingmethod_id
          and plp.dateinactive>trunc(sysdate)) changesperweekbool,
      (select plp.billingmethod
         from productlistpercustomer plp
        where plp.customer_id = cu.customer_id
          and plp.product_id = prd.product_id
          and plp.sizedefinition_id = nvl(sdf.sizedefinition_id, (select s.sizedefinition_id from sizedefinition s where s.code='*'))
          and plp.finishingmethod_id = fm.finishingmethod_id
          and plp.dateinactive>trunc(sysdate)) billingmethod,
      (select plp.inventorybillingtype
         from productlistpercustomer plp
        where plp.customer_id = cu.customer_id
          and plp.product_id = prd.product_id
          and plp.sizedefinition_id = nvl(sdf.sizedefinition_id, (select s.sizedefinition_id from sizedefinition s where s.code='*'))
          and plp.dateinactive>trunc(sysdate)
          and plp.finishingmethod_id = fm.finishingmethod_id ) inventorybillingtype,
      coalesce(d1.code, d2.code, d3.code) deliverypointcode, coalesce(d1.description, d2.description, d3.description) deliverypointdesc,
      ((select count(uq.uniqueitem_id)
          from uniqueitem uq, issuehistory ih
         where uq.uniqueitem_id = ih.uniqueitem_link_id
           and ih.weareremployment_link_id = wey.weareremployment_id
           and uq.customerowned = 'Y'
           and uq.poolitem = 1 -- pool
           and uq.status_id in ( select status.status_id from status where status.statustype='UI' and status.code in ('20','30') )
           and coalesce(uq.distributionpoint_id, uq.lastdistributionpoint_link_id) = distr.distributionpoint_id )+
       (select count(uq.uniqueitem_id) from uniqueitem uq, uniqueitemnonpool uqnp
         where uq.customerowned = 'Y'
           and uq.poolitem = 2 -- nonpool
           and uq.status_id in ( select status.status_id from status where status.statustype='UI' and status.code in ('20','30') )   -- in circulation, assigned
           and uq.uniqueitem_id = uqnp.uniqueitem_id
           and uqnp.weareremployment_id = wey.weareremployment_id
           and uqnp.wearerinventory_id = wi.wearerinventory_id ))cog_qty
from wearerinventory wi
     left join emblemtemplate emb on wi.emblemtemplate_id = emb.emblemtemplate_id
     join weareremployment wey on wi.weareremployment_id = wey.weareremployment_id
              left join deliverypoint d1 on wey.deliverypoint_id = d1.deliverypoint_id
              left join wearerfunction wef on wey.wearerfunction_id = wef.wearerfunction_id
              left join locker lk
                   join deliverypoint d2 on lk.deliverypoint_id = d2.deliverypoint_id
              on wey.locker_id = lk.locker_id
              left join garmentdispenser gds
                   join deliverypoint d3  on gds.deliverypoint_id = d3.deliverypoint_id
              on wey.garmentdispenser_id = gds.garmentdispenser_id
     join wearer we on wey.wearer_id = we.wearer_id
     join customer cu on we.customer_id = cu.customer_id
     join distributionpoint distr on wey.distributionpoint_id = distr.distributionpoint_id
     join department dep on distr.department_id = dep.department_id and dep.customer_id = cu.customer_id
     join costcenter coc on distr.costcenter_id = coc.costcenter_id and coc.customer_id = cu.customer_id
     join address ads on cu.visitaddress_id = ads.address_id
     join currency cur on cu.currency_id = cur.currency_id
     join product prd on wi.product_id = prd.product_id
     join sizedefinition sdf on wi.sizedefinition_id = sdf.sizedefinition_id
     join finishingmethod fm on wi.finishingmethod_id = fm.finishingmethod_id
     , languages lan, reportparam rp
where (wi.dateinactive > trunc(sysdate) or wi.circinventory <> 0 or wi.freeofchargeqty <> 0) --order 501566
  and ((rp.number_value = 0 and rp.string_value1 = ' ' and rp.string_value2 = 'ZZZZZZ')
       or
      (rp.number_value = 1 and exists (select cpc.customerspercluster_id --customer filter on Cluster
                                         from customerspercluster cpc, customercluster cc
                                        where cpc.cluster_id = cc.cluster_id
                                          and cpc.customer_id = cu.customer_id
                                          and cc.code between rp.string_value1 and rp.string_value2)))
/

  CREATE OR REPLACE VIEW "V_WEARERINVENTORY_AUX" ("CUSTOMERNUMBER", "WEARERNUMBER", "EMPLOYMENT", "WEARERFUNCTIONCODE", "DEPARTMENTNUMBER", "GARMENTDISPENSERCODE", "PRODUCTCODE", "FINISHINGMETHODCODE", "PRODUCTDESCRIPTION", "MAXINVENTORY", "CIRCINVENTORY", "CUSTOMERLANGUAGECODE", "WEARERACTIVE", "LANGUAGECODE", "DEPARTMENTDESCRIPTION") AS 
  select
  cu.customernumber, we.wearernumber, wey.sequencenumber Employment
, wearerfunction.code wearerfunctionCode, department.departmentnumber
, garmentdispenser.code garmentdispenserCode
, prd.code ProductCode, finishingmethod.code finishingmethodCode
, (select description from product_desc where languages.language_id = product_desc.language_id
and product_desc.product_id = prd.product_id) ProductDescription
, wearerinventory.maxinventory, wearerinventory.circinventory
, (select code from languages where languages.language_id = cu.language_id) CustomerLanguageCode
, GETDATEDIFF(trunc(sysdate), we.dateactive)*GETDATEDIFF(we.dateinactive, trunc(sysdate)) wearerActive
, languages.code languageCode,
department.description departmentDescription
from
  customer cu, wearer we
, weareremployment wey
    left outer join wearerfunction on (wey.wearerfunction_id = wearerfunction.wearerfunction_id)
    left outer join garmentdispenser on wey.garmentdispenser_id = garmentdispenser.garmentdispenser_id
, distributionpoint, department
, wearerinventory
  left outer join emblemtemplate on wearerinventory.emblemtemplate_id = emblemtemplate.emblemtemplate_id
, product prd, sizedefinition, finishingmethod
, languages
where
    cu.customer_id = we.customer_id
and we.wearer_id = wey.wearer_id
and wey.distributionpoint_id = distributionpoint.distributionpoint_id
    and distributionpoint.department_id = department.department_id
        and department.customer_id = cu.customer_id
and wey.weareremployment_id = wearerinventory.weareremployment_id
and wearerinventory.product_id = prd.product_id
and wearerinventory.sizedefinition_id = sizedefinition.sizedefinition_id
and wearerinventory.finishingmethod_id = finishingmethod.finishingmethod_id
/

  CREATE OR REPLACE VIEW "V_WEARERINVENTORY_WITHMODIF" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMERCITY", "WEARERNUMBER", "WEARERNAME", "ADMINNUMBER", "EMPLOYMENT", "WEARERFUNCTIONCODE", "WEARERFUNCTIONDESC", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "COSTCENTERCODE", "COSTCENTERDESCRIPTION", "BANK", "LOCKER", "GARMENTDISPENSERCODE", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "FINISHINGMETHODCODE", "MAXINVENTORY", "CHANGESPERWEEK", "CIRCINVENTORY", "STARTDATE", "ENDDATE", "SEASONDESCRIPTION", "CUSTOMERLANGUAGECODE", "WEARERACTIVE", "MODIFICATIONS", "LANGUAGECODE", "REPORTPARAM_ID") AS 
  select
  cu.customernumber, cu.name CustomerName, address.city CustomerCity, we.wearernumber
, we.fullname WearerName, we.customeremployeenumber AdminNumber, wey.sequencenumber Employment
, wearerfunction.code wearerfunctionCode, wearerfunction.description wearerfunctionDesc
, department.departmentnumber, department.description departmentDescription, costcenter.code costcenterCode
, costcenter.description costcenterDescription, locker.bank, locker.locker
, garmentdispenser.code garmentdispenserCode
, prd.code ProductCode
, (select description from product_desc where languages.language_id = product_desc.language_id
and product_desc.product_id = prd.product_id) ProductDescription
, sizedefinition.code sizedefinitionCode, finishingmethod.code finishingmethodCode
, wearerinventory.maxinventory, wearerinventory.changesperweek, wearerinventory.circinventory
, wearerinventory.dateactive StartDate, wearerinventory.dateinactive EndDate
, (select seasontype_desc.description from seasontype_desc,season where wearerinventory.season_id = season.season_id
and season.seasontype_id = seasontype_desc.seasontype_id and seasontype_desc.language_id = languages.language_id) SeasonDescription
, (select code from languages where languages.language_id = cu.language_id) CustomerLanguageCode
, GETDATEDIFF(trunc(sysdate), we.dateactive)*GETDATEDIFF(we.dateinactive, trunc(sysdate)) wearerActive --, customercluster.code clusterCode
, cast(F_MODIFICATIONS(wearerinventory.wearerinventory_id, 'W') as varchar2(40)) MODIFICATIONS
, languages.code languageCode
, rp.reportparam_id
from
  customer cu     --left outer join customercluster on cu.cluster_id = customercluster.cluster_id
, weareremployment wey
    left outer join wearerfunction on (wey.wearerfunction_id = wearerfunction.wearerfunction_id)
    left outer join locker on wey.locker_id = locker.locker_id
    left outer join garmentdispenser on wey.garmentdispenser_id = garmentdispenser.garmentdispenser_id
, wearer we, address, distributionpoint, department, costcenter
, wearerinventory
  left outer join emblemtemplate on wearerinventory.emblemtemplate_id = emblemtemplate.emblemtemplate_id
, product prd, sizedefinition, finishingmethod, languages
, reportparam rp
where
    we.customer_id = cu.customer_id
    and cu.visitaddress_id = address.address_id
and we.wearer_id = wey.wearer_id
and wey.distributionpoint_id = distributionpoint.distributionpoint_id
    and distributionpoint.department_id = department.department_id
        and department.customer_id = cu.customer_id
    and distributionpoint.costcenter_id = costcenter.costcenter_id
        and costcenter.customer_id = cu.customer_id
and wey.weareremployment_id = wearerinventory.weareremployment_id
and wearerinventory.product_id = prd.product_id
and wearerinventory.sizedefinition_id = sizedefinition.sizedefinition_id
and wearerinventory.finishingmethod_id = finishingmethod.finishingmethod_id
and wearerinventory.dateinactive > trunc(sysdate) --order 501566
and wearerinventory.circinventory <> 0 --order 501566
--and wearerinventory.freeofchargeqty <> 0 --order 501566
and ((rp.number_value = 0 and rp.string_value1 = ' ' and rp.string_value2 = 'ZZZZZZ')
    or
    (rp.number_value = 1 and exists (select cpc.customerspercluster_id --customer filter on Cluster
     from customerspercluster cpc, customercluster cc
     where cpc.cluster_id = cc.cluster_id
       and cpc.customer_id = cu.customer_id
       and cc.code between rp.string_value1 and rp.string_value2)))
/

  CREATE OR REPLACE VIEW "V_WEARERINVOICE" ("INVOICEHEADER_ID", "INVOICENUMBER", "INVOICEDATE", "INVOICECOMMENTS", "RENTSTARTDATE", "RENTENDDATE", "RENTSTARTYEARWEEKSNR", "RENTSTARTYEAR", "RENTSTARTWEEK", "RENTENDYEAR", "RENTENDWEEK", "DELTOCUSTOMER_LINK_ID", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITION_LINK_ID", "SIZECODE", "SIZEDESCRIPTION", "INVOICELINETYPE", "INVOICELINETYPEDESCRIPTION", "PRICE", "DISCOUNTPERCENTAGE", "CURRENCY_ID", "INVOICEBUSINESSUNIT_ID", "CURRENCY_CODE", "CURRENCY_DESC", "INVOICEAMOUNTDECIMALS", "DECIMALS", "PLANTCODE", "PLANTNAME", "PLANTSTREET", "PLANTSTREET2", "PLANTZIPCODE", "PLANTCITY", "PLANTSTATE", "PLANTCOUNTY", "PLANTPHONE", "PLANTFAX", "PLANTWEBSITE", "PLANTEMAIL", "FINISHINGMETHOD_ID", "BILLTOCUSTOMERNUMBER") AS 
  select IH.InvoiceHeader_ID, IH.InvoiceNumber, IH.InvoiceDate, IH.InvoiceComments, IH.StartDate RentStartDate, IH.EndDate RentEndDate
, getweeksinyear(GETYEAROFWEEK(IH.StartDate)) RentStartYearWeeksNr, GETYEAROFWEEK(IH.StartDate) RentStartYear, GETISOWEEK(IH.StartDate) RentStartWeek
, GETYEAROFWEEK(IH.EndDate) RentEndYear, GETISOWEEK(IH.EndDate) RentEndWeek
, IH.DelToCustomer_Link_ID, IH.DelToCustomerNumber, IH.DelToCustomerName
, ILP.Product_Link_Id Product_ID, IL.Code ProductCode, IL.Description ProductDescription, ilp.sizedefinition_link_id
, ilp.sizecode, ilp.sizedescription
, (select ilt.Type from InvoiceLineType ilt where ilt.invoicelinetype_id = il.invoicelinetype_id) InvoiceLineType
, (select iltd.description from InvoiceLineType_desc iltd, customer del where iltd.invoicelinetype_id = il.invoicelinetype_id
          and del.customer_id = ih.deltocustomer_link_id and iltd.language_id = del.language_id) InvoiceLineTypeDescription
, IL.Price, IL.DiscountPercentage, IH.Currency_ID, IH.InvoiceBusinessUnit_ID
, curr.code currency_code, curr.description currency_desc, curr.invoiceamountdecimals, curr.decimals
, p.code plantcode, p.name plantname, x.street plantstreet, x.street2 plantstreet2, x.zipcode plantzipcode
, x.city plantcity, x.state plantstate, x.county plantcounty, p.phoneno plantphone
, p.faxno plantfax, p.website plantwebsite, p.email plantemail, ilp.finishingmethod_id
, ih.billtocustomernumber billtocustomernumber
From InvoiceHeader IH, InvoiceLine IL, InvoiceLineProduct ILP,
     currency curr, businessunit e, plant p, address x
Where IH.InvoiceHeader_ID = IL.InvoiceHeader_ID
And IL.InvoiceLineType_ID in (1, 2)
And ILP.InvoiceLine_ID = IL.InvoiceLine_ID
and curr.currency_id = ih.currency_id
and ih.invoicebusinessunit_id = e.businessunit_id
and e.plant_id = p.plant_id
and p.address_id = x.address_id
/

  CREATE OR REPLACE VIEW "V_WEARERINVOICERPT" ("YEAR", "WEEK", "QTY", "INVOICEHEADER_ID", "STATUSQUODATE", "EMPLOYERPERCENTAGE", "MAXEMPLOYERAMOUNT", "INVOICECATEGORYCODE", "WEARERNUMBER", "WEARERNAME", "DATEACTIVE", "WEAREREMPLOYMENT_ID", "WEARER_ID", "INVOICENUMBER", "INVOICEDATE", "INVOICECOMMENTS", "RENTSTARTDATE", "RENTENDDATE", "RENTSTARTYEARWEEKSNR", "RENTSTARTWEEK", "RENTENDWEEK", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "PRODUCTCODE", "PRODUCTDESCRIPTION", "INVOICELINETYPE", "INVOICELINETYPEDESCRIPTION", "PRICE", "DISCOUNTPERCENTAGE", "CURRENCY_CODE", "INVOICEAMOUNTDECIMALS", "DECIMALS", "PLANTNAME", "PLANTSTREET", "PLANTZIPCODE", "PLANTCITY") AS 
  Select PN.Year, PN.Week, 1 qty
, PNL.InvoiceHeader_ID
, sysdate StatusQuoDate
, WIC.EmployerPercentage, wic.maxemployeramount
, WIC.Code InvoiceCategoryCode
, coalesce(WR.customeremployeenumber, cast(WR.Wearernumber as varchar2(10))) wearernumber, wr.fullname WearerName, wr.dateactive,
we.weareremployment_id, we.wearer_id
, IH.InvoiceNumber, IH.InvoiceDate, IH.InvoiceComments, IH.StartDate RentStartDate, IH.EndDate RentEndDate
, getweeksinyear(GETYEAROFWEEK(IH.StartDate)) RentStartYearWeeksNr, GETISOWEEK(IH.StartDate) RentStartWeek
, GETISOWEEK(IH.EndDate) RentEndWeek
, IH.DelToCustomerNumber, IH.DelToCustomerName
, IL.Code ProductCode, IL.Description ProductDescription
, (select ilt.Type from InvoiceLineType ilt where ilt.invoicelinetype_id = il.invoicelinetype_id) InvoiceLineType
, (select iltd.description from InvoiceLineType_desc iltd, customer del where iltd.invoicelinetype_id = il.invoicelinetype_id
          and del.customer_id = ih.deltocustomer_link_id and iltd.language_id = del.language_id) InvoiceLineTypeDescription
, IL.Price, IL.DiscountPercentage
, curr.code currency_code, curr.invoiceamountdecimals, curr.decimals
, p.name plantname, x.street plantstreet, x.zipcode plantzipcode
, x.city plantcity
From PackingNote PN, PackingNoteLine PNL, DeliveryScan DS, WearerInvoiceCategory WIC, weareremployment we, wearer wr--, finishingmethod fm
,InvoiceHeader IH, InvoiceLine IL, InvoiceLineProduct ILP,
     currency curr, businessunit e, plant p, address x
Where PNL.PackingNote_ID = PN.PackingNote_ID
And DS.PackingNote_ID = PN.PackingNote_ID
And DS.Product_Link_ID = PNL.Product_ID
and ds.sizedefinition_link_id = pnl.sizedefinition_id
and ds.finishingmethod_id = pnl.finishingmethod_id
and ds.chargewashing = 'Y'
and wic.wearerinvoicecategory_id = ds.WearerInvoiceCategory_ID
and ds.weareremployment_link_id = we.weareremployment_id
and we.wearer_id = wr.wearer_id
and pnl.invoiceheader_id = ih.invoiceheader_id
and IH.InvoiceHeader_ID = IL.InvoiceHeader_ID
And IL.InvoiceLineType_ID = 2
And ILP.InvoiceLine_ID = IL.InvoiceLine_ID
and curr.currency_id = ih.currency_id
and ih.invoicebusinessunit_id = e.businessunit_id
and e.plant_id = p.plant_id
and p.address_id = x.address_id
and pnl.product_id = ilp.product_link_id
and (pnl.sizedefinition_id = ilp.sizedefinition_link_id
or ilp.sizedefinition_link_id = (select sd.sizedefinition_id from sizedefinition sd where sd.code = '*'))
and pnl.finishingmethod_id = ilp.finishingmethod_id
and ih.deltocustomer_link_id = ds.customer_link_id
and ih.invoicebusinessunit_id = pn.invoicebusinessunit_id
union all
Select SQH.Year, SQH.Week,
(SQIC.QtyRentedPerPiece + sqic.beyondlifetimecirc) qty
, ih.invoiceheader_id InvoiceHeader_ID
, SQH.StatusQuoDate
, WIC.EmployerPercentage, wic.maxemployeramount
, WIC.Code InvoiceCategoryCode
, coalesce(WR.customeremployeenumber, cast(WR.Wearernumber as varchar2(10))) wearernumber, wr.fullname WearerName, wr.dateactive,
  we.weareremployment_id, we.wearer_id
, IH.InvoiceNumber, IH.InvoiceDate, IH.InvoiceComments, IH.StartDate RentStartDate, IH.EndDate RentEndDate
, getweeksinyear(GETYEAROFWEEK(IH.StartDate)) RentStartYearWeeksNr, GETISOWEEK(IH.StartDate) RentStartWeek
, GETISOWEEK(IH.EndDate) RentEndWeek
, IH.DelToCustomerNumber, IH.DelToCustomerName
, IL.Code ProductCode, IL.Description ProductDescription
, (select ilt.Type from InvoiceLineType ilt where ilt.invoicelinetype_id = il.invoicelinetype_id) InvoiceLineType
, (select iltd.description from InvoiceLineType_desc iltd, customer del where iltd.invoicelinetype_id = il.invoicelinetype_id
          and del.customer_id = ih.deltocustomer_link_id and iltd.language_id = del.language_id) InvoiceLineTypeDescription
, IL.Price, IL.DiscountPercentage
, curr.code currency_code, curr.invoiceamountdecimals, curr.decimals
, p.name plantname, x.street plantstreet, x.zipcode plantzipcode
, x.city plantcity
From StatusQuoHeader SQH, sqitemincirculation SQIC, WearerInvoiceCategory WIC, weareremployment we, wearer wr,
wearerinventory wi,InvoiceHeader IH, InvoiceLine IL, InvoiceLineProduct ILP,
     currency curr, businessunit e, plant p, address x
Where SQIC.StatusQuoHeader_ID = SQH.StatusQuoHeader_ID
And SQH.StatusQuoType = 1 --Items in circulation
And SQH.SubType = 0 --regular
and SQIC.QtyRentedPerPiece + sqic.beyondlifetimecirc <> 0
and sqic.weareremployment_link_id = we.weareremployment_id
and we.wearer_id = wr.wearer_id
and wi.product_id = sqic.product_link_id
and wi.sizedefinition_id = sqic.sizedefinition_link_id
and wi.finishingmethod_id = sqic.finishingmethod_id
and sqic.distributionpoint_link_id = we.distributionpoint_id
and wi.weareremployment_id = we.weareremployment_id
and wi.wearerinvoicecategory_id = wic.wearerinvoicecategory_id
and IH.InvoiceHeader_ID = IL.InvoiceHeader_ID
And IL.InvoiceLineType_ID = 1
And ILP.InvoiceLine_ID = IL.InvoiceLine_ID
and curr.currency_id = ih.currency_id
and ih.invoicebusinessunit_id = e.businessunit_id
and e.plant_id = p.plant_id
and p.address_id = x.address_id
and sqh.statusquodate >= ih.startdate and sqh.statusquodate <= ih.enddate
and sqic.product_link_id = ilp.product_link_id
and (sqic.sizedefinition_link_id = ilp.sizedefinition_link_id
or ilp.sizedefinition_link_id = (select sd.sizedefinition_id from sizedefinition sd where sd.code = '*'))
and sqic.finishingmethod_id = ilp.finishingmethod_id
and ih.deltocustomer_link_id = sqic.customer_link_id
and ih.invoicebusinessunit_id = SQH.InvoiceBusinessUnit_ID
/

  CREATE OR REPLACE VIEW "V_WEARERINVOICE_AUX" ("INVOICELINETYPE", "YEAR", "WEEK", "QTY", "INVOICEHEADER_ID", "PRODUCT_ID", "STATUSQUODATE", "INVOICEBUSINESSUNIT_ID", "SIZEDEFINITION_ID", "EMPLOYERPERCENTAGE", "MAXEMPLOYERAMOUNT", "CUSTOMER_LINK_ID", "INVOICECATEGORYCODE", "INVOICECATEGORYDESCRIPTION", "WEARERNUMBER", "WEARERNAME", "DATEACTIVE", "WEAREREMPLOYMENT_ID", "WEARER_ID", "FINISHINGMETHOD_ID") AS 
  Select 2 InvoiceLineType, PN.Year, PN.Week, Count (DS.UNIQUEITEM_LINK_ID) qty
, PNL.InvoiceHeader_ID, DS.Product_Link_ID Product_ID
, sysdate StatusQuoDate, pn.invoicebusinessunit_id, pnl.sizedefinition_id
, WIC.EmployerPercentage, wic.maxemployeramount, ds.customer_link_id
, WIC.Code InvoiceCategoryCode, WIC.Description InvoiceCategoryDescription
, coalesce(WR.customeremployeenumber, cast(WR.Wearernumber as varchar2(10))) wearernumber, wr.fullname WearerName, wr.dateactive,
we.weareremployment_id, we.wearer_id, ds.finishingmethod_id
From PackingNote PN, PackingNoteLine PNL, DeliveryScan DS, WearerInvoiceCategory WIC, weareremployment we, wearer wr--, finishingmethod fm
Where PNL.PackingNote_ID = PN.PackingNote_ID
And DS.PackingNote_ID = PN.PackingNote_ID
And DS.Product_Link_ID = PNL.Product_ID
and ds.sizedefinition_link_id = pnl.sizedefinition_id
and ds.finishingmethod_id = pnl.finishingmethod_id
and ds.chargewashing = 'Y'
and wic.wearerinvoicecategory_id = ds.WearerInvoiceCategory_ID
and ds.weareremployment_link_id = we.weareremployment_id
and we.wearer_id = wr.wearer_id
--and wr.customer_id = ds.customer_link_id
Group By PN.Year, PN.Week, --DS.Weareremployment_Link_Id,
pnl.sizedefinition_id,
ds.customer_link_id, PNL.InvoiceHeader_ID, DS.Product_Link_ID,
pn.invoicebusinessunit_id, WIC.EmployerPercentage, wic.maxemployeramount
, WIC.Code, WIC.Description, coalesce(WR.customeremployeenumber, cast(WR.Wearernumber as varchar2(10))), wr.fullname, wr.dateactive
, we.weareremployment_id, we.wearer_id, ds.finishingmethod_id
union all
Select 1 InvoiceLineType, SQH.Year, SQH.Week, --case when sqic.chargeafterdepreciation = 'N' then
sum(SQIC.QtyRentedPerPiece + sqic.beyondlifetimecirc) --else sum(SQIC.QtyRentedPerPiece) end
qty
, 0 InvoiceHeader_ID, SQIC.Product_Link_Id Product_ID
, SQH.StatusQuoDate, SQH.InvoiceBusinessUnit_ID, sqic.sizedefinition_link_id sizedefinition_id
, WIC.EmployerPercentage, wic.maxemployeramount, sqic.customer_link_id
, WIC.Code InvoiceCategoryCode, WIC.Description InvoiceCategoryDescription
, coalesce(WR.customeremployeenumber, cast(WR.Wearernumber as varchar2(10))) wearernumber, wr.fullname WearerName, wr.dateactive,
  we.weareremployment_id, we.wearer_id, sqic.finishingmethod_id
From StatusQuoHeader SQH, sqitemincirculation SQIC, WearerInvoiceCategory WIC, weareremployment we, wearer wr,
wearerinventory wi
Where SQIC.StatusQuoHeader_ID = SQH.StatusQuoHeader_ID
And SQH.StatusQuoType = 1 --Items in circulation
And SQH.SubType = 0 --regular
and SQIC.QtyRentedPerPiece + sqic.beyondlifetimecirc <> 0
--and wic.wearerinvoicecategory_id = SQIC.WearerInvoiceCategory_ID
and sqic.weareremployment_link_id = we.weareremployment_id
and we.wearer_id = wr.wearer_id
and wi.product_id = sqic.product_link_id
and wi.sizedefinition_id = sqic.sizedefinition_link_id
and wi.finishingmethod_id = sqic.finishingmethod_id
and wi.weareremployment_id = we.weareremployment_id
and wi.wearerinvoicecategory_id = wic.wearerinvoicecategory_id
--and wr.customer_id = sqic.customer_link_id
Group By SQH.Year, SQH.Week, --SQIC.Weareremployment_Link_Id,
sqic.sizedefinition_link_id, --sqic.chargeafterdepreciation,
sqic.customer_link_id, SQIC.Product_Link_Id, SQH.StatusQuoDate, SQH.InvoiceBusinessUnit_ID
, WIC.EmployerPercentage, wic.maxemployeramount
, WIC.Code, WIC.Description, coalesce(WR.customeremployeenumber, cast(WR.Wearernumber as varchar2(10))), wr.fullname, wr.dateactive
, we.weareremployment_id, we.wearer_id, sqic.finishingmethod_id
/

  CREATE OR REPLACE VIEW "V_WEARERPRODUCTPRESENTATION" ("CUSTOMERID", "WEARERNUMBER", "WEARERFULLNAME", "PRODUCTSHORTDESCRIPTION", "PRODUCTCODE", "SIZEDEFINITIONCODE", "FINISHINGMETHODCODE", "CIRCINVENTORY", "DATEACTIVE", "DATEINACTIVE", "LANGUAGE_CODE", "CHANGEPERWEEK", "BANK", "LOCKER", "WASHPRICE", "RENTALPRICE", "DATELASTINCREASE", "SIZE_DESC", "CURRENCYDECIMALS") AS 
  select /*version 2.2*/
       prdlcu.customer_id customerid, we.wearernumber, we.fullname wearerfullname, prd.shortdescription productshortdescription,
       prd.code  productcode, sz.code sizedefinitioncode, fm.code finishingmethodcode, wei.circinventory,
       wei.dateactive, wei.dateinactive, l.code language_code, wei.changesperweek changeperweek, lo.bank, lo.locker,
       pack_price.wash_price(prdlcu.customer_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, null, 1) washprice,
       (select wer.price
          from wearerinvprice wer
         where wer.wearerinventory_id = wei.wearerinventory_id
           and wer.startdate = (select max(weri.startdate)
                                  from wearerinvprice weri
                                 where weri.wearerinventory_id = wei.wearerinventory_id
                                   and weri.startdate < sysdate)) rentalprice,
       (select max(wap.startdate)
          from wearerinvprice wap
         where wap.wearerinventory_id = wei.wearerinventory_id
           and wap.startdate < sysdate)datelastincrease,
       (select sd.description
          from sizedefinition_desc sd
         where sz.sizedefinition_id = sd.sizedefinition_id
           and l.language_id=sd.language_id) size_desc,
       (select cur.decimals
          from currency cur
               join customer cu on cur.currency_id = cu.currency_id
         where cu.customer_id = we.customer_id) currencydecimals
  from wearer we
       join weareremployment wel
            left join  locker lo on wel.locker_id = lo.locker_id
            join wearerinventory wei on wel.weareremployment_id = wei.weareremployment_id
                 join product prd
                      join productlistpercustomer prdlcu on prdlcu.product_id = prd.product_id
                 on wei.product_id = prd.product_id
                 join sizedefinition sz on wei.sizedefinition_id = sz.sizedefinition_id
                 join finishingmethod fm on wei.finishingmethod_id = fm.finishingmethod_id
       on we.wearer_id = wel.wearer_id
       cross join languages l
 where we.customer_id = prdlcu.customer_id
/

  CREATE OR REPLACE VIEW "V_WEARERS" ("WEBSESSION_ID", "WEBUSER_ID", "DEPARTMENT_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "WEARERNAME", "WEARER_ID", "WEARERSEARCHNAME", "EMBLEMNAME", "ADMINNUMBER", "SEX", "DUMMYFORPOOL", "DATEACTIVE", "DATEINACTIVE", "REMARK", "FIRSTNAME", "EMPLOYEMENT", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "WEARERFUNCTIONCODE", "WEARERFUNCTIONDESCRIPTION", "WEARERFUNCTION_ID", "DELIVERYPOINTCODE", "DELIVERYPOINTDESCRIPTION", "DELIVERYPOINTCODEL", "DELIVERYPOINTDESCRIPTIONL", "DELIVERYPOINTCODEG", "DELIVERYPOINTDESCRIPTIONG", "BANK", "LOCKER", "KEYCOMBINATION", "LOCKERMANAGEMENT", "BANKLOCKER", "GARMENTDISPENSERCODE", "GARMENTDISPENSERDESCRIPTION", "DISPENSECREDIT", "SYSTEMUSER_ID", "TIMESTAMP", "WEARERACTIVE", "DELIVERYPOINT_ID", "LOCKER_ID", "GARMENTDISPENSER_ID", "COSTCENTERCODE", "COSTCENTERDESCRIPTION", "COSTCENTER_ID") AS 
  SELECT wus.websession_id, wc.webuser_id,DEPARTMENT.DEPARTMENT_ID, CUSTOMER.CUSTOMER_ID,--WD.DEPARTMENT_ID WEBUSERDEPARTMENT_ID,
  CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME customername, WEARER.WEARERNUMBER, WEARER.FULLNAME WEARERNAME, WEARER.WEARER_ID,
  WEARER.SEARCHNAME WEARERSEARCHNAME, WEARER.EMBLEMNAME, WEARER.CUSTOMEREMPLOYEENUMBER ADMINNUMBER,
  WEARER.SEX, WEARER.DUMMYFORPOOL,  WEARER.DATEACTIVE, WEARER.DATEINACTIVE, WEARER.REMARK, WEARER.FIRSTNAME ,
  WEAREREMPLOYMENT.SEQUENCENUMBER EMPLOYEMENT, DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER,
  DISTRIBUTIONPOINT.DESCRIPTION distributionpointdescription,
  DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION departmentdescription,
  WEARERFUNCTION.CODE wearerfunctioncode, WEARERFUNCTION.DESCRIPTION wearerfunctiondescription, WEARERFUNCTION.WEARERFUNCTION_ID,
  DELIVERYPOINT.CODE deliverypointcode, DELIVERYPOINT.DESCRIPTION deliverypointdescription,
  DPL.CODE deliverypointcodel, DPL.DESCRIPTION deliverypointdescriptionl,
  DPG.CODE deliverypointcodeg, DPG.DESCRIPTION deliverypointdescriptiong,
  LOCKER.BANK bank, LOCKER.LOCKER locker, LOCKER.keycombination, customer.lockermanagement
, cast(CONCATENATE(LEFTPAD(LOCKER.BANK, 6, '0'), LEFTPAD(LOCKER.LOCKER, 6, '0'))as varchar2(255)) banklocker,
  GARMENTDISPENSER.CODE garmentdispensercode,
  GARMENTDISPENSER.DESCRIPTION garmentdispenserdescription, WEAREREMPLOYMENT.DISPENSECREDIT,
  WEARER.SYSTEMUSER_ID, WEARER.TIMESTAMP,
  GETDATEDIFF(trunc(sysdate), WEARER.dateactive)*GETDATEDIFF(WEARER.dateinactive, trunc(sysdate)) wearerActive,
  WEAREREMPLOYMENT.DELIVERYPOINT_ID, WEAREREMPLOYMENT.LOCKER_ID, WEAREREMPLOYMENT.GARMENTDISPENSER_ID,
  COSTCENTER.CODE COSTCENTERCODE, COSTCENTER.DESCRIPTION COSTCENTERDESCRIPTION, COSTCENTER.COSTCENTER_ID
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT, COSTCENTER, WEARER,
  WEAREREMPLOYMENT
    LEFT OUTER JOIN (LOCKER LEFT JOIN DELIVERYPOINT DPL ON LOCKER.DELIVERYPOINT_ID = DPL.DELIVERYPOINT_ID)
      ON (WEAREREMPLOYMENT.LOCKER_ID = LOCKER.LOCKER_ID)
    LEFT OUTER JOIN (GARMENTDISPENSER LEFT JOIN DELIVERYPOINT DPG ON GARMENTDISPENSER.DELIVERYPOINT_ID = DPG.DELIVERYPOINT_ID)
      ON (WEAREREMPLOYMENT.GARMENTDISPENSER_ID = GARMENTDISPENSER.GARMENTDISPENSER_ID)
    LEFT OUTER JOIN DELIVERYPOINT  ON (WEAREREMPLOYMENT.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID)
    LEFT OUTER JOIN WEARERFUNCTION  ON (WEAREREMPLOYMENT.WEARERFUNCTION_ID = WEARERFUNCTION.WEARERFUNCTION_ID),
  webusercustomer wc,
    --left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  webusersession wus,webuser wu
WHERE WEARER.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
    AND WEARER.WEARER_ID = WEAREREMPLOYMENT.WEARER_ID
    AND WEAREREMPLOYMENT.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
    AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
    AND DISTRIBUTIONPOINT.COSTCENTER_ID = COSTCENTER.COSTCENTER_ID
    and wc.customer_id = customer.customer_id
    and wu.webuser_id = wus.webuser_id
    and wc.webuser_id = wu.webuser_id
    and ( NOT EXISTS (SELECT 1 FROM WEBUSERDEPARTMENT WDEP, WEBUSERCUSTOMER WCUST
                             WHERE WCUST.WEBUSER_ID = WU.WEBUSER_ID
                                   AND WDEP.WEBUSERCUSTOMER_ID = WCUST.WEBUSERCUSTOMER_ID
                                   AND WCUST.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID)
          OR
          EXISTS (SELECT 1 FROM WEBUSERDEPARTMENT WDEP, WEBUSERCUSTOMER WCUST
                           WHERE WDEP.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
                                 AND WCUST.WEBUSER_ID = WU.WEBUSER_ID
                                     AND WCUST.CUSTOMER_ID = DEPARTMENT.CUSTOMER_ID
                                     AND WDEP.WEBUSERCUSTOMER_ID = WCUST.WEBUSERCUSTOMER_ID)
        )
/

  CREATE OR REPLACE VIEW "V_WEARERSALES" ("WORKORDERNUMBER", "REFERENCENUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "DECIMALS", "INVOICEAMOUNTDECIMALS", "WEARERNUMBER", "WEARERNAME", "SIZECODE", "PRODUCTCODE", "PRODUCTDESC", "QUANTITYORDERED", "QUANTITYCANCELLED", "SALESPRICE", "DISCOUNTPERCENTAGE", "REPORTPARAM_ID", "LANGUAGECODE") AS 
  select wo.workordernumber, wo.referencenumber, cu.customernumber, cu.name CustomerName
, cur.decimals, cur.invoiceamountdecimals
, we.wearernumber, we.fullname WearerName
, sdl.code SizeCode, pl.code ProductCode
, (select pld.description from product_link_desc pld where pl.product_link_id = pld.product_link_id and pld.language_id = lan.language_id) ProductDesc
, wol.quantityordered, wol.quantitycancelled, wol.salesprice, wol.discountpercentage
, rp.reportparam_id
, lan.code LanguageCode
from workorder wo, weareremployment wee, wearer we, customer cu, currency cur
, workorderline wol, product_link pl, sizedefinition_link sdl
, reportparam rp
, languages lan
where wo.workorder_id = wol.workorder_id and
wo.weareremployment_link_id = wee.weareremployment_id and
wee.wearer_id = we.wearer_id and
we.customer_id = cu.customer_id and
cu.currency_id = cur.currency_id and
wol.product_link_id = pl.product_link_id and
wol.sizedefinition_link_id = sdl.sizedefinition_link_id and
rp.number_value = wo.workorder_id
/

  CREATE OR REPLACE VIEW "V_WEARERSDETAILS" ("DEPARTMENT_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_ID", "WEARERNUMBER", "WEARERNAME", "WEARERSEARCHNAME", "ADMINNUMBER", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DELIVERYPOINTCODEL", "DELIVERYPOINTDESCRIPTIONL", "DELIVERYPOINTCODEG", "DELIVERYPOINTDESCRIPTIONG", "DELIVERYPOINTCODEW", "DELIVERYPOINTDESCRIPTIONW", "COSTCENTERCODE", "COSTCENTERDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "EMPLOYEMENT", "BANK", "LOCKER", "GARMENTDISPENSERCODE", "GARMENTDISPENSERDESCRIPTION", "CITY", "WEARERACTIVE") AS 
  SELECT DEPARTMENT.DEPARTMENT_ID,
  CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME customername, CUSTOMER.CUSTOMER_ID,
  WEARER.WEARERNUMBER, WEARER.FULLNAME WEARERNAME, WEARER.SEARCHNAME WEARERSEARCHNAME,
  WEARER.CUSTOMEREMPLOYEENUMBER ADMINNUMBER,
  DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION departmentdescription,
  DPL.CODE deliverypointcodel, DPL.DESCRIPTION deliverypointdescriptionl,
  DPG.CODE deliverypointcodeg, DPG.DESCRIPTION deliverypointdescriptiong,
  DELIVERYPOINT.CODE deliverypointcodew, DELIVERYPOINT.DESCRIPTION deliverypointdescriptionw,
  COSTCENTER.CODE COSTCENTERCODE, COSTCENTER.DESCRIPTION COSTCENTERDESCRIPTION,
  DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION distributionpointdescription,
  WEAREREMPLOYMENT.SEQUENCENUMBER EMPLOYEMENT,
  LOCKER.BANK bank, LOCKER.LOCKER locker,
  GARMENTDISPENSER.CODE garmentdispensercode, GARMENTDISPENSER.DESCRIPTION garmentdispenserdescription,
  ADR.CITY,
  GETDATEDIFF(trunc(sysdate), WEARER.dateactive)*GETDATEDIFF(WEARER.dateinactive, trunc(sysdate)) wearerActive
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT, WEARER, COSTCENTER, address adr,
  WEAREREMPLOYMENT
    LEFT OUTER JOIN (LOCKER LEFT JOIN DELIVERYPOINT DPL ON LOCKER.DELIVERYPOINT_ID = DPL.DELIVERYPOINT_ID)
      ON (WEAREREMPLOYMENT.LOCKER_ID = LOCKER.LOCKER_ID)
    LEFT OUTER JOIN (GARMENTDISPENSER LEFT JOIN DELIVERYPOINT DPG ON GARMENTDISPENSER.DELIVERYPOINT_ID = DPG.DELIVERYPOINT_ID)
      ON (WEAREREMPLOYMENT.GARMENTDISPENSER_ID = GARMENTDISPENSER.GARMENTDISPENSER_ID)
    LEFT OUTER JOIN DELIVERYPOINT  ON (WEAREREMPLOYMENT.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID)
WHERE WEARER.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
    AND WEARER.WEARER_ID = WEAREREMPLOYMENT.WEARER_ID
    AND WEAREREMPLOYMENT.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
    AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
    AND DISTRIBUTIONPOINT.COSTCENTER_ID = COSTCENTER.COSTCENTER_ID
    AND CUSTOMER.VISITADDRESS_ID = ADR.ADDRESS_ID
/

  CREATE OR REPLACE VIEW "V_WEARERSPERFLAG" ("CUSTOMERNUMBER", "CUSTOMER_ID", "CUSTOMERNAME", "CITY", "DEPARTMENTNUMBER", "WEARERNUMBER", "SEARCHNAME", "FULLNAME", "WEARERFUNCTION", "EMPLOYMENTNUMBER", "FLAGCODE", "FLAGSTARTDATE", "FLAGDESCRIPTION", "LANGUAGECODE") AS 
  select
  cu.customernumber, cu.customer_id, cu.name CustomerName, address.city
, dep.departmentnumber
, wearer.wearernumber, wearer.searchname Searchname, wearer.fullname
, wearerfunction.code wearerfunction
, wey.sequencenumber EmploymentNumber
, flag.code Flagcode, wey.flagstartdate
, (select description from flag_desc where flag_desc.flag_id = flag.flag_id
  and flag_desc.language_id = languages.language_id )FlagDescription
, languages.code languagecode
from
   customer cu, wearer
, weareremployment wey
    left outer join wearerfunction on wey.wearerfunction_id = wearerfunction.wearerfunction_id
, flag, distributionpoint dip, department dep
, address, languages
where
    cu.customer_id = dep.customer_id
and dep.department_id = dip.department_id
and dip.distributionpoint_id = wey.distributionpoint_id
    and wey.wearer_id = wearer.wearer_id
    and wey.flag_id = flag.flag_id
        and wearer.customer_id = cu.customer_id
and cu.visitaddress_id = address.address_id
union
select
  cu.customernumber, cu.customer_id, cu.name CustomerName, address.city
, dep.departmentnumber
, wearer.wearernumber, wearer.searchname Searchname, wearer.fullname
, wearerfunction.code wearerfunction
, wey.sequencenumber EmploymentNumber
, flag.code Flagcode, wearer.flagstartdate
, (select description from flag_desc where flag_desc.flag_id = flag.flag_id
  and flag_desc.language_id = languages.language_id )FlagDescription
, languages.code languagecode
from
   customer cu, wearer
, weareremployment wey
    left outer join wearerfunction on wey.wearerfunction_id = wearerfunction.wearerfunction_id
, flag, distributionpoint dip, department dep
, address, languages
where
    cu.customer_id = dep.customer_id
and dep.department_id = dip.department_id
and dip.distributionpoint_id = wey.distributionpoint_id
    and wey.wearer_id = wearer.wearer_id
        and wearer.flag_id = flag.flag_id
            and wearer.customer_id = cu.customer_id
and cu.visitaddress_id = address.address_id
/

  CREATE OR REPLACE VIEW "V_WEARERS_OLDWEBAPP" ("WEBSESSION_ID", "WEBUSER_ID", "WEBUSERDEPARTMENT_ID", "DEPARTMENT_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "WEARERNAME", "WEARER_ID", "WEARERSEARCHNAME", "EMBLEMNAME", "ADMINNUMBER", "SEX", "DUMMYFORPOOL", "DATEACTIVE", "DATEINACTIVE", "REMARK", "FIRSTNAME", "EMPLOYEMENT", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "WEARERFUNCTIONCODE", "WEARERFUNCTIONDESCRIPTION", "WEARERFUNCTION_ID", "DELIVERYPOINTCODE", "DELIVERYPOINTDESCRIPTION", "DELIVERYPOINTCODEL", "DELIVERYPOINTDESCRIPTIONL", "DELIVERYPOINTCODEG", "DELIVERYPOINTDESCRIPTIONG", "BANK", "LOCKER", "KEYCOMBINATION", "LOCKERMANAGEMENT", "BANKLOCKER", "GARMENTDISPENSERCODE", "GARMENTDISPENSERDESCRIPTION", "DISPENSECREDIT", "SYSTEMUSER_ID", "TIMESTAMP", "WEARERACTIVE", "DELIVERYPOINT_ID", "LOCKER_ID", "GARMENTDISPENSER_ID", "COSTCENTERCODE", "COSTCENTERDESCRIPTION", "COSTCENTER_ID") AS 
  SELECT ws.websession_id, wc.webuser_id, WD.DEPARTMENT_ID WEBUSERDEPARTMENT_ID, DEPARTMENT.DEPARTMENT_ID,
  CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME customername, WEARER.WEARERNUMBER, WEARER.FULLNAME WEARERNAME, WEARER.WEARER_ID,
  WEARER.SEARCHNAME WEARERSEARCHNAME, WEARER.EMBLEMNAME, WEARER.CUSTOMEREMPLOYEENUMBER ADMINNUMBER,
  WEARER.SEX, WEARER.DUMMYFORPOOL,  WEARER.DATEACTIVE, WEARER.DATEINACTIVE, WEARER.REMARK, WEARER.FIRSTNAME ,
  WEAREREMPLOYMENT.SEQUENCENUMBER EMPLOYEMENT, DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER,
  DISTRIBUTIONPOINT.DESCRIPTION distributionpointdescription,
  DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION departmentdescription,
  WEARERFUNCTION.CODE wearerfunctioncode, WEARERFUNCTION.DESCRIPTION wearerfunctiondescription, WEARERFUNCTION.WEARERFUNCTION_ID,
  DELIVERYPOINT.CODE deliverypointcode, DELIVERYPOINT.DESCRIPTION deliverypointdescription,
  DPL.CODE deliverypointcodel, DPL.DESCRIPTION deliverypointdescriptionl,
  DPG.CODE deliverypointcodeg, DPG.DESCRIPTION deliverypointdescriptiong,
  LOCKER.BANK bank, LOCKER.LOCKER locker, LOCKER.keycombination, customer.lockermanagement
, cast(CONCATENATE(LEFTPAD(LOCKER.BANK, 6, '0'), LEFTPAD(LOCKER.LOCKER, 6, '0'))as varchar2(255)) banklocker,
  GARMENTDISPENSER.CODE garmentdispensercode,
  GARMENTDISPENSER.DESCRIPTION garmentdispenserdescription, WEAREREMPLOYMENT.DISPENSECREDIT,
  WEARER.SYSTEMUSER_ID, WEARER.TIMESTAMP,
  GETDATEDIFF(trunc(sysdate), WEARER.dateactive)*GETDATEDIFF(WEARER.dateinactive, trunc(sysdate)) wearerActive,
  WEAREREMPLOYMENT.DELIVERYPOINT_ID, WEAREREMPLOYMENT.LOCKER_ID, WEAREREMPLOYMENT.GARMENTDISPENSER_ID,
  COSTCENTER.CODE COSTCENTERCODE, COSTCENTER.DESCRIPTION COSTCENTERDESCRIPTION, COSTCENTER.COSTCENTER_ID
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT, COSTCENTER, WEARER,
  WEAREREMPLOYMENT
    LEFT OUTER JOIN (LOCKER LEFT JOIN DELIVERYPOINT DPL ON LOCKER.DELIVERYPOINT_ID = DPL.DELIVERYPOINT_ID)
      ON (WEAREREMPLOYMENT.LOCKER_ID = LOCKER.LOCKER_ID)
    LEFT OUTER JOIN (GARMENTDISPENSER LEFT JOIN DELIVERYPOINT DPG ON GARMENTDISPENSER.DELIVERYPOINT_ID = DPG.DELIVERYPOINT_ID)
      ON (WEAREREMPLOYMENT.GARMENTDISPENSER_ID = GARMENTDISPENSER.GARMENTDISPENSER_ID)
    LEFT OUTER JOIN DELIVERYPOINT  ON (WEAREREMPLOYMENT.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID)
    LEFT OUTER JOIN WEARERFUNCTION  ON (WEAREREMPLOYMENT.WEARERFUNCTION_ID = WEARERFUNCTION.WEARERFUNCTION_ID),
  webusercustomer wc
    left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  websession ws
WHERE WEARER.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
    AND WEARER.WEARER_ID = WEAREREMPLOYMENT.WEARER_ID
    AND WEAREREMPLOYMENT.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
    AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
    AND DISTRIBUTIONPOINT.COSTCENTER_ID = COSTCENTER.COSTCENTER_ID
    and wc.customer_id = customer.customer_id
    and customer.customer_id = ws.customer_id
/

  CREATE OR REPLACE VIEW "V_WEBALLOCATIONFORM" ("REPORTPARAM_ID", "ORDER0", "ORDER1", "ORDER2", "ORDER3", "YEAR", "WEEK", "WEEKSTARTDATE", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENT_ID", "WEBUSERDEPARTMENT_ID", "STOCKCOUNTSCHEDULE_ID", "DEPARTMENTNR", "DEPARTMENTDESC", "DISTRIBUTIONPOINT_ID", "DISTRIBUTIONPOINTNR", "DISTRIBUTIONPOINTDESC", "CPYNR", "PRODUCTSEQUENCE", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "SIZEDESC", "FINISHINGMETHODCODE", "FINISHMETHODDESC", "BUNDLEQTY", "PAR_MO", "PAR_TU", "PAR_WE", "PAR_TH", "PAR_FR", "PAR_SA", "PAR_SU", "CPBARCODE", "DATE_MO", "DATE_TU", "DATE_WE", "DATE_TH", "DATE_FR", "DATE_SA", "DATE_SU") AS 
  select /*+ index(sdl XIF799STANDARDDELIVERYLINE)*/
       rp.reportparam_id reportparam_id,
       case
        when scs.stockcountschedule_id is null then 0
        when rp.number_value = 1 -- reportparam numbervalue means sorting:  1= week - dept collate=Y  2= dept - week collate=N
        then wk.year*100+wk.week+cpy.cpynr
        else scs.stockcountschedule_id
       end order0,
       case -- reportparam numbervalue means sorting:  1= week - dept collate=Y  2= dept - week collate=N
        when scs.stockcountschedule_id is not null and rp.number_value = 1 then scs.stockcountschedule_id
        when scs.stockcountschedule_id is not null and rp.number_value <> 1 then scd.countsequence  -- stockcount consumptionpoint sequence
        when scs.stockcountschedule_id is null and rp.number_value = 1 then wk.year*100+wk.week+cpy.cpynr
        when scs.stockcountschedule_id is null and rp.number_value <> 1 then dep.departmentnumber
        else 0
       end order1,
       case
        when rp.number_value = 1 and scs.stockcountschedule_id is not null then scd.countsequence  -- stockcount consumptionpoint sequence
        when rp.number_value = 1 and scs.stockcountschedule_id is null then dep.departmentnumber
        else dip.distributionpointnumber
       end order2,
       case when rp.number_value = 1
        then dip.distributionpointnumber
        else wk.year*100+wk.week+cpy.cpynr
       end order3,
       wk.year,
       wk.week,
       wk.weekstartdate,
       c.customernumber,
       c.name customername,
       dep.department_id department_id,
       wd.department_id webuserdepartment_id,
       coalesce(scs.stockcountschedule_id, -1) stockcountschedule_id,
       dep.departmentnumber departmentnr,
       dep.description departmentdesc,
       dip.distributionpoint_id,
       dip.distributionpointnumber distributionpointnr,
       dip.description distributionpointdesc,
       cpy.cpynr,
       plpd.countsequence productsequence,
       nvl(plpc.customcode, p.code) productcode,
       nvl(plpc.customdescription, pd.description) productdesc,
       s.code sizecode,
       sd.description sizedesc,
       f.code finishingmethodcode,
       fd.description finishmethoddesc,
       case when plpc.custombundlesize <> 0
        then plpc.custombundlesize
        else
          case when nvl(((select pps.packingamount from plantproductsizesettings pps
                   where pps.product_id = p.product_id and pps.sizedefinition_id = sd.sizedefinition_id
                     and pps.plant_id = plant.plant_id)),0) <> 0
            then (select pps.packingamount from plantproductsizesettings pps
                   where pps.product_id = p.product_id and pps.sizedefinition_id = sd.sizedefinition_id
                     and pps.plant_id = plant.plant_id)
            else p.packingamount
          end
       end bundleqty,
       (select sda.amount from standarddeliveryamount sda where sda.standarddeliveryline_id = sdl.standarddeliveryline_id and sda.day_id = 1) Par_MO,
       (select sda.amount from standarddeliveryamount sda where sda.standarddeliveryline_id = sdl.standarddeliveryline_id and sda.day_id = 2) Par_TU,
       (select sda.amount from standarddeliveryamount sda where sda.standarddeliveryline_id = sdl.standarddeliveryline_id and sda.day_id = 3) Par_WE,
       (select sda.amount from standarddeliveryamount sda where sda.standarddeliveryline_id = sdl.standarddeliveryline_id and sda.day_id = 4) Par_TH,
       (select sda.amount from standarddeliveryamount sda where sda.standarddeliveryline_id = sdl.standarddeliveryline_id and sda.day_id = 5) Par_FR,
       (select sda.amount from standarddeliveryamount sda where sda.standarddeliveryline_id = sdl.standarddeliveryline_id and sda.day_id = 6) Par_SA,
       (select sda.amount from standarddeliveryamount sda where sda.standarddeliveryline_id = sdl.standarddeliveryline_id and sda.day_id = 7) Par_SU,
       -- Department/CP Barcode
       cast((select leftpad (dep.departmentnumber,6,'0')||leftpad(dip.distributionpointnumber,3,'0') from dual) as varchar2(9)) cpbarcode,
       (select to_char(wk.weekstartdate,  'MM/DD')from dual) Date_MO,
       (select to_char(wk.weekstartdate+1,'MM/DD')from dual) Date_TU,
       (select to_char(wk.weekstartdate+2,'MM/DD')from dual) Date_WE,
       (select to_char(wk.weekstartdate+3,'MM/DD')from dual) Date_TH,
       (select to_char(wk.weekstartdate+4,'MM/DD')from dual) Date_FR,
       (select to_char(wk.weekstartdate+5,'MM/DD')from dual) Date_SA,
       (select to_char(wk.weekstartdate+6,'MM/DD')from dual) Date_SU
  from standarddeliveryline       sdl,
       productlistperdistribpoint plpd,
       productlistpercustomer     plpc,
       distributionpoint          dip
         left outer join (stockcountscheduledist scd inner join stockcountschedule scs
                                                     on scd.stockcountschedule_id = scs.stockcountschedule_id)
         on scd.distributionpoint_id = dip.distributionpoint_id,
       department                 dep,
       customer                   c,
       businessunit               bu,
       plant,
       customerinternetoptions    ci,
       product                    p,
       product_desc               pd,
       sizedefinition             s,
       sizedefinition_desc        sd,
       finishingmethod            f,
       finishingmethod_desc       fd,
       webuser                    wu
         left outer join (webusercustomer wc left outer join webuserdepartment wd
                                             on wd.webusercustomer_id = wc.webusercustomer_id)
         on wc.webuser_id = wu.webuser_id,
       reportparam                rp,
       (select x.year,
               x.week,
               getdateforweekyear(1,x.week,x.year) weekstartdate,
               getdateforweekyear(7,x.week,x.year) weekenddate,
               rp2.reportparam_id
          from (select distinct getyearofweek(trunc(sysdate) + rownum - 1) year,
                                to_number(getisoweek(trunc(sysdate) + rownum - 1)) week
                  from dual connect by level <= 20 * 7) x,
               Reportparam rp2
         where ((x.week >= rp2.number_value2 and x.year = rp2.number_value1) -- min week
               or (x.year <> rp2.number_value1))
           and ((x.week <= rp2.number_value4 and x.year = rp2.number_value3) -- max week
               or (x.year <> rp2.number_value3))
           and x.year >= rp2.number_value1 -- min year
           and x.year <= rp2.number_value3 -- max year
           ) wk,
       (select rownum cpynr
          from dual connect by level <= 53) cpy
 where sdl.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
   and plpc.productlistpercustomer_id = sdl.productlistpercustomer_id
   and plpc.dateactive <= wk.weekenddate
   and plpc.dateinactive > wk.weekenddate
   and sdl.dateactive <= wk.weekenddate
   and sdl.dateinactive > wk.weekenddate
   and dip.distributionpoint_id = plpd.distributionpoint_id
   and dip.active = 'Y'
   and dep.department_id = dip.department_id
   and dep.active = 'Y'
   and c.customer_id = dep.customer_id
   and ci.customer_id = c.customer_id
   and p.product_id = plpd.product_id
   and pd.product_id = plpd.product_id
   and pd.language_id = wu.language_id
   and s.sizedefinition_id = plpd.sizedefinition_id
   and sd.sizedefinition_id = plpd.sizedefinition_id
   and sd.language_id = wu.language_id
   and f.finishingmethod_id = plpd.finishingmethod_id
   and fd.finishingmethod_id = plpd.finishingmethod_id
   and fd.language_id = wu.language_id
   and ((ci.orderlinen = 'Y' and p.typeofmerchandise = 1)
       or (ci.ordergarments = 'Y' and p.typeofmerchandise = 2)
       or (ci.ordersalesitems = 'Y' and p.typeofmerchandise = 3))
   and ((wu.accessnongarments = 'Y' and p.typeofmerchandise = 1)
       or (wu.accessgarments = 'Y' and p.typeofmerchandise = 2)
       or (wu.accesssalesitems = 'Y' and p.typeofmerchandise = 3))
   and wk.reportparam_id = rp.reportparam_id
   and wu.loginname = rp.string_value
   and c.customernumber = rp.number_value6
   --and rp.number_value5 = 1  -- report param number_value2 means: 1=stockcount schedule selected 2= departments selected.
   -- webuser department filter :
   /*and (exists (select wud.department_id from webuserdepartment wud, webusercustomer wuc
                where wud.webusercustomer_id = wuc.webusercustomer_id
                  and wuc.webuser_id = wu.webuser_id
                  and wuc.customer_id = c.customer_id
                  and wud.department_id = dep.department_id)
        or
       (not exists (select wud.department_id from webuserdepartment wud, webusercustomer wuc
                where wud.webusercustomer_id = wuc.webusercustomer_id
                  and wuc.webuser_id = wu.webuser_id
                  and wuc.customer_id = c.customer_id)))*/--TD 22308 SSB replaced by the 2 coalesces from bellow
   and cpy.cpynr <= rp.copy_number
   and coalesce(wc.customer_id, c.customer_id) = c.customer_id
   and coalesce(wd.department_id, dep.department_id) = dep.department_id
   and c.defaultbusinessunit_id = bu.businessunit_id
   and bu.plant_id = plant.plant_id
   and coalesce(scs.replenishmenttype, 1) = 1
order by order0, order1, order2, order3, cpynr, productsequence
/

  CREATE OR REPLACE VIEW "V_WEBALLOCATIONFORM_DAILY" ("REPORTPARAM_ID", "ORDER0", "ORDER1", "ORDER2", "ORDER3", "YEAR", "WEEK", "DAYNUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENT_ID", "WEBUSERDEPARTMENT_ID", "STOCKCOUNTSCHEDULE_ID", "DEPARTMENTNR", "DEPARTMENTDESC", "DISTRIBUTIONPOINT_ID", "DISTRIBUTIONPOINTNR", "DISTRIBUTIONPOINTDESC", "CPYNR", "PRODUCTSEQUENCE", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "SIZEDESC", "FINISHINGMETHODCODE", "FINISHMETHODDESC", "BUNDLEQTY", "ALLOCATIONDATE", "PARFORDAY", "DAYDESC", "CPBARCODE") AS 
  select /*+ index(sdl XIF799STANDARDDELIVERYLINE)*/
       rp.reportparam_id reportparam_id,
       case
        when scs.stockcountschedule_id is null then 0
        when rp.number_value = 1 -- reportparam numbervalue means sorting:  1= week - dept collate=Y  2= dept - week collate=N
        then dat.year*10000+dat.week*100+dat.day+cpy.cpynr
        else scs.stockcountschedule_id
       end order0,
       case -- reportparam numbervalue means sorting:  1= week - dept collate=Y  2= dept - week collate=N
        when scs.stockcountschedule_id is not null and rp.number_value = 1 then scs.stockcountschedule_id
        when scs.stockcountschedule_id is not null and rp.number_value <> 1 then scd.countsequence  -- stockcount consumptionpoint sequence
        when scs.stockcountschedule_id is null and rp.number_value = 1 then dat.year*10000+dat.week*100+dat.day+cpy.cpynr
        when scs.stockcountschedule_id is null and rp.number_value <> 1 then dep.departmentnumber
        else 0
       end order1,
       case
        when rp.number_value = 1 and scs.stockcountschedule_id is not null then scd.countsequence  -- stockcount consumptionpoint sequence
        when rp.number_value = 1 and scs.stockcountschedule_id is null then dep.departmentnumber
        else dip.distributionpointnumber
       end order2,
       case when rp.number_value = 1
        then dip.distributionpointnumber
        else dat.year*10000+dat.week*100+dat.day+cpy.cpynr
       end order3,
       dat.year,
       dat.week,
       dat.day daynumber,
       c.customernumber,
       c.name customername,
       dep.department_id department_id,
       wd.department_id webuserdepartment_id,
       coalesce(scs.stockcountschedule_id, -1) stockcountschedule_id,
       dep.departmentnumber departmentnr,
       dep.description departmentdesc,
       dip.distributionpoint_id,
       dip.distributionpointnumber distributionpointnr,
       dip.description distributionpointdesc,
       cpy.cpynr,
       plpd.countsequence productsequence,
       nvl(plpc.customcode, p.code) productcode,
       nvl(plpc.customdescription, pd.description) productdesc,
       s.code sizecode,
       sd.description sizedesc,
       f.code finishingmethodcode,
       fd.description finishmethoddesc,
       case when plpc.custombundlesize <> 0
        then plpc.custombundlesize
        else
          case when nvl(((select pps.packingamount from plantproductsizesettings pps
                   where pps.product_id = p.product_id and pps.sizedefinition_id = sd.sizedefinition_id
                     and pps.plant_id = plant.plant_id)),0) <> 0
            then (select pps.packingamount from plantproductsizesettings pps
                   where pps.product_id = p.product_id and pps.sizedefinition_id = sd.sizedefinition_id
                     and pps.plant_id = plant.plant_id)
            else p.packingamount
          end
       end bundleqty,
       dat.allocationdate,
       (select sda.amount
          from standarddeliveryamount sda
         where sda.standarddeliveryline_id = sdl.standarddeliveryline_id and sda.day_id = dat.day) parforday,
       dd.description daydesc,
       -- Department/CP Barcode
       cast((select leftpad (dep.departmentnumber,6,'0')||leftpad(dip.distributionpointnumber,3,'0') from dual) as varchar2(9)) cpbarcode
  from standarddeliveryline       sdl,
       productlistperdistribpoint plpd,
       productlistpercustomer     plpc,
       distributionpoint          dip
         left outer join (stockcountscheduledist scd inner join stockcountschedule scs
                                                     on scd.stockcountschedule_id = scs.stockcountschedule_id)
         on scd.distributionpoint_id = dip.distributionpoint_id,
       department                 dep,
       customer                   c,
       businessunit               bu,
       plant,
       customerinternetoptions    ci,
       product                    p,
       product_desc               pd,
       sizedefinition             s,
       sizedefinition_desc        sd,
       finishingmethod            f,
       finishingmethod_desc       fd,
       webuser                    wu
         left outer join (webusercustomer wc left outer join webuserdepartment wd
                                             on wd.webusercustomer_id = wc.webusercustomer_id)
         on wc.webuser_id = wu.webuser_id,
       reportparam                rp,
       (select x.allocationdate, x.year, x.week, getabsdaynumber(x.allocationdate) day, rp3.reportparam_id
          from (select distinct trunc(sysdate +(rownum - 1)) allocationdate,
                       getyearofweek(trunc(sysdate) + rownum - 1) year,
                       to_number(getisoweek(trunc(sysdate) + rownum - 1)) week
                  from dual connect by level <= 8 + (7 - getabsdaynumber(sysdate))) x,
               reportparam rp3
         where x.allocationdate >= rp3.date_value1
           and x.allocationdate <= rp3.date_value2) dat,
       day_desc                   dd,
       (select rownum cpynr
          from dual connect by level <= 53) cpy
 where sdl.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
   and plpc.productlistpercustomer_id = sdl.productlistpercustomer_id
   and plpc.dateactive <= dat.allocationdate
   and plpc.dateinactive > dat.allocationdate
   and sdl.dateactive <= dat.allocationdate
   and sdl.dateinactive > dat.allocationdate
   and dip.distributionpoint_id = plpd.distributionpoint_id
   and dip.active = 'Y'
   and dep.department_id = dip.department_id
   and dep.active = 'Y'
   and c.customer_id = dep.customer_id
   and ci.customer_id = c.customer_id
   and p.product_id = plpd.product_id
   and pd.product_id = plpd.product_id
   and pd.language_id = wu.language_id
   and s.sizedefinition_id = plpd.sizedefinition_id
   and sd.sizedefinition_id = plpd.sizedefinition_id
   and sd.language_id = wu.language_id
   and f.finishingmethod_id = plpd.finishingmethod_id
   and fd.finishingmethod_id = plpd.finishingmethod_id
   and fd.language_id = wu.language_id
   and dd.day_id = dat.day
   and dd.language_id = wu.language_id
   and ((ci.orderlinen = 'Y' and p.typeofmerchandise = 1)
       or (ci.ordergarments = 'Y' and p.typeofmerchandise = 2)
       or (ci.ordersalesitems = 'Y' and p.typeofmerchandise = 3))
   and ((wu.accessnongarments = 'Y' and p.typeofmerchandise = 1)
       or (wu.accessgarments = 'Y' and p.typeofmerchandise = 2)
       or (wu.accesssalesitems = 'Y' and p.typeofmerchandise = 3))
   and dat.reportparam_id = rp.reportparam_id
   and wu.loginname = rp.string_value
   and c.customernumber = rp.number_value6
   --and rp.number_value5 = 1  -- report param number_value2 means: 1=stockcount schedule selected 2= departments selected.
   and cpy.cpynr <= rp.copy_number
   and coalesce(wc.customer_id, c.customer_id) = c.customer_id
   and coalesce(wd.department_id, dep.department_id) = dep.department_id
   and c.defaultbusinessunit_id = bu.businessunit_id
   and bu.plant_id = plant.plant_id
   and coalesce(scs.replenishmenttype, 1) = 1
order by order0, order1, order2, order3, cpynr, productsequence
/

  CREATE OR REPLACE VIEW "V_WEBBUDGETCMONTHSUM_OLDWEBAPP" ("REPORTPARAM_ID", "WEBSESSION_ID", "WEBUSER_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CURRENCYCODE", "YEAR", "MONTH", "PRODUCTCODE", "PRODUCTDESC", "COSTCENTER_ID", "CCBUDGETRELEVANT", "COSTCENTERCODE", "COSTCENTERDESC", "INVOICED_AMOUNT", "INVOICED_TAX", "INVOICED_QUANTITY", "INVOICELINETYPE", "INVOICEAMOUNTDECIMALS") AS 
  SELECT RP.REPORTPARAM_ID,
  ws.websession_id, wc.webuser_id,
  cs.customer_id, cs.customernumber, cs.name customername,
  cr.code currencycode,
  ih.endyear year, ih.endmonth month,
  il.code productcode, il.description productdesc,
  cc.costcenter_id, cc.budgetrelevant ccbudgetrelevant,
  cc.code costcentercode, cc.description costcenterdesc,
/*  cri.amount invoiced_amount,
  coalesce(cri.amount*(select tg.taxrate from taxgroup tg
    where il.taxgroupcode = tg.code
    and tg.country_id = cs.country_id)/100, 0) invoiced_tax, */
  cri.quantity * coalesce(il.price, 0) * coalesce((select max(ilp.pricefactor) from invoicelineproduct ilp where ilp.invoiceline_id=il.invoiceline_id), 1) +
    (case when coalesce(il.price, 0) = 0 then cri.amount else 0 end) invoiced_amount,
  coalesce(((cri.quantity * coalesce(il.price, 0) * coalesce((select max(ilp.pricefactor) from invoicelineproduct ilp where ilp.invoiceline_id=il.invoiceline_id), 1))+
    (case when coalesce(il.price, 0) = 0 then cri.amount else 0 end))*
    (select tg.taxrate from taxgroup tg
      where il.taxgroupcode = tg.code
        and tg.country_id = cs.country_id) / 100, 0) invoiced_tax,
  cri.quantity invoiced_quantity,
  ilt.type INVOICELINETYPE, cr.invoiceamountdecimals
from invoiceheader ih, invoiceline il,
  costreportinfo cri, costcenter cc,
  customer cs, currency cr,
  status st, invoicelinetype ilt, REPORTPARAM RP
  ,websession ws, webusercustomer wc
where ih.invoiceheader_id = il.invoiceheader_id
  and il.invoiceline_id = cri.invoiceline_id
  and cri.costcenter_link_id = cc.costcenter_id
  and cs.customer_id = ih.deltocustomer_link_id
  and cs.currency_id = cr.currency_id
  and ih.status_id = st.status_id
  and st.code = '2'
  and cs.customer_id = ws.customer_id
  and cs.customer_id = wc.customer_id
  and il.invoicelinetype_id = ilt.invoicelinetype_id
/

  CREATE OR REPLACE VIEW "V_WEBBUDGETCOSTMONTH" ("REPORTPARAM_ID", "WEBSESSION_ID", "WEBUSER_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "BUDGETRELEVANT", "CURRENCYCODE", "YEAR", "MONTH", "PRODUCTCODE", "PRODUCTDESC", "COSTCENTER_ID", "CCBUDGETRELEVANT", "COSTCENTERCODE", "COSTCENTERDESC", "INVOICED_AMOUNT", "INVOICED_TAX", "INVOICED_QUANTITY", "INVOICELINETYPE", "INVOICEAMOUNTDECIMALS") AS 
  SELECT RP.REPORTPARAM_ID,
  wus.websession_id, wc.webuser_id,
  cs.customer_id, cs.customernumber, cs.name customername,
  plpc.budgetrelevant, cr.code currencycode,
  ih.endyear year, ih.endmonth month,
  il.code productcode, il.description productdesc,
  cc.costcenter_id, cc.budgetrelevant ccbudgetrelevant,
  cc.code costcentercode, cc.description costcenterdesc,
/*  cri.amount invoiced_amount,
  coalesce(cri.amount*(select tg.taxrate from taxgroup tg
    where il.taxgroupcode = tg.code
    and tg.country_id = cs.country_id)/100, 0) invoiced_tax, */
  cri.quantity * coalesce(il.price, 0) * ilp.pricefactor +
    (case when coalesce(il.price, 0) = 0 then cri.amount else 0 end) invoiced_amount,
  coalesce(((cri.quantity * coalesce(il.price, 0) * ilp.pricefactor)+
    (case when coalesce(il.price, 0) = 0 then cri.amount else 0 end))*
    (select tg.taxrate from taxgroup tg
      where il.taxgroupcode = tg.code
        and tg.country_id = cs.country_id) / 100, 0) invoiced_tax,
  cri.quantity invoiced_quantity,
  ilt.type INVOICELINETYPE, cr.invoiceamountdecimals
from invoiceheader ih, invoiceline il, invoicelineproduct ilp, costreportinfo cri, costcenter cc,
  customer cs, currency cr,
  productlistpercustomer plpc, status st, invoicelinetype ilt, REPORTPARAM RP
  ,webusersession wus, webusercustomer wc
where ih.invoiceheader_id = il.invoiceheader_id
  and il.invoiceline_id = ilp.invoiceline_id
  and il.invoiceline_id = cri.invoiceline_id
  and cri.costcenter_link_id = cc.costcenter_id
  and cs.customer_id = ih.deltocustomer_link_id
  and cs.currency_id = cr.currency_id
  and ilp.product_link_id = plpc.product_id
  and ilp.sizedefinition_link_id = plpc.sizedefinition_id -->
  and ilp.finishingmethod_id = plpc.finishingmethod_id
  and ih.invoicedate between plpc.dateactive and plpc.dateinactive --  hvh 27.04.05 -->
  and plpc.customer_id = cs.customer_id
  and ih.status_id = st.status_id
  and st.code = '2'
  and cs.customer_id = wus.customer_id
  and cs.customer_id = wc.customer_id
  and il.invoicelinetype_id = ilt.invoicelinetype_id
/

  CREATE OR REPLACE VIEW "V_WEBBUDGETCOSTMONTH_OLDWEBAPP" ("REPORTPARAM_ID", "WEBSESSION_ID", "WEBUSER_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "BUDGETRELEVANT", "CURRENCYCODE", "YEAR", "MONTH", "PRODUCTCODE", "PRODUCTDESC", "COSTCENTER_ID", "CCBUDGETRELEVANT", "COSTCENTERCODE", "COSTCENTERDESC", "INVOICED_AMOUNT", "INVOICED_TAX", "INVOICED_QUANTITY", "INVOICELINETYPE", "INVOICEAMOUNTDECIMALS") AS 
  SELECT RP.REPORTPARAM_ID,
  ws.websession_id, wc.webuser_id,
  cs.customer_id, cs.customernumber, cs.name customername,
  plpc.budgetrelevant, cr.code currencycode,
  ih.endyear year, ih.endmonth month,
  il.code productcode, il.description productdesc,
  cc.costcenter_id, cc.budgetrelevant ccbudgetrelevant,
  cc.code costcentercode, cc.description costcenterdesc,
/*  cri.amount invoiced_amount,
  coalesce(cri.amount*(select tg.taxrate from taxgroup tg
    where il.taxgroupcode = tg.code
    and tg.country_id = cs.country_id)/100, 0) invoiced_tax, */
  cri.quantity * coalesce(il.price, 0) * ilp.pricefactor +
    (case when coalesce(il.price, 0) = 0 then cri.amount else 0 end) invoiced_amount,
  coalesce(((cri.quantity * coalesce(il.price, 0) * ilp.pricefactor)+
    (case when coalesce(il.price, 0) = 0 then cri.amount else 0 end))*
    (select tg.taxrate from taxgroup tg
      where il.taxgroupcode = tg.code
        and tg.country_id = cs.country_id) / 100, 0) invoiced_tax,
  cri.quantity invoiced_quantity,
  ilt.type INVOICELINETYPE, cr.invoiceamountdecimals
from invoiceheader ih, invoiceline il, invoicelineproduct ilp, costreportinfo cri, costcenter cc,
  customer cs, currency cr,
  productlistpercustomer plpc, status st, invoicelinetype ilt, REPORTPARAM RP
  ,websession ws, webusercustomer wc
where ih.invoiceheader_id = il.invoiceheader_id
  and il.invoiceline_id = ilp.invoiceline_id
  and il.invoiceline_id = cri.invoiceline_id
  and cri.costcenter_link_id = cc.costcenter_id
  and cs.customer_id = ih.deltocustomer_link_id
  and cs.currency_id = cr.currency_id
  and ilp.product_link_id = plpc.product_id
  and ilp.sizedefinition_link_id = plpc.sizedefinition_id -->
  and ilp.finishingmethod_id = plpc.finishingmethod_id
  and ih.invoicedate between plpc.dateactive and plpc.dateinactive --  hvh 27.04.05 -->
  and plpc.customer_id = cs.customer_id
  and ih.status_id = st.status_id
  and st.code = '2'
  and cs.customer_id = ws.customer_id
  and cs.customer_id = wc.customer_id
  and il.invoicelinetype_id = ilt.invoicelinetype_id
/

  CREATE OR REPLACE VIEW "V_WEBBUDGETCOSTMONTH_PD" ("CUSTOMER_ID", "COSTCENTER_ID", "REPORTPARAM_ID", "PATIENTDAYS", "PATIENTS") AS 
  SELECT c.customer_id, c.costcenter_id,
  RP.REPORTPARAM_ID,
  sum(p.patientdays) patientdays, sum(p.patients) patients
from costcenter c, distributionpoint dp, patientday p, REPORTPARAM RP
where c.costcenter_id = dp.costcenter_id
  and dp.distributionpoint_id = p.distributionpoint_link_id
  and p.week = 0
  AND RP.NUMBER_VALUE = P.YEAR
  AND P.MONTH >= RP.NUMBER_VALUE1
  AND P.MONTH <= RP.NUMBER_VALUE2
  and c.budgetrelevant = 'Y'
group by c.customer_id, c.costcenter_id, RP.REPORTPARAM_ID
/

  CREATE OR REPLACE VIEW "V_WEBBUDGETCOSTMONTH_SUM" ("REPORTPARAM_ID", "WEBSESSION_ID", "WEBUSER_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CURRENCYCODE", "YEAR", "MONTH", "PRODUCTCODE", "PRODUCTDESC", "COSTCENTER_ID", "CCBUDGETRELEVANT", "COSTCENTERCODE", "COSTCENTERDESC", "INVOICED_AMOUNT", "INVOICED_TAX", "INVOICED_QUANTITY", "INVOICELINETYPE", "INVOICEAMOUNTDECIMALS") AS 
  SELECT RP.REPORTPARAM_ID,
  wus.websession_id, wc.webuser_id,
  cs.customer_id, cs.customernumber, cs.name customername,
  cr.code currencycode,
  ih.endyear year, ih.endmonth month,
  il.code productcode, il.description productdesc,
  cc.costcenter_id, cc.budgetrelevant ccbudgetrelevant,
  cc.code costcentercode, cc.description costcenterdesc,
/*  cri.amount invoiced_amount,
  coalesce(cri.amount*(select tg.taxrate from taxgroup tg
    where il.taxgroupcode = tg.code
    and tg.country_id = cs.country_id)/100, 0) invoiced_tax, */
  cri.quantity * coalesce(il.price, 0) * coalesce((select max(ilp.pricefactor) from invoicelineproduct ilp where ilp.invoiceline_id=il.invoiceline_id), 1) +
    (case when coalesce(il.price, 0) = 0 then cri.amount else 0 end) invoiced_amount,
  coalesce(((cri.quantity * coalesce(il.price, 0) * coalesce((select max(ilp.pricefactor) from invoicelineproduct ilp where ilp.invoiceline_id=il.invoiceline_id), 1))+
    (case when coalesce(il.price, 0) = 0 then cri.amount else 0 end))*
    (select tg.taxrate from taxgroup tg
      where il.taxgroupcode = tg.code
        and tg.country_id = cs.country_id) / 100, 0) invoiced_tax,
  cri.quantity invoiced_quantity,
  ilt.type INVOICELINETYPE, cr.invoiceamountdecimals
from invoiceheader ih, invoiceline il,
  costreportinfo cri, costcenter cc,
  customer cs, currency cr,
  status st, invoicelinetype ilt, REPORTPARAM RP
  ,webusersession wus, webusercustomer wc
where ih.invoiceheader_id = il.invoiceheader_id
  and il.invoiceline_id = cri.invoiceline_id
  and cri.costcenter_link_id = cc.costcenter_id
  and cs.customer_id = ih.deltocustomer_link_id
  and cs.currency_id = cr.currency_id
  and ih.status_id = st.status_id
  and st.code = '2'
  and cs.customer_id = wus.customer_id
  and cs.customer_id = wc.customer_id
  and il.invoicelinetype_id = ilt.invoicelinetype_id
/

  CREATE OR REPLACE VIEW "V_WEBBUDGETCOSTWEEK" ("REPORTPARAM_ID", "WEBSESSION_ID", "WEBUSER_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "BUDGETRELEVANT", "CURRENCYCODE", "YEAR", "WEEK", "PRODUCTCODE", "PRODUCTDESC", "COSTCENTER_ID", "CCBUDGETRELEVANT", "COSTCENTERCODE", "COSTCENTERDESC", "INVOICED_AMOUNT", "INVOICED_TAX", "INVOICED_QUANTITY", "INVOICELINETYPE", "INVOICEAMOUNTDECIMALS") AS 
  SELECT rp.reportparam_id,
  wus.websession_id, wc.webuser_id,
  cs.customer_id, cs.customernumber, cs.name customername,
  plpc.budgetrelevant, cr.code currencycode,
  CRI.YEAR, CRI.WEEK,
  il.code productcode, il.description productdesc,
  cc.costcenter_id, cc.budgetrelevant ccbudgetrelevant,
  cc.code costcentercode, cc.description costcenterdesc,
/*  cri.amount invoiced_amount,
  coalesce(cri.amount*(select tg.taxrate from taxgroup tg
    where il.taxgroupcode = tg.code
    and tg.country_id = cs.country_id)/100, 0) invoiced_tax, */
  cri.quantity * coalesce(il.price, 0) * ilp.pricefactor +
    (case when coalesce(il.price, 0) = 0 then cri.amount else 0 end) invoiced_amount,
  coalesce(((cri.quantity * coalesce(il.price, 0) * ilp.pricefactor)+
    (case when coalesce(il.price, 0) = 0 then cri.amount else 0 end))*
    (select tg.taxrate from taxgroup tg
      where il.taxgroupcode = tg.code
        and tg.country_id = cs.country_id) / 100, 0) invoiced_tax,
  cri.quantity invoiced_quantity,
  ilt.type INVOICELINETYPE, cr.invoiceamountdecimals
from invoiceheader ih, invoiceline il, invoicelineproduct ilp, costreportinfo cri, costcenter cc,
  customer cs, currency cr,
  productlistpercustomer plpc, status st, invoicelinetype ilt, reportparam rp
  ,webusersession wus, webusercustomer wc
where ih.invoiceheader_id = il.invoiceheader_id
  and il.invoiceline_id = ilp.invoiceline_id
  and il.invoiceline_id = cri.invoiceline_id
  and cri.costcenter_link_id = cc.costcenter_id
  and cs.customer_id = ih.deltocustomer_link_id
  and cs.currency_id = cr.currency_id
  and ilp.product_link_id = plpc.product_id
  --and ilp.product_link_id = plpc.product_id -->
  and ilp.sizedefinition_link_id = plpc.sizedefinition_id
  and ilp.finishingmethod_id = plpc.finishingmethod_id
  and ih.invoicedate between plpc.dateactive and plpc.dateinactive --  ?!
  and plpc.customer_id = cs.customer_id
  and ih.status_id = st.status_id
  and st.code = '2'
  and cs.customer_id = wus.customer_id
  and cs.customer_id = wc.customer_id
  and il.invoicelinetype_id = ilt.invoicelinetype_id
/

  CREATE OR REPLACE VIEW "V_WEBBUDGETCOSTWEEK_OLDWEBAPP" ("REPORTPARAM_ID", "WEBSESSION_ID", "WEBUSER_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "BUDGETRELEVANT", "CURRENCYCODE", "YEAR", "WEEK", "PRODUCTCODE", "PRODUCTDESC", "COSTCENTER_ID", "CCBUDGETRELEVANT", "COSTCENTERCODE", "COSTCENTERDESC", "INVOICED_AMOUNT", "INVOICED_TAX", "INVOICED_QUANTITY", "INVOICELINETYPE", "INVOICEAMOUNTDECIMALS") AS 
  SELECT rp.reportparam_id,
  ws.websession_id, wc.webuser_id,
  cs.customer_id, cs.customernumber, cs.name customername,
  plpc.budgetrelevant, cr.code currencycode,
  CRI.YEAR, CRI.WEEK,
  il.code productcode, il.description productdesc,
  cc.costcenter_id, cc.budgetrelevant ccbudgetrelevant,
  cc.code costcentercode, cc.description costcenterdesc,
/*  cri.amount invoiced_amount,
  coalesce(cri.amount*(select tg.taxrate from taxgroup tg
    where il.taxgroupcode = tg.code
    and tg.country_id = cs.country_id)/100, 0) invoiced_tax, */
  cri.quantity * coalesce(il.price, 0) * ilp.pricefactor +
    (case when coalesce(il.price, 0) = 0 then cri.amount else 0 end) invoiced_amount,
  coalesce(((cri.quantity * coalesce(il.price, 0) * ilp.pricefactor)+
    (case when coalesce(il.price, 0) = 0 then cri.amount else 0 end))*
    (select tg.taxrate from taxgroup tg
      where il.taxgroupcode = tg.code
        and tg.country_id = cs.country_id) / 100, 0) invoiced_tax,
  cri.quantity invoiced_quantity,
  ilt.type INVOICELINETYPE, cr.invoiceamountdecimals
from invoiceheader ih, invoiceline il, invoicelineproduct ilp, costreportinfo cri, costcenter cc,
  customer cs, currency cr,
  productlistpercustomer plpc, status st, invoicelinetype ilt, reportparam rp
  ,websession ws, webusercustomer wc
where ih.invoiceheader_id = il.invoiceheader_id
  and il.invoiceline_id = ilp.invoiceline_id
  and il.invoiceline_id = cri.invoiceline_id
  and cri.costcenter_link_id = cc.costcenter_id
  and cs.customer_id = ih.deltocustomer_link_id
  and cs.currency_id = cr.currency_id
  and ilp.product_link_id = plpc.product_id
  --and ilp.product_link_id = plpc.product_id -->
  and ilp.sizedefinition_link_id = plpc.sizedefinition_id
  and ilp.finishingmethod_id = plpc.finishingmethod_id
  and ih.invoicedate between plpc.dateactive and plpc.dateinactive --  ?!
  and plpc.customer_id = cs.customer_id
  and ih.status_id = st.status_id
  and st.code = '2'
  and cs.customer_id = ws.customer_id
  and cs.customer_id = wc.customer_id
  and il.invoicelinetype_id = ilt.invoicelinetype_id
/

  CREATE OR REPLACE VIEW "V_WEBBUDGETCOSTWEEK_PD" ("CUSTOMER_ID", "COSTCENTER_ID", "REPORTPARAM_ID", "PATIENTDAYS", "PATIENTS") AS 
  SELECT c.customer_id, c.costcenter_id,
  RP.REPORTPARAM_ID,
  sum(p.patientdays) patientdays, sum(p.patients) patients
from costcenter c, distributionpoint dp, patientday p, REPORTPARAM RP
where c.costcenter_id = dp.costcenter_id
  and dp.distributionpoint_id = p.distributionpoint_link_id
  and p.MONTH = 0
  AND RP.NUMBER_VALUE = P.YEAR
  AND P.WEEK >= RP.NUMBER_VALUE1
  AND P.WEEK <= RP.NUMBER_VALUE2
  and c.budgetrelevant = 'Y'
group by c.customer_id, c.costcenter_id, RP.REPORTPARAM_ID
/

  CREATE OR REPLACE VIEW "V_WEBBUDGETCOSTWEEK_PD_T" ("CUSTOMER_ID", "COSTCENTER_ID", "PATIENTDAYS", "PATIENTS") AS 
  SELECT c.customer_id, c.costcenter_id,
--  RP.REPORTPARAM_ID,
  sum(p.patientdays) patientdays, sum(p.patients) patients
from costcenter c, distributionpoint dp, patientday p--, REPORTPARAM RP
where c.costcenter_id = dp.costcenter_id
  and dp.distributionpoint_id = p.distributionpoint_link_id
  and p.MONTH = 0
  AND P.YEAR = 2005--RP.NUMBER_VALUE
  AND P.WEEK >= 1--RP.NUMBER_VALUE1
  AND P.WEEK <= 52--RP.NUMBER_VALUE2
  and c.budgetrelevant = 'Y'
group by c.customer_id, c.costcenter_id--, RP.REPORTPARAM_ID
/

  CREATE OR REPLACE VIEW "V_WEBBUDGETCOSTWEEK_SUM" ("REPORTPARAM_ID", "WEBSESSION_ID", "WEBUSER_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CURRENCYCODE", "YEAR", "WEEK", "PRODUCTCODE", "PRODUCTDESC", "COSTCENTER_ID", "CCBUDGETRELEVANT", "COSTCENTERCODE", "COSTCENTERDESC", "INVOICED_AMOUNT", "INVOICED_TAX", "INVOICED_QUANTITY", "INVOICELINETYPE", "INVOICEAMOUNTDECIMALS") AS 
  SELECT rp.reportparam_id,
  wus.websession_id, wc.webuser_id,
  cs.customer_id, cs.customernumber, cs.name customername,
  cr.code currencycode,
  CRI.YEAR, CRI.WEEK,
  il.code productcode, il.description productdesc,
  cc.costcenter_id, cc.budgetrelevant ccbudgetrelevant,
  cc.code costcentercode, cc.description costcenterdesc,
/*  cri.amount invoiced_amount,
  coalesce(cri.amount*(select tg.taxrate from taxgroup tg
    where il.taxgroupcode = tg.code
    and tg.country_id = cs.country_id)/100, 0) invoiced_tax, */
  cri.quantity * coalesce(il.price, 0) * coalesce((select max(ilp.pricefactor) from invoicelineproduct ilp where ilp.invoiceline_id=il.invoiceline_id), 1) +
    (case when coalesce(il.price, 0) = 0 then cri.amount else 0 end) invoiced_amount,
  coalesce(((cri.quantity * coalesce(il.price, 0) * coalesce((select max(ilp.pricefactor) from invoicelineproduct ilp where ilp.invoiceline_id=il.invoiceline_id), 1)) +
    (case when coalesce(il.price, 0) = 0 then cri.amount else 0 end))*
    (select tg.taxrate from taxgroup tg
      where il.taxgroupcode = tg.code
        and tg.country_id = cs.country_id)/100, 0) invoiced_tax,
  cri.quantity invoiced_quantity,
  ilt.type INVOICELINETYPE, cr.invoiceamountdecimals
from invoiceheader ih, invoiceline il, costreportinfo cri, costcenter cc,
  customer cs, currency cr,
  status st, invoicelinetype ilt, reportparam rp
  ,webusersession wus, webusercustomer wc
where ih.invoiceheader_id = il.invoiceheader_id
  and il.invoiceline_id = cri.invoiceline_id
  and cri.costcenter_link_id = cc.costcenter_id
  and cs.customer_id = ih.deltocustomer_link_id
  and cs.currency_id = cr.currency_id
  and ih.status_id = st.status_id
  and st.code = '2'
  and cs.customer_id = wus.customer_id
  and cs.customer_id = wc.customer_id
  and il.invoicelinetype_id = ilt.invoicelinetype_id
/

  CREATE OR REPLACE VIEW "V_WEBBUDGETCOSTWEEK_T" ("CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "BUDGETRELEVANT", "CURRENCYCODE", "YEAR", "WEEK", "PRODUCTCODE", "PRODUCTDESC", "COSTCENTER_ID", "CCBUDGETRELEVANT", "COSTCENTERCODE", "COSTCENTERDESC", "INVOICED_AMOUNT", "INVOICED_TAX", "INVOICED_QUANTITY", "INVOICELINETYPE") AS 
  SELECT -- rp.reportparam_id, ws.websession_id, wc.webuser_id,
  cs.customer_id, cs.customernumber, cs.name customername,
  plpc.budgetrelevant, cr.code currencycode,
  CRI.YEAR, CRI.WEEK,
  il.code productcode, il.description productdesc,
  cc.costcenter_id, cc.budgetrelevant ccbudgetrelevant,
  cc.code costcentercode, cc.description costcenterdesc,
  cri.amount invoiced_amount,
  coalesce(cri.amount*(select tg.taxrate from taxgroup tg
    where il.taxgroupcode = tg.code
    and tg.country_id = cs.country_id)/100, 0) invoiced_tax,
  cri.quantity invoiced_quantity,
  ilt.type INVOICELINETYPE
from invoiceheader ih, invoiceline il, invoicelineproduct ilp, costreportinfo cri, costcenter cc,
  customer cs, currency cr,
  productlistpercustomer plpc, status st, invoicelinetype ilt
--  , reportparam rp ,websession ws, webusercustomer wc
where ih.invoiceheader_id = il.invoiceheader_id
  and il.invoiceline_id = ilp.invoiceline_id
  and il.invoiceline_id = cri.invoiceline_id
  and cri.costcenter_link_id = cc.costcenter_id
  and cs.customer_id = ih.deltocustomer_link_id
  and cs.currency_id = cr.currency_id
  and ilp.product_link_id = plpc.product_id
  and ilp.product_link_id = plpc.product_id -->
  and ilp.sizedefinition_link_id = plpc.sizedefinition_id
  and ilp.finishingmethod_id = plpc.finishingmethod_id
  and ih.invoicedate between plpc.dateactive and plpc.dateinactive --  ?!
  and plpc.customer_id = cs.customer_id
  and ih.status_id = st.status_id
  and st.code = '2'
--  and cs.customer_id = ws.customer_id
--  and cs.customer_id = wc.customer_id
  and il.invoicelinetype_id = ilt.invoicelinetype_id
/

  CREATE OR REPLACE VIEW "V_WEBBUDGETCWEEK_SUM_OLDWEBAPP" ("REPORTPARAM_ID", "WEBSESSION_ID", "WEBUSER_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CURRENCYCODE", "YEAR", "WEEK", "PRODUCTCODE", "PRODUCTDESC", "COSTCENTER_ID", "CCBUDGETRELEVANT", "COSTCENTERCODE", "COSTCENTERDESC", "INVOICED_AMOUNT", "INVOICED_TAX", "INVOICED_QUANTITY", "INVOICELINETYPE", "INVOICEAMOUNTDECIMALS") AS 
  SELECT rp.reportparam_id,
  ws.websession_id, wc.webuser_id,
  cs.customer_id, cs.customernumber, cs.name customername,
  cr.code currencycode,
  CRI.YEAR, CRI.WEEK,
  il.code productcode, il.description productdesc,
  cc.costcenter_id, cc.budgetrelevant ccbudgetrelevant,
  cc.code costcentercode, cc.description costcenterdesc,
/*  cri.amount invoiced_amount,
  coalesce(cri.amount*(select tg.taxrate from taxgroup tg
    where il.taxgroupcode = tg.code
    and tg.country_id = cs.country_id)/100, 0) invoiced_tax, */
  cri.quantity * coalesce(il.price, 0) * coalesce((select max(ilp.pricefactor) from invoicelineproduct ilp where ilp.invoiceline_id=il.invoiceline_id), 1) +
    (case when coalesce(il.price, 0) = 0 then cri.amount else 0 end) invoiced_amount,
  coalesce(((cri.quantity * coalesce(il.price, 0) * coalesce((select max(ilp.pricefactor) from invoicelineproduct ilp where ilp.invoiceline_id=il.invoiceline_id), 1)) +
    (case when coalesce(il.price, 0) = 0 then cri.amount else 0 end))*
    (select tg.taxrate from taxgroup tg
      where il.taxgroupcode = tg.code
        and tg.country_id = cs.country_id)/100, 0) invoiced_tax,
  cri.quantity invoiced_quantity,
  ilt.type INVOICELINETYPE, cr.invoiceamountdecimals
from invoiceheader ih, invoiceline il, costreportinfo cri, costcenter cc,
  customer cs, currency cr,
  status st, invoicelinetype ilt, reportparam rp
  ,websession ws, webusercustomer wc
where ih.invoiceheader_id = il.invoiceheader_id
  and il.invoiceline_id = cri.invoiceline_id
  and cri.costcenter_link_id = cc.costcenter_id
  and cs.customer_id = ih.deltocustomer_link_id
  and cs.currency_id = cr.currency_id
  and ih.status_id = st.status_id
  and st.code = '2'
  and cs.customer_id = ws.customer_id
  and cs.customer_id = wc.customer_id
  and il.invoicelinetype_id = ilt.invoicelinetype_id
/

  CREATE OR REPLACE VIEW "V_WEBBUDGETDETERMINATION" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "CURRENCYCODE", "DECIMALS", "COSTCENTER_ID", "COSTCENTERCODE", "COSTCENTERDESC", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DEPARTMENT_ID", "WEBUSERDEPARTMENT_ID", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "FINISHINGMETHODCODE", "AMOUNT", "TAXRATE", "WASHPRICE", "WEBUSER_ID", "WEBSESSION_ID", "LANGUAGECODE", "REPORTPARAM_ID") AS 
  select cu.customernumber, cu.name customername,
  ad.city, cr.code currencycode, cr.decimals,cs.costcenter_id,
  cs.code costcentercode, cs.description costcenterdesc,
  de.departmentnumber, de.description departmentdesc,
  de.department_id, wd.department_id webuserdepartment_id,
  di.distributionpointnumber, di.description distributionpointdesc,
  pr.code productcode,
  (select prd.description from product_desc prd where prd.product_id = pr.product_id
    and prd.language_id = languages.language_id) productdesc,
  sz.code sizecode, fm.code finishingmethodcode,
  sum(sda.amount) amount,
  F_GETVAT(1, cu.customer_id, pr.product_id, rp.number_value, cu.country_id, rp.date_value1) taxrate,
  pack_price.Wash_Price(CU.CUSTOMER_ID, PR.PRODUCT_ID, SZ.SIZEDEFINITION_ID, FM.FINISHINGMETHOD_ID, RP.DATE_VALUE1) WASHPRICE,
  wc.webuser_id, wus.websession_id,
  languages.code languagecode, rp.reportparam_id
from customer cu, address ad, currency cr, costcenter cs, department de, distributionpoint di,
  productlistpercustomer plpc, product pr, sizedefinition sz, finishingmethod fm,
  productlistperdistribpoint plpd, standarddeliveryline sdl, standarddeliveryamount sda,
  webusercustomer wc
    left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  webusersession wus,
  languages, reportparam rp
where cu.customer_id = cs.customer_id
  and cs.costcenter_id = di.costcenter_id
  and de.department_id = di.department_id
  and cu.visitaddress_id = ad.address_id
  and cu.currency_id = cr.currency_id
  and cu.customer_id = plpc.customer_id
  and plpc.product_id = pr.product_id
  and plpd.sizedefinition_id = sz.sizedefinition_id
  and plpc.finishingmethod_id = fm.finishingmethod_id
  and plpc.productlistpercustomer_id = sdl.productlistpercustomer_id
  and di.distributionpoint_id = plpd.distributionpoint_id
  and plpd.productlistperdistribpoint_id = sdl.productlistperdistribpoint_id
  and sdl.standarddeliveryline_id = sda.standarddeliveryline_id
  and wc.customer_id = cu.customer_id
  and wus.customer_id = cu.customer_id
  and sdl.dateactive <= rp.date_value1 and sdl.dateinactive >= rp.date_value1
group by cu.customernumber, cu.name, ad.city, cr.code, cs.costcenter_id, cs.code, cs.description, de.departmentnumber,
  de.description, di.distributionpointnumber, di.description, pr.code, sz.code, fm.code,
  languages.language_id, CU.CUSTOMER_ID, PR.PRODUCT_ID, SZ.SIZEDEFINITION_ID, FM.FINISHINGMETHOD_ID,
  cu.customer_id, pr.productgroup_id, cu.country_id, RP.DATE_VALUE1,
  wc.webuser_id, wus.websession_id, cr.decimals, de.department_id, wd.department_id,
  RP.DATE_VALUE1, languages.code, rp.reportparam_id, rp.number_value
/

  CREATE OR REPLACE VIEW "V_WEBBUDGETDETERM_OLDWEBAPP" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "CURRENCYCODE", "DECIMALS", "COSTCENTER_ID", "COSTCENTERCODE", "COSTCENTERDESC", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DEPARTMENT_ID", "WEBUSERDEPARTMENT_ID", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "FINISHINGMETHODCODE", "AMOUNT", "TAXRATE", "WASHPRICE", "WEBUSER_ID", "WEBSESSION_ID", "LANGUAGECODE", "REPORTPARAM_ID") AS 
  select cu.customernumber, cu.name customername,
  ad.city, cr.code currencycode, cr.decimals,cs.costcenter_id,
  cs.code costcentercode, cs.description costcenterdesc,
  de.departmentnumber, de.description departmentdesc,
  de.department_id, wd.department_id webuserdepartment_id,
  di.distributionpointnumber, di.description distributionpointdesc,
  pr.code productcode,
  (select prd.description from product_desc prd where prd.product_id = pr.product_id
    and prd.language_id = languages.language_id) productdesc,
  sz.code sizecode, fm.code finishingmethodcode,
  sum(sda.amount) amount,
  F_GETVAT(1, cu.customer_id, pr.product_id, rp.number_value, cu.country_id, rp.date_value1) taxrate,
  pack_price.Wash_Price(CU.CUSTOMER_ID, PR.PRODUCT_ID, SZ.SIZEDEFINITION_ID, FM.FINISHINGMETHOD_ID, RP.DATE_VALUE1) WASHPRICE,
  wc.webuser_id, ws.websession_id,
  languages.code languagecode, rp.reportparam_id
from customer cu, address ad, currency cr, costcenter cs, department de, distributionpoint di,
  productlistpercustomer plpc, product pr, sizedefinition sz, finishingmethod fm,
  productlistperdistribpoint plpd, standarddeliveryline sdl, standarddeliveryamount sda,
  webusercustomer wc
    left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  websession ws,
  languages, reportparam rp
where cu.customer_id = cs.customer_id
  and cs.costcenter_id = di.costcenter_id
  and de.department_id = di.department_id
  and cu.visitaddress_id = ad.address_id
  and cu.currency_id = cr.currency_id
  and cu.customer_id = plpc.customer_id
  and plpc.product_id = pr.product_id
  and plpd.sizedefinition_id = sz.sizedefinition_id
  and plpc.finishingmethod_id = fm.finishingmethod_id
  and plpc.productlistpercustomer_id = sdl.productlistpercustomer_id
  and di.distributionpoint_id = plpd.distributionpoint_id
  and plpd.productlistperdistribpoint_id = sdl.productlistperdistribpoint_id
  and sdl.standarddeliveryline_id = sda.standarddeliveryline_id
  and wc.customer_id = cu.customer_id
  and ws.customer_id = cu.customer_id
  and sdl.dateactive <= rp.date_value1 and sdl.dateinactive >= rp.date_value1
group by cu.customernumber, cu.name, ad.city, cr.code, cs.costcenter_id, cs.code, cs.description, de.departmentnumber,
  de.description, di.distributionpointnumber, di.description, pr.code, sz.code, fm.code,
  languages.language_id, CU.CUSTOMER_ID, PR.PRODUCT_ID, SZ.SIZEDEFINITION_ID, FM.FINISHINGMETHOD_ID,
  cu.customer_id, pr.productgroup_id, cu.country_id, RP.DATE_VALUE1,
  wc.webuser_id, ws.websession_id, cr.decimals, de.department_id, wd.department_id,
  RP.DATE_VALUE1, languages.code, rp.reportparam_id, rp.number_value
/

  CREATE OR REPLACE VIEW "V_WEBBUDGETRECONCILIATION" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENT_ID", "WEBUSERDEPARTMENT_ID", "CITY", "CURRENCYCODE", "INVOICEAMOUNTDECIMALS", "COSTCENTER_ID", "COSTCENTERCODE", "COSTCENTERDESC", "CUSTOMER_ID", "WEBUSER_ID", "WEBSESSION_ID", "BUDGETAMOUNT", "ACTUALAMOUNT", "REPORTPARAM_ID") AS 
  select distinct cu.customernumber, cu.name customername,
  dp.department_id, wd.department_id webuserdepartment_id,
  ad.city, cr.code currencycode, cr.invoiceamountdecimals,
  cc.costcenter_id, cc.code costcentercode, cc.description costcenterdesc,
  cc.customer_id, wc.webuser_id, wus.websession_id,
  F_WBR_BUDGETAMOUNT(rp.number_value4, cc.costcenter_id, rp.number_value, rp.number_value5, rp.number_value1, rp.number_value2) BUDGETAMOUNT,
  F_WBR_ACTUALAMOUNT(rp.number_value4, cc.costcenter_id, rp.number_value, rp.number_value5, rp.number_value1, rp.number_value2) ACTUALAMOUNT,
  rp.reportparam_id
from costcenter cc, distributionpoint dp, customer cu, address ad, currency cr,
  webusercustomer wc
    left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  webusersession wus,
  reportparam rp
where cc.customer_id = cu.customer_id
  and cc.costcenter_id = dp.costcenter_id
  and cu.visitaddress_id = ad.address_id
  and cu.currency_id = cr.currency_id
  and wc.customer_id = cu.customer_id
  and wus.customer_id = cu.customer_id
/

  CREATE OR REPLACE VIEW "V_WEBBUDGETRECONC_OLDWEBAPP" ("CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENT_ID", "WEBUSERDEPARTMENT_ID", "CITY", "CURRENCYCODE", "INVOICEAMOUNTDECIMALS", "COSTCENTER_ID", "COSTCENTERCODE", "COSTCENTERDESC", "CUSTOMER_ID", "WEBUSER_ID", "WEBSESSION_ID", "BUDGETAMOUNT", "ACTUALAMOUNT", "REPORTPARAM_ID") AS 
  select distinct cu.customernumber, cu.name customername,
  dp.department_id, wd.department_id webuserdepartment_id,
  ad.city, cr.code currencycode, cr.invoiceamountdecimals,
  cc.costcenter_id, cc.code costcentercode, cc.description costcenterdesc,
  cc.customer_id, wc.webuser_id, ws.websession_id,
  F_WBR_BUDGETAMOUNT(rp.number_value4, cc.costcenter_id, rp.number_value, rp.number_value5, rp.number_value1, rp.number_value2) BUDGETAMOUNT,
  F_WBR_ACTUALAMOUNT(rp.number_value4, cc.costcenter_id, rp.number_value, rp.number_value5, rp.number_value1, rp.number_value2) ACTUALAMOUNT,
  rp.reportparam_id
from costcenter cc, distributionpoint dp, customer cu, address ad, currency cr,
  webusercustomer wc
    left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  websession ws,
  reportparam rp
where cc.customer_id = cu.customer_id
  and cc.costcenter_id = dp.costcenter_id
  and cu.visitaddress_id = ad.address_id
  and cu.currency_id = cr.currency_id
  and wc.customer_id = cu.customer_id
  and ws.customer_id = cu.customer_id
/

  CREATE OR REPLACE VIEW "V_WEBBUDGETS" ("CUSTOMER_ID", "CUSTOMERNUMBER", "NAME", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DESCRIPTION", "YEAR", "MONTH", "WEEK", "AMOUNT", "LANGUAGECODE") AS 
  select c.customer_id, c.customernumber, c.name, d.department_id, d.departmentnumber, d.description,
       b.year, b.month, b.week, b.amount, languages.code languagecode
from budget b, department d, customer c, languages
where b.department_link_id = d.department_id
      and d.customer_id = c.customer_id
			and d.active = 'Y'
/

  CREATE OR REPLACE VIEW "V_WEBCDN_DELAYEDDELIVERY" ("CLIENTDELIVERYNOTE_ID", "PACKINGSEQUENCE", "PRODUCTCODE", "SIZECODE", "FINISHINGMETHODCODE", "PRODUCTDESC", "PRIMARYID", "LANGUAGECODE", "PRODCUSTOM_CODE", "PRODCUSTOM_DESC") AS 
  select  -- ui
  cdn.clientdeliverynote_id, prd.packingsequence, prd.code productCode, sz.code sizeCode, fm.code finishingmethodCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc, uri.primaryid
, languages.code languageCode
, (SELECT plpc.customcode FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Code
, (SELECT plpc.customdescription FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc
from
  clientdeliverynote cdn, clientdeliverynoteline cdl, clientdelnotelinescan cds, uniqueresidentialitem uri
, product prd, sizedefinition sz, finishingmethod fm, batch b
, languages
where
    cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
and cdl.clientdeliverynoteline_id = cds.inscanclientdelnoteline_id
    and ( cds.outscanclientdelnoteline_id is null or cds.delayed = 'Y' )
        and cds.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id
and cdl.product_link_id = prd.product_id
and cdl.sizedefinition_link_id = sz.sizedefinition_id
and cdl.finishingmethod_id = fm.finishingmethod_id
and cdn.batch_id = b.batch_id
and b.closingdate is not null -- closed batch
  union all  -- nui
select
  cdn.clientdeliverynote_id, prd.packingsequence, prd.code productCode, sz.code sizeCode, fm.code finishingmethodCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc, '' primaryid
, languages.code languageCode
, (SELECT plpc.customcode FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Code
, (SELECT plpc.customdescription FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc
from
  clientdeliverynote cdn, clientdeliverynoteline cdl, clientdelnotelinedelayed cdd
, product prd, sizedefinition sz, finishingmethod fm, batch b
, languages
where
    cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
and cdl.clientdeliverynoteline_id = cdd.clientdeliverynoteline_id
and cdl.product_link_id = prd.product_id
and cdl.sizedefinition_link_id = sz.sizedefinition_id
and cdl.finishingmethod_id = fm.finishingmethod_id
and cdn.batch_id = b.batch_id
and b.closingdate is not null -- closed batch
/

  CREATE OR REPLACE VIEW "V_WEBCDN_DELIVEREDAFTER" ("CLIENTDELIVERYNOTE_ID", "PACKINGSEQUENCE", "PRODUCTCODE", "SIZECODE", "FINISHINGMETHODCODE", "PRODUCTDESC", "PRIMARYID", "FROMNOTENR", "FROMDELDATE", "LANGUAGECODE", "PRODCUSTOM_CODE", "PRODCUSTOM_DESC") AS 
  select  -- ui
  cdn.clientdeliverynote_id, prd.packingsequence, prd.code productCode, sz.code sizeCode, fm.code finishingmethodCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc, uri.primaryid
, cdn_From.Clientdeliverynotenumber fromNoteNr, cdn_From.Deliverydate fromDelDate
, languages.code languageCode
, (SELECT plpc.customcode FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Code
, (SELECT plpc.customdescription FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc
from
  clientdeliverynote cdn, clientdeliverynoteline cdl, clientdelnotelinescan cds, uniqueresidentialitem uri
, product prd, sizedefinition sz, finishingmethod fm
, clientdeliverynoteline cdl_From, clientdeliverynote cdn_From
, languages
where
    cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
and cdl.clientdeliverynoteline_id = cds.outscanclientdelnoteline_id
    and cds.inscanclientdelnoteline_id <> cds.outscanclientdelnoteline_id
        and cds.delayed = 'Y'
            and cds.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id
and cdl.product_link_id = prd.product_id
and cdl.sizedefinition_link_id = sz.sizedefinition_id
and cdl.finishingmethod_id = fm.finishingmethod_id
and cds.inscanclientdelnoteline_id = cdl_From.Clientdeliverynoteline_Id
    and cdl_From.Clientdeliverinote_Id = cdn_From.Clientdeliverynote_Id
  union all  -- n_ui
select
  cdn.clientdeliverynote_id, prd.packingsequence, prd.code productCode, sz.code sizeCode, fm.code finishingmethodCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc, '' primaryid
, cdn_From.Clientdeliverynotenumber fromNoteNr, cdn_From.Deliverydate fromDelDate
, languages.code languageCode
, (SELECT plpc.customcode FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Code
, (SELECT plpc.customdescription FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc
from
  clientdeliverynote cdn, clientdeliverynoteline cdl, clientdelnotelinedelayed cdd
, product prd, sizedefinition sz, finishingmethod fm, clientdeliverynoteline cdl_From, clientdeliverynote cdn_From
, languages
where
    cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
and cdl.clientdeliverynoteline_id = cdd.deliverdline_id
and cdl.product_link_id = prd.product_id
and cdl.sizedefinition_link_id = sz.sizedefinition_id
and cdl.finishingmethod_id = fm.finishingmethod_id
and cdd.clientdeliverynoteline_id = cdl_From.Clientdeliverynoteline_Id
    and cdl_From.Clientdeliverinote_Id = cdn_From.Clientdeliverynote_Id
/

  CREATE OR REPLACE VIEW "V_WEBCDN_RECEIVEFROMOWNER" ("CLIENTDELIVERYNOTE_ID", "PACKINGSEQUENCE", "PRODUCTCODE", "SIZECODE", "FINISHINGMETHODCODE", "PRODUCTDESC", "PRIMARYID", "OWNERNUMBER", "OWNERNAME", "ROOMNUMBER", "NOTENUMBER", "LANGUAGECODE", "PRODCUSTOM_CODE", "PRODCUSTOM_DESC") AS 
  select
  cdn.clientdeliverynote_id, prd.packingsequence, prd.code productCode, sz.code sizeCode, fm.code finishingmethodCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, uri.primaryid, client.clientnumber ownerNumber, client.name ownerName, dr.roomnumber
--, cdn.clientdeliverynotenumber noteNumber
, cdn_note.clientdeliverynotenumber noteNumber
, languages.code languageCode
, (SELECT plpc.customcode FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Code
, (SELECT plpc.customdescription FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc
from
  clientdeliverynote cdn, clientdeliverynoteline cdl
, clientdelnotelinescan cds, clientdeliverynoteline cdl_note, clientdeliverynote cdn_note
, uniqueresidentialitem uri
, client, clientresident cr, departmentroom dr
, product prd, sizedefinition sz, finishingmethod fm
, languages
WHERE cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
and cdl.clientdeliverynoteline_id = cds.outscanclientdelnoteline_id
    and cds.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id
and cdl.product_link_id = prd.product_id
and cdl.sizedefinition_link_id = sz.sizedefinition_id
and cdl.finishingmethod_id = fm.finishingmethod_id
and cds.inscanclientdelnoteline_id = cdl_note.clientdeliverynoteline_id
    and cdl_note.clientdeliverinote_id = cdn_note.clientdeliverynote_id
        and cdn_note.client_link_id <> cdn.client_link_id
            and cdn.client_link_id = client.client_id
                and client.client_id = cr.client_id
                    and cr.departmentroom_id = dr.departmentroom_id
/

  CREATE OR REPLACE VIEW "V_WEBCDN_SENDTOOWNER" ("CLIENTDELIVERYNOTE_ID", "PACKINGSEQUENCE", "PRODUCTCODE", "SIZECODE", "FINISHINGMETHODCODE", "PRODUCTDESC", "PRIMARYID", "OWNERNUMBER", "OWNERNAME", "ROOMNUMBER", "NOTENUMBER", "LANGUAGECODE", "PRODCUSTOM_CODE", "PRODCUSTOM_DESC") AS 
  select
  cdn.clientdeliverynote_id, prd.packingsequence, prd.code productCode, sz.code sizeCode, fm.code finishingmethodCode
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, uri.primaryid, client.clientnumber ownerNumber, client.name ownerName, dr.roomnumber
, cdn_note.clientdeliverynotenumber noteNumber
, languages.code languageCode
, (SELECT plpc.customcode FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Code
, (SELECT plpc.customdescription FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cdn.customer_link_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc
from
  clientdeliverynote cdn, clientdeliverynoteline cdl
, clientdelnotelinescan cds
    left outer join
      ( clientdeliverynoteline cdl_note join clientdeliverynote cdn_note on cdl_note.clientdeliverinote_id = cdn_note.clientdeliverynote_id
         ) on cds.outscanclientdelnoteline_id = cdl_note.clientdeliverynoteline_id
, uniqueresidentialitem uri, client, clientresident cr, departmentroom dr
, product prd, sizedefinition sz, finishingmethod fm
, languages
WHERE  cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
and cdl.clientdeliverynoteline_id = cds.inscanclientdelnoteline_id
    and cds.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id
        and uri.client_id = client.client_id
            and client.client_id = cr.client_id
                and cr.departmentroom_id = dr.departmentroom_id
and cdl.product_link_id = prd.product_id
and cdl.sizedefinition_link_id = sz.sizedefinition_id
and cdl.finishingmethod_id = fm.finishingmethod_id
and uri.client_id <> cdn.client_link_id
/

  CREATE OR REPLACE VIEW "V_WEBCLEANROOMNOTSCANNED" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_ID", "PRIMARYID", "STATUS_CODE", "PRODUCT_CODE", "SIZE_CODE", "FIRSTISSUEDATE", "LASTSCANDATE", "LANGUAGECODE", "PRODUCT_DESC", "STAY_DESC", "REPLACEMENT_CHARGES") AS 
  select /*version 1.0*/
       cu.customernumber, cu.name customername, cu.customer_id, ui.primaryid, st.code status_code, pr.code product_code,
       sd.code size_code, uif.firstissuedate, ui.lastscandate, lan.code languagecode,
       (select pds.description from product_desc pds where pds.product_id = pr.product_id and pds.language_id = lan.language_id) product_desc,
       (select sy.factorydescription from stay sy where sy.stay_id = ui.stay_id) stay_desc,
       f_replacement_price(cu.customer_id, ui.product_id, ui.sizedefinition_id, ui.finishingmethod_id, sysdate) replacement_charges
  from uniqueitem ui
       join uniqueitemnonpool uinp on ui.uniqueitem_id = uinp.uniqueitem_id
       join uniqueitemfixedinfo uif on ui.uniqueitem_id = uif.uniqueitem_id
       join weareremployment wemp on uinp.weareremployment_id = wemp.weareremployment_id
       join distributionpoint dp on wemp.distributionpoint_id = dp.distributionpoint_id
       join department d on dp.department_id = d.department_id
       join customer cu on d.customer_id = cu.customer_id
       join product pr on ui.product_id = pr.product_id
       join sizedefinition sd on ui.sizedefinition_id = sd.sizedefinition_id
       join status st on ui.status_id = st.status_id
       , languages lan
where st.statustype = 'UI' and st.code = '20'
  and ui.poolitem = 2
/

  CREATE OR REPLACE VIEW "V_WEBCLEANROOMREPAIRS" ("REPAIRDATE", "QUANTITY", "PRIMARYID", "WASHESTOTAL", "SIZE_CODE", "PRODUCT_CODE", "REPAIRTYPE_CODE", "LANGUAGECODE", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_ID", "REPAIRTYPE_DESC") AS 
  select /*version 1.0 */
       rh.repairdate, rh.quantity, ui.primaryid, ui.washestotal, sd.code size_code, pr.code product_code, rt.code repairtype_code,
       lan.code languagecode, c.customernumber, c.name customername, c.customer_id,
       (select rtd.description
          from repairtype_desc rtd
         where rtd.repairtype_id = rt.repairtype_id
           and rtd.language_id = lan.language_id) repairtype_desc
  from repairhistory rh
       join uniqueitem ui
            join product pr on ui.product_id = pr.product_id
            join sizedefinition sd on ui.sizedefinition_id = sd.sizedefinition_id
       on rh.uniqueitem_link_id = ui.uniqueitem_id
       join customer c on rh.customer_link_id = c.customer_id
       join repairtype rt on rh.repairtype_id = rt.repairtype_id
       , languages lan
/

  CREATE OR REPLACE VIEW "V_WEBCLIENTDELIVERYNOTELABELS" ("CLIENTDELIVERYNOTE_ID", "PRICE", "QUANTITY", "FINISHINGMETHOD_ID") AS 
  select /*version 1.0*/
       p.clientdeliverynote_id, p.price, p.quantity, u.finishingmethod_id
  from printqueueresidentialitem p
       join uniqueresidentialitemproduct u on p.uniqueresidentialitem_link_id = u.uniqueresidentialitem_id
 where p.chargeable = 'Y'
/

  CREATE OR REPLACE VIEW "V_WEBCLIENTDELIVERYNOTESCHARGE" ("CLIENTDELIVERINOTE_ID", "LANGUAGECODE", "CODE", "DESCRIPTION", "QUANTITY", "PRICE", "PRICEONDELNOTE", "PRICEDECIMALS", "AMOUNTDECIMALS") AS 
  select /*version 2.0*/
       cdsc.clientdeliverinote_id, l.code languagecode,
  sc.code,
  (select sd.description from specialcharge_desc sd where sd.specialcharge_id = cdsc.specialcharge_id
     and l.language_id = sd.language_id) description,
  cdsc.quantity, cdsc.price, cdsc.priceondelnote,
  (select cu.decimals
     from currency cu
          join customer c
               join clientdeliverynote cdn
               on c.customer_id = cdn.customer_link_id
          on cu.currency_id = c.currency_id
    where cdn.clientdeliverynote_id = cdsc.clientdeliverinote_id) pricedecimals,
  (select cu.invoiceamountdecimals
     from currency cu
          join customer c
               join clientdeliverynote cdn
               on c.customer_id = cdn.customer_link_id
          on cu.currency_id = c.currency_id
    where cdn.clientdeliverynote_id = cdsc.clientdeliverinote_id) amountdecimals
from clientdeliverynotespeccharge cdsc, specialcharge sc, languages l
where cdsc.specialcharge_id = sc.specialcharge_id
-- ClientDeliveryNote.rpt
/

  CREATE OR REPLACE VIEW "V_WEBCLIENTDELIVERYNOTEVAT" ("CLIENTDELIVERINOTE_ID", "STARTDATETAXRATE", "CODE", "TAXDESC", "TAXPERCENTAGE", "TAXAMOUNT") AS 
  select cdt.clientdeliverinote_id, tg.startdatetaxrate,
  tg.code, tg.description taxdesc, cdt.taxpercentage, cdt.taxamount
from clientdeliverynotetax cdt, taxgroup tg
where cdt.taxgroup_id = tg.taxgroup_id
/

  CREATE OR REPLACE VIEW "V_WEBCLIENTDELIVERYNOTE_FLAG" ("PRINTIDCODE", "UNIQUERESIDENTIALITEM_LINK_ID", "SCANTIMESTAMP", "LANGUAGE_CODE", "FLAGCODE", "FLAGDESC") AS 
  select 'Y' printidcode, ris.uniqueresidentialitem_link_id, trunc(ris.scantimestamp) scantimestamp, languages.code Language_code, flag.code flagCode,
(select flag_desc.description from flag_desc where flag.flag_id = flag_desc.flag_id and flag_desc.language_id = languages.language_id) flagDesc
from flag, residentialitemscan ris, residentialitemscanflag risf, languages
where risf.flag_id = flag.flag_id and ris.residentialitemscan_id = risf.residentialitemscan_id
and ris.transactiontype_id = 2 AND flag.showonwashlist = 'Y'
--and cds.uniqueresidentialitem_link_id = ris.uniqueresidentialitem_link_id
--and trunc(cds.outscantimestamp) = trunc(ris.scantimestamp)
--union all select 'N' printidcode, null, null, null, null, null from dual
/

  CREATE OR REPLACE VIEW "V_WEBCONSUMPOINTBARCODELABELS" ("CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DEPARTMENT_ID", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "DISTRIBUTIONPOINT_ID") AS 
  select cu.customer_id, cu.customernumber, cu.name customername
, de.departmentnumber, de.description departmentdesc, de.department_id
, dp.distributionpointnumber, dp.description distributionpointdesc, dp.distributionpoint_id
from customer cu, department de, distributionpoint dp
where dp.department_id = de.department_id and de.customer_id = cu.customer_id
      and de.active = 'Y' and dp.active = 'Y'
/

  CREATE OR REPLACE VIEW "V_WEBDELAMOUNTSANDCOSTS" ("WEBSESSION_ID", "WEBUSER_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINT_ID", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "COSTCENTER_ID", "COSTCENTER_CODE", "COSTCENTER_DESC", "ACTIVITY_ID", "ACTIVITY_CODE", "ACTIVITY_ACTIVE", "PRODUCTGROUP_ID", "PRODUCTGROUP_CODE", "PRODUCT_ID", "PRODUCT_CODE", "SIZEDEFINITION_ID", "SIZE_CODE", "FINISHINGMETHOD_ID", "FINISHING_CODE", "ACTIVITY_DESC", "PRODUCTGROUP_DESC", "PRODUCT_DESC", "SIZE_DESC", "FINISHING_DESC", "SIZESEQUENCENR", "WASH_PRICE", "DELIVERYDATE", "NOTENUMBER", "DELIVEREDAMOUNT", "PRICE", "DELIVEREDCOGQTY", "YEARMONTH", "CURRENCYCODE", "CURRENCYDESC", "LANGUAGE_CODE", "PRODUCTDESCRIPTIONONLY") AS 
  select cast(wus.websession_id as varchar2(50)) websession_id, wuc.webuser_id,
cu.customer_id, cu.customernumber, cu.name customername, de.department_id, de.departmentnumber, de.description departmentdesc,
dp.distributionpoint_id, dp.distributionpointnumber, dp.description distributionpointdesc,
cc.costcenter_id, cc.code CostCenter_code, cc.description CostCenter_desc,
ac.activity_id, ac.code activity_code, ac.active activity_active, pg.productgroup_id, pg.code productgroup_code,
pr.product_id, pr.code product_code, sd.sizedefinition_id, sd.code size_code, fm.finishingmethod_id, fm.code finishing_code,
(select acd.description from activity_desc acd where acd.activity_id = ac.activity_id and acd.language_id = lan.language_id) activity_desc,
(select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pg.productgroup_id and pgd.language_id = lan.language_id) productgroup_desc,
(select pd.description from product_desc pd where pd.product_id = pr.product_id and pd.language_id = lan.language_id) product_desc,
(select sdd.description from SizeDefinition_desc sdd where sdd.sizedefinition_id = sd.sizedefinition_id and sdd.language_id = lan.language_id) size_desc,
(select fmd.description from FinishingMethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id and fmd.language_id = lan.language_id) finishing_desc,
(select ps.sequencenumber from productsize ps where ps.product_id = pr.product_id and ps.sizedefinition_id = sd.sizedefinition_id) SizeSequenceNr,
PACK_PRICE.Wash_Price(cu.customer_id, pr.product_id, sd.sizedefinition_id, fm.finishingmethod_id, pn.deliverydate) Wash_Price,
pn.deliverydate, pn.notenumber, pnl.deliveredamount, pnl.price, pnl.deliveredcogqty, year(pn.deliverydate)*100+month(pn.deliverydate) YearMonth,
cy.code CurrencyCode, cy.description CurrencyDesc, lan.code Language_Code, wu.productdescriptiononly
from PackingNote PN, PackingNoteLine PNL, DistributionPoint DP, Department DE, Customer CU, CostCENTER CC,
  Activity AC, ProductGroup PG, Product PR, SizeDefinition SD, FinishingMethod FM, Currency CY, languages lan,
  webusercustomer wuc,--left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  webusersession wus, webuser wu
where pn.distributionpoint_id = dp.distributionpoint_id
  and dp.department_id = de.department_id
  and de.customer_id = cu.customer_id
  and dp.costcenter_id = cc.costcenter_id
  and cc.customer_id = cu.customer_id
  and pnl.packingnote_id = pn.packingnote_id
  and pnl.product_id = pr.product_id
  and pr.productgroup_id = pg.productgroup_id
  and pg.activity_id = ac.activity_id
  and pnl.sizedefinition_id = sd.sizedefinition_id
  and pnl.finishingmethod_id = fm.finishingmethod_id
  and cy.currency_id = cu.currency_id
  and pn.freeofchargereason_id is null
  and pn.status_id =(select s.status_id from status s where s.statustype='PN' and s.code='30')
  and wuc.customer_id = cu.customer_id
  and wu.webuser_id = wus.webuser_id
  and wuc.webuser_id = wu.webuser_id
  and (NOT EXISTS (SELECT 1 FROM WEBUSERDEPARTMENT WDEP, WEBUSERCUSTOMER WCUST
                   WHERE WCUST.WEBUSER_ID = WU.WEBUSER_ID
                         AND WDEP.WEBUSERCUSTOMER_ID = WCUST.WEBUSERCUSTOMER_ID
                         AND WCUST.CUSTOMER_ID = Cu.CUSTOMER_ID)
       OR
       EXISTS (SELECT 1 FROM WEBUSERDEPARTMENT WDEP, WEBUSERCUSTOMER WCUST
               WHERE WDEP.DEPARTMENT_ID = DE.DEPARTMENT_ID
                     AND WCUST.WEBUSER_ID = WU.WEBUSER_ID
                     AND WCUST.CUSTOMER_ID = Cu.CUSTOMER_ID
                     AND WDEP.WEBUSERCUSTOMER_ID = WCUST.WEBUSERCUSTOMER_ID)
       )
/

  CREATE OR REPLACE VIEW "V_WEBDELIVEREDPRODUCTS" ("REPORTPARAM_ID", "WEBSESSION_ID", "WEBUSER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_LINK_ID", "LANGUAGECODE", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "CC_CODE", "CC_DESCR", "COSTCENTER_ID", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "DELIVERYPOINT_ID", "PRODUCTGROUP_ID", "PRODUCTGROUPCODE", "PRODUCT_ID", "PRODUCTCODE", "ACTIVITY_ID", "THEORETICALWEIGHT", "TYPEOFMERCHANDISE", "PACKINDICATION", "PRODSIZE_THEORETICALWEIGHT", "SIZECODE", "FINISHINGMETHODCODE", "DELIVERYDATE", "AMOUNTDELIVERED", "CUSTOMERLANGUAGECODE", "PRODUCTGROUPDESCRIPTION", "PRODUCTDESCRIPTION", "SIZEDESCRIPTION", "FINISHINGMETHODDESCRIPTION") AS 
  select /*version 2.0*/
       rp.reportparam_id, wus.websession_id, wc.webuser_id, cu_link.customernumber, cu_link.name customername, cu_link.customer_link_id, lan.code languagecode,
       dep_link.department_link_id department_id, dep_link.departmentnumber, dep_link.description departmentdescription, cc.code cc_code,
       cc.description cc_descr, cc.costcenter_id, dist_link.distributionpointnumber, dist_link.description distributionpointdescription,
       del_link.deliverypoint_id, prg.productgroup_id, prg.code productgroupcode, pr_link.product_link_id product_id, pr_link.code productcode,
       prg.activity_id, pr.theoreticalweight, pr.typeofmerchandise, dh.packindication, prsz.theoreticalweight prodsize_theoreticalweight,
       sd_link.code sizecode, fm.code finishingmethodcode, dh.deliverydate, dh.amountdelivered, cu_link.languagecode customerlanguagecode,
       (select prg_desc.description
          from productgroup_desc prg_desc
         where prg_desc.productgroup_id = prg.productgroup_id
           and prg_desc.language_id = lan.language_id) productgroupdescription,
       (select prd_link.description
          from product_link_desc prd_link
         where prd_link.product_link_id = dh.product_link_id
           and prd_link.language_id = lan.language_id) productdescription,
       (select szd.description
          from sizedefinition_link_desc szd
         where szd.sizedefinition_link_id = dh.sizedefinition_link_id
           and szd.language_id = lan.language_id) sizedescription,
       (select fmd.description
          from finishingmethod_desc fmd
         where fmd.finishingmethod_id = dh.finishingmethod_id
           and fmd.language_id = lan.language_id) finishingmethoddescription
 from deliveryhistory dh
      join customer_link cu_link on dh.customer_link_id = cu_link.customer_link_id
      join department_link dep_link on cu_link.customer_link_id = dep_link.customer_link_id
      join distributionpoint_link dist_link on dh.distributionpoint_link_id = dist_link.distributionpoint_link_id and dist_link.department_link_id = dep_link.department_link_id
           left join distributionpoint dp
                join deliverypoint_link del_link on dp.deliverypoint_id = del_link.deliverypoint_link_id
           on dist_link.distributionpoint_id = dp.distributionpoint_id
      join costcenter cc on coalesce(dp.costcenter_id,(select d.costcenter_id from department d where d.department_id = dep_link.department_link_id))=cc.costcenter_id
      join sizedefinition_link sd_link  on dh.sizedefinition_link_id = sd_link.sizedefinition_link_id
           left join sizedefinition sd on sd_link.sizedefinition_id = sd.sizedefinition_id
      join finishingmethod fm on dh.finishingmethod_id = fm.finishingmethod_id
      join product_link pr_link on dh.product_link_id = pr_link.product_link_id
           left join product pr
                join productgroup prg on pr.productgroup_id = prg.productgroup_id
           on pr_link.product_id = pr.product_id
      join productsize prsz on pr.product_id = prsz.product_id and sd.sizedefinition_id = prsz.sizedefinition_id
      join webusercustomer wc on cu_link.customer_link_id = wc.customer_id
      join webuser wu on wc.webuser_id = wu.webuser_id
      join webusersession wus on wu.webuser_id = wus.webuser_id
      , reportparam rp, languages lan
where (not exists (select 1 from webuserdepartment wdep, webusercustomer wcust
                   where wcust.webuser_id = wu.webuser_id
                         and wdep.webusercustomer_id = wcust.webusercustomer_id
                         and wcust.customer_id = cu_link.customer_link_id)
       or
       exists (select 1 from webuserdepartment wdep, webusercustomer wcust
               where wdep.department_id = dep_link.department_link_id
                     and wcust.webuser_id = wu.webuser_id
                     and wcust.customer_id = dep_link.customer_link_id
                     and wdep.webusercustomer_id = wcust.webusercustomer_id)
       )
/

  CREATE OR REPLACE VIEW "V_WEBDELIVERYHISTORY" ("CUSTOMER_ID", "PACK", "PACKINDICATION", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEBUSERDEPARTMENT_ID", "DEPARTMENT_LINK_ID", "DELIVERYPOINT_ID", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINT_ID", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "PRODUCTGROUPCODE", "PRODUCTGROUPDESCRIPTION", "PRODUCTCODE", "PRODUCTDESCRIPTION", "ACTIVITYCODE", "THEORETICALWEIGHT", "TYPEOFMERCHANDISE", "PRODSIZE_THEORETICALWEIGHT", "SIZECODE", "SIZEDESCRIPTION", "DELIVERYDATE", "YEARWEEK", "WEEK", "YEAR", "REALMONTH", "REALYEAR", "DAYNUMBER", "AMOUNTORDERED", "AMOUNTDELIVERED", "AMOUNTSHORTAGE", "PRICE", "INTERNALPRICE", "DISCOUNT", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE", "COSTCENTER_ID", "ACTIVITY_ID", "PRODUCTGROUP_ID", "PRODUCT_ID", "WEBSESSION_ID", "WEBUSER_ID") AS 
  SELECT CUSTOMER_LINK.CUSTOMER_ID,product.pack,DELIVERYHISTORY.PACKINDICATION,
       CUSTOMER_LINK.CUSTOMERNUMBER, CUSTOMER_LINK.NAME customername,WD.DEPARTMENT_ID WEBUSERDEPARTMENT_ID,DEPARTMENT_LINK.DEPARTMENT_LINK_ID, DELIVERYPOINT.DELIVERYPOINT_ID,
       DEPARTMENT_LINK.DEPARTMENT_ID, DEPARTMENT_LINK.DEPARTMENTNUMBER, DEPARTMENT_LINK.DESCRIPTION departmentdescription,
       distributionpoint.distributionpoint_id, DISTRIBUTIONPOINT_LINK.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT_LINK.DESCRIPTION distributionpointdescription,
       PRODUCTGROUP.CODE productgroupcode,
       (SELECT pdd.DESCRIPTION FROM PRODUCTGROUP_DESC pdd WHERE pdd.PRODUCTGROUP_ID = PRODUCTGROUP.PRODUCTGROUP_ID
                AND pdd.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productgroupdescription,
       PRODUCT_LINK.CODE productcode,
       (SELECT B.DESCRIPTION FROM PRODUCT_LINK_DESC B WHERE B.PRODUCT_LINK_ID = DELIVERYHISTORY.PRODUCT_LINK_ID AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
       (SELECT F.CODE FROM ACTIVITY F WHERE F.ACTIVITY_ID = PRODUCTGROUP.ACTIVITY_ID) ACTIVITYCODE,
       PRODUCT.THEORETICALWEIGHT, PRODUCT.typeofmerchandise,
       PRODUCTSIZE.THEORETICALWEIGHT PRODSIZE_THEORETICALWEIGHT,
       SIZEDEFINITION_LINK.CODE sizecode,
       (SELECT C.DESCRIPTION FROM SIZEDEFINITION_LINK_DESC C WHERE C.SIZEDEFINITION_LINK_ID = DELIVERYHISTORY.SIZEDEFINITION_LINK_ID AND C.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEdescription,
       DELIVERYHISTORY.DELIVERYDATE, DELIVERYHISTORY.year*100 + DELIVERYHISTORY.week YEARWEEK,
       DELIVERYHISTORY.WEEK, DELIVERYHISTORY.YEAR,
       month(DELIVERYHISTORY.deliverydate) realmonth,
       year(DELIVERYHISTORY.deliverydate) realyear,
       DELIVERYHISTORY.DAYNUMBER,
       DELIVERYHISTORY.AMOUNTORDERED, DELIVERYHISTORY.AMOUNTDELIVERED,
       DELIVERYHISTORY.AMOUNTSHORTAGE, DELIVERYHISTORY.PRICE,
       DELIVERYHISTORY.INTERNALPRICE, DELIVERYHISTORY.DISCOUNT,
       DELIVERYHISTORY.SYSTEMUSER_ID, DELIVERYHISTORY.TIMESTAMP,
       LANGUAGES.CODE LANGUAGECODE,
       CCL.COSTCENTER_ID,
       CA.ACTIVITY_ID,
       PRODUCTGROUP.PRODUCTGROUP_ID,
       PRODUCT.PRODUCT_ID,
       wus.websession_id,
       wuc.webuser_id
 FROM DELIVERYHISTORY
        LEFT OUTER JOIN PRODUCT ON (DELIVERYHISTORY.PRODUCT_LINK_ID = PRODUCT.PRODUCT_ID)
        LEFT OUTER JOIN SIZEDEFINITION ON (DELIVERYHISTORY.SIZEDEFINITION_LINK_ID = SIZEDEFINITION.SIZEDEFINITION_ID),
      PRODUCTSIZE,
      SIZEDEFINITION_LINK,
      CUSTOMER_LINK,
      DEPARTMENT_LINK,
       webusercustomer wuc left outer join webuserdepartment wd on (wuc.webusercustomer_id=wd.webusercustomer_id),
     -- left outer join webuserdepartment wd on department_link.department_id = wd.department_id,
      DISTRIBUTIONPOINT_LINK,
      DISTRIBUTIONPOINT,
      DELIVERYPOINT,
       LANGUAGES,
       PRODUCT_LINK
      LEFT OUTER JOIN PRODUCTGROUP ON (PRODUCT_LINK.PRODUCTGROUPCODE = PRODUCTGROUP.CODE),
      PRODUCT_LINK parentproduct,
      COSTCENTER_LINK CCL,
      CUSTOMERACTIVITIES CA,
      ACTIVITY A,
      webuser wu,
      WEBUSERSESSION WUS
    --  WEBUSERCUSTOMER WUC
 WHERE DELIVERYHISTORY.DISTRIBUTIONPOINT_LINK_ID = DISTRIBUTIONPOINT_LINK.DISTRIBUTIONPOINT_LINK_ID
   AND DISTRIBUTIONPOINT_LINK.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
  AND DISTRIBUTIONPOINT.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT_LINK.DEPARTMENT_ID
  AND DEPARTMENT_LINK.CUSTOMER_LINK_ID = CUSTOMER_LINK.CUSTOMER_LINK_ID
  AND DELIVERYHISTORY.PRODUCT_LINK_ID = PRODUCT_LINK.PRODUCT_LINK_ID
  AND DELIVERYHISTORY.PARENTPRODUCT_LINK_ID = parentproduct.PRODUCT_LINK_ID
  AND DELIVERYHISTORY.SIZEDEFINITION_LINK_ID = SIZEDEFINITION_LINK.SIZEDEFINITION_LINK_ID
  AND PRODUCTSIZE.PRODUCT_ID = PRODUCT.PRODUCT_ID
  AND PRODUCTSIZE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
  and DISTRIBUTIONPOINT.Costcenter_Id = ccl.costcenter_id
  and ccl.customer_link_id = customer_link.customer_link_id
  AND CUSTOMER_LINK.CUSTOMER_ID = CA.CUSTOMER_ID AND CA.ACTIVITY_ID = A.ACTIVITY_ID
  AND A.ACTIVE = 'Y'
  and a.activity_id = PRODUCTGROUP.Activity_Id
  AND WU.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID
  AND WU.WEBUSER_ID = WUC.WEBUSER_ID
  AND WUC.CUSTOMER_ID = CUSTOMER_LINK.CUSTOMER_ID
  AND WUS.CUSTOMER_ID = WUC.CUSTOMER_ID
  AND PRODUCT.Model = 'N'
/

  CREATE OR REPLACE VIEW "V_WEBDELQTYPERDAY" ("WEBSESSION_ID", "WEBUSER_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINT_ID", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "COSTCENTER_ID", "COSTCENTER_CODE", "COSTCENTER_DESC", "ACTIVITY_ID", "ACTIVITY_CODE", "ACTIVITY_ACTIVE", "PRODUCTGROUP_ID", "PRODUCTGROUP_CODE", "PRODUCT_ID", "PRODUCT_CODE", "SIZEDEFINITION_ID", "SIZE_CODE", "FINISHINGMETHOD_ID", "FINISHING_CODE", "ACTIVITY_DESC", "PRODUCTGROUP_DESC", "PRODUCT_DESC", "SIZE_DESC", "FINISHING_DESC", "DELIVERYDATE", "NOTENUMBER", "DELIVEREDAMOUNT", "PRODUCTDESCRIPTIONONLY", "LANGUAGE_CODE") AS 
  select cast(wus.websession_id as varchar2(50)) websession_id, wuc.webuser_id,
cu.customer_id, cu.customernumber, cu.name customername, de.department_id, de.departmentnumber, de.description departmentdesc,
dp.distributionpoint_id, dp.distributionpointnumber, dp.description distributionpointdesc, cc.costcenter_id, cc.code costcenter_code, cc.description costcenter_desc,
ac.activity_id, ac.code activity_code, ac.active activity_active, pg.productgroup_id, pg.code productgroup_code,
pr.product_id, pr.code product_code, sd.sizedefinition_id, sd.code size_code, fm.finishingmethod_id, fm.code finishing_code,
(select acd.description from activity_desc acd where acd.activity_id = ac.activity_id and acd.language_id = lan.language_id) activity_desc,
(select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pg.productgroup_id and pgd.language_id = lan.language_id) productgroup_desc,
(select pd.description from product_desc pd where pd.product_id = pr.product_id and pd.language_id = lan.language_id) product_desc,
(select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sd.sizedefinition_id and sdd.language_id = lan.language_id) size_desc,
(select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id and fmd.language_id = lan.language_id) finishing_desc,
pn.deliverydate, pn.notenumber, sum(pnl.deliveredamount) deliveredamount, wu.productdescriptiononly, lan.code language_code
from packingnote pn
         join packingnoteline pnl on pnl.packingnote_id = pn.packingnote_id
         join distributionpoint dp on pn.distributionpoint_id = dp.distributionpoint_id
         join department de on dp.department_id = de.department_id
         join customer cu on de.customer_id = cu.customer_id
         join costcenter cc on dp.costcenter_id = cc.costcenter_id
         join product pr on pnl.product_id = pr.product_id
         join productgroup pg on pr.productgroup_id = pg.productgroup_id
         join activity ac on pg.activity_id = ac.activity_id
         join sizedefinition sd on pnl.sizedefinition_id = sd.sizedefinition_id
         join finishingmethod fm on pnl.finishingmethod_id = fm.finishingmethod_id
         join webusercustomer wuc on wuc.customer_id = cu.customer_id
         join webuser wu on wuc.webuser_id = wu.webuser_id
         join webusersession wus on wu.webuser_id = wus.webuser_id
         join status st on st.status_id = pn.status_id,
      languages lan
where pn.freeofchargereason_id is null
  and pnl.deliveredamount <> 0
  and (not exists (select 1 from webuserdepartment wdep, webusercustomer wcust
                   where wcust.webuser_id = wu.webuser_id
                         and wdep.webusercustomer_id = wcust.webusercustomer_id
                         and wcust.customer_id = cu.customer_id)
       or
       exists (select 1 from webuserdepartment wdep, webusercustomer wcust
               where wdep.department_id = de.department_id
                     and wcust.webuser_id = wu.webuser_id
                     and wcust.customer_id = cu.customer_id
                     and wdep.webusercustomer_id = wcust.webusercustomer_id)
       )
   and (st.statustype = 'PN' and st.code <> 40)
group by wus.websession_id, wuc.webuser_id,
cu.customer_id, cu.customernumber, cu.name, de.department_id, de.departmentnumber, de.description,
dp.distributionpoint_id, dp.distributionpointnumber, dp.description,
cc.costcenter_id, cc.code, cc.description,
ac.activity_id, ac.code, ac.active, pg.productgroup_id, pg.code,
pr.product_id, pr.code, sd.sizedefinition_id, sd.code, fm.finishingmethod_id, fm.code, lan.language_id,
pn.deliverydate, pn.notenumber, wu.productdescriptiononly, lan.code
/

  CREATE OR REPLACE VIEW "V_WEBGARMENTSPERWEARER" ("PRODUCTDESCRIPTIONONLY", "SHOWGARMENTISSUEDATE", "SHOWGARMENTWASHESTOTAL", "SHOWGARMENTWASHESISSUE", "SHOWGARMENTREPAIRSTOTAL", "SHOWGARMENTREPAIRSISSUE", "SHOWGARMENTREWASHESTOTAL", "SHOWGARMENTREWASHESISSUE", "UNIQUEITEM_ID", "WEBSESSION_ID", "WEBUSER_ID", "DEPARTMENT_ID", "PRODUCTCODE", "PRODUCTDESC", "FUNCTIONCODE", "FUNCTIONDESC", "EMPLOYMENT", "SIZECODE", "BANKLOCKER", "GARMENTDISPENSER", "IDCODE", "SEQNUMBER", "ISSUEDATE", "WASHNO", "WASHNONONPOOL", "REPAIRNO", "REPAIRNONONPOOL", "REWASHNO", "REWASHNONONPOOL", "MODIFICATIONS", "REASON", "CUSTOMEROWNED", "LASTSCANDATE", "LASTOUTSCANDATE", "RESIDUALVALUE", "ADMINNUMBER", "COSTCENTERCODE", "COSTCENTERDESC", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CITY", "WEARERNUMBER", "WEARERNAME", "WEARERSEARCHNAME", "WEARERACTIVE", "WEARERDATEACTIVE", "WEARERDATEINACTIVE", "LANGUAGECODE", "LANGUAGE_ID", "DELIVERYPOINT_ID_W", "WEARERFUNCTION_ID", "PRODUCT_ID", "COSTCENTER_ID", "WEARER_ID") AS 
  select /*version 3.1*/
       case
         when (select sy.value
                 from systemsetting sy
                where sy.plant_id = wu.plant_id
                  and sy.name = 'NEWWEBAPPLICATION') = 'N'
         then (select s.value
                 from systemsetting s
                where s.plant_id = wu.plant_id
                  and s.name = 'SHOWLONGPRODUCTDESC')
       else wu.productdescriptiononly end productdescriptiononly, wu.showgarmentissuedate,
       wu.showgarmentwashestotal, wu.showgarmentwashesissue, wu.showgarmentrepairstotal,
       wu.showgarmentrepairsissue, wu.showgarmentrewashestotal, wu.showgarmentrewashesissue,
       ui.uniqueitem_id, wus.websession_id, wc.webuser_id, de.department_id,
       rightpad(coalesce((select max(p.customcode)
                            from productlistpercustomer p
                           where p.customer_id = cu.customer_id
                             and p.product_id = ui.product_id
                             and p.sizedefinition_id = ui.sizedefinition_id
                             and p.finishingmethod_id = ui.finishingmethod_id),
                         (select max(p.customcode)
                            from productlistpercustomer p
                           where p.customer_id = cu.customer_id
                             and p.product_id = ui.product_id
                             and p.sizedefinition_id = (select sd.sizedefinition_id
                                                          from sizedefinition sd
                                                         where sd.code = '*')
                             and p.finishingmethod_id = ui.finishingmethod_id),
                         prd.code), 12, ' ') productcode,
       rightpad(coalesce((select max(p.customdescription)
                            from productlistpercustomer p
                           where p.customer_id = cu.customer_id
                             and p.product_id = ui.product_id
                             and p.sizedefinition_id = ui.sizedefinition_id
                             and p.finishingmethod_id = ui.finishingmethod_id),
                         (select max(p.customdescription)
                            from productlistpercustomer p
                           where p.customer_id = cu.customer_id
                             and p.product_id = ui.product_id
                             and p.sizedefinition_id = (select sd.sizedefinition_id
                                                          from sizedefinition sd
                                                         where sd.code = '*')
                             and p.finishingmethod_id = ui.finishingmethod_id),
                         (select pd.description
                            from product_desc pd
                           where pd.language_id = lan.language_id
                             and pd.product_id = ui.product_id)), 30, ' ') productdesc,
       wf.code functioncode, wf.description functiondesc, wey.sequencenumber employment,
       sz.code sizecode, concatenatewithblank(lk.bank, lk.locker) banklocker, gd.code garmentdispenser,
       ui.primaryid idcode, ui.idcodesequencenumber seqnumber, uifi.lastissuedate issuedate,
       ui.washestotal washno, uinp.washesthisissue washnononpool, ui.repairstotal repairno,
       uinp.repairsthisissue repairnononpool, ui.rewashtotal rewashno, uinp.rewashthisissue rewashnononpool,
       (select count(1)
          from uniqueitemmodification um
               join modification md on um.modification_id = md.modification_id
         where um.uniqueitem_id = ui.uniqueitem_id
           and md.useinwebapplication = 'Y') modifications,
       (select rsd.description
          from reasoncode_desc rsd
         where rsd.reasoncode_id = r.reasoncode_id
           and rsd.language_id = lan.language_id) reason, ui.customerowned,
       trunc(ui.lastscandate) lastscandate, trunc(ui.lastoutscandate) lastoutscandate,
       ui.residualvalueamount residualvalue, we.customeremployeenumber adminnumber,
       cc.code costcentercode, cc.description costcenterdesc, de.departmentnumber,
       de.description departmentdesc, cu.customer_id, cu.customernumber, cu.name customername,
       address.city, we.wearernumber, we.fullname wearername, we.searchname wearersearchname,
       getdatediff(trunc(sysdate), we.dateactive) * getdatediff(we.dateinactive, trunc(sysdate)) weareractive,
       we.dateactive wearerdateactive, we.dateinactive wearerdateinactive,
       lan.code languagecode, lan.language_id, wey.deliverypoint_id deliverypoint_id_w,
       wf.wearerfunction_id, ui.product_id, cc.costcenter_id, we.wearer_id
  from weareremployment wey
       left join garmentdispenser gd on wey.garmentdispenser_id = gd.garmentdispenser_id
       left join wearerfunction wf on wey.wearerfunction_id = wf.wearerfunction_id
       left join locker lk on wey.locker_id = lk.locker_id
       join wearer we
            left join flag on we.flag_id = flag.flag_id and flag.useinwebapplication = 'Y'
            join customer cu
                 join address on cu.mailaddress_id = address.address_id
                 join currency on cu.currency_id = currency.currency_id
            on we.customer_id = cu.customer_id
            join webusercustomer wc
                 join webuser wu on wc.webuser_id = wu.webuser_id
                 join webusersession wus on wc.webuser_id = wus.webuser_id
            on we.customer_id = wc.customer_id
       on wey.wearer_id = we.wearer_id
       join uniqueitemnonpool uinp
            join uniqueitem ui
                 left join finishingmethod fm on ui.finishingmethod_id = fm.finishingmethod_id
                 join uniqueitemfixedinfo uifi
                      join reasoncode r on uifi.reasoncode_id = r.reasoncode_id
                 on ui.uniqueitem_id = uifi.uniqueitem_id
                 join product prd on ui.product_id = prd.product_id
                 join sizedefinition sz on ui.sizedefinition_id = sz.sizedefinition_id
            on uinp.uniqueitem_id = ui.uniqueitem_id
       on wey.weareremployment_id = uinp.weareremployment_id
       join distributionpoint dip
            join department de on dip.department_id = de.department_id
            join costcenter cc on dip.costcenter_id = cc.costcenter_id
       on wey.distributionpoint_id = dip.distributionpoint_id
       cross join languages lan
 where (not exists
        (select 1
           from webuserdepartment wdep
           join webusercustomer wcust on wdep.webusercustomer_id = wcust.webusercustomer_id
          where wcust.webuser_id = wu.webuser_id
            and wcust.customer_id = cu.customer_id)
        or exists
        (select 1
           from webuserdepartment wdep
           join webusercustomer wcust on wdep.webusercustomer_id = wcust.webusercustomer_id
          where wdep.department_id = de.department_id
            and wcust.webuser_id = wu.webuser_id
            and wcust.customer_id = de.customer_id))
 union all
select case
          when (select sy.value
                  from systemsetting sy
                 where sy.plant_id = wu.plant_id
                   and sy.name = 'NEWWEBAPPLICATION') = 'N'
          then (select s.value
                  from systemsetting s
                 where s.plant_id = wu.plant_id
                   and s.name = 'SHOWLONGPRODUCTDESC')
       else wu.productdescriptiononly end productdescriptiononly, wu.showgarmentissuedate,
       wu.showgarmentwashestotal, wu.showgarmentwashesissue, wu.showgarmentrepairstotal,
       wu.showgarmentrepairsissue, wu.showgarmentrewashestotal, wu.showgarmentrewashesissue,
       0 uniqueitem_id, wus.websession_id, wc.webuser_id, de.department_id,
       rightpad(coalesce((select max(p.customcode)
                            from productlistpercustomer p
                           where p.customer_id = we.customer_id
                             and p.product_id = wi.product_id
                             and p.sizedefinition_id = wi.sizedefinition_id
                             and p.finishingmethod_id = wi.finishingmethod_id),
                         (select max(p.customcode)
                            from productlistpercustomer p
                           where p.customer_id = we.customer_id
                             and p.product_id = wi.product_id
                             and p.sizedefinition_id = (select sd.sizedefinition_id
                                                          from sizedefinition sd
                                                         where sd.code = '*')
                             and p.finishingmethod_id = wi.finishingmethod_id),
                         prd.code), 12, ' ') productcode,
       rightpad(coalesce((select max(p.customdescription)
                            from productlistpercustomer p
                           where p.customer_id = we.customer_id
                             and p.product_id = wi.product_id
                             and p.sizedefinition_id = wi.sizedefinition_id
                             and p.finishingmethod_id = wi.finishingmethod_id),
                         (select max(p.customdescription)
                            from productlistpercustomer p
                           where p.customer_id = we.customer_id
                             and p.product_id = wi.product_id
                             and p.sizedefinition_id = (select sd.sizedefinition_id
                                                          from sizedefinition sd
                                                         where sd.code = '*')
                             and p.finishingmethod_id = wi.finishingmethod_id),
                         (select pd.description
                            from product_desc pd
                           where pd.language_id = languages.language_id
                             and pd.product_id = wi.product_id)), 30, ' ') productdesc,
       wf.code functioncode, wf.description functiondesc, wey.sequencenumber employment,
       sz.code sizecode, concatenatewithblank(lk.bank, lk.locker) banklocker,
       gd.code garmentdispenser, null idcode, nonui.sequencenumber seqnumber,
       nonui.issuedate issuedate, null washno, null washnononpool, null repairno,
       null repairnononpool, null rewashno, null rewashnononpool,
       (select count(1)
          from wearerinventorymodification wim
               join modification md on wim.modification_id = md.modification_id
         where wim.wearerinventory_id = wi.wearerinventory_id
           and md.useinwebapplication = 'Y') modifications,
       rc.code reason, 'N' customerowned, null lastscandate, null lastoutscandate, -1 residualvalue,
       we.customeremployeenumber adminnumber, cc.code costcentercode, cc.description costcenterdesc,
       de.departmentnumber, de.description departmentdesc, cu.customer_id, cu.customernumber,
       cu.name customername, address.city, we.wearernumber, we.fullname wearername, we.searchname wearersearchname,
       getdatediff(trunc(sysdate), we.dateactive) * getdatediff(we.dateinactive, trunc(sysdate)) weareractive,
       we.dateactive wearerdateactive, we.dateinactive wearerdateinactive,
       languages.code languagecode, languages.language_id, wey.deliverypoint_id deliverypoint_id_w,
       wf.wearerfunction_id, prd.product_id, cc.costcenter_id, we.wearer_id
  from weareremployment wey
       left join garmentdispenser gd on wey.garmentdispenser_id = gd.garmentdispenser_id
       left join wearerfunction wf on wey.wearerfunction_id = wf.wearerfunction_id
       left join locker lk on wey.locker_id = lk.locker_id
       join wearer we
            left join flag on we.flag_id = flag.flag_id and flag.useinwebapplication = 'Y'
            join customer cu
                 join address on cu.mailaddress_id = address.address_id
                 join currency on cu.currency_id = currency.currency_id
            on we.customer_id = cu.customer_id
            join webusercustomer wc
                 join webuser wu on wc.webuser_id = wu.webuser_id
                 join webusersession wus on wc.webuser_id = wus.webuser_id
            on we.customer_id = wc.customer_id
       on wey.wearer_id = we.wearer_id
       join wearerinventory wi
            join nonuniqueitem nonui
                 join reasoncode rc on nonui.reasoncode_id = rc.reasoncode_id
            on wi.wearerinventory_id = nonui.wearerinventory_id
            join product prd on wi.product_id = prd.product_id
            join sizedefinition sz on wi.sizedefinition_id = sz.sizedefinition_id
            join finishingmethod fm on wi.finishingmethod_id = fm.finishingmethod_id
       on wey.weareremployment_id = wi.weareremployment_id
       join distributionpoint dip
            join department de on dip.department_id = de.department_id
            join costcenter cc on dip.costcenter_id = cc.costcenter_id
       on wey.distributionpoint_id = dip.distributionpoint_id
       cross join languages
 where (not exists
        (select 1
           from webuserdepartment wdep
                join webusercustomer wcust on wdep.webusercustomer_id = wcust.webusercustomer_id
          where wcust.webuser_id = wu.webuser_id
            and wcust.customer_id = cu.customer_id)
        or exists
        (select 1
           from webuserdepartment wdep
                join webusercustomer wcust on wdep.webusercustomer_id = wcust.webusercustomer_id
          where wdep.department_id = de.department_id
            and wcust.webuser_id = wu.webuser_id
            and wcust.customer_id = de.customer_id))
/

  CREATE OR REPLACE VIEW "V_WEBGARMENTSPERWEARER_FLAG" ("UNIQUEITEM_ID", "CODE", "FLAG_DESC", "LANGUAGE_ID") AS 
  select /*version 2.0*/
       uf.uniqueitem_id, fg.code,
       (select fgd.description
         from flag_desc fgd
        where fg.flag_id = fgd.flag_id
         and fgd.language_id = l.language_id) flag_desc, l.language_id
 from uniqueitemflag uf
      join flag fg on uf.flag_id = fg.flag_id
 cross join languages l
 where fg.useinwebapplication = 'Y'
   and trunc(uf.startdate) <= trunc(sysdate)
/

  CREATE OR REPLACE VIEW "V_WEBGARMENTSWEARER_OLDWEBAPP" ("PRODUCTDESCRIPTIONONLY", "SHOWGARMENTISSUEDATE", "SHOWGARMENTWASHESTOTAL", "SHOWGARMENTWASHESISSUE", "SHOWGARMENTREPAIRSTOTAL", "SHOWGARMENTREPAIRSISSUE", "SHOWGARMENTREWASHESTOTAL", "SHOWGARMENTREWASHESISSUE", "UNIQUEITEM_ID", "WEBSESSION_ID", "WEBUSER_ID", "WEBUSERDEPARTMENT_ID", "DEPARTMENT_ID", "PRODUCTCODE", "PRODUCTDESC", "FUNCTIONCODE", "FUNCTIONDESC", "EMPLOYMENT", "SIZECODE", "BANKLOCKER", "GARMENTDISPENSER", "IDCODE", "SEQNUMBER", "ISSUEDATE", "WASHNO", "WASHNONONPOOL", "REPAIRNO", "REPAIRNONONPOOL", "REWASHNO", "REWASHNONONPOOL", "MODIFICATIONS", "REASON", "CUSTOMEROWNED", "LASTSCANDATE", "LASTOUTSCANDATE", "FINMETHOD", "INVOICEAMOUNTDECIMALS", "RESIDUALVALUE", "FLAGCODE", "STAY", "STAYNR", "STATUS", "ADMINNUMBER", "COSTCENTERCODE", "COSTCENTERDESC", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEFAULTBUSINESSUNIT_ID", "CITY", "WEARERNUMBER", "WEARERNAME", "WEARERSEARCHNAME", "WEARERACTIVE", "WEARERDATEACTIVE", "WEARERDATEINACTIVE", "LANGUAGECODE", "LANGUAGE_ID", "CUSTOMERLANGUAGE_ID", "DELIVERYPOINT_ID_L", "DELIVERYPOINT_ID_G", "DELIVERYPOINT_ID_W", "WEARERFUNCTION_ID", "PRODUCT_ID", "COSTCENTER_ID", "WEARER_ID") AS 
  select --wu.productdescriptiononly
case when (select sy.value from systemsetting sy where sy.plant_id = wu.plant_id and sy.name = 'NEWWEBAPPLICATION') = 'N'
           then (select s.value from systemsetting s where s.plant_id = wu.plant_id and s.name = 'SHOWLONGPRODUCTDESC')
      else wu.productdescriptiononly
 end productdescriptiononly
, wu.showgarmentissuedate, wu.showgarmentwashestotal, wu.showgarmentwashesissue
, wu.showgarmentrepairstotal, wu.showgarmentrepairsissue, wu.showgarmentrewashestotal, wu.showgarmentrewashesissue
, h.UNIQUEITEM_ID, ws.websession_id, wc.webuser_id, WD.DEPARTMENT_ID WEBUSERDEPARTMENT_ID, DE.DEPARTMENT_ID
, cast(F_GETPRODUCTCODE(prd.code, cu.customer_id, h.product_id, h.sizedefinition_id, h.finishingmethod_id) as varchar2(12)) PRODUCTCODE
, cast(RIGHTPAD(F_GETPRODUCTDESC(cu.customer_id, h.product_id, h.sizedefinition_id, h.finishingmethod_id, languages.language_id),30,' ') as varchar2(255)) productdesc
, wf.code functioncode, wf.description functiondesc, wey.sequencenumber employment, sz.code sizecode
, cast(CONCATENATEWITHBLANK(lk.bank, lk.locker) as varchar2(255)) banklocker
, gd.code garmentdispenser, h.primaryid idcode, h.idcodesequencenumber seqnumber
, p.lastissuedate issuedate
, h.washestotal washno, g.washesthisissue washnononpool
, h.repairstotal repairno, g.repairsthisissue repairnononpool
, h.rewashtotal rewashno, g.rewashthisissue rewashnononpool
/*, ( SELECT COUNT(*) FROM UNIQUEITEMFLAG uf, flag fg
      WHERE uf.UNIQUEITEM_ID = h.UNIQUEITEM_ID and uf.flag_id=fg.flag_id
      and fg.useinwebapplication='Y' and
trunc(uf.startdate)<=trunc(sysdate)--tne 18NOV2005
) flag*/
, ( select count(*) from uniqueitemmodification um, modification md where um.uniqueitem_id=h.uniqueitem_id
   and um.modification_id=md.modification_id and md.useinwebapplication='Y') modifications
--, r.code reason
, (select rsd.description from reasoncode_desc rsd where r.reasoncode_id=rsd.reasoncode_id
    and rsd.language_id=languages.LANGUAGE_ID) reason
, h.customerowned
, trunc(h.lastscandate) lastscandate, trunc(h.lastoutscandate) lastoutscandate
, fm.code finmethod, currency.invoiceamountdecimals, h.residualvalueAmount residualvalue, flag.code flagcode
, ( SELECT cast(description as varchar2(10)) FROM stay_desc sty WHERE sty.stay_id = stay.stay_id
  AND sty.LANGUAGE_ID = languages.LANGUAGE_ID) stay, stay.staynr
, ( SELECT description FROM status_desc sd WHERE sd.status_id = h.status_id
  AND sd.LANGUAGE_ID = languages.LANGUAGE_ID) status
, we.customeremployeenumber adminnumber,  cc.code costcentercode, cc.description costcenterdesc
, de.departmentnumber, de.description departmentdesc
, cu.customernumber, cu.name customername, cu.defaultbusinessunit_id, address.city
, we.wearernumber, we.fullname wearername, we.searchname wearersearchname
, GETDATEDIFF(trunc(sysdate), we.dateactive)*GETDATEDIFF(we.dateinactive, trunc(sysdate)) weareractive
, we.dateactive WearerDateActive, we.dateinactive WearerDateInactive
, languages.code languagecode, languages.language_id, cu.language_id customerlanguage_id
, lk.deliverypoint_id deliverypoint_id_l
, gd.deliverypoint_id deliverypoint_id_g
, wey.deliverypoint_id deliverypoint_id_w
, wf.wearerfunction_id
, h.product_id
, cc.costcenter_id
, we.wearer_id
from
  weareremployment wey
    left outer join garmentdispenser gd on (gd.garmentdispenser_id = wey.garmentdispenser_id)
    left outer join locker lk on (lk.locker_id = wey.locker_id)
    left outer join wearerfunction wf on (wey.wearerfunction_id = wf.wearerfunction_id),
  wearer we
    left outer join flag on we.flag_id = flag.flag_id and flag.useinwebapplication='Y',
  customer cu, address, currency, languages,  uniqueitemnonpool g,
  distributionpoint dip, department de,  costcenter cc,
  uniqueitem h
    left outer join stay on h.stay_id = stay.stay_id
    left outer join finishingmethod fm on (fm.finishingmethod_id = h.finishingmethod_id),
  uniqueitemfixedinfo p, reasoncode r, PRODUCT prd,  sizedefinition sz,
  webusercustomer wc
    left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  websession ws, webuser wu
where wey.weareremployment_id = g.weareremployment_id
  and g.uniqueitem_id = h.uniqueitem_id
  and h.uniqueitem_id = p.uniqueitem_id
  and p.reasoncode_id = r.reasoncode_id
  AND H.PRODUCT_ID = prd.PRODUCT_ID
  and wey.wearer_id = we.wearer_id
  and we.customer_id = cu.customer_id
  and cu.mailaddress_id = address.address_id
  and cu.currency_id = currency.currency_id
  and wey.distributionpoint_id = dip.distributionpoint_id
  And dip.department_id = de.department_id
  and dip.costcenter_id = cc.costcenter_id
  and h.sizedefinition_id = sz.sizedefinition_id
  and wc.customer_id = CU.customer_id
  and CU.customer_id = ws.customer_id
  and wc.webuser_id = wu.webuser_id
Union all
select --wu.productdescriptiononly
case when (select sy.value from systemsetting sy where sy.plant_id = wu.plant_id and sy.name = 'NEWWEBAPPLICATION') = 'N'
           then (select s.value from systemsetting s where s.plant_id = wu.plant_id and s.name = 'SHOWLONGPRODUCTDESC')
      else wu.productdescriptiononly
 end productdescriptiononly
, wu.showgarmentissuedate, wu.showgarmentwashestotal, wu.showgarmentwashesissue
, wu.showgarmentrepairstotal, wu.showgarmentrepairsissue, wu.showgarmentrewashestotal, wu.showgarmentrewashesissue
, 0 UNIQUEITEM_ID, ws.websession_id, wc.webuser_id, WD.DEPARTMENT_ID WEBUSERDEPARTMENT_ID, DE.DEPARTMENT_ID
, cast(F_GETPRODUCTCODE(prd0.code, we.customer_id, g0.product_id, g0.sizedefinition_id, g0.finishingmethod_id) as varchar2(12)) PRODUCTCODE
, cast(RIGHTPAD(F_GETPRODUCTDESC(we.customer_id, g0.product_id, g0.sizedefinition_id, g0.finishingmethod_id, languages.language_id),30,' ') as varchar2(255)) productdesc
, wf0.code functioncode, wf0.description functiondesc, wey0.sequencenumber employment, sz.code sizecode
, cast(CONCATENATEWITHBLANK(lk0.bank, lk0.locker) as varchar2(255)) banklocker, gd0.code garmentdispenser, null idcode, h0.sequencenumber seqnumber
, h0.issuedate issuedate
, null washno, null washnononpool
, null repairno, null repairnononpool
, null rewashno, null rewashnononpool
--, null flag
, ( SELECT count(*) FROM wearerinventorymodification wim0, modification md
      WHERE wim0.wearerinventory_id = g0.wearerinventory_id and wim0.modification_id=md.modification_id
      and md.useinwebapplication = 'Y') modifications, r0.code reason, 'N' customerowned
, null lastscandate, null lastoutscandate
, fm0.code finmethod, currency.invoiceamountdecimals, -1 residualvalue, flag.code flagcode
, null stay, null staynr, null status
, we.customeremployeenumber adminnumber, cc.code costcentercode, cc.description costcenterdesc
, de.departmentnumber, de.description departmentdesc
, cu.customernumber, cu.name customername, cu.defaultbusinessunit_id, address.city
, we.wearernumber, we.fullname wearername, we.searchname wearersearchname
, GETDATEDIFF(trunc(sysdate), we.dateactive)*GETDATEDIFF(we.dateinactive, trunc(sysdate)) weareractive
, we.dateactive WearerDateActive, we.dateinactive WearerDateInactive
, languages.code languagecode, languages.language_id, cu.language_id customerlanguage_id
, lk0.deliverypoint_id deliverypoint_id_l
, gd0.deliverypoint_id deliverypoint_id_g
, wey0.deliverypoint_id deliverypoint_id_w
, wf0.wearerfunction_id
, prd0.product_id
, cc.costcenter_id
, we.wearer_id
from
  weareremployment wey0
    left outer join garmentdispenser gd0 on (gd0.garmentdispenser_id = wey0.garmentdispenser_id)
    left outer join locker lk0 on (lk0.locker_id = wey0.locker_id)
    left outer join wearerfunction wf0 on (wey0.wearerfunction_id = wf0.wearerfunction_id),
  wearer we
    left outer join flag on we.flag_id = flag.flag_id and flag.useinwebapplication='Y',
  customer cu, address, currency, languages,
  distributionpoint dip, department de,  costcenter cc,
  wearerinventory g0, nonuniqueitem h0, reasoncode r0, finishingmethod fm0, PRODUCT prd0,
  sizedefinition sz,
  webusercustomer wc
    left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
--  , PRODUCTLISTPERCUSTOMER plpc
  websession ws, webuser wu
where wey0.weareremployment_id = g0.weareremployment_id
  and g0.wearerinventory_id = h0.wearerinventory_id
  and g0.finishingmethod_id = fm0.finishingmethod_id
  and h0.reasoncode_id = r0.reasoncode_id
  AND G0.PRODUCT_ID = prd0.PRODUCT_ID
  and wey0.wearer_id = we.wearer_id
  and we.customer_id = cu.customer_id
  and cu.mailaddress_id = address.address_id
  and cu.currency_id = currency.currency_id
  and wey0.distributionpoint_id = dip.distributionpoint_id
  and dip.department_id = de.department_id
  and dip.costcenter_id = cc.costcenter_id
  and g0.sizedefinition_id = sz.sizedefinition_id
  and wc.customer_id = CU.customer_id
  and CU.customer_id = ws.customer_id
  and wc.webuser_id = wu.webuser_id
/*  and plpc.product_id = g0.product_id
  and plpc.finishingmethod_id = g0.finishingmethod_id
  and plpc.sizedefinition_id = g0.sizedefinition_id
  and plpc.customer_id = we.customer_id
*/
--WebGarmentsPerWearer.rpt
/

  CREATE OR REPLACE VIEW "V_WEBLINENASSQUANTITIESPERWEEK" ("DEPARTMENT_ID", "REPORTPARAM_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESCR", "DISTRIBUTIONPOINT_ID", "DISTRIBUTIONPOINTNUMBER", "DISTRIBPOINTDESCR", "DELIVERYPOINT_ID", "DELPOINTCODE", "DELPOINTDESCR", "COSTCENTER_ID", "COSTCENTERCODE", "COSTCENTERDESCR", "PRODUCTLISTPERDISTRIBPOINT_ID", "PRODUCTCODE", "PRODUCTDESCR", "SIZECODE", "FMCODE", "SDL_STANDARDDELIVERYLINEID", "DATE_MIN", "DATE_MAX", "DATEACTIVE", "DATEINACTIVE", "SDA_AMOUNT", "NSA_AMOUNT", "IOL_QUANTITY", "IO_STATUS", "IO_ORDERDATE", "IO_WEEKORDERDATE", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEBUSER_ID", "WEBSESSION_ID", "LANGUAGECODE", "WEBUSERDEPARTMENT_ID") AS 
  select d.department_id, rp.reportparam_id,
       d.departmentnumber,
       d.description departmentdescr,
       dp.distributionpoint_id,
       dp.distributionpointnumber,
       dp.description distribpointdescr,
       delp.deliverypoint_id,
       delp.code delpointcode,
       delp.description delpointdescr,
       cc.costcenter_id,
       cc.code costcentercode,
       cc.description costcenterdescr,
       plpd.productlistperdistribpoint_id,
       coalesce((select plpc.customcode from productlistpercustomer plpc
                       where plpc.product_id = plpd.product_id
                       and plpc.sizedefinition_id = plpd.sizedefinition_id
                       and plpc.finishingmethod_id = plpd.finishingmethod_id
                       and plpc.customer_id = c.customer_id),
       (select p.code from product p where p.product_id = plpd.product_id)) productcode,
       coalesce((select plpc.customdescription from productlistpercustomer plpc
                       where plpc.product_id = plpd.product_id
                       and plpc.sizedefinition_id = plpd.sizedefinition_id
                       and plpc.finishingmethod_id = plpd.finishingmethod_id
                       and plpc.customer_id = c.customer_id),
       (select pd.description
          from product p, product_desc pd
         where p.product_id = plpd.product_id
           and p.product_id = pd.product_id
           and pd.language_id = l.language_id)) productdescr,
       (select sd.code from sizedefinition sd where sd.sizedefinition_id = plpd.sizedefinition_id) sizecode,
       (select fm.code from finishingmethod fm where fm.finishingmethod_id = plpd.finishingmethod_id) fmcode,
       sdl.standarddeliveryline_id sdl_standarddeliverylineid,
       getdateforweekyear(1,rp.number_value3,rp.number_value1) date_min,
       getdateforweekyear(7,rp.number_value4,rp.number_value2) date_max,
       sdl.dateactive,
       sdl.dateinactive,
       (select sum(sda.amount) from standarddeliveryamount sda where sda.standarddeliveryline_id = sdl.standarddeliveryline_id
       and exists (select 1 from STOCKCOUNTSCHEDULE t, stockcountscheduleday sdd, stockcountscheduledept sdept
           where t.stockcountschedule_id=sdd.stockcountschedule_id
           and sdept.stockcountschedule_id=t.stockcountschedule_id
           and sdept.department_id=d.department_id and sdd.day_id=sda.day_id
            union
           select 1 from STOCKCOUNTSCHEDULE t, stockcountscheduleday sdd, stockcountscheduledist sdist
           where t.stockcountschedule_id=sdd.stockcountschedule_id
           and sdist.stockcountschedule_id=t.stockcountschedule_id
           and sdist.distributionpoint_id=dp.distributionpoint_id and sdd.day_id=sda.day_id )) sda_amount,
       (select sum(nsa.amount) from normstockamount nsa
        where nsa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
        and exists (select 1 from STOCKCOUNTSCHEDULE t, stockcountscheduleday sdd, stockcountscheduledept sdept
           where t.stockcountschedule_id=sdd.stockcountschedule_id
           and sdept.stockcountschedule_id=t.stockcountschedule_id
           and sdept.department_id=d.department_id and sdd.day_id=nsa.day_id
            union
           select 1 from STOCKCOUNTSCHEDULE t, stockcountscheduleday sdd, stockcountscheduledist sdist
           where t.stockcountschedule_id=sdd.stockcountschedule_id
           and sdist.stockcountschedule_id=t.stockcountschedule_id
           and sdist.distributionpoint_id=dp.distributionpoint_id and sdd.day_id=nsa.day_id
           )) nsa_amount,
       iol.quantity iol_quantity,
       io.status io_status,
       io.orderdate io_orderdate,
       getisoweek(io.orderdate) io_weekorderdate,
       c.customer_id,
       c.customernumber,
       c.name customername,
       wu.webuser_id,
       wus.websession_id,
       l.code languagecode,
       wud.department_id webuserdepartment_id
  from productlistperdistribpoint plpd,
       standarddelivery           sd,
       standarddeliveryline       sdl,
       internetorder              io,
       internetorderline          iol,
       department                 d,
       distributionpoint          dp,
       deliverypoint              delp,
       costcenter                 cc,
       customer                   c,
       languages                  l,
       webuser                    wu,
       webusercustomer wuc
                       left outer join webuserdepartment wud on (wuc.webusercustomer_id = wud.webusercustomer_id),
       webusersession             wus,
       reportparam rp
 where plpd.productlistperdistribpoint_id =
       sdl.productlistperdistribpoint_id
   and sdl.standarddelivery_id = sd.standarddelivery_id
   and io.distributionpoint_link_id = plpd.distributionpoint_id
   and io.internetorder_id = iol.internetorder_id
   and iol.product_link_id = plpd.product_id
   and iol.sizedefinition_link_id = plpd.sizedefinition_id
   and iol.finishingmethod_id = plpd.finishingmethod_id
   and plpd.distributionpoint_id = dp.distributionpoint_id
   and dp.department_id = d.department_id
   and dp.deliverypoint_id = delp.deliverypoint_id
   and dp.costcenter_id = cc.costcenter_id
   and d.customer_id = c.customer_id
   and wus.customer_id = c.customer_id
   and wu.webuser_id = wuc.webuser_id
   and wuc.customer_id = c.customer_id
   and io.status >= 3
   and iol.type = 1
   and plpd.orderingmethod = 1
/

  CREATE OR REPLACE VIEW "V_WEBMONTHLYUSAGE" ("WEBUSER_ID", "WEBUSERDEPARTMENT_ID", "DEPARTMENT_ID", "REPORTPARAM_ID", "WEBSESSION_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "COSTCENTRE_CODE", "COSTCENTRE_DESC", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "ACTIVITYCODE", "PRODUCTGROUPCODE", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "FINISHINGCODE", "FINISHINGDESC", "PATIENTDAYSDSP", "PATIENTDAYSDEP", "PATIENTDAYSCC", "QUANTITY", "WEIGHT", "PRICE", "PAR_LEVEL", "INVOICEAMOUNTDECIMALS", "CURRENCYCODE", "LANGUAGECODE") AS 
  select wc.webuser_id, WD.DEPARTMENT_ID WEBUSERDEPARTMENT_ID, dpl.department_id, rp.reportparam_id,
  ws.websession_id,
  cu.customernumber, cu.name customername,
  cc.code costcentre_code, cc.description costcentre_desc,
  dpl.departmentnumber, dpl.description departmentdesc,
  dspl.distributionpointnumber, dspl.description distributionpointdesc,
  ac.code activityCode, prdgr.code productgroupCode, prd.code productCode,
  (select product_link_desc.description from product_link_desc
   where product_link_desc.product_link_id = DH.PRODUCT_LINK_ID
     and product_link_desc.language_id = languages.language_id ) productDesc,
  szl.code sizeCode, fm.code Finishingcode,
  (select finishingmethod_desc.description from finishingmethod_desc
   where finishingmethod_desc.finishingmethod_id = fm.finishingmethod_id
     and finishingmethod_desc.language_id = languages.language_id ) FinishingDesc,
  coalesce((select SUM(pdy.patientdays) from patientday pdy
    where dspl.distributionpoint_link_id = pdy.distributionpoint_link_id
--     and pdy.year = rp.copy_number and pdy.month between rp.number_value1 and rp.number_value2
     and pdy.year*100+pdy.month between (rp.copy_number*100+rp.number_value1) and (rp.number_value3*100+rp.number_value2)
     and pdy.week = 0
   GROUP BY dspl.distributionpoint_link_id),0) patientdaysDsp,
  coalesce((select sum(pdy.patientdays) from patientday pdy, distributionpoint_link
   where distributionpoint_link.department_link_id = dpl.department_link_id
     and distributionpoint_link.distributionpoint_link_id = pdy.distributionpoint_link_id
--     and pdy.year = rp.copy_number and pdy.month between rp.number_value1 and rp.number_value2
     and pdy.year*100+pdy.month between (rp.copy_number*100+rp.number_value1) and (rp.number_value3*100+rp.number_value2)
     and pdy.week = 0
   group by distributionpoint_link.department_link_id),0) patientdaysDep,
  rp.number_value6 patientdaysCC,
  coalesce(sum(dh.amountdelivered),0) quantity,
  coalesce(sum(dh.amountdelivered *
    F_GETTHEORETICALWEIGHT(prd.theoreticalweight, prd.product_id, szl.sizedefinition_id)),0) weight,
  coalesce(sum(dh.amountdelivered*
    F_RESTOCKINGPRICE(cu.customer_id, prd.product_id, szl.sizedefinition_id, fm.finishingmethod_id,
    dh.deliverydate, prd.typeofmerchandise)),0) price,
--  F_GETPARLEVEL(RP.copy_number, RP.NUMBER_VALUE1, RP.NUMBER_VALUE2, rp.string_value,--RP.NUMBER_VALUE3,
    F_GETPARLEVEL(RP.copy_number, RP.NUMBER_VALUE3, RP.NUMBER_VALUE1, RP.NUMBER_VALUE2, rp.string_value,--RP.NUMBER_VALUE3,
    cu.customer_id, cc.costcenter_id, dpl.department_id, dspl.distributionpoint_id,
    DH.PRODUCT_LINK_ID, szl.sizedefinition_id, fm.finishingmethod_id) par_level,
  cur.invoiceamountdecimals, cur.code currencycode, languages.code languagecode
from deliveryhistory dh, customer_link cul, customer cu, customermonth cum, distributionpoint_link dspl,
  distributionpoint dsp, costcenter cc,
  department_link dpl, sizedefinition_link szl, finishingmethod fm,
  product prd
    left outer join (productgroup prdgr join activity ac on prdgr.activity_id = ac.activity_id )
    on prd.productgroup_id = prdgr.productgroup_id,
  webusercustomer wc
    left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  currency cur,
  languages, websession ws, reportparam rp
where dh.customer_link_id = cul.customer_link_id
  and cul.customer_id = cu.customer_id
  and cu.customer_id = cum.customer_id
--  AND RP.copy_number = CUM.YEAR
--  AND CUM.MONTH BETWEEN RP.NUMBER_VALUE1 AND RP.NUMBER_VALUE2
  and CUM.YEAR*100+CUM.MONTH BETWEEN (RP.copy_number*100+RP.NUMBER_VALUE1) AND (rp.number_value3*100+RP.NUMBER_VALUE2)
  and dh.distributionpoint_link_id = dspl.distributionpoint_link_id
  and dspl.distributionpoint_id = dsp.distributionpoint_id
  and dsp.costcenter_id = cc.costcenter_id
  and dh.department_link_id = dpl.department_link_id
  and dh.sizedefinition_link_id = szl.sizedefinition_link_id
  and dh.finishingmethod_id = fm.finishingmethod_id
  and dh.product_link_id = prd.product_id
  and cu.currency_id = cur.currency_id
  and wc.customer_id = cu.customer_id
  and dh.deliverydate between cum.startdate and cum.enddate
  and dh.customer_link_id = ws.customer_id
  and dh.packindication <> 2
  and cc.costcenter_id = rp.number_value
group by wc.webuser_id, WD.DEPARTMENT_ID, dpl.department_id,
  cu.customernumber, cu.name, cu.customer_id,
  cc.costcenter_id, cc.code, cc.description,
  dpl.departmentnumber, dpl.description,
  dspl.distributionpointnumber, dspl.description,
  DH.PRODUCT_LINK_ID, fm.finishingmethod_id, dspl.distributionpoint_link_id,
  ac.code, prdgr.code, prd.code, szl.code, fm.code,
  cur.invoiceamountdecimals, dpl.department_link_id, cur.code,
  languages.code, languages.language_id, ws.websession_id,
  rp.reportparam_id, rp.number_value, rp.number_value1, rp.number_value2,
  szl.sizedefinition_id, RP.NUMBER_VALUE3, cu.customer_id, dspl.distributionpoint_id,
  rp.number_value4, rp.number_value5, rp.number_value6, rp.number_value6, rp.copy_number, rp.string_value
/

  CREATE OR REPLACE VIEW "V_WEBMONTHLYUSAGEANG" ("WEBUSER_ID", "WEBUSERDEPARTMENT_ID", "DEPARTMENT_ID", "REPORTPARAM_ID", "WEBSESSION_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "COSTCENTRE_CODE", "COSTCENTRE_DESC", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "ACTIVITYCODE", "PRODUCTGROUPCODE", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "SIZEDESC", "FINISHINGCODE", "FINISHINGDESC", "PATIENTDAYSDSP", "PATIENTDAYSDEP", "PATIENTDAYSCC", "QUANTITY", "WEIGHT", "PRICE", "SOILWEIGHT", "POUNDPRICE", "INVOICEAMOUNTDECIMALS", "PRICEDECIMALS", "CURRENCYCODE", "LANGUAGECODE") AS 
  select wc.webuser_id, WD.DEPARTMENT_ID WEBUSERDEPARTMENT_ID, dpl.department_id, rp.reportparam_id,
  ws.websession_id,
  cu.customernumber, cu.name customername,
  cc.code costcentre_code, cc.description costcentre_desc,
  dpl.departmentnumber, dpl.description departmentdesc,
  dspl.distributionpointnumber, dspl.description distributionpointdesc,
  ac.code activityCode, prdgr.code productgroupCode, prd.code productCode,
  (select product_link_desc.description from product_link_desc
   where product_link_desc.product_link_id = DH.PRODUCT_LINK_ID
     and product_link_desc.language_id = languages.language_id ) productDesc,
  szl.code sizeCode,
  (select szd.description from sizedefinition_desc szd where szd.sizedefinition_id = szl.sizedefinition_link_id
     and szd.language_id = languages.language_id) sizedesc,
  fm.code Finishingcode,
  (select finishingmethod_desc.description from finishingmethod_desc
   where finishingmethod_desc.finishingmethod_id = fm.finishingmethod_id
     and finishingmethod_desc.language_id = languages.language_id ) FinishingDesc,
  coalesce((select SUM(pdy.patientdays) from patientday pdy where dspl.distributionpoint_link_id = pdy.distributionpoint_link_id
--     and pdy.year = rp.copy_number and pdy.month between rp.number_value1 and rp.number_value2
     and pdy.year*100+pdy.month between (rp.copy_number*100+rp.number_value1) and (rp.number_value3*100+rp.number_value2)
     and pdy.week = 0
   GROUP BY dspl.distributionpoint_link_id),0) patientdaysDsp,
  coalesce((select sum(pdy.patientdays) from patientday pdy, distributionpoint_link
   where distributionpoint_link.department_link_id = dpl.department_link_id
     and distributionpoint_link.distributionpoint_link_id = pdy.distributionpoint_link_id
--     and pdy.year = rp.copy_number and pdy.month between rp.number_value1 and rp.number_value2
     and pdy.year*100+pdy.month between (rp.copy_number*100+rp.number_value1) and (rp.number_value3*100+rp.number_value2)
     and pdy.week = 0
   group by distributionpoint_link.department_link_id),0) patientdaysDep,
  rp.number_value6 patientdaysCC,
  coalesce(sum(dh.amountdelivered),0) quantity,
  coalesce(sum(dh.amountdelivered *
    F_GETTHEORETICALWEIGHT(prd.theoreticalweight, prd.product_id, szl.sizedefinition_id)),0) weight,
  coalesce(
    F_RESTOCKINGPRICE_ANG(dh.customer_link_id, DH.PRODUCT_LINK_ID, szl.sizedefinition_link_id, fm.finishingmethod_id,
    dh.deliverydate, prd.typeofmerchandise),0) price,
--  F_GETSOILWEIGHT(dh.customer_link_id, DH.PRODUCT_LINK_ID, szl.sizedefinition_link_id, fm.finishingmethod_id, rp.date_value1) soilweight,
  coalesce(max(dh.pieceweight),0) soilweight,
  F_GETPOUNDPRICE(DH.PRODUCT_LINK_ID, fm.finishingmethod_id, szl.sizedefinition_link_id,
    dh.customer_link_id, prd.weighingcategory_id, dh.deliverydate) poundprice,
  cur.invoiceamountdecimals, cur.decimals pricedecimals,
  cur.code currencycode, languages.code languagecode
from deliveryhistory dh, customer_link cul, customer cu, customermonth cum, distributionpoint_link dspl,
     distributionpoint dsp, costcenter cc,
  department_link dpl, sizedefinition_link szl, finishingmethod fm,
  product prd
    left outer join (productgroup prdgr join activity ac on prdgr.activity_id = ac.activity_id )
    on prd.productgroup_id = prdgr.productgroup_id,
  webusercustomer wc
    left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  currency cur, languages, websession ws, reportparam rp
where dh.customer_link_id = cul.customer_link_id
  and cul.customer_id = cu.customer_id
  and cu.customer_id = cum.customer_id
--  AND RP.copy_number = CUM.YEAR
--  AND CUM.MONTH BETWEEN RP.NUMBER_VALUE1 AND RP.NUMBER_VALUE2
  and CUM.YEAR*100+CUM.MONTH BETWEEN (RP.copy_number*100+RP.NUMBER_VALUE1) AND (rp.number_value3*100+RP.NUMBER_VALUE2)
  and dh.distributionpoint_link_id = dspl.distributionpoint_link_id
  and dspl.distributionpoint_id = dsp.distributionpoint_id
  and dsp.costcenter_id = cc.costcenter_id
  and dh.department_link_id = dpl.department_link_id
  and dh.sizedefinition_link_id = szl.sizedefinition_link_id
  and dh.finishingmethod_id = fm.finishingmethod_id
  and dh.product_link_id = prd.product_id
  and cu.currency_id = cur.currency_id
  and wc.customer_id = cu.customer_id
  and dh.deliverydate between cum.startdate and cum.enddate
  and dh.customer_link_id = ws.customer_id
  and dh.packindication <> 2
  and cc.costcenter_id = rp.number_value
group by wc.webuser_id, WD.DEPARTMENT_ID, dpl.department_id,
  cu.customernumber, cu.name, dh.customer_link_id,
  cc.costcenter_id, cc.code, cc.description,
  dpl.departmentnumber, dpl.description, prd.weighingcategory_id,
  dspl.distributionpointnumber, dspl.description,
  DH.PRODUCT_LINK_ID, fm.finishingmethod_id, szl.sizedefinition_link_id,
  dspl.distributionpoint_link_id, ac.code, prdgr.code, prd.code, szl.code, fm.code,
  cur.invoiceamountdecimals, languages.code, languages.language_id, dpl.department_link_id, prd.typeofmerchandise, cur.decimals,
  ws.websession_id, cur.code, rp.reportparam_id, rp.number_value, rp.number_value1, rp.number_value2, dh.deliverydate,
  rp.number_value4, rp.number_value5, rp.copy_number, rp.number_value6, rp.number_value3
/

  CREATE OR REPLACE VIEW "V_WEBMONTHLYUSAGENEW" ("WEBUSER_ID", "CUSTOMER_ID", "DISTRIBUTIONPOINT_ID", "WEBUSERDEPARTMENT_ID", "YEAR", "MONTH", "COSTCENTER_ID", "DEPARTMENT_ID", "REPORTPARAM_ID", "WEBSESSION_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "COSTCENTRE_CODE", "COSTCENTRE_DESC", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "ACTIVITY_ID", "ACTIVITYCODE", "PRODUCTGROUP_ID", "PRODUCTGROUPCODE", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "SIZEDESC", "FINISHINGCODE", "FINISHINGDESC", "QUANTITY", "WEIGHT", "PRICE", "SOILWEIGHT", "POUNDPRICE", "COSTPRICE", "INVOICEAMOUNTDECIMALS", "PRICEDECIMALS", "CURRENCYCODE", "LANGUAGECODE", "BUDGETRELEVANT") AS 
  select /*+ordered index(dh xie14deliveryhistory)*/
 wc.webuser_id, cu.customer_id, dsp.distributionpoint_id, wd.department_id webuserdepartment_id,
 cum.year, cum.month, cc.costcenter_id, dpl.department_id, rp.reportparam_id, wus.websession_id,
 cu.customernumber, cu.name customername, cc.code costcentre_code, cc.description costcentre_desc,
 dpl.departmentnumber, dpl.description departmentdesc, dsp.distributionpointnumber, dsp.description distributionpointdesc,
 ac.activity_id activity_id, ac.code activitycode, prdgr.productgroup_id productgroup_id, prdgr.code productgroupcode,
 prd.product_id product_id, prd.code productcode,
 (select product_link_desc.description
    from product_link_desc
   where product_link_desc.product_link_id = prd.product_id
     and product_link_desc.language_id = languages.language_id) productdesc,
 szl.code sizecode,
 (select szd.description
    from sizedefinition_desc szd
   where szd.sizedefinition_id = szl.sizedefinition_id
     and szd.language_id = languages.language_id) sizedesc,
 fm.code finishingcode,
 (select finishingmethod_desc.description
    from finishingmethod_desc
   where finishingmethod_desc.finishingmethod_id = fm.finishingmethod_id
     and finishingmethod_desc.language_id = languages.language_id) finishingdesc,
 coalesce(sum(dh.amountdelivered), 0) quantity,
 coalesce(sum(dh.amountdelivered *
              f_gettheoreticalweight(prd.theoreticalweight,
                                     prd.product_id,
                                     szl.sizedefinition_id)),
          0) weight,
 coalesce(f_restockingprice_ang(dh.customer_link_id,
                                dh.product_link_id,
                                szl.sizedefinition_id,
                                fm.finishingmethod_id,
                                rp.date_value1,
                                prd.typeofmerchandise),
          0) price,
 coalesce(max(dh.pieceweight), 0) soilweight,
 f_getpoundprice(dh.product_link_id,
                 fm.finishingmethod_id,
                 szl.sizedefinition_id,
                 dh.customer_link_id,
                 prd.weighingcategory_id,
                 rp.date_value1) poundprice,
 coalesce(f_getcostreportprice(dh.customer_link_id,
                               prd.product_id,
                               szl.sizedefinition_id,
                               fm.finishingmethod_id,
                               rp.date_value1,
                               prd.typeofmerchandise,
                               prd.weighingcategory_id,
                               cur.decimals),
          0) costprice,
 cur.invoiceamountdecimals, cur.decimals pricedecimals, cur.code currencycode, languages.code languagecode,
 (select plpc.budgetrelevant
    from productlistpercustomer plpc
   where plpc.customer_id = cu.customer_id
     and plpc.product_id = dh.product_link_id
     and plpc.sizedefinition_id = dh.sizedefinition_link_id
     and plpc.finishingmethod_id = dh.finishingmethod_id
     and plpc.dateinactive > rp.date_value1) budgetrelevant
  from reportparam rp
       join costcenter cc on cc.costcenter_id = rp.number_value
       join distributionpoint dsp on dsp.costcenter_id = cc.costcenter_id
       join department dpl on dpl.department_id = dsp.department_id and dpl.costcenter_id = cc.costcenter_id
       join customermonth cum on cum.customer_id = dpl.customer_id
       join deliveryhistory dh on (dh.customer_link_id = dpl.customer_id and dh.distributionpoint_link_id = dsp.distributionpoint_id
                                  and dh.deliverydate >= cum.startdate and dh.deliverydate <= cum.enddate)
       join customer cu on cu.customer_id = dh.customer_link_id
       join currency cur on cur.currency_id = cu.currency_id
       join product prd on prd.product_id = dh.product_link_id
       join productgroup prdgr on prd.productgroup_id = prdgr.productgroup_id
       join activity ac on ac.activity_id = prdgr.activity_id
       join sizedefinition szl on dh.sizedefinition_link_id = szl.sizedefinition_id
       join finishingmethod fm on fm.finishingmethod_id = dh.finishingmethod_id
       join webusercustomer wc on wc.customer_id = cu.customer_id
       join webusersession wus on (wus.webuser_id = wc.webuser_id and wus.customer_id = wc.customer_id)
            left outer join webuserdepartment wd on wc.webusercustomer_id = wd.webusercustomer_id
       , languages
 where dh.packindication <> 2
   and cum.year * 100 + cum.month between (rp.copy_number * 100 + rp.number_value1) and (rp.number_value3 * 100 + rp.number_value2)
 group by wc.webuser_id, wd.department_id, dpl.department_id, dsp.distributionpoint_id, cu.customernumber, cu.name, dh.customer_link_id,
          cc.costcenter_id, cc.code, cc.description, dpl.departmentnumber, dpl.description, prd.weighingcategory_id, dsp.distributionpointnumber,
          dsp.description, dh.product_link_id, fm.finishingmethod_id, szl.sizedefinition_id, dsp.distributionpoint_id, ac.activity_id,
          ac.code, prdgr.productgroup_id, prdgr.code, prd.product_id, prd.code, szl.code, fm.code, cur.invoiceamountdecimals, languages.code,
          cu.customer_id, dh.sizedefinition_link_id, dh.finishingmethod_id,  languages.language_id, dpl.department_id, prd.typeofmerchandise,
          cur.decimals, wus.websession_id, cur.code, rp.reportparam_id, rp.number_value, rp.number_value1, rp.number_value2, rp.date_value1,
          dh.distributionpoint_link_id, cum.year, cum.month
/

  CREATE OR REPLACE VIEW "V_WEBMONTHLYUSAGENEW_OLD" ("WEBUSER_ID", "WEBUSERDEPARTMENT_ID", "DEPARTMENT_ID", "REPORTPARAM_ID", "WEBSESSION_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "COSTCENTRE_CODE", "COSTCENTRE_DESC", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "ACTIVITY_ID", "ACTIVITYCODE", "PRODUCTGROUP_ID", "PRODUCTGROUPCODE", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "FINISHINGCODE", "FINISHINGDESC", "PATIENTDAYSDSP", "PATIENTDAYSDEP", "PATIENTDAYSCC", "QUANTITY", "WEIGHT", "PRICE", "PAR_LEVEL", "INVOICEAMOUNTDECIMALS", "CURRENCYCODE", "LANGUAGECODE") AS 
  select wc.webuser_id, WD.DEPARTMENT_ID WEBUSERDEPARTMENT_ID, dpl.department_id, rp.reportparam_id,
  wus.websession_id,
  cu.customernumber, cu.name customername,
  cc.code costcentre_code, cc.description costcentre_desc,
  dpl.departmentnumber, dpl.description departmentdesc,
  dspl.distributionpointnumber, dspl.description distributionpointdesc,
  ac.activity_id ACTIVITY_ID,  ac.code activityCode, prdgr.productgroup_id PRODUCTGROUP_ID, prdgr.code productgroupCode, prd.product_id PRODUCT_ID, prd.code productCode,
  (select product_link_desc.description from product_link_desc
   where product_link_desc.product_link_id = DH.PRODUCT_LINK_ID
     and product_link_desc.language_id = languages.language_id ) productDesc,
  szl.code sizeCode, fm.code Finishingcode,
  (select finishingmethod_desc.description from finishingmethod_desc
  where finishingmethod_desc.finishingmethod_id = fm.finishingmethod_id
     and finishingmethod_desc.language_id = languages.language_id ) FinishingDesc,
  coalesce((select SUM(pdy.patientdays) from patientday pdy
    where dspl.distributionpoint_link_id = pdy.distributionpoint_link_id
--     and pdy.year = rp.copy_number and pdy.month between rp.number_value1 and rp.number_value2
     and pdy.year*100+pdy.month between (rp.copy_number*100+rp.number_value1) and (rp.number_value3*100+rp.number_value2)
     and pdy.week = 0
   GROUP BY dspl.distributionpoint_link_id),0) patientdaysDsp,
  coalesce((select sum(pdy.patientdays) from patientday pdy, distributionpoint_link
   where distributionpoint_link.department_link_id = dpl.department_link_id
     and distributionpoint_link.distributionpoint_link_id = pdy.distributionpoint_link_id
--     and pdy.year = rp.copy_number and pdy.month between rp.number_value1 and rp.number_value2
     and pdy.year*100+pdy.month between (rp.copy_number*100+rp.number_value1) and (rp.number_value3*100+rp.number_value2)
     and pdy.week = 0
   group by distributionpoint_link.department_link_id),0) patientdaysDep,
  rp.number_value6 patientdaysCC,
  coalesce(sum(dh.amountdelivered),0) quantity,
  coalesce(sum(dh.amountdelivered *
    F_GETTHEORETICALWEIGHT(prd.theoreticalweight, prd.product_id, szl.sizedefinition_id)),0) weight,
  coalesce(sum(dh.amountdelivered*
    F_RESTOCKINGPRICE(cu.customer_id, prd.product_id, szl.sizedefinition_id, fm.finishingmethod_id,
    dh.deliverydate, prd.typeofmerchandise)),0) price,
--  F_GETPARLEVEL(RP.copy_number, RP.NUMBER_VALUE1, RP.NUMBER_VALUE2, rp.string_value,--RP.NUMBER_VALUE3,
    F_GETPARLEVEL(RP.copy_number, RP.NUMBER_VALUE3, RP.NUMBER_VALUE1, RP.NUMBER_VALUE2, rp.string_value,--RP.NUMBER_VALUE3,
    cu.customer_id, cc.costcenter_id, dpl.department_id, dspl.distributionpoint_id,
    DH.PRODUCT_LINK_ID, szl.sizedefinition_id, fm.finishingmethod_id) par_level,
  cur.invoiceamountdecimals, cur.code currencycode, languages.code languagecode
from deliveryhistory dh, customer_link cul, customer cu, customermonth cum, distributionpoint_link dspl,
  distributionpoint dsp, costcenter cc,
  department_link dpl, sizedefinition_link szl, finishingmethod fm,
  product prd
    left outer join (productgroup prdgr join activity ac on prdgr.activity_id = ac.activity_id )
    on prd.productgroup_id = prdgr.productgroup_id,
  webusercustomer wc
    left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  currency cur,
  languages, webusersession wus, reportparam rp
where dh.customer_link_id = cul.customer_link_id
  and cul.customer_id = cu.customer_id
  and cu.customer_id = cum.customer_id
--  AND RP.copy_number = CUM.YEAR
--  AND CUM.MONTH BETWEEN RP.NUMBER_VALUE1 AND RP.NUMBER_VALUE2
  and CUM.YEAR*100+CUM.MONTH BETWEEN (RP.copy_number*100+RP.NUMBER_VALUE1) AND (rp.number_value3*100+RP.NUMBER_VALUE2)
  and dh.distributionpoint_link_id = dspl.distributionpoint_link_id
  and dspl.distributionpoint_id = dsp.distributionpoint_id
  and dsp.costcenter_id = cc.costcenter_id
  and dh.department_link_id = dpl.department_link_id
  and dh.sizedefinition_link_id = szl.sizedefinition_link_id
  and dh.finishingmethod_id = fm.finishingmethod_id
  and dh.product_link_id = prd.product_id
  and cu.currency_id = cur.currency_id
  and wc.customer_id = cu.customer_id
  and dh.deliverydate between cum.startdate and cum.enddate
  and dh.customer_link_id = wus.customer_id
  and dh.packindication <> 2
  and cc.costcenter_id = rp.number_value
group by wc.webuser_id, WD.DEPARTMENT_ID, dpl.department_id,
  cu.customernumber, cu.name, cu.customer_id,
  cc.costcenter_id, cc.code, cc.description,
  dpl.departmentnumber, dpl.description,
  dspl.distributionpointnumber, dspl.description,
  DH.PRODUCT_LINK_ID, fm.finishingmethod_id, dspl.distributionpoint_link_id,
  ac.activity_id, ac.code, prdgr.productgroup_id, prdgr.code, prd.product_id, prd.code, szl.code, fm.code,
  cur.invoiceamountdecimals, dpl.department_link_id, cur.code,
  languages.code, languages.language_id, wus.websession_id,
  rp.reportparam_id, rp.number_value, rp.number_value1, rp.number_value2,
  szl.sizedefinition_id, RP.NUMBER_VALUE3, cu.customer_id, dspl.distributionpoint_id,rp.number_value6, rp.copy_number, rp.string_value
/

  CREATE OR REPLACE VIEW "V_WEBMONTHLYUSAGE_CC" ("COSTCENTER_ID", "PATIENTDAYS", "YEAR", "MONTH", "PRODUCTCODE", "PRODUCTGROUPCODE", "ACTIVITYCODE", "SIZECODE", "FINMETHCODE", "DEPARTMENT_ID", "DEPARTMENT_LINK_ID") AS 
  select dp.costcenter_id, pdy.patientdays, pdy.year, pdy.month,
  pr.code productcode, prg.code productgroupcode, ac.code activitycode, sz.code sizecode, fm.code finmethcode,
  wd.department_id, dh.department_link_id
from patientday pdy, distributionpoint dp, deliveryhistory dh, customermonth cm,
  product pr
    left outer join (productgroup prg join activity ac on prg.activity_id = ac.activity_id)
    on pr.productgroup_id = prg.productgroup_id,
  sizedefinition sz, finishingmethod fm,
  webusercustomer wc
    left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id)
where dp.distributionpoint_id = pdy.distributionpoint_link_id
  and dh.packindication <> 2
  and pdy.week = 0
  and pdy.year = cm.year
  and pdy.month = cm.month
  and dh.deliverydate between cm.startdate and cm.enddate
  and dh.product_link_id = pr.product_id
  and dh.sizedefinition_link_id = sz.sizedefinition_id
  and dh.finishingmethod_id = fm.finishingmethod_id
  and wc.customer_id = dh.customer_link_id
/

  CREATE OR REPLACE VIEW "V_WEBPATDAYSANDINPATADMISSION" ("WEBSESSION_ID", "WEBUSER_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINT_ID", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "COSTCENTER_ID", "COSTCENTER_CODE", "COSTCENTER_DESC", "ACTIVITY_ID", "ACTIVITY_CODE", "ACTIVITY_ACTIVE", "PRODUCTGROUP_ID", "PRODUCTGROUP_CODE", "PRODUCT_ID", "PRODUCT_CODE", "SIZEDEFINITION_ID", "SIZE_CODE", "FINISHINGMETHOD_ID", "FINISHING_CODE", "ACTIVITY_DESC", "PRODUCTGROUP_DESC", "PRODUCT_DESC", "SIZE_DESC", "FINISHING_DESC", "DELIVERYDATE", "NOTENUMBER", "DELIVEREDAMOUNT", "WASH_PRICE", "PATIENTDAYS", "PATIENTS", "YEAR", "MONTH", "WEEK", "PRODUCTDESCRIPTIONONLY", "LANGUAGE_CODE") AS 
  select cast(wus.websession_id as varchar2(50)) websession_id, wuc.webuser_id,
cu.customer_id, cu.customernumber, cu.name customername, de.department_id, de.departmentnumber, de.description departmentdesc,
dp.distributionpoint_id, dp.distributionpointnumber, dp.description distributionpointdesc,
cc.costcenter_id, cc.code CostCenter_code, cc.description CostCenter_desc,
ac.activity_id, ac.code activity_code, ac.active activity_active, pg.productgroup_id, pg.code productgroup_code,
pr.product_id, pr.code product_code, sd.sizedefinition_id, sd.code size_code, fm.finishingmethod_id, fm.code finishing_code,
(select acd.description from activity_desc acd where acd.activity_id = ac.activity_id and acd.language_id = lan.language_id) activity_desc,
(select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pg.productgroup_id and pgd.language_id = lan.language_id) productgroup_desc,
(select pd.description from product_desc pd where pd.product_id = pr.product_id and pd.language_id = lan.language_id) product_desc,
(select sdd.description from SizeDefinition_desc sdd where sdd.sizedefinition_id = sd.sizedefinition_id and sdd.language_id = lan.language_id) size_desc,
(select fmd.description from FinishingMethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id and fmd.language_id = lan.language_id) finishing_desc,
pn.deliverydate, pn.notenumber, sum(pnl.deliveredamount) deliveredamount, --pnl.price, --pnl.deliveredcogqty, cy.code CurrencyCode, cy.description CurrencyDesc,
PACK_PRICE.Wash_Price(cu.customer_id, pr.product_id, sd.sizedefinition_id, fm.finishingmethod_id, pn.deliverydate) Wash_Price,
pa.patientdays, pa.patients, pa.year, pa.month, pa.week, wu.productdescriptiononly,
lan.code Language_Code
from PatientDay PA, PackingNote PN, PackingNoteLine PNL, DistributionPoint DP, Department DE, Customer CU, CostCENTER CC,
  Activity AC, ProductGroup PG, Product PR, SizeDefinition SD, FinishingMethod FM, languages lan, --Currency CY,
  webusercustomer wuc,--left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  webusersession wus, webuser wu
where pn.distributionpoint_id = dp.distributionpoint_id
  and dp.department_id = de.department_id
  and de.customer_id = cu.customer_id
  and dp.costcenter_id = cc.costcenter_id
  and cc.customer_id = cu.customer_id
  and pnl.packingnote_id = pn.packingnote_id
  and pnl.product_id = pr.product_id
  and pr.productgroup_id = pg.productgroup_id
  and pg.activity_id = ac.activity_id
  and pnl.sizedefinition_id = sd.sizedefinition_id
  and pnl.finishingmethod_id = fm.finishingmethod_id  --and cy.currency_id = cu.currency_id
  and wuc.customer_id = cu.customer_id
  and wu.webuser_id = wus.webuser_id
  and wuc.webuser_id = wu.webuser_id
  and pa.distributionpoint_link_id = dp.distributionpoint_id
  and pa.customer_link_id = cu.customer_id
  and pn.freeofchargereason_id is null
  and pnl.deliveredamount <> 0
  and pn.status_id=(select s.status_id from status s where s.statustype='PN' and s.code='30')
  and pa.year=year(pn.deliverydate)
  and pa.month=month(pn.deliverydate)
  and cc.budgetrelevant='Y'
  and (NOT EXISTS (SELECT 1 FROM WEBUSERDEPARTMENT WDEP, WEBUSERCUSTOMER WCUST
                   WHERE WCUST.WEBUSER_ID = WU.WEBUSER_ID
                         AND WDEP.WEBUSERCUSTOMER_ID = WCUST.WEBUSERCUSTOMER_ID
                         AND WCUST.CUSTOMER_ID = Cu.CUSTOMER_ID)
       OR
       EXISTS (SELECT 1 FROM WEBUSERDEPARTMENT WDEP, WEBUSERCUSTOMER WCUST
               WHERE WDEP.DEPARTMENT_ID = DE.DEPARTMENT_ID
                     AND WCUST.WEBUSER_ID = WU.WEBUSER_ID
                     AND WCUST.CUSTOMER_ID = Cu.CUSTOMER_ID
                     AND WDEP.WEBUSERCUSTOMER_ID = WCUST.WEBUSERCUSTOMER_ID)
       )
group by wus.websession_id, wuc.webuser_id,
cu.customer_id, cu.customernumber, cu.name, de.department_id, de.departmentnumber, de.description,
dp.distributionpoint_id, dp.distributionpointnumber, dp.description,
cc.costcenter_id, cc.code, cc.description,
ac.activity_id, ac.code, ac.active, pg.productgroup_id, pg.code,
pr.product_id, pr.code, sd.sizedefinition_id, sd.code, fm.finishingmethod_id, fm.code, lan.language_id,
pn.deliverydate, pn.notenumber, pa.patientdays, pa.patients, pa.year, pa.month, pa.week, wu.productdescriptiononly, lan.code
/

  CREATE OR REPLACE VIEW "V_WEBPATIENTDAYS" ("LINETYPE", "CUSTOMER_ID", "CUSTOMERNUMBER", "NAME", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEP_DESCRIPTION", "DISTRIBUTIONPOINT_ID", "DISTRIBUTIONPOINTNUMBER", "DISTRIB_POINT_DESC", "YEAR", "MONTH", "WEEK", "PATIENTDAYS", "PATIENTS", "WEBUSER_ID", "LANGUAGECODE", "PERIOD") AS 
  select /*version 2.0*/
       1 linetype, c.customer_id, c.customernumber, c.name, d.department_id, d.departmentnumber, d.description dep_description,
       dp.distributionpoint_id, dp.distributionpointnumber, dp.description distrib_point_desc, pd.year, pd.month, pd.week,
       pd.patientdays, pd.patients, wcust.webuser_id, lan.code languagecode,
       case when pd.week = 53 then 13
            else (pd.week-1)/4+1
        end period
 from patientday pd
      join distributionpoint dp
           join department d
                join customer c
                     join webusercustomer wcust on c.customer_id = wcust.customer_id
                on d.customer_id = c.customer_id
                join costcenter cc on d.costcenter_id = cc.costcenter_id
           on dp.department_id = d.department_id
      on pd.distributionpoint_link_id = dp.distributionpoint_id
      cross join languages lan
where pd.customer_link_id = c.customer_id
      and d.active = 'Y'
      and cc.budgetrelevant = 'Y'
      and (0 = (select count(wd.webusercustomer_id)
                  from webuserdepartment wd
                 where wd.webusercustomer_id = wcust.webusercustomer_id)
           or exists (select 1
                        from webuserdepartment wd
                       where wd.webusercustomer_id = wcust.webusercustomer_id
                         and wd.department_id = d.department_id))
union all
select 2 linetype, c.customer_id, c.customernumber, c.name, null department_id, null departmentnumber,
       null dep_description, null distributionpoint_id, null distributionpointnumber, null distrib_point_desc,
       pd.year, pd.month, pd.week, pd.patientdays, pd.patients, wcust.webuser_id, lan.code languagecode,
       case when pd.week = 53 then 13
            else (pd.week-1)/4+1
        end period
 from patientday pd
      join customer c
           join webusercustomer wcust on c.customer_id = wcust.customer_id
      on pd.customer_link_id = c.customer_id
      cross join languages lan
where pd.distributionpoint_link_id is null
/

  CREATE OR REPLACE VIEW "V_WEBPATIENTS" ("DISTRIBUTIONPOINT_LINK_ID", "YEAR", "MONTH", "PATIENTDAYS", "PATIENTS") AS 
  select /*version 2.0*/
       pd.distributionpoint_link_id, pd.year, pd.month, pd.patientdays, pd.patients
  from patientday pd
       join distributionpoint dp on pd.distributionpoint_link_id = dp.distributionpoint_id
/

  CREATE OR REPLACE VIEW "V_WEBPLANNEDDATA" ("WEBSESSION_ID", "WEBUSER_ID", "REPORTPARAM_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINT_ID", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "COSTCENTER_ID", "COSTCENTER_CODE", "COSTCENTER_DESC", "ACTIVITY_ID", "ACTIVITY_CODE", "ACTIVITY_ACTIVE", "PRODUCTGROUP_ID", "PRODUCTGROUP_CODE", "PRODUCT_ID", "PRODUCT_CODE", "SIZEDEFINITION_ID", "SIZE_CODE", "FINISHINGMETHOD_ID", "FINISHING_CODE", "ACTIVITY_DESC", "PRODUCTGROUP_DESC", "PRODUCT_DESC", "SIZE_DESC", "FINISHING_DESC", "SIZESEQUENCENR", "PLANNEDQTY", "DELQTY", "LANGUAGE_CODE", "PRODUCTDESCRIPTIONONLY") AS 
  select cast(wus.websession_id as varchar2(50)) websession_id, wuc.webuser_id,rp.reportparam_id,
cu.customer_id, cu.customernumber, cu.name customername, de.department_id, de.departmentnumber, de.description departmentdesc,
dp.distributionpoint_id, dp.distributionpointnumber, dp.description distributionpointdesc,
cc.costcenter_id, cc.code CostCenter_code, cc.description CostCenter_desc,
ac.activity_id, ac.code activity_code, ac.active activity_active, pg.productgroup_id, pg.code productgroup_code,
pr.product_id, pr.code product_code, sd.sizedefinition_id, sd.code size_code, fm.finishingmethod_id, fm.code finishing_code,
(select acd.description from activity_desc acd where acd.activity_id = ac.activity_id and acd.language_id = lan.language_id) activity_desc,
(select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pg.productgroup_id and pgd.language_id = lan.language_id) productgroup_desc,
(select pd.description from product_desc pd where pd.product_id = pr.product_id and pd.language_id = lan.language_id) product_desc,
(select sdd.description from SizeDefinition_desc sdd where sdd.sizedefinition_id = sd.sizedefinition_id and sdd.language_id = lan.language_id) size_desc,
(select fmd.description from FinishingMethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id and fmd.language_id = lan.language_id) finishing_desc,
(select ps.sequencenumber from productsize ps where ps.product_id = pr.product_id and ps.sizedefinition_id = sd.sizedefinition_id) SizeSequenceNr,
rp.number_value2 plannedqty,
 coalesce((select sum(pnl.deliveredamount) from packingnote pn, packingnoteline pnl , status st
where pn.packingnote_id=pnl.packingnote_id and pn.status_id=st.status_id and st.code='30' and pn.distributionpoint_id=dp.distributionpoint_id
and pnl.product_id=pr.product_id and pnl.sizedefinition_id=sd.sizedefinition_id and pnl.finishingmethod_id=fm.finishingmethod_id
and pnl.freeofchargereason_id is null and pn.deliverydate>=rp.date_value1 and pn.deliverydate<=rp.date_value2),0)delqty,
lan.code Language_Code, wu.productdescriptiononly
from ProductListPerDistribPoint PLPD, standarddelivery sdy, DistributionPoint DP, Department DE, Customer CU, CostCENTER CC,
  Activity AC, ProductGroup PG, Product PR, SizeDefinition SD, FinishingMethod FM, languages lan, --Currency CY,
  webusercustomer wuc,--left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  webusersession wus, webuser wu, reportparam rp
where plpd.distributionpoint_id = dp.distributionpoint_id
  and dp.department_id = de.department_id
  and de.customer_id = cu.customer_id
  and dp.costcenter_id = cc.costcenter_id
  and cc.customer_id = cu.customer_id
  and plpd.product_id = pr.product_id
  and pr.productgroup_id = pg.productgroup_id
  and pg.activity_id = ac.activity_id
  and plpd.sizedefinition_id = sd.sizedefinition_id
  and plpd.finishingmethod_id = fm.finishingmethod_id  --  and cy.currency_id = cu.currency_id
  and wuc.customer_id = cu.customer_id
  and wu.webuser_id = wus.webuser_id
  and wuc.webuser_id = wu.webuser_id
  and sdy.allowrecalcplanneddata = 1
  and cu.allowrecalcplanneddata = 1
  and sdy.sequencenumber = 1
  and plpd.productlistperdistribpoint_id=rp.number_value
  and wus.websession_id=rp.string_value
  and lan.code=rp.string_value1
  and wu.webuser_id=rp.number_value1
  and exists ( select 1 from standarddeliveryline sdl where  sdl.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
                      and sdy.standarddelivery_id = sdl.standarddelivery_id)
  and (NOT EXISTS (SELECT 1 FROM WEBUSERDEPARTMENT WDEP, WEBUSERCUSTOMER WCUST
                   WHERE WCUST.WEBUSER_ID = WU.WEBUSER_ID
                         AND WDEP.WEBUSERCUSTOMER_ID = WCUST.WEBUSERCUSTOMER_ID
                         AND WCUST.CUSTOMER_ID = Cu.CUSTOMER_ID)
       OR
       EXISTS (SELECT 1 FROM WEBUSERDEPARTMENT WDEP, WEBUSERCUSTOMER WCUST
               WHERE WDEP.DEPARTMENT_ID = DE.DEPARTMENT_ID
                     AND WCUST.WEBUSER_ID = WU.WEBUSER_ID
                     AND WCUST.CUSTOMER_ID = Cu.CUSTOMER_ID
                     AND WDEP.WEBUSERCUSTOMER_ID = WCUST.WEBUSERCUSTOMER_ID)
       )
/

  CREATE OR REPLACE VIEW "V_WEBPROPORTIONSDELQTY" ("WEBSESSION_ID", "WEBUSER_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINT_ID", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "COSTCENTER_ID", "COSTCENTER_CODE", "COSTCENTER_DESC", "ACTIVITY_ID", "ACTIVITY_CODE", "ACTIVITY_ACTIVE", "PRODUCTGROUP_ID", "PRODUCTGROUP_CODE", "PRODUCT_ID", "PRODUCT_CODE", "SIZEDEFINITION_ID", "SIZE_CODE", "FINISHINGMETHOD_ID", "FINISHING_CODE", "ACTIVITY_DESC", "PRODUCTGROUP_DESC", "PRODUCT_DESC", "SIZE_DESC", "FINISHING_DESC", "DELIVERYDATE", "NOTENUMBER", "DELIVEREDAMOUNT", "DELIVEREDCOGQTY", "PRICE", "CURRENCYCODE", "CURRENCYDESC", "PRODUCTDESCRIPTIONONLY", "LANGUAGE_CODE") AS 
  select cast(wus.websession_id as varchar2(50)) websession_id, wuc.webuser_id,
cu.customer_id, cu.customernumber, cu.name customername, de.department_id, de.departmentnumber, de.description departmentdesc,
dp.distributionpoint_id, dp.distributionpointnumber, dp.description distributionpointdesc,
cc.costcenter_id, cc.code CostCenter_code, cc.description CostCenter_desc,
ac.activity_id, ac.code activity_code, ac.active activity_active, pg.productgroup_id, pg.code productgroup_code,
pr.product_id, pr.code product_code, sd.sizedefinition_id, sd.code size_code, fm.finishingmethod_id, fm.code finishing_code,
(select acd.description from activity_desc acd where acd.activity_id = ac.activity_id and acd.language_id = lan.language_id) activity_desc,
(select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pg.productgroup_id and pgd.language_id = lan.language_id) productgroup_desc,
(select pd.description from product_desc pd where pd.product_id = pr.product_id and pd.language_id = lan.language_id) product_desc,
(select sdd.description from SizeDefinition_desc sdd where sdd.sizedefinition_id = sd.sizedefinition_id and sdd.language_id = lan.language_id) size_desc,
(select fmd.description from FinishingMethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id and fmd.language_id = lan.language_id) finishing_desc,
pn.deliverydate, pn.notenumber, pnl.deliveredamount, pnl.deliveredcogqty, --pnl.price,
PACK_PRICE.Wash_Price(cu.customer_id, pr.product_id, sd.sizedefinition_id, fm.finishingmethod_id, pn.deliverydate) price,
cy.code CurrencyCode, cy.description CurrencyDesc, wu.productdescriptiononly, lan.code Language_Code
from PackingNote PN, PackingNoteLine PNL, DistributionPoint DP, Department DE, Customer CU, CostCENTER CC,
  Activity AC, ProductGroup PG, Product PR, SizeDefinition SD, FinishingMethod FM, Currency CY, languages lan,
  webusercustomer wuc,--left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  webusersession wus, webuser wu
where pn.distributionpoint_id = dp.distributionpoint_id
  and dp.department_id = de.department_id
  and de.customer_id = cu.customer_id
  and dp.costcenter_id = cc.costcenter_id
  and cc.customer_id = cu.customer_id
  and pnl.packingnote_id = pn.packingnote_id
  and pnl.product_id = pr.product_id
  and pr.productgroup_id = pg.productgroup_id
  and pg.activity_id = ac.activity_id
  and pnl.sizedefinition_id = sd.sizedefinition_id
  and pnl.finishingmethod_id = fm.finishingmethod_id
  and pn.status_id =(select s.status_id from status s where s.statustype='PN' and s.code='30')
  and pn.freeofchargereason_id is null
  and cy.currency_id = cu.currency_id
  and wuc.customer_id = cu.customer_id
  and wu.webuser_id = wus.webuser_id
  and wuc.webuser_id = wu.webuser_id
  and (NOT EXISTS (SELECT 1 FROM WEBUSERDEPARTMENT WDEP, WEBUSERCUSTOMER WCUST
                   WHERE WCUST.WEBUSER_ID = WU.WEBUSER_ID
                         AND WDEP.WEBUSERCUSTOMER_ID = WCUST.WEBUSERCUSTOMER_ID
                         AND WCUST.CUSTOMER_ID = Cu.CUSTOMER_ID)
       OR
       EXISTS (SELECT 1 FROM WEBUSERDEPARTMENT WDEP, WEBUSERCUSTOMER WCUST
               WHERE WDEP.DEPARTMENT_ID = DE.DEPARTMENT_ID
                     AND WCUST.WEBUSER_ID = WU.WEBUSER_ID
                     AND WCUST.CUSTOMER_ID = Cu.CUSTOMER_ID
                     AND WDEP.WEBUSERCUSTOMER_ID = WCUST.WEBUSERCUSTOMER_ID)
       )
/

  CREATE OR REPLACE VIEW "V_WEBPWBCHECKPOINTSCANS" ("CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "STATUSCHANGEDATE", "LASTSTAYDATE", "CURRENTDATE", "CLIENT_ID", "CLIENTNUMBER", "CLIENTNAME", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "ROOMNUMBER", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTDESC", "FINISHINGMETHOD_ID", "FINMETHCODE", "FINMETHDESC", "URIPRIMARYID", "NUMBEROFWASHES", "UNIQUERESIDENTIALITEM_ID", "LASTINSCANDATE", "LASTOUTSCANDATE", "REMARK", "SCANTIMESTAMP", "SCANDATE", "PRIMARYID", "ADMINNUMBER", "LANGUAGECODE", "WEBUSERDEPARTMENT_ID", "WEBSESSION_ID", "WEBUSER_ID") AS 
  select cl.customer_id, cus.customernumber, cus.name customername,
  uri.statuschangedate, uri.laststaydate, trunc(sysdate) currentdate,
  cl.client_id, cl.clientnumber, cl.name clientname,
  d.department_id, d.departmentnumber, d.description departmentdesc, dr.roomnumber,
  pr.product_id product_id,
  pr.code productcode,
  (select prd.description from product_desc prd where prd.product_id = pr.product_id
     and prd.language_id = languages.language_id) productdesc,
  fm.finishingmethod_id, fm.code finmethcode,
  (select fmd.description from finishingcode_desc fmd where fmd.finishingcode_id = fm.finishingmethod_id
     and fmd.language_id = languages.language_id) finmethdesc,
  uri.primaryid uriprimaryid,
  uri.numberofwashes,
  uri.uniqueresidentialitem_id,
  uri.lastinscandate, uri.lastoutscandate, uri.remark
  , ris.scantimestamp, trunc(ris.scantimestamp) scandate, ris.primaryid,
  cl.adminnumber,
  languages.code languagecode,
  wd.department_id webuserdepartment_id,
  cast(wus.websession_id as varchar2(60)) websession_id,
  wc.webuser_id webuser_id
from customer cus, client cl,
    residentialitemscan ris
      left outer join (departmentroom dr
        inner join department d on d.department_id = dr.department_id)
      on dr.departmentroom_id = ris.departmentroom_id,
  uniqueresidentialitem uri,
  product pr, finishingmethod fm,
  languages,
  webusercustomer wc
    left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  webusersession wus
where cus.customer_id = cl.customer_id
  and cl.client_id = uri.client_id
  and ris.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id
  and ris.customer_link_id = cl.customer_id
  and ris.transactiontype_id = 6 --Checkpoint Scan
  and ris.product_link_id = pr.product_id
  and ris.finishingmethod_id = fm.finishingmethod_id
  and wc.customer_id = cl.customer_id
  and wus.customer_id = wc.customer_id
/

  CREATE OR REPLACE VIEW "V_WEBPWEARERINSCANDATE" ("WEBSESSION_ID", "WEBUSER_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "DISTRIBUTIONPOINT_ID", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "COSTCENTER_ID", "COSTCENTER_CODE", "COSTCENTER_DESC", "PRODUCTGROUP_ID", "PRODUCTGROUP_CODE", "PRODUCT_ID", "PRODUCT_CODE", "SIZEDEFINITION_ID", "SIZE_CODE", "FINISHINGMETHOD_ID", "FINISHING_CODE", "PRODUCTGROUP_DESC", "PRODUCT_DESC", "SIZE_DESC", "FINISHING_DESC", "WEARERFUNCTION_ID", "WEARERFUNCTION_CODE", "WEARERFUNCTION_DESC", "WEARER_ID", "WEARERNUMBER", "WEARERNAME", "WEARER_DATEACTIVE", "WEARER_DATEINACTIVE", "WEARERACTIVE", "UNIQUEITEM_ID", "PRIMARYID", "LASTINSCANDATE", "LASTOUTSCANDATE", "WASHESTOTAL", "PRODUCTDESCRIPTIONONLY", "LANGUAGECODE") AS 
  select wus.websession_id, wuc.webuser_id,
cu.customer_id, cu.customernumber, cu.name customername, d.department_id, d.departmentnumber, d.description departmentdesc,
dp.distributionpoint_id, dp.distributionpointnumber, dp.description distributionpointdesc,
cc.costcenter_id, cc.code CostCenter_code, cc.description CostCenter_desc,
pg.productgroup_id, pg.code productgroup_code, p.product_id, p.code product_code,
sd.sizedefinition_id, sd.code size_code, fm.finishingmethod_id, fm.code finishing_code,
(select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pg.productgroup_id and pgd.language_id = lan.language_id) productgroup_desc,
(select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = lan.language_id) product_desc,
(select sdd.description from SizeDefinition_desc sdd where sdd.sizedefinition_id = sd.sizedefinition_id and sdd.language_id = lan.language_id) size_desc,
(select fmd.description from FinishingMethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id and fmd.language_id = lan.language_id) finishing_desc,
wf.wearerfunction_id, wf.code WearerFunction_Code, wf.description WearerFunction_Desc,
we.wearer_id, we.wearernumber, we.fullname wearername, we.dateactive Wearer_dateactive, we.dateinactive Wearer_dateinactive,
GETDATEDIFF(trunc(sysdate), we.dateactive)*GETDATEDIFF(we.dateinactive, trunc(sysdate)) weareractive,
ui.uniqueitem_id, ui.primaryid, ui.lastinscandate, ui.lastoutscandate, ui.washestotal, wu.productdescriptiononly,
lan.code LanguageCode
from Customer Cu, DistributionPoint DP, Department D, CostCenter CC, ProductGroup PG, Product P, SizeDefinition SD, FinishingMethod FM,
UniqueItem UI, UniqueItemNonPool UINP, Wearer WE,   weareremployment wey left outer join WearerFunction WF on wey.wearerfunction_id = wf.wearerfunction_id
, languages lan,
  webusercustomer wuc,--left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  webusersession wus, webuser wu
where we.customer_id = cu.customer_id
 -- and wf.customer_id = cu.customer_id
  --and wey.wearerfunction_id = wf.wearerfunction_id
  and wey.wearer_id = we.wearer_id
  and wey.distributionpoint_id = dp.distributionpoint_id
  and dp.department_id = d.department_id
  and d.customer_id = cu.customer_id
  and dp.costcenter_id = cc.costcenter_id
  and cc.customer_id = cu.customer_id
 -- and ui.distributionpoint_id = dp.distributionpoint_id
  and UINP.Uniqueitem_Id = UI.Uniqueitem_Id
  and uinp.weareremployment_id=wey.weareremployment_id
  and ui.product_id = p.product_id
  and p.productgroup_id = pg.productgroup_id
  and ui.sizedefinition_id = sd.sizedefinition_id
  and ui.finishingmethod_id = fm.finishingmethod_id
  and wuc.customer_id = cu.customer_id
  and wu.webuser_id = wus.webuser_id
  and wuc.webuser_id = wu.webuser_id
  and (NOT EXISTS (SELECT 1 FROM WEBUSERDEPARTMENT WDEP, WEBUSERCUSTOMER WCUST
                   WHERE WCUST.WEBUSER_ID = WU.WEBUSER_ID
                         AND WDEP.WEBUSERCUSTOMER_ID = WCUST.WEBUSERCUSTOMER_ID
                         AND WCUST.CUSTOMER_ID = Cu.CUSTOMER_ID)
       OR
       EXISTS (SELECT 1 FROM WEBUSERDEPARTMENT WDEP, WEBUSERCUSTOMER WCUST
               WHERE WDEP.DEPARTMENT_ID = D.DEPARTMENT_ID
                     AND WCUST.WEBUSER_ID = WU.WEBUSER_ID
                     AND WCUST.CUSTOMER_ID = Cu.CUSTOMER_ID
                     AND WDEP.WEBUSERCUSTOMER_ID = WCUST.WEBUSERCUSTOMER_ID)
       )
/

  CREATE OR REPLACE VIEW "V_WEBSCANSPERWEARER" ("CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "WEARERNUMBER", "WEARERNAME", "PRIMARYID", "PRODUCTCODE", "SIZECODE", "SIZEDESC", "PRODUCTDESC", "YEAR", "WEEK", "DAYNO", "DAYCODE", "SCANTIMESTAMP", "SCANDATE", "TRANSACTIONTYPE_ID", "TRANSACTIONTYPEDESC", "FACTORYDESCRIPTION", "LANGUAGECODE", "REASON_CODE", "DELIVERYPOINT_ID", "COSTCENTER_ID", "DEPARTMENT_ID", "WEARERFUNCTION_ID", "PRODUCT_ID", "WEARER_ID") AS 
  select --count(*)
  culk.customernumber, culk.name customerName, culk.customer_id, delk.departmentnumber, delk.description departmentDesc
, wylk.wearernumber, wylk.wearername, scan.primaryid
, prdlk.code ProductCode, szlk.code SizeCode
, (select szlkd.description from sizedefinition_link_desc szlkd where szlkd.sizedefinition_link_id = szlk.sizedefinition_link_id and szlkd.language_id = languages.language_id) sizedesc
, (select product_desc.description from product_desc where product_desc.product_id = prdlk.product_id
  and product_desc.language_id = languages.language_id ) ProductDesc
, scan.year, scan.week, scan.dayno
, (select day_desc.code from day_desc where day_desc.day_id = scan.dayno
  and day_desc.language_id = languages.language_id) dayCode--, ((scan.year*100)+scan.week) YEARWEEK
, to_char(scan.scantimestamp, 'HH24.MI.SS') scantimestamp--, TO_TIMESTAMP(to_char(scan.scantimestamp, 'DD-MON-YY HH.MI.SS AM')) scantimestamp
, scan.scantimestamp ScanDate, transactiontype.transactiontype_id
, (select transactiontype_desc.description from transactiontype_desc where transactiontype_desc.transactiontype_id = transactiontype.transactiontype_id and transactiontype_desc.language_id = languages.language_id ) transactiontypeDesc
, transactiontype.factorydescription, languages.code languageCode
, (select rc.code from reasoncode rc where scan.reasoncode_id = rc.reasoncode_id) reason_code
, (select we.deliverypoint_id from weareremployment we where we.weareremployment_id = wylk.weareremployment_id) deliverypoint_id
, (select dp.costcenter_id from distributionpoint dp where dp.distributionpoint_id = dilk.distributionpoint_id) costcenter_id
, delk.department_id
, (select we.wearerfunction_id from weareremployment we where we.weareremployment_id = wylk.weareremployment_id) wearerfunction_id
, prdlk.product_id
, (select we.wearer_id from weareremployment we where we.weareremployment_id = wylk.weareremployment_id) wearer_id
from
  scan, customer_link culk, distributionpoint_link dilk, department_link delk, weareremployment_link wylk
, product_link prdlk, sizedefinition_link szlk, transactiontype
, languages
WHERE --    scan.customer_link_id = culk.customer_link_id        and scan.distributionpoint_link_id = dilk.distributionpoint_link_id    and dilk.department_link_id = delk.department_link_id    and delk.customer_link_id = culk.customer_link_id */
    scan.weareremployment_link_id = wylk.weareremployment_link_id
         and wylk.distributionpoint_link_id = dilk.distributionpoint_link_id
             and dilk.department_link_id = delk.department_link_id
                 and delk.customer_link_id = culk.customer_link_id
and scan.product_link_id = prdlk.product_link_id
and scan.sizedefinition_link_id = szlk.sizedefinition_link_id
and scan.transactiontype_id = transactiontype.transactiontype_id
    and (transactiontype.transactiontype_id <> 0
         and transactiontype.transactiontype_id <> 10
         and transactiontype.transactiontype_id <> 11
         and transactiontype.transactiontype_id <> 40
         and transactiontype.transactiontype_id <> 41
         and transactiontype.transactiontype_id <> 50
         and transactiontype.transactiontype_id <> 53
         and transactiontype.transactiontype_id <> 60
         and transactiontype.transactiontype_id <> 70
         and transactiontype.transactiontype_id <> 71
         and transactiontype.transactiontype_id <> 72
         and transactiontype.transactiontype_id <> 73
         and transactiontype.transactiontype_id <> 99) --and transactiontype.transactiontype_id not in (0, 10, 11, 40, 41, 50, 53, 60, 70, 71, 72, 73, 99)
/

  CREATE OR REPLACE VIEW "V_WEBUNIQUERESIDENTIALITEMS" ("CUSTOMER_ID", "STATUSCODE", "STAY_ID", "STATUSCHANGEDATE", "LASTSTAYDATE", "CURRENTDATE", "CLIENT_ID", "CLIENTNUMBER", "CLIENTNAME", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "ROOMNUMBER", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTDESC", "SIZECODE", "FINISHINGMETHOD_ID", "FINMETHCODE", "FINMETHDESC", "PRIMARYID", "STATUSDESC", "STAYDESC", "LASTSCANDATE", "NUMBEROFWASHES", "UNIQUERESIDENTIALITEM_ID", "FLAG_ID", "STARTDATE", "FREETEXTITEM", "USEINWEBAPPLICATION", "FLAGCODE", "FLAGDESC", "LASTINSCANDATE", "LASTOUTSCANDATE", "REMARK", "ASSIGNDATE", "LANGUAGECODE", "WEBUSERDEPARTMENT_ID", "WEBSESSION_ID", "WEBUSER_ID") AS 
  select cl.customer_id, st.code statuscode, sy.stay_id, uri.statuschangedate, uri.laststaydate, trunc(sysdate) currentdate, cl.client_id, cl.clientnumber,
       cl.name clientname, d.department_id, d.departmentnumber, d.description departmentdesc, dr.roomnumber, pr.product_id product_id,
       coalesce((select plpc.customcode from productlistpercustomer plpc
                  where plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC(cl.customer_id, urip.product_id, urip.sizedefinition_id, urip.finishingmethod_id,
                                                         (select szstar.sizedefinition_id from sizedefinition szstar where szstar.code = '*'), trunc(sysdate), 0))
              , pr.code) productcode,
       coalesce((select plpc.customdescription from productlistpercustomer plpc
                  where plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC(cl.customer_id, urip.product_id, urip.sizedefinition_id, urip.finishingmethod_id,
                                                         (select szstar.sizedefinition_id from sizedefinition szstar where szstar.code = '*'), trunc(sysdate), 0))
              , (select prd.description
                   from product_desc prd
                  where prd.product_id = pr.product_id
                    and prd.language_id = lan.language_id)) productdesc,
       sz.code sizecode, fm.finishingmethod_id finishingmethod_id, fm.code finmethcode,
       (select fmd.description
          from finishingcode_desc fmd
         where fmd.finishingcode_id = fm.finishingmethod_id
           and fmd.language_id = lan.language_id) finmethdesc, uri.primaryid,
       (select std.description
          from status_desc std
         where std.status_id = st.status_id
           and std.language_id = lan.language_id) statusdesc,
       (select syd.description
          from stay_desc syd
         where syd.stay_id = sy.stay_id
           and syd.language_id = lan.language_id) staydesc,
       (select max(ris.scantimestamp) from residentialitemscan ris where ris.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id) lastscandate,
       uri.numberofwashes, uri.uniqueresidentialitem_id, urif.flag_id, urif.startdate, urif.freetextitem,
       (select f.useinwebapplication from flag f where f.flag_id = urif.flag_id) useinwebapplication,
       (select f.code from flag f where f.flag_id = urif.flag_id) flagcode,
       (select fd.description
          from flag_desc fd
         where fd.language_id = lan.language_id
           and fd.flag_id = urif.flag_id) flagdesc,
       uri.lastinscandate, uri.lastoutscandate, uri.remark, urip.assigndate, lan.code languagecode,
       (select wd.department_id
          from webuserdepartment wd
         where wc.webusercustomer_id = wd.webusercustomer_id) webuserdepartment_id,
       wus.websession_id websession_id, wc.webuser_id webuser_id
  from uniqueresidentialitemproduct urip
  join uniqueresidentialitem uri
       left join clientresident cr
            join departmentroom dr
                 join department d on dr.department_id = d.department_id
            on cr.departmentroom_id = dr.departmentroom_id
       on uri.client_id = cr.client_id
       left join uniqueresidentialitemflag urif on uri.uniqueresidentialitem_id = urif.uniqueresidentialitem_id
       join client cl
            join webusercustomer wc on cl.customer_id = wc.customer_id
            join webusersession wus on cl.customer_id = wus.customer_id
       on uri.client_id = cl.client_id
       join status st on uri.status_id = st.status_id
       join stay sy on uri.stay_id = sy.stay_id
  on urip.uniqueresidentialitem_id = uri.uniqueresidentialitem_id
  join product pr on urip.product_id = pr.product_id
  join sizedefinition sz on urip.sizedefinition_id = sz.sizedefinition_id
  join finishingmethod fm on urip.finishingmethod_id = fm.finishingmethod_id
  , languages lan
union all
select cl.customer_id, st.code statuscode, sy.stay_id, uri.statuschangedate, uri.laststaydate, trunc(sysdate) currentdate, cl.client_id, cl.clientnumber,
       cl.name clientname, d.department_id, d.departmentnumber, d.description departmentdesc, dr.roomnumber, null productid, null productcode,
       null productdesc, null sizecode, null finishingmethod_id, null finmethcode, null finmethdesc, uri.primaryid,
       (select std.description
          from status_desc std
         where std.status_id = st.status_id
           and std.language_id = lan.language_id) statusdesc,
       (select syd.description
          from stay_desc syd
         where syd.stay_id = sy.stay_id
           and syd.language_id = lan.language_id) staydesc,
       (select max(ris.scantimestamp) from residentialitemscan ris where ris.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id) lastscandate,
       uri.numberofwashes, uri.uniqueresidentialitem_id, urif.flag_id, urif.startdate, urif.freetextitem,
       (select f.useinwebapplication from flag f where f.flag_id = urif.flag_id) useinwebapplication,
       (select f.code from flag f where f.flag_id = urif.flag_id) flagcode,
       (select fd.description
          from flag_desc fd
         where fd.language_id = lan.language_id
           and fd.flag_id = urif.flag_id) flagdesc,
       uri.lastinscandate, uri.lastoutscandate, uri.remark, null assigndate, lan.code languagecode,
       (select wd.department_id
          from webuserdepartment wd
         where wc.webusercustomer_id = wd.webusercustomer_id) webuserdepartment_id,
       wus.websession_id websession_id, wc.webuser_id webuser_id
  from uniqueresidentialitem uri
  left join clientresident cr
       join departmentroom dr
            join department d on dr.department_id = d.department_id
       on cr.departmentroom_id = dr.departmentroom_id
  on uri.client_id = cr.client_id
  left join uniqueresidentialitemflag urif on uri.uniqueresidentialitem_id = urif.uniqueresidentialitem_id
  join client cl
       join webusercustomer wc on cl.customer_id = wc.customer_id
       join webusersession wus on cl.customer_id = wus.customer_id
  on uri.client_id = cl.client_id
  join status st on uri.status_id = st.status_id
  join stay sy on uri.stay_id = sy.stay_id
  , languages lan
 where not exists (select 1 from uniqueresidentialitemproduct urip2 where urip2.uniqueresidentialitem_id = uri.uniqueresidentialitem_id)
/

  CREATE OR REPLACE VIEW "V_WEBWEARERINVENTORYREPORT" ("WEBSESSION_ID", "WEBUSER_ID", "DEPARTMENT_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMERCITY", "WEARERNUMBER", "WEARERSEARCHNAME", "WEARER_ID", "WEARERNAME", "ADMINNUMBER", "EMPLOYMENT", "WEARERFUNCTIONCODE", "WEARERFUNCTIONDESC", "WEARERFUNCTION_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "COSTCENTERCODE", "COSTCENTERDESCRIPTION", "COSTCENTER_ID", "BANK", "LOCKER", "BANKLOCKER", "GARMENTDISPENSERCODE", "GARMENTDISPENSERDESC", "DELIVERYPOINT_ID_G", "DELIVERYPOINT_ID_L", "DELIVERYPOINT_ID_W", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "SEQUENCENUMBER", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "MAXINVENTORY", "CHANGESPERWEEK", "CIRCINVENTORY", "MODIFICATIONSQTY", "STARTDATE", "ENDDATE", "SEASONDESCRIPTION", "EMBLEMTEMPLATEDESC", "CUSTOMERLANGUAGECODE", "WEARERACTIVE", "LANGUAGECODE", "PRODUCTDESCRIPTIONONLY") AS 
  select wus.websession_id, wc.webuser_id, DEPARTMENT.DEPARTMENT_ID,--WD.DEPARTMENT_ID WEBUSERDEPARTMENT_ID,
  cu.customer_id, cu.customernumber, cu.name CustomerName, address.city CustomerCity, we.wearernumber
, we.searchname wearersearchname, we.wearer_id
, we.fullname WearerName, we.customeremployeenumber AdminNumber, wey.sequencenumber Employment
, wearerfunction.code wearerfunctionCode, wearerfunction.description wearerfunctionDesc, wearerfunction.wearerfunction_id
, department.departmentnumber, department.description departmentDescription, costcenter.code costcenterCode
, costcenter.description costcenterDescription, costcenter.costcenter_id, locker.bank, locker.locker
--, CONCATENATE(LEFTPAD(LOCKER.BANK, 6, '0'), LEFTPAD(LOCKER.LOCKER, 6, '0')) banklocker
, cast(CONCATENATE(LEFTPAD(LOCKER.BANK, 6, '0'), LEFTPAD(LOCKER.LOCKER, 6, '0')) as varchar2(30)) banklocker
, garmentdispenser.code garmentdispenserCode
, garmentdispenser.description garmentdispenserDesc
, garmentdispenser.deliverypoint_id deliverypoint_id_g
, locker.deliverypoint_id deliverypoint_id_l
, wey.deliverypoint_id deliverypoint_id_w
, prd.product_id
,cast(RIGHTPAD(F_GETPRODUCTCODE(prd.code, cu.customer_id, prd.product_id, sizedefinition.sizedefinition_id, finishingmethod.finishingmethod_id),12,' ') as varchar2(30)) ProductCode
,cast(RIGHTPAD(F_GETPRODUCTDESC(cu.customer_id, prd.product_id, sizedefinition.sizedefinition_id, finishingmethod.finishingmethod_id, languages.language_id),30,' ') as varchar2(30)) ProductDescription
--,RIGHTPAD(F_GETPRODUCTCODE(prd.code, cu.customer_id, prd.product_id, sizedefinition.sizedefinition_id, finishingmethod.finishingmethod_id),12,' ') ProductCode
--,RIGHTPAD(F_GETPRODUCTDESC(cu.customer_id, prd.product_id, sizedefinition.sizedefinition_id, finishingmethod.finishingmethod_id, languages.language_id),30,' ') ProductDescription
, sizedefinition.code sizedefinitionCode, ps.sequencenumber, finishingmethod.code finishingmethodCode
,(select description from finishingmethod_desc where languages.language_id = finishingmethod_desc.language_id
and finishingmethod_desc.finishingmethod_id = finishingmethod.finishingmethod_id) FinishingmethodDescription
, wearerinventory.maxinventory, wearerinventory.changesperweek, wearerinventory.circinventory
, (select count(wm.modification_id) from wearerinventorymodification wm where wm.wearerinventory_id = wearerinventory.wearerinventory_id)ModificationsQty
, wearerinventory.dateactive StartDate, wearerinventory.dateinactive EndDate
, (select seasontype_desc.description from seasontype_desc,season where wearerinventory.season_id = season.season_id
and season.seasontype_id = seasontype_desc.seasontype_id and seasontype_desc.language_id = languages.language_id) SeasonDescription
, emblemtemplate.description emblemtemplateDesc
, (select code from languages where languages.language_id = cu.language_id) CustomerLanguageCode
, GETDATEDIFF(trunc(sysdate), we.dateactive)*GETDATEDIFF(we.dateinactive, trunc(sysdate)) wearerActive
, languages.code languageCode,wu.productdescriptiononly productdescriptiononly
from
  weareremployment wey
    left outer join wearerfunction on (wey.wearerfunction_id = wearerfunction.wearerfunction_id)
    left outer join locker on wey.locker_id = locker.locker_id
    left outer join garmentdispenser on wey.garmentdispenser_id = garmentdispenser.garmentdispenser_id,
  wearer we, customer cu, address, distributionpoint, department, costcenter,
  wearerinventory
    left outer join emblemtemplate on wearerinventory.emblemtemplate_id = emblemtemplate.emblemtemplate_id,
  product prd, sizedefinition, finishingmethod, productsize ps, languages,
  webusercustomer wc,
    --left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  webusersession wus, webuser wu
where we.customer_id = cu.customer_id
  and cu.visitaddress_id = address.address_id
  and we.wearer_id = wey.wearer_id
  and wey.distributionpoint_id = distributionpoint.distributionpoint_id
  and distributionpoint.department_id = department.department_id
  and department.customer_id = cu.customer_id
  and distributionpoint.costcenter_id = costcenter.costcenter_id
  and costcenter.customer_id = cu.customer_id
  and wey.weareremployment_id = wearerinventory.weareremployment_id
  and wearerinventory.product_id = prd.product_id
  and wearerinventory.sizedefinition_id = sizedefinition.sizedefinition_id
  and wearerinventory.finishingmethod_id = finishingmethod.finishingmethod_id
  and wc.customer_id = cu.customer_id
  and ps.product_id = prd.product_id
  and ps.sizedefinition_id = sizedefinition.sizedefinition_id
  and wu.webuser_id = wus.webuser_id
  and wc.webuser_id=wu.webuser_id
  and (NOT EXISTS (SELECT 1 FROM WEBUSERDEPARTMENT WDEP, WEBUSERCUSTOMER WCUST
                   WHERE WCUST.WEBUSER_ID = WU.WEBUSER_ID
                         AND WDEP.WEBUSERCUSTOMER_ID = WCUST.WEBUSERCUSTOMER_ID
                         AND WCUST.CUSTOMER_ID = CU.CUSTOMER_ID)
       OR
       EXISTS (SELECT 1 FROM WEBUSERDEPARTMENT WDEP, WEBUSERCUSTOMER WCUST
               WHERE WDEP.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
                     AND WCUST.WEBUSER_ID = WU.WEBUSER_ID
                     AND WCUST.CUSTOMER_ID = DEPARTMENT.CUSTOMER_ID
                     AND WDEP.WEBUSERCUSTOMER_ID = WCUST.WEBUSERCUSTOMER_ID)
       )
/

  CREATE OR REPLACE VIEW "V_WEBWEARERINVENTRPT_OLDWEBAPP" ("WEBSESSION_ID", "WEBUSER_ID", "WEBUSERDEPARTMENT_ID", "DEPARTMENT_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMERCITY", "WEARERNUMBER", "WEARERSEARCHNAME", "WEARER_ID", "WEARERNAME", "ADMINNUMBER", "EMPLOYMENT", "WEARERFUNCTIONCODE", "WEARERFUNCTIONDESC", "WEARERFUNCTION_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "COSTCENTERCODE", "COSTCENTERDESCRIPTION", "COSTCENTER_ID", "BANK", "LOCKER", "BANKLOCKER", "GARMENTDISPENSERCODE", "GARMENTDISPENSERDESC", "DELIVERYPOINT_ID_G", "DELIVERYPOINT_ID_L", "DELIVERYPOINT_ID_W", "PRODUCT_ID", "PRODUCTCODE", "PRODUCTDESCRIPTION", "SIZEDEFINITIONCODE", "SEQUENCENUMBER", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "MAXINVENTORY", "CHANGESPERWEEK", "CIRCINVENTORY", "MODIFICATIONSQTY", "STARTDATE", "ENDDATE", "SEASONDESCRIPTION", "EMBLEMTEMPLATEDESC", "CUSTOMERLANGUAGECODE", "WEARERACTIVE", "LANGUAGECODE", "PRODUCTDESCRIPTIONONLY") AS 
  select ws.websession_id, wc.webuser_id, WD.DEPARTMENT_ID WEBUSERDEPARTMENT_ID, DEPARTMENT.DEPARTMENT_ID,
  cu.customernumber, cu.name CustomerName, address.city CustomerCity, we.wearernumber
, we.searchname wearersearchname, we.wearer_id
, we.fullname WearerName, we.customeremployeenumber AdminNumber, wey.sequencenumber Employment
, wearerfunction.code wearerfunctionCode, wearerfunction.description wearerfunctionDesc, wearerfunction.wearerfunction_id
, department.departmentnumber, department.description departmentDescription, costcenter.code costcenterCode
, costcenter.description costcenterDescription, costcenter.costcenter_id, locker.bank, locker.locker
--, CONCATENATE(LEFTPAD(LOCKER.BANK, 6, '0'), LEFTPAD(LOCKER.LOCKER, 6, '0')) banklocker
, cast(CONCATENATE(LEFTPAD(LOCKER.BANK, 6, '0'), LEFTPAD(LOCKER.LOCKER, 6, '0')) as varchar2(30)) banklocker
, garmentdispenser.code garmentdispenserCode
, garmentdispenser.description garmentdispenserDesc
, garmentdispenser.deliverypoint_id deliverypoint_id_g
, locker.deliverypoint_id deliverypoint_id_l
, wey.deliverypoint_id deliverypoint_id_w
, prd.product_id
, cast(F_GETPRODUCTCODE(prd.code, cu.customer_id, prd.product_id, sizedefinition.sizedefinition_id, finishingmethod.finishingmethod_id) as varchar2(30)) ProductCode
, cast(RIGHTPAD(F_GETPRODUCTDESC(cu.customer_id, prd.product_id, sizedefinition.sizedefinition_id, finishingmethod.finishingmethod_id, languages.language_id),30,' ') as varchar2(30)) ProductDescription
, sizedefinition.code sizedefinitionCode, ps.sequencenumber, finishingmethod.code finishingmethodCode
,(select description from finishingmethod_desc where languages.language_id = finishingmethod_desc.language_id
and finishingmethod_desc.finishingmethod_id = finishingmethod.finishingmethod_id) FinishingmethodDescription
, wearerinventory.maxinventory, wearerinventory.changesperweek, wearerinventory.circinventory
, (select count(wm.modification_id) from wearerinventorymodification wm where wm.wearerinventory_id = wearerinventory.wearerinventory_id)ModificationsQty
, wearerinventory.dateactive StartDate, wearerinventory.dateinactive EndDate
, (select seasontype_desc.description from seasontype_desc,season where wearerinventory.season_id = season.season_id
and season.seasontype_id = seasontype_desc.seasontype_id and seasontype_desc.language_id = languages.language_id) SeasonDescription
, emblemtemplate.description emblemtemplateDesc
, (select code from languages where languages.language_id = cu.language_id) CustomerLanguageCode
, GETDATEDIFF(trunc(sysdate), we.dateactive)*GETDATEDIFF(we.dateinactive, trunc(sysdate)) wearerActive
, languages.code languageCode,wu.productdescriptiononly productdescriptiononly
from
  weareremployment wey
    left outer join wearerfunction on (wey.wearerfunction_id = wearerfunction.wearerfunction_id)
    left outer join locker on wey.locker_id = locker.locker_id
    left outer join garmentdispenser on wey.garmentdispenser_id = garmentdispenser.garmentdispenser_id,
  wearer we, customer cu, address, distributionpoint, department, costcenter,
  wearerinventory
    left outer join emblemtemplate on wearerinventory.emblemtemplate_id = emblemtemplate.emblemtemplate_id,
  product prd, sizedefinition, finishingmethod, productsize ps, languages,
  webusercustomer wc
    left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  websession ws, webuser wu
where we.customer_id = cu.customer_id
  and cu.visitaddress_id = address.address_id
  and we.wearer_id = wey.wearer_id
  and wey.distributionpoint_id = distributionpoint.distributionpoint_id
  and distributionpoint.department_id = department.department_id
  and department.customer_id = cu.customer_id
  and distributionpoint.costcenter_id = costcenter.costcenter_id
  and costcenter.customer_id = cu.customer_id
  and wey.weareremployment_id = wearerinventory.weareremployment_id
  and wearerinventory.product_id = prd.product_id
  and wearerinventory.sizedefinition_id = sizedefinition.sizedefinition_id
  and wearerinventory.finishingmethod_id = finishingmethod.finishingmethod_id
  and wc.customer_id = cu.customer_id
  and ps.product_id = prd.product_id
  and ps.sizedefinition_id = sizedefinition.sizedefinition_id
  and cu.customer_id = ws.customer_id
  and wc.webuser_id=wu.webuser_id
/

  CREATE OR REPLACE VIEW "V_WEBWEARERPRICES" ("WEARERNUMBER", "WEARERNAME", "CUSTOMEREMPLOYEENUMBER", "YEAR", "WEEK", "BANK", "LOCKER", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENT_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESC", "COSTCENTER_ID", "COSTCENTERCODE", "COSTCENTERDESC", "DELIVERYPOINT_ID", "DELIVERYPOINTCODE", "DELIVERYPOINTDESC", "DISTRIBUTIONPOINT_ID", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESC", "PRODUCT_CODE", "PRODUCT_DESC", "SIZE_CODE", "FINISHING_CODE", "BILLINGMETHOD", "PRICEUSAGE", "QTYRENTEDPERPIECE", "RENT_PRICE", "WASH_PRICE", "QTYWASH", "DECIMALS", "INVOICEAMOUNTDECIMALS", "LANGUAGE_CODE", "REPORTPARAM_ID", "WEBUSER_ID", "WEBSESSION_ID", "WEBUSERDEPARTMENT_ID") AS 
  select WR.WearerNumber, WR.Fullname WearerName, WR.CustomerEmployeeNumber, SQ.Year, SQ.Week
       , Lo.Bank, Lo.Locker, cu.Customer_ID, cu.CustomerNumber, cu.Name CustomerName
       , dep.department_id, Dep.DepartmentNumber, Dep.Description DepartmentDesc
       , cc.costcenter_id, cc.Code CostCenterCode, cc.Description  CostCenterDesc
       , dp.deliverypoint_id, DP.Code deliverypointCode, dp.description deliverypointDesc
       , dip.distributionpoint_id, Dip.DistributionPointNumber, dip.description DistributionPointDesc
       , coalesce(PLPC.CustomCode, (select plk.Code from product_link plk where plk.product_link_id = SQIC.Product_Link_Id)) product_code
       , coalesce(PLPC.CustomDescription , (select pld.description from product_link_desc pld where pld.product_link_id = SQIC.Product_Link_Id
         and pld.language_id = lan.language_id)) product_desc
       , (select szk.Code from SizeDefinition_Link szk where szk.Sizedefinition_Link_Id = SQIC.Sizedefinition_Link_Id) Size_code
       , (select fm.Code from finishingmethod fm where fm.Finishingmethod_Id = SQIC.Finishingmethod_Id) Finishing_code
       , PLPC.BillingMethod, PLPC.PriceUsage, SQIC.QtyRentedPerPiece
       , Pack_Price.Rent_Price(WR.Customer_ID, SQIC.Product_Link_ID, SQIC.SizeDefinition_Link_ID, SQIC.FinishingMethod_ID, getdateforweekyear(1, SQ.Week, SQ.Year)) Rent_Price
       , Pack_Price.Wash_Price(WR.Customer_ID, SQIC.Product_Link_ID, SQIC.SizeDefinition_Link_ID, SQIC.FinishingMethod_ID, getdateforweekyear(1, SQ.Week, SQ.Year)) Wash_Price
       , (select Count(1) from DeliveryScan DS, PackingNote PN where DS.Customer_Link_ID = cu.customer_id and DS.WearerEmployment_Link_ID = SQIC.WearerEmployment_Link_ID
         and DS.Product_Link_ID = SQIC.Product_Link_ID and DS.SizeDefinition_Link_ID = SQIC.SizeDefinition_Link_ID and DS.FinishingMethod_ID = SQIC.FinishingMethod_ID
         and ds.distributionpoint_link_id=dip.distributionpoint_id and ds.deliverypoint_link_id=dp.deliverypoint_id
         and DS.OutscanNoDelivery = 0 and DS.PackingNote_ID=pn.packingnote_id
         and pn.DeliveryDate >= rp.date_value1 and pn.DeliveryDate <= rp.date_value2) QtyWash
       , curr.Decimals, curr.Invoiceamountdecimals
       , lan.code Language_Code, rp.reportparam_id
       , wu.webuser_id, wus.websession_id, --wud.department_id
       -1 webuserdepartment_id
from StatusQuoHeader SQ, SQitemInCirculation SQIC, deliverypoint dp,
     ProductListPerCustomer PLPC, Wearer WR, WearerEmployment WE
     left outer join Locker Lo on lo.locker_id = we.locker_id
     left outer join GarmentDispenser GD on gd.garmentdispenser_id = we.garmentdispenser_id
     , distributionpoint dip, department dep, costcenter cc, customer cu, currency curr
     , languages lan, reportparam rp, webuser wu, webusersession wus, webusercustomer wuc
    -- left outer join webuserdepartment wud on (wuc.webusercustomer_id = wud.webusercustomer_id)
where WE.Wearer_ID = WR.Wearer_ID
and dp.deliverypoint_id = coalesce(Lo.DeliveryPoint_ID, gd.DeliveryPoint_ID, WE.DeliveryPoint_ID)
and SQIC.WearerEmployment_Link_ID = WE.WearerEmployment_ID
and SQIC.StatusQuoHeader_ID = SQ.StatusQuoHeader_ID
and SQIC.Product_Link_Id = PLPC.Product_Id
and (SQIC.Sizedefinition_Link_Id = PLPC.Sizedefinition_Id OR
    (PLPC.Sizedefinition_Id in (select sds.sizedefinition_id from sizedefinition sds where sds.code = '*')))
and SQIC.Finishingmethod_Id = PLPC.Finishingmethod_Id
and SQIC.Customer_Link_Id=cu.customer_id
and WR.Customer_ID = cu.customer_id
and cu.customer_id = PLPC.Customer_ID
and cu.currency_id = curr.currency_id
and dp.customer_id=cu.customer_id
and we.distributionpoint_id = dip.distributionpoint_id
and dip.department_id = dep.department_id
and dep.costcenter_id = cc.costcenter_id
and dep.customer_id = cu.customer_id
and cc.customer_id=cu.customer_id
--and wus.customer_id = cu.customer_id
and wu.webuser_id = wuc.webuser_id
and wuc.customer_id = cu.customer_id
and (SQIC.Totalcircinv > 0 or SQIC.Maxinv > 0 or SQIC.Maxfreeinv > 0)
--and coalesce(wud.department_id, dep.department_id) = dep.department_id
and wu.language_id = lan.language_id
--and cu.customer_id = rp.number_value
and wus.websession_id = rp.string_value
and wu.webuser_id = rp.number_value5
and lan.code = rp.string_value1
and (SQ.Year > rp.number_value1 OR
  (SQ.Year = rp.number_value1 AND SQ.Week >= rp.number_value3))
AND (SQ.Year < rp.number_value2 OR
  (SQ.Year = rp.number_value2 AND SQ.Week <= rp.number_value4))
and wu.webuser_id = wus.webuser_id
and (NOT EXISTS (SELECT 1 FROM WEBUSERDEPARTMENT WDEP, WEBUSERCUSTOMER WCUST
                            WHERE WCUST.WEBUSER_ID = WU.WEBUSER_ID
                                  AND WDEP.WEBUSERCUSTOMER_ID = WCUST.WEBUSERCUSTOMER_ID
                                  AND WCUST.CUSTOMER_ID = CU.CUSTOMER_ID)
       OR
       EXISTS (SELECT 1 FROM WEBUSERDEPARTMENT WDEP, WEBUSERCUSTOMER WCUST
                             WHERE WDEP.DEPARTMENT_ID = DEP.DEPARTMENT_ID
                                   AND WCUST.WEBUSER_ID = WU.WEBUSER_ID
                                   AND WCUST.CUSTOMER_ID = DEP.CUSTOMER_ID
                                   AND WDEP.WEBUSERCUSTOMER_ID = WCUST.WEBUSERCUSTOMER_ID))
/

  CREATE OR REPLACE VIEW "V_WEBWEARERSDETAILS" ("WEBSESSION_ID", "WEBUSER_ID", "WEBUSERDEPARTMENT_ID", "DEPARTMENT_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "WEARERNAME", "WEARERSEARCHNAME", "ADMINNUMBER", "WEARER_ID", "WEARERFUNCTIONCODE", "WEARERFUNCTIONDESCRIPTION", "WEARERFUNCTION_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DELIVERYPOINTCODEL", "DELIVERYPOINTDESCRIPTIONL", "DELIVERYPOINTCODEG", "DELIVERYPOINTDESCRIPTIONG", "DELIVERYPOINTCODEW", "DELIVERYPOINTDESCRIPTIONW", "DELIVERYPOINT_ID_L", "DELIVERYPOINT_ID_G", "DELIVERYPOINT_ID_W", "COSTCENTERCODE", "COSTCENTERDESCRIPTION", "COSTCENTER_ID", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "EMPLOYEMENT", "BANK", "LOCKER", "GARMENTDISPENSERCODE", "GARMENTDISPENSERDESCRIPTION", "CITY", "WEARERACTIVE") AS 
  SELECT wus.websession_id, wc.webuser_id, WD.DEPARTMENT_ID WEBUSERDEPARTMENT_ID, DEPARTMENT.DEPARTMENT_ID,
  CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME customername,
  WEARER.WEARERNUMBER, WEARER.FULLNAME WEARERNAME, WEARER.SEARCHNAME WEARERSEARCHNAME,
  WEARER.CUSTOMEREMPLOYEENUMBER ADMINNUMBER, WEARER.WEARER_ID,
  WEARERFUNCTION.CODE wearerfunctioncode, WEARERFUNCTION.DESCRIPTION wearerfunctiondescription, WEARERFUNCTION.WEARERFUNCTION_ID,
  DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION departmentdescription,
  DPL.CODE deliverypointcodel, DPL.DESCRIPTION deliverypointdescriptionl,
  DPG.CODE deliverypointcodeg, DPG.DESCRIPTION deliverypointdescriptiong,
  DELIVERYPOINT.CODE deliverypointcodew, DELIVERYPOINT.DESCRIPTION deliverypointdescriptionw,
	DPL.DELIVERYPOINT_ID DELIVERYPOINT_ID_L,
	DPG.DELIVERYPOINT_ID DELIVERYPOINT_ID_G,
	WEAREREMPLOYMENT.DELIVERYPOINT_ID DELIVERYPOINT_ID_W,
  COSTCENTER.CODE COSTCENTERCODE, COSTCENTER.DESCRIPTION COSTCENTERDESCRIPTION, COSTCENTER.COSTCENTER_ID,
  DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION distributionpointdescription,
  WEAREREMPLOYMENT.SEQUENCENUMBER EMPLOYEMENT,
  LOCKER.BANK bank, LOCKER.LOCKER locker,
  GARMENTDISPENSER.CODE garmentdispensercode, GARMENTDISPENSER.DESCRIPTION garmentdispenserdescription,
  ADR.CITY,
  GETDATEDIFF(trunc(sysdate), WEARER.dateactive)*GETDATEDIFF(WEARER.dateinactive, trunc(sysdate)) wearerActive
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT, WEARER, COSTCENTER, address adr,
  WEAREREMPLOYMENT
    LEFT OUTER JOIN (LOCKER LEFT JOIN DELIVERYPOINT DPL ON LOCKER.DELIVERYPOINT_ID = DPL.DELIVERYPOINT_ID)
      ON (WEAREREMPLOYMENT.LOCKER_ID = LOCKER.LOCKER_ID)
    LEFT OUTER JOIN (GARMENTDISPENSER LEFT JOIN DELIVERYPOINT DPG ON GARMENTDISPENSER.DELIVERYPOINT_ID = DPG.DELIVERYPOINT_ID)
      ON (WEAREREMPLOYMENT.GARMENTDISPENSER_ID = GARMENTDISPENSER.GARMENTDISPENSER_ID)
    LEFT OUTER JOIN DELIVERYPOINT  ON (WEAREREMPLOYMENT.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID)
		LEFT OUTER JOIN WEARERFUNCTION  ON (WEAREREMPLOYMENT.WEARERFUNCTION_ID = WEARERFUNCTION.WEARERFUNCTION_ID),
    webusercustomer wc
    left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  webusersession wus
WHERE WEARER.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
    AND WEARER.WEARER_ID = WEAREREMPLOYMENT.WEARER_ID
    AND WEAREREMPLOYMENT.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
    AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
    AND DISTRIBUTIONPOINT.COSTCENTER_ID = COSTCENTER.COSTCENTER_ID
    AND CUSTOMER.VISITADDRESS_ID = ADR.ADDRESS_ID
    and wc.customer_id = customer.customer_id
    and customer.customer_id = wus.customer_id
/

  CREATE OR REPLACE VIEW "V_WEBWEARERSDETAILS_OLDAPP" ("WEBSESSION_ID", "WEBUSER_ID", "WEBUSERDEPARTMENT_ID", "DEPARTMENT_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEARERNUMBER", "WEARERNAME", "WEARERSEARCHNAME", "ADMINNUMBER", "WEARER_ID", "WEARERFUNCTIONCODE", "WEARERFUNCTIONDESCRIPTION", "WEARERFUNCTION_ID", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DELIVERYPOINTCODEL", "DELIVERYPOINTDESCRIPTIONL", "DELIVERYPOINTCODEG", "DELIVERYPOINTDESCRIPTIONG", "DELIVERYPOINTCODEW", "DELIVERYPOINTDESCRIPTIONW", "DELIVERYPOINT_ID_L", "DELIVERYPOINT_ID_G", "DELIVERYPOINT_ID_W", "COSTCENTERCODE", "COSTCENTERDESCRIPTION", "COSTCENTER_ID", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "EMPLOYEMENT", "BANK", "LOCKER", "GARMENTDISPENSERCODE", "GARMENTDISPENSERDESCRIPTION", "CITY", "WEARERACTIVE") AS 
  SELECT ws.websession_id, wc.webuser_id, WD.DEPARTMENT_ID WEBUSERDEPARTMENT_ID, DEPARTMENT.DEPARTMENT_ID,
  CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME customername,
  WEARER.WEARERNUMBER, WEARER.FULLNAME WEARERNAME, WEARER.SEARCHNAME WEARERSEARCHNAME,
  WEARER.CUSTOMEREMPLOYEENUMBER ADMINNUMBER, WEARER.WEARER_ID,
  WEARERFUNCTION.CODE wearerfunctioncode, WEARERFUNCTION.DESCRIPTION wearerfunctiondescription, WEARERFUNCTION.WEARERFUNCTION_ID,
  DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION departmentdescription,
  DPL.CODE deliverypointcodel, DPL.DESCRIPTION deliverypointdescriptionl,
  DPG.CODE deliverypointcodeg, DPG.DESCRIPTION deliverypointdescriptiong,
  DELIVERYPOINT.CODE deliverypointcodew, DELIVERYPOINT.DESCRIPTION deliverypointdescriptionw,
  DPL.DELIVERYPOINT_ID DELIVERYPOINT_ID_L,
  DPG.DELIVERYPOINT_ID DELIVERYPOINT_ID_G,
  WEAREREMPLOYMENT.DELIVERYPOINT_ID DELIVERYPOINT_ID_W,
  COSTCENTER.CODE COSTCENTERCODE, COSTCENTER.DESCRIPTION COSTCENTERDESCRIPTION, COSTCENTER.COSTCENTER_ID,
  DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION distributionpointdescription,
  WEAREREMPLOYMENT.SEQUENCENUMBER EMPLOYEMENT,
  LOCKER.BANK bank, LOCKER.LOCKER locker,
  GARMENTDISPENSER.CODE garmentdispensercode, GARMENTDISPENSER.DESCRIPTION garmentdispenserdescription,
  ADR.CITY,
  GETDATEDIFF(trunc(sysdate), WEARER.dateactive)*GETDATEDIFF(WEARER.dateinactive, trunc(sysdate)) wearerActive
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT, WEARER, COSTCENTER, address adr,
  WEAREREMPLOYMENT
    LEFT OUTER JOIN (LOCKER LEFT JOIN DELIVERYPOINT DPL ON LOCKER.DELIVERYPOINT_ID = DPL.DELIVERYPOINT_ID)
      ON (WEAREREMPLOYMENT.LOCKER_ID = LOCKER.LOCKER_ID)
    LEFT OUTER JOIN (GARMENTDISPENSER LEFT JOIN DELIVERYPOINT DPG ON GARMENTDISPENSER.DELIVERYPOINT_ID = DPG.DELIVERYPOINT_ID)
      ON (WEAREREMPLOYMENT.GARMENTDISPENSER_ID = GARMENTDISPENSER.GARMENTDISPENSER_ID)
    LEFT OUTER JOIN DELIVERYPOINT  ON (WEAREREMPLOYMENT.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID)
    LEFT OUTER JOIN WEARERFUNCTION  ON (WEAREREMPLOYMENT.WEARERFUNCTION_ID = WEARERFUNCTION.WEARERFUNCTION_ID),
    webusercustomer wc
    left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  websession ws
WHERE WEARER.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
    AND WEARER.WEARER_ID = WEAREREMPLOYMENT.WEARER_ID
    AND WEAREREMPLOYMENT.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
    AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
    AND DISTRIBUTIONPOINT.COSTCENTER_ID = COSTCENTER.COSTCENTER_ID
    AND CUSTOMER.VISITADDRESS_ID = ADR.ADDRESS_ID
    and wc.customer_id = customer.customer_id
    and customer.customer_id = ws.customer_id
/

  CREATE OR REPLACE VIEW "V_WEBWORKORDER" ("WEBSESSION_ID", "WEBUSER_ID", "DEPARTMENT_ID", "WORKORDER_ID", "WORKORDERNUMBER", "ORDERDATE", "REFERENCENUMBER", "ORDERREMARK", "DELIVERYDATE", "ENTRYDATE", "DOCKET", "SCHEDULEDDELIVERY", "CUSTOMERNUMBER", "NAME", "CUSTOMER_ID", "STREET", "ZIPCODE", "CITY", "WEARERNR", "WEARERNAME", "WEARERSEARCHNAME", "ADMIN", "EMPLNR", "CUPBOARD", "LOCKER", "GARMENTDISPENSER", "DELIVERYPOINT", "DEPARTMENT", "DEPARTMENTNUMBER", "NAMEONLABEL", "CONSPOINT", "WEARERFUNCTION", "WEARERREMARK", "ROUTENUMBER", "ROUTEDESCRIPTION", "NOTLAUNDRYOWNED", "STATUSCODE", "REASONCODE", "SHOWGARMENTGRADE", "PRODUCTDESCRIPTIONONLY", "DELIVERYPOINT_ID", "REASONCODE_ID", "COSTCENTER_ID", "WEARER_ID") AS 
  select wus.websession_id, wc.webuser_id, DEPARTMENT.DEPARTMENT_ID,--WD.DEPARTMENT_ID WEBUSERDEPARTMENT_ID,
  wok.workorder_id, wok.workordernumber, wok.requestdate OrderDate, wok.referencenumber
, wok.remark OrderRemark,
--wok.neededdate DeliveryDate,
wok.completiondate DeliveryDate,
wok.entrydate,
wok.workordernumber Docket
--, wok.expectedcompletedate ScheduledDelivery,
, wok.neededdate ScheduledDelivery,
cu.customernumber, cu.name, cu.customer_id
, address.street, address.zipcode, address.city, w.wearernumber WearerNr, w.fullname WearerName
, w.searchname wearersearchname
, w.customeremployeenumber Admin, welk.sequencenumber EmplNr, lo.bank CupBoard, lo.locker
, ga.code GarmentDispenser, de.code DeliveryPoint, department.description Department
, department.departmentnumber
, w.emblemname NameOnLabel, distributionpoint.description ConsPoint, wearerfunction.description wearerfunction
, w.remark WearerRemark, route.routenumber, route.description RouteDescription
, wok.customerowned NotLaundryOwned, status.code StatusCode
, rc.code ReasonCode, wu.showgarmentgrade, wu.productdescriptiononly
, we.deliverypoint_id
, rc.reasoncode_id
, distributionpoint.costcenter_id
, we.wearer_id
from
  workorder wok
    left outer join route on wok.route_id = route.route_id,
  weareremployment_LINK welk,
  weareremployment we
    left outer join wearerfunction on we.wearerfunction_id = wearerfunction.wearerfunction_id
    left outer join wearer w on w.wearer_id = we.wearer_id
    left outer join locker lo on we.locker_id=lo.locker_id
    left outer join garmentdispenser ga on we.garmentdispenser_id=ga.garmentdispenser_id
    left outer join deliverypoint de on we.deliverypoint_id=de.deliverypoint_id,
  distributionpoint, department, customer cu, address, status,
  webusercustomer wc,
    --left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  webusersession wus, reasoncode rc, webuser wu
where wok.weareremployment_link_id = welk.weareremployment_link_id
  and welk.weareremployment_id = we.weareremployment_id
  and distributionpoint.distributionpoint_id=we.distributionpoint_id
  and distributionpoint.department_id = department.department_id
  and cu.customer_id = department.customer_id
  and cu.visitaddress_id=address.address_id
  and wok.status_id = status.status_id
  and wc.customer_id = cu.customer_id
  and wu.webuser_id = wus.webuser_id
  and status.statustype = 'WO'
  and wok.reasoncode_id = rc.reasoncode_id
  and wu.webuser_id=wc.webuser_id
  and (NOT EXISTS (SELECT 1 FROM WEBUSERDEPARTMENT WDEP, WEBUSERCUSTOMER WCUST
                            WHERE WCUST.WEBUSER_ID = WU.WEBUSER_ID
                                  AND WDEP.WEBUSERCUSTOMER_ID = WCUST.WEBUSERCUSTOMER_ID
                                  AND WCUST.CUSTOMER_ID = CU.CUSTOMER_ID)
       OR
       EXISTS (SELECT 1 FROM WEBUSERDEPARTMENT WDEP, WEBUSERCUSTOMER WCUST
                             WHERE WDEP.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
                                   AND WCUST.WEBUSER_ID = WU.WEBUSER_ID
                                   AND WCUST.CUSTOMER_ID = DEPARTMENT.CUSTOMER_ID
                                   AND WDEP.WEBUSERCUSTOMER_ID = WCUST.WEBUSERCUSTOMER_ID))
/

  CREATE OR REPLACE VIEW "V_WEBWORKORDEREMBLEM" ("WORKORDER_ID", "WORKORDERLINE_ID", "LANGUAGECODE", "EMBLEMNR", "EMBLEMDESCRIPTION", "EMBLEMTYPE", "SIZESHAPE", "BACKGROUND", "BORDER", "TEXT", "QUANTITY", "PLACEMENT", "PUTEMBLEMON", "WORKORDERLINEEMBLEM_ID", "FABRIC", "PRODUCT_ID", "SIZEDEFINITION_ID") AS 
  select
  workorderline.workorder_id, workorderline.workorderline_id,languages.code LanguageCode
, p.code EmblemNr
, (select product_desc.description from product_desc where p.product_id = product_desc.product_id
  and product_desc.language_id = languages.language_id ) EmblemDescription
, EmblemType, sizedefinition.code SizeShape, color.code Background, c.code Border, txt.code Text
, wokem.qtyrequested Quantity , placement.code Placement, product_link.code PutEmblemOn
, wokem.workorderlineemblem_id, fabric.code fabric --, e.font --not used in the report
, wokem.product_id, wokem.sizedefinition_id
from
  workorderlineemblem wokem
          left outer join sizedefinition on  sizedefinition.sizedefinition_id = wokem.sizedefinition_id
          left outer join
                     (emblemproduct e
                                left outer join  color txt on e.textcolor_id = txt.color_id
                                left outer join color c on c.color_id = e.bordercolor_id )
                 on wokem.product_id = e.product_id
           left outer join placement on placement.placement_id = wokem.placement_id
, languages ,color, workorderline , product p, fabric
, product_link left outer join productsize on product_link.product_id = productsize.product_id
 where
     wokem.product_id is not null
and wokem.emblemtemplateline_id is null
and workorderline.workorderline_id = wokem.workorderline_id
    and wokem.product_id = p.product_id
        and p.color_id = color.color_id
        and p.fabric_id = fabric.fabric_id
and workorderline.product_link_id = product_link.product_link_id
  UNION ALL
select
  workorderline.workorder_id, workorderline.workorderline_id,languages.code LanguageCode
, p.code EmblemNr
, coalesce((select product_desc.description from product_desc where product_desc.product_id = p.product_id
  and product_desc.language_id = languages.language_id)
  , emblemtemplateline.description) EmblemDescription
, emblemtemplateline.emblemtype EmblemType, sizedefinition.code SizeShape, color.code Background
, c.code Border, txt.code Text, wokem.qtyrequested Quantity , placement.code Placement
, product_link.code PutEmblemOn
, wokem.workorderlineemblem_id, fabric.code fabric --, e.font --not used in the report
, wokem.product_id, wokem.sizedefinition_id
from
  workorderlineemblem wokem
      left outer join placement on placement.placement_id = wokem.placement_id
, emblemtemplateline
      left outer join
              (emblemproduct e
               left outer join  color txt on e.textcolor_id = txt.color_id
               left outer join color c on c.color_id = e.bordercolor_id )
          on  emblemtemplateline.product_id = e.product_id
, workorderline, fabric
, product_link left outer join productsize on product_link.product_id = productsize.product_id
, sizedefinition, languages
, product p left outer join color  on  p.color_id = color.color_id
where
    wokem.emblemtemplateline_id is not null
and wokem.product_id is null
and emblemtemplateline.product_id is not null
and emblemtemplateline.product_id = p.product_id
    and p.fabric_id = fabric.fabric_id
and workorderline.product_link_id = product_link.product_link_id
and workorderline.workorderline_id = wokem.workorderline_id
and wokem.emblemtemplateline_id = emblemtemplateline.emblemtemplateline_id
and sizedefinition.sizedefinition_id = emblemtemplateline.sizedefinition_id
  UNION ALL
select
  workorderline.workorder_id, workorderline.workorderline_id, languages.code LanguageCode
, emblemtemplate.code EmblemNr
, coalesce( emblemtemplateline.description,
              cast(CONCATENATEWITHBLANK(txt.code, fabric.code) as varchar2(255))
                 ) EmblemDescription
, emblemtemplateline.emblemtype EmblemType, sizedefinition.code SizeShape, color.code Background
, c.code Border, txt.code Text, wokem.qtyrequested Quantity ,placement.code Placement
, product_link.code PutEmblemOn
, wokem.workorderlineemblem_id, fabric.code fabric --, emblemtemplateline.font --not used in the report
, wokem.product_id, wokem.sizedefinition_id
from
  workorderlineemblem wokem
, emblemtemplateline
       left outer join color on emblemtemplateline.bkgcolor_id = color.color_id
       left outer join color c on emblemtemplateline.bordercolor_id = c.color_id
       left outer join placement on placement.placement_id = emblemtemplateline.placement_id
       left outer join color txt on emblemtemplateline.textcolor_id = txt.color_id
, workorderline, fabric
, product_link left outer join productsize on product_link.product_id = productsize.product_id
, emblemtemplate, sizedefinition, languages
where
    wokem.emblemtemplateline_id is not null
and wokem.product_id is null
and emblemtemplateline.product_id is null
and workorderline.product_link_id = product_link.product_link_id
and workorderline.workorderline_id = wokem.workorderline_id
    and wokem.emblemtemplateline_id = emblemtemplateline.emblemtemplateline_id
and emblemtemplate.emblemtemplate_id = emblemtemplateline.emblemtemplate_id
and sizedefinition.sizedefinition_id = emblemtemplateline.sizedefinition_id
and fabric.fabric_id = emblemtemplateline.fabric_id
/

  CREATE OR REPLACE VIEW "V_WEBWORKORDERLINE" ("WORKORDER_ID", "PRODNR", "PRODDESCRIPTION", "FINMETHCODE", "SIZECODE", "UNIQUEYN", "QUALITYGRADE", "REASONCODE_ID", "REASONCODE", "QORDER", "QDONE", "QOPEN", "MODIFICATIONCODE", "INSTRUCTIONS", "LANGUAGECODE") AS 
  select
  wokli.workorder_id
, cast(RIGHTPAD(F_GETPRODUCTCODE(prdlik.code, culik.customer_id, prdlik.product_id, sizlik.sizedefinition_id, wokli.finishingmethod_id),12,' ') as varchar2(12)) ProdNr
, cast(RIGHTPAD(F_GETPRODUCTDESC(culik.customer_id, prdlik.product_id, sizlik.sizedefinition_id, wokli.finishingmethod_id, languages.language_id),30,' ') as varchar2(30)) ProdDescription
, finishingmethod.code FinMethCode, sizlik.code SizeCode, wokli.codeuniquely UniqueYN
, ( select qualitygrade_desc.description from qualitygrade_desc where qualitygrade_desc.qualitygrade_id=qualitygrade.qualitygrade_id
  and qualitygrade_desc.language_id = languages.language_id ) QualityGrade
, wokli.reasoncode_id
, ( select reasoncode_desc.description from reasoncode_desc where reasoncode_desc.reasoncode_id=reasoncode.reasoncode_id
  and reasoncode_desc.language_id = languages.language_id ) ReasonCode
, ( wokli.quantityordered-wokli.quantitycancelled ) qOrder, wokli.quantityfilled qDone
, ( wokli.quantityordered-wokli.quantityfilled-wokli.quantitycancelled) qOpen
--  , modificationgroup.code ModificationGroupCode,
, modification.code ModificationCode, wokli.instructions, languages.code languagecode
from
  workorder wo
     left outer join customer_link culik on wo.customer_link_id = culik.customer_link_id,
   workorderline wokli
     left outer join reasoncode on wokli.reasoncode_id = reasoncode.reasoncode_id
     left outer join qualitygrade on wokli.requestedgrade_id=qualitygrade.qualitygrade_id
     left outer join finishingmethod on wokli.finishingmethod_id = finishingmethod.finishingmethod_id
     left outer join (sizedefinition_link sizlik
       left outer join sizedefinition siz on sizlik.sizedefinition_id=siz.sizedefinition_id )
     on wokli.sizedefinition_link_id=sizlik.sizedefinition_link_id
     left outer join (product_link prdlik left outer join product prd on prdlik.product_id=prd.product_id )
     on wokli.product_link_id = prdlik.product_link_id
     left outer join  ( workorderlinemodification left outer join
                  -- (
       modification -- left outer join
                      --    (modificationspergroup inner join
               --                 (modificationgroup left outer join productmodificationgroup
            --    on modificationgroup.modificationgroup_id = productmodificationgroup.modificationgroup_id)
          --    on modificationspergroup.modificationgroup_id = modificationgroup.modificationgroup_id)
         --   on modification.modification_id = modificationspergroup.modification_id)
       on workorderlinemodification.modification_id = modification.modification_id
       AND modification.useinwebapplication='Y')
     on wokli.workorderline_id = workorderlinemodification.workorderline_id
, languages
where wo.workorder_id = wokli.workorder_id
/

  CREATE OR REPLACE VIEW "V_WEBWORKORDER_OLDWEBAPP" ("WEBSESSION_ID", "WEBUSER_ID", "WEBUSERDEPARTMENT_ID", "DEPARTMENT_ID", "WORKORDER_ID", "WORKORDERNUMBER", "ORDERDATE", "REFERENCENUMBER", "ORDERREMARK", "DELIVERYDATE", "ENTRYDATE", "DOCKET", "SCHEDULEDDELIVERY", "CUSTOMERNUMBER", "NAME", "STREET", "ZIPCODE", "CITY", "WEARERNR", "WEARERNAME", "WEARERSEARCHNAME", "ADMIN", "EMPLNR", "CUPBOARD", "LOCKER", "GARMENTDISPENSER", "DELIVERYPOINT", "DEPARTMENT", "DEPARTMENTNUMBER", "NAMEONLABEL", "CONSPOINT", "WEARERFUNCTION", "WEARERREMARK", "ROUTENUMBER", "ROUTEDESCRIPTION", "NOTLAUNDRYOWNED", "STATUSCODE", "REASONCODE", "SHOWGARMENTGRADE", "PRODUCTDESCRIPTIONONLY", "DELIVERYPOINT_ID", "REASONCODE_ID", "COSTCENTER_ID", "WEARER_ID") AS 
  select ws.websession_id, wc.webuser_id, WD.DEPARTMENT_ID WEBUSERDEPARTMENT_ID, DEPARTMENT.DEPARTMENT_ID,
  wok.workorder_id, wok.workordernumber, wok.requestdate OrderDate, wok.referencenumber
, wok.remark OrderRemark,
--wok.neededdate DeliveryDate,
wok.completiondate DeliveryDate,
wok.entrydate,
wok.workordernumber Docket
--, wok.expectedcompletedate ScheduledDelivery,
, wok.neededdate ScheduledDelivery,
cu.customernumber, cu.name
, address.street, address.zipcode, address.city, w.wearernumber WearerNr, w.fullname WearerName
, w.searchname wearersearchname
, w.customeremployeenumber Admin, welk.sequencenumber EmplNr, lo.bank CupBoard, lo.locker
, ga.code GarmentDispenser, de.code DeliveryPoint, department.description Department
, department.departmentnumber
, w.emblemname NameOnLabel, distributionpoint.description ConsPoint, wearerfunction.description wearerfunction
, w.remark WearerRemark, route.routenumber, route.description RouteDescription
, wok.customerowned NotLaundryOwned, status.code StatusCode
, rc.code ReasonCode, wu.showgarmentgrade, wu.productdescriptiononly
, we.deliverypoint_id
, rc.reasoncode_id
, distributionpoint.costcenter_id
, we.wearer_id
from
  workorder wok
    left outer join route on wok.route_id = route.route_id,
  weareremployment_LINK welk,
  weareremployment we
    left outer join wearerfunction on we.wearerfunction_id = wearerfunction.wearerfunction_id
    left outer join wearer w on w.wearer_id = we.wearer_id
    left outer join locker lo on we.locker_id=lo.locker_id
    left outer join garmentdispenser ga on we.garmentdispenser_id=ga.garmentdispenser_id
    left outer join deliverypoint de on we.deliverypoint_id=de.deliverypoint_id,
  distributionpoint, department, customer cu, address, status,
  webusercustomer wc
    left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  websession ws, reasoncode rc, webuser wu
where wok.weareremployment_link_id = welk.weareremployment_link_id
  and welk.weareremployment_id = we.weareremployment_id
  and distributionpoint.distributionpoint_id=we.distributionpoint_id
  and distributionpoint.department_id = department.department_id
  and cu.customer_id = department.customer_id
  and cu.visitaddress_id=address.address_id
  and wok.status_id = status.status_id
  and wc.customer_id = cu.customer_id
  and ws.customer_id = cu.customer_id
  and status.statustype = 'WO'
  and wok.reasoncode_id = rc.reasoncode_id
  and wu.webuser_id=wc.webuser_id
/

  CREATE OR REPLACE VIEW "V_WEB_MONTHLYCSVEXPORT" ("JAAR", "MAAND", "KLANTNUMMER", "AFDELINGSNUNMMER", "AFDELINGSOMSCHRIJVING", "ARTIKELKODE", "ARTIKELKODEOMSCHRIJVING", "AANTAL", "PRIJS", "DEL_YEAR", "DEL_MONTH", "WEBSESSION_ID", "WEBUSER_ID", "WEBUSERDEPARTMENT_ID", "DEPARTMENT_ID") AS 
  select
  cast(h.year as varchar2(4)) Jaar
, cast(GETMONTHASVARCHAR(h.deliverydate) as varchar2(2)) Maand
, c.customernumber Klantnummer, t.departmentnumber afdelingsnunmmer,
 t.description afdelingsomschrijving, p.code artikelkode,
 (select s.description from product_desc s where p.product_id = s.product_id and s.language_id = c.language_id) artikelkodeomschrijving,
 sum(l.deliveredamount) aantal, w.price prijs,
year(h.deliverydate) del_year, month(h.deliverydate) del_month,
ws.websession_id, wc.webuser_id, WD.DEPARTMENT_ID WEBUSERDEPARTMENT_ID, t.department_id
from packingnoteline l, packingnote h, customer c, deliverypoint d, product p, department t,
     distributionpoint i, generalwashprice w,
     webusercustomer wc left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
     websession ws, status st
where l.packingnote_id = h.packingnote_id
and h.distributionpoint_id = i.distributionpoint_id
and c.customer_id = d.customer_id
and d.deliverypoint_id = h.deliverypoint_id
and p.product_id = l.product_id
and t.customer_id= d.customer_id
--and w.product_id = l.product_id
--and w.sizedefinition_id = l.sizedefinition_id
--and w.finishingmethod_id = l.finishingmethod_id
and t.department_id = i.department_id
and i.deliverypoint_id = d.deliverypoint_id
and wc.customer_id = c.customer_id
and w.generalwashprice_id =
    (select max(w2.generalwashprice_id) --max = only one (the most recent)
      from generalwashprice w2
      where w2.product_id = l.product_id
            and w2.sizedefinition_id = l.sizedefinition_id
            and w2.finishingmethod_id = l.finishingmethod_id
            and w2.startdate = --mmost recent date
                (select max(w3.startdate) from generalwashprice w3
                        where w3.product_id = l.product_id
                        and w3.sizedefinition_id = l.sizedefinition_id
                        and w3.finishingmethod_id = l.finishingmethod_id
                        and w3.startdate <= GETLASTDAY(h.deliverydate)
                )
    )
and st.status_id = h.status_id and st.statustype = 'PN' and st.code = '30' -- only Processed Notes
group by ws.websession_id, wc.webuser_id, WD.DEPARTMENT_ID, t.department_id,
      h.deliverydate, h.year, c.customernumber, t.departmentnumber, t.description, p.code,
      p.product_id, c.language_id, w.price
/

  CREATE OR REPLACE VIEW "V_WEEKLYSALESSUMMARY" ("INVOICEBUSINESSUNIT_ID", "BU_CODE", "BU_DESC", "PLANT_ID", "PL_CODE", "PL_NAME", "INVOICEDATE", "INVOICELINETYPE", "TURNOVERGROUP_CODE", "TURNOVERGROUP_DESC", "PRODUCT_DESC", "PRODUCT_CODE", "PRODUCTGROUPCODE", "PRODUCTGROUPDESCRIPTION", "ROUTENUMBER", "AMOUNT", "LANGUAGE_CODE") AS 
  select ih.invoicebusinessunit_id, bu.code Bu_code, bu.description Bu_desc, pl.plant_id, Pl.Code Pl_code, Pl.Name Pl_name,
       ih.invoicedate, ilt.type InvoicelineType,
       coalesce(tg.code, ilt.factorydescription) TurnoverGroup_code,
       coalesce( (select tgd.description from turnovergroup_desc tgd where tg.turnovergroup_id = tgd.turnovergroup_id and tgd.language_id = lan.language_id),'-') TurnoverGroup_desc,
       coalesce((select pd.description from product_desc pd where p.product_id = pd.product_id and pd.language_id = lan.language_id),'-') Product_desc,
       coalesce(p.code, '-') Product_code,
       coalesce (ilp.productgroupcode, '-') productgroupcode,
       coalesce(ilp.productgroupdescription, ilt.factorydescription) productgroupdescription,
       ih.routenumber,
        case when il.adjustmentreason_id is null then il.amount else il.adjustedamount end Amount,
       lan.code Language_code
from invoiceheader ih, status st, invoiceline il
       left outer join turnovergroup tg on il.turnovergroup_id = tg.turnovergroup_id
       left outer join invoicelineproduct ilp
                  join product p on ilp.product_link_id = p.product_id
       on il.invoiceline_id=ilp.invoiceline_id
, invoicelinetype ilt,  businessunit bu , plant pl, languages lan
where ih.documenttype = 1 and ih.status_id = st.status_id and st.statustype = 'IN' and st.code = 2
      and il.extend='Y'
      and ih.invoiceheader_id = il.invoiceheader_id
      and il.invoicelinetype_id = ilt.invoicelinetype_id
      --and il.invoiceline_id=ilp.invoiceline_id ---select only lines with ilp and with products linked to that ilp
      and ih.invoicebusinessunit_id = bu.businessunit_id
      and bu.plant_id = pl.plant_id
/

  CREATE OR REPLACE VIEW "V_WEEKLYVALUERENTAL" ("LINE", "BILLINGMETHOD", "CUSTOMERNUMBER", "NAME", "PRODUCTCODE", "FMCODE", "PROD_DESC", "QUANTITY", "CHANGESPERWEEK", "PRICE", "DISCOUNT") AS 
  select v.line, v.billingmethod, v.customernumber, v.name, v.productcode, v.fmcode, v.prod_desc,
sum(v.quantity) quantity, v.changesperweek, v.price, v.discount
from (select 1 line, plpc.billingmethod, c.customernumber, c.name, p.code productcode, fm.code fmcode, (select pd.description from product_desc pd where pd.product_id=p.product_id and pd.language_id=l.language_id) prod_desc ,
      sdl.fixedrentquantity quantity, 0 changesperweek, pack_price.Rent_Price(c.customer_id, p.product_id, sd.sizedefinition_id, fm.finishingmethod_id, sysdate) price,
      pack_price.Rent_Discount(c.customer_id, p.product_id, sd.sizedefinition_id, fm.finishingmethod_id, sysdate) discount
      from productlistpercustomer plpc join customer c on plpc.customer_id = c.customer_id
      join product p on plpc.product_id = p.product_id
      join finishingmethod fm on fm.finishingmethod_id = plpc.finishingmethod_id
      join standarddeliveryline sdl on plpc.productlistpercustomer_id = sdl.productlistpercustomer_id
      join sizedefinition sd on sd.sizedefinition_id = plpc.sizedefinition_id
      cross join languages l
      where plpc.dateinactive > sysdate
      and p.typeofmerchandise = 1
      and plpc.billingmethod in (1) -- changes from (1,3) to (1) to see - ref PBR
      and plpc.changesperweek = 'N'
      and sdl.fixedrentquantity <> 0
      and l.code = 'EN_GB'
      and sdl.dateinactive > sysdate) v
group by v.line, v.billingmethod, v.customernumber, v.name, v.productcode, v.fmcode, v.prod_desc, v.changesperweek,v.price,v.discount
union all
select v.line, v.billingmethod, v.customernumber, v.name, v.productcode, v.fmcode, v.prod_desc,
(select sum(rqa.quantity) from rentalqtyadjustment rqa join productlistperdistribpoint plpd on rqa.productlistperdistribpoint_id=plpd.productlistperdistribpoint_id
                                          join distributionpoint dp on plpd.distributionpoint_id=dp.distributionpoint_id
                                          join department dep on dep.department_id=dp.department_id
                                          where dep.customer_id=v.customer_id
                                          and plpd.product_id=v.product_id
                                          and plpd.finishingmethod_id=v.finishingmethod_id
) quantity, v.changesperweek, v.price,v.discount
from (select 2 line,plpc.billingmethod,  c.customernumber, c.name, c.customer_id, p.product_id, p.code productcode, fm.finishingmethod_id, fm.code fmcode,  (select pd.description from product_desc pd where pd.product_id=p.product_id and pd.language_id=l.language_id) prod_desc ,
     0 changesperweek, pack_price.Rent_Price(c.customer_id, p.product_id, sd.sizedefinition_id, fm.finishingmethod_id, sysdate) price,pack_price.Rent_Discount(c.customer_id, p.product_id, sd.sizedefinition_id, fm.finishingmethod_id, sysdate) discount
    from productlistpercustomer plpc join customer c on plpc.customer_id = c.customer_id
    join product p on plpc.product_id = p.product_id
    join finishingmethod fm on fm.finishingmethod_id = plpc.finishingmethod_id
    join standarddeliveryline sdl on plpc.productlistpercustomer_id = sdl.productlistpercustomer_id
    join sizedefinition sd on sd.sizedefinition_id = plpc.sizedefinition_id
    cross join languages l
    where plpc.dateinactive > sysdate
    and sdl.dateinactive > sysdate
    and p.typeofmerchandise = 1
    and plpc.billingmethod in (3) --changes from (1,3) to (3) to see - ref PBR
    and plpc.changesperweek = 'N'
    --and sdl.fixedrentquantity = 0  --line taken out ref PBR
    and l.code = 'EN_GB') v
group by v.line, v.productcode, v.customernumber, v.name, v.productcode, v.product_id, v.customer_id, v.finishingmethod_id, v.billingmethod,v.fmcode, v.prod_desc, v.changesperweek, v.price,v.discount
union all
select v.line, v.billingmethod , v.customernumber, v.name, v.productcode, v.fmcode, v.prod_desc,
count(distinct(v.wearerinventory_id)), v.changesperweek, v.price, v.discount
from (select 3 line, plpc.billingmethod, c.customernumber, c.name, p.code productcode, fm.code fmcode, (select pd.description from product_desc pd where pd.product_id=p.product_id and pd.language_id=l.language_id) prod_desc ,
      wi.wearerinventory_id, wi.changesperweek, pack_price.Rent_Price(c.customer_id, p.product_id, sd.sizedefinition_id, fm.finishingmethod_id, sysdate, wi.changesperweek) price
      , pack_price.Rent_Discount(c.customer_id, p.product_id, sd.sizedefinition_id, fm.finishingmethod_id, sysdate) discount
      from wearerinventory wi
      join  weareremployment we on wi.weareremployment_id = we.weareremployment_id
      join uniqueitemnonpool uinp on uinp.wearerinventory_id = wi.wearerinventory_id
      join uniqueitem ui on ui.uniqueitem_id = uinp.uniqueitem_id
      join status s on ui.status_id = s.status_id
      join wearer w on we.wearer_id = w.wearer_id
      join customer c on w.customer_id = c.customer_id
      join product p on p.product_id = wi.product_id
      join productlistpercustomer plpc on (wi.product_id = plpc.product_id and wi.finishingmethod_id = plpc.finishingmethod_id and c.customer_id = plpc.customer_id)
      join sizedefinition sd on plpc.sizedefinition_id = sd.sizedefinition_id
      join finishingmethod fm on plpc.finishingmethod_id = fm.finishingmethod_id
      cross join languages l
      where plpc.dateinactive > sysdate
      and wi.dateinactive > sysdate  -- added wearer inventory inactive date check
      and plpc.billingmethod = 1
      and p.typeofmerchandise = 2
      and plpc.changesperweek = 'Y'
      and l.code = 'EN_GB'
      and ui.status_id = 26) v
group by v.line, v.billingmethod, v.customernumber, v.name, v.productcode, v.fmcode, v.prod_desc, v.changesperweek, v.price, v.discount
union all
select v.line, v.billingmethod, v.customernumber,v.name,v.productcode,v.fmcode,  v.prod_desc,
count(distinct v.uniqueitem_id) quantity, v.changesperweek , v.price, v.discount
from (select 4 line, plpc.billingmethod, c.customernumber, c.name, p.code productcode,fm.code fmcode,  (select pd.description from product_desc pd where pd.product_id=p.product_id and pd.language_id=l.language_id) prod_desc,
      ui.uniqueitem_id, 0 changesperweek, pack_price.Rent_Price(c.customer_id, p.product_id, sd.sizedefinition_id, fm.finishingmethod_id, sysdate) price,
      pack_price.Rent_Discount(c.customer_id, p.product_id, sd.sizedefinition_id, fm.finishingmethod_id, sysdate) discount
      from uniqueitem ui join uniqueitemnonpool uinp on ui.uniqueitem_id = uinp.uniqueitem_id
      join status s on ui.status_id = s.status_id
      join weareremployment we on uinp.weareremployment_id = we.weareremployment_id
      join wearerinventory wi on (wi.weareremployment_id = we.weareremployment_id and wi.sizedefinition_id = ui.sizedefinition_id and wi.finishingmethod_id=ui.finishingmethod_id)
      join wearer w on we.wearer_id = w.wearer_id
      join customer c on c.customer_id = w.customer_id
      join productlistpercustomer plpc on (wi.product_id = plpc.product_id and wi.finishingmethod_id = plpc.finishingmethod_id and plpc.customer_id=c.customer_id)
      join product p on p.product_id = ui.product_id
      join finishingmethod fm on fm.finishingmethod_id = plpc.finishingmethod_id
      join sizedefinition sd on plpc.sizedefinition_id = sd.sizedefinition_id
      cross join languages l
      where
      plpc.dateinactive > sysdate
      and wi.dateinactive > sysdate  -- added wearer inventory inactive date check
      and plpc.billingmethod = 3
      and ui.status_id = 26
      and l.code = 'EN_GB') v
group by v.line, v.billingmethod, v.customernumber, v.name, v.productcode, v.fmcode, v.prod_desc, v.changesperweek, v.price, v.discount
/

  CREATE OR REPLACE VIEW "V_WEEKLY_SUMMARY_DELIV" ("BRANCHTYPE", "INVOICEHEADER_ID", "INVOICENUMBER", "INVOICEDATE", "INVOICEBUSINESSUNIT_ID", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "STARTDATE", "ENDDATE", "DAYS", "INVOICETYPE", "LINE_DATE", "NOTENUMBER", "DAYNUMBER", "PRODUCT_CODE", "PROD_DESC", "DEL_QTY", "GROSS", "TARE", "THEORETICALWEIGHT", "THEORETICALWEIGHT_PROD", "PRICE", "AMOUNT", "LINETYPE", "LANGUAGE_CODE", "INVOICELINE_SEQUENCENUMBER", "SIZECODE", "SIZEDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION", "PNL_SIZEDEFINITION_ID") AS 
  select --+ INDEX(pnl XIF8PACKINGNOTELINE)
      distinct 1 branchtype, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate,
       ih.invoicebusinessunit_id, ih.deltocustomernumber, ih.deltocustomername,
       ih.billtocustomernumber, ih.billtocustomername, ih.startdate, ih.enddate,
       ih.enddate - ih.startdate days, ih.invoicetype,
       pn.deliverydate line_date, pn.notenumber, pn.daynumber, il.code product_code,
       il.description prod_desc, (pnl.deliveredamount) del_qty, 0 gross,
       0 tare,
       nvl((select max(dh.pieceweight) from deliveryhistory dh where dh.distributionpoint_link_id = pn.distributionpoint_id
                   and dh.processbusinessunit_id = pn.processbusinessunit_id
                   and dh.product_link_id = pnl.product_id
                   and dh.sizedefinition_link_id = pnl.sizedefinition_id
                   and dh.finishingmethod_id = pnl.finishingmethod_id
                   and dh.deliverydate = pn.deliverydate
           ),
           (select prz.theoreticalweight from productSIZE prz
             where prz.product_id = ilp.product_link_id and
             prz.sizedefinition_id = pnl.sizedefinition_id)) theoreticalweight,
      (select prod.theoreticalweight from product prod
       where prod.product_id = ilp.product_link_id) theoreticalweight_prod,
       il.price,
       il.amount, il.invoicelinetype_id linetype, 'EN_US' language_code,
       (select pilt.sequencenumber
         from   plantinvoicelinetype pilt, businessunit bu
         where  ih.invoicebusinessunit_id = bu.businessunit_id and
                bu.plant_id = pilt.plant_id and
                pilt.invoicelinetype_id = il.invoicelinetype_id) invoiceline_sequencenumber,
       ilp.sizecode, ilp.sizedescription, ilp.finishingmethodcode,
       ilp.finishingmethoddescription, pnl.sizedefinition_id pnl_sizedefinition_id
from   invoiceheader ih, invoiceline il, invoicelineproduct ilp, packingnote pn,
       packingnoteline pnl, status st
where ih.status_id = st.status_id and st.statustype = 'IN' and st.code = '2' and
      il.invoiceheader_id = ih.invoiceheader_id and il.invoicelinetype_id =  2 and --only wash
       ilp.invoiceline_id = il.invoiceline_id and
       pnl.invoiceheader_id = ih.invoiceheader_id and
       pn.packingnote_id = pnl.packingnote_id and
       pnl.product_id = ilp.product_link_id and
       ((ilp.sizecode= '*') or (pnl.sizedefinition_id = ilp.sizedefinition_link_id)) and
       pnl.finishingmethod_id = ilp.finishingmethod_id and
       pn.freeofchargereason_id is null and pn.invoicestatus > 0
       and ilp.billingmethod <> 0
--having sum(pnl.deliveredamount) > 0 -- SSB 06.01 commented this line so that correction tickets are selected (with their negative amounts)
union all
select 2 branchtype, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate,
       ih.invoicebusinessunit_id, ih.deltocustomernumber, ih.deltocustomername,
       ih.billtocustomernumber, ih.billtocustomername, ih.startdate, ih.enddate,
       ih.enddate - ih.startdate days, ih.invoicetype, wt.weighingdate line_date, wt.ticketnumber notenumber,
       wt.daynumber, il.code product_code, il.description prod_desc,
       0 del_qty, sum(wtl.grossweight) gross, sum(wtl.tareweight) tare, null theoreticalweight,
       null theoreticalweight_prod, il.price, il.amount, il.invoicelinetype_id linetype,--3 soil or 4 clean
       'EN_US' language_code,
       (select pilt.sequencenumber
         from   plantinvoicelinetype pilt, businessunit bu
         where  ih.invoicebusinessunit_id = bu.businessunit_id and
                bu.plant_id = pilt.plant_id and
                pilt.invoicelinetype_id = 3) invoiceline_sequencenumber,
       null sizecode, null sizedescription, null finishingmethodcode,
       null finishingmethoddescription, -1 pnl_sizedefinition_id
from   invoiceheader ih, invoiceline il, invoicelineproduct ilp,
       weighingticket wt, weighingticketline wtl, status st
where ih.status_id = st.status_id and st.statustype = 'IN' and st.code = '2' and
      ih.invoiceheader_id = il.invoiceheader_id and
       il.invoiceline_id = ilp.invoiceline_id and
       ((il.invoicelinetype_id = 3 and wt.soilticket = 'Y') or   --soil weight
        (il.invoicelinetype_id = 4 and wt.soilticket = 'N')) and --clean weight
       wtl.invoiceheader_id = ih.invoiceheader_id and
       wt.weighingticket_id = wtl.weighingticket_id and
       wtl.weighingcategory_id = ilp.weighingcategory_link_id
group  by ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate,
          ih.invoicebusinessunit_id, ih.deltocustomernumber,
          ih.deltocustomername, ih.billtocustomernumber, ih.billtocustomername,
          ih.startdate, ih.enddate, ih.invoicetype, wt.weighingdate, wt.ticketnumber,
          wt.daynumber, il.code, il.description,
          il.price, il.amount, il.invoicelinetype_id
union all
select 3 branchtype, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate,
       ih.invoicebusinessunit_id, ih.deltocustomernumber, ih.deltocustomername,
       ih.billtocustomernumber, ih.billtocustomername, ih.startdate, ih.enddate,
       ih.enddate - ih.startdate days, ih.invoicetype, pn.deliverydate line_date, pn.notenumber,
       pn.daynumber, il.code product_code, il.description prod_desc,
       0 del_qty, sum(pnc.grossweight) gross, sum(pnc.tareweight) tare, null theoreticalweight,
       null theoreticalweight_prod, il.price, il.amount, 4 linetype,--clean
       'EN_US' language_code,
       (select pilt.sequencenumber
         from   plantinvoicelinetype pilt, businessunit bu
         where  ih.invoicebusinessunit_id = bu.businessunit_id and
                bu.plant_id = pilt.plant_id and
                pilt.invoicelinetype_id = 3) invoiceline_sequencenumber,
       null sizecode, null sizedescription,  null finishingmethodcode,
       null finishingmethoddescription, -1 pnl_sizedefinition_id
from   invoiceheader ih, invoiceline il, invoicelineproduct ilp, packingnote pn,
       packingnotecontainer pnc, status st
where ih.status_id = st.status_id and st.statustype = 'IN' and st.code = '2' and
      ih.invoiceheader_id = il.invoiceheader_id and
       il.invoiceline_id = ilp.invoiceline_id and il.invoicelinetype_id = 4 and --clean weight
       il.invoiceheader_id = pnc.invoiceheader_id and
       pn.packingnote_id = pnc.packingnote_id and
       pnc.weighingcategory_id = ilp.weighingcategory_link_id
group  by ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate,
          ih.invoicebusinessunit_id, ih.deltocustomernumber,
          ih.deltocustomername, ih.billtocustomernumber, ih.billtocustomername,
          ih.startdate, ih.enddate, ih.invoicetype, pn.deliverydate, pn.notenumber,
          pn.daynumber, il.code, il.description,
          il.price, il.amount
union all
select --+ index(il XP2INVOICELINE)
       4 branchtype, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate,
       ih.invoicebusinessunit_id, ih.deltocustomernumber, ih.deltocustomername,
       ih.billtocustomernumber, ih.billtocustomername, ih.startdate, ih.enddate,
       ih.enddate - ih.startdate days, ih.invoicetype, null line_date, null notenumber,
       0 daynumber, case when il.invoicelinetype_id in (16,18) then il.code else
       null end product_code, case when il.invoicelinetype_id not in (16,18) then
       coalesce(( select iltd.description
       from invoicelinetype_desc iltd, languages lg
       where iltd.invoicelinetype_id = il.invoicelinetype_id
       and iltd.language_id = lg.language_id
       and lg.code = 'EN_US'),il.description)
       else il.description end prod_desc, 0 del_qty, 0 gross, 0 tare, null theoreticalweight,
       null theoreticalweight_prod, il.price, sum(il.amount), il.invoicelinetype_id linetype,
       'EN_US' language_code,
       (select pilt.sequencenumber
         from   plantinvoicelinetype pilt, businessunit bu
         where  ih.invoicebusinessunit_id = bu.businessunit_id and
                bu.plant_id = pilt.plant_id and
                pilt.invoicelinetype_id = 3) invoiceline_sequencenumber,
       null sizecode, null sizedescription, null finishingmethodcode,
       null finishingmethoddescription, -1 pnl_sizedefinition_id
from   invoiceheader ih, invoiceline il, status st
where ih.status_id = st.status_id and st.statustype = 'IN' and st.code = '2' and
      ih.invoiceheader_id = il.invoiceheader_id and il.invoicelinetype_id not in (2,3,4) --others
group  by ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate,
          ih.invoicebusinessunit_id, ih.deltocustomernumber,
          ih.deltocustomername, ih.billtocustomernumber, ih.billtocustomername,
          ih.startdate, ih.enddate, ih.invoicetype, il.code,il.description,
          il.invoicelinetype_id, il.price
union all
select --+ INDEX(pnl XIF8PACKINGNOTELINE)
      distinct 5 branchtype, ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate,
       ih.invoicebusinessunit_id, ih.deltocustomernumber, ih.deltocustomername,
       ih.billtocustomernumber, ih.billtocustomername, ih.startdate, ih.enddate,
       ih.enddate - ih.startdate days, ih.invoicetype,
       pn.deliverydate line_date, pn.notenumber, pn.daynumber, il.code product_code,
       il.description prod_desc, (pnl.deliveredamount) del_qty, 0 gross,
       0 tare,
       nvl((select max(dh.pieceweight) from deliveryhistory dh where dh.distributionpoint_link_id = pn.distributionpoint_id
                   and dh.processbusinessunit_id = pn.processbusinessunit_id
                   and dh.product_link_id = pnl.product_id
                   and dh.sizedefinition_link_id = pnl.sizedefinition_id
                   and dh.finishingmethod_id = pnl.finishingmethod_id
                   and dh.deliverydate = pn.deliverydate
           ),
           (select prz.theoreticalweight from productSIZE prz
             where prz.product_id = ilp.product_link_id and
             prz.sizedefinition_id = pnl.sizedefinition_id)) theoreticalweight,
      (select prod.theoreticalweight from product prod
       where prod.product_id = ilp.product_link_id) theoreticalweight_prod,
       il.price,
       il.amount, il.invoicelinetype_id linetype, 'EN_US' language_code,
       (select pilt.sequencenumber
         from   plantinvoicelinetype pilt, businessunit bu
         where  ih.invoicebusinessunit_id = bu.businessunit_id and
                bu.plant_id = pilt.plant_id and
                pilt.invoicelinetype_id = il.invoicelinetype_id) invoiceline_sequencenumber,
       ilp.sizecode, ilp.sizedescription, ilp.finishingmethodcode,
       ilp.finishingmethoddescription, pnl.sizedefinition_id pnl_sizedefinition_id
from   invoiceheader ih, invoiceline il, invoicelineproduct ilp, packingnote pn,
       packingnoteline pnl, status st
where ih.status_id = st.status_id and st.statustype = 'IN' and st.code = '2' and
      il.invoiceheader_id = ih.invoiceheader_id and il.invoicelinetype_id =  2 and --only wash
       ilp.invoiceline_id = il.invoiceline_id and
       pnl.invoiceheader_id = ih.invoiceheader_id and
       pn.packingnote_id = pnl.packingnote_id and
       pnl.product_id = ilp.product_link_id and
       ((ilp.sizecode= '*') or (pnl.sizedefinition_id = ilp.sizedefinition_link_id)) and
       pnl.finishingmethod_id = ilp.finishingmethod_id and
       pn.freeofchargereason_id is null and pn.invoicestatus > 0
       and ilp.billingmethod = 0
/

  CREATE OR REPLACE VIEW "V_WEEKLY_SUMMARY_DELIV_AUX" ("BILLTOCUSTOMERNUMBER", "INVOICENUMBER", "INVOICEDATE") AS 
  select ih.billtocustomernumber, ih.invoicenumber, ih.invoicedate
from  invoiceheader ih, status st
where ih.status_id = st.status_id and st.statustype = 'IN' and st.code = '2'
/

  CREATE OR REPLACE VIEW "V_WEEKLY_SUMMARY_DELIV_H" ("INVOICEHEADER_ID", "INVOICETYPE", "ENDDATE", "STARTDATE", "DAYS", "INVOICENUMBER", "INVOICEBUSINESSUNIT_ID", "DELTOCUSTOMERNUMBER", "DELTOCUSTOMERNAME", "BILLTOCUSTOMERNUMBER", "BILLTOCUSTOMERNAME", "INVOICEDATE") AS 
  select h.invoiceheader_id, h.invoicetype, h.enddate, h.startdate, (h.enddate - h.startdate) days,
       h.invoicenumber, H.INVOICEBUSINESSUNIT_ID,
       h.deltocustomernumber, h.deltocustomername, h.billtocustomernumber, h.billtocustomername, h.invoicedate
from invoiceheader h, status st
where h.status_id = st.status_id and st.statustype = 'IN' and st.code = '2' --only final invoices
/

  CREATE OR REPLACE VIEW "V_WEEKLY_SUMMARY_DELIV_L" ("INVOICEHEADER_ID", "LINE_DATE", "DAYNUMBER", "PRODUCT_CODE", "PROD_DESC", "DEL_QTY", "GROSS", "TARE", "THEORETICALWEIGHT", "THEORETICALWEIGHT_PROD", "PRICE", "AMOUNT", "LINETYPE", "LANGUAGE_CODE", "INVOICELINE_SEQUENCENUMBER", "SIZECODE", "SIZEDESCRIPTION", "FINISHINGMETHODCODE", "FINISHINGMETHODDESCRIPTION") AS 
  select l.invoiceheader_id, n.deliverydate line_date, n.daynumber,
           l.code product_code, l.description PROD_DESC,
           sum(nl.deliveredamount) del_qty, 0 gross, 0 tare,
           0 theoreticalweight,
           (select pr.theoreticalweight from product pr
            where pr.product_id = nl.product_id) theoreticalweight_prod,
           l.price, l.amount, 2 linetype
           , languages.code language_code
           , ( SELECT pilt.sequencenumber
             from plantinvoicelinetype pilt, businessunit bu, invoiceheader h
             where l.invoiceheader_id = h.invoiceheader_id
                   and h.invoicebusinessunit_id = bu.businessunit_id
                   and bu.plant_id = pilt.plant_id
                   and pilt.invoicelinetype_id = t.invoicelinetype_id) InvoiceLine_SequenceNumber,
           P.SIZECODE, P.SIZEDESCRIPTION, P.FINISHINGMETHODCODE, P.FINISHINGMETHODDESCRIPTION
    from invoiceline l, invoicelinetype t, invoicelineproduct p,
         packingnote n, packingnoteline nl, LANGUAGES
    where --l.amount <> 0 and
          l.invoicelinetype_id = t.invoicelinetype_id
          and l.invoiceline_id = p.invoiceline_id
          and t.type = 2 --wash
          and nl.invoiceheader_id = l.invoiceheader_id
          and n.freeofchargereason_id is null
          and n.packingnote_id = nl.packingnote_id
          and nl.product_id = p.product_link_id
          and p.sizedefinition_link_id = (select sz.sizedefinition_id from sizedefinition sz where sz.code = '*')
          and nl.finishingmethod_id = p.finishingmethod_id
    group by l.invoiceheader_id, n.deliverydate, n.daynumber,
          l.code, l.description, nl.product_id,
          P.SIZECODE, P.SIZEDESCRIPTION, nl.sizedefinition_id,
          P.FINISHINGMETHODCODE, P.FINISHINGMETHODDESCRIPTION,
          l.price, l.amount, t.invoicelinetype_id, languages.code
    having sum(nl.deliveredamount) > 0
UNION ALL
    select l.invoiceheader_id, n.deliverydate line_date, n.daynumber,
           l.code product_code, l.description PROD_DESC,
           sum(nl.deliveredamount) del_qty, 0 gross, 0 tare,
           (select prz.theoreticalweight from productSIZE prz
            where prz.product_id = nl.product_id and prz.sizedefinition_id = nl.sizedefinition_id) theoreticalweight,
           (select prod.theoreticalweight from product prod
            where prod.product_id = nl.product_id) theoreticalweight_prod,
           l.price, l.amount, 2 linetype
           , languages.code language_code
           , ( SELECT pilt.sequencenumber
             from plantinvoicelinetype pilt, businessunit bu, invoiceheader h
             where l.invoiceheader_id = h.invoiceheader_id
                   and h.invoicebusinessunit_id = bu.businessunit_id
                   and bu.plant_id = pilt.plant_id
                   and pilt.invoicelinetype_id = t.invoicelinetype_id) InvoiceLine_SequenceNumber,
           P.SIZECODE, P.SIZEDESCRIPTION, P.FINISHINGMETHODCODE, P.FINISHINGMETHODDESCRIPTION
    from invoiceline l, invoicelinetype t, invoicelineproduct p,
         packingnote n, packingnoteline nl, LANGUAGES
    where --l.amount <> 0 and
          l.invoicelinetype_id = t.invoicelinetype_id
          and l.invoiceline_id = p.invoiceline_id
          and t.type = 2 --wash
          and nl.invoiceheader_id = l.invoiceheader_id
          and n.freeofchargereason_id is null
          and n.packingnote_id = nl.packingnote_id
          and nl.product_id = p.product_link_id
          and nl.sizedefinition_id = p.sizedefinition_link_id
          AND p.sizedefinition_link_id <> (select sz.sizedefinition_id from sizedefinition sz
                                      where sz.code = '*')
          and nl.finishingmethod_id = p.finishingmethod_id
    group by l.invoiceheader_id, n.deliverydate, n.daynumber,
          l.code, l.description, nl.product_id,
          P.SIZECODE, P.SIZEDESCRIPTION, nl.sizedefinition_id,
          P.FINISHINGMETHODCODE, P.FINISHINGMETHODDESCRIPTION,
          l.price, l.amount, t.invoicelinetype_id, languages.code
    having sum(nl.deliveredamount) > 0
UNION ALL
    select l.invoiceheader_id, wt.weighingdate line_date, wt.daynumber,
           l.code product_code, l.description PROD_DESC,
           0 del_qty, sum(wtl.grossweight) gross, sum(wtl.tareweight) tare,
           null theoreticalweight,
           null theoreticalweight_prod,
           l.price, l.amount, 3 linetype
           , languages.code language_code
           , ( SELECT pilt.sequencenumber
             from plantinvoicelinetype pilt, businessunit bu, invoiceheader h
             where l.invoiceheader_id = h.invoiceheader_id
                   and h.invoicebusinessunit_id = bu.businessunit_id
                   and bu.plant_id = pilt.plant_id
                   and pilt.invoicelinetype_id = 3) InvoiceLine_SequenceNumber,
            null SIZECODE, null SIZEDESCRIPTION, null FINISHINGMETHODCODE, null FINISHINGMETHODDESCRIPTION
    from invoiceline l, invoicelinetype t, invoicelineproduct p,
         weighingticket wt, weighingticketline wtl, LANGUAGES
    where --l.amount <> 0 and
          l.invoicelinetype_id = t.invoicelinetype_id
          and l.invoiceline_id = p.invoiceline_id
          and t.type = 3 --soil weight
          and wtl.invoiceheader_id = l.invoiceheader_id
          and wt.soilticket = 'Y'
          and wt.weighingticket_id = wtl.weighingticket_id
          and wtl.weighingcategory_id = p.weighingcategory_link_id
    group by l.invoiceheader_id, wt.weighingdate, wt.daynumber,
          l.code, l.description,
          l.price, l.amount, LANGUAGES.CODE
UNION ALL
    select l.invoiceheader_id, wt.weighingdate line_date, wt.daynumber,
           l.code product_code, l.description PROD_DESC,
           0 del_qty, sum(wtl.grossweight) gross, sum(wtl.tareweight) tare,
           null theoreticalweight,
           null theoreticalweight_prod,
           l.price, l.amount, 3 linetype
           , languages.code language_code
           , ( SELECT pilt.sequencenumber
             from plantinvoicelinetype pilt, businessunit bu, invoiceheader h
             where l.invoiceheader_id = h.invoiceheader_id
                   and h.invoicebusinessunit_id = bu.businessunit_id
                   and bu.plant_id = pilt.plant_id
                   and pilt.invoicelinetype_id = 3) InvoiceLine_SequenceNumber,
            null SIZECODE, null SIZEDESCRIPTION, null FINISHINGMETHODCODE, null FINISHINGMETHODDESCRIPTION
    from invoiceline l, invoicelinetype t, invoicelineproduct p,
         weighingticket wt, weighingticketline wtl, LANGUAGES
    where --l.amount <> 0 and
          l.invoicelinetype_id = t.invoicelinetype_id
          and l.invoiceline_id = p.invoiceline_id
          and t.type = 4 --clean weight
          and wtl.invoiceheader_id = l.invoiceheader_id
          and wt.soilticket <> 'Y'
          and wt.weighingticket_id = wtl.weighingticket_id
          and wtl.weighingcategory_id = p.weighingcategory_link_id
    group by l.invoiceheader_id, wt.weighingdate, wt.daynumber,
          l.code, l.description,
          l.price, l.amount, LANGUAGES.CODE
UNION ALL
    select l.invoiceheader_id, pn.deliverydate line_date, pn.daynumber,
           l.code product_code, l.description PROD_DESC,
           0 del_qty, sum(pnc.grossweight) gross, sum(pnc.tareweight) tare,
           null theoreticalweight,
           null theoreticalweight_prod,
           l.price, l.amount, 3 linetype
           , languages.code language_code
           , ( SELECT pilt.sequencenumber
             from plantinvoicelinetype pilt, businessunit bu, invoiceheader h
             where l.invoiceheader_id = h.invoiceheader_id
                   and h.invoicebusinessunit_id = bu.businessunit_id
                   and bu.plant_id = pilt.plant_id
                   and pilt.invoicelinetype_id = 3) InvoiceLine_SequenceNumber,
            null SIZECODE, null SIZEDESCRIPTION, null FINISHINGMETHODCODE, null FINISHINGMETHODDESCRIPTION
    from invoiceline l, invoicelinetype t, invoicelineproduct p,
         packingnote pn, packingnotecontainer pnc, LANGUAGES
    where --l.amount <> 0 and
          l.invoicelinetype_id = t.invoicelinetype_id
          and l.invoiceline_id = p.invoiceline_id
          and t.type = 4 --clean weight
          and pnc.invoiceheader_id = l.invoiceheader_id
          and pn.packingnote_id = pnc.packingnote_id
          and pnc.weighingcategory_id = p.weighingcategory_link_id
    group by l.invoiceheader_id, pn.deliverydate, pn.daynumber,
          l.code, l.description,
          l.price, l.amount, LANGUAGES.CODE
UNION ALL
    select l.invoiceheader_id, null line_date, 0 daynumber,
           l.code product_code, l.description PROD_DESC,
           0 del_qty, 0 gross, 0 tare,
           null theoreticalweight,
           null theoreticalweight_prod,
           0 price, SUM(l.amount), T.TYPE linetype
           , languages.code language_code
           , ( SELECT pilt.sequencenumber
             from plantinvoicelinetype pilt, businessunit bu, invoiceheader h
             where l.invoiceheader_id = h.invoiceheader_id
                   and h.invoicebusinessunit_id = bu.businessunit_id
                   and bu.plant_id = pilt.plant_id
                   and pilt.invoicelinetype_id = 3) InvoiceLine_SequenceNumber,
            null SIZECODE, null SIZEDESCRIPTION, null FINISHINGMETHODCODE, null FINISHINGMETHODDESCRIPTION
    from invoiceline l, invoicelinetype t, languages
    WHERE L.Invoicelinetype_Id = t.invoicelinetype_id
          and (t.type in (16, 18))
          --and l.amount <> 0
    group by l.invoiceheader_id, t.type, l.code, l.description, t.invoicelinetype_id, languages.code
UNION ALL
    select l.invoiceheader_id, null line_date, 0 daynumber,
           null product_code,
           (select iltd.description from invoicelinetype_desc iltd
            where iltd.invoicelinetype_id = t.invoicelinetype_id
                  and iltd.language_id = languages.language_id) PROD_DESC,
           0 del_qty, 0 gross, 0 tare,
           null theoreticalweight,
           null theoreticalweight_prod,
           0 price, SUM(l.amount), T.TYPE linetype
           , languages.code language_code
           , ( SELECT pilt.sequencenumber
             from plantinvoicelinetype pilt, businessunit bu, invoiceheader h
             where l.invoiceheader_id = h.invoiceheader_id
                   and h.invoicebusinessunit_id = bu.businessunit_id
                   and bu.plant_id = pilt.plant_id
                   and pilt.invoicelinetype_id = 3) InvoiceLine_SequenceNumber,
            null SIZECODE, null SIZEDESCRIPTION, null FINISHINGMETHODCODE, null FINISHINGMETHODDESCRIPTION
    from invoiceline l, invoicelinetype t, languages
    WHERE L.Invoicelinetype_Id = t.invoicelinetype_id
          and not (t.type in (2, 3, 4, 16, 18))
          --and l.amount <> 0
    group by l.invoiceheader_id, t.type, t.invoicelinetype_id, languages.language_id, languages.code
/

  CREATE OR REPLACE VIEW "V_WEIGHINGCATEGORY" ("CODE", "WEIGHINGCATEGORYDESCRIPTION", "REWASH", "ACTIVE", "LEGACYWEIGHINGCATEGORYCODE", "TURNOVERGROUPCODE", "TURNOVERGROUPDESCRIPTION", "USERNAME", "TIMESTAMP", "WEIGHINGCATEGORY_ID", "LANGUAGECODE") AS 
  SELECT WEIGHINGCATEGORY.CODE,
 (SELECT description FROM WEIGHINGCATEGORY_DESC A WHERE A.WEIGHINGCATEGORY_ID = WEIGHINGCATEGORY.WEIGHINGCATEGORY_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID),
 WEIGHINGCATEGORY.REWASH, WEIGHINGCATEGORY.ACTIVE, WEIGHINGCATEGORY.LEGACYWEIGHINGCATEGORYCODE, turnovergroup.code,
 (SELECT description FROM turnovergroup_DESC C WHERE C.TURNOVERGROUP_ID = WEIGHINGCATEGORY.TURNOVERGROUP_ID
  AND C.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID),
  WEIGHINGCATEGORY.SYSTEMUSER_ID, WEIGHINGCATEGORY.TIMESTAMP, WEIGHINGCATEGORY.WEIGHINGCATEGORY_ID,
  LANGUAGES.CODE
FROM WEIGHINGCATEGORY
 left outer join turnovergroup on(WEIGHINGCATEGORY.TURNOVERGROUP_ID = turnovergroup.TURNOVERGROUP_ID),
 languages
/

  CREATE OR REPLACE VIEW "V_WEIGHINGCATEGORYCHARGE" ("WEIGHINGCATEGORYCODE", "WEIGHINGCATEGORYDESCRIPTION", "SPECIALCHARGECODE", "SPECIALCHARGEDESCRIPTION", "TIMESTAMP", "SYSTEMUSER_ID", "LANGUAGECODE") AS 
  select b.code weighingcategorycode,
( select description from weighingcategory_desc x where x.weighingcategory_id = a.weighingcategory_id and x.language_id = languages.language_id) weighingcategorydescription,
c.code specialchargecode,
( select description from specialcharge_desc y where y.specialcharge_id = a.specialcharge_id and y.language_id = languages.language_id) specialchargedescription,
a.timestamp, a.systemuser_id, languages.code languagecode
from weighingcategorycharge a, weighingcategory b, specialcharge c, languages
where a.weighingcategory_id = b.weighingcategory_id
and a.specialcharge_id = c.specialcharge_id
/

  CREATE OR REPLACE VIEW "V_WEIGHINGCATEGORYTAX" ("WEIGHINGCATEGORYCODE", "WEIGHINGCATEGORYDESCRIPTION", "COUNTRYCODE", "COUNTRYDESCRIPTION", "TAXGROUPCODE", "TAXGROUPDESCRIPTION", "TIMESTAMP", "SYSTEMUSER_ID", "LANGUAGECODE") AS 
  select b.code weighingcategorycode,
( select description from weighingcategory_desc x where x.weighingcategory_id = a.weighingcategory_id and x.language_id = languages.language_id) weighingcategorydescription,
c.code countrycode, c.description countrydescription,
d.code taxgroupcode, d.description taxgroupdescription,
a.timestamp, a.systemuser_id, languages.code languagecode
from weighingcategorytax a
 left outer join taxgroup d on (a.taxgroup_id = d.taxgroup_id), weighingcategory b, country c, languages
where a.weighingcategory_id = b.weighingcategory_id
and a.country_id =c.country_id
/

  CREATE OR REPLACE VIEW "V_WEIGHINGCATEGPERCUSTOMER" ("CUSTOMERNUMBER", "CUSTOMERNAME", "WEIGHINGCATEGORYCODE", "WEIGHINGCATEGORYDESCRIPTION", "DATEACTIVE", "DATEINACTIVE", "WEIGHTSOILED", "WEIGHTCLEAN", "INVOICEMETHOD", "TOTALWEIGHTSOIL", "TOTALWEIGHTCLEAN", "TOTALAMOUNTINVOICEDSOIL", "TOTALAMOUNTINVOICEDCLEAN", "SOILPERCENTAGE", "REMARK", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE") AS 
  SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, WEIGHINGCATEGORY.CODE,
 (SELECT description FROM WEIGHINGCATEGORY_DESC A WHERE A.WEIGHINGCATEGORY_ID = WEIGHINGCATEGPERCUSTOMER.WEIGHINGCATEGORY_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) weighingcategorydescription,
 WEIGHINGCATEGPERCUSTOMER.DATEACTIVE,
 WEIGHINGCATEGPERCUSTOMER.DATEINACTIVE, WEIGHINGCATEGPERCUSTOMER.WEIGHTSOILED,
 WEIGHINGCATEGPERCUSTOMER.WEIGHTCLEAN, WEIGHINGCATEGPERCUSTOMER.INVOICEMETHOD,
 WEIGHINGCATEGPERCUSTOMER.TOTALWEIGHTSOIL, WEIGHINGCATEGPERCUSTOMER.TOTALWEIGHTCLEAN,
 WEIGHINGCATEGPERCUSTOMER.TOTALAMOUNTINVOICEDSOIL,
 WEIGHINGCATEGPERCUSTOMER.TOTALAMOUNTINVOICEDCLEAN, WEIGHINGCATEGPERCUSTOMER.SOILPERCENTAGE,
 WEIGHINGCATEGPERCUSTOMER.Remark,
 WEIGHINGCATEGPERCUSTOMER.SYSTEMUSER_ID, WEIGHINGCATEGPERCUSTOMER.TIMESTAMP, LANGUAGES.CODE
FROM WEIGHINGCATEGPERCUSTOMER, WEIGHINGCATEGORY, CUSTOMER, LANGUAGES
WHERE WEIGHINGCATEGPERCUSTOMER.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
 and WEIGHINGCATEGPERCUSTOMER.WEIGHINGCATEGORY_ID = WEIGHINGCATEGORY.WEIGHINGCATEGORY_ID
/

  CREATE OR REPLACE VIEW "V_WEIGHINGDETAILS" ("INVOICEHEADER_ID", "YEAR", "WEEK", "WEIGHINGDATE", "WEIGHINGYEAR", "WEIGHINGWEEK", "TICKETNUMBER", "WEIGHINGCATEGORY_CODE", "WEIGHINGCATEGORY_DESC", "DAYDESCRIPTION", "DAYNUMBER", "TAREWEIGHT", "GROSSWEIGHT", "WEIGHTDECIMALS", "NETWEIGHT", "LANGUAGESCODE") AS 
  select ih.invoiceheader_id,wt.weighingyear year, wt.weighingweek week,
wt.weighingdate, wt.weighingyear, wt.weighingweek, wt.ticketnumber, wc.code weighingcategory_code,
(select wcd.description from weighingcategory_desc wcd where wc.weighingcategory_id = wcd.weighingcategory_id and wcd.language_id = lan.language_id) weighingcategory_desc,
(select dd.description from day_desc dd
    where dd.language_id = lan.language_id and dd.day_id = wt.daynumber) daydescription,wt.daynumber,
wtl.tareweight, wtl.grossweight, wtl.weightdecimals, (wtl.grossweight - wtl.tareweight) netweight,
lan.code LanguagesCode
from invoiceheader ih, weighingticket wt, weighingticketline wtl, weighingcategory wc, languages lan
where ih.invoiceheader_id = wtl.invoiceheader_id
and wt.weighingticket_id = wtl.weighingticket_id
and wtl.weighingcategory_id = wc.weighingcategory_id
/

  CREATE OR REPLACE VIEW "V_WEIGHINGHISTORY" ("PROCESSBUSINESSUNIT_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "WEIGHINGCATEGORYCODE", "TIMESTAMP", "WEIGHINGDATE", "YEAR", "WEEK", "DAYNUMBER", "YEARWEEK", "REALMONTH", "REALYEAR", "SOILWEIGHT", "CLEANWEIGHT", "PROCESSBUSINESSUNITNR", "PROCESSBUSINESSUNITNAME", "INVOICEBUSINESSUNITNR", "INVOICEBUSINESSUNITNAME", "SYSTEMUSER_ID", "CUSTOMERLANGUAGECODE", "LANGUAGECODE", "WEIGHINGUSE", "WEIGHINGCATEGORYDESCRIPTION", "WEIGHTDECIMALSMANUALINPUT", "WEIGHTUNIT") AS 
  select /*version 1.0*/
       wh.processbusinessunit_id, cl.customer_id, cl.customernumber, cl.name customername,
       depl.departmentnumber, depl.description departmentdescription,
       dpl.distributionpointnumber, dpl.description distributionpointdescription, wcl.code weighingcategorycode,
       wh.timestamp, wh.weighingdate, wh.year, wh.week, wh.daynumber, wh.year * 100 + wh.week yearweek,
       month(wh.weighingdate) realmonth, year(wh.weighingdate) realyear, wh.soilweight, wh.cleanweight,
       pbu.code processbusinessunitnr, pbu.description processbusinessunitname,
       ibu.code invoicebusinessunitnr, ibu.description invoicebusinessunitname, wh.systemuser_id,
       cl.languagecode customerlanguagecode, lan.code languagecode, wc.weighinguse,
       (select wcld.description
          from weighingcategory_link_desc wcld
         where wcld.weighingcategory_link_id = wh.weighingcategory_link_id
           and wcld.language_id = lan.language_id) weighingcategorydescription,
       case when wc.weighinguse = 1 then rg.decimals else castvarcharasnumber(ss.value) end weightdecimalsmanualinput,
       case when wc.weighinguse = 1 then rg.code else 'Weightunit' end weightunit
  from weighinghistory wh
       join weighingcategory_link wcl
            left join weighingcategory wc
                 left join registrationunit rg on wc.registrationunit_id = rg.registrationunit_id
            on wcl.weighingcategory_id = wc.weighingcategory_id
       on wh.weighingcategory_link_id = wcl.weighingcategory_link_id
       join distributionpoint_link dpl on wh.distributionpoint_link_id = dpl.distributionpoint_link_id
       join department_link depl on wh.department_link_id = depl.department_link_id
       join customer_link cl on wh.customer_link_id = cl.customer_link_id
       join businessunit ibu on wh.invoicebusinessunit_id = ibu.businessunit_id
       join businessunit pbu
            join systemsetting ss on pbu.plant_id = ss.plant_id
       on wh.processbusinessunit_id = pbu.businessunit_id
       cross join languages lan
 where ss.name = 'WEIGHTDECIMALSMANUALINPUT'
/

  CREATE OR REPLACE VIEW "V_WEIGHINGHISTORYPERPLANT" ("PLANTCODE", "PLANTNAME", "PROCESSBUSINESSUNIT_ID", "PROCESSBUCODE", "PROCESSBUDESC", "MARKETSEGMENTCODE", "MARKETSEGMENTDESC", "WEIGHINGCATEGORYCODE", "WEIGHINGCATEGORYDESC", "WEIGHINGDATE", "YEAR", "WEEK", "DAYNUMBER", "YEARWEEK", "REALMONTH", "REALYEAR", "SOILWEIGHT", "CLEANWEIGHT", "LANGUAGECODE", "WEIGHTDECIMALSMANUALINPUT", "WEIGHINGUSE", "WEIGHTUNIT") AS 
  select
  plant.code plantCode, plant.name plantName
, weighinghistory.processbusinessunit_id, processBu.code processBuCode, processBu.description processBuDesc
, marketsegment.code marketsegmentCode
, ( select marketsegment_desc.description from marketsegment_desc where marketsegment_desc.marketsegment_id = marketsegment.marketsegment_id
  and marketsegment_desc.language_id = languages.language_id ) marketsegmentDesc
, weighingcategory_link.code weighingcategoryCode
, ( select b.description  from weighingcategory_link_desc b where b.weighingcategory_link_id = weighinghistory.weighingcategory_link_id
  and b.language_id = languages.language_id ) weighingcategoryDesc
, weighinghistory.weighingdate, weighinghistory.year, weighinghistory.week, weighinghistory.daynumber
, weighinghistory.year*100 + weighinghistory.week yearweek
, MONTH(weighinghistory.weighingdate) realmonth
, YEAR(weighinghistory.weighingdate) realyear
,  weighinghistory.soilweight soilweight
, weighinghistory.cleanweight cleanweight
, languages.code languagecode
, ( case
when (select a.weighinguse from weighingcategory a
where a.weighingcategory_id=WEIGHINGCATEGORY_LINK.WEIGHINGCATEGORY_ID)=1
then ((select rg.decimals from weighingcategory a, registrationunit rg
where a.weighingcategory_id=WEIGHINGCATEGORY_LINK.WEIGHINGCATEGORY_ID and a.registrationunit_id=rg.registrationunit_id))
  else CASTVARCHARASNUMBER(SS.VALUE) end) WEIGHTDECIMALSMANUALINPUT,
    ( select a.weighinguse from weighingcategory a
where a.weighingcategory_id=WEIGHINGCATEGORY_LINK.WEIGHINGCATEGORY_ID) weighinguse,
( case
when (select a.weighinguse from weighingcategory a
where a.weighingcategory_id=WEIGHINGCATEGORY_LINK.WEIGHINGCATEGORY_ID)=1
then ((select rg.code from weighingcategory a, registrationunit rg
where a.weighingcategory_id=WEIGHINGCATEGORY_LINK.WEIGHINGCATEGORY_ID and a.registrationunit_id=rg.registrationunit_id))
  else 'Weightunit' end) Weightunit
from
  weighinghistory, weighingcategory_link
, businessunit processBu, plant
, customer cu, marketsegment
, languages
, SYSTEMSETTING SS
where
    weighinghistory.weighingcategory_link_id = weighingcategory_link.weighingcategory_link_id
and weighinghistory.processbusinessunit_id = processBu.businessunit_id
    and processBu.Plant_Id = plant.plant_id
and weighinghistory.customer_link_id = cu.customer_id
    and cu.marketsegment_id = marketsegment.marketsegment_id
AND processBu.PLANT_ID = SS.PLANT_ID
AND SS.NAME = 'WEIGHTDECIMALSMANUALINPUT'
/

  CREATE OR REPLACE VIEW "V_WEIGHINGHISTORYPRICE" ("REPORTPARAM_ID", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "DISTRIBUTIONPOINTNUMBER", "DISTRIBUTIONPOINTDESCRIPTION", "WEIGHINGCATEGORYCODE", "PROCESSBUSINESSUNITNR", "PROCESSBUSINESSUNITNAME", "INVOICEBUSINESSUNITNR", "INVOICEBUSINESSUNITNAME", "CUSTOMERLANGUAGECODE", "DECIMALS", "INVOICEAMOUNTDECIMALS", "LANGUAGECODE", "WEIGHINGCATEGORYDESCRIPTION", "PRICE", "VATRATE", "WEIGHTDECIMALSMANUALINPUT", "AMOUNT", "RNDAMOUNTPRICE") AS 
  select /*version 1.0*/
       rp.reportparam_id, cl.customer_id, cl.customernumber, cl.name customername,
       depl.departmentnumber, depl.description departmentdescription,
       dpl.distributionpointnumber, dpl.description distributionpointdescription,
       wcl.code weighingcategorycode, pbu.code processbusinessunitnr, pbu.description processbusinessunitname,
       ibu.code invoicebusinessunitnr, ibu.description invoicebusinessunitname, cl.languagecode customerlanguagecode,
       cr.decimals, cr.invoiceamountdecimals, lan.code languagecode,
       (select wcld.description
          from weighingcategory_link_desc wcld
         where wcld.weighingcategory_link_id = wh.weighingcategory_link_id
           and wcld.language_id = lan.language_id) weighingcategorydescription,
       f_getrecweightprice(rp.number_value, cl.customer_id, wh.weighingcategory_link_id, rp.string_value, rp.date_value1) price,
       f_getweightvat(rp.number_value, cl.customer_id, wh.weighingcategory_link_id, rp.number_value1, cu.country_id, rp.date_value1) vatrate,
       castvarcharasnumber(ss.value) weightdecimalsmanualinput,
       case when rp.string_value = 'Y' then sum(wh.soilweight) else sum(wh.cleanweight) end amount,
       round(case when (rp.string_value = 'Y') then sum(wh.soilweight)
             else sum(wh.cleanweight) end *
             f_getrecweightprice(rp.number_value, cl.customer_id, wh.weighingcategory_link_id, rp.string_value, rp.date_value1)
             , cr.invoiceamountdecimals) rndamountprice
  from weighinghistory wh
       join weighingcategory_link wcl on wh.weighingcategory_link_id = wcl.weighingcategory_link_id
       join distributionpoint_link dpl on wh.distributionpoint_link_id = dpl.distributionpoint_link_id
       join department_link depl on wh.department_link_id = depl.department_link_id
       join customer_link cl
            left join customer cu
                 join currency cr on cu.currency_id = cr.currency_id
            on cl.customer_id = cu.customer_id
       on wh.customer_link_id = cl.customer_link_id
       join businessunit ibu on wh.invoicebusinessunit_id = ibu.businessunit_id
       join businessunit pbu
            join systemsetting ss on pbu.plant_id = ss.plant_id
       on wh.processbusinessunit_id = pbu.businessunit_id
       cross join languages lan
       cross join reportparam rp
 where ss.name = 'WEIGHTDECIMALSMANUALINPUT'
   and cl.customernumber between rp.number_value2 and rp.number_value3
   and wh.weighingdate >= rp.date_value1
   and wh.weighingdate <= rp.date_value2
   and wcl.code >= rp.string_value1
   and wcl.code <= rp.string_value2
 group by rp.reportparam_id, cl.customer_id, cl.customernumber, cl.name, depl.departmentnumber, depl.description,
       dpl.distributionpointnumber, dpl.description, wcl.code, pbu.code, pbu.description, ibu.code, ibu.description,
       cl.languagecode, cr.decimals, cr.invoiceamountdecimals, lan.code, lan.language_id, rp.number_value,
       wh.weighingcategory_link_id, rp.string_value, rp.date_value1, ss.value, rp.number_value1, cu.country_id
/

  CREATE OR REPLACE VIEW "V_WEIGHINGTICKET" ("SOILTICKET", "TICKETNUMBER", "CUSTOMERNUMBER", "CUSTOMERNAME", "CUSTOMER_ID", "CUSTOMERVISITADDRESS_STREET", "CUSTOMERVISITADDRESSZIPCODE", "CUSTOMERVISITADDRESSCITY", "WEIGHINGDATE", "STATUSCODE", "STATUSDESCRIPTION", "EMPLOYEENUMBER", "EMPLOYEENAME", "PROCESSBUSINESSUNITNR", "PROCESSBUSINESSUNITNAME", "INVOICEBUSINESSUNITNR", "INVOICEBUSINESSUNITNAME", "CONSIGNMENTNOTENUMBER", "USERNAME", "TIMESTAMP", "PROCESSBUSINESSUNITPLANT_ID", "WEIGHINGTICKET_ID", "DAYNUMBER", "DAYDESCRIPTION", "LANGUAGECODE", "CUSTOMERLANGUAGECODE", "REMARK", "ORIGIN", "CORRECTEDNOTENUMBER", "DELIVERYDATE", "WEIGHINGYEAR", "WEIGHINGWEEK", "PROCESSEDTIMESTAMP", "WEIGHTUNIT", "CONTAINERRECORDINGACTIVE", "USER_NAME", "PLANTLOGO") AS 
  select /*version 2.1*/
       wt.soilticket, wt.ticketnumber, cu.customernumber, cu.name customername,
       cu.customer_id, vad.street customervisitaddress_street,
       vad.zipcode customervisitaddresszipcode, vad.city customervisitaddresscity,
       wt.weighingdate, st.code statuscode,
       (select std.description
          from status_desc std
         where std.status_id = wt.status_id
           and std.language_id = lan.language_id) statusdescription,
       emp.employeenumber, emp.name employeename, pbu.code processbusinessunitnr,
       pbu.description processbusinessunitname, ibu.code invoicebusinessunitnr,
       ibu.description invoicebusinessunitname,
       (select cn.consignmentnotenumber
          from consignmentnote cn
         where wt.consignmentnote_id = cn.consignmentnote_id) consignmentnotenumber,
       wt.systemuser_id username, wt.timestamp, pbu.plant_id processbusinessunitplant_id,
       wt.weighingticket_id, wt.daynumber,
       (select dad.description
          from day_desc dad
         where dad.language_id = lan.language_id
           and dad.day_id = wt.daynumber) daydescription,
       lan.code languagecode, clan.code customerlanguagecode, wt.remark, wt.origin,
       wt.correctednotenumber, wt.deliverydate, wt.weighingyear, wt.weighingweek, wt.processedtimestamp,
       (select ss.value
          from systemsetting ss
         where ss.name = 'WEIGHTUNIT'
           and ss.plant_id = pbu.plant_id) weightunit,
       (select ss1.value
          from systemsetting ss1
         where ss1.name = 'CONTAINERRECORDINGACTIVE'
           and ss1.plant_id = pbu.plant_id) containerrecordingactive,
       (select su.username
          from systemuser su
         where wt.systemuser_id = su.systemuser_id) user_name,
       (select pl.logo from plant pl where pl.plant_id = pbu.plant_id) plantlogo
  from weighingticket wt
       left join employee emp on wt.employee_id = emp.employee_id
       join businessunit pbu on wt.processbusinessunit_id = pbu.businessunit_id
       join businessunit ibu on wt.invoicebusinessunit_id = ibu.businessunit_id
       join status st on wt.status_id = st.status_id
       join customer cu
            join address vad on cu.visitaddress_id = vad.address_id
            join languages clan on cu.language_id = clan.language_id
       on wt.customer_id = cu.customer_id
       cross join languages lan
/

  CREATE OR REPLACE VIEW "V_WEIGHINGTICKETLINE" ("TICKETNUMBER", "SEQUENCENUMBER", "CONTAINERTYPECODE", "CONTAINERTYPE_DESC", "DEPARTMENTNUMBER", "DEPARTMENTDESCRIPTION", "WEIGHINGCATEGORY_CODE", "WEIGHINGCATEGORY_DESC", "TAREWEIGHT", "GROSSWEIGHT", "WEIGHTDECIMALS", "NETWEIGHT", "WEIGHINGTIMESTAMP", "SYSTEMUSER_ID", "TIMESTAMP", "WEIGHINGSEQUENCENR", "SOILPORTION", "OLD_WEIGHT", "DISTRIBUTIONPOINT_DESC", "DISTRIBUTIONPOINTNUMBER", "LANGUAGECODE", "REPORTPARAM_ID", "CONTAINER_PRIMARYID", "CONTAINER_SECONDARYID") AS 
  select /*version 1.1*/
       wt.ticketnumber, max(wtl.sequencenumber) sequencenumber,
       (select ct.code
          from containertype ct
         where ct.containertype_id = wtl.containertype_id) containertypecode,
       (select ctd.description
          from containertype_desc ctd
         where ctd.containertype_id = wtl.containertype_id
           and ctd.language_id = lan.language_id) containertype_desc,
       dep.departmentnumber, dep.description departmentdescription, wc.code weighingcategory_code,
       (select wcd.description
          from weighingcategory_desc wcd
         where wcd.weighingcategory_id = wtl.weighingcategory_id
           and wcd.language_id = lan.language_id) weighingcategory_desc,
       wtl.tareweight, wtl.grossweight, wtl.weightdecimals,
       (wtl.grossweight - wtl.tareweight) netweight,
       wtl.weighingtimestamp, wtl.systemuser_id, wtl.timestamp, wtl.weighingsequencenr, wtl.soilportion,
       f_getoldweight(rp.number_value1, wt.correctednotenumber, wtl.weighingcategory_id) old_weight,
       dp.description distributionpoint_desc, dp.distributionpointnumber,
       lan.code languagecode, rp.reportparam_id,
       (select cnt.primaryid
          from container cnt
         where wtl.container_id = cnt.container_id) container_primaryid,
       (select sec.secondaryid
          from secondarycontainer sec
         where wtl.container_id = sec.container_id) container_secondaryid
  from weighingticketline wtl
       left join distributionpoint dp on wtl.distributionpoint_id = dp.distributionpoint_id
       join department dep on wtl.department_id = dep.department_id
       join weighingcategory wc on wtl.weighingcategory_id = wc.weighingcategory_id
       join weighingticket wt on wtl.weighingticket_id = wt.weighingticket_id
       cross join languages lan
       cross join reportparam rp
 where wt.ticketnumber = rp.number_value
 group by wt.ticketnumber, wtl.containertype_id, wtl.weighingticketline_id, lan.language_id,
          dep.departmentnumber, dep.description, wc.code, wtl.weighingcategory_id,
          wtl.tareweight, wtl.grossweight, wtl.weightdecimals, wtl.weighingtimestamp,
          wtl.systemuser_id, wtl.timestamp, wtl.weighingsequencenr, wtl.container_id,
          wtl.soilportion, rp.number_value1, wt.correctednotenumber,
          dp.description, dp.distributionpointnumber, lan.code, rp.reportparam_id
/

  CREATE OR REPLACE VIEW "V_WEIGHTSPERPLANT" ("PLANTCODE", "PLANTNAME", "PROCESSBUSINESSUNIT_ID", "PROCESSBUCODE", "PROCESSBUDESC", "MARKETSEGMENTCODE", "MARKETSEGMENTDESC", "WEIGHINGCATEGORYCODE", "WEIGHINGCATEGORYDESC", "WEIGHINGDATE", "YEAR", "WEEK", "DAYNUMBER", "YEARWEEK", "REALMONTH", "REALYEAR", "SOILWEIGHT", "CLEANWEIGHT", "LANGUAGECODE", "WEIGHTDECIMALSMANUALINPUT", "WEIGHINGUSE", "WEIGHTUNIT") AS 
  select /*version 1.0*/
       pl.code plantcode, pl.name plantname, wh.processbusinessunit_id,
       pbu.code processbucode, pbu.description processbudesc,
       ms.code marketsegmentcode,
       (select msd.description
          from marketsegment_desc msd
         where msd.marketsegment_id = ms.marketsegment_id
           and msd.language_id = lan.language_id) marketsegmentdesc,
       wcl.code weighingcategorycode,
       (select wcld.description
          from weighingcategory_link_desc wcld
         where wcld.weighingcategory_link_id = wh.weighingcategory_link_id
           and wcld.language_id = lan.language_id) weighingcategorydesc,
       wh.weighingdate, wh.year, wh.week,
       wh.daynumber, wh.year * 100 + wh.week yearweek,
       month(wh.weighingdate) realmonth, year(wh.weighingdate) realyear,
       round(wh.soilweight, 1) soilweight,
       round(wh.cleanweight, 1) cleanweight, lan.code languagecode,
       (case
         when (select a.weighinguse
                 from weighingcategory a
                where a.weighingcategory_id = wcl.weighingcategory_id) = 1 then
          ((select rg.decimals
              from weighingcategory a, registrationunit rg
             where a.weighingcategory_id = wcl.weighingcategory_id
               and a.registrationunit_id = rg.registrationunit_id))
         else
          castvarcharasnumber(ss.value)
       end) weightdecimalsmanualinput,
       (select a.weighinguse
           from weighingcategory a
          where a.weighingcategory_id = wcl.weighingcategory_id) weighinguse,
       (case
         when (select a.weighinguse
                 from weighingcategory a
                where a.weighingcategory_id = wcl.weighingcategory_id) = 1 then
          ((select rg.code
              from weighingcategory a, registrationunit rg
             where a.weighingcategory_id = wcl.weighingcategory_id
               and a.registrationunit_id = rg.registrationunit_id))
         else
          ''
       end) weightunit
  from weighinghistory wh
       join weighingcategory_link wcl on wh.weighingcategory_link_id = wcl.weighingcategory_link_id
       join businessunit pbu
            join plant pl on pbu.plant_id = pl.plant_id
            join systemsetting ss on pbu.plant_id = ss.plant_id and ss.name = 'WEIGHTDECIMALSMANUALINPUT'
       on wh.processbusinessunit_id = pbu.businessunit_id
       join customer cu
            join marketsegment ms on cu.marketsegment_id = ms.marketsegment_id
       on wh.customer_link_id = cu.customer_id
       cross join languages lan
/

  CREATE OR REPLACE VIEW "V_WOISSUEHISTORY" ("WORKORDER_ID", "ASSIGNDATE", "PRODUCTCODE", "PRODUCTDESC", "SIZEDEFINITIONCODE", "SIZEDEFINITIONDESC", "ISSUEDQTY", "QDDESC", "STOCKROOMNAME", "LANGUAGECODE") AS 
  select  fv.workorder_id, fv.assigndate, fv.productcode,fv.productdesc, fv.sizedefinitionCode, fv.sizedefinitionDesc,
sum(fv.issuedqty) issuedqty,fv.qddesc,fv.stockroomname,fv.languagecode
 from
(select wo.workorder_id,
       trunc(a.timestamp) assigndate,
       p.code productcode,
       (select description
          from product_link_desc z
         where z.product_link_id = p.product_id
           and z.language_id = languages.language_id) productdesc,
       sz.code sizedefinitionCode,
       (select description
          from sizedefinition_link_desc k
         where k.sizedefinition_link_id = sz.sizedefinition_link_id
           and k.language_id = languages.language_id) sizedefinitionDesc,
       -a.quantity issuedqty,
       coalesce((select qd.description
                  from qualitygrade_desc qd
                 where qd.qualitygrade_id = qg.qualitygrade_id
                   and qd.language_id = languages.language_id),
                qg.code) qddesc,
       coalesce( s.name ,(select s.name   from stockroom sa   where wo.processingstockroom_id = sa.stockroom_id)) stockroomname,
       languages.code languagecode
  from workorderstocktransaction a,
       workorder                 wo,
       workorderline             wol,
       product                   p,
       sizedefinition_link       sz,
       qualitygrade              qg, stocktransaction st,
       stockreservationpergrade srg, stockdefinitionperitem sdi, stockroom s,
       languages
 where a.workorderline_id = wol.workorderline_id
   and wol.workorder_id = wo.workorder_id
   and st.stockreservationpergrade_id =srg.stockreservationpergrade_id
   and st.stocktransaction_id = a.stocktransaction_id and srg.stockdefinitionperitem_id=sdi.stockdefinitionperitem_id
   and sdi.stockroom_id=s.stockroom_id
   and sdi.product_id = p.product_id
   and sdi.sizedefinition_id= sz.sizedefinition_link_id
   and  srg.qualitygrade_id = qg.qualitygrade_id)  fv
 group by fv.workorder_id, fv.assigndate, fv.productcode,fv.productdesc, fv.sizedefinitionCode, fv.sizedefinitionDesc,
 fv.qddesc,fv.stockroomname,fv.languagecode
/

  CREATE OR REPLACE VIEW "V_WORKORDEREMBLEM" ("WORKORDER_ID", "WORKORDERLINE_ID", "LANGUAGECODE", "EMBLEMNR", "PUTEMBLEMON", "WORKORDERLINEEMBLEM_ID", "PRODUCT_ID", "SIZEDEFINITION_ID", "ATTACHMENT_BY", "EMBROIDERYFILEPATHPRODUCTION", "FONTSIZE", "COLORPALETTE", "EMBLEMTEMPLATELINE_ID", "EMBLEMTEMPLATELINE_DESC", "EMBROIDERYLETTERING", "EMBROIDERYLETTERINGLINE1", "EMBROIDERYLETTERINGLINE2", "EMBROIDERYLETTERINGLINE3", "CUSTOMERSUPPLIED", "EMBLEMTYPE", "SHORTDESCRIPTION", "QUANTITY", "EMBLEMDESCRIPTION", "SIZESHAPE", "BACKGROUND", "BORDER", "TEXT", "PLACEMENT", "FABRIC", "EMBLEM_FONT") AS 
  select /*version 2.0*/
       wol.workorder_id, wol.workorderline_id, lan.code languagecode, coalesce(pre.code, prw.code) emblemnr, prl.code putemblemon, wokem.workorderlineemblem_id,
       wokem.product_id, wokem.sizedefinition_id, coalesce(etl.attachmentby, -1) attachment_by, etl.embroideryfilepathproduction, etl.fontsize, etl.colorpalette,
       etl.emblemtemplateline_id, etl.description emblemtemplateline_desc, wokem.embroiderylettering, wokem.embroideryletteringline1, wokem.embroideryletteringline2,
       wokem.embroideryletteringline3, coalesce(etl.customersupplied, wokem.customersupplied) customersupplied, etl.emblemtype emblemtype,
       coalesce(pre.shortdescription, prw.shortdescription) shortdescription,  wokem.qtyrequested quantity,
       coalesce((select prd.description
                   from product_desc prd
                  where prd.product_id = coalesce(pre.product_id, prw.product_id)
                    and prd.language_id = lan.language_id),
                 etl.description,
                 (cast(concatenatewithblank(coalesce((select txte.code
                                                        from color txte
                                                       where txte.color_id = etl.textcolor_id), ''),
                                            coalesce((select fa2.code
                                                        from fabric fa2
                                                       where fa2.fabric_id = etl.fabric_id), '')
                                           ) as varchar2(255)))
                ) emblemdescription,
       (select sd.code
          from sizedefinition sd
         where sd.sizedefinition_id = coalesce(etl.sizedefinition_id, wokem.sizedefinition_id)) sizeshape,
       (select back.description
          from color_desc back
         where back.color_id = coalesce(etl.bkgcolor_id, pre.color_id, prw.color_id)
           and back.language_id = lan.language_id) background,
       (select bord.description
          from color_desc bord
         where bord.color_id = coalesce(etl.bordercolor_id, epe.bordercolor_id, epw.bordercolor_id)
           and bord.language_id = lan.language_id) border,
       (select txtd.description
          from color_desc txtd
         where txtd.color_id = coalesce(etl.textcolor_id, epe.textcolor_id, epw.textcolor_id)
           and txtd.language_id = lan.language_id) text,
       (select pla.code
          from placement pla
         where pla.placement_id = coalesce(etl.placement_id, wokem.placement_id)) placement,
       (select fa.code
          from fabric fa
         where fa.fabric_id = coalesce(etl.fabric_id, pre.fabric_id, prw.fabric_id)) fabric,
       (select ef.description
          from emblemfont ef
         where ef.emblemfont_id = coalesce(etl.emblemfont_id, epe.emblemfont_id, epw.emblemfont_id)) emblem_font
  from workorderlineemblem wokem
       left join product prw on wokem.product_id = prw.product_id
       left join emblemproduct epw on wokem.product_id = epw.product_id
       left join emblemtemplateline etl
            left join product pre on etl.product_id = pre.product_id
            left join emblemproduct epe on etl.product_id = epe.product_id
            join emblemtemplate et on etl.emblemtemplate_id = et.emblemtemplate_id
       on wokem.emblemtemplateline_id = etl.emblemtemplateline_id
       join workorderline wol
            join product_link prl on wol.product_link_id = prl.product_link_id
       on wokem.workorderline_id = wol.workorderline_id
       cross join languages lan
/

  CREATE OR REPLACE VIEW "V_WORKORDEREMBLEM_EMBCOLORS" ("EMBLEMTEMPLATELINE_ID", "EMBROIDERYCOLOR_ID", "SEQUENCENUMBER", "COLOR_ID", "COLOR_CODE", "COLOR_RALCODE", "COLOR_USEDFOREMBLEM", "SYSTEMUSER_ID", "TIMESTAMP", "LANGUAGECODE", "COLOR_DESCRIPTION") AS 
  select /*version 2.0*/
       ec.emblemtemplateline_id, ec.embroiderycolor_id, ec.sequencenumber, ec.color_id, co.code color_code, co.ralcode color_ralcode,
       co.usedforemblem color_usedforemblem, ec.systemuser_id, ec.timestamp, lang.code languagecode,
       (select cd.description
          from color_desc cd
         where cd.color_id = co.color_id
           and cd.language_id = lang.language_id) color_description
  from embroiderycolor ec
       join color co on ec.color_id = co.color_id
       join emblemtemplateline etl on ec.emblemtemplateline_id = etl.emblemtemplateline_id
       cross join languages lang
/

  CREATE OR REPLACE VIEW "V_WORKORDEREMBL_CFC" ("WORKORDER_ID", "WORKORDERLINE_ID", "LANGUAGECODE", "EMBLEMNR", "EMBLEMDESCRIPTION", "EMBLEMTYPE", "SIZESHAPE", "BACKGROUND", "BORDER", "TEXT", "QUANTITY", "PLACEMENT", "PUTEMBLEMON", "WORKORDERLINEEMBLEM_ID", "FABRIC", "EMBLEM_FONT", "PRODUCT_ID", "SIZEDEFINITION_ID", "ATTACHMENT_BY", "EMBROYDERYFILEPATHPRODUCTION", "FONTSIZE", "COLORPALETTE", "EMBLEMTEMPLATELINE_ID", "EMBLEMTEMPLATELINE_DESC", "EMBROIDERYLETTERING", "EMBROIDERYLETTERINGLINE1", "EMBROIDERYLETTERINGLINE2", "EMBROIDERYLETTERINGLINE3", "PONUMBER") AS 
  select /*+index(wokem XAK1WORKORDERLINEEMBLEM)*/
  workorderline.workorder_id, workorderline.workorderline_id,languages.code LanguageCode
, p.code EmblemNr
, ( select product_desc.description from product_desc where p.product_id = product_desc.product_id
  and product_desc.language_id = languages.language_id ) EmblemDescription
, EmblemType, sizedefinition.code SizeShape, color.code Background, c.code Border, txt.code Text
, wokem.qtyrequested Quantity , placement.code Placement, product_link.code PutEmblemOn
, wokem.workorderlineemblem_id
-- 22-10-2008, RVI - 502536 Begin
--, fabric.code fabric, null emblem_font
, fabric.code fabric
, (select ef.description from emblemfont ef where ef.emblemfont_id = e.emblemfont_id) emblem_font
-- 22-10-2008 RVI - 502536 End
, wokem.product_id, wokem.sizedefinition_id
, -1 attachment_by
, null embroyderyfilepathproduction, null fontsize, null colorpalette
, null emblemtemplateline_id
, null emblemtemplateline_desc
, wokem.embroiderylettering
, wokem.embroideryletteringline1
, wokem.embroideryletteringline2
, wokem.embroideryletteringline3
,(select min(poh.purchaseordernumber) from purchaseorderline pol, purchaseorderheader poh, workorderlineemblem wole
        left outer join workorderlineemblempoline wolpole
          on wole.workorderlineemblem_id=wolpole.workorderlineemblem_id
       where wole.workorderlineemblem_id=wokem.workorderlineemblem_id
         and nvl(wole.purchaseorderline_id ,wolpole.purchaseorderline_id)=pol.purchaseorderline_id
         and pol.purchaseorderheader_id=poh.purchaseorderheader_id) POnumber
from
  workorderlineemblem wokem
          left outer join sizedefinition on  sizedefinition.sizedefinition_id = wokem.sizedefinition_id
          left outer join
                     (emblemproduct e
                                left outer join  color txt on e.textcolor_id = txt.color_id
                                left outer join color c on c.color_id = e.bordercolor_id )
                 on wokem.product_id = e.product_id
           left outer join placement on placement.placement_id = wokem.placement_id
, languages ,color, workorderline , product p, fabric
, product_link ---left outer join productsize on product_link.product_id = productsize.product_id
 where
     wokem.product_id is not null
and wokem.emblemtemplateline_id is null
and workorderline.workorderline_id = wokem.workorderline_id
    and wokem.product_id = p.product_id
        and p.color_id = color.color_id
        and p.fabric_id = fabric.fabric_id
and workorderline.product_link_id = product_link.product_link_id
UNION ALL
select /*+index(wokem XAK1WORKORDERLINEEMBLEM)*/
  workorderline.workorder_id, workorderline.workorderline_id,languages.code LanguageCode
, p.code EmblemNr
, coalesce((select product_desc.description from product_desc where product_desc.product_id = p.product_id
  and product_desc.language_id = languages.language_id)
  , emblemtemplateline.description) EmblemDescription
, emblemtemplateline.emblemtype EmblemType, sizedefinition.code SizeShape, color.code Background
, c.code Border, txt.code Text, wokem.qtyrequested Quantity , placement.code Placement
, product_link.code PutEmblemOn
, wokem.workorderlineemblem_id
, fabric.code fabric, ef.description emblem_font
-- 22-10-2008, RVI - 502536 Begin
--, wokem.product_id, wokem.sizedefinition_id
, emblemtemplateline.product_id, emblemtemplateline.sizedefinition_id
-- 22-10-2008, RVI - 502536 End
, emblemtemplateline.attachmentby attachment_by
, emblemtemplateline.embroideryfilepathproduction embroyderyfilepathproduction, emblemtemplateline.fontsize, emblemtemplateline.colorpalette
, emblemtemplateline.emblemtemplateline_id emblemtemplateline_id
, emblemtemplateline.description emblemtemplateline_desc
, wokem.embroiderylettering
, wokem.embroideryletteringline1
, wokem.embroideryletteringline2
, wokem.embroideryletteringline3
,(select min(poh.purchaseordernumber) from purchaseorderline pol, purchaseorderheader poh, workorderlineemblem wole
        left outer join workorderlineemblempoline wolpole
          on wole.workorderlineemblem_id=wolpole.workorderlineemblem_id
       where wole.workorderlineemblem_id=wokem.workorderlineemblem_id
         and nvl(wole.purchaseorderline_id ,wolpole.purchaseorderline_id)=pol.purchaseorderline_id
         and pol.purchaseorderheader_id=poh.purchaseorderheader_id) POnumber
from
  workorderlineemblem wokem
      left outer join placement on placement.placement_id = wokem.placement_id
, emblemtemplateline
      left outer join emblemfont ef on emblemtemplateline.emblemfont_id = ef.emblemfont_id
      left outer join
              (emblemproduct e
               left outer join  color txt on e.textcolor_id = txt.color_id
               left outer join color c on c.color_id = e.bordercolor_id )
          on  emblemtemplateline.product_id = e.product_id
, workorderline, fabric
, product_link ---left outer join productsize on product_link.product_id = productsize.product_id
, sizedefinition, languages
, product p left outer join color  on  p.color_id = color.color_id
where
    wokem.emblemtemplateline_id is not null
and wokem.product_id is null
and emblemtemplateline.product_id is not null
and emblemtemplateline.product_id = p.product_id
    and p.fabric_id = fabric.fabric_id
and workorderline.product_link_id = product_link.product_link_id
and workorderline.workorderline_id = wokem.workorderline_id
and wokem.emblemtemplateline_id = emblemtemplateline.emblemtemplateline_id
and sizedefinition.sizedefinition_id = emblemtemplateline.sizedefinition_id
UNION ALL
select /*+index(wokem XAK1WORKORDERLINEEMBLEM)*/
  workorderline.workorder_id, workorderline.workorderline_id, languages.code LanguageCode
, emblemtemplate.code EmblemNr
, coalesce(emblemtemplateline.description, cast(CONCATENATEWITHBLANK(txt.code, fabric.code) as varchar2(255))) EmblemDescription
, emblemtemplateline.emblemtype EmblemType, sizedefinition.code SizeShape, color.code Background
, c.code Border, txt.code Text, wokem.qtyrequested Quantity ,placement.code Placement
, product_link.code PutEmblemOn
, wokem.workorderlineemblem_id
, fabric.code fabric, ef.description emblem_font
, wokem.product_id, wokem.sizedefinition_id
, emblemtemplateline.attachmentby attachment_by
, emblemtemplateline.embroideryfilepathproduction embroyderyfilepathproduction, emblemtemplateline.fontsize, emblemtemplateline.colorpalette
, emblemtemplateline.emblemtemplateline_id emblemtemplateline_id
, emblemtemplateline.description emblemtemplateline_desc
, wokem.embroiderylettering
, wokem.embroideryletteringline1
, wokem.embroideryletteringline2
, wokem.embroideryletteringline3
,(select min(poh.purchaseordernumber) from purchaseorderline pol, purchaseorderheader poh, workorderlineemblem wole
        left outer join workorderlineemblempoline wolpole
          on wole.workorderlineemblem_id=wolpole.workorderlineemblem_id
       where wole.workorderlineemblem_id=wokem.workorderlineemblem_id
         and nvl(wole.purchaseorderline_id ,wolpole.purchaseorderline_id)=pol.purchaseorderline_id
         and pol.purchaseorderheader_id=poh.purchaseorderheader_id) POnumber
from
  workorderlineemblem wokem
, emblemtemplateline
       left outer join emblemfont ef on emblemtemplateline.emblemfont_id = ef.emblemfont_id
       left outer join color on emblemtemplateline.bkgcolor_id = color.color_id
       left outer join color c on emblemtemplateline.bordercolor_id = c.color_id
       left outer join placement on placement.placement_id = emblemtemplateline.placement_id
       left outer join color txt on emblemtemplateline.textcolor_id = txt.color_id
, workorderline, fabric
, product_link --left outer join productsize on product_link.product_id = productsize.product_id
, emblemtemplate, sizedefinition, languages
where
    wokem.emblemtemplateline_id is not null
and wokem.product_id is null
and emblemtemplateline.product_id is null
and workorderline.product_link_id = product_link.product_link_id
and workorderline.workorderline_id = wokem.workorderline_id
    and wokem.emblemtemplateline_id = emblemtemplateline.emblemtemplateline_id
and emblemtemplate.emblemtemplate_id = emblemtemplateline.emblemtemplate_id
and sizedefinition.sizedefinition_id = emblemtemplateline.sizedefinition_id
and fabric.fabric_id = emblemtemplateline.fabric_id
/

  CREATE OR REPLACE VIEW "V_WORKORDERINSTR" ("CUSTVSGENERAL", "CUSTOMER_ID", "CUSTOMERUSERINSTRUCTION_ID", "INSTRUCT", "DATEACTIVE", "CUSTOMERNUMBER", "CODE") AS 
  SELECT 1 custVsGeneral,
       CUI.Customer_Id,
       CUI.CUSTOMERUSERINSTRUCTION_ID,
       (select CUID_1.INSTRUCTION
                  from CUSTOMERUSERINSTRUCTION_DESC CUID_1
                 where CUI.CUSTOMERUSERINSTRUCTION_ID =
                       CUID_1.CUSTOMERUSERINSTRUCTION_ID
                   AND CUID_1.LANGUAGE_ID = lan.language_id)instruct,
       CUI.DATEACTIVE dateactive,c.customernumber, lan.code
  FROM DIALOGS                  D,
       USERINSTRUCTIONPERSCREEN UIPS,
       CUSTOMERUSERINSTRUCTION  CUI,
       customer c, languages lan
 where D.CODE = 'WorkOrderPrintOut'
   AND D.DIALOG_ID = UIPS.DIALOG_ID
   AND UIPS.CUSTOMERUSERINSTRUCTION_ID = CUI.CUSTOMERUSERINSTRUCTION_ID
   AND UIPS.GENERALUSERINSTRUCTION_ID IS NULL
   AND CUI.CUSTOMER_ID = c.customer_id
   AND CUI.DATEACTIVE <= sysdate
   AND CUI.DATEINACTIVE >= sysdate
union all
SELECT 2 custVsGeneral,
       GUIPC.CUSTOMER_ID,
       GUI.GENERALUSERINSTRUCTION_ID,
      (select GUID_1.INSTRUCTION
                  from GENERALUSERINSTRUCTION_DESC GUID_1
                 where GUI.GENERALUSERINSTRUCTION_ID =
                       GUID_1.GENERALUSERINSTRUCTION_ID
                   AND GUID_1.LANGUAGE_ID = lan.language_id)instruct,
       GUI.DATEACTIVE dateactive,c.customernumber, lan.code
  FROM DIALOGS                       D,
       USERINSTRUCTIONPERSCREEN      UIPS,
       GENERALUSERINSTRUCTIONPERCUST GUIPC,
       GENERALUSERINSTRUCTION        GUI, customer c, languages lan
 where D.CODE ='WorkOrderPrintOut'
   AND D.DIALOG_ID = UIPS.DIALOG_ID
   AND UIPS.GENERALUSERINSTRUCTION_ID = GUI.GENERALUSERINSTRUCTION_ID
   AND GUIPC.GENERALUSERINSTRUCTION_ID = GUI.GENERALUSERINSTRUCTION_ID
   AND UIPS.CUSTOMERUSERINSTRUCTION_ID IS NULL
   AND GUIPC.CUSTOMER_ID = c.customer_id
   AND GUI.DATEACTIVE <=sysdate
   AND GUI.DATEINACTIVE >=sysdate
/

  CREATE OR REPLACE VIEW "V_WORKORDERISSUES" ("WORKORDER_ID", "ASSIGNDATE", "ASSIGNYEAR", "ASSIGNWEEK", "ASSIGNDAY", "INCIRCDATE", "INCIRCYEAR", "INCIRCWEEK", "INCIRCDAY", "AMOUNT", "QUANTITY", "PRODNR", "SIZECODE", "PRODDESCRIPTION", "ISSUEGRADE", "LANGUAGECODE", "LANGUAGE_ID") AS 
  select ih.workorder_id, ih.assigndate, ih.assignyear, ih.assignweek, ih.assignday
, ih.incircdate, ih.incircyear, ih.incircweek, ih.incircday
, ih.amount, ih.quantity
, (select pr.code from product pr where pr.product_id = ih.product_link_id) ProdNr
, (select sd.code from sizedefinition sd where sd.sizedefinition_id = ih.sizedefinition_link_id) SizeCode
, (SELECT pd.description FROM product_desc pd WHERE pd.product_id = ih.product_link_id
          AND pd.language_id = lan.language_id) ProdDescription
, (select qg.code from qualitygrade qg where qg.qualitygrade_id = ih.issuegrade_id) issuegrade
, lan.code languagecode, lan.language_id
from issuehistory ih, languages lan
union all --needed to see also Issued for WO from stock with Origin 8-9 Transferred
select wo.workorder_id, trunc(wost.timestamp) assigndate
, year(trunc(wost.timestamp)) assignyear, cast(getweeknumber(trunc(wost.timestamp)) as numeric) assignweek, EXTRACT(day FROM trunc(wost.timestamp)) assignday
, trunc(wost.timestamp) incircdate, year(trunc(wost.timestamp)) incircyear, cast(getweeknumber(trunc(wost.timestamp)) as numeric) incircweek, EXTRACT(day FROM trunc(wost.timestamp)) incircday
, (-1)*sum(wost.quantity) amount, (-1)*sum(wost.quantity) quantity
, (select pr.code from product pr where pr.product_id = wol.product_link_id) ProdNr
, (select sd.code from sizedefinition sd where sd.sizedefinition_id = wol.sizedefinition_link_id) SizeCode
, (SELECT pd.description FROM product_desc pd WHERE pd.product_id = wol.product_link_id
          AND pd.language_id = lan.language_id) ProdDescription
, (select qg.code from qualitygrade qg where qg.qualitygrade_id = srg.qualitygrade_id) issuegrade
, lan.code languagecode, lan.language_id
from workorder wo, workorderline wol, workorderstocktransaction wost,stocktransaction st,
stockreservationpergrade srg, languages lan
where wo.workorder_id=wol.workorder_id
      and wol.workorderline_id=wost.workorderline_id
      and wo.origin in (8,9)
      and wost.stocktransaction_id=st.stocktransaction_id
      and st.stockreservationpergrade_id=srg.stockreservationpergrade_id
      and wost.quantity < 0
group by wo.workorder_id, wol.workorderline_id, trunc(wost.timestamp), wol.product_link_id
, wol.sizedefinition_link_id, srg.qualitygrade_id, lan.language_id, lan.code
/

  CREATE OR REPLACE VIEW "V_WORKORDERLINE_CFC" ("WORKORDERLINE_ID", "WORKORDER_ID", "PRODNR", "PRODDESCRIPTION", "PRODLONGDESCRIPTION", "FINMETHCODE", "SIZECODE", "UNIQUEYN", "QUALITYGRADE", "QUANTITYORDERED", "QUANTITYCANCELLED", "QORDER", "QDONE", "QOPEN", "MODIFICATIONGROUPCODE", "MODIFICATIONCODE", "MODIFICATIONDESC", "INSTRUCTIONS", "LANGUAGECODE", "QUALITYGRADE_CODE", "REASONCODE_ID", "RENTALQTYADJUSTMENT_ID", "EXECUTEDBY", "SUPPLIERNUMBER", "SUPLIERNAME", "SUPPLIERPRODUCTCODE", "SUPPLIERPRODUCTDESCRIPTION", "SUPPLIERSIZECODE") AS 
  SELECT wokli.workorderline_id,
       wokli.workorder_id,
       prdlk.code ProdNr,
       (SELECT product_desc.description
        FROM   product_desc
        WHERE  prdlk.product_id = product_desc.product_id
               AND product_desc.language_id = languages.language_id) ProdDescription,
       (SELECT product_desc.longdescription
        FROM   product_desc
        WHERE  prdlk.product_id = product_desc.product_id -- todo6863
               AND product_desc.language_id = languages.language_id) ProdLongDescription,
       finishingmethod.code FinMethCode,
       szlk.code SizeCode,
       wokli.codeuniquely UniqueYN,
       (SELECT qualitygrade_desc.description
        FROM   qualitygrade_desc
        WHERE  qualitygrade_desc.qualitygrade_id =
               qualitygrade.qualitygrade_id
               AND qualitygrade_desc.language_id = languages.language_id) QualityGrade,
       wokli.quantityordered,
       wokli.quantitycancelled,
       (wokli.quantityordered - wokli.quantitycancelled) qOrder,
       wokli.quantityfilled qDone,
       (wokli.quantityordered - wokli.quantityfilled -
       wokli.quantitycancelled) qOpen,
       (SELECT mdgr.code
        FROM   modificationgroup        mdgr,
               modificationspergroup    mdspg,
               productmodificationgroup prdmspg
        WHERE  mdgr.modificationgroup_id = mdspg.modificationgroup_id
               AND mdspg.modification_id = modification.modification_id
               AND mdspg.modificationgroup_id = prdmspg.modificationgroup_id
               AND prdmspg.product_id = wokli.product_link_id
               AND prdmspg.sequencenumber =
               workorderlinemodification.sequencenumber) ModificationGroupCode,
       modification.code ModificationCode,
       (SELECT modification_desc.description
        FROM   modification_desc
        WHERE  modification_desc.modification_id =
               modification.modification_id
               AND modification_desc.language_id = languages.language_id) ModificationDesc,
       wokli.instructions,
       languages.code languagecode,
       qualitygrade.code qualitygrade_code,
       wokli.reasoncode_id, wokli.rentalqtyadjustment_id, wokli.executedby,
       sup.suppliernumber, sup.name SuplierName,
       sp.supplierproductcode, sp.supplierproductdescription, sp.suppliersizecode
FROM   workorderline wokli
left outer join workorderlinepurchordline wolpol
          on wokli.workorderline_id=wolpol.workorderline_id
left outer join purchaseorderline pol on nvl(wokli.purchaseorderline_id, wolpol.purchaseorderline_id)=pol.purchaseorderline_id
left outer join  purchaseorderheader poh on pol.purchaseorderheader_id=poh.purchaseorderheader_id
LEFT   OUTER JOIN(workorderlinemodification
      INNER JOIN   modification ON workorderlinemodification.modification_id = modification.modification_id)
ON wokli.workorderline_id = workorderlinemodification.workorderline_id
LEFT   OUTER JOIN qualitygrade ON wokli.requestedgrade_id = qualitygrade.qualitygrade_id
LEFT   OUTER JOIN finishingmethod ON wokli.finishingmethod_id = finishingmethod.finishingmethod_id
LEFT   OUTER JOIN sizedefinition_link szlk ON wokli.sizedefinition_link_id = szlk.sizedefinition_link_id
LEFT   OUTER JOIN product prdlk ON wokli.product_link_id = prdlk.product_id
, supplier sup,supplierproduct  sp , languages
where nvl(poh.supplier_id,prdlk.supplier_id) =sup.supplier_id
and sup.supplier_id=sp.supplier_id
and sp.supplierproduct_id=coalesce((select max(a.supplierproduct_id) from supplierproduct a,productsizepersupproduct b
     where a.supplier_id=sup.supplier_id  and a.supplierproduct_id=b.supplierproduct_id
     and b.product_id=wokli.product_link_id  and b.sizedefinition_id=wokli.sizedefinition_link_id ),sp.supplierproduct_id)
/

  CREATE OR REPLACE VIEW "V_WORKORDERPICKED" ("WORKORDERLINE_ID", "WORKORDER_ID", "PRODCODE", "SIZECODE", "FMCODE", "CODEUNIQUELY", "QUANTITYORDERED", "QUANTITYFILLED", "QUANTITYCANCELLED", "PICKLISTLINE_ID", "STOCKTYPE", "QTYPICKED", "INSTRUCTIONS", "LANGUAGE_CODE", "QOPEN", "PRODDESC", "PICKERGRADE", "ORDEREDGRADE", "OOSPRODUCT") AS 
  select /*version 2.0*/
       wokli.workorderline_id, wokli.workorder_id,p.code prodcode, sd.code sizecode, fm.code fmcode, wokli.codeuniquely codeuniquely,
       wokli.quantityordered quantityordered, wokli.quantityfilled quantityfilled, wokli.quantitycancelled, plo.picklistline_id, pl.stocktype,
       plo.qtypicked,wokli.instructions, lan.code language_code, (wokli.quantityordered - wokli.quantityfilled - wokli.quantitycancelled) qopen,
       (select pd.description
          from product_desc pd
         where p.product_id = pd.product_id
           and pd.language_id = lan.language_id) proddesc,
       (select qdesc.description
          from qualitygrade_desc qdesc
         where qdesc.qualitygrade_id = qg.qualitygrade_id
           and qdesc.language_id = lan.language_id) pickergrade,
       (select qdesc.description
          from qualitygrade_desc qdesc
         where qdesc.qualitygrade_id = qordered.qualitygrade_id
           and qdesc.language_id = lan.language_id) orderedgrade,
       (select coalesce( oosp.status, 0)
          from workorder wo
               join stockdefinitionperitem sdi on wo.processingstockroom_id = sdi.stockroom_id
               join outofserviceproduct oosp on srg.stockreservationpergrade_id = oosp.stockreservationpergrade_id
              where wo.workorder_id = wokli.workorder_id
                and sdi.stockdefinitionperitem_id = srg.stockdefinitionperitem_id
                and sdi.product_id = wokli.product_link_id
                and sdi.sizedefinition_id= wokli.sizedefinition_link_id
                and srg.qualitygrade_id=wokli.requestedgrade_id
                and (oosp.sequencenumber is null or oosp.sequencenumber = (select max(oosp1.sequencenumber)
                                                                             from outofserviceproduct oosp1
                                                                            where oosp1.stockreservationpergrade_id = srg.stockreservationpergrade_id))) oosproduct
  from workorderline wokli
       left join picklistlineorigin plo
            left join picklistline pl
                      left join stockreservationpergrade srg
                                left join qualitygrade qg on srg.qualitygrade_id = qg.qualitygrade_id
                      on pl.stockreservationpergrade_id = srg.stockreservationpergrade_id
            on plo.picklistline_id = pl.picklistline_id
       on wokli.workorderline_id = plo.baselinetable_link_id and plo.baselinetable='WORKORDERLINE' and plo.baselinetype in (8,9)
       join product p on wokli.product_link_id = p.product_id
       join sizedefinition sd on wokli.sizedefinition_link_id = sd.sizedefinition_id
       join finishingmethod fm on wokli.finishingmethod_id = fm.finishingmethod_id
       join qualitygrade qordered on wokli.requestedgrade_id = qordered.qualitygrade_id
       cross join languages lan
/

  CREATE OR REPLACE VIEW "V_WORKORDERPLPC" ("WORKORDERLINE_ID", "WORKORDER_ID", "SUPPLIERNUMBER", "SUPLIERNAME", "LOGOFILEPATHORIGINAL", "LOGOFILEPATHPRODUCTION", "BACKING", "BORDERWIDTH", "BORDERMATERIAL", "THICKNESS", "ACTUALWIDTH", "ACTUALLENGTH", "SHAPE", "DIRECTION", "MATCOLORTYPE", "SEQUENCENUMBER", "LANGUAGE_CODE", "LOGO_CODE", "LOGO_DESC", "BG_CODE", "BG_DESC", "RESVALUESCHEMECODE") AS 
  select /*version 2.1*/
       wokli.workorderline_id, wo.workorder_id, sup.suppliernumber, sup.name supliername, moi.logofilepathoriginal, moi.logofilepathproduction, moi.backing, moi.borderwidth,
       moi.bordermaterial, moi.thickness, moi.actualwidth, moi.actuallength, moi.shape, moi.direction, mc.matcolortype, mc.sequencenumber, lan.code language_code,
       (select c1.code
          from color c1
         where c1.color_id = mc.color_id
           and mc.matcolortype = 1) logo_code,
       (select cd1.description
          from color_desc cd1
         where cd1.color_id = mc.color_id
           and cd1.language_id = lan.language_id
           and mc.matcolortype = 1) logo_desc,
       (select c2.code
          from color c2
         where c2.color_id = mc.color_id
           and mc.matcolortype = 2) bg_code,
       (select cd2.description
          from color_desc cd2
         where cd2.color_id = mc.color_id
           and cd2.language_id = lan.language_id
           and mc.matcolortype = 2) bg_desc,
        (select rvs.code from residualvaluescheme rvs where rvs.residualvaluescheme_id = plpc.residualvaluescheme_id) resvalueschemecode
  from workorderline wokli
       join workorder wo on wokli.workorder_id = wo.workorder_id
       join productlistpercustomer plpc
            left join matcolor mc on plpc.productlistpercustomer_id = mc.productlistpercustomer_id
            join matorderinginfo moi
                 join supplier sup on moi.supplier_id = sup.supplier_id
            on plpc.productlistpercustomer_id = moi.productlistpercustomer_id
       on wokli.product_link_id = plpc.product_id and wokli.sizedefinition_link_id = plpc.sizedefinition_id
                                                  and wokli.finishingmethod_id = plpc.finishingmethod_id
                                                  and wo.customer_link_id = plpc.customer_id
       cross join languages lan
 where wo.entrydate >= plpc.dateactive
   and wo.entrydate <= plpc.dateinactive
/

  CREATE OR REPLACE VIEW "V_WORKORDERREASONCODE" ("WORKORDER_ID", "REASONCODE", "REASONCODEDESC", "LANGUAGECODE") AS 
  select distinct
  wokli.workorder_id
, reasoncode.code reasoncode
, ( select reasoncode_desc.description from reasoncode_desc
    where reasoncode_desc.reasoncode_id=reasoncode.reasoncode_id
          and reasoncode_desc.language_id = languages.language_id ) ReasonCodeDesc
, languages.code languageCode
from
  workorderline wokli, reasoncode, languages
where
    wokli.reasoncode_id = reasoncode.reasoncode_id
/

  CREATE OR REPLACE VIEW "V_WORKORDERREPLACEMENT" ("LINETYPE", "WORKORDER_ID", "DIALOG_ID", "CHECKPOINTSCAN_ID", "ID_CODE", "PROD_CODE", "PROD_DESC", "SIZE_CODE", "QUANTITY", "FLAGSTARTDATE", "LANGUAGES_CODE", "UNIQUEITEM_ID") AS 
  select /*version 2.0*/
       1 linetype, --1 unique replacement items
       wo.workorder_id, wo.dialog_id,
       (select di.dialog_id
          from dialogs di
         where di.code = 'CheckPointScan') checkpointscan_id,
       ui.primaryid id_code, pr.code prod_code,
       (select prd.description
          from product_desc prd
         where pr.product_id = prd.product_id and prd.language_id = lan.language_id) prod_desc,
       sd.code size_code, 0 quantity, uif.startdate flagstartdate, lan.code languages_code, ui.uniqueitem_id
  from uniqueitem ui
       join uniqueitemnonpool uinp
            join workorderline wol
                 join workorder wo on wol.workorder_id = wo.workorder_id
            on uinp.replacementworkorderline_id = wol.workorderline_id
       on ui.uniqueitem_id = uinp.uniqueitem_id
       join product pr on ui.product_id = pr.product_id
       join sizedefinition sd on ui.sizedefinition_id = sd.sizedefinition_id
       join uniqueitemflag uif on ui.uniqueitem_id = uif.uniqueitem_id
       cross join languages lan
 where ((select count(1)
           from automaticflag af
          where uif.flag_id = af.flag_id
            and af.event = 'Replacement requested using replacement button') > 0)
union all --2 non-unique replacement items
select 2 linetype, wo.workorder_id, wo.dialog_id,
       (select di.dialog_id
          from dialogs di
         where di.code = 'CheckPointScan') checkpointscan_id,
       ' ' id_code, pr.code prod_code,
       (select prd.description
          from product_desc prd
         where pr.product_id = prd.product_id
           and prd.language_id = lan.language_id) prod_desc,
       sd.code size_code, 0 quantity, nui.flagstartdate, lan.code languages_code, nui.nonuniqueitem_id uniqueitem_id
  from nonuniqueitem nui
       join wearerinventory wi
            join product pr on wi.product_id = pr.product_id
            join sizedefinition sd on wi.sizedefinition_id = sd.sizedefinition_id
       on nui.wearerinventory_id = wi.wearerinventory_id
       join workorderline wol
            join workorder wo on wol.workorder_id = wo.workorder_id
       on nui.replacementworkorderline_id = wol.workorderline_id
       cross join languages lan
 where ((select count(1)
           from automaticflag af
          where nui.flag_id = af.flag_id
            and af.event = 'Replacement requested using replacement button') >0)
union all --3 unique substitutes
select 3 linetype, wo.workorder_id, wo.dialog_id,
       (select di.dialog_id
          from dialogs di
         where di.code = 'CheckPointScan') checkpointscan_id,
       sui.primaryid id_code, pr.code prod_code,
       (select prd.description
          from product_desc prd
         where pr.product_id = prd.product_id
           and prd.language_id = lan.language_id) prod_desc,
       sd.code size_code, 0 quantity, uif.startdate flagstartdate, lan.code languages_code, sui.uniqueitem_id
  from uniqueitem sui
       join product pr on sui.product_id = pr.product_id
       join sizedefinition sd on sui.sizedefinition_id = sd.sizedefinition_id
       join uniqueitemflag uif on sui.uniqueitem_id = uif.uniqueitem_id
       join workorderline wol
            join workorder wo on wol.workorder_id = wo.workorder_id
       on sui.substituteworkorderline_id = wol.workorderline_id
       cross join languages lan
 where ((select count(1)
           from automaticflag af
          where uif.flag_id = af.flag_id and af.event = 'Substitute garment') > 0)
union all --4 non-unique substitutes
select 4 linetype, wo.workorder_id, wo.dialog_id,
       (select di.dialog_id
          from dialogs di
         where di.code = 'CheckPointScan') checkpointscan_id,
       ' ' id_code, pr.code prod_code,
       (select prd.description
          from product_desc prd
         where pr.product_id = prd.product_id
           and prd.language_id = lan.language_id) prod_desc,
       sd.code size_code, 0 quantity, nsui.flagstartdate, lan.code languages_code, nsui.nonuniqueitem_id uniqueitem_id
  from nonuniqueitem nsui
       join product pr on nsui.substituteforproduct_id = pr.product_id
       join sizedefinition sd on nsui.substituteforsizedefinition_id = sd.sizedefinition_id
       join workorderline wol
            join workorder wo on wol.workorder_id = wo.workorder_id
       on nsui.substituteworkorderline_id = wol.workorderline_id
       cross join languages lan
 where ((select count(1)
           from automaticflag af
          where nsui.flag_id = af.flag_id
            and af.event = 'Substitute garment') > 0)
/

  CREATE OR REPLACE VIEW "V_WORKORDERSPERPURCHASEORDER" ("WORKORDER_ID", "WORKORDERNUMBER", "REQUESTDATE", "NEEDEDDATE", "CUSTOMER_ID", "CUSTOMERNUMBER", "CUSTOMERNAME", "WEARER_ID", "WEARERNUMBER", "WEARERNAME", "SEARCHNAME", "PRODCODE", "SIZECODE", "PRODDESC", "PURCHASEORDERNUMBER", "WOLORDERED", "POLORDERED", "SUPPLIERNUMBER", "SUPPNAME", "LAN_CODE") AS 
  select WO.WORKORDER_ID,
       WO.WORKORDERNUMBER,
       WO.REQUESTDATE,
       WO.NEEDEDDATE,
       CU.CUSTOMER_ID,
       CU.CUSTOMERNUMBER,
       CU.NAME CUSTOMERNAME,
       W.WEARER_ID,
       W.WEARERNUMBER,
       W.FULLNAME WEARERNAME,
       W.SEARCHNAME,
       PRD.CODE PRODCODE,
       SD.CODE SIZECODE,
       (select PD.DESCRIPTION
          from PRODUCT_DESC PD
         where PRD.PRODUCT_ID = PD.PRODUCT_ID
           and PD.LANGUAGE_ID = LAN.LANGUAGE_ID) PRODDESC,
       POH.PURCHASEORDERNUMBER,
       WOL.QUANTITYORDERED WOLORDERED,
       POL.QUANTITYORDERED POLORDERED,
       SU.SUPPLIERNUMBER,
       SU.NAME SUPPNAME,
       LAN.CODE LAN_CODE
  from WORKORDER           WO,
       WORKORDERLINE       WOL,
       PURCHASEORDERLINE   POL,
       WEAREREMPLOYMENT    WE,
       WEARER              W,
       CUSTOMER            CU,
       PRODUCT             PRD,
       SIZEDEFINITION      SD,
       PURCHASEORDERHEADER POH,
       SUPPLIER            SU,
       LANGUAGES           LAN
where WO.WORKORDER_ID = WOL.WORKORDER_ID
   and WO.WEAREREMPLOYMENT_LINK_ID = WE.WEAREREMPLOYMENT_ID
   and WE.WEARER_ID = W.WEARER_ID
   and W.CUSTOMER_ID = CU.CUSTOMER_ID
   and WOL.PURCHASEORDERLINE_ID = POL.PURCHASEORDERLINE_ID
   and WOL.PRODUCT_LINK_ID = PRD.PRODUCT_ID
   and WOL.SIZEDEFINITION_LINK_ID = SD.SIZEDEFINITION_ID
   and POL.PURCHASEORDERHEADER_ID = POH.PURCHASEORDERHEADER_ID
   and POH.SUPPLIER_ID = SU.SUPPLIER_ID
union all
select WO.WORKORDER_ID,
       WO.WORKORDERNUMBER,
       WO.REQUESTDATE,
       WO.NEEDEDDATE,
       CU.CUSTOMER_ID,
       CU.CUSTOMERNUMBER,
       CU.NAME CUSTOMERNAME,
       W.WEARER_ID,
       W.WEARERNUMBER,
       W.FULLNAME WEARERNAME,
       W.SEARCHNAME,
       PRD.CODE PRODCODE,
       SD.CODE SIZECODE,
       (select PD.DESCRIPTION
          from PRODUCT_DESC PD
         where PRD.PRODUCT_ID = PD.PRODUCT_ID
           and PD.LANGUAGE_ID = LAN.LANGUAGE_ID) PRODDESC,
       POH.PURCHASEORDERNUMBER,
       WOL.QUANTITYORDERED WOLORDERED,
       POL.QUANTITYORDERED POLORDERED,
       SU.SUPPLIERNUMBER,
       SU.NAME SUPPNAME,
       LAN.CODE LAN_CODE
  from WORKORDER                 WO,
       WORKORDERLINE             WOL,
       WORKORDERLINEPURCHORDLINE WOLPOL,
       PURCHASEORDERLINE         POL,
       WEAREREMPLOYMENT          WE,
       WEARER                    W,
       CUSTOMER                  CU,
       PRODUCT                   PRD,
       SIZEDEFINITION            SD,
       PURCHASEORDERHEADER       POH,
       SUPPLIER                  SU,
       LANGUAGES                 LAN
where WO.WORKORDER_ID = WOL.WORKORDER_ID
   and WO.WEAREREMPLOYMENT_LINK_ID = WE.WEAREREMPLOYMENT_ID
   and WE.WEARER_ID = W.WEARER_ID
   and W.CUSTOMER_ID = CU.CUSTOMER_ID
   and WOL.WORKORDERLINE_ID = WOLPOL.WORKORDERLINE_ID
   and WOLPOL.PURCHASEORDERLINE_ID = POL.PURCHASEORDERLINE_ID
   and WOL.PRODUCT_LINK_ID = PRD.PRODUCT_ID
   and WOL.SIZEDEFINITION_LINK_ID = SD.SIZEDEFINITION_ID
   and POL.PURCHASEORDERHEADER_ID = POH.PURCHASEORDERHEADER_ID
   and POH.SUPPLIER_ID = SU.SUPPLIER_ID
/

  CREATE OR REPLACE VIEW "V_WORKORDERSTATISTICS" ("WORKORDER_ID", "REASONCODE_ID", "WORKORDERNUMBER", "DISTRIBUTIONPOINT_LINK_ID", "DISTRIBUTIONPOINT_ID", "DEPARTMENT_ID", "CUSTOMER_ID", "BUSINESSUNIT_ID", "COMPLETIONDATE", "NEEDEDDATE", "ENTRYDATE", "ORIGIN", "WEAREREMPLOYMENT_ID", "CUSTOMER_LINK_ID", "REASON_CODE", "REASON_DESC", "SYSTEMUSER_ID", "BUSINESSUNIT_CODE", "REPORTPARAM_ID", "LANGUAGE_CODE", "CUSTOMERNUMBER", "WOREFERENCENR", "WOREFNR_DESC") AS 
  select wok.workorder_id, wok.reasoncode_id , wok.workordernumber,
wok.distributionpoint_link_id, dp.distributionpoint_id, dep.department_id,
coalesce((select c2.customer_id from customer c2, distributionpoint dp2, department dep2
where welk.distributionpoint_link_id=dp2.distributionpoint_id and dp2.department_id=dep2.department_id and dep2.customer_id = c2.customer_id), cu.customer_id) customer_id,
--cu.customer_id,
wok.businessunit_id, wok.completiondate, wok.neededdate, wok.entrydate, wok.origin
, wok.weareremployment_link_id weareremployment_id, wok.customer_link_id
, rc.code Reason_code
, (select rcd.description from Reasoncode_Desc rcd where rcd.reasoncode_id=rc.reasoncode_id and rcd.language_id=lan.language_id) Reason_desc
, su.systemuser_id, bu.code Businessunit_code
, rp.reportparam_id
, lan.code Language_code
, coalesce((select c1.customernumber from customer c1, distributionpoint dp1, department dep1
where welk.distributionpoint_link_id=dp1.distributionpoint_id and dp1.department_id=dep1.department_id and dep1.customer_id = c1.customer_id), cu.customernumber) customernumber
, worefnr.referencenumber woreferencenr, worefnr.description worefnr_desc
from workorder wok
left outer join weareremployment_LINK welk on wok.weareremployment_link_id = welk.weareremployment_link_id
left outer join distributionpoint dp on dp.distributionpoint_id=wok.distributionpoint_link_id
     left outer join department dep on dp.department_id = dep.department_id
             left outer join customer cu on cu.customer_id = dep.customer_id
                 left outer join address on cu.visitaddress_id=address.address_id
left outer join reasoncode rc on wok.reasoncode_id=rc.reasoncode_id
left outer join woreferencenumber worefnr on wok.woreferencenumber_id = worefnr.woreferencenumber_id
, businessunitsperusergroup bupug, systemuser su, businessunit bu
, languages lan
, reportparam rp
where
wok.businessunit_id=bupug.businessunit_id and su.usergroup_id=bupug.usergroup_id
and wok.businessunit_id=bu.businessunit_id
and
((rp.string_value1=' ' and rp.string_value2 ='ZZZZZZZZZZZZ')
or
exists (select * from workorderline wol, product p where wok.workorder_id=wol.workorder_id and wol.product_link_id=p.product_id and p.code>=rp.string_value1 and p.code<=rp.string_value2)
)
/

  CREATE OR REPLACE VIEW "V_WORKORDERSTATISTICSLINE" ("WORKORDERLINE_ID", "WORKORDERNUMBER", "PRODUCT_CODE", "PRODUC_DESC", "COMPLETIONDATE", "EXPECTEDDATE", "WORKORDER_ID", "REASONCODE_ID", "DISTRIBUTIONPOINT_LINK_ID", "DISTRIBUTIONPOINT_ID", "DEPARTMENT_ID", "CUSTOMER_ID", "BUSINESSUNIT_ID", "WOCOMPLETIONDATE", "NEEDEDDATE", "ENTRYDATE", "ORIGIN", "WEAREREMPLOYMENT_ID", "CUSTOMER_LINK_ID", "REASON_CODE", "REASON_DESC", "SYSTEMUSER_ID", "BUSINESSUNIT_CODE", "LANGUAGE_CODE", "CUSTOMERNUMBER") AS 
  select wol.workorderline_id, wok.workordernumber
, p.code Product_code
, (select pd.description from Product_Desc pd where pd.product_id=wol.product_link_id and pd.language_id=lan.language_id) Produc_desc
, wol.completiondate, wol.expecteddate
, wok.workorder_id, wok.reasoncode_id
, wok.distributionpoint_link_id, dp.distributionpoint_id, dep.department_id, cu.customer_id
, wok.businessunit_id, wok.completiondate wocompletiondate
, wok.neededdate, wok.entrydate, wok.origin
, wok.weareremployment_link_id weareremployment_id, wok.customer_link_id
, rc.code Reason_code
, (select rcd.description from Reasoncode_Desc rcd where rcd.reasoncode_id=rc.reasoncode_id and rcd.language_id=lan.language_id) Reason_desc
, su.systemuser_id, bu.code Businessunit_code
, lan.code Language_code
, coalesce((select c1.customernumber from customer c1, distributionpoint dp1, department dep1
where welk.distributionpoint_link_id=dp1.distributionpoint_id and dp1.department_id=dep1.department_id and dep1.customer_id = c1.customer_id), cu.customernumber) customernumber
from workorder wok
left outer join weareremployment_LINK welk on wok.weareremployment_link_id = welk.weareremployment_link_id
left outer join distributionpoint dp on dp.distributionpoint_id=wok.distributionpoint_link_id
     left outer join department dep on dp.department_id = dep.department_id
             left outer join customer cu on cu.customer_id = dep.customer_id
                 left outer join address on cu.visitaddress_id=address.address_id
left outer join reasoncode rc on wok.reasoncode_id=rc.reasoncode_id
, businessunitsperusergroup bupug, systemuser su, businessunit bu
, languages lan
, workorderline wol
left outer join product_link p on wol.product_link_id=p.product_id
where wol.workorder_id = wok.workorder_id and
wok.businessunit_id=bupug.businessunit_id and su.usergroup_id=bupug.usergroup_id
and wok.businessunit_id=bu.businessunit_id
/

  CREATE OR REPLACE VIEW "V_WOTRANSPORTSTICKER" ("SHIPMENTLIST_ID", "SHIPMENTLISTNUMBER", "TRANSPORTUNITNUMBER", "WORKORDER_ID", "WORKORDERNUMBER", "CUSTOMERNUMBER", "NAME", "DEPARTMENTNUMBER", "DEPDESC", "DISTRIBUTIONPOINTNUMBER", "CONSPOINTDESC", "DELPOINTCODE", "DELPOINTDESC", "STREET", "STREET2", "ZIPCODE", "CITY", "COUNTRYDESC", "WEARERNUMBER", "CUSTOMEREMPLOYEENUMBER", "FULLNAME", "QUANTITYSHIPPED", "BANK", "LOCKER") AS 
  select sl.shipmentlist_id,sl.shipmentlistnumber,sll.transportunitnumber,
wo.workorder_id, wo.workordernumber, c.customernumber, c.name,
d.departmentnumber, d.description depdesc,
dp.distributionpointnumber, dp.description conspointdesc,
delp.code delpointcode, delp.description delpointdesc,
adr.street, adr.street2, adr.zipcode, adr.city, co.description countrydesc,
w.wearernumber, w.customeremployeenumber, w.fullname,sll.quantityshipped,
lo.bank, lo.locker
from shipmentlist sl, shipmentlistline sll,workorderline wol, workorder wo,wearer w, weareremployment we
                left outer join locker lo on we.locker_id=lo.locker_id
                    left outer join garmentdispenser ga on we.garmentdispenser_id=ga.garmentdispenser_id
                left outer join deliverypoint de on we.deliverypoint_id=de.deliverypoint_id,
 distributionpoint dp, department d, customer c, address adr, deliverypoint delp, country co
 where sl.shipmentlist_id=sll.shipmentlist_id
 and sll.workorderline_id=wol.workorderline_id
 and wol.workorder_id=wo.workorder_id
 and wo.weareremployment_link_id = we.weareremployment_id
 and we.wearer_id = w.wearer_id
 and we.distributionpoint_id=dp.distributionpoint_id
 and dp.department_id=d.department_id
 and d.customer_id=c.customer_id
 and c.visitaddress_id=adr.address_id
 and c.country_id=co.country_id
 and coalesce(we.deliverypoint_id, lo.deliverypoint_id, ga.deliverypoint_id)=delp.deliverypoint_id
/

  CREATE OR REPLACE VIEW "V_WSPBATCHJOB" ("PLANTNR", "BATCHNR", "YEARNR", "CUSTOMERNR", "DEPARTMENTNR", "ROUTENR", "CUSTOMERNAME", "PREVIOUSBATCHNUMBER") AS 
  select
p.code plantnr,b.batchnumber batchnr, b.year yearnr,c.customernumber customernr,
d.departmentnumber departmentnr,
F_FIRSTROUTEPERDAY(C.CUSTOMER_LINK_ID, bc.planneddeliverydate) routenr,
c.name customername,
 coalesce((select max(batchjob.batchnumber)
 from batchjob, batchjobcontent
 where batchjob.batchjob_id = batchjobcontent.batchjob_id
 and batchjobcontent.department_link_id = bc.department_link_id
 and batchjob.batchnumber< b.batchnumber
 ),0) previousbatchnumber
from batchjob b, batchjobcontent bc, plant p, department_link d, customer_link c
where b.batchjob_id = bc.batchjob_id
and b.plant_id = p.plant_id
and bc.department_link_id = d.department_link_id
and d.customer_link_id = c.customer_link_id
/

  CREATE OR REPLACE VIEW "V_YIELDPERCUSTOMER" ("INVOICEHEADER_ID", "INVOICEDATE", "INVOICEBUSINESSUNIT_ID", "CUSTOMERID", "CUSTOMERNUMBER", "CUSTOMERNAME", "INVOICEAMOUNTDECIMALS") AS 
  SELECT
ih.invoiceheader_id invoiceheader_id, ih.invoicedate invoicedate, ih.invoicebusinessunit_id,
ih.deltocustomer_link_id customerid, ih.deltocustomernumber customernumber, ih.deltocustomername customername,
cur.invoiceamountdecimals
 FROM invoiceheader ih,status st, currency cur
 WHERE ih.documenttype = 1 and ih.status_id = st.status_id and st.statustype = 'IN' and st.code = 2
 and ih.currency_id=cur.currency_id
/

  CREATE OR REPLACE VIEW "V_YIELDPERCUSTOMER_LINES" ("INVOICEHEADER_ID", "INVOICELINETYPE", "AMOUNT", "PRODUCTGROUPCODE", "PRODUCTCODE", "PACK", "PRODUCTDESCRIPTION", "THEORETICALWEIGHT", "TYPEOFMERCHANDISE", "ACTIVITYCODE", "DELIVERYAMOUNT", "DELIVERYAMOUNTPACK", "SIZECODE", "FINISHINGMETHODCODE", "LANGUAGECODE", "PRODLINETYPE", "REPORTPARAM_ID") AS 
  SELECT ih.invoiceheader_id, ilt.type InvoicelineType,
       (case when il.adjustmentreason_id is null then il.amount else il.adjustedamount end) Amount,
       pg.CODE productgroupcode,
       p.CODE productcode,  p.pack pack,
       (SELECT pd.description FROM product_desc pd  WHERE pd.product_id = p.product_id
                AND pd.LANGUAGE_ID = lan.LANGUAGE_ID) productdescription,
       (select ps.theoreticalweight from productsize ps
       where ps.product_id = ilp.product_link_id and ps.sizedefinition_id = ilp.sizedefinition_link_id) THEORETICALWEIGHT,
       p.typeofmerchandise typeofmerchandise,
       ay.code ACTIVITYCODE,
       (select sum(dh.amountdelivered) from deliveryhistory dh, finishingmethod fm--, department dep
        where dh.PRODUCT_LINK_ID = ilp.product_link_id
              AND dh.SIZEDEFINITION_LINK_ID = ilp.sizedefinition_link_id
              and dh.finishingmethod_id=ilp.finishingmethod_id
              and dh.INVOICEBUSINESSUNIT_ID = ih.invoicebusinessunit_id
              and dh.deliverydate between rp.date_value2 and rp.date_value1
              and dh.customer_link_id = ih.deltocustomer_link_id
              --and dh.department_link_id = dep.department_id
              and dh.packindication in (1,3)
              and dh.finishingmethod_id = fm.finishingmethod_id
              --and dep.departmentnumber >= rp.number_value2
              --and dep.departmentnumber <= rp.number_value4
              and fm.code >= rp.string_value1
              and fm.code <= rp.string_value2) deliveryAmount,
       (select sum(dh.amountdelivered) from deliveryhistory dh, finishingmethod fm--, department dep
        where dh.PRODUCT_LINK_ID = ilp.product_link_id
              AND dh.SIZEDEFINITION_LINK_ID = ilp.sizedefinition_link_id
              and dh.finishingmethod_id=ilp.finishingmethod_id
              and dh.INVOICEBUSINESSUNIT_ID = ih.invoicebusinessunit_id
              and dh.deliverydate between rp.date_value2 and rp.date_value1
              and dh.customer_link_id = ih.deltocustomer_link_id
              --and dh.department_link_id = dep.department_id
              and dh.packindication = 2
              and dh.finishingmethod_id = fm.finishingmethod_id
              --and dep.departmentnumber >= rp.number_value2
              --and dep.departmentnumber <= rp.number_value4
              and fm.code >= rp.string_value1
              and fm.code <= rp.string_value2) deliveryAmountPack,
              ilp.sizecode sizecode,
              ilp.finishingmethodcode finishingmethodcode,
        lan.code LANGUAGECODE, 1 prodlineType
       , rp.reportparam_id
 FROM invoiceheader ih,
      invoiceline il left outer join invoicelineproduct ilp on il.invoiceline_id = ilp.invoiceline_id
                     left outer join product p on ilp.product_link_id = p.product_id
                     join productgroup pg on pg.productgroup_id = p.productgroup_id
                     join activity ay on ay.activity_id = pg.activity_id,
      invoicelinetype ilt,
      languages lan, reportparam rp
 WHERE ih.invoiceheader_id = il.invoiceheader_id
       and il.extend='Y'
       and il.invoicelinetype_id = ilt.invoicelinetype_id
       and ilt.type in (1, 2) -- rent and wash
union
SELECT  ih.invoiceheader_id, ilt.type InvoicelineType,
        (case when il.adjustmentreason_id is null then il.amount else il.adjustedamount end) Amount,
        null productgroupcode,
        wc.code productcode, 'N' pack,
        (select wcd.description from weighingcategory_desc wcd where wcd.weighingcategory_id = wc.weighingcategory_id and wcd.language_id = lan.language_id) productdescription ,
        0 THEORETICALWEIGHT, 0 typeofmerchandise, ac.code ACTIVITYCODE,
        0 deliveryAmount,
        0 deliveryAmountPack,
        null sizecode,
        null finishingmethodcode,
        lan.code LANGUAGECODE, ilt.type prodlineType --3 or 4 depending on ilt.Type
       , -1 reportparam_id
FROM invoiceheader ih,
        invoiceline il left outer join invoicelineproduct ilp on il.invoiceline_id = ilp.invoiceline_id,
        invoicelinetype ilt, weighingcategory wc, activity ac,
        languages lan
WHERE ih.invoiceheader_id = il.invoiceheader_id
      and il.extend='Y'
      and il.invoicelinetype_id = ilt.invoicelinetype_id
      and ilp.weighingcategory_link_id=wc.weighingcategory_id
      and wc.activity_id=ac.activity_id
      and ilt.type in (3, 4)
union
SELECT ih.invoiceheader_id, ilt.type InvoicelineType,
       (case when il.adjustmentreason_id is null then il.amount else il.adjustedamount end) Amount,
       null productgroupcode,
       null,  'N' pack,
       null productdescription,
       null THEORETICALWEIGHT,
       0 typeofmerchandise,
       null ACTIVITYCODE,
       0 deliveryAmount,
       0 deliveryAmountPack,
       null sizecode,
       null finishingmethodcode,
       lan.code LANGUAGECODE, 999 prodlineType, --other
       -1 reportparam_id
 FROM invoiceheader ih, invoicelinetype ilt, invoiceline il,
      languages lan
 WHERE ih.invoiceheader_id = il.invoiceheader_id
       and il.extend='Y'
       and il.invoicelinetype_id = ilt.invoicelinetype_id
       and ilt.type not in (1, 2, 3, 4, 7, 8, 9, 18)
/

